text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Is it possible to embed and use a portable executable in a .net DLL? The easiest way to think of my question is to think of a single, simple unix command (albeit, this is for windows) and I need progmatic access to run it.
I have a single command-line based executable that performs some unit of work. I want to call that executable with the .net process library, as I can do with any other executable.
However, it dawned on me that there is potential for the dll to become useless or break with unintended updates to the executable or a non-existant executable.
Is it possible to run the executable from the Process object in the .net framework, as I would an external executable file?
A: No, you can't execute it directly. You could probably unpack it to a temporary directory and execute it from there.
A: Is this where PInvoke can help?
A: Depending on the functionality of the command line program you want to run, it might be possible to duplicate the functionality in PowerShell, where you can embed the PowerShell runtime in your .NET application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Whats the best way to do throbber in C#? Specifically what I am looking to do is make the icons for the Nodes in my System.Windows.Forms.TreeView control to throb while a long loading operation is taking place.
A: If you load each frame into an ImageList, you can use a loop to update to each frame.
Example:
bool runThrobber = true;
private void AnimateThrobber(TreeNode animatedNode)
{
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(delegate
{
while (runThrobber)
{
this.Invoke((MethodInvoker)delegate
{
animatedNode.SelectedImageIndex++;
if (animatedNode.SelectedImageIndex >= imageList1.Images.Count) > animatedNode.SelectedImageIndex = 0;
});
Thread.Sleep(100);
}
});
bg.RunWorkerAsync();
}
Obviously there's more than a few ways to implement this, but here's the basic idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Automate firefox with python? Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?
A: You could try selenium.
A: The PyXPCOM extension is one possibility.
But looking at what firewatir provides, I have to 2nd the suggestion for twill. It's based on mechanize, which might also be useful in this context.
A: I use Selenium RC. All my tests are written in Python and are run with test suite.
One minor thing is that You either have to start selenium manually and point Your tests to it or start selenium from test suite which requires little bit of coding. But it's doable.
Generally I'm very pleased with this solution.
A: See if twill can help you. It can be used as a command line tool or as a python library.
A: I would suggest you to use Selenium instead of Mechanize/Twill because Mechanize would fail while handling Javascript.
A: The languages of choice of Firefox is Javascript. Unless you have a specific requirement that requires Python, I would advice you to use that.
A: Install Mozlab in Firefox and enable the telnet server, then open a socket.
A: Many command line tools don't have a javascript interpreter so do not support web 2.0 functionality. juicedpyshell is based on PyXPCOMext's PyShell example. It gives you a python shell window "inside" the browser, and simplifies access to both the DOM of what you are browsing to and also the shell window itself (so you can add GUI elements as part of your automation script). But its a new project so probably not as full featured as some of the above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How to escape text for regular expression in Java? Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.
A: To have protected pattern you may replace all symbols with "\\\\", except digits and letters. And after that you can put in that protected pattern your special symbols to make this pattern working not like stupid quoted text, but really like a patten, but your own. Without user special symbols.
public class Test {
public static void main(String[] args) {
String str = "y z (111)";
String p1 = "x x (111)";
String p2 = ".* .* \\(111\\)";
p1 = escapeRE(p1);
p1 = p1.replace("x", ".*");
System.out.println( p1 + "-->" + str.matches(p1) );
//.*\ .*\ \(111\)-->true
System.out.println( p2 + "-->" + str.matches(p2) );
//.* .* \(111\)-->true
}
public static String escapeRE(String str) {
//Pattern escaper = Pattern.compile("([^a-zA-z0-9])");
//return escaper.matcher(str).replaceAll("\\\\$1");
return str.replaceAll("([^a-zA-Z0-9])", "\\\\$1");
}
}
A: Pattern.quote("blabla") works nicely.
The Pattern.quote() works nicely. It encloses the sentence with the characters "\Q" and "\E", and if it does escape "\Q" and "\E".
However, if you need to do a real regular expression escaping(or custom escaping), you can use this code:
String someText = "Some/s/wText*/,**";
System.out.println(someText.replaceAll("[-\\[\\]{}()*+?.,\\\\\\\\^$|#\\\\s]", "\\\\$0"));
This method returns: Some/\s/wText*/\,**
Code for example and tests:
String someText = "Some\\E/s/wText*/,**";
System.out.println("Pattern.quote: "+ Pattern.quote(someText));
System.out.println("Full escape: "+someText.replaceAll("[-\\[\\]{}()*+?.,\\\\\\\\^$|#\\\\s]", "\\\\$0"));
A: Since Java 1.5, yes:
Pattern.quote("$5");
A: It may be too late to respond, but you can also use Pattern.LITERAL, which would ignore all special characters while formatting:
Pattern.compile(textToFormat, Pattern.LITERAL);
A: I think what you're after is \Q$5\E. Also see Pattern.quote(s) introduced in Java5.
See Pattern javadoc for details.
A: Difference between Pattern.quote and Matcher.quoteReplacement was not clear to me before I saw following example
s.replaceFirst(Pattern.quote("text to replace"),
Matcher.quoteReplacement("replacement text"));
A: First off, if
*
*you use replaceAll()
*you DON'T use Matcher.quoteReplacement()
*the text to be substituted in includes a $1
it won't put a 1 at the end. It will look at the search regex for the first matching group and sub THAT in. That's what $1, $2 or $3 means in the replacement text: matching groups from the search pattern.
I frequently plug long strings of text into .properties files, then generate email subjects and bodies from those. Indeed, this appears to be the default way to do i18n in Spring Framework. I put XML tags, as placeholders, into the strings and I use replaceAll() to replace the XML tags with the values at runtime.
I ran into an issue where a user input a dollars-and-cents figure, with a dollar sign. replaceAll() choked on it, with the following showing up in a stracktrace:
java.lang.IndexOutOfBoundsException: No group 3
at java.util.regex.Matcher.start(Matcher.java:374)
at java.util.regex.Matcher.appendReplacement(Matcher.java:748)
at java.util.regex.Matcher.replaceAll(Matcher.java:823)
at java.lang.String.replaceAll(String.java:2201)
In this case, the user had entered "$3" somewhere in their input and replaceAll() went looking in the search regex for the third matching group, didn't find one, and puked.
Given:
// "msg" is a string from a .properties file, containing "<userInput />" among other tags
// "userInput" is a String containing the user's input
replacing
msg = msg.replaceAll("<userInput \\/>", userInput);
with
msg = msg.replaceAll("<userInput \\/>", Matcher.quoteReplacement(userInput));
solved the problem. The user could put in any kind of characters, including dollar signs, without issue. It behaved exactly the way you would expect.
A: ^(Negation) symbol is used to match something that is not in the character group.
This is the link to Regular Expressions
Here is the image info about negation:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "355"
} |
Q: In what order are ON DELETE CASCADE constraints processed? Here is an example of what I've got going on:
CREATE TABLE Parent (id BIGINT NOT NULL,
PRIMARY KEY (id)) ENGINE=InnoDB;
CREATE TABLE Child (id BIGINT NOT NULL,
parentid BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (parentid),
CONSTRAINT fk_parent FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE) ENGINE=InnoDB;
CREATE TABLE Uncle (id BIGINT NOT NULL,
parentid BIGINT NOT NULL,
childid BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (parentid),
KEY (childid),
CONSTRAINT fk_parent_u FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE,
CONSTRAINT fk_child FOREIGN KEY (childid) REFERENCES Child (id)) ENGINE=InnoDB;
Notice there is no ON DELETE CASCADE for the Uncle-Child relationship; i.e. deleting a Child does not delete its Uncle(s) and vice-versa.
When I have a Parent and an Uncle with the same Child, and I delete the Parent, it seems like InnoDB should be able to just "figure it out" and let the cascade ripple through the whole family (i.e. deleting the Parent deletes the Uncle and the Child as well). However, instead, I get the following:
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cascade_test/uncle`, CONSTRAINT `fk_child` FOREIGN KEY (`childid`) REFERENCES `child` (`id`))
InnoDB is trying to cascade-delete the Child before the Uncle(s) that refer to it.
Am I missing something? Is this supposed to fail for some reason I don't understand? Or is there some trick to making it work (or is it a bug in MySQL)?
A: In the simpler case, what happens if a record is deleted from Child and it has a referencing Uncle? That's unspecified, so the constraints fail for that anyway.
If deleting a Child does not delete its Uncles, then what happens instead? Uncle.childid cannot be null.
What you want is one of these three things:
*
*Uncle.childid can be null, and you want ON DELETE SET NULL for childid.
*Uncle.childid cannot be null, and you want ON DELETE CASCADE for childid.
*Childid does not belong on Uncle, and you want a ChildsUncle relation with ON DELETE CASCADE foreign key constraints to both Child and Uncle. Uncleid would be a candidate key for that relation (i.e. it should be unique).
A: The parent deletion is triggering the child deletion as you stated and I don't know why it goes to the child table before the uncle table. I imagine you would have to look at the dbms code to know for sure, but im sure there is an algorithm that picks which tables to cascade to first.
The system does not really 'figure out' stuff the way you imply here and it is just following its constraint rules. The problem is the schema you created in that it encounters a constraint that will not let it pass further.
I see what you are saying.. if it hit the uncle table first it would delete the record and then delete the child (and not hit the uncle cascade from the child deletion). But even so, I don't think a schema would be set up to rely on that kind of behavior in reality. I think the only way to know for sure what is going on is to look through the code or get one of the mysql/postgresql programmers in here to say how it processes fk constraints.
A: @Matt Solnit first of all this is really a good question and as far as I know when a record from Parent is to be deleted then innodb first tries to identify which other tables holds references to it so that it can delete the record from them as well. In your case it is Child table and Uncle table, now it seems that in this case it decides to first delete record from Child table and thus it repeats the same process for Child and eventually fails as Uncle holds reference to Child table but neither "ON DELETE CASCADE" nor "ON DELETE SET NULL" is specified for fk_child FK in Uncle table. However, it does seems that if innodb first tries to delete record from the Uncle table then deletion should have happened smoothly. Well after giving a second thought I think that since innodb follows ACID model thus it chooses Child over Uncle to start the deletion process becuase if it starts with Uncle even then the deletion in Child might still have failed e.g. assume a Friend table that has fk_child key (similar to Uncle) without ON DELETE CASCADE, now this would still have caused the whole transaction to fail and therefore this looks right behaviour to me. In others words innodb starts with table that may cause a possible failure in the transaction but that is my theory in reality it might be a completely different story. :)
A: the design is all wrong. You should have single table, with parent child relationship (literrally).
Then you can figure out uncles (and aunts) with a query
select id from persons where -find all children of the grandparents
parent id in (
select parentid from persons --find the grandparents
where id in (
select parentid from persons --find the parents
where id=THECHILD)
)
minus --and take out the child's parents
select parentid from persons
where id=THECHILD
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How can I prevent SQL injection in PHP? If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:
$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
That's because the user can input something like value'); DROP TABLE table;--, and the query becomes:
INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
What can be done to prevent this from happening?
A: The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
*
*Using PDO (for any supported database driver):
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute([ 'name' => $name ]);
foreach ($stmt as $row) {
// Do something with $row
}
*Using MySQLi (for MySQL):
Since PHP 8.2+ we can make use of execute_query() which prepares, binds parameters, and executes SQL statement in one method:
$result = $dbConnection->execute_query('SELECT * FROM employees WHERE name = ?', [$name]);
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
Up to PHP8.1:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.
Correctly setting up the connection
PDO
Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example, the error mode isn't strictly necessary, but it is advised to add it. This way PDO will inform you of all MySQL errors by means of throwing the PDOException.
What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.
Mysqli
For mysqli we have to follow the same routine:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
$dbConnection->set_charset('utf8mb4'); // charset
Explanation
The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.
Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.
Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute([ 'column' => $unsafeValue ]);
Can prepared statements be used for dynamic queries?
While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.
For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.
// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
$dir = 'ASC';
}
A: I've written this little function several years ago:
function sqlvprintf($query, $args)
{
global $DB_LINK;
$ctr = 0;
ensureConnection(); // Connect to database if not connected already.
$values = array();
foreach ($args as $value)
{
if (is_string($value))
{
$value = "'" . mysqli_real_escape_string($DB_LINK, $value) . "'";
}
else if (is_null($value))
{
$value = 'NULL';
}
else if (!is_int($value) && !is_float($value))
{
die('Only numeric, string, array and NULL arguments allowed in a query. Argument '.($ctr+1).' is not a basic type, it\'s type is '. gettype($value). '.');
}
$values[] = $value;
$ctr++;
}
$query = preg_replace_callback(
'/{(\\d+)}/',
function($match) use ($values)
{
if (isset($values[$match[1]]))
{
return $values[$match[1]];
}
else
{
return $match[0];
}
},
$query
);
return $query;
}
function runEscapedQuery($preparedQuery /*, ...*/)
{
$params = array_slice(func_get_args(), 1);
$results = runQuery(sqlvprintf($preparedQuery, $params)); // Run query and fetch results.
return $results;
}
This allows running statements in an one-liner C#-ish String.Format like:
runEscapedQuery("INSERT INTO Whatever (id, foo, bar) VALUES ({0}, {1}, {2})", $numericVar, $stringVar1, $stringVar2);
It escapes considering the variable type. If you try to parameterize table, column names, it would fail as it puts every string in quotes which is an invalid syntax.
SECURITY UPDATE: The previous str_replace version allowed injections by adding {#} tokens into user data. This preg_replace_callback version doesn't cause problems if the replacement contains these tokens.
A: I'd recommend using PDO (PHP Data Objects) to run parameterized SQL queries.
Not only does this protect against SQL injection, but it also speeds up queries.
And by using PDO rather than mysql_, mysqli_, and pgsql_ functions, you make your application a little more abstracted from the database, in the rare occurrence that you have to switch database providers.
A: Use PDO and prepared queries.
($conn is a PDO object)
$stmt = $conn->prepare("INSERT INTO tbl VALUES(:id, :name)");
$stmt->bindValue(':id', $id);
$stmt->bindValue(':name', $name);
$stmt->execute();
A: As you can see, people suggest you use prepared statements at the most. It's not wrong, but when your query is executed just once per process, there would be a slight performance penalty.
I was facing this issue, but I think I solved it in very sophisticated way - the way hackers use to avoid using quotes. I used this in conjunction with emulated prepared statements. I use it to prevent all kinds of possible SQL injection attacks.
My approach:
*
*If you expect input to be integer make sure it's really integer. In a variable-type language like PHP it is this very important. You can use for example this very simple but powerful solution: sprintf("SELECT 1,2,3 FROM table WHERE 4 = %u", $input);
*If you expect anything else from integer hex it. If you hex it, you will perfectly escape all input. In C/C++ there's a function called mysql_hex_string(), in PHP you can use bin2hex().
Don't worry about that the escaped string will have a 2x size of its original length because even if you use mysql_real_escape_string, PHP has to allocate same capacity ((2*input_length)+1), which is the same.
*This hex method is often used when you transfer binary data, but I see no reason why not use it on all data to prevent SQL injection attacks. Note that you have to prepend data with 0x or use the MySQL function UNHEX instead.
So, for example, the query:
SELECT password FROM users WHERE name = 'root';
Will become:
SELECT password FROM users WHERE name = 0x726f6f74;
or
SELECT password FROM users WHERE name = UNHEX('726f6f74');
Hex is the perfect escape. No way to inject.
Difference between UNHEX function and 0x prefix
There was some discussion in comments, so I finally want to make it clear. These two approaches are very similar, but they are a little different in some ways:
The 0x prefix can only be used for data columns such as char, varchar, text, block, binary, etc.
Also, its use is a little complicated if you are about to insert an empty string. You'll have to entirely replace it with '', or you'll get an error.
UNHEX() works on any column; you do not have to worry about the empty string.
Hex methods are often used as attacks
Note that this hex method is often used as an SQL injection attack where integers are just like strings and escaped just with mysql_real_escape_string. Then you can avoid the use of quotes.
For example, if you just do something like this:
"SELECT title FROM article WHERE id = " . mysql_real_escape_string($_GET["id"])
an attack can inject you very easily. Consider the following injected code returned from your script:
SELECT ... WHERE id = -1 UNION ALL SELECT table_name FROM information_schema.tables;
and now just extract table structure:
SELECT ... WHERE id = -1 UNION ALL SELECT column_name FROM information_schema.column WHERE table_name = __0x61727469636c65__;
And then just select whatever data ones want. Isn't it cool?
But if the coder of an injectable site would hex it, no injection would be possible because the query would look like this:
SELECT ... WHERE id = UNHEX('2d312075...3635');
A:
Deprecated Warning:
This answer's sample code (like the question's sample code) uses PHP's MySQL extension, which was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.
Security Warning: This answer is not in line with security best practices. Escaping is inadequate to prevent SQL injection, use prepared statements instead. Use the strategy outlined below at your own risk. (Also, mysql_real_escape_string() was removed in PHP 7.)
IMPORTANT
The best way to prevent SQL Injection is to use Prepared Statements instead of escaping, as the accepted answer demonstrates.
There are libraries such as Aura.Sql and EasyDB that allow developers to use prepared statements easier. To learn more about why prepared statements are better at stopping SQL injection, refer to this mysql_real_escape_string() bypass and recently fixed Unicode SQL Injection vulnerabilities in WordPress.
Injection prevention - mysql_real_escape_string()
PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function, mysql_real_escape_string.
mysql_real_escape_string takes a string that is going to be used in a MySQL query and return the same string with all SQL injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \'.
NOTE: you must be connected to the database to use this function!
// Connect to MySQL
$name_bad = "' OR 1'";
$name_bad = mysql_real_escape_string($name_bad);
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection: <br />" . $query_bad . "<br />";
$name_evil = "'; DELETE FROM customers WHERE 1 or username = '";
$name_evil = mysql_real_escape_string($name_evil);
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection: <br />" . $query_evil;
You can find more details in MySQL - SQL Injection Prevention.
A:
Security Warning: This answer is not in line with security best practices. Escaping is inadequate to prevent SQL injection, use prepared statements instead. Use the strategy outlined below at your own risk.
You could do something basic like this:
$safe_variable = mysqli_real_escape_string($dbConnection, $_POST["user-input"]);
mysqli_query($dbConnection, "INSERT INTO table (column) VALUES ('" . $safe_variable . "')");
This won't solve every problem, but it's a very good stepping stone. I left out obvious items such as checking the variable's existence, format (numbers, letters, etc.).
A: Whatever you do end up using, make sure that you check your input hasn't already been mangled by magic_quotes or some other well-meaning rubbish, and if necessary, run it through stripslashes or whatever to sanitize it.
A:
Deprecated Warning:
This answer's sample code (like the question's sample code) uses PHP's MySQL extension, which was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.
Security Warning: This answer is not in line with security best practices. Escaping is inadequate to prevent SQL injection, use prepared statements instead. Use the strategy outlined below at your own risk. (Also, mysql_real_escape_string() was removed in PHP 7.)
Parameterized query AND input validation is the way to go. There are many scenarios under which SQL injection may occur, even though mysql_real_escape_string() has been used.
Those examples are vulnerable to SQL injection:
$offset = isset($_GET['o']) ? $_GET['o'] : 0;
$offset = mysql_real_escape_string($offset);
RunQuery("SELECT userid, username FROM sql_injection_test LIMIT $offset, 10");
or
$order = isset($_GET['o']) ? $_GET['o'] : 'userid';
$order = mysql_real_escape_string($order);
RunQuery("SELECT userid, username FROM sql_injection_test ORDER BY `$order`");
In both cases, you can't use ' to protect the encapsulation.
Source: The Unexpected SQL Injection (When Escaping Is Not Enough)
A: In my opinion, the best way to generally prevent SQL injection in your PHP application (or any web application, for that matter) is to think about your application's architecture. If the only way to protect against SQL injection is to remember to use a special method or function that does The Right Thing every time you talk to the database, you are doing it wrong. That way, it's just a matter of time until you forget to correctly format your query at some point in your code.
Adopting the MVC pattern and a framework like CakePHP or CodeIgniter is probably the right way to go: Common tasks like creating secure database queries have been solved and centrally implemented in such frameworks. They help you to organize your web application in a sensible way and make you think more about loading and saving objects than about securely constructing single SQL queries.
A: There are many ways of preventing SQL injections and other SQL hacks. You can easily find it on the Internet (Google Search). Of course PDO is one of the good solutions. But I would like to suggest you some good links prevention from SQL injection.
What is SQL injection and how to prevent
PHP manual for SQL injection
Microsoft explanation of SQL injection and prevention in PHP
And some other like Preventing SQL injection with MySQL and PHP.
Now, why you do you need to prevent your query from SQL injection?
I would like to let you know: Why do we try for preventing SQL injection with a short example below:
Query for login authentication match:
$query="select * from users where email='".$_POST['email']."' and password='".$_POST['password']."' ";
Now, if someone (a hacker) puts
$_POST['email']= [email protected]' OR '1=1
and password anything....
The query will be parsed into the system only up to:
$query="select * from users where email='[email protected]' OR '1=1';
The other part will be discarded. So, what will happen? A non-authorized user (hacker) will be able to log in as administrator without having his/her password. Now, he/she can do anything that the administrator/email person can do. See, it's very dangerous if SQL injection is not prevented.
A: I favor stored procedures (MySQL has had stored procedures support since 5.0) from a security point of view - the advantages are -
*
*Most databases (including MySQL) enable user access to be restricted to executing stored procedures. The fine-grained security access control is useful to prevent escalation of privileges attacks. This prevents compromised applications from being able to run SQL directly against the database.
*They abstract the raw SQL query from the application so less information of the database structure is available to the application. This makes it harder for people to understand the underlying structure of the database and design suitable attacks.
*They accept only parameters, so the advantages of parameterized queries are there. Of course - IMO you still need to sanitize your input - especially if you are using dynamic SQL inside the stored procedure.
The disadvantages are -
*
*They (stored procedures) are tough to maintain and tend to multiply very quickly. This makes managing them an issue.
*They are not very suitable for dynamic queries - if they are built to accept dynamic code as parameters then a lot of the advantages are negated.
A: I think if someone wants to use PHP and MySQL or some other dataBase server:
*
*Think about learning PDO (PHP Data Objects) – it is a database access layer providing a uniform method of access to multiple databases.
*Think about learning MySQLi
Libraries examples:
---- PDO
----- No placeholders - ripe for SQL injection! It's bad
$request = $pdoConnection->("INSERT INTO parents (name, addr, city) values ($name, $addr, $city)");
----- Unnamed placeholders
$request = $pdoConnection->("INSERT INTO parents (name, addr, city) values (?, ?, ?);
----- Named placeholders
$request = $pdoConnection->("INSERT INTO parents (name, addr, city) value (:name, :addr, :city)");
--- MySQLi
$request = $mysqliConnection->prepare('
SELECT * FROM trainers
WHERE name = ?
AND email = ?
AND last_login > ?');
$query->bind_param('first_param', 'second_param', $mail, time() - 3600);
$query->execute();
P.S:
PDO wins this battle with ease. With support for twelve
different database drivers and named parameters, we can get used to its API. From a security standpoint, both of them are safe as long as the developer uses them the way they are supposed to be used
A: If possible, cast the types of your parameters. But it's only working on simple types like int, bool, and float.
$unsafe_variable = $_POST['user_id'];
$safe_variable = (int)$unsafe_variable ;
mysqli_query($conn, "INSERT INTO table (column) VALUES ('" . $safe_variable . "')");
A: For those unsure of how to use PDO (coming from the mysql_ functions), I made a very, very simple PDO wrapper that is a single file. It exists to show how easy it is to do all the common things applications need to be done. Works with PostgreSQL, MySQL, and SQLite.
Basically, read it while you read the manual to see how to put the PDO functions to use in real life to make it simple to store and retrieve values in the format you want.
I want a single column
$count = DB::column('SELECT COUNT(*) FROM `user`');
I want an array(key => value) results (i.e. for making a selectbox)
$pairs = DB::pairs('SELECT `id`, `username` FROM `user`');
I want a single row result
$user = DB::row('SELECT * FROM `user` WHERE `id` = ?', array($user_id));
I want an array of results
$banned_users = DB::fetch('SELECT * FROM `user` WHERE `banned` = ?', array('TRUE'));
A:
Security Warning: This answer is not in line with security best practices. Escaping is inadequate to prevent SQL injection, use prepared statements instead.
A few guidelines for escaping special characters in SQL statements.
Don't use MySQL. This extension is deprecated. Use MySQLi or PDO instead.
MySQLi
For manually escaping special characters in a string you can use the mysqli_real_escape_string function. The function will not work properly unless the correct character set is set with mysqli_set_charset.
Example:
$mysqli = new mysqli('host', 'user', 'password', 'database');
$mysqli->set_charset('charset');
$string = $mysqli->real_escape_string($string);
$mysqli->query("INSERT INTO table (column) VALUES ('$string')");
For automatic escaping of values with prepared statements, use mysqli_prepare, and mysqli_stmt_bind_param where types for the corresponding bind variables must be provided for an appropriate conversion:
Example:
$stmt = $mysqli->prepare("INSERT INTO table (column1, column2) VALUES (?,?)");
$stmt->bind_param("is", $integer, $string);
$stmt->execute();
No matter if you use prepared statements or mysqli_real_escape_string, you always have to know the type of input data you're working with.
So if you use a prepared statement, you must specify the types of the variables for mysqli_stmt_bind_param function.
And the use of mysqli_real_escape_string is for, as the name says, escaping special characters in a string, so it will not make integers safe. The purpose of this function is to prevent breaking the strings in SQL statements, and the damage to the database that it could cause. mysqli_real_escape_string is a useful function when used properly, especially when combined with sprintf.
Example:
$string = "x' OR name LIKE '%John%";
$integer = '5 OR id != 0';
$query = sprintf( "SELECT id, email, pass, name FROM members WHERE email ='%s' AND id = %d", $mysqli->real_escape_string($string), $integer);
echo $query;
// SELECT id, email, pass, name FROM members WHERE email ='x\' OR name LIKE \'%John%' AND id = 5
$integer = '99999999999999999999';
$query = sprintf("SELECT id, email, pass, name FROM members WHERE email ='%s' AND id = %d", $mysqli->real_escape_string($string), $integer);
echo $query;
// SELECT id, email, pass, name FROM members WHERE email ='x\' OR name LIKE \'%John%' AND id = 2147483647
A:
Security Warning: This answer is not in line with security best practices. Escaping is inadequate to prevent SQL injection, use prepared statements instead. Use the strategy outlined below at your own risk. (Also, mysql_real_escape_string() was removed in PHP 7.)
Warning: The mysql extension is removed at this time. we recommend using the PDO extension
Using this PHP function mysql_escape_string() you can get a good prevention in a fast way.
For example:
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."'
mysql_escape_string — Escapes a string for use in a mysql_query
For more prevention, you can add at the end ...
wHERE 1=1 or LIMIT 1
Finally you get:
SELECT * FROM users WHERE name = '".mysql_escape_string($name_from_html_form)."' LIMIT 1
A: The simple alternative to this problem could be solved by granting appropriate permissions in the database itself.
For example: if you are using a MySQL database then enter into the database through terminal or the UI provided and just follow this command:
GRANT SELECT, INSERT, DELETE ON database TO username@'localhost' IDENTIFIED BY 'password';
This will restrict the user to only get confined with the specified query's only. Remove the delete permission and so the data would never get deleted from the query fired from the PHP page.
The second thing to do is to flush the privileges so that the MySQL refreshes the permissions and updates.
FLUSH PRIVILEGES;
more information about flush.
To see the current privileges for the user fire the following query.
select * from mysql.user where User='username';
Learn more about GRANT.
A: Regarding many useful answers, I hope to add some value to this thread.
SQL injection is an attack that can be done through user inputs (inputs that filled by a user and then used inside queries). The SQL injection patterns are correct query syntax while we can call it: bad queries for bad reasons, and we assume that there might be a bad person that try to get secret information (bypassing access control) that affect the three principles of security (confidentiality, integrity, and availability).
Now, our point is to prevent security threats such as SQL injection attacks, the question asking (how to prevent an SQL injection attack using PHP), be more realistic, data filtering or clearing input data is the case when using user-input data inside such query, using PHP or any other programming language is not the case, or as recommended by more people to use modern technology such as prepared statement or any other tools that currently supporting SQL injection prevention, consider that these tools not available anymore? How do you secure your application?
My approach against SQL injection is: clearing user-input data before sending it to the database (before using it inside any query).
Data filtering for (converting unsafe data to safe data)
Consider that PDO and MySQLi are not available. How can you secure your application? Do you force me to use them? What about other languages other than PHP? I prefer to provide general ideas as it can be used for wider border, not just for a specific language.
*
*SQL user (limiting user privilege): most common SQL operations are (SELECT, UPDATE, INSERT), then, why give the UPDATE privilege to a user that does not require it? For example, login, and search pages are only using SELECT, then, why use DB users in these pages with high privileges?
RULE: do not create one database user for all privileges. For all SQL operations, you can create your scheme like (deluser, selectuser, updateuser) as usernames for easy usage.
See principle of least privilege.
*Data filtering: before building any query user input, it should be validated and filtered. For programmers, it's important to define some properties for each user-input variables:
data type, data pattern, and data length. A field that is a number between (x and y) must be exactly validated using the exact rule, and for a field that is a string (text): pattern is the case, for example, a username must contain only some characters, let’s say [a-zA-Z0-9_-.]. The length varies between (x and n) where x and n (integers, x <=n).
Rule: creating exact filters and validation rules are best practices for me.
*Use other tools: Here, I will also agree with you that a prepared statement (parametrized query) and stored procedures. The disadvantages here is these ways require advanced skills which do not exist for most users. The basic idea here is to distinguish between the SQL query and the data that is used inside. Both approaches can be used even with unsafe data, because the user-input data here does not add anything to the original query, such as (any or x=x).
For more information, please read OWASP SQL Injection Prevention Cheat Sheet.
Now, if you are an advanced user, start using this defense as you like, but, for beginners, if they can't quickly implement a stored procedure and prepared the statement, it's better to filter input data as much they can.
Finally, let's consider that a user sends this text below instead of entering his/her username:
[1] UNION SELECT IF(SUBSTRING(Password,1,1)='2',BENCHMARK(100000,SHA1(1)),0) User,Password FROM mysql.user WHERE User = 'root'
This input can be checked early without any prepared statement and stored procedures, but to be on the safe side, using them starts after user-data filtering and validation.
The last point is detecting unexpected behavior which requires more effort and complexity; it's not recommended for normal web applications.
Unexpected behavior in the above user input is SELECT, UNION, IF, SUBSTRING, BENCHMARK, SHA, and root. Once these words detected, you can avoid the input.
UPDATE 1:
A user commented that this post is useless, OK! Here is what OWASP.ORG provided:
Primary defenses:
Option #1: Use of Prepared Statements (Parameterized Queries)
Option #2: Use of Stored Procedures
Option #3: Escaping all User Supplied Input
Additional defenses:
Also Enforce: Least Privilege
Also Perform: White List Input Validation
As you may know, claiming an article should be supported by a valid argument, at least by one reference! Otherwise, it's considered as an attack and a bad claim!
Update 2:
From the PHP manual, PHP: Prepared Statements - Manual:
Escaping and SQL injection
Bound variables will be escaped automatically by the server. The
server inserts their escaped values at the appropriate places into the
statement template before execution. A hint must be provided to the
server for the type of bound variable, to create an appropriate
conversion. See the mysqli_stmt_bind_param() function for more
information.
The automatic escaping of values within the server is sometimes
considered a security feature to prevent SQL injection. The same
degree of security can be achieved with non-prepared statements if
input values are escaped correctly.
Update 3:
I created test cases for knowing how PDO and MySQLi send the query to the MySQL server when using a prepared statement:
PDO:
$user = "''1''"; // Malicious keyword
$sql = 'SELECT * FROM awa_user WHERE userame =:username';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':username' => $user));
Query Log:
189 Query SELECT * FROM awa_user WHERE userame ='\'\'1\'\''
189 Quit
MySQLi:
$stmt = $mysqli->prepare("SELECT * FROM awa_user WHERE username =?")) {
$stmt->bind_param("s", $user);
$user = "''1''";
$stmt->execute();
Query Log:
188 Prepare SELECT * FROM awa_user WHERE username =?
188 Execute SELECT * FROM awa_user WHERE username ='\'\'1\'\''
188 Quit
It's clear that a prepared statement is also escaping the data, nothing else.
As also mentioned in the above statement,
The automatic escaping of values within the server is sometimes considered a security feature to prevent SQL injection. The same degree of security can be achieved with non-prepared statements, if input values are escaped correctly
Therefore, this proves that data validation such as intval() is a good idea for integer values before sending any query. In addition, preventing malicious user data before sending the query is a correct and valid approach.
Please see this question for more detail: PDO sends raw query to MySQL while Mysqli sends prepared query, both produce the same result
References:
*
*SQL Injection Cheat Sheet
*SQL Injection
*Information security
*Security Principles
*Data validation
A:
Security Warning: This answer is not in line with security best practices. Escaping is inadequate to prevent SQL injection, use prepared statements instead. Use the strategy outlined below at your own risk. (Also, mysql_real_escape_string() was removed in PHP 7.)
Deprecated Warning: The mysql extension is deprecated at this time. we recommend using the PDO extension
I use three different ways to prevent my web application from being vulnerable to SQL injection.
*
*Use of mysql_real_escape_string(), which is a pre-defined function in PHP, and this code add backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. Pass the input values as parameters to minimize the chance of SQL injection.
*The most advanced way is to use PDOs.
I hope this will help you.
Consider the following query:
$iId = mysql_real_escape_string("1 OR 1=1");
$sSql = "SELECT * FROM table WHERE id = $iId";
mysql_real_escape_string() will not protect here. If you use single quotes (' ') around your variables inside your query is what protects you against this. Here is an solution below for this:
$iId = (int) mysql_real_escape_string("1 OR 1=1");
$sSql = "SELECT * FROM table WHERE id = $iId";
This question has some good answers about this.
I suggest, using PDO is the best option.
Edit:
mysql_real_escape_string() is deprecated as of PHP 5.5.0. Use either mysqli or PDO.
An alternative to mysql_real_escape_string() is
string mysqli_real_escape_string ( mysqli $link , string $escapestr )
Example:
$iId = $mysqli->real_escape_string("1 OR 1=1");
$mysqli->query("SELECT * FROM table WHERE id = $iId");
A: To use the parameterized query, you need to use either Mysqli or PDO. To rewrite your example with mysqli, we would need something like the following.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("server", "username", "password", "database_name");
$variable = $_POST["user-input"];
$stmt = $mysqli->prepare("INSERT INTO table (column) VALUES (?)");
// "s" means the database expects a string
$stmt->bind_param("s", $variable);
$stmt->execute();
The key function you'll want to read up on there would be mysqli::prepare.
Also, as others have suggested, you may find it useful/easier to step up a layer of abstraction with something like PDO.
Please note that the case you asked about is a fairly simple one and that more complex cases may require more complex approaches. In particular:
*
*If you want to alter the structure of the SQL based on user input, parameterized queries are not going to help, and the escaping required is not covered by mysql_real_escape_string. In this kind of case, you would be better off passing the user's input through a whitelist to ensure only 'safe' values are allowed through.
A: A simple way would be to use a PHP framework like CodeIgniter or Laravel which have inbuilt features like filtering and active-record so that you don't have to worry about these nuances.
A: Warning: the approach described in this answer only applies to very specific scenarios and isn't secure since SQL injection attacks do not only rely on being able to inject X=Y.
If the attackers are trying to hack into the form via PHP's $_GET variable or with the URL's query string, you would be able to catch them if they're not secure.
RewriteCond %{QUERY_STRING} ([0-9]+)=([0-9]+)
RewriteRule ^(.*) ^/track.php
Because 1=1, 2=2, 1=2, 2=1, 1+1=2, etc... are the common questions to an SQL database of an attacker. Maybe also it's used by many hacking applications.
But you must be careful, that you must not rewrite a safe query from your site. The code above is giving you a tip, to rewrite or redirect (it depends on you) that hacking-specific dynamic query string into a page that will store the attacker's IP address, or EVEN THEIR COOKIES, history, browser, or any other sensitive information, so you can deal with them later by banning their account or contacting authorities.
A: A good idea is to use an object-relational mapper like Idiorm:
$user = ORM::for_table('user')
->where_equal('username', 'j4mie')
->find_one();
$user->first_name = 'Jamie';
$user->save();
$tweets = ORM::for_table('tweet')
->select('tweet.*')
->join('user', array(
'user.id', '=', 'tweet.user_id'
))
->where_equal('user.username', 'j4mie')
->find_many();
foreach ($tweets as $tweet) {
echo $tweet->text;
}
It not only saves you from SQL injections, but from syntax errors too! It also supports collections of models with method chaining to filter or apply actions to multiple results at once and multiple connections.
A: There are so many answers for PHP and MySQL, but here is code for PHP and Oracle for preventing SQL injection as well as regular use of oci8 drivers:
$conn = oci_connect($username, $password, $connection_string);
$stmt = oci_parse($conn, 'UPDATE table SET field = :xx WHERE ID = 123');
oci_bind_by_name($stmt, ':xx', $fieldval);
oci_execute($stmt);
A:
Deprecated Warning:
This answer's sample code (like the question's sample code) uses PHP's MySQL extension, which was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.
Security Warning: This answer is not in line with security best practices. Escaping is inadequate to prevent SQL injection, use prepared statements instead. Use the strategy outlined below at your own risk. (Also, mysql_real_escape_string() was removed in PHP 7.)
Using PDO and MYSQLi is a good practice to prevent SQL injections, but if you really want to work with MySQL functions and queries, it would be better to use
mysql_real_escape_string
$unsafe_variable = mysql_real_escape_string($_POST['user_input']);
There are more abilities to prevent this: like identify - if the input is a string, number, char or array, there are so many inbuilt functions to detect this. Also, it would be better to use these functions to check input data.
is_string
$unsafe_variable = (is_string($_POST['user_input']) ? $_POST['user_input'] : '');
is_numeric
$unsafe_variable = (is_numeric($_POST['user_input']) ? $_POST['user_input'] : '');
And it is so much better to use those functions to check input data with mysql_real_escape_string.
A: Every answer here covers only part of the problem.
In fact, there are four different query parts which we can add to SQL dynamically: -
*
*a string
*a number
*an identifier
*a syntax keyword
And prepared statements cover only two of them.
But sometimes we have to make our query even more dynamic, adding operators or identifiers as well.
So, we will need different protection techniques.
In general, such a protection approach is based on whitelisting.
In this case, every dynamic parameter should be hardcoded in your script and chosen from that set.
For example, to do dynamic ordering:
$orders = array("name", "price", "qty"); // Field names
$key = array_search($_GET['sort'], $orders)); // if we have such a name
$orderby = $orders[$key]; // If not, first one will be set automatically.
$query = "SELECT * FROM `table` ORDER BY $orderby"; // Value is safe
To ease the process I wrote a whitelist helper function that does all the job in one line:
$orderby = white_list($_GET['orderby'], "name", ["name","price","qty"], "Invalid field name");
$query = "SELECT * FROM `table` ORDER BY `$orderby`"; // sound and safe
There is another way to secure identifiers - escaping but I rather stick to whitelisting as a more robust and explicit approach. Yet as long as you have an identifier quoted, you can escape the quote character to make it safe. For example, by default for mysql you have to double the quote character to escape it. For other other DBMS escaping rules would be different.
Still, there is an issue with SQL syntax keywords (such as AND, DESC and such), but white-listing seems the only approach in this case.
So, a general recommendation may be phrased as
*
*Any variable that represents an SQL data literal, (or, to put it simply - an SQL string, or a number) must be added through a prepared statement. No Exceptions.
*Any other query part, such as an SQL keyword, a table or a field name, or an operator - must be filtered through a white list.
Update
Although there is a general agreement on the best practices regarding SQL injection protection, there are still many bad practices as well. And some of them too deeply rooted in the minds of PHP users. For instance, on this very page there are (although invisible to most visitors) more than 80 deleted answers - all removed by the community due to bad quality or promoting bad and outdated practices. Worse yet, some of the bad answers aren't deleted, but rather prospering.
For example, there(1) are(2) still(3) many(4) answers(5), including the second most upvoted answer suggesting you manual string escaping - an outdated approach that is proven to be insecure.
Or there is a slightly better answer that suggests just another method of string formatting and even boasts it as the ultimate panacea. While of course, it is not. This method is no better than regular string formatting, yet it keeps all its drawbacks: it is applicable to strings only and, like any other manual formatting, it's essentially optional, non-obligatory measure, prone to human error of any sort.
I think that all this because of one very old superstition, supported by such authorities like OWASP or the PHP manual, which proclaims equality between whatever "escaping" and protection from SQL injections.
Regardless of what PHP manual said for ages, *_escape_string by no means makes data safe and never has been intended to. Besides being useless for any SQL part other than string, manual escaping is wrong, because it is manual as opposite to automated.
And OWASP makes it even worse, stressing on escaping user input which is an utter nonsense: there should be no such words in the context of injection protection. Every variable is potentially dangerous - no matter the source! Or, in other words - every variable has to be properly formatted to be put into a query - no matter the source again. It's the destination that matters. The moment a developer starts to separate the sheep from the goats (thinking whether some particular variable is "safe" or not) he/she takes his/her first step towards disaster. Not to mention that even the wording suggests bulk escaping at the entry point, resembling the very magic quotes feature - already despised, deprecated and removed.
So, unlike whatever "escaping", prepared statements is the measure that indeed protects from SQL injection (when applicable).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2773"
} |
Q: Is it possible to write ActiveX Controls in C# that will run in Excel? I have been searching on the web for some example code on how we can write a custom ActiveX Control for use in Excel using .NET but so far I have found old articles suggesting that it is not supported.
The application we are building uses Excel as a report writer so we which to add some custom controls to the worksheets to provide a richer experience. From the research I have done so far it appears that some ActiveX Controls can only be hosted in IE and hence I need to ensure that any approach taken works with Excel as a host.
The link http://www.codeproject.com/KB/miscctrl/exposingdotnetcontrols.aspx mentions the following:
CAVEAT: As this support has been dropped from Beta2 of .NET, don't blame me if it fries your PC or toasts the cat.
Can anybody give me an indication if it is possible using .NET 1.1 and if so to any pointers on best practices?
A: Andrew Whitechapel writes about managed controls as ActiveX controls in Office documents. You can read his article here:
Using Managed Controls as ActiveX Controls
A: I would thought that you're out of luck, but did find this:
http://dotnetslackers.com/articles/csharp/WritingAnActiveXControlInCSharp.aspx
Gives me the willies... but it might just right for you.
A: Further information on creating ActiveX Controls using C# can be found below although these articles seem to use IE as a Hosting Container not Excel.
http://www.ondotnet.com/pub/a/dotnet/2003/01/20/winformshosting.html
http://www.codeproject.com/KB/miscctrl/exposingdotnetcontrols.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Multiple permission types (roles) stored in database as single decimal I was going to ask a question here about whether or not my design for some users/roles database tables was acceptable, but after some research I came across this question:
What is the best way to handle multiple permission types?
It sounds like an innovative approach, so instead of a many-to-many relationship users_to_roles table, I have multiple permissions defined as a single decimal (int data type I presume). That means all permissions for a single user are in one row. It probably won't make sense until you read the other question and answer
I can't get my brain around this one. Can someone please explain the conversion process? It sounds "right", but I'm just not getting how I convert the roles to a decimal before it goes in the db, and how it gets converted back when it comes out of the db. I'm using Java, but if you stubbed it out, that would be cool as well.
Here is the original answer in the off chance the other question gets deleted:
"Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.
[Flags]
public enum Permission
{
VIEWUSERS = 1, // 2^0 // 0000 0001
EDITUSERS = 2, // 2^1 // 0000 0010
VIEWPRODUCTS = 4, // 2^2 // 0000 0100
EDITPRODUCTS = 8, // 2^3 // 0000 1000
VIEWCLIENTS = 16, // 2^4 // 0001 0000
EDITCLIENTS = 32, // 2^5 // 0010 0000
DELETECLIENTS = 64, // 2^6 // 0100 0000
}
Then, you can combine several permissions using the AND bitwise operator.
For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3.
You can then store the permission of one user into a single column of your DataBase (in our case it would be 3).
Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not."
A: You use bitwise operations. The pseudo-code would be something like:
bool HasPermission(User user, Permission permission) {
return (user.Permission & permission) != 0;
}
void SetPermission(User user, Permission permission) {
user.Permission |= permission;
}
void ClearPermission(User user, Permission permission) {
user.Permission &= ~permission;
}
Permission is the enum type defined in your post, though whatever type it is needs to be based on an integer-like type. The same applies to the User.Permission field.
If those operators (&, |=, and &=) don't make sense to you, then read up on bitwise operations (bitwise AND and bitwise OR).
A: Actually, this is how we determine authority within a fairly large web application that I'm the DBA for.
If you are going to do something like this, you'll really benefit from having a numbers table. It will make your calculations much faster.
The basic setup includes the following tables:
*
*Groups - for doing many to many of users and security points
*Security points - which contain a value for anonymous authorization and one for authenticated users who are not part of a separate group
*Group security point join table
*A special BitMask numbers table that contains entries for the ^2 values. Thus there is one entry for 2 (2) and two entries for three (2 and 1). This keeps us from having to calculate values each time.
First we determine if the user is logged in. If they aren't we return the anonymous authorization for the security point.
Next we determine if the user is a member of any groups associated with the security point through a simple EXISTS using a JOIN. If they aren't we return the value associated with authenticated user. Most of the anonymous and authenticated defaults are set to 1 on our system because we require you to belong to specific groups.
Note: If an anonymous user gets a no access, the interface throws them over to a log in box to allow them to log in and try again.
If the user is a member of one or more groups, then we select distinct values from the BitMask table for each of the values defined for the groups. For example, if you belonged to three groups and had one authorization level of 8, one with 12 and the last with 36, our select against the Bit Mask table would return 8, 8 and 4, and 4 and 32 respectively. By doing a distinct we get the number 4, 8 and 32 which correctly bit masks to 101100.
That value is returned as the users authorization level and processed by the web site.
Make sense?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Replacements for switch statement in Python? I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?
A: def f(x):
return 1 if x == 'a' else\
2 if x in 'bcd' else\
0 #default
Short and easy to read, has a default value and supports expressions in both conditions and return values.
However, it is less efficient than the solution with a dictionary. For example, Python has to scan through all the conditions before returning the default value.
A: Simple, not tested; each condition is evaluated independently: there is no fall-through, but all cases are evaluated (although the expression to switch on is only evaluated once), unless there is a break statement. For example,
for case in [expression]:
if case == 1:
print(end='Was 1. ')
if case == 2:
print(end='Was 2. ')
break
if case in (1, 2):
print(end='Was 1 or 2. ')
print(end='Was something. ')
prints Was 1. Was 1 or 2. Was something. (Dammit! Why can't I have trailing whitespace in inline code blocks?) if expression evaluates to 1, Was 2. if expression evaluates to 2, or Was something. if expression evaluates to something else.
A: A solution I tend to use which also makes use of dictionaries is:
def decision_time( key, *args, **kwargs):
def action1()
"""This function is a closure - and has access to all the arguments"""
pass
def action2()
"""This function is a closure - and has access to all the arguments"""
pass
def action3()
"""This function is a closure - and has access to all the arguments"""
pass
return {1:action1, 2:action2, 3:action3}.get(key,default)()
This has the advantage that it doesn't try to evaluate the functions every time, and you just have to ensure that the outer function gets all the information that the inner functions need.
A: There have been a lot of answers so far that have said, "we don't have a switch in Python, do it this way". However, I would like to point out that the switch statement itself is an easily-abused construct that can and should be avoided in most cases because they promote lazy programming. Case in point:
def ToUpper(lcChar):
if (lcChar == 'a' or lcChar == 'A'):
return 'A'
elif (lcChar == 'b' or lcChar == 'B'):
return 'B'
...
elif (lcChar == 'z' or lcChar == 'Z'):
return 'Z'
else:
return None # or something
Now, you could do this with a switch-statement (if Python offered one) but you'd be wasting your time because there are methods that do this just fine. Or maybe, you have something less obvious:
def ConvertToReason(code):
if (code == 200):
return 'Okay'
elif (code == 400):
return 'Bad Request'
elif (code == 404):
return 'Not Found'
else:
return None
However, this sort of operation can and should be handled with a dictionary because it will be faster, less complex, less prone to error and more compact.
And the vast majority of "use cases" for switch statements will fall into one of these two cases; there's just very little reason to use one if you've thought about your problem thoroughly.
So, rather than asking "how do I switch in Python?", perhaps we should ask, "why do I want to switch in Python?" because that's often the more interesting question and will often expose flaws in the design of whatever you're building.
Now, that isn't to say that switches should never be used either. State machines, lexers, parsers and automata all use them to some degree and, in general, when you start from a symmetrical input and go to an asymmetrical output they can be useful; you just need to make sure that you don't use the switch as a hammer because you see a bunch of nails in your code.
A: My favorite one is a really nice recipe. It's the closest one I've seen to actual switch case statements, especially in features.
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
Here's an example:
# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = 'ten'
for case in switch(v):
if case('one'):
print 1
break
if case('two'):
print 2
break
if case('ten'):
print 10
break
if case('eleven'):
print 11
break
if case(): # default, could also just omit condition or 'if True'
print "something else!"
# No need to break here, it'll stop anyway
# break is used here to look as much like the real thing as possible, but
# elif is generally just as good and more concise.
# Empty suites are considered syntax errors, so intentional fall-throughs
# should contain 'pass'
c = 'z'
for case in switch(c):
if case('a'): pass # only necessary if the rest of the suite is empty
if case('b'): pass
# ...
if case('y'): pass
if case('z'):
print "c is lowercase!"
break
if case('A'): pass
# ...
if case('Z'):
print "c is uppercase!"
break
if case(): # default
print "I dunno what c was!"
# As suggested by Pierre Quentel, you can even expand upon the
# functionality of the classic 'case' statement by matching multiple
# cases in a single shot. This greatly benefits operations such as the
# uppercase/lowercase example above:
import string
c = 'A'
for case in switch(c):
if case(*string.lowercase): # note the * for unpacking as arguments
print "c is lowercase!"
break
if case(*string.uppercase):
print "c is uppercase!"
break
if case('!', '?', '.'): # normal argument passing style also applies
print "c is a sentence terminator!"
break
if case(): # default
print "I dunno what c was!"
Some of the comments indicated that a context manager solution using with foo as case rather than for case in foo might be cleaner, and for large switch statements the linear rather than quadratic behavior might be a nice touch. Part of the value in this answer with a for loop is the ability to have breaks and fallthrough, and if we're willing to play with our choice of keywords a little bit we can get that in a context manager too:
class Switch:
def __init__(self, value):
self.value = value
self._entered = False
self._broken = False
self._prev = None
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return False # Allows a traceback to occur
def __call__(self, *values):
if self._broken:
return False
if not self._entered:
if values and self.value not in values:
return False
self._entered, self._prev = True, values
return True
if self._prev is None:
self._prev = values
return True
if self._prev != values:
self._broken = True
return False
if self._prev == values:
self._prev = None
return False
@property
def default(self):
return self()
Here's an example:
# Prints 'bar' then 'baz'.
with Switch(2) as case:
while case(0):
print('foo')
while case(1, 2, 3):
print('bar')
while case(4, 5):
print('baz')
break
while case.default:
print('default')
break
A: class Switch:
def __init__(self, value):
self.value = value
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return False # Allows a traceback to occur
def __call__(self, *values):
return self.value in values
from datetime import datetime
with Switch(datetime.today().weekday()) as case:
if case(0):
# Basic usage of switch
print("I hate mondays so much.")
# Note there is no break needed here
elif case(1,2):
# This switch also supports multiple conditions (in one line)
print("When is the weekend going to be here?")
elif case(3,4):
print("The weekend is near.")
else:
# Default would occur here
print("Let's go have fun!") # Didn't use case for example purposes
A: Defining:
def switch1(value, options):
if value in options:
options[value]()
allows you to use a fairly straightforward syntax, with the cases bundled into a map:
def sample1(x):
local = 'betty'
switch1(x, {
'a': lambda: print("hello"),
'b': lambda: (
print("goodbye," + local),
print("!")),
})
I kept trying to redefine switch in a way that would let me get rid of the "lambda:", but gave up. Tweaking the definition:
def switch(value, *maps):
options = {}
for m in maps:
options.update(m)
if value in options:
options[value]()
elif None in options:
options[None]()
Allowed me to map multiple cases to the same code, and to supply a default option:
def sample(x):
switch(x, {
_: lambda: print("other")
for _ in 'cdef'
}, {
'a': lambda: print("hello"),
'b': lambda: (
print("goodbye,"),
print("!")),
None: lambda: print("I dunno")
})
Each replicated case has to be in its own dictionary; switch() consolidates the dictionaries before looking up the value. It's still uglier than I'd like, but it has the basic efficiency of using a hashed lookup on the expression, rather than a loop through all the keys.
A: I think the best way is to use the Python language idioms to keep your code testable. As showed in previous answers, I use dictionaries to take advantage of python structures and language and keep the "case" code isolated in different methods. Below there is a class, but you can use directly a module, globals and functions. The class has methods that can be tested with isolation.
Depending to your needs, you can play with static methods and attributes too.
class ChoiceManager:
def __init__(self):
self.__choice_table = \
{
"CHOICE1" : self.my_func1,
"CHOICE2" : self.my_func2,
}
def my_func1(self, data):
pass
def my_func2(self, data):
pass
def process(self, case, data):
return self.__choice_table[case](data)
ChoiceManager().process("CHOICE1", my_data)
It is possible to take advantage of this method using also classes as keys of "__choice_table". In this way you can avoid isinstance abuse and keep all clean and testable.
Supposing you have to process a lot of messages or packets from the net or your MQ. Every packet has its own structure and its management code (in a generic way).
With the above code it is possible to do something like this:
class PacketManager:
def __init__(self):
self.__choice_table = \
{
ControlMessage : self.my_func1,
DiagnosticMessage : self.my_func2,
}
def my_func1(self, data):
# process the control message here
pass
def my_func2(self, data):
# process the diagnostic message here
pass
def process(self, pkt):
return self.__choice_table[pkt.__class__](pkt)
pkt = GetMyPacketFromNet()
PacketManager().process(pkt)
# isolated test or isolated usage example
def test_control_packet():
p = ControlMessage()
PacketManager().my_func1(p)
So complexity is not spread in the code flow, but it is rendered in the code structure.
A: Expanding on Greg Hewgill's answer - We can encapsulate the dictionary-solution using a decorator:
def case(callable):
"""switch-case decorator"""
class case_class(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def do_call(self):
return callable(*self.args, **self.kwargs)
return case_class
def switch(key, cases, default=None):
"""switch-statement"""
ret = None
try:
ret = case[key].do_call()
except KeyError:
if default:
ret = default.do_call()
finally:
return ret
This can then be used with the @case-decorator
@case
def case_1(arg1):
print 'case_1: ', arg1
@case
def case_2(arg1, arg2):
print 'case_2'
return arg1, arg2
@case
def default_case(arg1, arg2, arg3):
print 'default_case: ', arg1, arg2, arg3
ret = switch(somearg, {
1: case_1('somestring'),
2: case_2(13, 42)
}, default_case(123, 'astring', 3.14))
print ret
The good news are that this has already been done in NeoPySwitch-module. Simply install using pip:
pip install NeoPySwitch
A: There's a pattern that I learned from Twisted Python code.
class SMTP:
def lookupMethod(self, command):
return getattr(self, 'do_' + command.upper(), None)
def do_HELO(self, rest):
return 'Howdy ' + rest
def do_QUIT(self, rest):
return 'Bye'
SMTP().lookupMethod('HELO')('foo.bar.com') # => 'Howdy foo.bar.com'
SMTP().lookupMethod('QUIT')('') # => 'Bye'
You can use it any time you need to dispatch on a token and execute extended piece of code. In a state machine you would have state_ methods, and dispatch on self.state. This switch can be cleanly extended by inheriting from base class and defining your own do_ methods. Often times you won't even have do_ methods in the base class.
Edit: how exactly is that used
In case of SMTP you will receive HELO from the wire. The relevant code (from twisted/mail/smtp.py, modified for our case) looks like this
class SMTP:
# ...
def do_UNKNOWN(self, rest):
raise NotImplementedError, 'received unknown command'
def state_COMMAND(self, line):
line = line.strip()
parts = line.split(None, 1)
if parts:
method = self.lookupMethod(parts[0]) or self.do_UNKNOWN
if len(parts) == 2:
return method(parts[1])
else:
return method('')
else:
raise SyntaxError, 'bad syntax'
SMTP().state_COMMAND(' HELO foo.bar.com ') # => Howdy foo.bar.com
You'll receive ' HELO foo.bar.com ' (or you might get 'QUIT' or 'RCPT TO: foo'). This is tokenized into parts as ['HELO', 'foo.bar.com']. The actual method lookup name is taken from parts[0].
(The original method is also called state_COMMAND, because it uses the same pattern to implement a state machine, i.e. getattr(self, 'state_' + self.mode))
A: I've always liked doing it this way
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
From here
A: In addition to the dictionary methods (which I really like, BTW), you can also use if-elif-else to obtain the switch/case/default functionality:
if x == 'a':
# Do the thing
elif x == 'b':
# Do the other thing
if x in 'bc':
# Fall-through by not using elif, but now the default case includes case 'a'!
elif x in 'xyz':
# Do yet another thing
else:
# Do the default
This of course is not identical to switch/case - you cannot have fall-through as easily as leaving off the break statement, but you can have a more complicated test. Its formatting is nicer than a series of nested ifs, even though functionally that's what it is closer to.
A: Just mapping some a key to some code is not really an issue as most people have shown using the dict. The real trick is trying to emulate the whole drop through and break thing. I don't think I've ever written a case statement where I used that "feature". Here's a go at drop through.
def case(list): reduce(lambda b, f: (b | f[0], {False:(lambda:None),True:f[1]}[b | f[0]]())[0], list, False)
case([
(False, lambda:print(5)),
(True, lambda:print(4))
])
I was really imagining it as a single statement. I hope you'll pardon the silly formatting.
reduce(
initializer=False,
function=(lambda b, f:
( b | f[0]
, { False: (lambda:None)
, True : f[1]
}[b | f[0]]()
)[0]
),
iterable=[
(False, lambda:print(5)),
(True, lambda:print(4))
]
)
I hope that's valid Python code. It should give you drop through. Of course the Boolean checks could be expressions and if you wanted them to be evaluated lazily you could wrap them all in a lambda. It wouldn't be to hard to make it accept after executing some of the items in the list either. Just make the tuple (bool, bool, function) where the second bool indicates whether or not to break or drop through.
A: If you don't worry losing syntax highlight inside the case suites, you can do the following:
exec {
1: """
print ('one')
""",
2: """
print ('two')
""",
3: """
print ('three')
""",
}.get(value, """
print ('None')
""")
Where value is the value. In C, this would be:
switch (value) {
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
default:
printf("None");
break;
}
We can also create a helper function to do this:
def switch(value, cases, default):
exec cases.get(value, default)
So we can use it like this for the example with one, two and three:
switch(value, {
1: """
print ('one')
""",
2: """
print ('two')
""",
3: """
print ('three')
""",
}, """
print ('None')
""")
A: I've found the following answer from Python documentation most helpful:
You can do this easily enough with a sequence of if... elif... elif... else. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See PEP 275 for complete details and the current status.
For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:
def function_1(...):
...
functions = {'a': function_1,
'b': function_2,
'c': self.method_1, ...}
func = functions[value]
func()
For calling methods on objects, you can simplify yet further by using the getattr() built-in to retrieve methods with a particular name:
def visit_a(self, ...):
...
...
def dispatch(self, value):
method_name = 'visit_' + str(value)
method = getattr(self, method_name)
method()
It’s suggested that you use a prefix for the method names, such as visit_ in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object.
A: As a minor variation on Mark Biek's answer, for uncommon cases like this duplicate where the user has a bunch of function calls to delay with arguments to pack in (and it isn't worth building a bunch of functions out-of-line), instead of this:
d = {
"a1": lambda: a(1),
"a2": lambda: a(2),
"b": lambda: b("foo"),
"c": lambda: c(),
"z": lambda: z("bar", 25),
}
return d[string]()
… you can do this:
d = {
"a1": (a, 1),
"a2": (a, 2),
"b": (b, "foo"),
"c": (c,)
"z": (z, "bar", 25),
}
func, *args = d[string]
return func(*args)
This is certainly shorter, but whether it's more readable is an open question…
I think it might be more readable (although not briefer) to switch from lambda to partial for this particular use:
d = {
"a1": partial(a, 1),
"a2": partial(a, 2),
"b": partial(b, "foo"),
"c": c,
"z": partial(z, "bar", 25),
}
return d[string]()
… which has the advantage of working nicely with keyword arguments as well:
d = {
"a1": partial(a, 1),
"a2": partial(a, 2),
"b": partial(b, "foo"),
"c": c,
"k": partial(k, key=int),
"z": partial(z, "bar", 25),
}
return d[string]()
A: Python >= 3.10
Wow, Python 3.10+ now has a match/case syntax which is like switch/case and more!
PEP 634 -- Structural Pattern Matching
Selected features of match/case
1 - Match values:
Matching values is similar to a simple switch/case in another language:
match something:
case 1 | 2 | 3:
# Match 1-3.
case _:
# Anything else.
#
# Match will throw an error if this is omitted
# and it doesn't match any of the other patterns.
2 - Match structural patterns:
match something:
case str() | bytes():
# Match a string like object.
case [str(), int()]:
# Match a `str` and an `int` sequence
# (`list` or a `tuple` but not a `set` or an iterator).
case [_, _]:
# Match a sequence of 2 variables.
# To prevent a common mistake, sequence patterns don’t match strings.
case {"bandwidth": 100, "latency": 300}:
# Match this dict. Extra keys are ignored.
3 - Capture variables
Parse an object; saving it as variables:
match something:
case [name, count]
# Match a sequence of any two objects and parse them into the two variables.
case [x, y, *rest]:
# Match a sequence of two or more objects,
# binding object #3 and on into the rest variable.
case bytes() | str() as text:
# Match any string like object and save it to the text variable.
Capture variables can be useful when parsing data (such as JSON or HTML) that may come in one of a number of different patterns.
Capture variables is a feature. But it also means that you need to use dotted constants (ex: COLOR.RED) only. Otherwise, the constant will be treated as a capture variable and overwritten.
More sample usage:
match something:
case 0 | 1 | 2:
# Matches 0, 1 or 2 (value).
print("Small number")
case [] | [_]:
# Matches an empty or single value sequence (structure).
# Matches lists and tuples but not sets.
print("A short sequence")
case str() | bytes():
# Something of `str` or `bytes` type (data type).
print("Something string-like")
case _:
# Anything not matched by the above.
print("Something else")
Python <= 3.9
My favorite Python recipe for switch/case was:
choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')
Short and simple for simple scenarios.
Compare to 11+ lines of C code:
// C Language version of a simple 'switch/case'.
switch( key )
{
case 'a' :
result = 1;
break;
case 'b' :
result = 2;
break;
default :
result = -1;
}
You can even assign multiple variables by using tuples:
choices = {'a': (1, 2, 3), 'b': (4, 5, 6)}
(result1, result2, result3) = choices.get(key, ('default1', 'default2', 'default3'))
A: I'm just going to drop my two cents in here. The reason there isn't a case/switch statement in Python is because Python follows the principle of "there's only one right way to do something". So obviously you could come up with various ways of recreating switch/case functionality, but the Pythonic way of accomplishing this is the if/elif construct. I.e.,
if something:
return "first thing"
elif somethingelse:
return "second thing"
elif yetanotherthing:
return "third thing"
else:
return "default thing"
I just felt PEP 8 deserved a nod here. One of the beautiful things about Python is its simplicity and elegance. That is largely derived from principles laid out in PEP 8, including "There's only one right way to do something."
A: Let's say you don't want to just return a value, but want to use methods that change something on an object. Using the approach stated here would be:
result = {
'a': obj.increment(x),
'b': obj.decrement(x)
}.get(value, obj.default(x))
Here Python evaluates all methods in the dictionary.
So even if your value is 'a', the object will get incremented and decremented by x.
Solution:
func, args = {
'a' : (obj.increment, (x,)),
'b' : (obj.decrement, (x,)),
}.get(value, (obj.default, (x,)))
result = func(*args)
So you get a list containing a function and its arguments. This way, only the function pointer and the argument list get returned, not evaluated. 'result' then evaluates the returned function call.
A: Solution to run functions:
result = {
'case1': foo1,
'case2': foo2,
'case3': foo3,
}.get(option)(parameters_optional)
where foo1(), foo2() and foo3() are functions
Example 1 (with parameters):
option = number['type']
result = {
'number': value_of_int, # result = value_of_int(number['value'])
'text': value_of_text, # result = value_of_text(number['value'])
'binary': value_of_bin, # result = value_of_bin(number['value'])
}.get(option)(value['value'])
Example 2 (no parameters):
option = number['type']
result = {
'number': func_for_number, # result = func_for_number()
'text': func_for_text, # result = func_for_text()
'binary': func_for_bin, # result = func_for_bin()
}.get(option)()
Example 4 (only values):
option = number['type']
result = {
'number': lambda: 10, # result = 10
'text': lambda: 'ten', # result = 'ten'
'binary': lambda: 0b101111, # result = 47
}.get(option)()
A: I've made a switch case implementation that doesn't quite use ifs externally (it still uses an if in the class).
class SwitchCase(object):
def __init__(self):
self._cases = dict()
def add_case(self,value, fn):
self._cases[value] = fn
def add_default_case(self,fn):
self._cases['default'] = fn
def switch_case(self,value):
if value in self._cases.keys():
return self._cases[value](value)
else:
return self._cases['default'](0)
Use it like this:
from switch_case import SwitchCase
switcher = SwitchCase()
switcher.add_case(1, lambda x:x+1)
switcher.add_case(2, lambda x:x+3)
switcher.add_default_case(lambda _:[1,2,3,4,5])
print switcher.switch_case(1) #2
print switcher.switch_case(2) #5
print switcher.switch_case(123) #[1, 2, 3, 4, 5]
A: If you have a complicated case block you can consider using a function dictionary lookup table...
If you haven't done this before it's a good idea to step into your debugger and view exactly how the dictionary looks up each function.
NOTE: Do not use "()" inside the case/dictionary lookup or it will call each of your functions as the dictionary / case block is created. Remember this because you only want to call each function once using a hash style lookup.
def first_case():
print "first"
def second_case():
print "second"
def third_case():
print "third"
mycase = {
'first': first_case, #do not use ()
'second': second_case, #do not use ()
'third': third_case #do not use ()
}
myfunc = mycase['first']
myfunc()
A: Python 3.10 (2021) introduced the match-case statement which provides a first-class implementation of a "switch" for Python. For example:
def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
return 0 # 0 is the default case if x is not found
The match-case statement is considerably more powerful than this simple example.
The original answer below was written in 2008, before match-case was available:
You could use a dictionary:
def f(x):
return {
'a': 1,
'b': 2,
}[x]
A: If you're searching extra-statement, as "switch", I built a Python module that extends Python. It's called ESPY as "Enhanced Structure for Python" and it's available for both Python 2.x and Python 3.x.
For example, in this case, a switch statement could be performed by the following code:
macro switch(arg1):
while True:
cont=False
val=%arg1%
socket case(arg2):
if val==%arg2% or cont:
cont=True
socket
socket else:
socket
break
That can be used like this:
a=3
switch(a):
case(0):
print("Zero")
case(1):
print("Smaller than 2"):
break
else:
print ("greater than 1")
So espy translate it in Python as:
a=3
while True:
cont=False
if a==0 or cont:
cont=True
print ("Zero")
if a==1 or cont:
cont=True
print ("Smaller than 2")
break
print ("greater than 1")
break
A: If you are really just returning a predetermined, fixed value, you could create a dictionary with all possible input indexes as the keys, along with their corresponding values. Also, you might not really want a function to do this - unless you're computing the return value somehow.
Oh, and if you feel like doing something switch-like, see here.
A: Although there are already enough answers, I want to point a simpler and more powerful solution:
class Switch:
def __init__(self, switches):
self.switches = switches
self.between = len(switches[0]) == 3
def __call__(self, x):
for line in self.switches:
if self.between:
if line[0] <= x < line[1]:
return line[2]
else:
if line[0] == x:
return line[1]
return None
if __name__ == '__main__':
between_table = [
(1, 4, 'between 1 and 4'),
(4, 8, 'between 4 and 8')
]
switch_between = Switch(between_table)
print('Switch Between:')
for i in range(0, 10):
if switch_between(i):
print('{} is {}'.format(i, switch_between(i)))
else:
print('No match for {}'.format(i))
equals_table = [
(1, 'One'),
(2, 'Two'),
(4, 'Four'),
(5, 'Five'),
(7, 'Seven'),
(8, 'Eight')
]
print('Switch Equals:')
switch_equals = Switch(equals_table)
for i in range(0, 10):
if switch_equals(i):
print('{} is {}'.format(i, switch_equals(i)))
else:
print('No match for {}'.format(i))
Output:
Switch Between:
No match for 0
1 is between 1 and 4
2 is between 1 and 4
3 is between 1 and 4
4 is between 4 and 8
5 is between 4 and 8
6 is between 4 and 8
7 is between 4 and 8
No match for 8
No match for 9
Switch Equals:
No match for 0
1 is One
2 is Two
No match for 3
4 is Four
5 is Five
No match for 6
7 is Seven
8 is Eight
No match for 9
A: Similar to this answer by abarnert, here is a solution specifically for the use case of calling a single function for each 'case' in the switch, while avoiding the lambda or partial for ultra-conciseness while still being able to handle keyword arguments:
class switch(object):
NO_DEFAULT = object()
def __init__(self, value, default=NO_DEFAULT):
self._value = value
self._result = default
def __call__(self, option, func, *args, **kwargs):
if self._value == option:
self._result = func(*args, **kwargs)
return self
def pick(self):
if self._result is switch.NO_DEFAULT:
raise ValueError(self._value)
return self._result
Example usage:
def add(a, b):
return a + b
def double(x):
return 2 * x
def foo(**kwargs):
return kwargs
result = (
switch(3)
(1, add, 7, 9)
(2, double, 5)
(3, foo, bar=0, spam=8)
(4, lambda: double(1 / 0)) # if evaluating arguments is not safe
).pick()
print(result)
Note that this is chaining calls, i.e. switch(3)(...)(...)(...). Don't put commas in between. It's also important to put it all in one expression, which is why I've used extra parentheses around the main call for implicit line continuation.
The above example will raise an error if you switch on a value that is not handled, e.g. switch(5)(1, ...)(2, ...)(3, ...). You can provide a default value instead, e.g. switch(5, default=-1)... returns -1.
A: Expanding on the "dict as switch" idea. If you want to use a default value for your switch:
def f(x):
try:
return {
'a': 1,
'b': 2,
}[x]
except KeyError:
return 'default'
A: Most of the answers here are pretty old, and especially the accepted ones, so it seems worth updating.
First, the official Python FAQ covers this, and recommends the elif chain for simple cases and the dict for larger or more complex cases. It also suggests a set of visit_ methods (a style used by many server frameworks) for some cases:
def dispatch(self, value):
method_name = 'visit_' + str(value)
method = getattr(self, method_name)
method()
The FAQ also mentions PEP 275, which was written to get an official once-and-for-all decision on adding C-style switch statements. But that PEP was actually deferred to Python 3, and it was only officially rejected as a separate proposal, PEP 3103. The answer was, of course, no—but the two PEPs have links to additional information if you're interested in the reasons or the history.
One thing that came up multiple times (and can be seen in PEP 275, even though it was cut out as an actual recommendation) is that if you're really bothered by having 8 lines of code to handle 4 cases, vs. the 6 lines you'd have in C or Bash, you can always write this:
if x == 1: print('first')
elif x == 2: print('second')
elif x == 3: print('third')
else: print('did not place')
This isn't exactly encouraged by PEP 8, but it's readable and not too unidiomatic.
Over the more than a decade since PEP 3103 was rejected, the issue of C-style case statements, or even the slightly more powerful version in Go, has been considered dead; whenever anyone brings it up on python-ideas or -dev, they're referred to the old decision.
However, the idea of full ML-style pattern matching arises every few years, especially since languages like Swift and Rust have adopted it. The problem is that it's hard to get much use out of pattern matching without algebraic data types. While Guido has been sympathetic to the idea, nobody's come up with a proposal that fits into Python very well. (You can read my 2014 strawman for an example.) This could change with dataclass in 3.7 and some sporadic proposals for a more powerful enum to handle sum types, or with various proposals for different kinds of statement-local bindings (like PEP 3150, or the set of proposals currently being discussed on -ideas). But so far, it hasn't.
There are also occasionally proposals for Perl 6-style matching, which is basically a mishmash of everything from elif to regex to single-dispatch type-switching.
A: I found that a common switch structure:
switch ...parameter...
case p1: v1; break;
case p2: v2; break;
default: v3;
can be expressed in Python as follows:
(lambda x: v1 if p1(x) else v2 if p2(x) else v3)
or formatted in a clearer way:
(lambda x:
v1 if p1(x) else
v2 if p2(x) else
v3)
Instead of being a statement, the Python version is an expression, which evaluates to a value.
A: The solutions I use:
A combination of 2 of the solutions posted here, which is relatively easy to read and supports defaults.
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}.get(whatToUse, lambda x: x - 22)(value)
where
.get('c', lambda x: x - 22)(23)
looks up "lambda x: x - 2" in the dict and uses it with x=23
.get('xxx', lambda x: x - 22)(44)
doesn't find it in the dict and uses the default "lambda x: x - 22" with x=44.
A: If you'd like defaults, you could use the dictionary get(key[, default]) function:
def f(x):
return {
'a': 1,
'b': 2
}.get(x, 9) # 9 will be returned default if x is not found
A: You can use a dispatched dict:
#!/usr/bin/env python
def case1():
print("This is case 1")
def case2():
print("This is case 2")
def case3():
print("This is case 3")
token_dict = {
"case1" : case1,
"case2" : case2,
"case3" : case3,
}
def main():
cases = ("case1", "case3", "case2", "case1")
for case in cases:
token_dict[case]()
if __name__ == '__main__':
main()
Output:
This is case 1
This is case 3
This is case 2
This is case 1
A: I didn't find the simple answer I was looking for anywhere on Google search. But I figured it out anyway. It's really quite simple. Decided to post it, and maybe prevent a few less scratches on someone else's head. The key is simply "in" and tuples. Here is the switch statement behavior with fall-through, including RANDOM fall-through.
l = ['Dog', 'Cat', 'Bird', 'Bigfoot',
'Dragonfly', 'Snake', 'Bat', 'Loch Ness Monster']
for x in l:
if x in ('Dog', 'Cat'):
x += " has four legs"
elif x in ('Bat', 'Bird', 'Dragonfly'):
x += " has wings."
elif x in ('Snake',):
x += " has a forked tongue."
else:
x += " is a big mystery by default."
print(x)
print()
for x in range(10):
if x in (0, 1):
x = "Values 0 and 1 caught here."
elif x in (2,):
x = "Value 2 caught here."
elif x in (3, 7, 8):
x = "Values 3, 7, 8 caught here."
elif x in (4, 6):
x = "Values 4 and 6 caught here"
else:
x = "Values 5 and 9 caught in default."
print(x)
Provides:
Dog has four legs
Cat has four legs
Bird has wings.
Bigfoot is a big mystery by default.
Dragonfly has wings.
Snake has a forked tongue.
Bat has wings.
Loch Ness Monster is a big mystery by default.
Values 0 and 1 caught here.
Values 0 and 1 caught here.
Value 2 caught here.
Values 3, 7, 8 caught here.
Values 4 and 6 caught here
Values 5 and 9 caught in default.
Values 4 and 6 caught here
Values 3, 7, 8 caught here.
Values 3, 7, 8 caught here.
Values 5 and 9 caught in default.
A: # simple case alternative
some_value = 5.0
# this while loop block simulates a case block
# case
while True:
# case 1
if some_value > 5:
print ('Greater than five')
break
# case 2
if some_value == 5:
print ('Equal to five')
break
# else case 3
print ( 'Must be less than 5')
break
A: I was quite confused after reading the accepted answer, but this cleared it all up:
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
This code is analogous to:
function(argument){
switch(argument) {
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
default:
return "nothing";
}
}
Check the Source for more about dictionary mapping to functions.
A: def f(x):
dictionary = {'a':1, 'b':2, 'c':3}
return dictionary.get(x,'Not Found')
##Returns the value for the letter x;returns 'Not Found' if x isn't a key in the dictionary
A: class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
def case(*args):
return any((arg == switch.value for arg in args))
Usage:
while switch(n):
if case(0):
print "You typed zero."
break
if case(1, 4, 9):
print "n is a perfect square."
break
if case(2):
print "n is an even number."
if case(2, 3, 5, 7):
print "n is a prime number."
break
if case(6, 8):
print "n is an even number."
break
print "Only single-digit numbers are allowed."
break
Tests:
n = 2
#Result:
#n is an even number.
#n is a prime number.
n = 11
#Result:
#Only single-digit numbers are allowed.
A: I liked Mark Bies's answer
Since the x variable must used twice, I modified the lambda functions to parameterless.
I have to run with results[value](value)
In [2]: result = {
...: 'a': lambda x: 'A',
...: 'b': lambda x: 'B',
...: 'c': lambda x: 'C'
...: }
...: result['a']('a')
...:
Out[2]: 'A'
In [3]: result = {
...: 'a': lambda : 'A',
...: 'b': lambda : 'B',
...: 'c': lambda : 'C',
...: None: lambda : 'Nothing else matters'
...: }
...: result['a']()
...:
Out[3]: 'A'
Edit: I noticed that I can use None type with with dictionaries. So this would emulate switch ; case else
A: Also use the list for storing the cases, and call corresponding the function by select -
cases = ['zero()', 'one()', 'two()', 'three()']
def zero():
print "method for 0 called..."
def one():
print "method for 1 called..."
def two():
print "method for 2 called..."
def three():
print "method for 3 called..."
i = int(raw_input("Enter choice between 0-3 "))
if(i<=len(cases)):
exec(cases[i])
else:
print "wrong choice"
Also explained at screwdesk.
A: The following works for my situation when I need a simple switch-case to call a bunch of methods and not to just print some text. After playing with lambda and globals it hit me as the simplest option for me so far. Maybe it will help someone also:
def start():
print("Start")
def stop():
print("Stop")
def print_help():
print("Help")
def choose_action(arg):
return {
"start": start,
"stop": stop,
"help": print_help,
}.get(arg, print_help)
argument = sys.argv[1].strip()
choose_action(argument)() # calling a method from the given string
A: And another option:
def fnc_MonthSwitch(int_Month): #### Define a function take in the month variable
str_Return ="Not Found" #### Set Default Value
if int_Month==1: str_Return = "Jan"
if int_Month==2: str_Return = "Feb"
if int_Month==3: str_Return = "Mar"
return str_Return; #### Return the month found
print ("Month Test 3: " + fnc_MonthSwitch( 3) )
print ("Month Test 14: " + fnc_MonthSwitch(14) )
A: Easy to remember:
while True:
try:
x = int(input("Enter a numerical input: "))
except:
print("Invalid input - please enter a Integer!");
if x==1:
print("good");
elif x==2:
print("bad");
elif x==3:
break
else:
print ("terrible");
A: A switch statement is just syntactic sugar for if/elif/else.
What any control statement is doing is delegating the job based on certain condition is being fulfilled - decision path. For wrapping that into a module and being able to call a job based on its unique id, one can use inheritance and the fact that any method in Python is virtual, to provide the derived class specific job implementation, as a specific "case" handler:
#!/usr/bin/python
import sys
class Case(object):
"""
Base class which specifies the interface for the "case" handler.
The all required arbitrary arguments inside "execute" method will be
provided through the derived class
specific constructor
@note in Python, all class methods are virtual
"""
def __init__(self, id):
self.id = id
def pair(self):
"""
Pairs the given id of the "case" with
the instance on which "execute" will be called
"""
return (self.id, self)
def execute(self): # Base class virtual method that needs to be overridden
pass
class Case1(Case):
def __init__(self, id, msg):
self.id = id
self.msg = msg
def execute(self): # Override the base class method
print("<Case1> id={}, message: \"{}\"".format(str(self.id), self.msg))
class Case2(Case):
def __init__(self, id, n):
self.id = id
self.n = n
def execute(self): # Override the base class method
print("<Case2> id={}, n={}.".format(str(self.id), str(self.n)))
print("\n".join(map(str, range(self.n))))
class Switch(object):
"""
The class which delegates the jobs
based on the given job id
"""
def __init__(self, cases):
self.cases = cases # dictionary: time complexity for the access operation is 1
def resolve(self, id):
try:
cases[id].execute()
except KeyError as e:
print("Given id: {} is wrong!".format(str(id)))
if __name__ == '__main__':
# Cases
cases=dict([Case1(0, "switch").pair(), Case2(1, 5).pair()])
switch = Switch(cases)
# id will be dynamically specified
switch.resolve(0)
switch.resolve(1)
switch.resolve(2)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1717"
} |
Q: Why won't my local Apache open html pages? so, I'm running Apache on my laptop.
If I go to "localhost", I get the page that says,
If you can see this, it means that the installation of the Apache web server software on this system was successful. You may now add content to this directory and replace this page.
except, I can't add content and replace that page.
I can click on its links, and that works fine.
First of all, there's not even an "index.html" document in that directory. If I try to directly access one that I created with localhost/index.html, I get "the request URL was not found on the server." So, I'm not even sure where that page is coming from. I've searched for words in that page under the apache directory, and nothing turns up. It seems to redirect somewhere.
Just as a test, I KNOW that it loads localhost/manual/index.html (doesn't matter what that is) so I tried to replace that with something I've written, and I received the message
The server encountered an internal error or misconfiguration and was unable to complete your request.
The error log says,
[Fri Sep 12 20:27:54 2008] [error] [client 127.0.0.1] Syntax error in type map, no ':' in C:/Program Files/Apache Group/Apache2/manual/index.html for header \r\n
But, that page works fine if I open directly with a browser.
so, basically, I don't know what I don't know here. I'm not sure what apache is looking for. I'm not sure if the error is in my config file, my html page, or what.
Oh, and the reason I want to open this using apache is (mainly) because I'm trying to test some php, so I'm trying to get apache to run locally.
Thanks.
A: "By default, your pages should be placed in the "C:\Program Files\Apache Group\Apache2\htdocs" folder for Apache 2.0 and the "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs" folder for Apache 2.2. When your site is ready, simply delete the existing files in the folder and replace them with those you want to test."
From here.
A: OK,
To answer my own. . .I found that the "Listen" directive in the configuration file had been set to "Listen 80" instead of "Listen localhost: 80".
Also, localhost/htdocs/index.html doesn't work, but localhost/index.html does.
Hopefully this can help someone in the future.
Thanks, Schroeder.
A: If you have Skype it also uses the same ports(80, 443) as Xampp does. So start Xampp first and then Skype.
[source: http://starikovs.com/2011/02/23/apache-doesnt-start-in-xampp/]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to animate the command line? I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:
[======> ] 37%
and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?
A: One way to do this is to repeatedly update the line of text with the current progress. For example:
def status(percent):
sys.stdout.write("%3d%%\r" % percent)
sys.stdout.flush()
Note that I used sys.stdout.write instead of print (this is Python) because print automatically prints "\r\n" (carriage-return new-line) at the end of each line. I just want the carriage-return which returns the cursor to the start of the line. Also, the flush() is necessary because by default, sys.stdout only flushes its output after a newline (or after its buffer gets full).
A: There are two ways I know of to do this:
*
*Use the backspace escape character ('\b') to erase your line
*Use the curses package, if your programming language of choice has bindings for it.
And a Google revealed ANSI Escape Codes, which appear to be a good way. For reference, here is a function in C++ to do this:
void DrawProgressBar(int len, double percent) {
cout << "\x1B[2K"; // Erase the entire current line.
cout << "\x1B[0E"; // Move to the beginning of the current line.
string progress;
for (int i = 0; i < len; ++i) {
if (i < static_cast<int>(len * percent)) {
progress += "=";
} else {
progress += " ";
}
}
cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
flush(cout); // Required.
}
A: below is my answer,use the windows APIConsoles(Windows), coding of C.
/*
* file: ProgressBarConsole.cpp
* description: a console progress bar Demo
* author: lijian <[email protected]>
* version: 1.0
* date: 2012-12-06
*/
#include <stdio.h>
#include <windows.h>
HANDLE hOut;
CONSOLE_SCREEN_BUFFER_INFO bInfo;
char charProgress[80] =
{"================================================================"};
char spaceProgress = ' ';
/*
* show a progress in the [row] line
* row start from 0 to the end
*/
int ProgressBar(char *task, int row, int progress)
{
char str[100];
int len, barLen,progressLen;
COORD crStart, crCurr;
GetConsoleScreenBufferInfo(hOut, &bInfo);
crCurr = bInfo.dwCursorPosition; //the old position
len = bInfo.dwMaximumWindowSize.X;
barLen = len - 17;//minus the extra char
progressLen = (int)((progress/100.0)*barLen);
crStart.X = 0;
crStart.Y = row;
sprintf(str,"%-10s[%-.*s>%*c]%3d%%", task,progressLen,charProgress, barLen-progressLen,spaceProgress,50);
#if 0 //use stdand libary
SetConsoleCursorPosition(hOut, crStart);
printf("%s\n", str);
#else
WriteConsoleOutputCharacter(hOut, str, len,crStart,NULL);
#endif
SetConsoleCursorPosition(hOut, crCurr);
return 0;
}
int main(int argc, char* argv[])
{
int i;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hOut, &bInfo);
for (i=0;i<100;i++)
{
ProgressBar("test", 0, i);
Sleep(50);
}
return 0;
}
A: PowerShell has a Write-Progress cmdlet that creates an in-console progress bar that you can update and modify as your script runs.
A: Here is the answer for your question... (python)
def disp_status(timelapse, timeout):
if timelapse and timeout:
percent = 100 * (float(timelapse)/float(timeout))
sys.stdout.write("progress : ["+"*"*int(percent)+" "*(100-int(percent-1))+"]"+str(percent)+" %")
sys.stdout.flush()
stdout.write("\r \r")
A: The secret is to print only \r instead of \n or \r\n at the and of the line.
\r is called carriage return and it moves the cursor at the start of the line
\n is called line feed and it moves the cursor on the next line
In the console. If you only use \r you overwrite the previously written line.
So first write a line like the following:
[ ]
then add a sign for each tick
\r[= ]
\r[== ]
...
\r[==========]
and so on.
You can use 10 chars, each representing a 10%.
Also, if you want to display a message when finished, don't forget to also add enough white chars so that you overwrite the previously written equal signs like so:
\r[done ]
A: As a follow up to Greg's answer, here is an extended version of his function that allows you to display multi-line messages; just pass in a list or tuple of the strings you want to display/refresh.
def status(msgs):
assert isinstance(msgs, (list, tuple))
sys.stdout.write(''.join(msg + '\n' for msg in msgs[:-1]) + msgs[-1] + ('\x1b[A' * (len(msgs) - 1)) + '\r')
sys.stdout.flush()
Note: I have only tested this using a linux terminal, so your mileage may vary on Windows-based systems.
A: If your using a scripting language you could use the "tput cup" command to get this done...
P.S. This is a Linux/Unix thing only as far as I know...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "81"
} |
Q: Is there replacement for cat on Windows I need to join two binary files with a *.bat script on Windows.
How can I achieve that?
A: You can use copy /b like this:
copy /b file1+file2 destfile
A: Just use the dos copy command with multiple source files and one destination file.
copy file1+file2 appendedfile
You might need the /B option for binary files
A: Windows type command works similarly to UNIX cat.
Example 1:
type file1 file2 > file3
is equivalent of:
cat file1 file2 > file3
Example 2:
type *.vcf > all_in_one.vcf
This command will merge all the vcards into one.
A: If you have control over the machine where you're doing your work, I highly recommend installing GnuWin32. Just "Download All" and let the wget program retrieve all the packages. You will then have access to cat, grep, find, gzip, tar, less, and hundreds of others.
GnuWin32 is one of the first things I install on a new Windows box.
A: In Windows 10's Redstone 1 release, the Windows added a real Linux subsystem for the NTOS kernel. I think originally it was intended to support Android apps, and maybe docker type scenarios. Microsoft partnered with Canonical and added an actual native bash shell. Also, you can use the apt package manager to get many Ubuntu packages. For example, you can do apt-get gcc to install the GCC tool chain as you would on a Linux box.
If such a thing existed while I was in university, I think I could have done most of my Unix programming assignments in the native Windows bash shell.
A: Shameless PowerShell plug (because I think the learning curve is a pain, so teaching something at any opportunity can help)
Get-Content file1,file2
Note that type is an alias for Get-Content, so if you like it better, you can write:
type file1,file2
A: If you simply want to append text to the end of existing file, you can use the >> pipe. ex:
echo new text >>existingFile.txt
A: So i was looking for a similar solution with the abillity to preserve EOL chars and found out there was no way, so i do what i do best and made my own utillity
This is a native cat executable for windows - https://mega.nz/#!6AVgwQhL!qJ1sxx-tLtpBkPIUx__iQDGKAIfmb21GHLFerhNoaWk
Usage: cat file1 file2 file3 file4 -o output.txt
-o | Specifies the next arg is the output, we must use this rather than ">>" to preserve the line endings
I call it sharp-cat as its built with C#, feel free to scan with an antivirus and source code will be made available at request
A: If you have to use a batch script and have python installed here is a polyglot answer in batch and python:
1>2# : ^
'''
@echo off
python "%~nx0" " %~nx1" "%~nx2" "%~nx3"
exit /b
rem ^
'''
import sys
import os
sys.argv = [argv.strip() for argv in sys.argv]
if len(sys.argv) != 4:
sys.exit(1)
_, file_one, file_two, out_file = sys.argv
for file_name in [file_one, file_two]:
if not os.path.isfile(file_name):
print "Can't find: {0}".format(file_name)
sys.exit(1)
if os.path.isfile(out_file):
print "Output file exists and will be overwritten"
with open(out_file, "wb") as out:
with open(file_one, "rb") as f1:
out.write(f1.read())
with open(file_two, "rb") as f2:
out.write(f2.read())
If saved as join.bat usage would be:
join.bat file_one.bin file_two.bin out_file.bin
Thanks too this answer for the inspiration.
A: I try to rejoin tar archive which has been splitted in a Linux server.
And I found if I use type in Windows's cmd.exe, it will causes the file being joined in wrong order.(i.e. type sometimes will puts XXXX.ad at first and then XXXX.ac , XXXX.aa etc ...)
So, I found a tool named bat in GitHub https://github.com/sharkdp/bat which has a Windows build, and has better code highlight and the important thing is, it works fine on Windows to rejoin tar archive!
A: Windows type command has problems, for example with Unicode characters on 512 bytes boundary. Try Cygwin's cat.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "346"
} |
Q: How do you balance fun feature creep with time constraints? I enjoy programming, usually. Tedious stuff is easy to get done as quickly and correctly as possible so I can get through it and not have to see it again.
But a lot of my coding is fun and when I get in the 'zone' I just really enjoy myself.
Which is where I make the mistake of spending too much time, perhaps adding features, perhaps writing it in a cool or elegant manner, or just doing neat prototypes.
*
*How do you recognize this is happening before it exceeds your time frame?
*What do you do before starting a potentially fun piece of code, or during, to get back on track?
*When is it ok to let yourself go "hog wild" and just enjoy it without worrying about consequences?
-Adam
A: Keep a detailed prioritized feature list/bug list. review it often then balance the fun work with bugs/features that need to get done.
A: Give yourself a hard deadline--even for your own projects. Otherwise, you'll just keep tweaking and adding features ad infinitum.
A: Always have a working release (snapshot) ready. Treat it like the way SQL server implement snapshot isolation. :)
Continue adding new cool stuffs to a separate copy of the project. Once it is stable, overwrite your release folder and that is your new snapshot. Whenever somebody ask for a demo or release, that way you can always switch to the stable application and will have something to show anytime.
A: With a backlog. That way you'll always have in mind what needs to be done before you can start doing what you want to do.
A: Justify any "fun" features you insert by regarding them as marketable eye-candy.
Unless, of course, they're not visible ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to load an xml string in the code behind to databound UI controls that bind to the XPath of the XML? Every sample that I have seen uses static XML in the xmldataprovider source, which is then used to databind UI controls using XPath binding.
Idea is to edit a dynamic XML (structure known to the developer during coding), using the WPF UI.
Has anyone found a way to load a dynamic xml string (for example load it from a file during runtime), then use that xml string as the XmlDataprovider source?
Code snippets would be great.
Update: To make it more clear,
Let's say I want to load an xml string I received from a web service call. I know the structure of the xml. So I databind it to WPF UI controls on the WPF Window. How to make this work? All the samples over the web, define the whole XML inside the XAML code in the XmlDataProvider node. This is not what I am looking for. I want to use a xml string in the codebehind to be databound to the UI controls.
A: Here is some code I used to load a XML file from disk and bind it to a TreeView. I removed some of the normal tests for conciseness. The XML in the example is an OPML file.
XmlDataProvider provider = new XmlDataProvider();
if (provider != null)
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(fileName);
provider.Document = doc;
provider.XPath = "/opml/body/outline";
FeedListTreeView.DataContext = provider;
}
A: using your webservice get your XML and create an XML Document from it, You can then set the Source of your xmlDataProvider to the XMLDocument you got from the service.
I'm not at a pc with visual studio to test it but it should be possible for you to do this.
The steps are as you mentioned in your question:
1. Get XML from webservice
2. Convert XML String to XML Document
3. Set the XMLDataProvider.Document value to your XML Document
4. Bind that to your controls
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: My first Lisp macro; is it leaky? I've been working through Practical Common Lisp and as an exercise decided to write a macro to determine if a number is a multiple of another number:
(defmacro multp (value factor)
`(= (rem ,value ,factor) 0))
so that :
(multp 40 10)
evaluates to true whilst
(multp 40 13)
does not
The question is does this macro leak in some way? Also is this "good" Lisp? Is there already an existing function/macro that I could have used?
A: Your macro looks fine to me. I don't know what a leaky macro is, but yours is pretty straightforward and doesn't require any gensyms. As far as if this is "good" Lisp, my rule of thumb is to use a macro only when a function won't do, and in this case a function can be used in place of your macro. However, if this solution works for you there's no reason not to use it.
A: Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both value and factor are evaluated only once and in order, and rem doesn't have any side effects.
This is not good Lisp though, because there's no reason to use a macro in this case. A function
(defun multp (value factor)
(zerop (rem value factor)))
is identical for all practical purposes. (Note the use of zerop. I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero, (= ... 0) might be better)
A: Well, in principle, a user could do this:
(flet ((= (&rest args) nil))
(multp 40 10))
which would evaluate to NIL... except that ANSI CL makes it illegal to rebind most standard symbols, including CL:=, so you're on the safe side in this particular case.
In generial, of course, you should be aware of both referential untransparency (capturing identifiers from the context the macro is expanded in) and macro unhygiene (leaking identifiers to expanded code).
A: No, no symbol introduced in the macro's "lexical closure" is released to the outside.
Note that leaking isn't NECESSARILY a bad thing, even if accidental leaking almost always is. For one project I worked on, I found that a macro similar to this was useful:
(defmacro ana-and (&rest forms)
(loop for form in (reverse forms)
for completion = form then `(let ((it ,form))
(when it
,completion))
finally (return completion)))
This allowed me to get "short-circuiting" of things needed to be done in sequence, with arguments carried over from previous calls in the sequence (and a failure signalled by returning NIL). The specific context this code is from is for a hand-written parser for a configuration file that has a cobbled-together-enough syntax that writing a proper parser using a parser generator was more work than hand-rolling.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to implement draggable tab using Java Swing? How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.
EDIT: The Java Tutorials - Drag and Drop and Data Transfer.
A: Found this code out there on the tubes:
class DnDTabbedPane extends JTabbedPane {
private static final int LINEWIDTH = 3;
private static final String NAME = "test";
private final GhostGlassPane glassPane = new GhostGlassPane();
private final Rectangle2D lineRect = new Rectangle2D.Double();
private final Color lineColor = new Color(0, 100, 255);
//private final DragSource dragSource = new DragSource();
//private final DropTarget dropTarget;
private int dragTabIndex = -1;
public DnDTabbedPane() {
super();
final DragSourceListener dsl = new DragSourceListener() {
public void dragEnter(DragSourceDragEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}
public void dragExit(DragSourceEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
lineRect.setRect(0,0,0,0);
glassPane.setPoint(new Point(-1000,-1000));
glassPane.repaint();
}
public void dragOver(DragSourceDragEvent e) {
//e.getLocation()
//This method returns a Point indicating the cursor location in screen coordinates at the moment
Point tabPt = e.getLocation();
SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
Point glassPt = e.getLocation();
SwingUtilities.convertPointFromScreen(glassPt, glassPane);
int targetIdx = getTargetTabIndex(glassPt);
if(getTabAreaBound().contains(tabPt) && targetIdx>=0 &&
targetIdx!=dragTabIndex && targetIdx!=dragTabIndex+1) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}else{
e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
}
}
public void dragDropEnd(DragSourceDropEvent e) {
lineRect.setRect(0,0,0,0);
dragTabIndex = -1;
if(hasGhost()) {
glassPane.setVisible(false);
glassPane.setImage(null);
}
}
public void dropActionChanged(DragSourceDragEvent e) {}
};
final Transferable t = new Transferable() {
private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);
public Object getTransferData(DataFlavor flavor) {
return DnDTabbedPane.this;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] f = new DataFlavor[1];
f[0] = this.FLAVOR;
return f;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.getHumanPresentableName().equals(NAME);
}
};
final DragGestureListener dgl = new DragGestureListener() {
public void dragGestureRecognized(DragGestureEvent e) {
Point tabPt = e.getDragOrigin();
dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
if(dragTabIndex<0) return;
initGlassPane(e.getComponent(), e.getDragOrigin());
try{
e.startDrag(DragSource.DefaultMoveDrop, t, dsl);
}catch(InvalidDnDOperationException idoe) {
idoe.printStackTrace();
}
}
};
//dropTarget =
new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true);
new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);
}
class CDropTargetListener implements DropTargetListener{
public void dragEnter(DropTargetDragEvent e) {
if(isDragAcceptable(e)) e.acceptDrag(e.getDropAction());
else e.rejectDrag();
}
public void dragExit(DropTargetEvent e) {}
public void dropActionChanged(DropTargetDragEvent e) {}
public void dragOver(final DropTargetDragEvent e) {
if(getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM) {
initTargetLeftRightLine(getTargetTabIndex(e.getLocation()));
}else{
initTargetTopBottomLine(getTargetTabIndex(e.getLocation()));
}
repaint();
if(hasGhost()) {
glassPane.setPoint(e.getLocation());
glassPane.repaint();
}
}
public void drop(DropTargetDropEvent e) {
if(isDropAcceptable(e)) {
convertTab(dragTabIndex, getTargetTabIndex(e.getLocation()));
e.dropComplete(true);
}else{
e.dropComplete(false);
}
repaint();
}
public boolean isDragAcceptable(DropTargetDragEvent e) {
Transferable t = e.getTransferable();
if(t==null) return false;
DataFlavor[] f = e.getCurrentDataFlavors();
if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
return true;
}
return false;
}
public boolean isDropAcceptable(DropTargetDropEvent e) {
Transferable t = e.getTransferable();
if(t==null) return false;
DataFlavor[] f = t.getTransferDataFlavors();
if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
return true;
}
return false;
}
}
private boolean hasGhost = true;
public void setPaintGhost(boolean flag) {
hasGhost = flag;
}
public boolean hasGhost() {
return hasGhost;
}
private int getTargetTabIndex(Point glassPt) {
Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, DnDTabbedPane.this);
boolean isTB = getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM;
for(int i=0;i<getTabCount();i++) {
Rectangle r = getBoundsAt(i);
if(isTB) r.setRect(r.x-r.width/2, r.y, r.width, r.height);
else r.setRect(r.x, r.y-r.height/2, r.width, r.height);
if(r.contains(tabPt)) return i;
}
Rectangle r = getBoundsAt(getTabCount()-1);
if(isTB) r.setRect(r.x+r.width/2, r.y, r.width, r.height);
else r.setRect(r.x, r.y+r.height/2, r.width, r.height);
return r.contains(tabPt)?getTabCount():-1;
}
private void convertTab(int prev, int next) {
if(next<0 || prev==next) {
//System.out.println("press="+prev+" next="+next);
return;
}
Component cmp = getComponentAt(prev);
String str = getTitleAt(prev);
if(next==getTabCount()) {
//System.out.println("last: press="+prev+" next="+next);
remove(prev);
addTab(str, cmp);
setSelectedIndex(getTabCount()-1);
}else if(prev>next) {
//System.out.println(" >: press="+prev+" next="+next);
remove(prev);
insertTab(str, null, cmp, null, next);
setSelectedIndex(next);
}else{
//System.out.println(" <: press="+prev+" next="+next);
remove(prev);
insertTab(str, null, cmp, null, next-1);
setSelectedIndex(next-1);
}
}
private void initTargetLeftRightLine(int next) {
if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
lineRect.setRect(0,0,0,0);
}else if(next==getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount()-1);
lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
}else if(next==0) {
Rectangle rect = getBoundsAt(0);
lineRect.setRect(-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
}else{
Rectangle rect = getBoundsAt(next-1);
lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
}
}
private void initTargetTopBottomLine(int next) {
if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
lineRect.setRect(0,0,0,0);
}else if(next==getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount()-1);
lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
}else if(next==0) {
Rectangle rect = getBoundsAt(0);
lineRect.setRect(rect.x,-LINEWIDTH/2,rect.width,LINEWIDTH);
}else{
Rectangle rect = getBoundsAt(next-1);
lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
}
}
private void initGlassPane(Component c, Point tabPt) {
//Point p = (Point) pt.clone();
getRootPane().setGlassPane(glassPane);
if(hasGhost()) {
Rectangle rect = getBoundsAt(dragTabIndex);
BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
c.paint(g);
image = image.getSubimage(rect.x,rect.y,rect.width,rect.height);
glassPane.setImage(image);
}
Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane);
glassPane.setPoint(glassPt);
glassPane.setVisible(true);
}
private Rectangle getTabAreaBound() {
Rectangle lastTab = getUI().getTabBounds(this, getTabCount()-1);
return new Rectangle(0,0,getWidth(),lastTab.y+lastTab.height);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(dragTabIndex>=0) {
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(lineColor);
g2.fill(lineRect);
}
}
}
class GhostGlassPane extends JPanel {
private final AlphaComposite composite;
private Point location = new Point(0, 0);
private BufferedImage draggingGhost = null;
public GhostGlassPane() {
setOpaque(false);
composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
}
public void setImage(BufferedImage draggingGhost) {
this.draggingGhost = draggingGhost;
}
public void setPoint(Point location) {
this.location = location;
}
public void paintComponent(Graphics g) {
if(draggingGhost == null) return;
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(composite);
double xx = location.getX() - (draggingGhost.getWidth(this) /2d);
double yy = location.getY() - (draggingGhost.getHeight(this)/2d);
g2.drawImage(draggingGhost, (int)xx, (int)yy , null);
}
}
A: @Tony: It looks like Euguenes solution just overlooks preserving TabComponents during a swap.
The convertTab method just needs to remember the TabComponent and set it to the new tabs it makes.
Try using this:
private void convertTab(TabTransferData a_data, int a_targetIndex) {
DnDTabbedPane source = a_data.getTabbedPane();
System.out.println("this=source? " + (this == source));
int sourceIndex = a_data.getTabIndex();
if (sourceIndex < 0) {
return;
} // if
//Save the tab's component, title, and TabComponent.
Component cmp = source.getComponentAt(sourceIndex);
String str = source.getTitleAt(sourceIndex);
Component tcmp = source.getTabComponentAt(sourceIndex);
if (this != source) {
source.remove(sourceIndex);
if (a_targetIndex == getTabCount()) {
addTab(str, cmp);
setTabComponentAt(getTabCount()-1, tcmp);
} else {
if (a_targetIndex < 0) {
a_targetIndex = 0;
} // if
insertTab(str, null, cmp, null, a_targetIndex);
setTabComponentAt(a_targetIndex, tcmp);
} // if
setSelectedComponent(cmp);
return;
} // if
if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {
return;
} // if
if (a_targetIndex == getTabCount()) {
source.remove(sourceIndex);
addTab(str, cmp);
setTabComponentAt(getTabCount() - 1, tcmp);
setSelectedIndex(getTabCount() - 1);
} else if (sourceIndex > a_targetIndex) {
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex);
setTabComponentAt(a_targetIndex, tcmp);
setSelectedIndex(a_targetIndex);
} else {
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex - 1);
setTabComponentAt(a_targetIndex - 1, tcmp);
setSelectedIndex(a_targetIndex - 1);
}
}
A: Curses! Beaten to the punch by a Google search. Unfortunately it's true there is no easy way to create draggable tab panes (or any other components) in Swing. So whilst the example above is complete this one I've just written is a bit simpler. So it will hopefully demonstrate the more advanced techniques involved a bit clearer. The steps are:
*
*Detect that a drag has occurred
*Draw the dragged tab to an offscreen buffer
*Track the mouse position whilst dragging occurs
*Draw the tab in the buffer on top of the component.
The above example will give you what you want but if you want to really understand the techniques applied here it might be a better exercise to round off the edges of this example and add the extra features demonstrated above to it.
Or maybe I'm just disappointed because I spent time writing this solution when one already existed :p
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public class DraggableTabbedPane extends JTabbedPane {
private boolean dragging = false;
private Image tabImage = null;
private Point currentMouseLocation = null;
private int draggedTabIndex = 0;
public DraggableTabbedPane() {
super();
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if(!dragging) {
// Gets the tab index based on the mouse position
int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY());
if(tabNumber >= 0) {
draggedTabIndex = tabNumber;
Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber);
// Paint the tabbed pane to a buffer
Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics totalGraphics = totalImage.getGraphics();
totalGraphics.setClip(bounds);
// Don't be double buffered when painting to a static image.
setDoubleBuffered(false);
paintComponent(totalGraphics);
// Paint just the dragged tab to the buffer
tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = tabImage.getGraphics();
graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this);
dragging = true;
repaint();
}
} else {
currentMouseLocation = e.getPoint();
// Need to repaint
repaint();
}
super.mouseDragged(e);
}
});
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if(dragging) {
int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10);
if(tabNumber >= 0) {
Component comp = getComponentAt(draggedTabIndex);
String title = getTitleAt(draggedTabIndex);
removeTabAt(draggedTabIndex);
insertTab(title, null, comp, null, tabNumber);
}
}
dragging = false;
tabImage = null;
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Are we dragging?
if(dragging && currentMouseLocation != null && tabImage != null) {
// Draw the dragged tab
g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this);
}
}
public static void main(String[] args) {
JFrame test = new JFrame("Tab test");
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(400, 400);
DraggableTabbedPane tabs = new DraggableTabbedPane();
tabs.addTab("One", new JButton("One"));
tabs.addTab("Two", new JButton("Two"));
tabs.addTab("Three", new JButton("Three"));
tabs.addTab("Four", new JButton("Four"));
test.add(tabs);
test.setVisible(true);
}
}
A: Add this to isDragAcceptable to avoid Exceptions:
boolean transferDataFlavorFound = false;
for (DataFlavor transferDataFlavor : t.getTransferDataFlavors()) {
if (FLAVOR.equals(transferDataFlavor)) {
transferDataFlavorFound = true;
break;
}
}
if (transferDataFlavorFound == false) {
return false;
}
A: I liked Terai Atsuhiro san's DnDTabbedPane, but I wanted more from it. The original Terai implementation transfered tabs within the TabbedPane, but it would be nicer if I could drag from one TabbedPane to another.
Inspired by @Tom's effort, I decided to modify the code myself.
There are some details I added. For example, the ghost tab now slides along the tabbed pane instead of moving together with the mouse.
setAcceptor(TabAcceptor a_acceptor) should let the consumer code decide whether to let one tab transfer from one tabbed pane to another. The default acceptor always returns true.
/** Modified DnDTabbedPane.java
* http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html
* originally written by Terai Atsuhiro.
* so that tabs can be transfered from one pane to another.
* eed3si9n.
*/
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
public class DnDTabbedPane extends JTabbedPane {
public static final long serialVersionUID = 1L;
private static final int LINEWIDTH = 3;
private static final String NAME = "TabTransferData";
private final DataFlavor FLAVOR = new DataFlavor(
DataFlavor.javaJVMLocalObjectMimeType, NAME);
private static GhostGlassPane s_glassPane = new GhostGlassPane();
private boolean m_isDrawRect = false;
private final Rectangle2D m_lineRect = new Rectangle2D.Double();
private final Color m_lineColor = new Color(0, 100, 255);
private TabAcceptor m_acceptor = null;
public DnDTabbedPane() {
super();
final DragSourceListener dsl = new DragSourceListener() {
public void dragEnter(DragSourceDragEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}
public void dragExit(DragSourceEvent e) {
e.getDragSourceContext()
.setCursor(DragSource.DefaultMoveNoDrop);
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
s_glassPane.setPoint(new Point(-1000, -1000));
s_glassPane.repaint();
}
public void dragOver(DragSourceDragEvent e) {
//e.getLocation()
//This method returns a Point indicating the cursor location in screen coordinates at the moment
TabTransferData data = getTabTransferData(e);
if (data == null) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
/*
Point tabPt = e.getLocation();
SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
if (DnDTabbedPane.this.contains(tabPt)) {
int targetIdx = getTargetTabIndex(tabPt);
int sourceIndex = data.getTabIndex();
if (getTabAreaBound().contains(tabPt)
&& (targetIdx >= 0)
&& (targetIdx != sourceIndex)
&& (targetIdx != sourceIndex + 1)) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
return;
} // if
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
*/
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
}
public void dragDropEnd(DragSourceDropEvent e) {
m_isDrawRect = false;
m_lineRect.setRect(0, 0, 0, 0);
// m_dragTabIndex = -1;
if (hasGhost()) {
s_glassPane.setVisible(false);
s_glassPane.setImage(null);
}
}
public void dropActionChanged(DragSourceDragEvent e) {
}
};
final DragGestureListener dgl = new DragGestureListener() {
public void dragGestureRecognized(DragGestureEvent e) {
// System.out.println("dragGestureRecognized");
Point tabPt = e.getDragOrigin();
int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
if (dragTabIndex < 0) {
return;
} // if
initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex);
try {
e.startDrag(DragSource.DefaultMoveDrop,
new TabTransferable(DnDTabbedPane.this, dragTabIndex), dsl);
} catch (InvalidDnDOperationException idoe) {
idoe.printStackTrace();
}
}
};
//dropTarget =
new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,
new CDropTargetListener(), true);
new DragSource().createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE, dgl);
m_acceptor = new TabAcceptor() {
public boolean isDropAcceptable(DnDTabbedPane a_component, int a_index) {
return true;
}
};
}
public TabAcceptor getAcceptor() {
return m_acceptor;
}
public void setAcceptor(TabAcceptor a_value) {
m_acceptor = a_value;
}
private TabTransferData getTabTransferData(DropTargetDropEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DropTargetDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DragSourceDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getDragSourceContext()
.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
class TabTransferable implements Transferable {
private TabTransferData m_data = null;
public TabTransferable(DnDTabbedPane a_tabbedPane, int a_tabIndex) {
m_data = new TabTransferData(DnDTabbedPane.this, a_tabIndex);
}
public Object getTransferData(DataFlavor flavor) {
return m_data;
// return DnDTabbedPane.this;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] f = new DataFlavor[1];
f[0] = FLAVOR;
return f;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.getHumanPresentableName().equals(NAME);
}
}
class TabTransferData {
private DnDTabbedPane m_tabbedPane = null;
private int m_tabIndex = -1;
public TabTransferData() {
}
public TabTransferData(DnDTabbedPane a_tabbedPane, int a_tabIndex) {
m_tabbedPane = a_tabbedPane;
m_tabIndex = a_tabIndex;
}
public DnDTabbedPane getTabbedPane() {
return m_tabbedPane;
}
public void setTabbedPane(DnDTabbedPane pane) {
m_tabbedPane = pane;
}
public int getTabIndex() {
return m_tabIndex;
}
public void setTabIndex(int index) {
m_tabIndex = index;
}
}
private Point buildGhostLocation(Point a_location) {
Point retval = new Point(a_location);
switch (getTabPlacement()) {
case JTabbedPane.TOP: {
retval.y = 1;
retval.x -= s_glassPane.getGhostWidth() / 2;
} break;
case JTabbedPane.BOTTOM: {
retval.y = getHeight() - 1 - s_glassPane.getGhostHeight();
retval.x -= s_glassPane.getGhostWidth() / 2;
} break;
case JTabbedPane.LEFT: {
retval.x = 1;
retval.y -= s_glassPane.getGhostHeight() / 2;
} break;
case JTabbedPane.RIGHT: {
retval.x = getWidth() - 1 - s_glassPane.getGhostWidth();
retval.y -= s_glassPane.getGhostHeight() / 2;
} break;
} // switch
retval = SwingUtilities.convertPoint(DnDTabbedPane.this,
retval, s_glassPane);
return retval;
}
class CDropTargetListener implements DropTargetListener {
public void dragEnter(DropTargetDragEvent e) {
// System.out.println("DropTarget.dragEnter: " + DnDTabbedPane.this);
if (isDragAcceptable(e)) {
e.acceptDrag(e.getDropAction());
} else {
e.rejectDrag();
} // if
}
public void dragExit(DropTargetEvent e) {
// System.out.println("DropTarget.dragExit: " + DnDTabbedPane.this);
m_isDrawRect = false;
}
public void dropActionChanged(DropTargetDragEvent e) {
}
public void dragOver(final DropTargetDragEvent e) {
TabTransferData data = getTabTransferData(e);
if (getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM) {
initTargetLeftRightLine(getTargetTabIndex(e.getLocation()), data);
} else {
initTargetTopBottomLine(getTargetTabIndex(e.getLocation()), data);
} // if-else
repaint();
if (hasGhost()) {
s_glassPane.setPoint(buildGhostLocation(e.getLocation()));
s_glassPane.repaint();
}
}
public void drop(DropTargetDropEvent a_event) {
// System.out.println("DropTarget.drop: " + DnDTabbedPane.this);
if (isDropAcceptable(a_event)) {
convertTab(getTabTransferData(a_event),
getTargetTabIndex(a_event.getLocation()));
a_event.dropComplete(true);
} else {
a_event.dropComplete(false);
} // if-else
m_isDrawRect = false;
repaint();
}
public boolean isDragAcceptable(DropTargetDragEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
return false;
}
public boolean isDropAcceptable(DropTargetDropEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
return false;
}
}
private boolean m_hasGhost = true;
public void setPaintGhost(boolean flag) {
m_hasGhost = flag;
}
public boolean hasGhost() {
return m_hasGhost;
}
/**
* returns potential index for drop.
* @param a_point point given in the drop site component's coordinate
* @return returns potential index for drop.
*/
private int getTargetTabIndex(Point a_point) {
boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM;
// if the pane is empty, the target index is always zero.
if (getTabCount() == 0) {
return 0;
} // if
for (int i = 0; i < getTabCount(); i++) {
Rectangle r = getBoundsAt(i);
if (isTopOrBottom) {
r.setRect(r.x - r.width / 2, r.y, r.width, r.height);
} else {
r.setRect(r.x, r.y - r.height / 2, r.width, r.height);
} // if-else
if (r.contains(a_point)) {
return i;
} // if
} // for
Rectangle r = getBoundsAt(getTabCount() - 1);
if (isTopOrBottom) {
int x = r.x + r.width / 2;
r.setRect(x, r.y, getWidth() - x, r.height);
} else {
int y = r.y + r.height / 2;
r.setRect(r.x, y, r.width, getHeight() - y);
} // if-else
return r.contains(a_point) ? getTabCount() : -1;
}
private void convertTab(TabTransferData a_data, int a_targetIndex) {
DnDTabbedPane source = a_data.getTabbedPane();
int sourceIndex = a_data.getTabIndex();
if (sourceIndex < 0) {
return;
} // if
Component cmp = source.getComponentAt(sourceIndex);
String str = source.getTitleAt(sourceIndex);
if (this != source) {
source.remove(sourceIndex);
if (a_targetIndex == getTabCount()) {
addTab(str, cmp);
} else {
if (a_targetIndex < 0) {
a_targetIndex = 0;
} // if
insertTab(str, null, cmp, null, a_targetIndex);
} // if
setSelectedComponent(cmp);
// System.out.println("press="+sourceIndex+" next="+a_targetIndex);
return;
} // if
if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {
//System.out.println("press="+prev+" next="+next);
return;
} // if
if (a_targetIndex == getTabCount()) {
//System.out.println("last: press="+prev+" next="+next);
source.remove(sourceIndex);
addTab(str, cmp);
setSelectedIndex(getTabCount() - 1);
} else if (sourceIndex > a_targetIndex) {
//System.out.println(" >: press="+prev+" next="+next);
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex);
setSelectedIndex(a_targetIndex);
} else {
//System.out.println(" <: press="+prev+" next="+next);
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex - 1);
setSelectedIndex(a_targetIndex - 1);
}
}
private void initTargetLeftRightLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height);
m_isDrawRect = true;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
}
}
private void initTargetTopBottomLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
}
}
private void initGlassPane(Component c, Point tabPt, int a_tabIndex) {
//Point p = (Point) pt.clone();
getRootPane().setGlassPane(s_glassPane);
if (hasGhost()) {
Rectangle rect = getBoundsAt(a_tabIndex);
BufferedImage image = new BufferedImage(c.getWidth(),
c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
c.paint(g);
image = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
s_glassPane.setImage(image);
} // if
s_glassPane.setPoint(buildGhostLocation(tabPt));
s_glassPane.setVisible(true);
}
private Rectangle getTabAreaBound() {
Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);
return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (m_isDrawRect) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(m_lineColor);
g2.fill(m_lineRect);
} // if
}
public interface TabAcceptor {
boolean isDropAcceptable(DnDTabbedPane a_component, int a_index);
}
}
class GhostGlassPane extends JPanel {
public static final long serialVersionUID = 1L;
private final AlphaComposite m_composite;
private Point m_location = new Point(0, 0);
private BufferedImage m_draggingGhost = null;
public GhostGlassPane() {
setOpaque(false);
m_composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);
}
public void setImage(BufferedImage draggingGhost) {
m_draggingGhost = draggingGhost;
}
public void setPoint(Point a_location) {
m_location.x = a_location.x;
m_location.y = a_location.y;
}
public int getGhostWidth() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getWidth(this);
}
public int getGhostHeight() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getHeight(this);
}
public void paintComponent(Graphics g) {
if (m_draggingGhost == null) {
return;
} // if
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(m_composite);
g2.drawImage(m_draggingGhost, (int) m_location.getX(), (int) m_location.getY(), null);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: Best way to write a Safari 4 Extension What is the best way to write a Safari extension? I've written a couple XUL extensions for Firefox, and now I'd like to write versions of them for Safari. Is there a way that would allow you to add buttons or forms to the browser UI, since this is not possible with an Input manager or Service menu?
A: With the release of Safari 5.0, Apple released a new extension framework for developers to use. In features it looks similar to Firefox extension framework allowing to customize buttons, toolbars, context menus, injections using javascript and html 5
More at this link
https://developer.apple.com/documentation/safariextensions
A: Nobody seems to have even mentioned the fact that Safari actually does support true plugins, which input manager hacks most definitely are not.
"WebKit Plug-In Programming Topics"
http://developer.apple.com/documentation/InternetWeb/Conceptual/WebKit_PluginProgTopic/
This is how things like support for PDF and Flash content are implemented. Take a peek inside your /Library/Internet Plug-ins/ directory to see examples.
Of course, there are inherent limitations, and you may not be able to accomplish what you hope to as far as UI modification. Safari plug-ins can't do all the things that Input Manager hacks can, but they will work in WebKit anywhere, and in future versions of the OS. Note: Safari is 64-bit by default on Snow Leopard, so no Input Managers work. I'm missing Safari AdBlock already... :-( I would love to see it rewritten as a bonafide plugin.
A:
Is there a way that would allow you to add buttons or forms to the browser UI, since this is not possible with an Input manager or Service menu?
Actually, with an InputManager, it would be possible. SIMBL, the common technique for Safari extensions, is simply a wrapper around InputManagers — it stands for Smart Input Manager Bundle Loader. You can add stuff to the menu bar, to the toolbar, dialogs, anywhere, simply by extending Safari's existing classes.
That said, writing extensions for Safari is not only non-trivial, as æon said, but also completely unsupported. There are some relatively popular ones out there, like Inquisitor (recently acquired by Yahoo!) and Google's Gears, but for the most part, it's very unlike Firefox's extensions, which are an officially-supported, widely used technique.
You also definitely want to take into consideration the special limitations of InputManagers on Leopard.
A: Safari plugin development is non-trivial. The interface is written in Objective-C, and most of it is not even part of WebKit (so you can't see the source), but there's machinery to inspect and patch the object hierarchy of a running application. It requires understanding of Cocoa and Objective-C, but no lower.
Here's a high level overview I had in my bookmarks of the process http://livingcode.org/2006/tab-dumping-in-safari. It goes over creating Safari plugins using Python with working (probably outdated) code. Instead of Python you can use anything that has Objective-C bindings.
There are two major parts to it:
*
*You need to attach your code to a running Safari. This is typically done with SIMBL http://www.culater.net/software/SIMBL/SIMBL.php.
*Once you're inside, you need to figure what to patch. There's a tutorial on reversing Cocoa applications http://www.culater.net/wiki/moin.cgi/CocoaReverseEngineering, which links to the most important tool, class-dump http://www.codethecode.com/projects/class-dump/ (the link on wiki is broken). Class-dump gives you a complete hierarchy of Safari's classes, where you can guess by names what, specifically, you need to patch. This is a very trial and error mode.
Reading the links above will give you the scope of the project.
A: Things have changed recently. Apple now has an extensions API available as a part of Safari 5. You can find out more on Apple's site and by joining the Safari Developer Program.
Extensions to Safari have to be digitally signed, but you can get the signing certificate free from Apple. This is the legitimate way to get your extension into Safari without resorting to hacks that will likely break every time Apple updates Safari.
A: Also, to note - Apple has stated that InputManagers are being severely limited as of Leopard and will not run in 64-bit applications per Apple Leopard Release Notes. This is especially interesting considering most applications will be 64-bit in Snow Leopard (including presumably Safari). Apple is definitely trying to obliterate InputManager as a vector to overriding and extending functionality. Safari desperately needs an extension mechanism.
A: Safari Extensions do NOT need to be Approved by apple. You just have a developer cert (for free) to make them, but you can pass them around and although Apple is making the Extension Gallery, you don't have to distribute it through there. As you can see there are already quite a few extensions that you can try today. The cert just ensures that it hasn't been tampered with.
http://safariextensions.tumblr.com/
A: If you want to look at an existing extension to see how its done, download it or get it from your Safari extensions folder then change the .safariextz to .xar then open/extract with Pacifist to view the code and if you want add it to the Extension Builder app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: What are some good rigid body dynamics references? I'm not a math guy in the least but I'm interested in learning about rigid body physics (for the purpose of implementing a basic 3d physics engine). In school I only took Maths through Algebra II, but I've done 3d dev for years so I have a fairly decent understanding of vectors, quaternions, matrices, etc. My real problem is reading complex formulas and such, so I'm looking for some decent rigid body dynamics references that will make some sense.
Anyone have any good references?
A: Physics for Game Programmers I think is better than Physics for Game Developers.
If you want something thick in your bookshelf (like I do), Eberly's 3D Game Engine Design and Erleben's Physics-Based Animation can accompany the above.
A: Chris Hecker has a nice set of articles on his website which were originally published in Game Developer Magazine. They start with 2D physics and progress to 3D.
Physically Based Modeling by David Baraff is also good, but is a bit heavier on the math.
A: I guess what you are looking for is Classical Mechanics, which describes motion in one, two, and three dimensions in a generalized manner.
I found a good introductory course on Classical Mechanics from the University of Texas.
I do not guarantee that you will be able to understand all the concepts there, but it will at least give you a basis for your plan. I advise you to consult a Physics professor to help you understand the math.
Good luck!
A: If you are already familiar (and comfortable) with
*
*linear algebra
*basic calculus
*Newton's laws of motion
then 6DoF Rigid Body Dynamics is what you are looking for. It's a brief article written [disclaimer: by me] when I once had to develop a helicopter flight simulator.
Using a rotation matrix allows for extremely simple modelling equations, but there exists a simple mapping to and from a quaternion if you prefer that representation for other reasons.
A: Trying not to get you to rip off your hair with frustration (well, Baraff's/Witkin great math articles with the multi-dimensional matrices would do that sometimes), you can look at the easier online articles such as the ones published in Gamasutra.
Here are two of them:
*
*http://www.gamasutra.com/resource_guide/20030121/kennedy_pfv.htm
*http://www.gamasutra.com/features/19990702/data_structures_01.htm
*http://www.gamasutra.com/resource_guide/20030121/jacobson_pfv.htm
You'd notice that they point at the mentioned resources as part of their references. I would add that unless you need to solve equations system for multiple particles, articulated characters, or non-rigid complex object, this might be enough to start with.
If however, you do look for more advanced physics and mathematics which involves matrices and equations systems look up Witkin and Baraff's home pages (I think they are both in Pixar if I'm not mistaken), or start with Hecker (that tried more than several practical methods and documented his results).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Git commit opens blank text file, for what? In all the Git tutorials I've read they say that you can do:
git init
git add .
git commit
When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.
A: When you create a new commit, git fires up a text editor and writes some stuff into it.
Using this text editor, the intention is for you to write the commit message that will be associated with your feshly created commit.
After you have finished doing so, save and exit the text editor. Git will use what you've written as the commit message.
The commit message has a particular structure, described as follows:
The first line of the commit message is used as the message header (or title). The preffered length of the commit header is less than 40 characters, as this is the number of characters that github displays on the Commits tab of a given repository before truncating it, which some people find irritating.
When composing the header, using a capitalized, present tense verb for the first word is common practice, though not at all required.
One newline delineates the header and body of the message.
The body can consist whatever you like. An overview of the changes introduced by your commit is reasonable. Some third party applications use info included the body of commit messages to set off various kinds of hooks (I'm thinking Gerrit and Pivotal Tracker, to name two).
Here's a short and sweet example. A leading # denotes a comment.
Gitignore index.pyc
Ignore gunicorn generated binary file
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch dev
# Your branch is ahead of 'origin/dev' by 10 commits.
# (use "git push" to publish your local commits)
#
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: .gitignore
#
Here one Mr. Torvalds opines on what makes a good commit.
And here Tpope does likewise.
As stated in several other answers, changing the default editor is a one-liner on the command line.
For my preference:
git config --global core.editor "vim"
A: As mentioned by Ben Collins, without the -m "..." argument to type the commit inline (which is generally a bad idea as it encourages you to be brief), this "big text file" that is opened up is a window in which to type the commit message.
Usually it's recommended to write a summary in the first line, skip a line, and then write more detailed notes beneath; this helps programs that do things like email the commit messages with an appropriate subject line and the full list of changes made in the body.
Instead of changing the EDITOR shell variable, you can also change the editor used by adding the additional lines in your ~/.gitconfig file:
[core]
editor = emacs
excludesfile = /Users/will/.gitignore
That second line actually has nothing to do with your problem, but I find it really useful so I can populate my ~/.gitignore file with all those filetypes I know I'll never, ever, want to commit to a repository.
A: Try Escape then ZZ, after you're done typing your message.
As others have said when you run that commit command it actually runs a text editor to enter the message into.
In my case (OS X) it was VI, which I figured out after some digging around.
In that case, hit Escape to go into "command" mode (as opposed to INSERT mode) the enter ZZ. I'm sure there are other ways of accomplishing the task but that did it for me.
Having never used VI or emacs it wasn't readily apparent to me and wasn't mentioned in any of the beginner guides I was using.
Hopefully this helps.
A: The git commit command will open up the editor specified in the EDITOR environment variable so you can enter a commit comment. On a Linux or BSD system, this should be vi by default, although any editor should work.
Just enter your comments and save the file.
A: The text file that is being opened is a summary of the current commit operation. The git commit drops you into this file so the you can add a commit message at the top of the file. Once you've added your message just save and exit from this file.
There is also a "-m msg" switch on this command that allows you to add the commit message on the command line.
A: I was confused because I kept trying to enter a filename after the :w in VIM. That doesn't trigger the commit. Instead I kept getting a message "Aborting commit due to empty commit message." Don't put a filename after the :w. :w saves the file to .git/COMMIT_EDITMSG by default. Then :q to exit to complete the commit. You can see the results with git log.
A: Now that I've changed my editor to emacs, everything work fine.
But before I set this, "git commit -a" did open gedit, but also immediately ended with a "Aborting commit due to empty commit message.". Saving the file from gedit had no effect. Explicitly setting the editor with "git config --global core.editor "gedit"" had the same result.
There's nothing wrong with emacs, but out of curiosity why doesn't this work with gedit, and is there any way to get it to work?
Thanks.
A: For those of you using OS X I found this command to work well:
git config --global core.editor "open -t -W"
which will force git to open the default text editor (textedit in my case) and then wait for you to exit the application. Keep in mind that you need to "Save" and then "Quit" textedit before the commit will go through. There are a few other commands you can play around with as detailed on this page:
Apple Developer Library - Open Command
You can also try git config --global core.editor "open -e -W" if you want git to always open textedit regardless of what the default editor is.
A: If you’re on Mac OS X and using BBEdit, you can set this up as the editor of choice for commit messages:
git config --global core.editor "bbedit -w"
Once finished edit, save and close the file and git will use it for the comments.
A: Assuming that your editor defaults to vi/vim, you can exit the commit message editor by typing:
:x
which will save and exit the commit message file. Then you'll go back to the normal git command section.
More vi commands:
http://www.lagmonster.org/docs/vi.html
A: You're meant to put the commit message in this text file, then save and quit.
You can change the default text editor that git uses with this command:
git config --global core.editor "nano"
You have to change nano to whatever command would normally open your text editor.
A: As all have said this is just where you add your commit comment - but for some it may still be confusing esp if you have not configured your editor settings, and you are not aware of what VI is : then you could be in for a shock, because you will think you are still in the GIT-Bash
In that case you are in fact in a text editor with some interesting ways of dealing with things and this set of commands may help you out so that you can get past your first commit and then configure an editor you are familiar with or use it as an opportunity to learn how to use it.
A: The -m option to commit lets you enter a commit message on the command line:
git commit -m "my first commit"
A: When doing revision control, you should always explain what the changed you made are. Usually the first time you're have a comment such as "Initial Commit."
However in the long run you want to make a good comment for each commit. You will want something of the form:
Added experimental feature x.
X will increase the performance of
feature Y in condition Z. Should you
need X activate it with the -x or
--feature-eks switches. This addresses feature request #1138.
A: Yeah, make sure you have a sensible editor set. Not sure what your default editor will be but if, like me, it is nano (it will say so somewhere near the top after you type commit) you just need to type in a comment and then hit Ctrl-X to finish. Then hit y, followed by enter to affirm the commit.
Also, if you want to see a simple list of the files you'll be committing rather than a huge diff listing beforehand try
git diff --name-only
A: Being new to Terminal as well, "Escape and then ZZ" worked for me, I've been having this issue for months and also couldn't find a way around it.
Thanks TheGeoff for your simple advice!
A: The following is probably the easiest way to commit all changes:
git commit -a -m "Type your commit message here..."
Of course there are much more detailed ways of committing, but that should get you started.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "98"
} |
Q: If possible how can one embed PostgreSQL? If it's possible, I'm interested in being able to embed a PostgreSQL database, similar to sqllite. I've read that it's not possible. I'm no database expert though, so I want to hear from you.
Essentially I want PostgreSQL without all the configuration and installation. If it's possible, tell me how.
A: You can't embed it as a in process type thing like sqlite etc, but you can easily embed it into your application setup using Inno setup at http://www.innosetup.org. Search their mailing list archive and you will find someone did most of the work for you and all you have to to is grab the zipped distro and you can easily have postgresql installed when the user installs your app. You can then use the pg_hba.conf file to restrict the server to local host only. Not a true embedded DB, but it would work.
A: Run postgresql in a background process.
Start a separate thread in your application that would start a postgresql server in local mode either by binding it to localhost with some random free port or by using sockets (does windows support sockets?). That should be fairly easy, something like:
system("C:\Program Files\MyApplication\pgsql\postgres.exe -D C:\Documents and Settings\User\Local Settings\MyApplication\database -h 127.0.0.1 -p 12345");
and then just connect to 127.0.0.1:12345.
When your application quits, you can always send a SIGTERM to your thread and then wait a few seconds for postgresql to quit (ie join the thread).
PS: You can also use pg_ctl to control your "embedded" database, even without threads, just do a "pg_ctl start" (with appropriate options) when starting the application and "pg_ctl stop" when quitting it.
A: You cannot embed it, nor should you try.
For embedding you should use sqlite as you mentioned or firebird rdbms.
A: Unless you do a major rewrite of code, it is not possible to run Postgres "embedded". Either run it as a separate process or use something else. SQLite is an excellent choice. But there are others. MySQL has an embedded version. See it at http://mysql.com/oem/. Also several java choices, and Mac has Core Data you can write too. Hell, you can even use FoxPro. What OS you on and what services you need from the database?
A: PostgreSQL is intended to run as a stand-alone server; it's probably possible to embed it if you hack at it hard and long enough, but it would be much easier to just run it as intended in a separate process.
A: HSQLDB (http://hsqldb.org/) is another db which is easily embedded. Requires Java, but is an excellent and often-used choice for Java applications.
A: Anyone tried on Mac OS X:
http://pagesperso-orange.fr/bruno.gaufier/xhtml/prod_postgresql.xhtml
http://www.macosxguru.net/article.php?story=20041119135924825
(Of course sqlite would be my embedded db of choice as well)
A: Well, I know this is a very very very old post, but if anyone has nowadays this question, I would refer to:
*
*You can use containers running Postgres. Here's a post that could be helpful, doing something along this line using R:
https://rsangole.netlify.app/post/2021/08/07/docker-based-rstudio-postgres/?utm_source=pocket_mylist
*Take a look at duckdb https://duckdb.org/docs/installation/ It is relatively new and still needs to mature. But it works pretty much like an embedded database ("In-process, serverless"), with bindings for several languages (Python, R, Java, ...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: Can I change the appearance of an html image during hover without a second image? Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?
A: Here's some good information about image opacity and transparency with CSS.
So to make an image with opacity 50%, you'd do this:
<img src="image.png" style="opacity: 0.5; filter: alpha(opacity=50)" />
The opacity: part is how Firefox does it, and it's a value between 0.0 and 1.0. filter: is how IE does it, and it's a value from 0 to 100.
A: You don't use an img tag, but an element with a background-image css attribute and set the background-position on hover. IE requires an 'a' tag as a parent element for the :hover selector. They are called css sprites.
A great article explaining how to use CSS sprites.
A: Here's some code to play with. Basic idea: put all possible states of the picture into one big image, set a "window size", that's smaller than the image; move the window around using background-position.
#test {
display: block;
width: 250px; /* window */
height: 337px; /* size */
background: url(http://vi.sualize.us/thumbs/08/09/01/fashion,indie,inspiration,portrait-f825c152cc04c3dbbb6a38174a32a00f_h.jpg) no-repeat; /* put the image */
border: 1px solid red; /* for debugging */
text-indent: -1000px; /* hide the text */
}
#test:hover {
background-position: -250px 0; /* on mouse over move the window to a different part of the image */
}
<a href="#" id="test">a button</a>
A: The way I usually see things done with smaller images such as buttons it that only a certain portion of the image is shown. Then many states of the picture will make up a larger picture which gets shifted around behind the visible port. I'll delete this when someone has code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Listview background drawing problem C# Winform I have a little problem with a Listview.
I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error]. There is a a narrow strip that doesn't paint. The width of that strip is approximately the same as a row header would be if I had a row header.
If you have a thought on what can be done to make the background draw I'd love to hear it.
Now just to try a new idea, I'm offering a ten vote bounty for the first solution that still has me using this awful construct of a mess of a pseudo grid view. [I love legacy code.]
Edit:
Here is a sample that exhibits the problem.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ListView lv = new ListView();
lv.Dock = System.Windows.Forms.DockStyle.Fill;
lv.FullRowSelect = true;
lv.GridLines = true;
lv.HideSelection = false;
lv.Location = new System.Drawing.Point(0, 0);
lv.TabIndex = 0;
lv.View = System.Windows.Forms.View.Details;
lv.AllowColumnReorder = true;
this.Controls.Add(lv);
lv.MultiSelect = true;
ColumnHeader ch = new ColumnHeader();
ch.Name = "Foo";
ch.Text = "Foo";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch);
ColumnHeader ch2 = new ColumnHeader();
ch.Name = "Bar";
ch.Text = "Bar";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch2);
lv.BeginUpdate();
for (int i = 0; i < 3; i++)
{
ListViewItem lvi = new ListViewItem("1", "2");
lvi.BackColor = Color.Black;
lvi.ForeColor = Color.White;
lv.Items.Add(lvi);
}
lv.EndUpdate();
}
}
A: Ah! I see now :}
You want hacky? I present unto you the following:
...
lv.OwnerDraw = true;
lv.DrawItem += new DrawListViewItemEventHandler( lv_DrawItem );
...
void lv_DrawItem( object sender, DrawListViewItemEventArgs e )
{
Rectangle foo = e.Bounds;
foo.Offset( -10, 0 );
e.Graphics.FillRectangle( new SolidBrush( e.Item.BackColor ), foo );
e.DrawDefault = true;
}
For a more inventive - and no less hacky - approach, you could try utilising the background image of the ListView ;)
A: (Prior to the Edit...)
I've just tried setting the BackColor on a System.Windows.Forms.ListView, and the color is applied across the control just fine (with and without images).
Are you doing any Custom Painting at all?
A: Ok I'm adding some additional solution notes. If you use the solution above you also need to insert a draw handler for the column headers, otherwise they won't paint. The selected item rectangle also looks funny so you'll want to check for that in the lv_DrawItem function and implement a similar solution. Remeber that highlighting is chosen at the system level and not in you application.
A: Better ListView (and free Better ListView Express) allows setting background image with various alignment settings (centered, tiled, stretched, fit, snap to border/corner). Alpha transparency is also supported:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Starting a process with inherited stdin/stdout/stderr in Java 6 If I start a process via Java's ProcessBuilder class, I have full access to that process's standard in, standard out, and standard error streams as Java InputStreams and OutputStreams. However, I can't find a way to seamlessly connect those streams to System.in, System.out, and System.err.
It's possible to use redirectErrorStream() to get a single InputStream that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C system() call.
This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of isatty() in the child process carries through the redirection.
A: For System.in use the following pipein() instead of pipe()
pipein(System.in, p.getOutputStream());
Implementation:
private static void pipein(final InputStream src, final OutputStream dest) {
new Thread(new Runnable() {
public void run() {
try {
int ret = -1;
while ((ret = System.in.read()) != -1) {
dest.write(ret);
dest.flush();
}
} catch (IOException e) { // just exit
}
}
}).start();
}
A: You will need to copy the Process out, err, and input streams to the System versions. The easiest way to do that is using the IOUtils class from the Commons IO package. The copy method looks to be what you need. The copy method invocations will need to be in separate threads.
Here is the basic code:
// Assume you already have a processBuilder all configured and ready to go
final Process process = processBuilder.start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(process.getOutputStream(), System.out);
} } ).start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(process.getErrorStream(), System.err);
} } ).start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(System.in, process.getInputStream());
} } ).start();
A: A variation on John's answer that compiles and doesn't require you to use Commons IO:
private static void pipeOutput(Process process) {
pipe(process.getErrorStream(), System.err);
pipe(process.getInputStream(), System.out);
}
private static void pipe(final InputStream src, final PrintStream dest) {
new Thread(new Runnable() {
public void run() {
try {
byte[] buffer = new byte[1024];
for (int n = 0; n != -1; n = src.read(buffer)) {
dest.write(buffer, 0, n);
}
} catch (IOException e) { // just exit
}
}
}).start();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: What function does a tag cloud serve? I see them all the time and always ignore them. Can someone explain to me why they have become so prevalent? If I'm using a site that allows me to explore it via tags (e.g., this one, del.icio.us, etc.) that's what I will do. Why would I need a "cloud" of tags upon which to click? I can just type that tag(s) into a search box. What am I missing?
A: It's a easy mechanism to determine which tags are most popular or how dense that tag is populated ( amount of tags).
It's just a intuative interface, I'm fairly certain that's one of the bigger reason's why they are so popular, that and they are very Web 2.0 also.
A:
Why would I need a "cloud" of tags upon which to click? I can just type that tag(s) into a search box. What am I missing?
How do you know what tags are available to type without a lot of trial and error? Even if you know what tags are available, how do you know which are most popular without a bunch more trial and error?
A: The thing that makes a tag cloud really useful (at least a well implemented tag cloud IMO) is the ability to drill into a topic deeper and deeper.
For example, I could click "Topic A" and then I can see the items in the tag cloud for all tags within the "Topic A" items. I can then drill into one of those sub topic and narrow the items even further.
The stackoverflow tag cloud doesn't do this (which is too bad), but if it did, I could click something like "visualstudio" to drill into the threads tagged visualstudio then click "asp.net" to drill into that, then "javascript". The end result would be a list of all items tagged all three "visualstudio", "asp.net" and "javascript". This is where a tag cloud becomes really useful. Unfortunately, not all tag clouds work this way (but IMO they should).
A: It's more of a browse assist than a search assist. If you see a large or bold tag in a tag cloud that interests you it my lead to some knowledge discovery that wouldn't have otherwise been sought out with a deliberate search. When I am browsing del.ico.us or stackoverflow I appreciate the tags as they sometimes lead me to discover related topics.
Wikipedia has an interesting definition:
A tag cloud or word cloud (or weighted list in visual design) is a visual depiction of user-generated tags, or simply the word content of a site, used typically to describe the content of web sites. Tags are usually single words and are typically listed alphabetically, and the importance of a tag is shown with font size or color. 1 Thus both finding a tag by alphabet and by popularity is possible. The tags are usually hyperlinks that lead to a collection of items that are associated with a tag.
A: Because searching for php is not the same as viewing all posts that the owner has tagged as php. Try it.
A: It helps you understand the focus of the page or site that you're looking at. What topics being discussed the most? What kinds of information will I find here?
If you search for something related to Java and land on two sites, one with a tag cloud showing 'Java' is prominent, and one where Java is almost invisible but 'C#' is prominent it's pretty easy to quickly decide which site is most valuable to you.
A: Tags give a way of explicitly labelling something with what it is about instead of relying on computers to extract this information.
For example, you might be interested in on questions about stackoverflow. If you search for "stackoverflow" you will get all kinds of questions that are not about stackoverflow at all (e.g. they only contain the word "stackoverflow" because there is some link to another question). By selecting questions that are tagged with "stackoverflow" you get only those post that people have explicitly identified as being about stackoverflow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: C++ Quiz - Singletons I'll soon be posting an article on my blog, but I'd like to verify I haven't missed anything first.
Find an example I've missed, and I'll cite you on my post.
The topic is failed Singleton implementations: In what cases can you accidentally get multiple instances of a singleton?
So far, I've come up with:
*
*Race Condition on first call to instance()
*Incorporation into multiple DLLs or DLL and executable
*Template definition of a singleton - actually separate classes
Any other ways I'm missing - perhaps with inheritance?
A: If you use a static instance field that you initialize in your cpp file, you can get multiple instances (and even worse behavior) if the initialization of some static/global tries to get an instance of your singleton. This is because the order of static initialization across compilation units is undefined.
A: Inheritance shouldn't be an issue as long as the ctor is private.
However, if you don't disallow the copy constructor, users may [un]intentionally copy the singleton instance. Privately inheriting from boost::noncopyable is the easiest way to prevent this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Can distutils create empty __init__.py files? If all of my __init__.py files are empty, do I have to store them into version control, or is there a way to make distutils create empty __init__.py files during installation?
A: In Python, __init__.py files actually have a meaning! They mean that the folder they are in is a Python module. As such, they have a real role in your code and should most probably be stored in Version Control.
You could well imagine a folder in your source tree that is NOT a Python module, for example a folder containing only resources (e.g. images) and no code. That folder would not need to have a __init__.py file in it. Now how do you make the difference between folders where distutils should create those files and folders where it should not ?
A: Is there a reason you want to avoid putting empty __init__.py files in version control? If you do this you won't be able to import your packages from the source directory wihout first running distutils.
If you really want to, I suppose you can create __init__.py in setup.py. It has to be before running distutils.setup, so setup itself is able to find your packages:
from distutils import setup
import os
for path in [my_package_directories]:
filename = os.path.join(pagh, '__init__.py')
if not os.path.exists(filename):
init = open(filename, 'w')
init.close()
setup(
...
)
but... what would you gain from this, compared to having the empty __init__.py files there in the first place?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What are the best strategies for using multiple AJAX libraries? What experience can you share about using multiple AJAX libraries?
There are useful features in Prototype, some in jQuery, the Yahoo library, etc. Is it possible to include all libraries and use what you want from each, do they generally all play nicely together with name spaces, etc. For the sake of speed is there a practical limit to the size/number of libraries to include or is this negligible? Are there pairs that work particularly well together (e.g. Prototype/Scriptaculous) or pairs that don't?
A: You could use all those libraries, but I highly recommend against it. Downloading and executing that much JavaScript will most likely choke the browser and slow down your user's experience. It would be much better from a user's perspective and a developer's to pick one. Less context/architecture switching and less code to maintain.
Like other answers have said, most don't conflict.
See Yahoo!'s Exceptional Performance site for more info.
A: You could use Google AJAX Libraries API.
It provides a common distribution network and a loading architecture for jQuery, prototype, script.aculo.us, MooTools and dojo
A: YUI is pretty strongly namespaced so shouldn't clash with other libraries.
As mentioned you can run jQuery in no conflict mode.
Prototype does have some issues playing nice with other libraries in part because it (or it used to) modifies core Objects like Array. Protosafe attempts to address those issues.
Script.aculo.us is simply a widget library that sits on top of Prototype so those two should obviously play nicely together.
All of this means that you could use YUI, jQuery, Prototype & Script.aculo.us in your application, but you may find that using a single library makes it a lot easier to maintain things.
A: I'm a jQuery believer as well, so pardon my lack of knowledge about the others, but ...
What makes jQuery so great is the no-conflict mode, so for example, you would do:
$('#foobar').whatever();
With no-conflict mode, you'd do this:
var jq = jQuery.noConflict();
jq('#foobar').whatever();
One less thing to worry about. I'd imagine prototype offers a similar feature, and Yahoo as well.
But anyway, I'd don't want to advocate jQuery too much and make people mad, but whatever library you select, I think they all can do pretty much of everything you would need. Especially think about the benefits of not having to learn three different libraries.
All three should be capable. Select the one you like best and extend it. :)
A: I'm using jQuery and the javascript file only version of the Microsof ajax tool kit side by side in project right now.
I think I'm going to go with jQuery and end up removing the Microsoft one. I'm very new to jQuery, but the more I learn about it, the more enamoured I get.
A: The best strategy is to not use multiple libraries. It's tempting to want to throw more libraries at a problem, but it's inefficient, error prone, and makes your code harder to maintain by others.
In most cases you should be able to avoid using multiple libraries by understanding your problem domain and which library will help you best solve it. There is also a myriad of plugins and extensions for all of these libraries.
For example, JQuery supports cross-domain JSONP calls right out of the box and has a nice widget library in JQueryUI, Prototype does not.
$.getJSON('http://anothersite.com/mashup.json?callback=?', function(data) { });
Prototype has really good OO support and it's easy to traverse the DOM, but lacks some of the cross-domain functionality required to create widgets and mashups.
var Foo = Class.create({
initialize: function(name) {
this.name = name;
}
});
var Bar = Class.create(Foo, {
initialize: function($super, name) {
$super(name);
}
});
Mootools has great effects, good OO support, really solid widgets and cross domain request, but (and this might just be my impression), the development community isn't as collaborative and social with the global community (outside of mootools) as the other communities (Prototype used to be this way). This could be a result of their main developer(s) living outside the US, and thus are not able to attend as many conferences and participate in the greater community. I wouldn't let that deter you completely though, but it is something to keep in mind.
A: Ruby on Rails uses both prototype and Scriptaculous by default, as there is little overlap between the two. I've also used yui snippets in addition to that and have never had a problem. Load times are an issue, but the libraries are usually cached, so it's only on the first page loaded.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: continuous integration web service I am in a position where I could become a team leader of a team distributed over two countries. This team would be the tech. team for a start up company that we plan to bootstrap on limited funds. So I am trying to find out ways to minimize upfront expenses. Right now we are planning to use Java and will have a lot of junit tests. I am planing on using github for VCS and lighthouse for a bug tracker. In addition I want to add a continuous integration server but I do not know of any continuous integration servers that are offered as a web service.
Does anybody know if there are continuous integration servers available in a software as a service model?
P.S. if anybody knows were I can get these three services at one location that would be great to know to.
A: I am assuming you are talking about continuous integration.
You can run CruiseControl on a virtual machine or an old machine, but if it needs to be up in the Internet, you can try virtual dedicated server hosting services. You can save money by picking Linux here, but I'd go for a Windows server if your target platform is Windows.
A: Note: This is an outdated answer from 2008. There are now plenty of such services thanks to things like Amazon's Elastic Cloud Compute service (for example, travis-ci)
I rather doubt you'll find a service to build stuff for you. Building requires a lot of CPU power, and if you're having to rebuild every time someone commits, it would be hard to scale such a service.. And I'm sure there's probably security issues and the likes as well..
As @eed3si9n said, you could run CruiseControl on a spare (virtual-)machine and use that. Then setup port forwarding, and something like http://dyndns.com or http://no-ip.info to make it publicly accessible. It's not ideal..
I've never used CruiseControl before, but I imagine there will be a way to take the build results, and upload them to a public web-server (as a dumb HTML file). That way it would sit on your home machine, watching github, building new versions and sending the results to a reliable web-host (so no "Connection Timeout" every time your home connection isn't accessible)
In fact, I just looked at the CruiseControl documentation - the build results are stored as a set of XML files, so it'd be trivial to transfer/display them on another machine.
Basically, my suggestion is: run the continuous integration server on a spare machine, have it upload the results to a public web server somehow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Alternative to PHP QuickForm? I'm currently playing around with HTML_QuickForm for generating forms in PHP. It seems kind of limited in that it's hard to insert my own javascript or customizing the display and grouping of certain elements.
Are there any alternatives to QuickForm that might provide more flexibility?
A: If you find it hard to insert Javascript into the form elements, consider using a JavaScript framework such as Prototype or jQuery. There, you can centralize the task of injecting event handling into form controls.
By that, I mean that you won't need to insert event handlers into the HTML form code. Instead, you register those events from somewhere else. For example, in Prototype you would be able to write something like this:
$('myFormControl').observe('click', myClickFunction)
Also have a look at the answers to another question.
/EDIT: of course, you can also insert custom attributes and thus event handlers into the form elements using HTML_QuickForm. However, the above way is superior.
A: I've found the Zend_Form package of the Zend Framework to be particulary flexible. This component can also be used with Zend_Dojo to rapidly implement common javascript form helpers. However, the component is agnostic when it comes to the library that you use, but supports Dojo naitively. The component also allows for grouping, multi-page forms, custom decorators, validators and other features making it very flexible.
A: I wrote an article about this for OnLamp: Autofilled PHP Forms
My beef with HTML_QuickForm and Zend_Form and all the other form-handling frameworks I could find is that they seem to assume that you'll be writing code to generate the form. But that didn't match my development process, where I'd start with the LOOK of the page (specified via HTML templates) and add functionality to it.
In my view of the world, form handling boils down to:
*
*Fetching the data that should go in the form to start (usually from a database).
*Fetching the HTML code for the form (usually a template).
*Mushing 1 and 2 together, and outputting the result.
*Getting the submitted form data and validating it.
*Re-displaying the form with error messages and the invalid data, OR
*Displaying the congratulations-your-data-was-ok page.
fillInFormValues() makes 2, 3, and 5 really easy.
A: I'll second Zend_Form; it has an excellent ini style implementation that allows you to define a form extremely quickly:
[main]
vessel.form.method = "post"
vessel.form.elements.name.type = "text"
vessel.form.elements.name.name = "name"
vessel.form.elements.name.options.label = "Name: "
vessel.form.elements.name.options.required = true
vessel.form.elements.identifier_type.type = "select"
vessel.form.elements.identifier_type.name = "identifier_type"
vessel.form.elements.identifier_type.options.label = "Identifier type: "
vessel.form.elements.identifier_type.options.required = true
vessel.form.elements.identifier_type.options.multioptions.IMO Number = "IMO Number";
vessel.form.elements.identifier_type.options.multioptions.Registry organisation and Number = "Registry organisation and Number";
vessel.form.elements.identifier_type.options.multioptions.SSR Number = "SSR Number";
vessel.form.elements.identifier.type = "text"
vessel.form.elements.identifier.name = "identifier"
vessel.form.elements.identifier.options.label = "Identifier: "
vessel.form.elements.identifier.options.required = true
vessel.form.elements.identifier.options.filters.lower.filter = "StringToUpper"
vessel.form.elements.email.type = "text"
vessel.form.elements.email.name = "email"
vessel.form.elements.email.options.label = "Email: "
vessel.form.elements.email.options.required = true
vessel.form.elements.owner_id.type = "hidden"
vessel.form.elements.owner_id.name = "owner_id"
vessel.form.elements.owner_id.options.required = true
; submit button
vessel.form.elements.submit.type = "submit"
vessel.form.elements.submit.name = "Update"
vessel.form.elements.submit.option.value = "Update"
A: With Zend_Form it is entirely possible to start with your form visually, and then work backwords.
This is done by removing all decorators and replacing them with a ViewScript decorator
$this->form->setDecorators( array(array('ViewScript', array('viewScript' => 'forms/aform.phtml'))));
And in that viewscript you would do something like this:
<?=$this->element->title->renderViewHelper()?>
Going with this approach, you can basically do anything you want with the form.
Another great thing about Zend_Form is that you can create custom elements which can encapsulate other stuff in them. For example, you can have an element which outputs a textarea and then some Javascript to turn it into a WYSIWYG area.
A: I can't really say anything about it but, the other day, I ran across the clonefish form library. It looked promising enough to end up in my bookmarks list as a "look at this later".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Calculate code metrics Are there any tools available that will calculate code metrics (for example number of code lines, cyclomatic complexity, coupling, cohesion) for your project and over time produce a graph showing the trends?
A: NDepend for .net
A: I was also looking for a code metrics tool/plugin for my IDE but as far as I know there are none (for eclipse that is) that also show a graph of the complexity over a specified time period.
However, I did find the eclipse metrics plugin, it can handle:
*
*McCabe's Cyclomatic Complexity
*Efferent Couplings
*Lack of Cohesion in Methods
*Lines Of Code in Method
*Number Of Fields
*Number Of Levels
*Number Of Locals In Scope
*Number Of Parameters
*Number Of Statements
*Weighted Methods Per Class
And while using it, I didn't miss the graphing option you are seeking as well.
I think that, if you don't find any plugins/tools that can handle the graphing over time, you should look at the tool that suits you most and offers you all the information you need; even if the given information is only for the current build of your project.
As a side note, the eclipse metrics plugin allows you to export the data to an external file (link goes to an example), so if you use a source control tool, and you should!, you can always export the data for the specific build and store the file along with the source code, that way you still have a (basic) way to go back in time and check the differences.
A: On my latest project I used SourceMonitor. It's a nice free tool for code metrics analysis.
Here is an excerpt from SourceMonitor official site:
*
*Collects metrics in a fast, single
pass through source files.
*Measures metrics for source code
written in C++, C, C#, VB.NET, Java,
Delphi, Visual Basic (VB6) or HTML.
*Includes method and function level
metrics for C++, C, C#, VB.NET,
Java, and Delphi.
*Saves metrics in checkpoints for
comparison during software
development projects.
*Displays and prints metrics in
tables and charts.
*Operates within a standard Windows
GUI or inside your scripts using XML
command files.
*Exports metrics to XML or CSV
(comma-separated-value) files for
further processing with other tools.
For .NET beside NDepend which is simply the best tool, I can recommend vil.
Following tools can perform trend analysis:
*
*CAST
*Klocwork Insight
A: keep in mind, What you measure is what you get. loc says nothing about productivity or efficency.
rate a programmer by lines of code and you will get.. lines of code.
the same argument goes for other metrics.
otoh.. http://www.crap4j.org/ is a very conservative and useful metric. it sets complexity in relation with coverage.
A: NDepend, I am using it and its best for this purpose.
Check this :
http://www.codeproject.com/KB/dotnet/NDepend.aspx
A: Concerning the tool NDepend it comes with 82 different code metric, from Number of Lines of Code, to Method Rank (popularity), Cyclomatic Complexity, Lack of Cohesion of Methods, Percentage Coverage (extracted from NCover or VSTS), Depth of Inheritance...
With its rule system, NDepend can also find issues and estimates technical debt which is an interesting code metric (amount of dev-effort to fix problems vs. amount of dev-time spoiled per year to let problems unfixed).
All these metrics are detailled here.
A: If you're in the .NET space, Developer Express' CodeRush provides LOC, Cyclomatic Complexity and the (rather excellent, IMHO) Maintenance Complexity analysis of code in real-time.
(Sorry about the Maintenance Complexity link; it's going to Google's cache. The original seems to be offline ATM).
A: Code Analyzer is simple tool which generates this kind of metrics.
(source: teel.ws)
A: Atlassian FishEye is another excellent tool for the job. It integrates with your source control system (currently supports CVS, SVN and Perforce), and analyzes all your files that way. The analysis is rather basic though, and the product itself is commercial (but very reasonably priced, IMO).
You can also get an add-on for it called Crucible that facilitates peer code reviews.
A: For Visual Studio .NET (at least C# and VB.NET) I find the free StudioTools to be extremely useful for metrics. It also adds a number of features found in commercial tools such as ReSharper.
A: Sonar is definitively a tool that you must consider, especially for Java projects. However it will also handle PHP or C/C++, Flex and Cobol code.
Here is a screenshot that show some metrics on a project:
alt text http://sonar.codehaus.org/wp-content/uploads/2009/05/squid-metrics.png
Note that you can try the tool by using their demo site at http://nemo.sonarsource.org
A: For Python, pylint can provide some code quality metrics.
A: There's also a code metrics plugin for reflector, in case you are using .NET.
A: I would recommend Code Metrics Viewer Exention for visual studio.
It is very easy to analyze solution at once, also do comparison if you made progress ;-)
Read more here about the features
A: On the PHP front, I believe for example phpUnderControl includes metrics through phpUnit (if I am not mistaken).
Keep in mind that metrics are often flawed. For example, a coder who's working on trivial problems will produce more code and there for look better on your graphs, than a coder who's cracking the complex issues.
A: If you're after some trend analysis, does it really mean anything to measure beyond SLOC?
Even if you just doing a grep for trailing semi-colons and counting the number of lines returned, what you are after is consistency in the SLOC measurement technique. In this way today's measurement can be compared with last month's measurement in a meaningful way.
I can't really see what would a trend of McCabe Cyclometric Complexity give? I think that CC should be used more for a snapshot of quality to provide feedback to the developers.
Edit: Ooh. Just thought of a couple of other measurements that might be useful. Comments as a percentage of SLOC and test coverage. Neither of which you want to let slip. Coming back to retrofit either of these is never as god as doing them "in the heat of the moment!"
HTH.
cheers,
Rob
A: Scitools' Understand does have the capability to generate a lot of code metrics for you. I don't have a lot of experience with the code metrics features, but the static analysis features in general were nice and the price was very reasonable. The support was excellent.
A: Project Code Meter gives a differential development history report (in Excel format) which shows your coding progress metrics in SLOC, time and productivity percentage (it's time estimation is based on cyclomatic complexity and other metrics). Then in Excel you can easily produce the graph you want.
see this article which describes it step by step:
http://www.projectcodemeter.com/cost_estimation/help/FN_monsizing.htm
A: For Java you can try our tool, QualityGate that computes more than 60 source code metrics, tracks all changes through time and also provides an overall rating for the maintainability of the source code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "87"
} |
Q: In PHP is it possible to use a function inside a variable I know in php you can embed variables inside variables, like:
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
But I was wondering how, and if it was possible to include a function inside a variable.
I know I could just write:
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions:
<?php
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
There is <b>alot</b> of text and html here... but I want some <i>functions</i>!
-somefunc() doesn't work
-{somefunc()} doesn't work
-$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string
-more non-working: ${somefunc()}
</body>
</html>
EOF;
?>
Or I want dynamic changes in that load of code:
<?
function somefunc($stuff) {
$output = "my bold text <b>{$stuff}</b>.";
return $output;
}
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
somefunc("is awesome!")
somefunc("is actually not so awesome..")
because somefunc("won\'t work due to my problem.")
</body>
</html>
EOF;
?>
Well?
A: Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call:
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
will output "foo <b>bar</b> baz".
I find it easier however (and this works in PHP4) to either just call the function outside of the string:
<?
echo "foo " . somefunc("bar") . " baz";
?>
or assign to a temporary variable:
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
A: "bla bla bla".function("blub")." and on it goes"
A: Expanding a bit on what Jason W said:
I find it easier however (and this works in PHP4) to either just call the
function outside of the string:
<?
echo "foo " . somefunc("bar") . " baz";
?>
You can also just embed this function call directly in your html, like:
<?
function get_date() {
$date = `date`;
return $date;
}
function page_title() {
$title = "Today's date is: ". get_date() ."!";
echo "$title";
}
function page_body() {
$body = "Hello";
$body = ", World!";
$body = "\n\n";
$body = "Today is: " . get_date() . "\n";
}
?>
<html>
<head>
<title><? page_title(); ?></title>
</head>
<body>
<? page_body(); ?>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Do I really need to use transactions in stored procedures? [MSSQL 2005] I'm writing a pretty straightforward e-commerce app in asp.net, do I need to use transactions in my stored procedures?
Read/Write ratio is about 9:1
A: Many people ask - do I need transactions? Why do I need them? When to use them?
The answer is simple: use them all the time, unless you have a very good reason not to (for instance, don't use atomic transactions for "long running activities" between businesses). The default should always be yes. You are in doubt? - use transactions.
Why are transactions beneficial? They help you deal with crashes, failures, data consistency, error handling, they help you write simpler code etc. And the list of benefits will continue to grow with time.
Here is some more info from http://blogs.msdn.com/florinlazar/
A: Remember in SQL Server all single statement CRUD operations are in an implicit transaction by default. You just need to turn on explict transactions (BEGIN TRAN) if you need to make multiple statements act as an atomic unit.
A: The answer is, it depends. You do not always need transaction safety. Sometimes it's overkill. Sometimes it's not.
I can see that, for example, when you implement a checkout process you only want to finalize it once you gathered all data, etc.. Think about a payment f'up, you can rollback - that's an example when you need a transaction. Or maybe when it's wise to use them.
Do you need a transaction when you create a new user account? Maybe, if it's across 10 tables (for whatever reason), if it's just a single table then probably not.
It also depends on what you sold your client on and who they are, and if they requested it, etc.. But if making a decision is up to you, then I'd say, choose wisely.
My bottom line is, avoid premature optimization. Build your application, keep in mind that you may want to go back and refactor/optimize later when you need it. Look at a couple opensource projects and see how they implemented different parts of their app, learn from that. You'll see that most of them don't use transactions at all, yet there are huge online stores that use them.
A: Of course, it depends.
It depends upon the work that the particular stored procedure performs and, perhaps, not so much the "read/write ratio" that you suggest. In general, you should consider enclosing a unit of work within a transaction if it is query that could be impacted by some other, simultaneously running query. If this sounds nondeterministic, it is. It is often difficult to predict under what circumstances a particular unit of work qualifies as a candidate for this.
A good place to start is to review the precise CRUD being performed within the unit of work, in this case within your stored procedure, and decide if it a) could be affected by some other, simultaneous operation and b) if that other work matters to the end result of this work being performed (or, even, vice versa). If the answer is "Yes" to both of these then consider wrapping the unit of work within a transaction.
What this is suggesting is that you can't always simply decide to either use or not use transactions, rather you should apply them when it makes sense. Use the properties defined by ACID (Atomicity, Consistency, Isolation, and Durability) to help decide when this might be the case.
One other thing to consider is that in some circumstances, particularly if the system must perform many operations in quick succession, e.g., a high-volume transaction processing application, you might need to weigh the relative performance cost of the transaction. Depending upon the size of the unit of work, a commit (or rollback) of a transaction can be resource expensive, perhaps negatively impacting the performance of your system unnecessarily or, at least, with limited benefit.
Unfortunately, this is not an easy question to precisely answer: "It depends."
A: Use them if:
*
*There are some errors that you may want to test for and catch which won't be caught except by you going out and doing the work (looking things up, testing values, etc.), usually from within a transaction so that you can roll back the whole operation.
*There are multi-step operations of any sort, which should, logically, be rolled back as a group if they fail.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: IDebugProgramProvider2.GetProviderProcessData on Vista As part of a JavaScript Profiler for IE 6/7 I needed to load a custom debugger that I created into IE. I got this working fine on XP, but couldn't get it working on Vista (full story here: http://damianblog.com/2008/09/09/tracejs-v2-rip/).
The call to GetProviderProcessData is failing on Vista. Anyone have any suggestions?
Thanks,
Damian
// Create the MsProgramProvider
IDebugProgramProvider2* pIDebugProgramProvider2 = 0;
HRESULT st = CoCreateInstance(CLSID_MsProgramProvider, 0, CLSCTX_ALL, IID_IDebugProgramProvider2, (void**)&pIDebugProgramProvider2);
if(st != S_OK) {
return st;
}
// Get the IDebugProgramNode2 instances running in this process
AD_PROCESS_ID processID;
processID.ProcessId.dwProcessId = GetCurrentProcessId();
processID.ProcessIdType = AD_PROCESS_ID_SYSTEM;
CONST_GUID_ARRAY engineFilter;
engineFilter.dwCount = 0;
PROVIDER_PROCESS_DATA processData;
st = pIDebugProgramProvider2->GetProviderProcessData(PFLAG_GET_PROGRAM_NODES|PFLAG_DEBUGGEE, 0, processID, engineFilter, &processData);
if(st != S_OK) {
ShowError(L"GPPD Failed", st);
pIDebugProgramProvider2->Release();
return st;
}
A: It would help to know what the error result was.
Possible problems I can think of:
If your getting permission denied, your most likely missing some requried Privilege in your ACL. New ones are sometimes not doceumented well, check the latest Platform SDK headers to see if any new ones that still out. It may be that under vista the Privilege is not assigned my default to your ACL any longer.
If your getting some sort of Not Found type error, then it may be 32bit / 64bit problem. Your debbugging API may only be available under 64bit COM on vista 64. The 32bit/64bit interoperation can be very confusing.
A: I'm not familiar with these interfaces, but unexpected failures in Vista may require being past a UAC prompt. Have you tried starting the debugger with admin privileges?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the benefit of using ONLY OpenID authentication on a site? From my experience with OpenID, I see a number of significant downsides:
Adds a Single Point of Failure to the site
It is not a failure that can be fixed by the site even if detected. If the OpenID provider is down for three days, what recourse does the site have to allow its users to login and access the information they own?
Takes a user to another sites content and every time they logon to your site
Even if the OpenID provider does not have an error, the user is re-directed to their site to login. The login page has content and links. So there is a chance a user will actually be drawn away from the site to go down the Internet rabbit hole.
Why would I want to send my users to another company's website?
[ Note: my provider no longer does this and seems to have fixed this problem (for now).]
Adds a non-trivial amount of time to the signup
To sign up with the site a new user is forced to read a new standard, chose a provider, and signup. Standards are something that the technical people should agree to in order to make a user experience frictionless. They are not something that should be thrust on the users.
It is a Phisher's Dream
OpenID is incredibly insecure and stealing the person's ID as they log in is trivially easy. [ taken from David Arno's Answer below ]
For all of the downside, the one upside is to allow users to have fewer logins on the Internet. If a site has opt-in for OpenID then users who want that feature can use it.
What I would like to understand is:
What benefit does a site get for making OpenID mandatory?
A: It's a good way to outsource a part of your infrastructure. You don't have to worry about lost passwords etc., someone else does it for you.
I'm not sure I'd use it exclusively, though. I haven't used OpenID enough to entirely trust it, and the sign up process needs to be streamlined until > 90% of users have an OpenID.
A:
Adds a critical point to failure to the site
The third highest idea on uservoice for Stackoverflow is to allow changing the OpenID provider. And in the comments there is the suggestion to allow associating more than on OpenID. On sites where multiple OpenIDs can be associated with an account if your usual OpenID provider is down you can still log in with another provider (assuming you've already associated it with the site).
Also, it's only a critical point of failure for users of the OpenID provider that isn't working. All the other users on other OpenID providers can continue to log it. Over time you'd expect that users would migrate to the most reliable providers.
Takes a user to another sites content and every time they logon to your site
If you've set up your OpenID provider to always trust a site (or OpenID consumer in the nomenclature) and you are already logged into your OpenID provider then they will redirect you straight back to the site without you even seeing your OpenID providers site.
Adds a non-trial amount of time to the signup
Currently that may be true, but as andyuk said, "This becomes less of an issue the more sites that support OpenID". I'd expect that in a few years time most users will already have an OpenID and know what it is.
A: One of the big benefits of going OpenID-only from an engineering perspective is that abstracting out the credentials-authentication piece lets users pick authentication methods that are much more sophisticated than whatever you would bother to build for your site. Yes, some OpenID providers are easily phished. On the other hand, other OpenID users log in with Information Cards, hardware tokens, or telephone verification, and these are credentials which cannot be captured and replayed by a phisher.
As Gabe Wachob put it:
People who want to innovate in authentication methods [...] do NOT have to be the same people who innovate in offering services on the web (any one of a million folks running Mediawiki, Drupal, etc). That "delinking" of authentication innovation and service innovation is what is valuable in OpenID.
So by using OpenID, you can offer your users stronger authentication methods. The abstraction lets you implement one interface, and then you can pick any provider to work with, whether they use eight-character passwords in cleartext or challenge-response neural implants.
A: The list of downsides misses the most obvious one: it is a phisher's dream. OpenID is incredibly insecure and stealing the person's ID as they log in is trivially easy.
Matt Sheppard hits the nail on the head as to the answer though:the benefit of only using OpenID is that it involves less hassle for the site creator as there are no usernames and passwords to handle and no user account creation code required.
A: The benefit of making OpenID mandatory is simply that login code for the website does not need to be written (beyond the OpenID integration), and no precautions need to be taken around storing user passwords etc.
Not having your own login code also means not having to deal with a lot of support issues like resetting of lost passwords etc.
Certainly most of your downsides are valid, so I guess it becomes a trade off.
What surprises me is that there are not more sites forming a close relationship with a particular OpenID provider to simply the account signup phase - i.e. some sort of 'You can use any OpenID you like, but you can also create one right now by entering a username and password etc' login page, which automatically creates a new account with the selected provider for you.
A: It encourages users to sign-up to OpenID, find out more about it and hopefully to evangelise it themselves.
Stack Overflow proves just supporting OpenID can work.
"Adds critical point to failure to the site"
In the event of an OpenID provider failing to work, the site should have a mechanism to allow users to login and add/change OpenID providers. Perhaps the site could email a temporary link to bypass security so users can access their account.
"Takes a user to another sites content and every time they logon to your site"
My OpenID provider allows me a trust a given website so I do not need to even view their website.
"Adds a non-trial amount of time to the signup"
This becomes less of an issue the more sites that support OpenID.
A: As a web developer, I'm a big fan of the idea of OpenID. Writing Auth code is a pain in the ass. As a web user, I'm a big fan of OpenID - for non-critical uses like SO, forums, etc - because once you have the ID, it's a very simple way to join a site.
I think, outside of a few exceptions - like a community for developers - at this time, you can't force OpenID only. The "average" web user (whatever that means) doesn't get it. However, promoting it in a site like this raises awareness among developers, and the idea will eventually trickle down. As OpenID appears on more and more sites, people will look in to it, realize they have one, and then start using it. In order for OpenID - which is a great idea - to catch on, there needs to be a critical mass of users and sites supporting it.
Eventually, it will just be "the way it is", and we'll wonder why we ever created authentication code for every single website we made, or why we would create a unique identity everywhere we went on the Web
A: As discussed in one of the podcasts, it adds a barrier to entry to the wanderer happening by wondering if this might be where they should post their Yahoo! Answers question.
It's somewhat elitist, but given the focus of this website in particular it is fairly acceptable to turn away any who can't figure out the Open ID process, and anyone who really has a real question they need answered can be bothered to work through any slight hardship.
A: From my experience with OpenID, I see a number of significant upsides :
If you choose to log in with your trusted OpenID provider, eg. Verisign PIP+VIP you can enjoy the benefit of out of band SecureID authentication mechanisms. This should be seen as the major benefit the outweighs ALL others. You are no longer trusting whatever crappy form based authentication is on the site you access, you are trusting Verisign VIP or whatever your choice of OpenID provider may be.
Internet rabbit hole? Sounds like bad implementation and I for one do not know what you are referring to.
You cannot steal authentication detail easily, it can be made closer to impossible than what we already have! You may be able to trick to me into thinking I am contacting my provider, but Verisign for one has an option to not allow or accept redirections. I see these phishing issues as something trivial also, especially again if you weigh it against the benefits of out of band authentication mechanisms that you can gain through your OpenID authentication provider. So say you phished RSA key detail one time, it would not be valid the next time or maybe just totally useless if you were to say use a browser certificate.
In conclusion, OpenID is just the evolution of the current system, an Email address to verify against. If your email account is your current single point of failure then yes, your OpenID could be your new single point of failure in the case where the OpenID you control is no longer under your control. So, if you trust only your email server then simply host your own OpenID URL. If you trust Gmail, use a gmail URL for your OpenID because by the same token, you already trust Gmail as your SSO as your gmail account can ultimately retrieve your account passwords.
It's a no brainer, but I can see that some people may have difficulty understanding the basic concepts of authentication mechanisms. If I CAN login with my SecureID card (via my OpenID provider) to a site that I have an account on, I WOULD. So if it was the only option, I'll take it!
A: Adds critical point to failure to the site
That critical point of failure could be the confirmation email you send out, but the user's mailbox is a) unavailable due to a typo, b) full or c) provider is 'down'.
Takes a user to another sites content and every time they logon to your site
I can see that, but IMHO - this is not so bad. I mean, Y! seems to be one of the most cluttered logins and it also never works for me. ;) Aside, most OpenID providers don't look so bad (yet).
Also, keep your audience in mind. If mom and pop are your users, OpenID is probably confusing as hell. But so is probably a lot on the Internet. In SO's case, the people are somewhat savvy users and know what they want.
Adds a non-trial amount of time to the signup
This is a non-issue. Look at the list of providers:
http://openid.net/get/
So many people have at least a Yahoo! account, so if it actually worked. It wouldn't be so bad. I agree though that if a user doesn't have OpenID, and doesn't know what it's for. It's not so easy to educate them.
And think about the implication - "to register for site A, you need to register at site B". And we all know that registering per se is a pain in the ass. But in the long run, this is also exactly what OpenID tries to address.
In mainstream, I currently see no value for making OpenID mandatory. I like it as an add-on though. Just how people provide links to "login with your Facebook", etc.. Then people who don't get it (or don't care) don't need to bother. But others can still use it.
A: One thing to mention also. You already have a userbase with OpenID, they just need to login.
A: OpenID may be the greatest thing since sliced bread, but I have been given no reason to trust "them" with my identity - other than Jeff Atwood/Joel Spolsky made me do it in order to be here complaining about it ;-)
A: I am in favour of OpenID, mainly from an ease of use perspective. I remain to be convinced about it's safety, but it has a lot of potential. There are lots of things that could be said on this, but I just wanted to respond to the following two points:
Adds a non-trivial amount of time to
the signup
Only the first time it's setup. Also, with companies like Yahoo providing support now, many people won't even have to bother setting up an OpenID if they don't want to. If you used Google or someone similar as your OpenID provider, would you see them as inherently insecure? And how often would you expect them to have downtime?
It is a Phisher's Dream
I do accept that this might be partly true. But is phishing not more of a social problem than a technological one? OpenID could make it easier, but that doesn't eliminate the fact that the real problem is the user. It's far more important to make users aware of how phishers operate than trying to safe guard them through technology.
A: At least OpenID sends you to your OpenID provider to login.
I was reading a blog on blogspot and there is a link to follow this blog (presumably tell me when there are newposts) to do this it pops up a box asking for my Gmail username and password.
Even assuming that this is genuine and not a phishing site - they now (potentailly) have the login to my Gmail, my Google documents, my Google applications - everything!
A: The main benefit of having an OpenID will be seen in the long term. Instead of having to apply to different sites for an identity, you do that once and then use it on all the sites that require a unique identity. Of course for secure sites like banking and trading it will need a different kind of thinking altogether. But for social networking sites and the like you can use it easily.
Mom and Dad will find it easy too because now they have to remember only one username/password. A lot of times it gets hard for us to remember what login we have at which site, and end up using the correct username/password of Site A on Site B. OpenID will solve that. Plus it's a good revenue model for an OpenID provider and user. I can enter to one such provider all the details I am willing to give and every such detail I give I can earn money.
Maybe the provider can coax me to tell it more about myself using that as an incentive, which it can then sell to the sites I register with. So Site A pays OpenID for my information. OpenID then passes a cut of that on to me. Site A doesn't have to manage users, OpenID gets money, user gets money, everybody is happy :)
This way you won't have to make OpenID mandatory. People themselves will want it. OpenID providers will then compete amongst themselves to provide better services, and where there is competition there will be better value provided to all concerned. I think it's a fabulous idea.
Edit:
Regarding downtimes at one particular provider; if OpenID provider A is not confident of providing 100% uptime, it can take the help of another provider B, and the user on Provider A can choose from the options provider A gives. The site which goes to provider A to authenticate a user will know which other providers to go to in case provider A is not working. This will be stored in its database on first login automatically.
Anybody want to brainstorm the implementation details ? :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
} |
Q: access $(this) with href="javascript:..." in jQuery I am using jQuery. I call a JavaScript function with next html:
<li><span><a href="javascript:uncheckEl('tagVO-$id')">$tagname</a></span></li>
I would like to remove the li element and I thought this would be easy with the $(this) object. This is my JavaScript function:
function uncheckEl(id) {
$("#"+id+"").attr("checked","");
$("#"+id+"").parent("li").css("color","black");
$(this).parent("li").remove(); // This is not working
retrieveItems();
}
But $(this) is undefined. Any ideas?
A: Try something like this (e.g. to hide the <li>):
function unCheckEl(id, ref) {
(...)
$(ref).parent().parent().hide(); // this should be your <li>
}
And your link:
<a href="javascript:uncheckEl('tagVO-$id', \$(this))">
$(this) is not present inside your function, because how is it supposed to know where the action is called from? You pass no reference in it, so $(this) could refer to everything but the <a>.
A: Why not something like:
<li id="uncheck_tagVO-$id">$tagname</li>
and
$('li').click( function() {
var id = this.id.split("_")[1];
$('#'+id).attr("checked","").parent("li").css("color","black");
$(this).remove();
retrieveItems();
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Windows Mobile development in Python What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?
A: Python CE
Python port for Windows CE (Pocket PC) devices. Intended to be as close to desktop version as possible (console, current directory support, testsuite passed).
(source: sourceforge.net)
A: (I used to write customer apps for Windows Mobile.)
Forget about python. Even if it's technically possible:
*
*your app will be big (you'll have to bundle the whole python runtime with your app)
*your app will use lots of memory (python is a memory hog, relative to C/C++)
*your app will be slow
*you wont find any documentation or discussion groups to help you when you (inevitably) encounter problems
Go with C/C++ (or C#). Visual Studio 2005/2008 have decent tools for those (SDK for winmo built-in, debugging on the emulator or device connected through USB), the best documentation is for those technologies plus there are active forums/discussion groups/mailing lists where you can ask for help.
A: If the IronPython and .Net Compact Framework teams work together, Visual Studio may one day support Python for Windows Mobile development out-of-the-box. Unfortunately, this feature request has been sitting on their issue tracker for ages...
A: Just found this: http://ejr44.blogspot.com/2008/05/python-for-windows-mobile-cab.html
Looks like a complete set of .CAB files to provide Python on Windows Mobile.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Take a screenshot of a webpage with JavaScript? Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server?
I'm not so concerned with browser security issues. etc. as the implementation would be for HTA. But is it possible?
A: This might not be the ideal solution for you, but it might still be worth mentioning.
Snapsie is an open source, ActiveX object that enables Internet Explorer screenshots to be captured and saved. Once the DLL file is registered on the client, you should be able to capture the screenshot and upload the file to the server withing JavaScript. Drawbacks: it needs to register the DLL file at the client and works only with Internet Explorer.
A: We had a similar requirement for reporting bugs. Since it was for an intranet scenario, we were able to use browser addons (like Fireshot for Firefox and IE Screenshot for Internet Explorer).
A: This question is old but maybe there's still someone interested in a state-of-the-art answer:
You can use getDisplayMedia:
https://github.com/ondras/browsershot
A: I have done this for an HTA by using an ActiveX control. It was pretty easy to build the control in VB6 to take the screenshot. I had to use the keybd_event API call because SendKeys can't do PrintScreen. Here's the code for that:
Declare Sub keybd_event Lib "user32" _
(ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Public Const CaptWindow = 2
Public Sub ScreenGrab()
keybd_event &H12, 0, 0, 0
keybd_event &H2C, CaptWindow, 0, 0
keybd_event &H2C, CaptWindow, &H2, 0
keybd_event &H12, 0, &H2, 0
End Sub
That only gets you as far as getting the window to the clipboard.
Another option, if the window you want a screenshot of is an HTA would be to just use an XMLHTTPRequest to send the DOM nodes to the server, then create the screenshots server-side.
A: The SnapEngage uses a Java applet (1.5+) to make a browser screenshot. AFAIK, java.awt.Robot should do the job - the user has just to permit the applet to do it (once).
And I have just found a post about it:
*
*Stack Overflow question JavaScript code to take a screenshot of a website without using ActiveX
*Blog post How SnapABug works – and what they should do
A: I found that dom-to-image did a good job (much better than html2canvas). See the following question & answer: https://stackoverflow.com/a/32776834/207981
This question asks about submitting this back to the server, which should be possible, but if you're looking to download the image(s) you'll want to combine it with FileSaver.js, and if you want to download a zip with multiple image files all generated client-side take a look at jszip.
A: You can achieve that using HTA and VBScript. Just call an external tool to do the screenshotting. I forgot what the name is, but on Windows Vista there is a tool to do screenshots. You don't even need an extra install for it.
As for as automatic - it totally depends on the tool you use. If it has an API, I am sure you can trigger the screenshot and saving process through a couple of Visual Basic calls without the user knowing that you did what you did.
Since you mentioned HTA, I am assuming you are on Windows and (probably) know your environment (e.g. OS and version) very well.
A: If you are willing to do it on the server side, there are options like PhantomJS, which is now deprecated. The best way to go would be Headless Chrome with something like Puppeteer on Node.JS. Capturing a web page using Puppeteer would be as simple as follows:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'example.png'});
await browser.close();
})();
However it requires headless chrome to be able to run on your servers, which has some dependencies and might not be suitable on restricted environments. (Also, if you are not using Node.JS, you might need to handle installation / launching of browsers yourself.)
If you are willing to use a SaaS service, there are many options such as
*
*Restpack
*UrlBox
*Screenshot Layer
A: Another possible solution that I've discovered is http://www.phantomjs.org/ which allows one to very easily take screenshots of pages and a whole lot more. Whilst my original requirements for this question aren't valid any more (different job), I will likely integrate PhantomJS into future projects.
A: Google is doing this in Google+ and a talented developer reverse engineered it and produced http://html2canvas.hertzen.com/ . To work in IE you'll need a canvas support library such as http://excanvas.sourceforge.net/
A: Pounder's if this is possible to do by setting the whole body elements into a canvase then using canvas2image ?
http://www.nihilogic.dk/labs/canvas2image/
A: A possible way to do this, if running on windows and have .NET installed you can do:
public Bitmap GenerateScreenshot(string url)
{
// This method gets a screenshot of the webpage
// rendered at its full size (height and width)
return GenerateScreenshot(url, -1, -1);
}
public Bitmap GenerateScreenshot(string url, int width, int height)
{
// Load the webpage into a WebBrowser control
WebBrowser wb = new WebBrowser();
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(url);
while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }
// Set the size of the WebBrowser control
wb.Width = width;
wb.Height = height;
if (width == -1)
{
// Take Screenshot of the web pages full width
wb.Width = wb.Document.Body.ScrollRectangle.Width;
}
if (height == -1)
{
// Take Screenshot of the web pages full height
wb.Height = wb.Document.Body.ScrollRectangle.Height;
}
// Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.Dispose();
return bitmap;
}
And then via PHP you can do:
exec("CreateScreenShot.exe -url http://.... -save C:/shots domain_page.png");
Then you have the screenshot in the server side.
A: A great solution for screenshot taking in Javascript is the one by https://grabz.it.
They have a flexible and simple-to-use screenshot API which can be used by any type of JS application.
If you want to try it, at first you should get the authorization app key + secret and the free SDK
Then, in your app, the implementation steps would be:
// include the grabzit.min.js library in the web page you want the capture to appear
<script src="grabzit.min.js"></script>
//use the key and the secret to login, capture the url
<script>
GrabzIt("KEY", "SECRET").ConvertURL("http://www.google.com").Create();
</script>
Screenshot could be customized with different parameters. For example:
GrabzIt("KEY", "SECRET").ConvertURL("http://www.google.com",
{"width": 400, "height": 400, "format": "png", "delay", 10000}).Create();
</script>
That's all.
Then simply wait a short while and the image will automatically appear at the bottom of the page, without you needing to reload the page.
There are other functionalities to the screenshot mechanism which you can explore here.
It's also possible to save the screenshot locally. For that you will need to utilize GrabzIt server side API. For more info check the detailed guide here.
A: As of today Apr 2020 GitHub library html2Canvas
https://github.com/niklasvh/html2canvas
GitHub 20K stars | Azure pipeles : Succeeded | Downloads 1.3M/mo |
quote : " JavaScript HTML renderer The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.
A: I made a simple function that uses rasterizeHTML to build a svg and/or an image with page contents.
Check it out :
https://github.com/orisha/tdg-screen-shooter-pure-js
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "152"
} |
Q: DynamicPopulateExtender ,TextArea and line feeds I have this in a page :
<textarea id="taEditableContent" runat="server" rows="5"></textarea>
<ajaxToolkit:DynamicPopulateExtender ID="dpeEditPopulate" runat="server" TargetControlID="taEditableContent"
ClearContentsDuringUpdate="true" PopulateTriggerControlID="hLink" ServicePath="/Content.asmx"
ServiceMethod="EditContent" ContextKey='<%=ContextKey %>' />
Basically, a DynamicPopulateExtender that fills the contents of a textarea from a webservice. Problem is, no matter how I return the line breaks, the text in the text area will have no line feeds.
If I return the newlines as "br/" the entire text area remains empty. If I return new lines as "/r/n" , I get all the text as one continous line. The webservice returns the string correctly:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://rprealm.com/">First line
Third line
Fourth line</string>
But what I get in the text area is :
First line Third line Fourth line
A: The problem is that the white space is ignored by default when the XML is processed. Try to add the xml:space="preserve" attribute to the string element. You'll also need to define the xml prefix as xmlns:xml="http://www.w3.org/XML/1998/namespace".
A: Try to add the following style on textarea: style="white-space: pre"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatically get own phone number in Symbian How to get the phone number of the device in Symbian?
A: According to the GSM specs, only the IMSI is required to be available on the SIM card.
The actual phone number MSISDN is stored on the HLR database in the operator's network and does not need to be available on the SIM card or transmitted to the phone.
So no matter what technology you are using (Symbina, Java ...) you can never count on being able to consistently get your own phone number from the device or SIM. You might be lucky if the operator stores it on the SIM or if the phone provides the user with a possibility to enter it manually, but it does not have to be this way.
A: As Pat has said, although there are APIs for accessing the "own number" slot on the SIM, rarely in my experience is this slot filled.
The usual strategy for obtaining the phone number for a connected application is to send an SMS as part of a verification process. Either:
*
*Programatically send an SMS from the handset to your server (lots of good SMS gateway interconnect providers out there). The SMS will arrive at your server 'from' the number of the handset (or the SIM to be more correct). Of course the SMS should contain some token so the server can link it with a given session/user.
This has the advantage that you don't need the user to enter their own phone number (which is fraut with subtle difficulties given few folks understand how to format numbers in E.164 format). One disadvantage is that the process can cost your user money (one SMS).
*Have the user enter their phone number (web site or on the handset) and connect to your server, passing that phone number. Have the handset then wait for an SMS to arrive that you send from your server. If this SMS does indeed arrive, you have verified the phone number they entered as correct and valid. Obvious disadvantage is that this relies on the user to enter their number correctly - again, given the plethora of ways of writing phone numbers around the world, its not as trivial as it sounds to normalise numbers to E.164....
Alas, neither of these methods are bullet-proof, particularly because SMS is an unconnected transport. Depending on GSM network load, the load of your gateway provider, phase of the moon and direction of window blowing an SMS can take a second to a month to arrive (yes, I do have experience of the latter). The mean delivery time is often in the seconds, but you do have to play with the operation timeout and might have to tweak it on a geographical and GSM network basis.
[And no, don't rely on delivery reports - even more unreliable than SMS delivery]
A: FYI: Actually i have found this.
http://www3.symbian.com/faq.nsf/AllByDate/100335073FFD8FEF80256E3200571A49?OpenDocument
But the fact is, the phone number is not always stored in SIM. The operator chooses to do it or not!
A: You can't. Afaik.
Check this discussion:
http://discussion.forum.nokia.com/forum/showthread.php?t=65117
A: It is not generally possible to get the MSISDN from a Symbian device (or BREW, or any other platform). We've tried.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Changing the default folder in Emacs I am fairly new to Emacs and I have been trying to figure out how to change the default folder for C-x C-f on start-up. For instance when I first load Emacs and hit C-x C-f its default folder is C:\emacs\emacs-21.3\bin, but I would rather it be the desktop. I believe there is some way to customize the .emacs file to do this, but I am still unsure what that is.
Update: There are three solutions to the problem that I found to work, however I believe solution 3 is Windows only.
*
*Solution 1: Add (cd "C:/Users/Name/Desktop") to the .emacs file
*Solution 2: Add (setq default-directory "C:/Documents and Settings/USER_NAME/Desktop/") to the .emacs file
*Solution 3: Right click the Emacs short cut, hit properties and change the start in field to the desired directory.
A: You didn't say so, but it sounds like you're starting Emacs from a Windows shortcut.
The directory that you see with c-x c-f is the cwd, in Emacs terms, the default-directory (a variable).
When you start Emacs using an MS Windows shortcut, the default-directory is initially the folder (directory) specified in the "Start In" field of the shortcut properties. Right click the shortcut, select Properties, and type the path to your desktop in the Start In field.
If you're using Emacs from the command line, default-directory starts as the directory where you started Emacs (the cwd).
This approach is better than editing your .emacs file, since it will allow you to have more than one shortcuts with more than one starting directory, and it lets you have the normal command line behavior of Emacs if you need it.
CWD = current working directory = PWD = present working directory. It makes a lot more sense at the command line than in a GUI.
A: The default folder is actually the same as the current working folder for the buffer, i.e. it can be different for every file you work with. Say that the file you are working with is located in C:\dir_a, then the working directory for that buffer will by default be C:\dir_a. You can change this with M-x cd and type in whatever directory you would like to be the default instead (and by default I mean the one that will show up when you do C-x C-f).
If you start emacs without opening a file, you will end up with the *scratch* buffer open. If you started emacs from a Windows shortcut, the working directory will be the same as that specified in the shortcut properties. If you started it from the command line, it will be the directory from where you started it. You can still change this default directory with M-x cd, also from the *scratch* buffer.
Finally, you can do as Vadim suggests and put
(cd "c:/dir_a/")
in your .emacs file, to make that directory the default no matter how you start emacs.
A: I think the line you need to add to your .emacs is is
(setq default-directory "C:/Documents and Settings/USER NAME/Desktop/" )
Emacs will start in your desktop that way, unless you have a file open. It will usually start in the same directory as the file in your current buffer otherwise.
A: As you're on Windows you can do it with a shortcut.
Create a shortcut to C:\emacs\emacs-21.3\bin\runemacs.exe. Edit the properties of the shortcut and change the value of Start In: to be whatever you want your default directory to be.
A: I am using emacs 22.2.1 under Windows XP and have been helped by the answers above to get the response in the minibuffer I want to the command C-x C-f. Initially I was getting
"Find file: C:\Program Files\emacs\bin/" like Anton.
I have HOME set to "C:\Documents and settings\USER NAME\My Documents".
The response to C-x C-f I want in the minibuffer is "Find file: ~/".
By adding (setq default-directory "C:/Documents and Settings/USER NAME/My Documents") to my .emacs file I was able to get the response "Find file: C:\Documents and settings\USER NAME\My Documents/" which is functionally the same as "Find file: ~/".
However, I noticed one further point. "Customize Emacs" under "Options" allowed me to inhibit the startup screen. Now when I open emacs I go immediately to the scratch buffer. When I type C-x C-f in the scratch buffer I get the exact response I want.
A: You can type the 'cd' emacs command. ( M-x cd ) to change the default folder as a one off.
A: I've put
(cd "c:/cvsroot/")
in my .emacs and it did the job
A: I have added to my shortcut (in Gnome, Linux) a pramater which is a blank dummy file name, and I specify the directory. Since my emacs defaults to "home" I simply say:
/Desktop/blank_file
and that opens a file called "blank_file"
That also moves the current working directory for that emacs session to the desktop.
If I happen to put stuff in "blank_file" then save it, of course, I've got that stuff saved. Which might be an annoyance or it might be a good thing, depending!
A: To change default directory to DESKTOP in Dired and shell put this in your ~/.emacs:
;;This works for Windows XP.
(setq default-directory (concat "C:\Documents and Settings\MY_ACCOUNT\DESKTOP\"))
A: For windows users, the best way that I found is to create the shortcut for runemacs.exe and placing the shortcut in the root directory of my notes folder.
This way, when you use this shortcut to open emacs, it will by default open in the root directory without having to specifically set the Start In property (you can leave the Start In property blank).
Reference: According to Microsoft, if you leave the 'Start In' box empty, the script will run in the current working directory
TIP:
Additionally, if you have organized your notes into multiple root folders (Personal, Work etc...), you can copy multiple such shortcuts in each folder to open various instances of emacs with their own default directories.
A: In Windows 8, it works to create a shortcut in the Desktop and change the property 'Start In:' for the shortcut.
Now, I ran the program emacs-23.3\bin\addpm.exe as recommended, and the Windows-8 screen (that horrendous invention from Microsoft) it appeared an icon-link to Emacs. But there you have to change again the property 'Start In'. (It is different from the one in the desktop).
Just right-click, choose in the bottom bar 'Open the file location' (or similar, I did it in my language), and you are taken to the folder with a new shortcut, in which you can (must) also change the property 'Start In:'.
A little involved, but in fact very easy.
A: Since the most annoying thing is having windows Emacs dump you into system32 when you are just using the shortcut, but want every other case to work, just use a bit of elisp...
(when (string< "C:\WINDOWS\system32" default-directory) (setq default-directory "~/"))
So it will only default to your home directory when you end up in system. The only drawback is if you really want to start emacs in system32...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "119"
} |
Q: Loading Java classes from a signed applet If I'm running a signed Java applet. Can I load additional classes from remote sources, in the same domain or maybe even the same host, and run them?
I'd like to do this without changing pages or even stopping the current applet. Of course, the total size of all classes is too large to load them all at once.
Is there a way to do this? And is there a way to do this with signed applets and preserve their "confidence" status?
A: I think classes are lazy loaded in applets. being loaded on demand.
Anyway, if the classes are outside of a jar you can simply use the applet classloader and load them by name. Ex:
ClassLoader loader = this.getClass().getClassLoader();
Class clazz = loader.loadClass("acme.AppletAddon");
If you want to load classes from a jar I think you will need to create a new instance of URLClassLoader with the url(s) of the jar(s).
URL[] urls = new URL[]{new URL("http://localhost:8080/addon.jar")};
URLClassLoader loader = URLClassLoader.newInstance(urls,this.getClass().getClassLoader());
Class clazz = loader.loadClass("acme.AppletAddon");
By default, applets are forbidden to create new classloaders. But if you sign your applet and include permission to create new classloaders you can do it.
A: Yes, you can open URL connections to the host you ran your applet from. You can either create a classloader with HTTP urls, or download the classes (as jars) to the user's machine and create a classloader with those jars in the classpath. The applet won't stop and you don't need to load another page.
Regarding the second part of your question about confidence, once the user has granted access to your applet it can download anything, yes anything, it wants to the local machine. You can probably inform the user as to what it's doing, if your UI design permits this.
Hope this helps.
A: Sounds like it should be possible (but I've never done it). Have you already had a look at Remote Method Invocation (RMI)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Using the DLR for (primarily) static language compilation I'm building a compiler that targets .NET and I've previously generated CIL directly, but generating DLR trees will make my life a fair amount easier. I'm supporting a few dynamic features, namely runtime function creation and ducktyping, but the vast majority of the code is completely static.
So now that that's been explained, I have the following questions:
*
*Has the DLR been used for static compilation, outside of small examples on MSDN blogs?
*If so, what sort of performance was achieved?
*If not, is there anything fundamentally preventing this?
*Are there any better mechanisms of generating code than either using the DLR or emitting IL directly?
Any insight into this or references to blogs/code/talks would be greatly appreciated.
A: I'm not aware of anyone using the DLR in quite this fashion yet, though this is definitely one of its intended use cases. One interesting thing to consider is that the DLR's expression trees have been merged with LINQ expression trees, so the IL being produced for LINQ in some as-yet-unannounced future version of Visual Studio will be using the DLR code.
A neat aspect of releasing the DLR as open source is that we have no idea what kinds of interesting things people outside the company might be doing with it :).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Getting started with REST I am looking for some good links with best practices and sample code on creating RESTful web services using .NET.
Also, any other input you might have regarding REST would be greatly appreciated.
A: Windows Communication Foundation supports REST model since .NET 3.5.
You can find documentation and code samples on MSDN:
REST and POX
Some resources to learn REST:
*
*REST documentation on xFront.com
*Architectural Styles and the Design
of Network-based Software
Architectures. Chapter 5:
Representational State Transfer
(REST) (Ph.D dissertation of Roy Fielding - author of REST)
*Wikipedia entry
A: The best introduction I have read is the RESTful Web Services book, which goes beyond explaining the model and principles and actually shows you how to design a RESTful web service. Most useful is its checklist for how to write/specify an REST API:
*
*Figure out the data set [i.e. specify the data model].
*Split the data set into resources. For each kind of resource:
*Name the resources with URIs.
*Expose a subset of the uniform interface [i.e. specify which HTTP methods are used and what they do].
*Design the representations(s) accepted from the client [e.g. the XML format you can PUT or POST].
*Design the representations(s) served to the client [e.g. the XML you get back].
*Integrate this resource into existing resources, using hypermedia links and forms.
*Consider the typical course of events: what's supposed to happen? [This is like a use case main success scenario.]
*Consider error conditions. [This is like use case exception scenarios.]
A: "A very clear article on how to make a web service more RESTful using delicious"
A: The articles from the "RESTful Web" series at xml.com are a great
introduction.
The author (Joe Gregorio, of The Atom Publishing Protocol fame) also
regularly publishes insightful articles about all things REST on his
weblog. "RESTify DayTrader" (REST
Architecture applied to a benchmark stock trading application) is a good starting point. I also like "Why so many Python web frameworks?", which shows the implementation of a small restful web framework in Python.
A: ADO.Net Data Servcies makes it really easy to build and consume RESTful web services in the .Net world but nevertheless understanding the concepts is important. Compared to WCF (which added REST support later), ADO.Net Data Services was built primarily for REST.
Guidelines for Building RESTful Web Services has all the info on the resources you need.
This is another useful blog entry:
The uniform interface constraints describe how a service built for the Web can be a good participant in the Web architecture. These constraints are described briefly as follows :
1) Identification of resources: A resource is any information item that can be named and represented (e.g. a document, a stock price at a given point in time, the current weather in Las Vegas, etc). Resources in your service should be identified using URIs.
2) Manipulation of resources via representations: A representation is the physical representation of a resource and should correspond to a valid media type. Using standard media types as the data formats behind your service increases the reach of your service by making it accessible to a wide range of potential clients. Interaction with the resource should be based on retrieval and manipulation of the representation of the resource identified by its URI.
3)Self-descriptive messages: Following the principles of statelessness in your service's interactions, using standard media types and correctly indicating the cacheability of messages via HTTP method usage and control headers ensures that messages are self descriptive. Self descriptive messages make it possible for messages to be processed by intermediaries between the client and server without impacting either.
4)Hypermedia as the engine of application state: Application state should be expressed using URIs and hyperlinks to transition between states. This is probably the most controversial and least understood of the architectural constraints set forth in Roy Fielding's dissertation. In fact, Fielding's dissertation contains an explicit arguments against using HTTP cookies for representing application state to hammer this point home yet it is often ignored.
A: When I began developing REST web services I read REST API Design Rulebook from Mark Masse. Once you know the basics and the theory, you will be able to implement REST with WCF, HTTPListener or ServiceStack. All these frameworks are .NET and quite good documented...
I would recommend to you service stack (http://www.servicestack.net/) there is enough information on the web to get started.
WCF offers the ASP.NET web API, it is OK, but I don't use it.
In any case, there is no good REST framework today, you have to choose one that you find easy to use and then apply the theory that you learned from the book.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Self Testing Systems I had an idea I was mulling over with some colleagues. None of us knew whether or not it exists currently.
The Basic Premise is to have a system that has 100% uptime but can become more efficient dynamically.
Here is the scenario: * So we hash out a system quickly to a
specified set of interfaces, it has
zero optimizations, yet we are
confident that it is 100% stable
though (dubious, but for the sake of
this scenario please play
along) * We then profile
the original classes, and start to
program replacements for the
bottlenecks.
* The original and the replacement are initiated simultaneously and
synchronized.
* An original is allowed to run to completion: if a replacement hasn´t
completed it is vetoed by the system
as a replacement for the
original.
* A replacement must always return the same value as the original, for a
specified number of times, and for a
specific range of values, before it is
adopted as a replacement for the
original.
* If exception occurs after a replacement is adopted, the system
automatically tries the same operation
with a class which was superseded by
it.
Have you seen a similar concept in practise? Critique Please ...
Below are comments written after the initial question in regards to
posts:
* The system demonstrates a Darwinian approach to system evolution.
* The original and replacement would run in parallel not in series.
* Race-conditions are an inherent issue to multi-threaded apps and I
acknowledge them.
A: I believe this idea to be an interesting theoretical debate, but not very practical for the following reasons:
*
*To make sure the new version of the code works well, you need to have superb automatic tests, which is a goal that is very hard to achieve and one that many companies fail to develop. You can only go on with implementing the system after such automatic tests are in place.
*The whole point of this system is performance tuning, that is - a specific version of the code is replaced by a version that supersedes it in performance. For most applications today, performance is of minor importance. Meaning, the overall performance of most applications is adequate - just think about it, you probably rarely find yourself complaining that "this application is excruciatingly slow", instead you usually find yourself complaining on the lack of specific feature, stability issues, UI issues etc. Even when you do complain about slowness, it's usually an overall slowness of your system and not just a specific applications (there are exceptions, of course).
*For applications or modules where performance is a big issue, the way to improve them is usually to identify the bottlenecks, write a new version and test is independently of the system first, using some kind of benchmarking. Benchmarking the new version of the entire application might also be necessary of course, but in general I think this process would only take place a very small number of times (following the 20%-80% rule). Doing this process "manually" in these cases is probably easier and more cost-effective than the described system.
*What happens when you add features, fix non-performance related bugs etc.? You don't get any benefit from the system.
*Running the two versions in conjunction to compare their performance has far more problems than you might think - not only you might have race conditions, but if the input is not an appropriate benchmark, you might get the wrong result (e.g. if you get loads of small data packets and that is in 90% of the time the input is large data packets). Furthermore, it might just be impossible (for example, if the actual code changes the data, you can't run them in conjunction).
The only "environment" where this sounds useful and actually "a must" is a "genetic" system that generates new versions of the code by itself, but that's a whole different story and not really widely applicable...
A: A system that runs performance benchmarks while operating is going to be slower than one that doesn't. If the goal is to optimise speed, why wouldn't you benchmark independently and import the fastest routines once they are proven to be faster?
And your idea of starting routines simultaneously could introduce race conditions.
Also, if a goal is to ensure 100% uptime you would not want to introduce untested routines since they might generate uncatchable exceptions.
Perhaps your ideas have merit as a harness for benchmarking rather than an operational system?
A: Have I seen a similar concept in practice? No. But I'll propose an approach anyway.
It seems like most of your objectives would be meet by some sort of super source control system, which could be implemented with CruiseControl.
CruiseControl can run unit tests to ensure correctness of the new version.
You'd have to write a CruiseControl builder pluggin that would execute the new version of your system against a series of existing benchmarks to ensure that the new version is an improvement.
If the CruiseControl build loop passes, then the new version would be accepted. Such a process would take considerable effort to implement, but I think it feasible. The unit tests and benchmark builder would have to be pretty slick.
A: I think an Inversion of Control Container like OSGi or Spring could do most of what you are talking about. (dynamic loading by name)
You could build on top of their stuff. Then implement your code to
*
*divide work units into discrete modules / classes (strategy pattern)
*identify each module by unique name and associate a capability with it
*when a module is requested it is requested by capability and at random one of the modules with that capability is used.
*keep performance stats (get system tick before and after execution and store the result)
*if an exception occurs mark that module as do not use and log the exception.
If the modules do their work by message passing you can store the message until the operation completes successfully and redo with another module if an exception occurs.
A: For design ideas for high availability systems, check out Erlang.
A: I don't think code will learn to be better, by itself. However, some runtime parameters can easily adjust onto optimal values, but that would be just regular programming, right?
About the on-the-fly change, I've shared the wondering and would be building it on top of Lua, or similar dynamic language. One could have parts that are loaded, and if they are replaced, reloaded into use. No rocket science in that, either. If the "old code" is still running, it's perfectly all right, since unlike with DLL's, the file is needed only when reading it in, not while executing code that came from there.
Usefulness? Naa...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What's the best way to write JavaScript/Ruby applications on Windows Mobile device? I recently bought a Windows Mobile device and since I'm a developer I want to use it as a development platform. Yes, it's not supposed to be used like that but it's always with me and my laptop isn't. I know cke is a good editor for code but how can I run JavaScript/Ruby code without too much of a headache?
I probably could write a web application, send code to it and get the results back but maybe there's better solutions?
A: There is a possibility to run Ruby on Windows Mobile
Check this article for steps: Human vs Machine
Javascript is bit crippled on Windows Mobile.
Follow up the discussions here: Windows Mobile IE Team Blog
Hopefully the next version if Pocket Internet Explorer supports better!
A: I'm not sure if you're interested, but there's only a port of Python for CE.
http://pythonce.sourceforge.net/
A: You can also use etcl from Evolane (http://www.evolane.com/software/etcl).
It comes with console.
A: This is n old port of Ruby to WinCE, but from what I've read it doesn't work all that well - who knows, give it a try, YMMV
http://uema2.s8.xrea.com/ruby-mswince/
As for Javascript, WinMo devices have Pocket Internet Explorer - it isn't very good, but runs some Javascript. If you want something that is a bit closer to a desktop you could install Opera.
A: I've had a Windows Mobile phone for just over a month and would also like to run code on it. Unfortunately it's such a limited platform with hardly any community support. It seems to me that the only decent choices are Python, NSBASIC and PPL
For Javascript, you'll be better off using Opera, opposed to Pocket Internet Explorer.
As for cke, I found CEdit a more stable editor but you do have to pay for it. Though I don't think there is any editor that does syntax highlighting for Ruby on Window Mobile.
A: Rhomobile's open source framework Rhodes (www.rhomobile.com) works great on Windows Mobile.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: C++ function pointers and classes Say I have:
void Render(void(*Call)())
{
D3dDevice->BeginScene();
Call();
D3dDevice->EndScene();
D3dDevice->Present(0,0,0,0);
}
This is fine as long as the function I want to use to render is a function or a static member function:
Render(MainMenuRender);
Render(MainMenu::Render);
However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g.
Render(MainMenu->Render);
However I really have no idea how to do this, and still allow functions and static member functions to be used.
A: You can make a wrapper function void Wrap(T *t) that just calls t->Call() and have Render take such a function together with an object. That is:
void Wrap(T *t)
{
t->Call();
}
void Render(void (*f)(T *), T *t)
{
...
f(t);
...
}
A: What about what C++ FAQ: Pointers to members says?
A: There are a lot of ways to skin this cat, including templates. My favorite is Boost.function as I've found it to be the most flexible in the long run. Also read up on Boost.bind for binding to member functions as well as many other tricks.
It would look like this:
#include <boost/bind.hpp>
#include <boost/function.hpp>
void Render(boost::function0<void> Call)
{
// as before...
}
Render(boost::bind(&MainMenu::Render, myMainMenuInstance));
A: I did so once by defining a global function "Call" which accepts a pointer to your intance as member
void CallRender(myclass *Instance)
{
Instance->Render();
}
So render becomes:
void Render(void (*Call)(myclass*), myclass* Instance)
{
...
Call(Instance);
...
}
And your call to render is:
Render(CallRender, &MainMenu);
I know it's ugly, but worked for me (I was using pthreads)
A: You can't call a member function from a pointer unless you have a reference to the object as well. For example:
((object).*(ptrToMember))
So you won't be able to acheive this without changing the signature of your render method. This article explains why this is generally a bad idea.
A better way might be to define a "Renderer" interface which your classes that have render methods can implement and have that be the parameter type of your main Render method. You could then write a "StaticCaller" implementation to support the calling of your static methods by reference.
eg (My C++ is really rusty, I haven't compiled this either).
void Render(IRenderer *Renderer)
{
D3dDevice->BeginScene();
Renderer->Render();
D3dDevice->EndScene();
D3dDevice->Present(0,0,0,0);
}
// The "interface"
public class IRenderer
{
public:
virtual void Render();
};
public class StaticCaller: public IRenderer
{
void (*Call)();
public:
StaticCaller((*Call)())
{
this->Call = Call;
}
void Render()
{
Call();
}
};
All this is pretty boilerplate but it should make for more readability.
A: You can declare a function pointer to a member function of class T using:
typedef void (T::*FUNCTIONPOINTERTYPE)(args..)
FUNCTIONPOINTERTYPE function;
And invoke it as:
T* t;
FUNCTIONPOINTERTYPE function;
(t->*function)(args..);
Extrapolating this into useful currying system with variable arguments, types, return values, etc, is monotonous and annoying. I've heard good things about the aforementioned boost library, so I'd recommend looking into that before doing anything drastic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Where to put master page's code in an MVC application? I'm using a few (2 or 3) master pages in my ASP.NET MVC application and they must each display bits of information from the database. Such as a list of sponsors, current fundings status etc.
So my question was, where should I put these master-page database calling code?
Normally, these should goes into its own controller class right? But then that'd mean I'd have to wire them up manually (e.g. passing ViewDatas) since it is out of the normal routing framework provided by the MVC framework.
Is there a way to this cleanly without wiring ViewData passing/Action calls to master pages manually or subclassing the frameworks'?
The amount of documentation is very low... and I'm very new to all this including the concepts of MVC itself so please share your tips/techniques on this.
A: One way to do this is to put in the masterpage view the hook for the ViewData and then you define a BaseController : Controller (or multiple base classes) where you do all the db calls you need.
What you wanna do is quite the same thing described in this articles.
I hope this helps!
Regards
A: Great question. You have several options available to you.
*
*Have a jQuery call on your masterpage that grabs the data you need from a controller and then populate your fields using jQuery again.
*Your second option is to create user controls that make their own calls to the controller to populate their information.
I think the best choice is creating controls for the region of your masterpage that has data that needs to be populated. Thus leaving your masterpage to strictly contain design elements. Good luck.
A: If you don't mind strongly typed view data, you can put all the master page data in a common base class for viewData. You can set this data in the base class's constructor. All your views requiring additional data will then need strongly typed viewdata that inherits from this base class.
To allow a call to View() in your controllers without any explicit viewdata you can override View in your ControllerBase:
protected override ViewResult View(string viewName, string masterName, object model)
{
if (model == null)
{
model = new ViewDataBase();
}
return base.View(viewName, masterName, model);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What are the problems of using transactions in a database? From this post. One obvious problem is scalability/performance. What are the other problems that transactions use will provoke?
Could you say there are two sets of problems, one for long running transactions and one for short running ones? If yes, how would you define them?
EDIT: Deadlock is another problem, but data inconsistency might be worse, depending on the application domain. Assuming a transaction-worthy domain (banking, to use the canonical example), deadlock possibility is more like a cost to pay for ensuring data consistency, rather than a problem with transactions use, or you would disagree? If so, what other solutions would you use to ensure data consistency which are deadlock free?
A: You can get deadlocks even without using explicit transactions. For one thing, most relational databases will apply an implicit transaction to each statement you execute.
Deadlocks are fundamentally caused by acquiring multiple locks, and any activity that involves acquiring more than one lock can deadlock with any other activity that involves acquiring at least two of the same locks as the first activity. In a database transaction, some of the acquired locks may be held longer than they would otherwise be held -- to the end of the transaction, in fact. The longer locks are held, the greater the chance for a deadlock. This is why a longer-running transaction has a greater chance of deadlock than a shorter one.
A: It depends a lot on the transactional implementation inside your database and may also depend on the transaction isolation level you use. I'm assuming "repeatable read" or higher here. Holding transactions open for a long time (even ones which haven't modified anything) forces the database to hold on to deleted or updated rows of frequently-changing tables (just in case you decide to read them) which could otherwise be thrown away.
Also, rolling back transactions can be really expensive. I know that in MySQL's InnoDB engine, rolling back a big transaction can take FAR longer than committing it (we've seen a rollback take 30 minutes).
Another problem is to do with database connection state. In a distributed, fault-tolerant application, you can't ever really know what state a database connection is in. Stateful database connections can't be maintained easily as they could fail at any moment (the application needs to remember what it was in the middle of doing it and redo it). Stateless ones can just be reconnected and have the (atomic) command re-issued without (in most cases) breaking state.
A: One issue with transactions is that it's possible (unlikely, but possible) to get deadlocks in the DB. You do have to understand how your database works, locks, transacts, etc in order to debug these interesting/frustrating problems.
-Adam
A: I think the major issue is at the design level. At what level or levels within my application do I utilise transactions.
For example I could:
*
*Create transactions within stored procedures,
*Use the data access API (ADO.NET) to control transactions
*Use some form of implicit rollback higher in the application
*A distributed transaction in (via DTC / COM+).
Using more then one of these levels in the same application often seems to create performance and/or data integrity issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Smoothing Zedgraph linegraphs without 'bumps' When you use Zedgraph for linegraphs and set IsSmooth to true, the lines are nicely curved instead of having hard corners/angles.
While this looks much better for most graphs -in my humble opinion- there is a small catch. The smoothing algorithm makes the line take a little 'dive' or 'bump' before going upwards or downwards.
In most cases, if the datapoint are themselves smooth, this isn't a problem, but if your datapoints go from say 0 to 15, the 'dive' makes the line go under the x-axis, which makes it seems as though there are some datapoints below zero (which is not the case).
How can I fix this (prefably easily ;)
A: No simple answer for this. Keeping the tension near zero will be your simplest solution.
ZedGraph uses GDI's DrawCurve tension parameter to apply smoothness, which is probably Hermite Interpolation. You can try to implement your own Cosine Interpolation, which will keep local extremes because of its nature. You can look at the this link to see why:
http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/
EDIT: Website is down. Here is a cached version of the page:
http://web.archive.org/web/20090920093601/http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/
A: You could try to alter the myCurve.Line.SmoothTension property up or down and see if that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C (or any) compilers deterministic performance Whilst working on a recent project, I was visited by a customer QA representitive, who asked me a question that I hadn't really considered before:
How do you know that the compiler you are using generates machine code that matches the c code's functionality exactly and that the compiler is fully deterministic?
To this question I had absolutely no reply as I have always taken the compiler for granted. It takes in code and spews out machine code. How can I go about and test that the compiler isn't actually adding functionality that I haven't asked it for? or even more dangerously implementing code in a slightly different manner to that which I expect?
I am aware that this is perhapse not really an issue for everyone, and indeed the answer might just be... "you're over a barrel and deal with it". However, when working in an embedded environment, you trust your compiler implicitly. How can I prove to myself and QA that I am right in doing so?
A: You know by testing. When you test, you're testing your both code and the compiler.
You will find that the odds that you or the compiler writer have made an error are much smaller than the odds that you would make an error if you wrote the program in question in some assembly language.
A: There are compiler validation suits available.
The one I remember is "Perennial".
When I worked on a C compiler for a embedded SOC processor we had to validate the compiler against this and two other validation suits (that I forget the name of). Validating the compiler to a certain level of conformance to these test suits was part of the contract.
A: It all boils down to trust. Does your customer trust any compiler? Use that, or at least compare output code between yours and theirs.
If they don't trust any, is there a reference implementation for the language? Could you convince them to trust it? Then compare yours against the reference or use the reference.
This all assuming you actually verify the actual code you get from the vendor/provider and that you check the compiler has not been tampered with, which should be the first step.
Anyhow this still leaves the question about how would you verify, without having references, a compiler, from scratch. That certainly looks like a ton of work and requires a definition of the language, which not always is available, sometimes the definition is the compiler.
A:
How do you know that the compiler you are using generates machine code that matches the c code's functionality exactly and that the compiler is fully deterministic?
You don't, that's why you test the resultant binary, and why you make sure to ship the same binary you tested with. And why when you make 'minor' software changes, you regression test to make sure none of the old functionality broke.
The only software I've certified is avionics. FAA certification isn't rigorous enough to prove the software works correctly, while at the same time it does force you to jump through a certain amount of hoops. The trick is to structure your 'process' so it improves quality as much as possible, with as little extraneous hoop-jumping as you can get away with. So anything that you know is worthless and won't actually find bugs, you can probably weasel out of. And anything you know you should do because it will find bugs that isn't explicitly asked for by the FAA, your best bet is to twist words until it sounds like you're giving the FAA/your QA people what they asked for.
This actually isn't as dishonest as I've made it sound, in general the FAA cares more about you being conscientious and confident that you're trying to do a good job, than about what exactly you do.
A: Some intellectual ammunition might be found in Crosstalk, a magazine for defense software engineers. This question is the kind of thing they spend many waking hours on. http://www.stsc.hill.af.mil/crosstalk/2006/08/index.html (If i can find my old notes from an old project, i'll be back here...)
A: You can never fully trust the compiler, even highly recommended ones. They could release an update that has a bug, and your code compiles the same. This problem is compounded when updating old code with the buggy compiler, doing testing and shipping out the goods only to have the customer ring you 3 months later with a problem.
It all comes back to testing, and if there is one thing I have learnt it is to thouroughly test after any non-trivial change. If the problem seems impossible to find have a look at the compiled assembler and check it's doing what it should be doing.
On several occasions I have found bugs in the compiler. One time there was a bug where 16 bit variables would get incremented but without carry and only if the 16 bit variable was part of an extern struct defined in a header file.
A: You don't know for sure that the compiler will do exactly what you expect. The reason is, of course, that a compiler is a peice of software, and is therefore susceptible to bugs.
Compiler writers have the advantage of working from a high quality spec, while the rest of us have to figure out what we're making as we go along. However, compiler specs also have bugs, and complex parts with subtle interactions. So, it's not exactly trivial to figure out what the compiler should be doing.
Still, once you decide what you think the language spec means, you can write a good, fast, automated test for every nuance. This is where compiler writing has a huge advantage over writing other kinds of software: in testing. Every bug becomes an automated test case, and the test suite can very thorough. Compiler vendors have a lot more budget to invest in verifying the correctness of the compiler than you do (you already have a day job, right?).
What does this mean for you? It means that you need to be open to the possibilities of bugs in your compiler, but chances are you won't find any yourself.
I would pick a compiler vendor that is not likely to go out of business any time soon, that has a history of high quality in their compilers, and that has demonstrated their ability to service (patch) their products. Compilers seem to get more correct over time, so I'd choose one that's been around a decade or two.
Focus your attention on getting your code right. If it's clear and simple, then when you do hit a compiler bug, you won't have to think really hard to decide where the problem lies. Write good unit tests, which will ensure that your code does what you expect it to do.
A:
...you trust your compiler implicitly
You'll stop doing that the first time you come across a compiler bug. ;-)
But ultimately this is what testing is for. It doesn't matter to your test regime how the bug got in to your product in the first place, all that matters is that it didn't pass your extensive testing regime.
A: Well.. you can't simply say that you trust your compiler's output - particularly if you work with embedded code. It is not hard to find discrepancies between the code generated when compiling the very same code with different compilers. This is the case because the C standard itself is too loose. Many details can be implemented differently by different compilers without breaking the standard. How do we deal with this stuff? We avoid compiler dependent constructs whenever possible. We may deal with it by choosing a safer subset of C like Misra-C as previously mentioned by the user cschol. I seldom have to inspect the code generated by the compiler but that has also happened to me at times. But, ultimately, you are relying on your tests in order to make sure that the code behaves as intended.
Is there a better option out there? Some people claim that there is. The other option is to write your code in SPARK/Ada. I have never written code in SPARK but my understanding is that you would still have to link it against routines written in C that would deal with the "bare metal" stuff. The beauty of SPARK/Ada is that you are absolutely guaranteed that the code generated by any compiler is always going to be the same. No ambiguity whatsoever. On top of that, the language allows you to annotate the code with explanations as to how the code is intended to behave. The SPARK toolset will use these annotations to formally prove that the code written does indeed do what the annotations have described. So I have been told that for critical systems, SPARK/Ada is a pretty good bet. I have never tried it myself though.
A: You can apply that argument at any level: do you trust the third party libraries? do you trust the OS? do you trust the processor?
A good example of why this may be a valid concern of course, is how Ken Thompson put a backdoor into the original 'login' program ... and modified the C compiler so that even if you recompiled login you still got the backdoor. See this posting for more details.
Similar questions have been raised about encryption algorithms -- how do we know there isn't a backdoor in DES for the NSA to snoop through?
At the end of the you have to decide if you trust the infrastructure you are building on enough to not worry about it, otherwise you have to start developing your own silicon chips!
A: For safety critical embedded application certifying agencies require to satisfy the "proven-in-use" requirement for the compiler. There are typically certain requirements (kind of like "hours of operation") that need to be met and proven by detailed documentation. However, most people either cannot or don't want to meet these requirements because it can be very difficult especially on your first project with a new target/compiler.
One other approach is basically to NOT trust the compiler's output at all. Any compiler and even language-dependent (Appendix G of the C-90 standard, anyone?) deficiencies need to be covered by a strict set of static analysis, unit- and coverage testing in addition to the later functional testing.
A standard like MISRA-C can help to restrict the input to the compiler to a "safe" subset of the C language. Another approach is to restrict the input to a compiler to a subset of a language and test what the output for the entire subset is. If our application is only built of components from the subset it is assumed to be known what the output of the compiler will be. The usually goes by "qualification of the compiler".
The goal of all of this is to be able to answer the QA representative's question with "We don't just rely on determinism of the compiler but this is the way we prove it...".
A: Try unit testing.
If that's not enough, use different compilers and compare the results of your unit tests. Compare strace outputs, run your tests in a VM, keep a log of disk and network I/O, then compare those.
Or propose to write your own compiler and tell them what it's going to cost.
A: The most you can easily certify is that you are using an untampered compiler from provider X. If they do not trust provider X, it's their problem (if X is reasonably trustworthy). If they do not trust any compiler provider, then they are totally unreasonable.
Answering their question: I make sure I'm using an untampered compiler from X through these means. X is well reputed, plus I have a nice set of tests that show our application behaves as expected.
Everything else is starting to open the can of worms. You have to stop somewhere, as Rob says.
A: Sometimes you do get behavioural changes when you request aggressive levels of optimisation.
And optimisation and floating point numbers? Forget it!
A: For most software development (think desktop applications) the answer is probably that you don't know and don't care.
In safety-critical systems (think nuclear power plants and commercial avionics) you do care and regulatory agencies will require you to prove it. In my experience, you can do this one of two ways:
*
*Use a qualified compiler, where "qualified" means that it has been verified according to the standards set out by the regulatory agency.
*Perform object code analysis. Essentially, you compile a piece of reference code and then manually analyze the output to demonstrate that the compiler has not inserted any instructions that can't be traced back to your source code.
A: You get the one Dijkstra wrote.
A: Select a formally verified compiler, like Compcert C compiler.
A: *
*Changing the optimization level of the compiler will change the output.
*Slight changes to a function may make the compiler inline or no longer inline a function.
*Changes to the compiler (gcc versions for example) may change the output
*Certain library functions may be instrinic (i.e., emit optimized assembly) while others most are not.
The good news is that for most things it really doesn't matter that much. Where it does, you may want to consider assembly if it really matters (e.g., in an ISR).
A: If you are concerned about unexpected machine code which doesn't produce visible results, the only way is probably to contact compiler vendor for certification of some sort which will satisfy your customer.
Otherwise you'll know it the same you know about bugs in your code - testing.
Machine code from modern compilers can be vastly different and totally incomprehensible for puny humans.
A: I think it's possible to reduce this problem to the Halting Problem somehow.
The most obvious problem is that if you use some kind of program to analyze the compiler and its determinism, how do you know that your program gets compiled correctly, and produces the correct result?
If you're using another, "safe" compiler though, I'm not sure. What I'm sure is writing a compiler from scratch would probably be an easier job.
A: Even a qualified or certified compiler can produce undesirable results. Keep your code simple and test, test, test. That or walk through the machine code by hand while not allowing any human error. PLus the operating system or whatever environment you are running on (preferably no operating system, just your program).
This problem has been solved in mission critical environments since software and compilers began. As many of the others who have responded also know. Each industry has its own rules from certified compilers to programming style (you must always program this way, never use this or that or the other), lots of testing and peer review. Verifying every execution path, etc.
If you are not in one of those industries, then you get what you get. A commercial program on a COTS operating system on COTS hardware. It will fail, that is a guarantee.
A: If your worried about malicious bugs in the compiler, one recommendation (IIRC, an NSA requirement for some projects) is that the compiler binary predate the writing of the code. At least then you know that no one has added bugs targeted at your program.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Terminal emulation in Flex I need to do some emulation of some old DOS or mainframe terminals in Flex. Something like the image below for example.
The different coloured text is easy enough, but the ability to do different background colours, such as the yellow background is beyond the capabilities of the standard Flash text.
I may also need to be able to enter text at certain places and scroll text up the "terminal". Any idea how I'd attack this? Or better still, any existing code/components for this sort of thing?
A: Use TextField.getCharBoundaries to get a rectangle of the first and last characters in the areas where you want a background. From these rectangles you can construct a rectangle that spans the whole area. Use this to draw the background in a Shape placed behind the text field, or in the parent of the text field.
Update you asked for an example, here is how to get a rectangle from a range of characters:
var firstCharBounds : Rectangle = textField.getCharBoundaries(firstCharIndex);
var lastCharBounds : Rectangle = textField.getCharBoundaries(lastCharIndex);
var rangeBounds : Rectangle = new Rectangle();
rangeBounds.topLeft = firstCharBounds.topLeft;
rangeBounds.bottomRight = lastCharBounds.bottomRight;
If you want to find a rectangle for a whole line you can do this instead:
var charBounds : Rectangle = textField.getCharBoundaries(textField.getLineOffset(lineNumber));
var lineBounds : Rectangle = new Rectangle(0, charBounds.y, textField.width, firstCharBounds.height);
When you have the bounds of the text range you want to paint a background for, you can do this in the updateDisplayList method of the parent of the text field (assuming the text field is positioned at [0, 0] and has white text, and that textRangesWithYellowBackground is an array of rectangles that represent the text ranges that should have yellow backgrounds):
graphics.clear();
// this draws the black background
graphics.beginFill(0x000000);
graphics.drawRect(0, 0, textField.width, textField.height);
graphics.endFill();
// this draws yellow text backgrounds
for each ( var r : Rectangle in textRangesWithYellowBackground )
graphics.beginFill(0xFFFF00);
graphics.drawRect(r.x, r.y, r.width, r.height);
graphics.endFill();
}
A: The font is fixed width and height, so making a background bitmap dynamically isn't difficult, and is probably the quickest and easiest solution. In fact, if you size it correctly there will only be one stretched pixel per character.
Color the pixel (or pixels) according to the background of the character.
-Adam
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to run executable at end of Setup Project? I have a Visual Studio Setup Project that I use to install a fairly simple WinForms application. At the end of the install I have a custom user interface page that shows a single check box which asks the user if they want to run the application. I've seen other installers do this quite often. But I cannot find a way to get the Setup Project to run an executable after the install finishes. An ideas?
NOTE: You cannot use Custom Actions because these are used as part of the install process, I want to run my installed application once the user presses the 'Close' button at the end of the install.
A: I believe this is one of the real limitations of the Visual Studio installation project. You need to be able to modify the last page of the installation UI but VS.NET does not give you a way to do this. You could modify the tables in the .MSI after it has been built but VS.NET would probably overwrite these changes each time it is built. You may be able to override the last page using a merge module that you include in the installation project. Either way you will need to become familiar with how the UI dialogs are authored in an .MSI and this is not trivial.
You may want to consider switching to a free script based installer or buy a commercial setup authoring application (just don't buy InstallShield for the love of Pete). Take a look at InstallAware (although I have not used it).
A: I've just found a very easy way which does not require external tools. You only have to add a class file to the main project and a custom action to the setup project.
http://www.codeproject.com/KB/install/Installation.aspx
A: You also can use custom actions
A: I've done this for internal apps by creating a VB Script harness that launches the setup executable, waits for it to close, and then launches the second program.
You could also accomplish this with a little more polish using a few Win API calls in a C executable.
A: You can use MSILAUNCH (though I've only got it to work with MSICREATE).
http://www.cornerhouse.ca/en/msi.html
A: I managed it by doing invoking the Main method the assembly using the following line:
(typeof(ClassWithinAssemblyToExecute)).Assembly.EntryPoint.Invoke(null, new Object[] {} )
A: you can do it by custom installer. just add installer class and there u will see many event like after install, before install. just hook up after install and from there run ur exe by process class. i would suggest u google to find more about custom installer.
here is one good link that might help u http://www.codeproject.com/Articles/19560/Launching-Your-Application-After-Install-using-Vis
thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: How do I create an in-memory handle in Haskell? I want something that looks like a file handle but is really backed by an in-memory buffer to use for I/O redirects. How can I do this?
A: If you can express what you want to do in terms of C or system calls you could use Haskell's Foreign Function Interface (FFI). I started to suggest using mmap, but on second thought I think mmap might be a mapping the wrong way even if you used it with the anonymous option.
You can find more information about the Haskell FFI at the haskell.org wiki.
A: I just wrote a library which provides this, called "knob" [hackage]. You can use it to create Handles which reference/modify a ByteString:
import Data.ByteString (pack)
import Data.Knob
import System.IO
main = do
knob <- newKnob (pack [])
h <- newFileHandle knob "test.txt" WriteMode
hPutStrLn h "Hello world!"
hClose h
bytes <- Data.Knob.getContents knob
putStrLn ("Wrote bytes: " ++ show bytes)
A: This is actually a bug in the library design, and one that's annoyed me, too. I see two approaches to doing what you want, neither of which is terribly attractive.
*
*Create a new typeclass, make the current handle an instance of it, write another instance to do the in-memory-data thing, and change all of your programs that need to use this facility. Possibly this is as simple as importing System.SIO (or whatever you want to call it) instead of System.IO. But if you use the custom I/O routines in libraries such as Data.ByteString, there's more work to be done there.
*Rewrite the I/O libraries to extend them to support this. Not trivial, and a lot of work, but it wouldn't be particularly difficult work to do. However, then you've got a compatibility issue with systems that don't have this library.
A: This may not be possible. GHC, at least, seems to require a handle to have an OS file descriptor that is used for all read/write/seek operations.
See /libraries/base/IOBase.lhs from the GHC sources.
You may be able to get the same effect by enlisting the OS's help: create a temporary file, connect the handle to it and then memory map the file for the I/O redirects. This way, all the handle I/O would become visible in the memory mapped section.
A: To add a modern answer to this question, you could use createPipe from System.Process:
createPipe :: IO (Handle, Handle)
https://www.stackage.org/haddock/lts-10.3/process-1.6.1.0/System-Process.html#v:createPipe
A: It's not possible without modifying the compiler. This is because Handle is an abstract data type, not a typeclass.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Why should the "PIMPL" idiom be used? Backgrounder:
The PIMPL Idiom (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.
This hides internal implementation details and data from the user of the library.
When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?
To illustrate, this code puts the Purr() implementation on the impl class and wraps it as well.
Why not implement Purr directly on the public class?
// header file:
class Cat {
private:
class CatImpl; // Not defined here
CatImpl *cat_; // Handle
public:
Cat(); // Constructor
~Cat(); // Destructor
// Other operations...
Purr();
};
// CPP file:
#include "cat.h"
class Cat::CatImpl {
Purr();
... // The actual implementation can be anything
};
Cat::Cat() {
cat_ = new CatImpl;
}
Cat::~Cat() {
delete cat_;
}
Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
printf("purrrrrr");
}
A: I think most people refer to this as the Handle Body idiom. See James Coplien's book Advanced C++ Programming Styles and Idioms. It's also known as the Cheshire Cat because of Lewis Caroll's character that fades away until only the grin remains.
The example code should be distributed across two sets of source files. Then only Cat.h is the file that is shipped with the product.
CatImpl.h is included by Cat.cpp and CatImpl.cpp contains the implementation for CatImpl::Purr(). This won't be visible to the public using your product.
Basically the idea is to hide as much as possible of the implementation from prying eyes.
This is most useful where you have a commercial product that is shipped as a series of libraries that are accessed via an API that the customer's code is compiled against and linked to.
We did this with the rewrite of IONA's Orbix 3.3 product in 2000.
As mentioned by others, using his technique completely decouples the implementation from the interface of the object. Then you won't have to recompile everything that uses Cat if you just want to change the implementation of Purr().
This technique is used in a methodology called design by contract.
A: Typically, the only reference to a PIMPL class in the header for the owner class (Cat in this case) would be a forward declaration, as you have done here, because that can greatly reduce the dependencies.
For example, if your PIMPL class has ComplicatedClass as a member (and not just a pointer or reference to it) then you would need to have ComplicatedClass fully defined before its use. In practice, this means including file "ComplicatedClass.h" (which will also indirectly include anything ComplicatedClass depends on). This can lead to a single header fill pulling in lots and lots of stuff, which is bad for managing your dependencies (and your compile times).
When you use the PIMPL idiom, you only need to #include the stuff used in the public interface of your owner type (which would be Cat here). Which makes things better for people using your library, and means you don't need to worry about people depending on some internal part of your library - either by mistake, or because they want to do something you don't allow, so they #define private public before including your files.
If it's a simple class, there's usually isn't any reason to use a PIMPL, but for times when the types are quite big, it can be a big help (especially in avoiding long build times).
A: *
*Because you want Purr() to be able to use private members of CatImpl. Cat::Purr() would not be allowed such an access without a friend declaration.
*Because you then don't mix responsibilities: one class implements, one class forwards.
A: Well, I wouldn't use it. I have a better alternative:
File foo.h
class Foo {
public:
virtual ~Foo() { }
virtual void someMethod() = 0;
// This "replaces" the constructor
static Foo *create();
}
File foo.cpp
namespace {
class FooImpl: virtual public Foo {
public:
void someMethod() {
//....
}
};
}
Foo *Foo::create() {
return new FooImpl;
}
Does this pattern have a name?
As someone who is also a Python and Java programmer, I like this a lot more than the PIMPL idiom.
A: Placing the call to the impl->Purr inside the .cpp file means that in the future you could do something completely different without having to change the header file.
Maybe next year they discover a helper method they could have called instead and so they can change the code to call that directly and not use impl->Purr at all. (Yes, they could achieve the same thing by updating the actual impl::Purr method as well, but in that case you are stuck with an extra function call that achieves nothing but calling the next function in turn.)
It also means the header only has definitions and does not have any implementation which makes for a cleaner separation, which is the whole point of the idiom.
A: We use the PIMPL idiom in order to emulate aspect-oriented programming where pre, post and error aspects are called before and after the execution of a member function.
struct Omg{
void purr(){ cout<< "purr\n"; }
};
struct Lol{
Omg* omg;
/*...*/
void purr(){ try{ pre(); omg-> purr(); post(); }catch(...){ error(); } }
};
We also use a pointer-to-base class to share different aspects between many classes.
The drawback of this approach is that the library user has to take into account all the aspects that are going to be executed, but only sees his/her class. It requires browsing the documentation for any side effects.
A: For what is worth, it separates the implementation from the interface. This is usually not very important in small size projects. But, in large projects and libraries, it can be used to reduce the build times significantly.
Consider that the implementation of Cat may include many headers, may involve template meta-programming which takes time to compile on its own. Why should a user, who just wants to use the Cat have to include all that? Hence, all the necessary files are hidden using the pimpl idiom (hence the forward declaration of CatImpl), and using the interface does not force the user to include them.
I'm developing a library for nonlinear optimization (read "lots of nasty math"), which is implemented in templates, so most of the code is in headers. It takes about five minutes to compile (on a decent multi-core CPU), and just parsing the headers in an otherwise empty .cpp takes about a minute. So anyone using the library has to wait a couple of minutes every time they compile their code, which makes the development quite tedious. However, by hiding the implementation and the headers, one just includes a simple interface file, which compiles instantly.
It does not necessarily have anything to do with protecting the implementation from being copied by other companies - which wouldn't probably happen anyway, unless the inner workings of your algorithm can be guessed from the definitions of the member variables (if so, it is probably not very complicated and not worth protecting in the first place).
A: If your class uses the PIMPL idiom, you can avoid changing the header file on the public class.
This allows you to add/remove methods to the PIMPL class, without modifying the external class's header file. You can also add/remove #includes to the PIMPL too.
When you change the external class's header file, you have to recompile everything that #includes it (and if any of those are header files, you have to recompile everything that #includes them, and so on).
A: I just implemented my first PIMPL class over the last couple of days. I used it to eliminate problems I was having, including file *winsock2.*h in Borland Builder. It seemed to be screwing up struct alignment and since I had socket things in the class private data, those problems were spreading to any .cpp file that included the header.
By using PIMPL, winsock2.h was included in only one .cpp file where I could put a lid on the problem and not worry that it would come back to bite me.
To answer the original question, the advantage I found in forwarding the calls to the PIMPL class was that the PIMPL class is the same as what your original class would have been before you pimpl'd it, plus your implementations aren't spread over two classes in some weird fashion. It's much clearer to implement the public members to simply forward to the PIMPL class.
Like Mr Nodet said, one class, one responsibility.
A: I don't know if this is a difference worth mentioning but...
Would it be possible to have the implementation in its own namespace and have a public wrapper / library namespace for the code the user sees:
catlib::Cat::Purr(){ cat_->Purr(); }
cat::Cat::Purr(){
printf("purrrrrr");
}
This way all library code can make use of the cat namespace and as the need to expose a class to the user arises a wrapper could be created in the catlib namespace.
A: I find it telling that, in spite of how well-known the PIMPL idiom is, I don't see it crop up very often in real life (e.g., in open source projects).
I often wonder if the "benefits" are overblown; yes, you can make some of your implementation details even more hidden, and yes, you can change your implementation without changing the header, but it's not obvious that these are big advantages in reality.
That is to say, it's not clear that there's any need for your implementation to be that well hidden, and perhaps it's quite rare that people really do change only the implementation; as soon as you need to add new methods, say, you need to change the header anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "146"
} |
Q: XmlSerializer - There was an error reflecting type Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it. I am creating an XMLSerializer class and passing that into the constructor:
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
I am getting an exception saying:
There was an error reflecting type.
Inside the data class there is another composite object. Does this also need to have the [Serializable] attribute, or by having it on the top object, does it recursively apply it to all objects inside?
A: Also be aware that XmlSerializer cannot serialize abstract properties.. See my question here (which I have added the solution code to)..
XML Serialization and Inherited Types
A: Most common reasons by me:
- the object being serialized has no parameterless constructor
- the object contains Dictionary
- the object has some public Interface members
A: All the objects in the serialization graph have to be serializable.
Since XMLSerializer is a blackbox, check these links if you want to debug further into the serialization process..
Changing where XmlSerializer Outputs Temporary Assemblies
HOW TO: Debug into a .NET XmlSerializer Generated Assembly
A: If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the IXmlSerialiable interface, which will allow you more freedom at the cost of more verbose coding.
public class NetService : IXmlSerializable
{
#region Data
public string Identifier = String.Empty;
public string Name = String.Empty;
public IPAddress Address = IPAddress.None;
public int Port = 7777;
#endregion
#region IXmlSerializable Implementation
public XmlSchema GetSchema() { return (null); }
public void ReadXml(XmlReader reader)
{
// Attributes
Identifier = reader[XML_IDENTIFIER];
if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);
if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);
}
public void WriteXml(XmlWriter writer)
{
// Attributes
writer.WriteAttributeString(XML_IDENTIFIER, Identifier);
writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());
writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());
}
private const string XML_IDENTIFIER = "Id";
private const string XML_NETWORK_ADDR = "Address";
private const string XML_NETWORK_PORT = "Port";
#endregion
}
There is an interesting article, which show an elegant way to implements a sophisticated way to "extend" the XmlSerializer.
The article say:
IXmlSerializable is covered in the official documentation, but the documentation states it's not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you're willing to accept this uncertainty and deal with possible changes in the future, there's no reason whatsoever you can't take advantage of it.
Because this, I suggest to implement you're own IXmlSerializable classes, in order to avoid too much complicated implementations.
...it could be straightforward to implements our custom XmlSerializer class using reflection.
A: I just got the same error and discovered that a property of type IEnumerable<SomeClass> was the problem. It appears that IEnumerable cannot be serialized directly.
Instead, one could use List<SomeClass>.
A: Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.
You can exclude fields/properties from xml serialization by decorating them with the [XmlIgnore] attribute.
XmlSerializer does not use the [Serializable] attribute, so I doubt that is the problem.
A: I've discovered that the Dictionary class in .Net 2.0 is not serializable using XML, but serializes well when binary serialization is used.
I found a work around here.
A: I recently got this in a web reference partial class when adding a new property. The auto generated class was adding the following attributes.
[System.Xml.Serialization.XmlElementAttribute(Order = XX)]
I needed to add a similar attribute with an order one higher than the last in the auto generated sequence and this fixed it for me.
A: I had a similar problem, and it turned out that the serializer could not distinguish between 2 classes I had with the same name (one was a subclass of the other). The inner exception looked like this:
'Types BaseNamespace.Class1' and 'BaseNamespace.SubNamespace.Class1' both use the XML type name, 'Class1', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.
Where BaseNamespace.SubNamespace.Class1 is a subclass of BaseNamespace.Class1.
What I needed to do was add an attribute to one of the classes (I added to the base class):
[XmlType("BaseNamespace.Class1")]
Note: If you have more layers of classes you need to add an attribute to them as well.
A: I too thought that the Serializable attribute had to be on the object but unless I'm being a complete noob (I am in the middle of a late night coding session) the following works from the SnippetCompiler:
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Inner
{
private string _AnotherStringProperty;
public string AnotherStringProperty
{
get { return _AnotherStringProperty; }
set { _AnotherStringProperty = value; }
}
}
public class DataClass
{
private string _StringProperty;
public string StringProperty
{
get { return _StringProperty; }
set{ _StringProperty = value; }
}
private Inner _InnerObject;
public Inner InnerObject
{
get { return _InnerObject; }
set { _InnerObject = value; }
}
}
public class MyClass
{
public static void Main()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
TextWriter writer = new StreamWriter(@"c:\tmp\dataClass.xml");
DataClass clazz = new DataClass();
Inner inner = new Inner();
inner.AnotherStringProperty = "Foo2";
clazz.InnerObject = inner;
clazz.StringProperty = "foo";
serializer.Serialize(writer, clazz);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
}
I would imagine that the XmlSerializer is using reflection over the public properties.
A: Sometime, this type of error is because you dont have constructur of class without argument
A: Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.
A: I had a situation where the Order was the same for two elements in a row
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "SeriousInjuryFlag")]
.... some code ...
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "AccidentFlag")]
When I changed the code to increment the order by one for each new Property in the class, the error went away.
A: I was getting the same error when I created a property having a datatype - Type. On this, I was getting an error - There was an error reflecting type. I kept checking the 'InnerException' of every exception from the debug dock and got the specific field name (which was Type) in my case. The solution is as follows:
[XmlIgnore]
public Type Type { get; set; }
A: Also note that you cannot serialize user interface controls and that any object you want to pass onto the clipboard must be serializable otherwise it cannot be passed across to other processes.
A: I have been using the NetDataSerialiser class to serialise
my domain classes. NetDataContractSerializer Class.
The domain classes are shared between client and server.
A: [System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
Or
[XmlIgnore]
string [] strFielsName {get;set;}
A: I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable.
A: I have a slightly different solution to all described here so far, so for any future civilisation here's mine!
I had declared a datatype of "time" as the original type was a TimeSpan and subsequently changed to a String:
[System.Xml.Serialization.XmlElementAttribute(DataType="time", Order=3)]
however the actual type was a string
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
by removing the DateType property the Xml can be serialized
[System.Xml.Serialization.XmlElementAttribute(Order=3)]
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "367"
} |
Q: PHP Forms-Based Authentication on Windows using Local User Accounts I'm running PHP, Apache, and Windows. I do not have a domain setup, so I would like my website's forms-based authentication to use the local user accounts database built in to Windows (I think it's called SAM).
I know that if Active Directory is setup, you can use the PHP LDAP module to connect and authenticate in your script, but without AD there is no LDAP. What is the equivalent for standalone machines?
A: I haven't found a simple solution either. There are examples using CreateObject and the WinNT ADSI provider. But eventually they all bump into
User authentication issues with the Active Directory Service Interfaces WinNT provider. I'm not 100% sure but I guess the WSH/network connect approach has the same problem.
According to How to validate user credentials on Microsoft operating systems you should use LogonUser or SSPI.
It also saysLogonUser Win32 API does not require TCB privilege in Microsoft Windows Server 2003, however, for downlevel compatibility, this is still the best approach.
On Windows XP, it is no longer required that a process have the SE_TCB_NAME privilege in order to call LogonUser. Therefore, the simplest method to validate a user's credentials on Windows XP, is to call the LogonUser API.Therefore, if I were certain Win9x/2000 support isn't needed, I would write an extension that exposes LogonUser to php.
You might also be interested in User Authentication from NT Accounts. It uses the w32api extension, and needs a support dll ...I'd rather write that small LogonUser-extension ;-)
If that's not feasible I'd probably look into the fastcgi module for IIS and how stable it is and let the IIS handle the authentication.
edit:
I've also tried to utilize System.Security.Principal.WindowsIdentity and php's com/.net extension. But the dotnet constructor doesn't seem to allow passing parameters to the objects constructor and my "experiment" to get the assembly (and with it CreateInstance()) from GetType() has failed with an "unknown zval" error.
A: Good Question!
I've given this some thought... and I can't think of a good solution. What I can think of is a horrible horrible hack that just might work. After seeing that no one has posted an answer to this question for nearly a day, I figured a bad, but working answer would be ok.
The SAM file is off limits while the system is running. There are some DLL Injection tricks which you may be able to get working but in the end you'll just end up with password hashes and you'd have to hash the user provided passwords to match against them anyway.
What you really want is something that tries to authenticate the user against the SAM file. I think you can do this by doing something like the following.
*
*Create a File Share on the server and make it so that only accounts that you want to be able to log in as are granted access to it.
*In PHP use the system command to invoke a wsh script that: mounts the share using the username and password that the website user provides. records if it works, and then unmounts the drive if it does.
*Collect the result somehow. The result can be returned to php either on the stdout of the script, or hopefully using the return code for the script.
I know it's not pretty, but it should work.
I feel dirty :|
Edit: reason for invoking the external wsh script is that PHP doesn't allow you to use UNC paths (as far as I can remember).
A: Building a PHP extension requires a pretty large investment in terms of hard disk space. Since I already have the GCC (MinGW) environment installed, I have decided to take the performance hit of launching a process from the PHP script. The source code is below.
// Usage: logonuser.exe /user username /password password [/domain domain]
// Exit code is 0 on logon success and 1 on failure.
#include <windows.h>
int main(int argc, char *argv[]) {
HANDLE r = 0;
char *user = 0;
char *password = 0;
char *domain = 0;
int i;
for(i = 1; i < argc; i++) {
if(!strcmp(argv[i], "/user")) {
if(i + 1 < argc) {
user = argv[i + 1];
i++;
}
} else if(!strcmp(argv[i], "/domain")) {
if(i + 1 < argc) {
domain = argv[i + 1];
i++;
}
} else if(!strcmp(argv[i], "/password")) {
if(i + 1 < argc) {
password = argv[i + 1];
i++;
}
}
}
if(user && password) {
LogonUser(user, domain, password, LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, &r);
}
return r ? 0 : 1;
}
Next is the PHP source demonstrating its use.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_REQUEST['user'], $_REQUEST['password'], $_REQUEST['domain'])) {
$failure = 1;
$user = $_REQUEST['user'];
$password = $_REQUEST['password'];
$domain = $_REQUEST['domain'];
if($user && $password) {
$cmd = "logonuser.exe /user " . escapeshellarg($user) . " /password " . escapeshellarg($password);
if($domain) $cmd .= " /domain " . escapeshellarg($domain);
system($cmd, $failure);
}
if($failure) {
echo("Incorrect credentials.");
} else {
echo("Correct credentials!");
}
}
}
?>
<form action="<?php echo(htmlentities($_SERVER['PHP_SELF'])); ?>" method="post">
Username: <input type="text" name="user" value="<?php echo(htmlentities($user)); ?>" /><br />
Password: <input type="password" name="password" value="" /><br />
Domain: <input type="text" name="domain" value="<?php echo(htmlentities($domain)); ?>" /><br />
<input type="submit" value="logon" />
</form>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Best way to initiate a download? On a PHP-based web site, I want to send users a download package after they have filled out a short form. The site-initiated download should be similar to sites like download.com, which say "your download will begin in a moment."
A couple of possible approaches I know about, and browser compatibility (based on a quick test):
1) Do a window.open pointing to the new file.
- FireFox 3 blocks this.
- IE6 blocks this.
- IE7 blocks this.
2) Create an iframe pointing to the new file.
- FireFox 3 seems to think this is OK. (Maybe it's because I already accepted it once?)
- IE6 blocks this.
- IE7 blocks this.
How can I do this so that at least these three browsers will not object?
Bonus: is there a method that doesn't require browser-conditional statements?
(I believe that download.com employs both methods conditionally, but I can't get either one to work.)
Responses and Clarifications:
Q: "Why not point the current window to the file?"
A: That might work, but in this particular case, I want to show them some other content while their download starts - for example, "would you like to donate to this project?"
UPDATE: I have abandoned this approach. See my answer below for reasons.
A: I usually just have a PHP script that outputs the file directly to the browser with the appropriate Content-Type
if(file_exists($filename)) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: " . $content-type);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($filename));
readfile("$filename");
}else{
print "ERROR: the file " . basename($filename) . " could not be downloaded because it did not exist.";
}
The only disadvantage is that, since this sets the HTTP header, it has be called before you have any other output.
But you can have a link to the PHP download page and it will cause the browser to pop up a download box without messing up the content of the current page.
A: You can also do a meta refresh, which most browsers support. Download.com places one in a noscript tag.
<meta http-equiv="refresh" content="5;url=/download.php?doc=123.zip"/>
A: Update: I have decided to abandon this approach, and instead just present the user with a link to the actual file. My reasoning is this:
My initial attempts at a server-initiated download were blocked by the browser. That got me thinking: "the browser is right. How does it know that this is a legitimate download? It should block a download that isn't obviously user-initiated."
Any method that I can use for a server-initiated download could also be used by someone who wants to send malware. Therefore, downloads should only happen when the user specifically requests the file by clicking on a link for it.
You're free to disagree, and if you still want to initiate a download, hopefully this thread will help you do it.
A: One catch is that you may encounter issues with IE (version 6 in particular) if the headers are not set up "correctly".
Ensure you set the right Content-Type, but also consider setting the Cache options for IE (at least) to allow caching. If the file is one the user can open rather than save (e.g. an MS Word document) early versions of IE need to cache the file, as they hand off the "open" request to the applicable app, pointing to the file that was downloaded in the cache.
There's also a related issue, if the IE6 user's cache is full, it won't properly save the file (thus when the applicable app gets the hand off to open it, it will complain the file is corrupt.
You may also want to turn of any gzip actions on the downloads too (for IE)
IE6/IE7 both have issues with large downloads (e.g. 4.x Gigs...) not a likely scenario since IE doesn't even have a download manager, but something to be aware of.
Finally, IE6 sometimes doesn't nicely handle a download "push" if it was initiated from within a nested iframe. I'm not exactly sure what triggers the issue, but I find it is easier with IE6 to avoid this scenario.
A: Hoi!
@Nathan:
I decided to do exactly that: Have my "getfile.php" load all necessary stuff and then do a
header("Location: ./$path/$filename");
to let the browser itself and directly do whatever it thinks is correct do with the file. This even works fine in Opera with me.
But this will be a problem in environments, where no direct access to the files is allowed, in that case you will have to find a different way! (Thank Discordia my files are public PDFs!)
Best regards, Basty
A: How about changing the location to point to the new file? (e.g. by changing window.location)
A: I've always just made an iframe which points to the file.
<iframe src="/download.exe" frameborder="0" height="0" width="0"><a href="/download.exe">Click here to download.</a></iframe>
A: Regarding not pointing the current window to the download.
In my experience you can still show your "please donate" page, since downloads (as long as they send the correct headers) don't actually update the browser window.
I do this for csv exports on one of my sites, and as far as the user is concerned it just pops up a safe file window.
So i would recommend a simple meta-redirect as Soldarnal showed.
A: Just to summarise, you have 2 goals:
*
*start download process
*show user a page with a donate options
To achieve this I would do the following:
When your user submits the form, he gets the resulting page with a donate options and a text saying that his download will start in 5 seconds. And in the head section of this page you put the META code as Soldarnal said:
<meta http-equiv="refresh" content="5;url=/download.php?doc=123.zip>
And that's all.
A: <a href="normaldownload.zip" onclick="use_dhtml_or_ajax_to_display_page()">
Current page is unaffected if download is saved. Just ensure that download doesn't open in the same window (proper MIME type or Content-Disposition) and you'll be able to show anything.
See more complete answer
A: You can use Javascript/jQuery to initiate the download. Here's an example - you can get rid of the Ajax request and just use the setTimeout() block.
$("btnDownloadCSV").on('click', function() {
$.ajax({
url: "php_backend/get_download_url",
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: {somedata: "somedata"},
success: function(data) {
// If iFrame already exists, remove it.
if($("[id^='iframeTempCSV_"]).length) {
$("[id^='iframeTempCSV_"]).remove();
}
setTimeout(function() {
// If I'm creating an iframe with the same id, it will permit download only the first time.
// So randHashId appended to ID to trick the browser.
var randHashId = Math.random().toString(36).substr(2);
// Create a fresh iFrame for auto-downloading CSV
$('<iframe id="iframeTempCSV_'+randHashId+'" style="display:none;" src="'+data.filepath+'"></iframe>').appendTo('body');
}, 1000);
},
error: function(xhr, textStatus, errorThrown) {
console.error("Error downloading...");
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: In PHP5, should I use Exceptions or trigger_error/set_error_handler? What are the pros/cons of doing either way. Is there One Right Way(tm) ?
A: You should use exceptions in "Exceptional circumstances", that is when you call a method doFoo() you should expect it to perform, if for some reason doFoo is unable to do it's job then it should raise an exception.
A lot of old php code would take the approach of returning false or null when a failure has occured, but this makes things hard to debug, exceptions make this debugging much easier.
For example say you had a method called getDogFood() which returned an array of DogFood objects, if you called this method and it returns null when something goes wrong how will your calling code be able to tell whether null was returned because there was an error or there is just no dog food available?
Regarding dealing with legacy code libraries that use php's inbuilt error logging, you can override the error logging with the set_error_handler() function, which you could use to then rethrow a generic Exception.
Now that you have all of your code throwing detailed exceptions, you are free to decide what to do with them, in some parts of your code you may wish to catch them and try alternative methods or you can log them using your own logging functions which might log to a database, file, email - whichever you prefer. In short - Exceptions are more flexible .
A: I love the idea of using exceptions, but I often have third party libraries involved, and then if they don't use exceptions you end up with 3-4 different approaches to the problem! Zend uses exceptions. CakePHP uses a custom error handler, and most PEAR libraries use the PEAR::Error object.
I which there WAS one true way in this regard. The custom error handlers route is probably the most flexible in this situation. Exceptions are a great idea though if you're either only using your own code, or using libraries that use them.
Unfortunately in the PHP world we're still suffering from the refusal to die of PHP4, so things like exceptions, while they may represent best practise have been incredibly slow to catch on while everyone is still writing things to be able to work in both 4 and 5. Hopefully this debacle is now ending, though by the time it does, we'll have tensions between 6 and 5 instead...
/me holds head in hands...
A: It depends on the situation. I tend to use Exceptions when I am writing business logic/application internals, and trigger_error for Validator's and things of that sort.
The pro's of using Exceptions at the logic level is to allow your application to do in case of such an error. You allow the application to chose instead of having the business logic know how to present the error.
The pro's of using trigger_error for Validator's and things of that nature are, say,
try {
$user->login();
} catch (AuthenticationFailureException $e) {
set_error_handler("my_login_form_handler");
trigger_error("User could not be logged in. Please check username and password and try again!");
} catch (PersistenceException $pe) { // database unavailable
set_error_handler("my_login_form_handler");
trigger_error("Internal system error. Please contact the administrator.");
}
where my_login_form_handler pretties up the string and places the element in a visible area above the login form.
A: The idea of exception is elegant and makes the error handling process so smooth. but this only applies when you have appropriate exception classes and in team development, one more important thing is "standard" exceptions. so if you plan to use exceptions, you'd better first standardize your exception types, or the better choice is to use exceptions from some popular framework. one other thing that applies to PHP (where you can write your code object orienter combined with structural code), is that if you are writing your whole application using classes. If you are writing object oriented, then exceptions are better for sure. after all I think your error handling process will be much smoother with exception than trigger_error and stuff.
A: Obviously, there's no "One Right Way", but there's a multitude of opinions on this one. ;)
Personally i use trigger_error for things the exceptions cannot do, namely notices and warnings (i.e. stuff you want to get logged, but not stop the flow of the application in the same way that errors/exceptions do (even if you catch them at some level)).
I also mostly use exceptions for conditions that are assumed to be non-recoverable (to the caller of the method in which the exception occurs), i.e. serious errors. I don't use exceptions as an alternative to returning a value with the same meaning, if that's possible in a non-convoluted way. For example, if I create a lookup method, I usually return a null value if it didn't find whatever it was looking for instead of throwing an EntityNotFoundException (or equivalent).
So my rule of thumb is this:
*
*As long as not finding something is a reasonable result, I find it much easier returning and checking for null-values (or some other default value) than handling it using a try-catch-clause.
*If, on the other hand, not finding it is a serious error that's not within the scope of the caller to recover from, I'd still throw an exception.
The reason for throwing exceptions in the latter case (as opposed to triggering errors), is that exceptions are much more expressive, given that you use properly named Exception subclasses. I find that using PHP's Standard Library's exceptions is a good starting point when deciding what exceptions to use: http://www.php.net/~helly/php/ext/spl/classException.html
You might want to extend them to get more semantically correct exceptions for your particular case, however.
A: Intro
In my personal experience, as a general rule, I prefer to use Exceptions in my code instead of trigger_error. This is mainly because using Exceptions is more flexible than triggering errors. And, IMHO, this is also beneficial not only for myself as for the 3rd party developer.
*
*I can extend the Exception class (or use exception codes) to explicitly differentiate the states of my library. This helps me and 3rd party developers in handling and debugging the code. This also exposes where and why it can fail without the need for source code browsing.
*I can effectively halt the execution of my Library without halting the execution of the script.
*The 3rd party developer can chain my Exceptions (in PHP > 5.3.*) Very useful for debugging and might be handy in handling situations where my library can fail due to disparate reasons.
And I can do all this without imposing how he should handle my library failures. (ie: creating complex error handling functions). He can use a try catch block or just use an generic exception handler
Note:
Some of these points, in essence, are also valid for trigger_error, just a bit more complex to implement. Try catch blocks are really easy to use and very code friendly.
Example
I think this is an example might illustrate my point of view:
class HTMLParser {
protected $doc;
protected $source = null;
public $parsedHtml;
protected $parseErrors = array();
public function __construct($doc) {
if (!$doc instanceof DOMDocument) {
// My Object is unusable without a valid DOMDOcument object
// so I throw a CriticalException
throw new CriticalException("Could not create Object Foo. You must pass a valid DOMDOcument object as parameter in the constructor");
}
$this->doc = $doc;
}
public function setSource($source) {
if (!is_string($source)) {
// I expect $source to be a string but was passed something else so I throw an exception
throw new InvalidArgumentException("I expected a string but got " . gettype($source) . " instead");
}
$this->source = trim($source);
return $this;
}
public function parse() {
if (is_null($this->source) || $this->source == '') {
throw new EmptyStringException("Source is empty");
}
libxml_use_internal_errors(true);
$this->doc->loadHTML($this->source);
$this->parsedHtml = $this->doc->saveHTML();
$errors = libxml_get_errors();
if (count($errors) > 0) {
$this->parseErrors = $errors;
throw new HtmlParsingException($errors[0]->message,$errors[0]->code,null,
$errors[0]->level,$errors[0]->column,$errors[0]->file,$errors[0]->line);
}
return $this;
}
public function getParseErrors() {
return $this->parseErrors;
}
public function getDOMObj() {
return clone $this->doc;
}
}
Explanation
In the constructor I throw a CriticalException if the param passed is not of type DOMDocument because without it my library will not work at all.
(Note: I could simply write __construct(DOMDocument $doc) but this is just an example).
In setsource() method I throw a InvalidArgumentException if the param passed is something other than a string. I prefer to halt the library execution here because source property is an essential property of my class and an invalid value will propagate the error throughout my library.
The parse() method is usually the last method invoked in the cycle. Even though I throw a XmlParsingException if libXML finds a malformed document, the parsing is completed first and the results usable (to an extent).
Handling the example library
Here's an example how to handle this made up library:
$source = file_get_contents('http://www.somehost.com/some_page.html');
try {
$parser = new HTMLParser(new DOMDocument());
$parser->setSource($source)
->parse();
} catch (CriticalException $e) {
// Library failed miserably, no recover is possible for it.
// In this case, it's prorably my fault because I didn't pass
// a DOMDocument object.
print 'Sorry. I made a mistake. Please send me feedback!';
} catch (InvalidArgumentException $e) {
// the source passed is not a string, again probably my fault.
// But I have a working parser object.
// Maybe I can try again by typecasting the argument to string
var_dump($parser);
} catch (EmptyStringException $e) {
// The source string was empty. Maybe there was an error
// retrieving the HTML? Maybe the remote server is down?
// Maybe the website does not exist anymore? In this case,
// it isn't my fault it failed. Maybe I can use a cached
// version?
var_dump($parser);
} catch (HtmlParsingException $e) {
// The html suplied is malformed. I got it from the interwebs
// so it's not my fault. I can use $e or getParseErrors()
// to see if the html (and DOM Object) is usable
// I also have a full functioning HTMLParser Object and can
// retrieve a "loaded" functioning DOMDocument Object
var_dump($parser->getParseErrors());
var_dump($parser->getDOMObj());
}
$var = 'this will print wether an exception was previously thrown or not';
print $var;
You can take this further and nest try catch blocks, chain exceptions, run selective code following a determined exception chain path, selective logging, etc...
As a side note, using Exceptions does not mean that the PROGRAM execution will halt, it just means that the code depending of my object will be bypassed. It's up to me or the 3rd party developer to do with it as he pleases.
A: If you want to use exceptions instead of errors for your entire application, you can do it with ErrorException and a custom error handler (see the ErrorException page for a sample error handler). The only downside to this method is that non-fatal errors will still throw exceptions, which are always fatal unless caught. Basically, even an E_NOTICE will halt your entire application if your error_reporting settings do not suppress them.
In my opinion, there are several benefits to using ErrorException:
*
*A custom exception handler will let you display nice messages, even for errors, using set_exception_handler.
*It does not disrupt existing code in any way... trigger_error and other error functions will still work normally.
*It makes it really hard to ignore stupid coding mistakes that trigger E_NOTICEs and E_WARNINGs.
*You can use try/catch to wrap code that may generate a PHP error (not just exceptions), which is a nice way to avoid using the @ error suppression hack:
try {
$foo = $_GET['foo'];
} catch (ErrorException $e) {
$foo = NULL;
}
*You can wrap your entire script in a single try/catch block if you want to display a friendly message to your users when any uncaught error happens. (Do this carefully, because only uncaught errors and exceptions are logged.)
A: The Exceptions are the modern and robust way of signaling an error condition / an exceptional situation. Use them :)
A: Using exceptions are not a good idea in the era of 3rd party application integration.
Because, the moment you try to integrate your app with something else, or someone else's app with yours, your entire application will come to a halt the moment a class in some 3rd party plugin throws an exception. Even if you have full fledged error handling, logging implemented in your own app, someone's random object in a 3rd party plugin will throw an exception, and your entire application will stop right there.
EVEN if you have the means in your application to make up for the error of that library you are using....
A case in example may be a 3rd party social login library which throws an exception because the social login provider returned an error, and kills your entire app unnecessarily - hybridauth, by the way. So, There you have an entire app, and there you have a library bringing in added functionality for you - in this case, social login - and even though you have a lot of fallback stuff in the case a provider does not authenticate (your own login system, plus like 20 or so other social login providers), your ENTIRE application will come to a grinding halt. And you will end up having to change the 3rd party library to work around these issues, and the point of using a 3rd party library to speed up development will be lost.
This is a serious design flaw in regard to philosophy of handling errors in PHP. Lets face it - under the other end of most of applications developed today, there is a user. Be it an intranet user, be it a user over internet, be it a sysadmin, it does not matter - there is generally a user.
And, having an application die on your face without there being anything you can do at that point other than to go back to a previous page and have a shot in the dark regarding what you are trying to do, as a user, is bad, bad practice from development side. Not to mention, an internal error which only the developers should know due to many reasons (from usability to security) being thrown on the face of a user.
As a result, im going to have to just let go of a particular 3rd party library (hybridauth in this case) and not use it in my application, solely for that reason. Despite the fact that hybridauth is a very good library, and apparently a lot of good effort have been spent on it, with a phletora of capabilities.
Therefore, you should refrain from using exceptions in your code. EVEN if the code you are doing right now, is the top level code that will run your application, and not a library, it is possible that you may want to include all or part of your code in other projects, or have to integrate parts or entirety of it with other code of yours or 3rd party code. And if you used exceptions, you will end up with the same situation - entire applications/integrations dying in your face even if you have proper means to handle whatever issue a piece of code provides.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: Automate Safari web browser using c# on Windows I wondered if anyone had successfully managed, or knew how to automate the Safari web browser on the Windows platform.
Ideally I would like to automate Safari in a similar way to using mshtml for Internet Explorer. Failing that a way to inject JavaScript into the running process would also be fine. I've used the JavaScript injection method to automate Firefox via the jssh plug-in.
I'm looking to automate the browser using .Net to enhance an existing automation framework WatiN
Edit: Whilst I think selenium might be a great choice for automating Safari in certain scenarios, I would like to use a solution that does not require installing software on the server i.e. Selenium Core or an intermediate proxy server in the case of Selenium Remote Control.
Update: 23-03-2009:
Whilst I've not yet found a way to automate Safari, I have found a way to automate Webkit inside of Chrome. If you run Chrome using the --remote-shell-port=9999 command line switches (ref: http://www.ericdlarson.com/misc/chrome_command_line_flags.html) you can send javascript to the browser.
Once connected to the remote debug seesion
*
*Send debug() to attach to the current tab
*Send any javascript command using print, i.e. print document.window.location.href
We've used this method to add Chrome support to WatiN
A: I'm not sure if this helps, but the guys at ArtOfTest have added Safari support to their .Net based automation framework WebAii. Maybe you could figure out what they are doing.
A: you might check my post here where I am using the method described above to automate Chrome in C#
http://markcz.wordpress.com/2012/02/18/automating-chrome-browser-from-csharp/
Martin
A: Selenium has been very useful for me for compatibility testing.
A: WatiN here http://watinandmore.blogspot.com/2010/01/browserattachto-and-iattachto.html lets you automate IE and FF. It is open source, so you can have a look on how they do it.
Maybe you can adapt it to your needs?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Getting started with Silverlight development How does one start development in Silverlight?
Does one need a new IDE? or Visual studio will support?
A: Let's tackle this systematically, because there is a lot to learn and there is a lot of information out there. You may want to start with Microsoft's resources first, as they are highly reviewed, and all in one place, and we're working hard to create a lot of them to produce a smooth on-ramp. Then, when you are comfortable, you can certainly branch out to other resources as well.
My advice would be to memorize this URL: http://silverlight.net
Just about everything you'll need for some time is there.
Here is how I'd go about getting started, but there are lots of alternative paths as well...
*
*Go to the [getting started page][1] but don't download everything you see. Focus on just the big green numbers 1 and 2, that is the links to download Visual Studio 2000, the tools for Beta 2 VS 200, and the Beta 1 pack as well as the Blend 2.5 June 2008 preview.
*Click on Learn on the menu (or click [here][2] ) and watch on lien or download the first video, the Silverlight install experience.
*Assuming you haven't worked in Silverlight or WPF before, I'd take a look at our [showcase][3] applications, just to get a sense of what can be done with Silverlight.
*Once you've done that, the order of videos I’ve recommended in the past is in [this blog entry.][4] (which you'll see is where i cribbed these notes from)
Once the basics are under your belt, be sure to check out our expanding collection of [tutorials][5], [videos][6], [webcasts][7], and we have a lot more on the way, including forthcoming books, and a number of alternatives. Also, tomorrow I start a monthly blog cast with [Sparkling Client][8] which I hope will be fun and informative.
Finally, when you have questions, you certainly can ask here (this looks like a tremendous resource!) but if they are Silverlight related you may also want to post them on our [forums][9]
Hope that helps.
-jesse liberty
A: Yes there is tooling support for Visual Studio. It is still in Beta though.
Get Started Building Silverlight 2 Applications
1) Install Visual Studio 2008 then Install Silverlight Tools Beta 2 for Visual Studio 2008
This add-on to Visual Studio 2008 allows you to use .NET to create Silverlight 2 Beta 2 Web sites. The Silverlight 2 Beta 2 Runtime and the Silverlight 2 Beta 2 SDK are installed as part of this install. For additional information read the overview and the Silverlight 2 Beta 2 Readme Notes. Note if you have Visual Studio 2008 Service Pack 1 Beta installed, please see this information for details on installing correctly.
2) Install Expression Blend 2.5 June 2008 Preview
This is a preview version of Expression Blend for designing Silverlight 2 experiences.
3) Install Deep Zoom Composer
This tool allows you to prepare your images for use with the Deep Zoom feature in Silverlight 2.
One thing to watch out for is that Silverlight does not support Synchronous calls to the server. All calls are Asynchronous as of this Beta.
A: Most documentation for Silverlight 2.0 example projects along with the source code is to be found on the Web. A goldmine for finding new and relevant stuff is to do a daily look at Link, where links are posted to all the good stuff as it becomes available.
A: My own blog posting on this:
http://www.codersbarn.com/post/2008/05/07/Beginning-Silverlight-First-Steps.aspx
Anthony :-)
A: Dan Wahlin has some good Silverlight 2 videos at:
http://weblogs.asp.net/dwahlin/archive/2008/03/07/silverlight-2-0-video-tutorials.aspx
They are quite helpful.
rp
A: You can start developing for Silverlight with a text editor. It might take a little longer to put things together, but you will understand a lot more about what is going on.
A: If you find yourself here in 2011, when we're up to version 4, the place to start is now Get Started With Silverlight
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to replace WinAPI functions calls in the MS VC++ project with my own implementation (name and parameters set are the same)? I need to replace all WinAPI calls of the
*
*CreateFile,
*ReadFile,
*SetFilePointer,
*CloseHandle
with my own implementation (which use low-level file reading via Bluetooth).
The code, where functions will be replaced, is Video File Player and it already works with the regular hdd files.
It is also needed, that Video Player still can play files from HDD, if the file in the VideoPlayer input is a regular hdd file.
What is the best practice for such task?
A: I suggest that you follow these steps:
*
*Write a set of wrapper functions, e.g MyCreateFile, MyReadFile, etc, that initially just call the corresponding API and pass the same arguments along, unmodified.
*Use your text editor to search for all calls to the original APIs, and replace these with calls to your new wrapper functions.
*Test that the application still functions correctly.
*Modify the wrapper functions to suit your own purposes.
Note that CreateFile is a macro which expands to either CreateFileW or CreateFileA, depending on whether UNICODE is defined. Consider using LPCTSTR and the TCHAR functions so that your application can be built as either ANSI or Unicode.
Please don't use #define, as suggested in other responses here, as this will just lead to maintenance problems, and as Maximilian correctly points out, it's not a best-practice.
A: You could just write your new functions in a custom namespace. e.g.
namespace Bluetooth
{
void CreateFile(/*params*/);
void etc...
}
Then in your code, the only thing you would have to change is:
if (::CreateFile(...))
{
}
to
if (Bluetooth::CreateFile(...))
{
}
Easy! :)
A: If you're trying to intercept calls to these APIs from another application, consider Detours.
A: If you can edit the code, you should just re-write it to use a custom API that does what you want. Failing that, use Maximilian's technique, but be warned that it is a maintenance horror.
If you cannot edit the code, you can patch the import tables to redirect calls to your own code. A description of this technique can be found in this article - search for the section titled "Spying by altering of the Import Address Table".
This is dangerous, but if you're careful you can make it work. Also check out Microsoft Detours, which does the same sort of thing but doesn't require you to mess around with the actual patching.
A: If you really want to hijack the API, look at syringe.dll (L-GPL).
A: I don't think this is best practice but it should work if you put it in an include file that's included everywhere the function you want to change is called:
#define CreateFile MyCreateFile
HRESULT MyCreateFile(whatever the params are);
Implementation of MyCreateFile looks something like this:
#undef CreateFile
HRESULT MyCreateFile(NobodyCanRememberParamListsLikeThat params)
{
if (InputIsNormalFile())
CreateFile(params);
else
// do your thing
}
You basically make every CreateFile call a MyCreateFile call where you can decide if you want need to use your own implementation or the orginal one.
Disclaimer: I think doing this is ugly and I wouldn't do it. I'd rather search and replace all occurences or something.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Overlapped I/O on anonymous pipe Is it possible to use overlapped I/O with an anonymous pipe? CreatePipe() does not have any way of specifying FILE_FLAG_OVERLAPPED, so I assume ReadFile() will block, even if I supply an OVERLAPPED-structure.
A: Here is an implementation for an anonymous pipe function with the possibility to specify FILE_FLAG_OVERLAPPED:
/******************************************************************************\
* This is a part of the Microsoft Source Code Samples.
* Copyright 1995 - 1997 Microsoft Corporation.
* All rights reserved.
* This source code is only intended as a supplement to
* Microsoft Development Tools and/or WinHelp documentation.
* See these sources for detailed information regarding the
* Microsoft samples programs.
\******************************************************************************/
/*++
Copyright (c) 1997 Microsoft Corporation
Module Name:
pipeex.c
Abstract:
CreatePipe-like function that lets one or both handles be overlapped
Author:
Dave Hart Summer 1997
Revision History:
--*/
#include <windows.h>
#include <stdio.h>
static volatile long PipeSerialNumber;
BOOL
APIENTRY
MyCreatePipeEx(
OUT LPHANDLE lpReadPipe,
OUT LPHANDLE lpWritePipe,
IN LPSECURITY_ATTRIBUTES lpPipeAttributes,
IN DWORD nSize,
DWORD dwReadMode,
DWORD dwWriteMode
)
/*++
Routine Description:
The CreatePipeEx API is used to create an anonymous pipe I/O device.
Unlike CreatePipe FILE_FLAG_OVERLAPPED may be specified for one or
both handles.
Two handles to the device are created. One handle is opened for
reading and the other is opened for writing. These handles may be
used in subsequent calls to ReadFile and WriteFile to transmit data
through the pipe.
Arguments:
lpReadPipe - Returns a handle to the read side of the pipe. Data
may be read from the pipe by specifying this handle value in a
subsequent call to ReadFile.
lpWritePipe - Returns a handle to the write side of the pipe. Data
may be written to the pipe by specifying this handle value in a
subsequent call to WriteFile.
lpPipeAttributes - An optional parameter that may be used to specify
the attributes of the new pipe. If the parameter is not
specified, then the pipe is created without a security
descriptor, and the resulting handles are not inherited on
process creation. Otherwise, the optional security attributes
are used on the pipe, and the inherit handles flag effects both
pipe handles.
nSize - Supplies the requested buffer size for the pipe. This is
only a suggestion and is used by the operating system to
calculate an appropriate buffering mechanism. A value of zero
indicates that the system is to choose the default buffering
scheme.
Return Value:
TRUE - The operation was successful.
FALSE/NULL - The operation failed. Extended error status is available
using GetLastError.
--*/
{
HANDLE ReadPipeHandle, WritePipeHandle;
DWORD dwError;
UCHAR PipeNameBuffer[ MAX_PATH ];
//
// Only one valid OpenMode flag - FILE_FLAG_OVERLAPPED
//
if ((dwReadMode | dwWriteMode) & (~FILE_FLAG_OVERLAPPED)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
//
// Set the default timeout to 120 seconds
//
if (nSize == 0) {
nSize = 4096;
}
sprintf( PipeNameBuffer,
"\\\\.\\Pipe\\RemoteExeAnon.%08x.%08x",
GetCurrentProcessId(),
InterlockedIncrement(&PipeSerialNumber)
);
ReadPipeHandle = CreateNamedPipeA(
PipeNameBuffer,
PIPE_ACCESS_INBOUND | dwReadMode,
PIPE_TYPE_BYTE | PIPE_WAIT,
1, // Number of pipes
nSize, // Out buffer size
nSize, // In buffer size
120 * 1000, // Timeout in ms
lpPipeAttributes
);
if (! ReadPipeHandle) {
return FALSE;
}
WritePipeHandle = CreateFileA(
PipeNameBuffer,
GENERIC_WRITE,
0, // No sharing
lpPipeAttributes,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | dwWriteMode,
NULL // Template file
);
if (INVALID_HANDLE_VALUE == WritePipeHandle) {
dwError = GetLastError();
CloseHandle( ReadPipeHandle );
SetLastError(dwError);
return FALSE;
}
*lpReadPipe = ReadPipeHandle;
*lpWritePipe = WritePipeHandle;
return( TRUE );
}
A: No. As explained here, anonymous pipes do not support asynchronous I/O. You need to use a named pipe. There's example code to do this on MSDN here and here.
A: first of all need understand - what is Anonymous Pipes and what, are exist difference between anonymous and Named Pipes at all.
really exist only single pipe type (implemented by npfs.sys). no any difference, except name, between named and anonymous pipes at all. both is only pipes.
so called anonymous pipes - this is special/random named pipes before win7 and true unnamed pipes begin from win7.
when msdn write that "anonymous pipe is one-way pipe" - this is lie. as any pipe it can be one-way or duplex. when msdn write that "Asynchronous (overlapped) read and write operations are not supported by anonymous pipes." - this is lie. of course pipes support asynchronous io. the name of pipe not affect this.
before win7 really unnamed pipes even not exist at all. CreatePipe function use Win32Pipes.%08x.%08x format for create name of "Anonymous Pipe".
static LONG PipeSerialNumber;
WCHAR name[64];
swprintf(name, L"\\Device\\NamedPipe\\Win32Pipes.%08x.%08x",
GetCurrentProcessId(), InterlockedIncrement(&PipeSerialNumber));
begin from win7 CreatePipe use another technique (relative file open) for create pipe pair - now it really anonymous.
for example code witch create pipe pair where one pipe is asynchronous and not inheritable. and another pipe is synchronous and inheritable. both pipes is duplex (support both read and write)
ULONG CreatePipeAnonymousPair7(PHANDLE phServerPipe, PHANDLE phClientPipe)
{
HANDLE hNamedPipe;
IO_STATUS_BLOCK iosb;
static UNICODE_STRING NamedPipe = RTL_CONSTANT_STRING(L"\\Device\\NamedPipe\\");
OBJECT_ATTRIBUTES oa = { sizeof(oa), 0, const_cast<PUNICODE_STRING>(&NamedPipe), OBJ_CASE_INSENSITIVE };
NTSTATUS status;
if (0 <= (status = NtOpenFile(&hNamedPipe, SYNCHRONIZE, &oa, &iosb, FILE_SHARE_VALID_FLAGS, 0)))
{
oa.RootDirectory = hNamedPipe;
static LARGE_INTEGER timeout = { 0, MINLONG };
static UNICODE_STRING empty = {};
oa.ObjectName = ∅
if (0 <= (status = ZwCreateNamedPipeFile(phServerPipe,
FILE_READ_ATTRIBUTES|FILE_READ_DATA|
FILE_WRITE_ATTRIBUTES|FILE_WRITE_DATA|
FILE_CREATE_PIPE_INSTANCE,
&oa, &iosb, FILE_SHARE_READ|FILE_SHARE_WRITE,
FILE_CREATE, 0, FILE_PIPE_BYTE_STREAM_TYPE, FILE_PIPE_BYTE_STREAM_MODE,
FILE_PIPE_QUEUE_OPERATION, 1, 0, 0, &timeout)))
{
oa.RootDirectory = *phServerPipe;
oa.Attributes = OBJ_CASE_INSENSITIVE|OBJ_INHERIT;
if (0 > (status = NtOpenFile(phClientPipe, SYNCHRONIZE|FILE_READ_ATTRIBUTES|FILE_READ_DATA|
FILE_WRITE_ATTRIBUTES|FILE_WRITE_DATA, &oa, &iosb,
FILE_SHARE_VALID_FLAGS, FILE_SYNCHRONOUS_IO_NONALERT)))
{
NtClose(oa.RootDirectory);
}
}
NtClose(hNamedPipe);
}
return RtlNtStatusToDosError(status);
}
ULONG CreatePipeAnonymousPair(PHANDLE phServerPipe, PHANDLE phClientPipe)
{
static char flag_supported = -1;
if (flag_supported < 0)
{
ULONG dwMajorVersion, dwMinorVersion;
RtlGetNtVersionNumbers(&dwMajorVersion, &dwMinorVersion, 0);
flag_supported = _WIN32_WINNT_WIN7 <= ((dwMajorVersion << 8)| dwMinorVersion);
}
if (flag_supported)
{
return CreatePipeAnonymousPair7(phServerPipe, phClientPipe);
}
static LONG PipeSerialNumber;
WCHAR name[64];
swprintf(name, L"\\\\?\\pipe\\Win32Pipes.%08x.%08x", GetCurrentProcessId(), InterlockedIncrement(&PipeSerialNumber));
HANDLE hClient, hServer = CreateNamedPipeW(name,
PIPE_ACCESS_DUPLEX|FILE_READ_DATA|FILE_WRITE_DATA|FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE|PIPE_READMODE_BYTE, 1, 0, 0, 0, 0);
if (hServer != INVALID_HANDLE_VALUE)
{
static SECURITY_ATTRIBUTES sa = { sizeof(sa), 0, TRUE };
hClient = CreateFileW(name, FILE_GENERIC_READ|FILE_GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, 0);
if (hClient != INVALID_HANDLE_VALUE)
{
*phServerPipe = hServer, *phClientPipe = hClient;
return NOERROR;
}
CloseHandle(hServer);
}
return GetLastError();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: How can I tell if I have an open relay? I'm trying to work out if I have an open relay on my server. How do I do that?
I've tried http://www.abuse.net/relay.html
and it reports:
Hmmn, at first glance, host appeared to accept a message for relay.
THIS MAY OR MAY NOT MEAN THAT IT'S AN OPEN RELAY.
Some systems appear to accept relay mail, but then reject messages internally rather than delivering them, but you cannot tell at this point whether the message will be relayed or not.
What further tests can I do to determine if the server has an open relay?
A: Eh? As your link tells you, register for the site and it will give you an address @abuse.net, valid for 24 hours. Enter that address into the testing form. If your abuse.net account receives the test email, you have an open relay.
A: You could try setting up a email client to sent email through your server, from an email address that isn't hosted on the same server. If you can successfuly send mail, from an email address at a different domain, without entering a login and password for your SMTP server, then it's probably an open relay.
A: This depends on your MTA and how you've configured it. Ultimately there is only one thing you must do to prevent relaying. Restrict relaying to authenticated users and/or restrict relaying to specific IPs. I prefer to restrict all IPs except localhost on my mail server and require authentication from everyone else.
The common mistake is to allow more IPs than necessary. Imagine a user on a cable modem who decides to allow the roommate's laptop to relay with the statement 192.168.1.0/24 rather than the more specific 192.168.1.0/29. Now anyone else on the /24 can relay off the server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cross platform IPC I'm looking for suggestions on possible IPC mechanisms that are:
*
*Cross platform (Win32 and Linux at least)
*Simple to implement in C++ as well as the most common scripting languages (perl, ruby, python, etc).
*Finally, simple to use from a programming point of view!
What my options are? I'm programming under Linux, but I'd like what I write to be portable to other OSes in the future. I've thought about using sockets, named pipes, or something like DBus.
A: You might want to try YAMI , it's very simple yet functional, portable and comes with binding to few languages
A: I can suggest you to use the plibsys C library. It is very simple, lightweight and cross-platform. Released under the LGPL. It provides:
*
*named system-wide shared memory regions (System V, POSIX and Windows implementations);
*named system-wide semaphores for access synchronization (System V, POSIX and Windows implementations);
*named system-wide shared buffer implementation based on the shared memory and semaphore;
*sockets (TCP, UDP, SCTP) with IPv4 and IPv6 support (UNIX and Windows implementations).
It is easy to use library with quite a good documentation. As it is written in C you can easily make bindings from scripting languages.
If you need to pass large data sets between processes (especially if speed is essential) it is better to use shared memory to pass the data itself and sockets to notify a process that the data is ready. You can make it as following:
*
*a process puts the data into a shared memory segment and sends a notification via a socket to another process; as a notification usually is very small the time overhead is minimal;
*another process receives the notification and reads the data from the shared memory segment; after that it sends a notification that the data was read back to the first process so it can feed more data.
This approach can be implemented in a cross-platform fashion.
A: In terms of speed, the best cross-platform IPC mechanism will be pipes. That assumes, however, that you want cross-platform IPC on the same machine. If you want to be able to talk to processes on remote machines, you'll want to look at using sockets instead. Luckily, if you're talking about TCP at least, sockets and pipes behave pretty much the same behavior. While the APIs for setting them up and connecting them are different, they both just act like streams of data.
The difficult part, however, is not the communication channel, but the messages you pass over it. You really want to look at something that will perform verification and parsing for you. I recommend looking at Google's Protocol Buffers. You basically create a spec file that describes the object you want to pass between processes, and there is a compiler that generates code in a number of different languages for reading and writing objects that match the spec. It's much easier (and less bug prone) than trying to come up with a messaging protocol and parser yourself.
A: How about Facebook's Thrift?
Thrift is a software framework for scalable cross-language services development. It combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk, and OCaml.
A: I think you'll want something based on sockets.
If you want RPC rather than just IPC I would suggest something like XML-RPC/SOAP which runs over HTTP, and can be used from any language.
A: YAMI - Yet Another Messaging Infrastructure is a lightweight messaging and networking framework.
A: If you're willing to try something a little different, there's the ICE platform from ZeroC. It's open source, and is supported on pretty much every OS you can think of, as well as having language support for C++, C#, Java, Ruby, Python and PHP. Finally, it's very easy to drive (the language mappings are tailored to fit naturally into each language). It's also fast and efficient. There's even a cut-down version for devices.
A: Distributed computing is usually complex and you are well advised to use existing libraries or frameworks instead of reinventing the wheel. Previous poster have already enumerated a couple of these libraries and frameworks. Depending on your needs you can pick either a very low level (like sockets) or high level framework (like CORBA). There can not be a generic "use this" answer. You need to educate yourself about distributed programming and then will find it much easier to pick the right library or framework for the job.
There exists a wildly used C++ framework for distributed computing called ACE and the CORBA ORB TAO (which is buildt upon ACE). There exist very good books about ACE http://www.cs.wustl.edu/~schmidt/ACE/ so you might take a look. Take care!
A: It doesn't get more simple than using pipes, which are supported on every OS I know of, and can be accessed in pretty much every language.
Check out this tutorial.
A: TCP sockets to localhost FTW.
A: For C++, check out Boost IPC.
You can probably create or find some bindings for the scripting languages as well.
Otherwise if it's really important to be able to interface with scripting languages your best bet is simply to use files, pipes or sockets or even a higher level abstraction like HTTP.
A: Why not D-Bus? It's a very simple message passing system that runs on almost all platforms and is designed for robustness. It's supported by pretty much every scripting language at this point.
http://freedesktop.org/wiki/Software/dbus
A: If you want a portable, easy to use, multi-language and LGPLed solution, I would recommend you ZeroMQ:
*
*Amazingly fast, almost linear scaleable and still simple.
*Suitable for simple and complex systems/architectures.
*Very powerful communication patterns available: REP-REP, PUSH-PULL, PUB-SUB, PAIR-PAIR.
*You can configure the transport protocol to make it more efficient if you are passing messages between threads (inproc://), processes (ipc://) or machines ({tcp|pgm|epgm}://), with a smart option to shave off some part of the protocol overheads in case of connections are running between VMware virtual machines (vmci://).
For serialization I would suggest MessagePack or Protocol Buffers (which other have already mentioned as well), depending on your needs.
A: Python has a pretty good IPC library: see https://docs.python.org/2/library/ipc.html
A: Xojo has built-in cross-platform IPC support with its IPCSocket class. Although you obviously couldn't "implement" it in other languages, you could use it in a Xojo console app and call it from other languages making this option perhaps very simple for you.
A: In the current ages there is available a very easy, C++1x compliant, well documented, Linux and Windows compatible, open-source "CommonAPI" library: CommonAPI C++.
The underlying IPC system is D-Bus (libdbus) or SomeIP if one wish. Application interfaces are specified using a simple and tailored for that Franca IDL language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "77"
} |
Q: ASP.NET - Is it possible to trigger a postback from server code? Is it possible to to programmatically trigger a postback from server code in ASP.NET? I know that it is possible to do a Response.Redirect or Server.Transfer to redirect to a page, but is there a way to trigger a postback to the same page in server code (i.e. without using javascript trickery to submit a form)?
A: Postbacks are caused by a FORM submission. You need to initiate them from the client.
A: Asp.net Postbacks are initiated from the client (typically form submission). I am not sure what you are trying to achieve. Some of the server side page lifecyle events are already executed and what you are trying to do is raise the previous event handlers again.
A: You could do it with an Ajax request. You'd have to have the page polling the server. There isn't any way for the server to push information out to the browser without requesting it. But having some Javascript that runs in the background and polls the server every 5 seconds (or more, depending on your needs) would probably be the best solution.
APPEND
If you go this route, you can have the server send back just a yes or no, or even just 0 or 1 depending on whether or not the postback should be performed. Depending on your needs, there many be no reason to actually use the XML part of AJAX. Just run a simple Asynchronous request, possibly with a few querystring variables, and get back a simple one word, or even a number as a response. That way you can keep the javascript for creating and parsing the XML out if it isn't needed.
A: If you are looking to initiate communication from the server, rather then polling, have a look at Microsoft's SignalR. The easiest context for this, and one the SignalR has as part of its example code is a chat application. You will be able to initiate messages from code behind and receive them as javascript events on your page.
Server Code To Send:
using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
}
Client Code to catch server messages is the override of 'chat.client.broadcastMessage':
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
A: For those using newer versions of .NET, you have to use Page.ClientScript.GetPostBackEventReference since 'this.GetPostBackEventReference(...)' is obsolete. Also probably Page.ClientScript.RegisterStartupScript(...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Common memory optimization What are the most common memory optimizations in csharp, dotnet 2.0. Wanted to see if there common things that people may not be doing by default in winform app
A: *
*use structs for small wrapper objects to avoid heap fragmentation
*think carefully about object lifetimes, especially for large objects so they do not end up on the LOH unless you intend them to
*think about allocations inside of a loop
*make sure dynamically sized array will be of reasonable size, otherwise partition the problem
A: Use StringBuilder instead of directly modifying a string if you're performing many modifications to the same string.
A: Sealing as much classes as possible should also help. AFAIK this is one trick that SmartAssembly uses to reduce memory consumption.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is global memory initialized in C++? Is global memory initialized in C++? And if so, how?
(Second) clarification:
When a program starts up, what is in the memory space which will become global memory, prior to primitives being initialized? I'm trying to understand if it is zeroed out, or garbage for example.
The situation is: can a singleton reference be set - via an instance() call, prior to its initialization:
MySingleton* MySingleton::_instance = NULL;
and get two singleton instances as a result?
See my C++ quiz on on multiple instances of a singleton...
A: Yes global primitives are initialized to NULL.
Example:
int x;
int main(int argc, char**argv)
{
assert(x == 0);
int y;
//assert(y == 0); <-- wrong can't assume this.
}
You cannot make any assumptions about classes, structs, arrays, blocks of memory on the heap...
It's safest just to always initialize everything.
A: Coming from the embedded world...
Your code gets compiled into three types of memory:
1. .data: initialized memory
2. .text: constants and code
3. .bss: uninitialized memory (initialized to 0 in C++ if not explicitly initialized)
Globals go in .data if initialized. If not they are placed in .bss and zero'ed in premain code.
A: From the standard:
Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD [plain old data] types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit. [Note:8.5.1 describes the order in which aggregate members are initialized. The initial-
ization of local static objects is described in 6.7.]
So yes, globals which have static storage duration will be initialized. Globals allocated, e.g., on the heap will of course not be initialized automatically.
A: Variables declared with static/global scope are always initialized under VC++ at least.
Under some circumstances there can actually be a difference in behaviour between:
int x = 0;
int main() { ... }
and
int x;
int main() { ... }
If you are using shared data segments then VC++ at least uses the presence of an explicit initialization along with a #pragma data_seg to determine whether a particular variable should go in the shared data segment or the private data segment for a process.
For added fun consider what happens if you have a static C++ object with constructor/destructor declared in a shared data segment. The constructor/destructor is called every time the exe/dll attaches to the data segment which is almost certainly not what you want.
More details in this KB article
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Rails Model, View, Controller, and Helper: what goes where? In Ruby on Rails Development (or MVC in general), what quick rule should I follow as to where to put logic.
Please answer in the affirmative - With Do put this here, rather than Don't put that there.
A: The Rails way is to have skinny controllers and fat models.
A: Do put stuff related to authorization/access control in the controller.
Models are all about your data. Validation, Relationships, CRUD, Business Logic
Views are about showing your data. Display and getting input only.
Controllers are about controlling what data goes from your model to your view (and which view) and from your view to your model. Controllers can also exist without models.
I like to think of the controller as a security guard/receptionist who directs you the customer(request) to the appropriate counter where you ask a teller (view) a question. The teller (view) then goes and gets the answer from a manager (model), who you never see. You the request then go back to the security guard/receptionist (controller) and wait until you are directed to go another teller (view) who tells you the answer the manager (model) told them in response to the other teller's (view) question.
Likewise if you want to tell the teller (view) something then largely the same thing happens except the second teller will tell you whether the manager accepted your information. It is also possible that the security guard/receptionist (controller) may have told you to take a hike since you were not authorized to tell the manager that information.
So to extend the metaphor, in my stereotyped and unrealistic world, tellers (views) are pretty but empty-headed and often believe anything you tell them, security guard/receptionists are minimally polite but are not very knowledgeable but they know where people should and shouldn't go and managers are really ugly and mean but know everything and can tell what is true and what isn't.
A: One thing that helps separate properly is avoiding the "pass local variables from controller to view" anti-pattern. Instead of this:
# app/controllers/foos_controller.rb:
class FoosController < ApplicationController
def show
@foo = Foo.find(...)
end
end
#app/views/foos/show.html.erb:
...
<%= @foo.bar %>
...
Try moving it to a getter that is available as a helper method:
# app/controllers/foos_controller.rb:
class FoosController < ApplicationController
helper_method :foo
def show
end
protected
def foo
@foo ||= Foo.find(...)
end
end
#app/views/foos/show.html.erb:
...
<%= foo.bar %>
...
This makes it easier to modify what gets put in "@foo" and how it is used. It increases separation between controller and view without making them any more complicated.
A: To add to pauliephonic's answer:
Helper: functions to make creating the view easier. For example, if you're always iterating over a list of widgets to display their price, put it into a helper (along with a partial for the actual display). Or if you have a piece of RJS that you don't want cluttering up the view, put it into a helper.
A: Well, it sort of depends upon what the logic has to deal with...
Often, it makes sense to push more things into your models, leaving controllers small. This ensures that this logic can easily be used from anywhere you need to access the data that your model represents. Views should contain almost no logic. So really, in general, you should strive to make it so that you Don't Repeat Yourself.
Also, a quick bit of google reveals a few more concrete examples of what goes where.
Model: validation requirements, data relationships, create methods, update methods, destroy methods, find methods (note that you should have not only the generic versions of these methods, but if there is something you are doing a lot, like finding people with red hair by last name, then you should extract that logic so that all you have to do is call the find_redH_by_name("smith") or something like that)
View: This should be all about formatting of data, not the processing of data.
Controller: This is where data processing goes. From the internet: "The controller’s purpose is to respond to the action requested by the user, take any parameters the user has set, process the data, interact with the model, and then pass the requested data, in final form, off to the view."
Hope that helps.
A: MVC
Controller: Put code here that has to do with working out what a user wants, and deciding what to give them, working out whether they are logged in, whether they should see certain data, etc. In the end, the controller looks at requests and works out what data (Models) to show and what Views to render. If you are in doubt about whether code should go in the controller, then it probably shouldn't. Keep your controllers skinny.
View: The view should only contain the minimum code to display your data (Model), it shouldn't do lots of processing or calculating, it should be displaying data calculated (or summarized) by the Model, or generated from the Controller. If your View really needs to do processing that can't be done by the Model or Controller, put the code in a Helper. Lots of Ruby code in a View makes the pages markup hard to read.
Model: Your model should be where all your code that relates to your data (the entities that make up your site e.g. Users, Post, Accounts, Friends etc.) lives. If code needs to save, update or summarise data related to your entities, put it here. It will be re-usable across your Views and Controllers.
A: The MVC pattern is really only concerned with UI and nothing else. You shouldn't put any complex business logic in the controller as it controls the view but not the logic. The Controller should concern itself with selecting the proper view and delegate more complex stuff to the domain model (Model) or the business layer.
Domain Driven Design has a concept of Services which is a place you stick logic which needs to orchestrate a number of various types of objects which generally means logic which doesn't naturally belong on a Model class.
I generally think of the Service layer as the API of my applications. My Services layers usually map pretty closely to the requirements of the application I'm creating thus the Service layer acts as a simplification of the more complex interactions found in the lower levels of my app, i.e. you could accomplish the same goal bypassing the Service layers but you'd have to pull a lot more levers to make it work.
Note that I'm not talking about Rails here I'm talking about a general architectural style which addresses your particular problem.
A: Perfect explanations here already, one very simple sentence as conclusion and easy to remember:
We need SMART Models, THIN Controllers, and DUMB Views.
http://c2.com/cgi/wiki?ModelViewController
A: In simple terms, generally,
Models will have all the codes related to table(s), their simple or complex relationships (think them as sql queries involving multiple tables), manipulation of the data/variables to arrive at a result using the business logic.
Controllers will have code/pointers towards the relevant models for the job requested.
Views will accept the user input/interaction and display the resultant response.
Any major deviation from these will put unwanted strain on that part and the overall application performance may get impacted.
A: Testing, Testing ...
Put as much logic as possible in the model and then you will be able to test it properly. Unit tests test the data and the way it is formed by testing the model, and functional tests test the way it is routed or controlled by testing the controllers, so it follows that you can't test the integrity of the data unless it is in the model.
j
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "155"
} |
Q: Is it possible to display the entity ⇓ in IE6 is it possible to display ⇓ entity in ie6? It is being display in every browser but not IE 6.I am writing markup such as:
<span>⇓</span>
A: According to this page, that symbol doesn't show in IE6 at all.
Symbol Character Numeric Description
⇓ ⇓ ⇓ Down double arrow - - * Doesn't show with MS IE6
If you really need that particular symbol, you may just have to go for a small graphic of the arrow - not an ideal solution, but if you need it to display in IE6 then that may be your only option.
A: Yes, it is possible... But you'll need to explicitly tell IE which font to find it in. For instance:
<span style="font-family:Arial Unicode MS"> ⇓ </span>
should produce ⇓ in most browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: IIS Integrated Request Processing Pipeline -- Modify Request I want to implement an ISAPI filter like feature using HttpModule in IIS7 running under IIS Integrated Request Processing Pipeline mode.
The goal is to look at the incoming request at the Web Server level, and inject some custom HttpHeaders into the request. (for ex: HTTP\_EAUTH\_ID)
And later in the page lifecycle of an ASPX page, i should be able to use that variable as
string eauthId = Request.ServerVariables["HTTP\_EAUTH\_ID"].ToString();
So implementing this module at the Web Server level, is it possible to alter the ServerVariables collection ??
A: HttpRequest.ServerVariables Property is a read-only collection. So, you cannot directly modify that. I would suggest storing your custom data in httpcontext (or global application object or your database) from your httpmodule and then reading that shared value in the aspx page.
If you still want to modify server variables, there is a hack technique mentioned in this thread using Reflection.
A: I believe the server variables list only contains the headers sent from the browser to the server.
A: You won't be able to modify either the HttpRequest.Headers or the HttpRequest.ServerVariables collection. You will however be able to tack on your information to any of:
HttpContext.Current.Items
HttpContext.Current.Response.Headers
Unfortunately, Request.Params, Request.QueryString, Request.Cookies, Request.Form (and almost any other place you'd think of stuffing it is read only.
I'd strongly advise against using reflection if this is a HttpModule you're planning on installing into IIS 7. Given that this code will be called for (potentially) every request that goes through the web server it'll need to be really fast and reflection just isn't going to cut it (unless you have very few users).
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Guidelines to improve your code What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people insist that every if statement is followed by a brace block ({...}).
I'm interested in what guidelines other people follow, and the reasons behind them. I'm also interested in guidelines that you think are rubbish, but are commonly held. Can anyone suggest a few?
To get the ball rolling, I'll mention a few to start with:
*
*Always use braces after every if / else statement (mentioned above). The rationale behind this is that it's not always easy to tell if a single statement is actually one statement, or a preprocessor macro that expands to more than one statement, so this code would break:
// top of file:
#define statement doSomething(); doSomethingElse
// in implementation:
if (somecondition)
doSomething();
but if you use braces then it will work as expected.
*
*Use preprocessor macros for conditional compilation ONLY. preprocessor macros can cause all sorts of hell, since they don't allow C++ scoping rules. I've run aground many times due to preprocessor macros with common names in header files. If you're not careful you can cause all sorts of havoc!
Now over to you.
A: A few of my personal favorites:
Strive to write code that is const correct. You will enlist the compiler to help weed out easy to fix but sometimes painful bugs. Your code will also tell a story of what you had in mind at the time you wrote it -- valuable for newcomers or maintainers once you're gone.
Get out of the memory management business. Learn to use smart pointers: std::auto_ptr, std::tr1::shared_ptr (or boost::shared_ptr) and boost::scoped_ptr. Learn the differences between them and when to use one vs. another.
You're probably going to be using the Standard Template Library. Read the Josuttis book. Don't just stop after the first few chapters on containers thinking that you know the STL. Push through to the good stuff: algorithms and function objects.
A: *
*Delete unnecessary code.
That is all.
A: *
*Use and enforce a common coding style and guidelines. Rationale: Every developer on the team or in the firm is able to read the code without distractions that may occur due to different brace styles or similar.
*Regularly do a full rebuild of your entire source base (i.e. do daily builds or builds after each checkin) and report any errors! Rationale: The source is almost always in a usable state, and problems are detected shortly after they are "implemented", where problem solving is cheap.
A: Turn on all the warnings you can stand in your compiler (gcc: -Wall is a good start but doesn't include everything so check the docs), and make them errors so you have to fix them (gcc: -Werror).
A: Google's style guide, mentioned in one of these answers, is pretty solid. There's some pointless stuff in it, but it's more good than bad.
Sutter and Alexandrescu wrote a decent book on this subject, called C++ Coding Standards.
Here's some general tips from lil' ole me:
*
*Your indentation and bracketing style are both wrong. So are everyone else's. So follow the project's standards for this. Swallow your pride and setup your editor so that everything is as consistent as possible with the rest of the codebase. It's really really annoying having to read code that's indented inconsistently. That said, bracketing and indenting have nothing whatsoever to do with "improving your code." It's more about improving your ability to work with others.
*Comment well. This is extremely subjective, but in general it's always good to write comments about why code works the way it does, rather than explaining what it does. Of course for complex code it's also good for programmers who may not be familiar with the algorithm or code to have an idea of what it's doing as well. Links to descriptions of the algorithms employed are very welcome.
*Express logic in as straightforward a manner as possible. Ironically suggestions like "put constants on the left side of comparisons" have gone wrong here, I think. They're very popular, but for English speakers, they often break the logical flow of the program to those reading. If you can't trust yourself (or your compiler) to write equality compares correctly, then by all means use tricks like this. But you're sacrificing clarity when you do it. Also falling under this category are things like ... "Does my logic have 3 levels of indentation? Could it be simpler?" and rolling similar code into functions. Maybe even splitting up functions. It takes experience to write code that elegantly expresses the underlying logic, but it's worth working at it.
Those were pretty general. For specific tips I can't do a much better job than Sutter and Alexandrescu.
A: In if statements put the constant on the left i.e.
if( 12 == var )
not
if( var == 12 )
Beacause if you miss typing a '=' then it becomes assignment. In the top version the compiler says this isn't possible, in the latter it runs and the if is always true.
I use braces for if's whenever they are not on the same line.
if( a == b ) something();
if( b == d )
{
bigLongStringOfStuffThatWontFitOnASingleLineNeatly();
}
Open and close braces always get their own lines. But that is of course personal convention.
A: Only comment when it's only necessary to explain what the code is doing, where reading the code couldn't tell you the same.
Don't comment out code that you aren't using any more. If you want to recover old code, use your source control system. Commenting out code just makes things look messy, and makes your comments that actually are important fade into the background mess of commented code.
A: *
*Use consistent formatting.
*When working on legacy code employ the existing style of formatting, esp. brace style.
*Get a copy of Scott Meyer's book Effective C++
*Get a copy of Steve MConnell's book Code Complete.
A: There is also a nice C++ Style Guide used internally by Google, which includes most of the rules mentioned here.
A: Start to write a lot of comments -- but use that as an opportunity to refactor the code so that it's self explanatory.
ie:
for(int i=0; i<=arr.length; i++) {
arr[i].conf() //confirm that every username doesn't contain invalid characters
}
Should've been something more like
for(int i=0; i<=activeusers.length; i++) {
activeusers[i].UsernameStripInvalidChars()
}
A: In a similar vein you might find some useful suggestions here: How do you make wrong code look wrong? What patterns do you use to avoid semantic errors?
A: *
*Use tabs for indentations, but align data with spaces
This means people can decide how much to indent by changing the tab size, but also that things stay aligned (eg you might want all the '=' in a vertical line when assign values to a struct)
*Allways use constants or inline functions instead of macros where posible
*Never use 'using' in header files, because everything that includes that heafer will also be affected, even if the person includeing your header doesn't want all of std (for example) in their global namespace.
*If something is longer than about 80 columes, break it up into multiple lines eg
if(SomeVeryLongVaribleName != LongFunction(AnotherVarible, AString) &&
BigVaribleIsValid(SomeVeryLongVaribleName))
{
DoSomething();
}
*Only overload operators to make them do what the user expects, eg overloading the + and - operators for a 2dVector is fine
*Always comment your code, even if its just to say what the next block is doing (eg "delete all textures that are not needed for this level"). Someone may need to work with it later, posibly after you have left and they don't want to find 1000's of lines of code with no comments to indicate whats doing what.
A: *
*setup coding convention and make everyone involved follow the convention (you wouldn't want reading code that require you to figure out where is the next statement/expression because it is not indented properly)
*constantly refactoring your code (get a copy of Refactoring, by Martin Fowler, pros and cons are detailed in the book)
*write loosely coupled code (avoid writing comment by writing self-explanatory code, loosely coupled code tends to be easier to manage/adapt to change)
*if possible, unit test your code (or if you are macho enough, TDD.)
*release early, release often
*avoid premature optimization (profiling helps in optimizing)
A: Where you can, use pre-increment instead of post-increment.
A: I use PC-Lint on my C++ projects and especially like how it references existing publications such as the MISRA guidelines or Scott Meyers' "Effective C++" and "More Effective C++". Even if you are planning on writing very detailed justifications for each rule your static analysis tool checks, it is a good idea to point to established publications that your user trusts.
A: Here is the most important piece of advice I was given by a C++ guru, and it helped me in a few critical occasions to find bugs in my code:
*
*Use const methods when a method is not supposed to modify the object.
*Use const references and pointers in parameters when the object is not supposed to modify the object.
With these 2 rules, the compiler will tell you for free where in your code the logic is flawed!
A: Also, for some good techniques you might follow Google's blog "Testing on the Toilet".
A: Look at it six months later
A: make sure you indent properly
A: Hmm - I probably should have been a bit more specific.
I'm not so much looking for advice for myself - I'm writing a static code analysis tool (the current commercial offerings just aren't good enough for what I want), and I'm looking for ideas for plugins to highlight possible errors in the code.
Several people have mentioned things like const correctness and using smart pointers - that's the kind of think I can check for. Checking for indentation and commenting is a bit harder to do (from a programming point of view anyway).
A: Smart pointers have a nice way of indicating ownership very clearly. If you're a class or a function:
*
*if you get a raw pointer, you don't own anything. You're allowed to use the pointee, courtesy of your caller, who guarantees that the pointee will stay alive longer than you.
*if you get a weak_ptr, you don't own the pointee, and on top of that the pointee can disappear at any time.
*if you get a shared_ptr, you own the object along with others, so you don't need to worry. Less stress, but also less control.
*if you get an auto_ptr, you are the sole owner of the object. It's yours, you're the king. You have the power to destroy that object, or give it to someone else (thereby losing ownership).
I find the case for auto_ptr particularly strong: in a design, if I see an auto_ptr, I immediately know that that object is going to "wander" from one part of the system to the other.
This is at least the logic I use on my pet project. I'm not sure how many variations there can be on the topic, but until now this ruleset has served me well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do I write a python HTTP server to listen on multiple ports? I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?
What I'm doing now:
class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def doGET
[...]
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass
server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)
server.serve_forever()
A: Not easily. You could have two ThreadingHTTPServer instances, write your own serve_forever() function (don't worry it's not a complicated function).
The existing function:
def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self.__serving = True
self.__is_shut_down.clear()
while self.__serving:
# XXX: Consider using another file descriptor or
# connecting to the socket to wake this up instead of
# polling. Polling reduces our responsiveness to a
# shutdown request and wastes cpu at all other times.
r, w, e = select.select([self], [], [], poll_interval)
if r:
self._handle_request_noblock()
self.__is_shut_down.set()
So our replacement would be something like:
def serve_forever(server1,server2):
while True:
r,w,e = select.select([server1,server2],[],[],0)
if server1 in r:
server1.handle_request()
if server2 in r:
server2.handle_request()
A: I would say that threading for something this simple is overkill. You're better off using some form of asynchronous programming.
Here is an example using Twisted:
from twisted.internet import reactor
from twisted.web import resource, server
class MyResource(resource.Resource):
isLeaf = True
def render_GET(self, request):
return 'gotten'
site = server.Site(MyResource())
reactor.listenTCP(8000, site)
reactor.listenTCP(8001, site)
reactor.run()
I also thinks it looks a lot cleaner to have each port be handled in the same way, instead of having the main thread handle one port and an additional thread handle the other. Arguably that can be fixed in the thread example, but then you're using three threads.
A: Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both http://localhost:1111/ and http://localhost:2222/
from threading import Thread
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write("Hello World!")
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
def serve_on_port(port):
server = ThreadingHTTPServer(("localhost",port), Handler)
server.serve_forever()
Thread(target=serve_on_port, args=[1111]).start()
serve_on_port(2222)
update:
This also works with Python 3 but three lines need to be slightly changed:
from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler
and
self.wfile.write(bytes("Hello World!", "utf-8"))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Checkbox in listview control Can you have a multicolumn listview control where one of the columns is a checkbox? Example code or links would be greatly appreciated.
I am using visual studio 2005
A: Add Checkbox column like below.
myListView.CheckBoxes = true;
myListView.Columns.Add(text, width, alignment);
Add ListViewItem s like below.
ListViewItem lstViewItem = new ListViewItem();
lstViewItem.SubItems.Add("Testing..");
lstViewItem.SubItems.Add("Testing1..");
myListView.Items.Add(lstViewItem);
A: Allan Anderson created a custom control to let you do this.
You can find it here: http://www.codeproject.com/KB/list/aa_listview.aspx
Here's some example code for that control:
GlacialList mylist = new GlacialList();
mylist.Columns.Add( "Column1", 100 ); // this can also be added
// through the design time support
mylist.Columns.Add( "Column2", 100 );
mylist.Columns.Add( "Column3", 100 );
mylist.Columns.Add( "Column4", 100 );
GLItem item;
item = this.glacialList1.Items.Add( "Atlanta Braves" );
item.SubItems[1].Text = "8v";
item.SubItems[2].Text = "Live";
item.SubItems[2].BackColor = Color.Bisque;
item.SubItems[3].Text = "MLB.TV";
item = this.glacialList1.Items.Add( "Florida Marlins" );
item.SubItems[1].Text = "";
item.SubItems[2].Text = "Delayed";
item.SubItems[2].BackColor = Color.LightCoral;
item.SubItems[3].Text = "Audio";
item.SubItems[1].BackColor = Color.Aqua; // set the background
// of this particular subitem ONLY
item.UserObject = myownuserobjecttype; // set a private user object
item.Selected = true; // set this item to selected state
item.SubItems[1].Span = 2; // set this sub item to span 2 spaces
ArrayList selectedItems = mylist.SelectedItems;
// get list of selected items
A: Why dont you try for XPTable by Mathew Hall
A: You could use a grid view instead, as that gives you more fine control of column contents.
A: Maybe ListView.Checkboxes.
A: You can set the the CheckBoxes property to true. In code this can be done like this:
listView1.CheckBoxes = true;
A: Better use grid view control, but if you want only one column with checkboxes and that column is the first one you can just write:
this.listView1.CheckBoxes = true;
A: You can try TreeViewAdv. It is open source and hosted on sourceforge.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Deleting lines of code in a text editor Edit: This question had been tagged "Tolstoy" in appreciation of the quality and length of my writing:) Just reading the first and the last paragraph should be enough:) If you tend to select and move code with the mouse, the stuff in middle could be interesting to you.
This question is about how you use text editors in general. I’m looking for the best way to delete a plurality of lines of code (no intent to patent it:) This extends to transposing lines, i.e. deleting and adding them somewhere else. Most importantly, I don’t want to be creating any blank lines that I have to delete separately. Sort of like Visual Studio's SHIFT+DELETE feature, but working for multiple lines at once.
Say you want to delete line 3 from following code (tabs and newlines visualized as well). The naïve way would be to select the text between angle brackets:
if (true) {\n
\t int i = 1;\n
\t <i *= 2;>\n
\t i += 3;\n
}\n
Then hit backspace. This creates a blank line. Hit backspace twice more to delete \t and \n.
You end up with:
if (true) {\n
\t int i = 1;\n
\t i += 3;\n
}\n
When you try to select a whole line, Visual Studio doesn't let you select the trailing newline character. For example, placing the cursor on a line and hitting SHIFT+END will not select the newline at the end. Neither will you select the newline if you use your mouse, i.e. clicking in the middle of a line and dragging the cursor all the way to the right. You only select the trailing newline characters if you make a selection that spans at least two lines. Most editors I use do it this way; Microsoft WordPad and Word are counter-examples (and I frequently get newlines wrong when deleting text there; at least Word has a way to display end-of-line and end-of-paragraph characters explicitly).
When using Visual Studio and other editors in general, here’s the solution that currently works best for me:
Using the mouse, I select the characters that I put between angle brackets:
if (true) {\n
\t int i = 1;<\n
\t i *= 2;>\n
\t i += 3;\n
}\n
Hitting backspace now, you delete the line in one go without having to delete any other characters. This works for several contiguous lines at once. Additionally, it can be used for transposing lines. You could drag the selection between the angle brackets to the point marked with a caret:
if (true) {\n
\t int i = 1;<\n
\t i *= 2;>\n
\t i += 3;^\n
}\n
This leaves you with:
if (true) {\n
\t int i = 1;\n
\t i += 3;<\n
\t i *= 2;>\n
}\n
where lines 3 and 4 have switched place.
There are variations on this theme. When you want to delete line 3, you could also select the following characters:
if (true) {\n
\t int i = 1;\n
<\t i *= 2;\n
>\t i += 3;\n
}\n
In fact, this is what Visual Studio does if you tell it to select a complete line. You do this by clicking in the margin between your code and the column where the red circles go which indicate breakpoints. The mouse pointer is mirrored in that area to distinguish it a little better, but I think it's too narrow and physically too far removed from the code I want to select.
Maybe this method is useful to other people as well, even if it only serves to make them aware of how newlines are handled when selecting/deleting text:) It works nicely for most non-specialized text editors. However, given the vast amount of features and plugins for Visual Studio (which I use most), I'm sure there is better way to use it to delete and move lines of code. Getting the indentation right automatically when moving code between different blocks would be nice (i.e. without hitting "Format Document/Selection"). I'm looking forward to suggestions; no rants on micro-optimization, please:)
Summary of Answers
With respect to Visual Studio: Navigating well with the cursor keys.
The solution that would best suit my style of going over and editing code is the Eclipse way:
You can select several consecutive lines of code, where the first and the last selected line may be selected only partially. Pressing ALT+{up,down} moves the complete lines (not just the selection) up and down, fixing indentation as you go. Hitting CTRL+D deletes the lines completely (not just the selection) without leaving any unwanted blank lines. I would love to see this in Visual Studio!
A: In Emacs:
*
*kill-line C-k
*transpose-lines C-x C-t
C-a C-k C-k -- kill whole line including newline (or kill-whole-line by C-S-backspace).
C-u <number> C-k -- kill <number> of lines (including newlines).
C-y -- yank back the most recently killed text (aka paste)
A: In VIM:
*
*Delete the whole line including the newline: dd
*Transpose lines: dd p
You can always prefix any command with a number to repeat it, so to delete 10 lines do:
10 dd
You can also specify a range of lines to delete. For instance, to delete lines 10-15:
:10,15d
Or you can move the lines, for instance move lines 10-15 below line 20:
:10,15m20
Or you can copy the lines:
:10,15t20
A: What I do is, starting with the cursor at the start of the line (in some editors you have to press home twice to do this), hold shift and press down until all lines that I want to delete are selected. Then I press delete.
A: In Eclipse you can ALT-↓ or ALT-↑ to move a line. I find this incredibly useful, as well as ALT-SHIFT-{↓, ↑} to copy a line. In addition, it doesn't wreck your clipboard. It even corrects indentation as the line is moving!
A: Learn to use your cursor keys.
For moving lines I do the following:
*
*Use ↑/↓to move to the line you want to copy.
*Hit Home if not there already, and again if it places the cursor after whitespace.
*Then press Shift+↓ to select the line (or lines) you want to move
*Ctrl+X to cut the line.
*Move Up/Down to the line you want to insert
*Ctrl+V
This should work in pretty much any text editor on Windows.
When deleting lines I still tend to use Ctrl+X (although I guess I also use backspace) as the above is so ingrained in how I edit, and it's also more forgiving.
(Although I find them disorienting on the occasions I use Macs, I think Apple might have been on to something with the way they've set up the Home/End, skip word shortcuts on Macs)
A: Adding to the existing vim answer, you can use d along with any cursor movement command to delete from the cursor's current position to the new position. For example, to delete...
*
*...to end-of-paragraph (usually meaning "to the next blank line"): d}
*...the line containing the cursor and the next 5 lines: d5j
*...a set of parentheses, braces, etc. and its contents: d% (with the cursor on the opening or closing paren/brace/etc.)
*...to the third appearance of the word "foo": d3/foo
It's quite flexible.
A: Using the Brief keyboard mapping this is done using the Alt+L to mark the line and the - key on the numeric keypad (or Alt+D) to cut the line to clipboard. The cut will remove the line entirely, including the newline character.
Hitting the Ins key on the numeric keypad would put the line back into the document including the newline character.
IMHO Brief is a really well designed keyboard mapping.
PS: I think MSVC has an option to emulate the Brief keyboard mapping.
A: in Eclipse i use CTRL+ D to delete a single line (or a couple)
for many lines i'll select them with the mouse or with SHIFT + ARROW then press the DEL key.
A: In addition to the above, use Resharper for Visual Studio to do what you want. Best VS plugin you will find ever. It provides a bunch of different commands that help with moving/deleting/copying code here there and everywhere. Not to mention refactor/generate/etc code.
Ctrl-Shift-Alt ↑or ↓ will move a method up or down, line up or down, etc.
Shift-Del - deletes the current line, but puts it in the clipboard (unless you modify your settings to not do this - I'm trying to recall if this is a VS standard shortcut, not just Resharper - been too long).
Ctrl-C, Ctrl-X without selecting copies/cuts the current line.
And on and on...
See http://www.jetbrains.com/resharper/docs/ReSharper40DefaultKeymap2.pdf for a full list.
A: Ctrl+Shift+L removes line without copying it to the buffer.
A: In Emacs, in addition to C-k (and C-k with a numeric prefix arg, to kill N lines), you can just use the mouse:
*
*To kill one line: triple-click it, then right-click twice
*To kill multiple lines: triple-click the first line, then right-click on the last line ("first" line can be after the "last" line -- "first" here means first one you click)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: python regex to match multi-line preprocessor macro What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.
Here's the regex:
\s*#define(.*\\\n)+[\S]+(?!\\)
It should match all of this:
#define foo(x) if(x) \
doSomething(x)
But only some of this (shouldn't match the next line of code:
#define foo(x) if(x) \
doSomething(x)
normalCode();
And also shouldn't match single-line preprocessor macros.
I'm pretty sure that the regex above works - but as I said, there probably a better way of doing it, and I imagine that there are ways of breaking it. Can anyone suggest any?
A: This is a simple test program I knocked up:
#!/usr/bin/env python
TEST1="""
#include "Foo.h"
#define bar foo\\
x
#include "Bar.h"
"""
TEST2="""
#define bar foo
#define x 1 \\
12 \\
2 \\\\ 3
Foobar
"""
TEST3="""
#define foo(x) if(x) \\
doSomething(x)
"""
TEST4="""
#define foo(x) if(x) \\
doSomething(x)
normalCode();
"""
import re
matcher = re.compile(r"^[ \t]*#define(.*\\\n)+.*$",re.MULTILINE)
def extractDefines(s):
mo = matcher.search(s)
if not mo:
print mo
return
print mo.group(0)
extractDefines(TEST1)
extractDefines(TEST2)
extractDefines(TEST3)
extractDefines(TEST4)
The re I used:
r"^[ \t]*#define(.*\\\n)+.*$"
Is very similar to the one use used, the changes:
*
*[ \t] To avoid newlines at the start
of the define.
*I rely on + being
greedy, so I can use a simple .*$ at
the end to get the first line of the
define that doesn't end with \
A: start = r"^\s*#define\s+"
continuation = r"(?:.*\\\n)+"
lastline = r".*$"
re_multiline_macros = re.compile(start + continuation + lastline,
re.MULTILINE)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to determine the value of a controller variable during execution in Ruby on Rails? What is the best way for me to determine a controller variable's value during execution?
For example, is there a way I can insert a break in the code, and cause the value of the variable to be output to the screen (or the log)?
A: If you have a controller instance variable named @foo, then in your controller you can simply do something like:
logger.debug "@foo is: #{@foo}"
Additionally, you can output the value in your view template using:
<%= debug @foo %>
A: I prefer using the inspect method like so:
raise @foo.inspect
It has more information than to_s, like the attribute values.
A: Summary from Jordi Bunster, John Topley, and Jaryl:
I. Quick and dirty way:
raise @foo.inspect
in your controller. Or
<% raise @foo.inspect %>
in your view.
II. Proper logging to you development.log:
logger.debug "@foo == #{@foo.inspect}"
III. Full-fledged debugging:
Install the debugger (gem install ruby-debug), and then start the development server with the --debugger flag. Then, in your code, call the debugger instruction.
Inside the debugger prompt, you have many commands, including p to print the value of a variable.
A: Yes. The easiest way is to raise the value as a string. Like so: raise @foo.to_s
Or, you can install the debugger (gem install ruby-debug), and then start the development server with the --debugger flag. Then, in your code, call the debugger instruction.
Inside the debugger prompt, you have many commands, including p to print the value of a variable.
Update: here's a bit more about ruby-debug.
A: Raising an exception is the fastest way if you just need to look at a value, but it's worth the time to learn how to use the debugger properly. It's rare that you would only need to just see the value of a variable, you are likely trying to find a bug in your code, and that's what a debugger is for.
Sending the info to the development log is slower than either of the other two options here so far if you learn how to use the debugger (who wants to read through log files). Use the logger for production, you are going to want to see what the value was when somebody calls you up and says everything is broken.
A: Well, I usually prefer the standard error output
$stderr.print("whatever")
Its simple and does the job.
A: *
*Add pry-moves to Gemfile: gem 'pry-moves'
*Insert binding.pry where you want to stop
*Type variable's name to see its value
Then continue by typing c, move to next line with n or perform other debugging actions until you will resolve the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to set up a Subversion (SVN) server on GNU/Linux - Ubuntu I have a laptop running Ubuntu that I would like to act as a Subversion server. Both for myself to commit to locally, and for others remotely. What are the steps required to get this working? Please include steps to:
*
*Get and configure Apache, and necessary modules (I know there are other ways to create a SVN server, but I would like it Apache-specific)
*Configure a secure way of accessing the server (SSH/HTTPS)
*Configure a set of authorised users (as in, they must authorised to commit, but are free to browse)
*Validate the setup with an initial commit (a "Hello world" of sorts)
These steps can involve any mixture of command line or GUI application instructions. If you can, please note where instructions are specific to a particular distribution or version, and where a users' choice of a particular tool can be used instead (say, nano instead of vi).
A: Afterwards, I needed to execute (within the context of the example quoted above)
$ sudo chmod g+w /var/svn/$REPOS/db/rep-cache.db
$ sudo chown www-data:www-data /var/svn/$REPOS/db/rep-cache.db
Otherwise I kept receiving a 409 error when committing local modifications
(though the commitments were server side effective, I needed to follow up with local updates)
A: Steps I've taken to make my laptop a Subversion server. Credit must go to AlephZarro for his directions here. I now have a working SVN server (which has currently only been tested locally).
Specific setup:
Kubuntu 8.04 Hardy Heron
Requirements to follow this guide:
*
*apt-get package manager program
*text editor (I use kate)
*sudo access rights
1: Install Apache HTTP server and required modules:
sudo apt-get install libapache2-svn apache2
The following extra packages will be installed:
apache2-mpm-worker apache2-utils apache2.2-common
2: Enable SSL
sudo a2enmod ssl
sudo kate /etc/apache2/ports.conf
Add or check that the following is in the file:
<IfModule mod_ssl.c>
Listen 443
</IfModule>
3: Generate an SSL certificate:
sudo apt-get install ssl-cert
sudo mkdir /etc/apache2/ssl
sudo /usr/sbin/make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/apache2/ssl/apache.pem
4: Create virtual host
sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/svnserver
sudo kate /etc/apache2/sites-available/svnserver
Change (in ports.conf):
"NameVirtualHost *" to "NameVirtualHost *:443"
and (in svnserver)
<VirtualHost *> to <VirtualHost *:443>
Add, under ServerAdmin (also in file svnserver):
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/apache.pem
SSLProtocol all
SSLCipherSuite HIGH:MEDIUM
5: Enable the site:
sudo a2ensite svnserver
sudo /etc/init.d/apache2 restart
To overcome warnings:
sudo kate /etc/apache2/apache2.conf
Add:
"ServerName $your_server_name"
6: Adding repository(ies):
The following setup assumes we want to host multiple repositories.
Run this for creating the first repository:
sudo mkdir /var/svn
REPOS=myFirstRepo
sudo svnadmin create /var/svn/$REPOS
sudo chown -R www-data:www-data /var/svn/$REPOS
sudo chmod -R g+ws /var/svn/$REPOS
6.a. For more repositories: do step 6 again (changing the value of REPOS), skipping the step mkdir /var/svn
7: Add an authenticated user
sudo htpasswd -c -m /etc/apache2/dav_svn.passwd $user_name
8: Enable and configure WebDAV and SVN:
sudo kate /etc/apache2/mods-available/dav_svn.conf
Add or uncomment:
<Location /svn>
DAV svn
# for multiple repositories - see comments in file
SVNParentPath /var/svn
AuthType Basic
AuthName "Subversion Repository"
AuthUserFile /etc/apache2/dav_svn.passwd
Require valid-user
SSLRequireSSL
</Location>
9: Restart apache server:
sudo /etc/init.d/apache2 restart
10: Validation:
Fired up a browser:
http://localhost/svn/$REPOS
https://localhost/svn/$REPOS
Both required a username and password. I think uncommenting:
<LimitExcept GET PROPFIND OPTIONS REPORT>
</LimitExcept>
in /etc/apache2/mods-available/dav_svn.conf, would allow anonymous browsing.
The browser shows "Revision 0: /"
Commit something:
svn import --username $user_name anyfile.txt https://localhost/svn/$REPOS/anyfile.txt -m “Testing”
Accept the certificate and enter password.
Check out what you've just committed:
svn co --username $user_name https://localhost/svn/$REPOS
Following these steps (assuming I haven't made any error copy/pasting), I had a working SVN repository on my laptop.
A: If you get 403 forbidden when you hit the webserver it may be because you used a hostname that is not what you specified in your config file (ie localhost or 127.0.0.1). Try hitting https://whateveryousetasyourhostname instead...
A: For Apache:
sudo apt-get -yq install apache2
For SSH:
sudo apt-get -yq install openssh-server
For Subversion:
sudo apt-get -yq install subversion subversion-tools
If you'd like you can combine these into one command like:
sudo apt-get -yq install apache2 openssh-server subversion subversion-tools
I can't help with the rest...
A: Please write a single command on the terminal.
To open the terminal please press Ctrl + Alt + T, and then type this command:
$sudo apt-get install subversion
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
} |
Q: Which jQuery plugin should be used to fix the IE6 PNG transparency issue? Is there an IE6/PNG fix that is officially developed by the jQuery team?
If not which of the available plugins should I use?
A: I'm using jquery.pngFix.js. I don't know if it's officially sanctioned or not, I do know that it works. I chose it because it was the plugin included with FancyBox, no other reason.
A: This .htc pngfix has always worked for me, even in cases where the jquery plugin failed.
A: Check this out. Some people mention jQuery plugins in the comments as well.
PNG Fix from 24 Ways
A: Hello Guyz, Here is my Fix to this problem
Download jQuery-Plugin "pngFix" from (http://jquery.andreaseberhard.de)
Great PlugIn By The Way!!!
--Change these lines like the following:
// this line
jQuery(this).find("img[src$=.png]:visible").each(function() {
// this line
jQuery(this).find(":visible").each(function(){
// and this line
jQuery(this).find("input[src$=.png]:visible").each(function() {
--Before the end Place this Code
// Store a reference to the original method.
var _show = jQuery.fn.show;
// Overriding Show method.
jQuery.fn.show = function(){
// Execute the original method.
_show.apply( this, arguments );
// Fix Png
return $(this).pngFix();
}
//No more problems with hidden images
})(jQuery);
//The End
A: Hey guys, just wanted to toss this one in. I was digging around for it again and it has one specific advantage over the rest: repeatable backgrounds, as well as background-position (the one thats flagged as the best answer here actually just scales the background image).
http://www.dillerdesign.com/experiment/DD_belatedPNG/
It's so great. Just drop it in and forget its there. Have yet to see it explode a set of CSS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: c++ Having multiple graphics options Currently my app uses just Direct3D9 for graphics, however in the future I' m planning to extend this to D3D10 and possibly OpenGL. The question is how can I do this in a tidy way?
At present there are various Render methods in my code
void Render(boost::function<void()> &Call)
{
D3dDevice->BeginScene();
Call();
D3dDevice->EndScene();
D3dDevice->Present(0,0,0,0);
}
The function passed then depends on the exact state, eg MainMenu->Render, Loading->Render, etc. These will then oftern call the methods of other objects.
void RenderGame()
{
for(entity::iterator it = entity::instances.begin();it != entity::instance.end(); ++it)
(*it)->Render();
UI->Render();
}
And a sample class derived from entity::Base
class Sprite: public Base
{
IDirect3DTexture9 *Tex;
Point2 Pos;
Size2 Size;
public:
Sprite(IDirect3DTexture9 *Tex, const Point2 &Pos, const Size2 &Size);
virtual void Render();
};
Each method then takes care of how best to render given the more detailed settings (eg are pixel shaders supported or not).
The problem is I'm really not sure how to extend this to be able to use one of, what may be somewhat different (D3D v OpenGL) render modes...
A: Define an interface that is sufficient for your application's graphic output demands. Then implement this interface for every renderer you want to support.
class IRenderer {
public:
virtual ~IRenderer() {}
virtual void RenderModel(CModel* model) = 0;
virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) = 0;
// ...etc...
};
class COpenGLRenderer : public IRenderer {
public:
virtual void RenderModel(CModel* model) {
// render model using OpenGL
}
virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) {
// draw screen aligned quad using OpenGL
}
};
class CDirect3DRenderer : public IRenderer {
// similar, but render using Direct3D
};
Properly designing and maintaining these interfaces can be very challenging though.
In case you also operate with render driver dependent objects like textures, you can use a factory pattern to have the separate renderers each create their own implementation of e.g. ITexture using a factory method in IRenderer:
class IRenderer {
//...
virtual ITexture* CreateTexture(const char* filename) = 0;
//...
};
class COpenGLRenderer : public IRenderer {
//...
virtual ITexture* CreateTexture(const char* filename) {
// COpenGLTexture is the OpenGL specific ITexture implementation
return new COpenGLTexture(filename);
}
//...
};
Isn't it an idea to look at existing (3d) engines though? In my experience designing this kind of interfaces really distracts from what you actually want to make :)
A: I'd say if you want a really complete the answer, go look at the source code for Ogre3D. They have both D3D and OpenGL back ends. Look at : http://www.ogre3d.org
Basically their API kind of forces you into working in a D3D-ish way, creating buffer objects and stuffing them with data, then issuing draw calls on those buffers. That's the way the hardware likes it anyway, so it's not a bad way to go.
And then once you see how they do things, you might as well just just go ahead and use it and save yourself the trouble of having to re-implement all that it already provides. :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Best way to handle user account authentication and passwords What is the best way to handle user account management in a system, without having your employees who have access to a database, to have access to the accounts.
Examples:
*
*Storing username/password in the database. This is a bad idea because anyone that has access to a database can see the username and password. And hence use it.
*Storing username/password hash. This is a better method, but the account can be accessed by replacing the password hash in the database with the hash of another account that you know the auth info for. Then after access is granted reverting it back in the database.
How does windows/*nix handle this?
A:
This is a better method, but the account can be accessed by replacing the password hash in the database with the hash of another account that you know the auth info for.
There's really no way around this. Anyone who as write access to the password file has complete control of the computer.
A: I'd go with 2 but use some salt. Some pseudocode:
SetPassword(user, password)
salt = RandomString()
hash = Hashfunction(salt+password)
StoreInDatabase(user, salt, hash)
CheckPassword(user, password)
(salt, hash) = GetFromDatabase(user)
if Hashfunction(salt+password) == hash
return "Success"
else
return "Login Failed"
It is important to use a well known hash function (such as MD5 or SHA-1), implemented in a library. Don't roll your own or try implementing it from a book its just not worth the risk of getting it wrong.
@Brian R. Bondy: The reason you use salt is to make dictionary attaks harder, the attacker can't hash a dictionary and try against all the passwords, instead she have to take the salt + the dictionary and hash it, which makes the storage requierments expode. If you have a dictionary of the 1000 most commaon passwords and hash them you need something like 16 kB but if you add two random letters you get 62*62*16 kB ≈ 62 Mb.
Else you could use some kind of One-time passwords I have heard good things about OTPW but havent used it.
A: This was a common issue in UNIX many years ago, and was resolved by separating the user identity components (username, UID, shell, full name, etc.) from the authentication components (password hash, password hash salt). The identity components can be globally readable (and in fact must be, if UIDs are to be mapped to usernames), but the authentication components must be kept inaccessible to users. To authenticate a user, have a trusted system which will accept a username and password, and will return a simple result of "authenticated" or "not authenticated". This system should be the only application with access to the authentication database, and should wait for a random amount of time (perhaps between 0.1 and 3 seconds) before replying to help avoid timing attacks.
A: You could use openID and save no confidential user passwords at all. Who said it is for websites only?
A: Jeff Atwood has some good posts concerning hashing, if you decide to go that route:
*
*Rainbow Hash Cracking
*You're Probably Storing Passwords Incorrectly
A: *
*A very bad idea indeed. If the database is compromised, all accounts are compromised.
*Good way to go. If your hash algorithm includes the username, replacing the password hash with another one will not work.
Unix stores hashes in a a text file /etc/shadow, which is accessible only to privileged users. Passwords are encrypted with a salt.
A: You could store the salt for the hashed password in another table, of course each user would have their own salt. You could then limit access to that table.
A: The usual approach is to use option two with email:
Store user name, password hash and email address into the database.
Users can either input their password or reset it, in the latter case a random password is generated, a new hash is created for the user and the password is sent to him via email.
Edit: If the database is compromised then you can only guarantee no sensible information can be accessed, you can no longer ensure the security of your application.
A: Hash the username and the password together. That way, if two users have the same password, the hashes will still be different.
A: This is a bit of a non problem for a lot of applications because gaining access to the database is probably the most common goal of any attacker. So if they already have access to the database why would they still want to login to the application ? :)
A: If the 'system' is a public website RPX can provide you with a login/user account services for the most common providers, like OpenId, Facebook, Google, etc.
Now, given the way you formulate your question I guess the 'system' you're talking about is more likely an internal windows/linux based enterprise app. Nevertheless; for those googling around for login/user account providers (like I did before a came across RPX), this could be a good fit :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Learning kernel hacking and embedded development at home? I was always attracted to the world of kernel hacking and embedded systems.
Has anyone got good tutorials (+easily available hardware) on starting to mess with such stuff?
Something like kits for writing drivers etc, which come with good documentation and are affordable?
Thanks!
A: An absolute must is this book by Rubini. (available both as a hardcopy or a free soft copy)
He gives implementations of several dummy drivers that don't require that you have any hardware other than your pc. So for getting started in kernel development it's the easiest way to go.
As for doing embedded work I would recommend purchasing one of the numerous SBC (single board computers) that are out there. There are a number of these that are based on x86 processors, usually with PC/104 interfaces (electrically PC/104 is identical to the ISA bus standard, but based on stackable connectors rather than edge connectors - very easy to interface custom hardware to)
They usually have vga connectors that make it easier to do debugging.
A: If you are completely new to kernel development, i would suggest not starting with hardware development and going to some "software-only" kernel modules like proc file / sysfs or for more complex examples filesystem / network development , developing on a uml/vmware/virtualbox/... machine so crashing your machine won't hurt so much :) For embedded development you could go for a small ARM Development Kit or a small Via C3/C4 machine, or any old PC which you can burn with your homebrew USB / PCI / whatever device.
A good place to start is probably Kernelnewbies.org - which has lots of links and useful information for kernel developers, and also features a list of easy to implement tasks to tackle for beginners.
Some books to read:
Understanding the Linux Kernel - a very good reference detailing the design of the kernel subsystems
Linux Device Drivers - is written more like a tutorial with a lot of example code, focusing on getting you going and explaining key aspects of the linux kernel. It introduces the build process and the basics of kernel modules.
Linux Kernel Module Programming Guide - Some more introductory material
As suggested earlier, looking at the linux code is always a good idea, especially as Linux Kernel API's tend to change quite often ... LXR helps a lot with a very nice browsing interface - lxr.linux.no
To understand the Kernel Build process, this link might be helpful:
Linux Kernel Makefiles (kbuild)
Last but not least, browse the Documentation directory of the Kernel Source distribution!
Here are some interesting exercises insolently stolen from a kernel development class:
*
*Write a kernel module which creates the file /proc/jiffies reporting the current time in jiffies on every read access.
*Write a kernel module providing the proc file /proc/sleep. When an application writes a number of seconds as ASCII text into this file ("echo 3 > /proc/sleep"), it should block for the specified amount of seconds. Write accesses should have no side effect on the contents of the file, i.e., on the read accesses, the file should appear to be empty (see LDD3, ch. 6/7)
*Write a proc file where you can store some text temporarily (using echo "blah" > /proc/pipe) and get it out again (cat /proc/pipe), clearing the file. Watch out for synchronisation issues.
*Modify the pipe example module to register as a character device /dev/pipe, add dynamic memory allocation for write requests.
*Write a really simple file system.
A: For embedded Linux hacking, simple Linksys WRT54G router that you can buy everywhere is a development platform on its own http://en.wikipedia.org/wiki/Linksys_WRT54G_series:
The WRT54G is notable for being the first consumer-level network device that had its firmware source code released to satisfy the obligations of the GNU GPL. This allows programmers to modify the firmware to change or add functionality to the device. Several third-party firmware projects provide the public with enhanced firmware for the WRT54G.
I've tried installing OpenWrt and DD-WRT firmware on it. You can check those out as a starting point for hacking on a low-cost platform.
A: For starters, the best way is to read a lot of code. Since Linux is Open Source, you'll find dozens of drivers. Find one that works in some ways like what you want to write. You'll find some decent and relatively easy-to-understand code (the loopback device, ROM fs, etc.)
You can also use the lxr.linux.no, which is the Linux code cross-referenced. If you have to find out how something works, and need to look into the code, this is a good and easy way.
There's also an O'Reilly book (Understanding the Linux Kernel, the 3rd edition is about the 2.6 kernels) or if you want something for free, you can use the Advanced Linux Programing book (http://www.advancedlinuxprogramming.com/). There are also a lot of specific documentation about file systems, networking, etc.
A: Some things to be prepared for:
*
*you'll be cross-compiling. The embedded device will use a MIPS, PowerPC, or ARM CPU but won't have enough CPU power, memory, or storage to compile its own kernel in a reasonable amount of time.
*An embedded system often uses a serial port as the console, and to lower the cost there is usually no connector soldered onto production boards. Debugging kernel panics is very difficult unless you can solder on a serial port connector, you won't have much information about what went wrong.
The Linksys NSLU2 is a low-cost way to get a real embedded system to work with, and has a USB port to add peripherals. Any of a number of wireless access points can also be used, see the OpenWrt compatibility page. Be aware that current models of the Linksys WRT54G you'll find in stores can no longer be used with Linux: they have less RAM and Flash in order to reduce the cost. Cisco/Linksys now uses vxWorks on the WRT54G, with a smaller memory footprint.
If you really want to get into it, evaluation kits for embedded CPUs start at a couple hundred US dollars. I'd recommend not spending money on these unless you need it professionally for a job or consulting contract.
A: I am completely beginner in kernel hacking :) I decided to buy two books "Linux Program Development: a guide with exercises" and "Writing Linux Device Drivers: a guide with exercises" They are very clearly written and provide good base to further learning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: How to load JAR files dynamically at Runtime? Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own ClassLoader, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument.
Any suggestions for simple code that does this?
A: The best I've found is org.apache.xbean.classloader.JarFileClassLoader which is part of the XBean project.
Here's a short method I've used in the past, to create a class loader from all the lib files in a specific directory
public void initialize(String libDir) throws Exception {
File dependencyDirectory = new File(libDir);
File[] files = dependencyDirectory.listFiles();
ArrayList<URL> urls = new ArrayList<URL>();
for (int i = 0; i < files.length; i++) {
if (files[i].getName().endsWith(".jar")) {
urls.add(files[i].toURL());
//urls.add(files[i].toURI().toURL());
}
}
classLoader = new JarFileClassLoader("Scheduler CL" + System.currentTimeMillis(),
urls.toArray(new URL[urls.size()]),
GFClassLoader.class.getClassLoader());
}
Then to use the classloader, just do:
classLoader.loadClass(name);
A: If you are working on Android, the following code works:
String jarFile = "path/to/jarfile.jar";
DexClassLoader classLoader = new DexClassLoader(jarFile, "/data/data/" + context.getPackageName() + "/", null, getClass().getClassLoader());
Class<?> myClass = classLoader.loadClass("MyClass");
A: I know I'm late to the party, but I have been using pf4j, which is a plug-in framework, and it works pretty well.
PF4J is a microframework and the aim is to keep the core simple but extensible.
An example of plugin usage:
Define an extension point in your application/plugin using ExtensionPoint interface marker:
public interface Greeting extends ExtensionPoint {
String getGreeting();
}
Create an extension using @Extension annotation:
@Extension
public class WelcomeGreeting implements Greeting {
public String getGreeting() {
return "Welcome";
}
}
Then you can load and unload the plugin as you wish:
public static void main(String[] args) {
// create the plugin manager
PluginManager pluginManager = new JarPluginManager(); // or "new ZipPluginManager() / new DefaultPluginManager()"
// start and load all plugins of application
pluginManager.loadPlugins();
pluginManager.startPlugins();
// retrieve all extensions for "Greeting" extension point
List<Greeting> greetings = pluginManager.getExtensions(Greeting.class);
for (Greeting greeting : greetings) {
System.out.println(">>> " + greeting.getGreeting());
}
// stop and unload all plugins
pluginManager.stopPlugins();
pluginManager.unloadPlugins();
}
For further details please refer to the documentation
A: You should take a look at OSGi, e.g. implemented in the Eclipse Platform. It does exactly that. You can install, uninstall, start and stop so called bundles, which are effectively JAR files. But it does a little more, as it offers e.g. services that can be dynamically discovered in JAR files at runtime.
Or see the specification for the Java Module System.
A: Another working solution using Instrumentation that works for me. It has the advantage of modifying the class loader search, avoiding problems on class visibility for dependent classes:
Create an Agent Class
For this example, it has to be on the same jar invoked by the command line:
package agent;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.util.jar.JarFile;
public class Agent {
public static Instrumentation instrumentation;
public static void premain(String args, Instrumentation instrumentation) {
Agent.instrumentation = instrumentation;
}
public static void agentmain(String args, Instrumentation instrumentation) {
Agent.instrumentation = instrumentation;
}
public static void appendJarFile(JarFile file) throws IOException {
if (instrumentation != null) {
instrumentation.appendToSystemClassLoaderSearch(file);
}
}
}
Modify the MANIFEST.MF
Adding the reference to the agent:
Launcher-Agent-Class: agent.Agent
Agent-Class: agent.Agent
Premain-Class: agent.Agent
I actually use Netbeans, so this post helps on how to change the manifest.mf
Running
The Launcher-Agent-Class is only supported on JDK 9+ and is responsible for loading the agent without explicitly defining it on the command line:
java -jar <your jar>
The way that works on JDK 6+ is defining the -javaagent argument:
java -javaagent:<your jar> -jar <your jar>
Adding new Jar at Runtime
You can then add jar as necessary using the following command:
Agent.appendJarFile(new JarFile(<your file>));
I did not find any problems using this on documentation.
A: While most solutions listed here are either hacks (pre JDK 9) hard to configure (agents) or just don't work anymore (post JDK 9) I find it really surprising that nobody mentioned a clearly documented method.
You can create a custom system class loader and then you're free to do whatever you wish. No reflection required and all classes share the same classloader.
When starting the JVM add this flag:
java -Djava.system.class.loader=com.example.MyCustomClassLoader
The classloader must have a constructor accepting a classloader, which must be set as its parent. The constructor will be called on JVM startup and the real system classloader will be passed, the main class will be loaded by the custom loader.
To add jars just call ClassLoader.getSystemClassLoader() and cast it to your class.
Check out this implementation for a carefully crafted classloader. Please note, you can change the add() method to public.
A: How about the JCL class loader framework? I have to admit, I haven't used it, but it looks promising.
Usage example:
JarClassLoader jcl = new JarClassLoader();
jcl.add("myjar.jar"); // Load jar file
jcl.add(new URL("http://myserver.com/myjar.jar")); // Load jar from a URL
jcl.add(new FileInputStream("myotherjar.jar")); // Load jar file from stream
jcl.add("myclassfolder/"); // Load class folder
jcl.add("myjarlib/"); // Recursively load all jar files in the folder/sub-folder(s)
JclObjectFactory factory = JclObjectFactory.getInstance();
// Create object of loaded class
Object obj = factory.create(jcl, "mypackage.MyClass");
A: The solution proposed by jodonnell is good but should be a little bit enhanced. I used this post to develop my application with success.
Assign the current thread
Firstly we have to add
Thread.currentThread().setContextClassLoader(classLoader);
or you will not able to load resource (such as spring/context.xml) stored into the jar.
Do not include
your jars into the parent class loader or you will not able to understand who is loading what.
see also Problem reloading a jar using URLClassLoader
However, OSGi framework remain the best way.
A: Another version of the hackish solution from Allain, that also works on JDK 11:
File file = ...
URL url = file.toURI().toURL();
URLClassLoader sysLoader = new URLClassLoader(new URL[0]);
Method sysMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
sysMethod.setAccessible(true);
sysMethod.invoke(sysLoader, new Object[]{url});
On JDK 11 it gives some deprecation warnings but serves as a temporary solution those who use Allain solution on JDK 11.
A: In case anyone searches for this in the future, this way works for me with OpenJDK 13.0.2.
I have many classes that I need to instantiate dynamically at runtime, each potentially with a different classpath.
In this code, I already have an object called pack, that holds some metadata about the class I am trying to load. The getObjectFile() method returns the location of the class file for the class. The getObjectRootPath() method returns the path to the bin/ directory containing the class files that include the class I am trying to instantiate. The getLibPath() method returns the path to a directory containing the jar files constituting the classpath for the module the class is a part of.
File object = new File(pack.getObjectFile()).getAbsoluteFile();
Object packObject;
try {
URLClassLoader classloader;
List<URL> classpath = new ArrayList<>();
classpath.add(new File(pack.getObjectRootPath()).toURI().toURL());
for (File jar : FileUtils.listFiles(new File(pack.getLibPath()), new String[] {"jar"}, true)) {
classpath.add(jar.toURI().toURL());
}
classloader = new URLClassLoader(classpath.toArray(new URL[] {}));
Class<?> clazz = classloader.loadClass(object.getName());
packObject = clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return packObject;
I was using the Maven dependency: org.xeustechnologies:jcl-core:2.8 to do this before, but after moving past JDK 1.8, it sometimes froze and never returned being stuck "waiting for references" at Reference::waitForReferencePendingList().
I am also keeping a map of class loaders so that they can be reused if the class I am trying to instantiate is in the same module as a class that I have already instantiated, which I would recommend.
A: The reason it's hard is security. Classloaders are meant to be immutable; you shouldn't be able to willy-nilly add classes to it at runtime. I'm actually very surprised that works with the system classloader. Here's how you do it making your own child classloader:
URLClassLoader child = new URLClassLoader(
new URL[] {myJar.toURI().toURL()},
this.getClass().getClassLoader()
);
Class classToLoad = Class.forName("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod("myMethod");
Object instance = classToLoad.newInstance();
Object result = method.invoke(instance);
Painful, but there it is.
A: please take a look at this project that i started: proxy-object lib
This lib will load jar from file system or any other location. It will dedicate a class loader for the jar to make sure there are no library conflicts. Users will be able to create any object from the loaded jar and call any method on it.
This lib was designed to load jars compiled in Java 8 from the code base that supports Java 7.
To create an object:
File libDir = new File("path/to/jar");
ProxyCallerInterface caller = ObjectBuilder.builder()
.setClassName("net.proxy.lib.test.LibClass")
.setArtifact(DirArtifact.builder()
.withClazz(ObjectBuilderTest.class)
.withVersionInfo(newVersionInfo(libDir))
.build())
.build();
String version = caller.call("getLibVersion").asString();
ObjectBuilder supports factory methods, calling static functions, and call back interface implementations.
i will be posting more examples on the readme page.
A: This can be a late response, I can do it as this (a simple example for fastutil-8.2.2.jar) using jhplot.Web class from DataMelt (http://jwork.org/dmelt)
import jhplot.Web;
Web.load("http://central.maven.org/maven2/it/unimi/dsi/fastutil/8.2.2/fastutil-8.2.2.jar"); // now you can start using this library
According to the documentation, this file will be download inside "lib/user" and then dynamically loaded, so you can start immediately using classes from this jar file in the same program.
A: Here is a version that is not deprecated. I modified the original to remove the deprecated functionality.
/**************************************************************************************************
* Copyright (c) 2004, Federal University of So Carlos *
* *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted *
* provided that the following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of *
* conditions and the following disclaimer. *
* * Redistributions in binary form must reproduce the above copyright notice, this list of *
* * conditions and the following disclaimer in the documentation and/or other materials *
* * provided with the distribution. *
* * Neither the name of the Federal University of So Carlos nor the names of its *
* * contributors may be used to endorse or promote products derived from this software *
* * without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR *
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
**************************************************************************************************/
/*
* Created on Oct 6, 2004
*/
package tools;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
/**
* Useful class for dynamically changing the classpath, adding classes during runtime.
*/
public class ClasspathHacker {
/**
* Parameters of the method to add an URL to the System classes.
*/
private static final Class<?>[] parameters = new Class[]{URL.class};
/**
* Adds a file to the classpath.
* @param s a String pointing to the file
* @throws IOException
*/
public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}
/**
* Adds a file to the classpath
* @param f the file to be added
* @throws IOException
*/
public static void addFile(File f) throws IOException {
addURL(f.toURI().toURL());
}
/**
* Adds the content pointed by the URL to the classpath.
* @param u the URL pointing to the content to be added
* @throws IOException
*/
public static void addURL(URL u) throws IOException {
URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Class<?> sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL",parameters);
method.setAccessible(true);
method.invoke(sysloader,new Object[]{ u });
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}
}
public static void main(String args[]) throws IOException, SecurityException, ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
addFile("C:\\dynamicloading.jar");
Constructor<?> cs = ClassLoader.getSystemClassLoader().loadClass("test.DymamicLoadingTest").getConstructor(String.class);
DymamicLoadingTest instance = (DymamicLoadingTest)cs.newInstance();
instance.test();
}
}
A: With Java 9, the answers with URLClassLoader now give an error like:
java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClassLoader
This is because the class loaders used have changed. Instead, to add to the system class loader, you can use the Instrumentation API through an agent.
Create an agent class:
package ClassPathAgent;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.util.jar.JarFile;
public class ClassPathAgent {
public static void agentmain(String args, Instrumentation instrumentation) throws IOException {
instrumentation.appendToSystemClassLoaderSearch(new JarFile(args));
}
}
Add META-INF/MANIFEST.MF and put it in a JAR file with the agent class:
Manifest-Version: 1.0
Agent-Class: ClassPathAgent.ClassPathAgent
Run the agent:
This uses the byte-buddy-agent library to add the agent to the running JVM:
import java.io.File;
import net.bytebuddy.agent.ByteBuddyAgent;
public class ClassPathUtil {
private static File AGENT_JAR = new File("/path/to/agent.jar");
public static void addJarToClassPath(File jarFile) {
ByteBuddyAgent.attach(AGENT_JAR, String.valueOf(ProcessHandle.current().pid()), jarFile.getPath());
}
}
A: The following solution is hackish, as it uses reflection to bypass encapsulation, but it works flawlessly:
File file = ...
URL url = file.toURI().toURL();
URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, url);
A: Here is a quick workaround for Allain's method to make it compatible with newer versions of Java:
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
try {
Method method = classLoader.getClass().getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, new File(jarPath).toURI().toURL());
} catch (NoSuchMethodException e) {
Method method = classLoader.getClass()
.getDeclaredMethod("appendToClassPathForInstrumentation", String.class);
method.setAccessible(true);
method.invoke(classLoader, jarPath);
}
Note that it relies on knowledge of internal implementation of specific JVM, so it's not ideal and it's not a universal solution. But it's a quick and easy workaround if you know that you are going to use standard OpenJDK or Oracle JVM. It might also break at some point in future when new JVM version is released, so you need to keep that in mind.
A: I needed to load a jar file at runtime for both java 8 and java 9+ (above comments don't work for both of these versions). Here is the method to do it (using Spring Boot 1.5.2 if it may relate).
public static synchronized void loadLibrary(java.io.File jar) {
try {
java.net.URL url = jar.toURI().toURL();
java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
method.setAccessible(true); /*promote the method to public access*/
method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});
} catch (Exception ex) {
throw new RuntimeException("Cannot load library from jar file '" + jar.getAbsolutePath() + "'. Reason: " + ex.getMessage());
}
}
A: For dynamic uploading of jar files, you can use my modification of URLClassLoader. This modification has no problem with changing the jar file during application operation, like the standard URLClassloader. All loaded jar files are loaded into RAM and thus independent of the original file.
In-memory jar and JDBC class loader
A: I personally find that java.util.ServiceLoader does the job pretty well. You can get an example here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "366"
} |
Q: Unable to load System.Data.Linq.dll for CodeDom I am trying to dynamicaly compile code using CodeDom. I can load other assemblies, but I cannot load System.Data.Linq.dll. I get an error:
Metadata file 'System.Data.Linq.dll' could not be found
My code looks like:
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.CompilerOptions = "/target:library /optimize";
compilerParams.GenerateExecutable = false;
compilerParams.GenerateInMemory = true;
compilerParams.IncludeDebugInformation = false;
compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("System.Data.Linq.dll");
Any ideas?
A: That may be because this assembly is stored in a different location than mscorlib is. It should work if you provide a full path to the assembly. The most convenient way to get the full path is to let the .NET loader do the work for you. I would try something like this:
compilerParams.ReferencedAssemblies.Add(typeof(DataContext).Assembly.Location);
A: This may be a silly answer, but are you sure the code is running on a machine with .NET Framework 3.5?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is help file (or user manual) dead? Back in the days of Unix, you couldn't even close a software without reading the man page first. Then came Mac and Windows with consistent menu layout and keyboard shortcuts, but you still saw paper user manuals shipped in the shrinkwrap box, which described each and every single operation possible in the app. After the Internet, help files became html documents.
Nowadays with Web 2.0 applications, you hardly see the Help. Even if it's there, they simply describe some specific tasks. In other words, the apps are relying more on the common sense or don't-make-me-think factor of the user base.
Years ago Microsoft came up with a concept called Inductive User Interface, which basically tells programmers to put in instructions on the apps itself, but I am not sure how popular that idea is.
Are help files, user manuals, and context sensitive online help with F1 key dead? Have I failed if user could not find out what to do from the UI? If not, what degree of help should I provide? (both for desktop and web app)
EDIT: How does documentation/help file mesh with agile development methods? For example, should the developers think twice before UI changes that may obsolete a bunch of screenshots?
A: No way. You look at the amount of documentation and training and marketing expenditure even MS puts up.. you'll get your answer.
Try using someone else's product, and you will learn the true value of documentation - I'm learning Godiagrams right now.. :)
So I can say without a doubt.. NO and it never will.. no matter how intuitive user interfaces get.. beyond a certain size, you will need help and training. But by understanding the user and what he needs to get done, you could design it such that the time he/she needs to learn the system to do his/her routine tasks is minimal.
A: Three notes on help:
*
*F1 / stand-alone context-sensitive help was always doomed. It was hidden by default, and so the people who most needed it were least likely to read it. There was hope at one time that we would be able to train users to always hit F1 when they ran into trouble, but too many applications without useful context-sensitive help... combined with too many bizarre help interfaces... pretty much killed this.
*Manuals are as important now as they ever were. Not so many printed manuals anymore, but online manuals are better than ever. The proliferation of wiki-as-a-manual systems has helped here, reducing the up-front cost of creating good online documentation. Of course, plenty of people just don't read...
*The beauty of using web pages as an application interface is that you can combine useful context-sensitive help with the UI, removing the barrier for novices and others who otherwise couldn't be bothered to look for relevant information when they get stuck.
Of course, there are still plenty of apps, even online apps, designed with obtuse interfaces and a tiny little help icon in a corner somewhere, presumably hoping that the latter mitigates the former. Pity them.
A:
Have I failed if user could not find out what to do from the UI?
If not, what degree of help should I provide? (both for desktop and web app)
They should be able to use your your app to do basic things from the UI. eg say for an image editor, they should be able to create a new image, and draw some lines then save it just by looking at the UI.
This is best done by following common layouts (like having new, open and save under file in the menubar, and using the standard open and save dialogs).
The same goes for webapps, people exspect to be able to do the basic stuff without having to read the docs, but for more advanced features people will still read the docs. (eg most pople will read the docs for say BB code, or markdown at least sometimes, but they expect to be able to post without having to know them)
Are help files, user manuals, and context sensitive online help with F1 key dead?
They still have their place. People will use them to learn about how to best use various features, for example markdown or bbcode, or how to use filters to get certain effects in an image editor.
A: I've been incorporating context-sensitive screencasts into my applications. I've found this helps non-technical users grasp the application quickly, without asking for live help.
A: The Idiot/Dummy books must be doing quite well. Imagine if the standard application help was as good as those books. The standard F1 help for a lot of apps is just awful.
Is help dead? No, but some of it should be taken out and shot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: How do you do fuzzy searches using bound parameters in PDO? Trying to do this sort of thing...
WHERE username LIKE '%$str%'
...but using bound parameters to prepared statements in PDO. e.g.:
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
I've tried numerous permutations of single quotes and % signs and it's just getting cross with me.
I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?
A: 5 years later, in case anyone else stumbles upon this, there is an alternative method I've discovered. The accepted solution wasn't really feasible for my situation, but this method seems to get the job done as well:
$query = $db->prepare("select * FROM table WHERE field LIKE CONCAT('%',:search,'%')");
$query->bindParam(':search', $str);
$query->execute();
I'm not sure if there will be a performance hit due to the overhead of calling the CONCAT function, but I wanted to pass this along as an option. Hopefully it will help someone.
A: Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:
$str = "%$str%";
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How can I show a grey transparent overlay in C#? How can I show a grey transparent overlay in C#?
It should overlay other process which are not owned by the application doing the overlay.
A: Create a transparent window the size of the whole screen, mark it always-on-top, calculate the regions of your other application windows, and make the non-window regions of the top window grey.
I suppose you could just position your own application windows on top of the transparent grey one, with it being above all the other ones, but getting a tricky z-order scenario like that right, especially in conjunction with other apps that might also be doing z-order tricks, is tough.
A: Here a little app which do more or less the functionnality you want :
http://www.anappaday.com/downloads/2006/09/day-10-jedi-concentrate.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I listen in on shortcuts when the app is the task bar in C# An example of an app that does this is Enso, it pops up when you press the caps lock.
A: You can act on global hotkeys by calling the winapi function RegisterHotKey. Also see https://www.codeproject.com/Articles/4345/NET-system-wide-hotkey-component and https://www.codeproject.com/Articles/3055/System-Hotkey-Component for example. You can not use all key combination as hotkeys. For those that don't work you might try a global keyboard hook (SetWindowsHookEx)
A: You need to install a hook in user32.dll. Lookup the Win32-API call SetWindowsHookEx. You can call it from C# via the stuff in System.Runtime.InteropServices.
This article discusses the topic nicely.
Edit: Lars Truijens answer looks like a nicer approach actually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Scriptaculous Ajax.Autocompleter extra functionality in LI I'm using the Ajax.Autocompleter class from the Prototype/Scriptaculous library which calls an ASP.NET WebHandler which creates an unordered list with list items that contain suggestions.
Now I'm working on a page where you can add suggestions to a 'stop words' table, which means that if they occur in the table, they won't be suggested anymore.
I put a button inside the LI elements and when you click on it it should do an ajax request to a page which then adds the word to the table. That works. But then I want the suggestions to be refreshed instantly, so that the suggestions appear without the word just added to the table. Preferably the selected word is the word next or before the previously clicked word.
How do I do this? What happens instead now is that the LI you clicked the button of gets to be the selected word and the suggestions disappear.
The list items look like this:
<li>{0}
<img onclick=\"deleteWord('{0}');\" src=\"delete.gif\"/>
</li>
Where {0} represents the suggested word. The JavaScript function deleteWord(w) gets to call the webhandler which can add the word to the 'stop words' table.
A: Scriptaculous Autocompleter monitors the onclick event on the 'li'. When you stick an image inside an 'li', both the 'img' and the 'li' will get the click event, as this demonstrates. That's why Autocompleter is just doing its normal thing when the button is clicked:
<ul>
<li onclick="alert('li');">
<img onclick="alert('image')" src="blah.gif"/>
</li>
</ul>
What I'd try is to have your 'onclick' set some sort of state variable that tells you that Delete has been clicked. Then, override 'updateElement' in the Autocompleter to not do anything if the state is set. An alternative is to subclass the entire Autocompleter and override 'onClick'. That will make the list not disappear when your image is clicked.
To have the list update in real-time, in your image's 'onclick', delete the 'li' from the list in the DOM too. Like this conceptually:
img onclick="deleteWord('blah');setStateVariable();this.parentNode.parentNode.removeChild(this.parentNode);"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Installing Curl IDE/RTE on AMD processors Trying to move my development environment to Linux. And new to Curl. Can't get it to install the IDE & RTE packages on an AMD HP PC running Ubuntu x64. I tried to install the Debian package via the package installer and get "Error: Wrong architecture - i386". Tried using the --force-architecture switch but it errors out.
I'm assuming Curl IDE will just run under Intel processors? Anyone have any luck with this issue and can advise?
A: It's been a while since I ran linux, but try looking for the x64 version. There are also x64 to x86 compatibility libraries available that should make 32 bit programs work for most situations.
The ubuntu forums are a much better place for this question, however.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linq to NHibernate multiple OrderBy calls I'm having trouble ordering by more than one field in my Linq to NHibernate query. Does anyone either know what might be wrong or if there is a work around?
Code:
IQueryable<AgendaItem> items = _agendaRepository.GetAgendaItems(location)
.Where(item => item.Minutes.Contains(query) || item.Description.Contains(query));
int total = items.Count();
var results = items
.OrderBy(item => item.Agenda.Date)
.ThenBy(item => item.OutcomeType)
.ThenBy(item => item.OutcomeNumber)
.Skip((page - 1)*pageSize)
.Take(pageSize)
.ToArray();
return new SearchResult(query, total, results);
I've tried replacing ThenBy with multiple OrderBy calls. Same result. The method works great if I comment out the two ThenBy calls.
Error I'm receiving:
[SqlException (0x80131904): Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.
Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
[ADOException: could not execute query
[ SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc ]
Positional parameters: #0>1 #0>%Core% #0>%Core%
[SQL: SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc]]
NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +258
NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18
NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +87
NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) +342
NHibernate.Impl.CriteriaImpl.List(IList results) +41
NHibernate.Impl.CriteriaImpl.List() +35
NHibernate.Linq.CriteriaResultReader`1.List() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:22
NHibernate.Linq.d__0.MoveNext() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:27
A: This looks to me like a bug with Linq to NHybernate. One possible workaround is to convert to an array before sorting. A potentially big downside is that you can't limit the results using Skip() and Take() before enumerating, so this may not be sufficient for you.
var results = items
.ToArray()
.OrderBy(item => item.Agenda.Date)
.ThenBy(item => item.OutcomeType)
.ThenBy(item => item.OutcomeNumber)
.Skip((page - 1)*pageSize)
.Take(pageSize)
A: although i dont think it'd make a difference, what happens if you do your linq like this:
(from i in items orderby i.prop1, i.prop2, i.prop3).Skip(...).Take(...).ToArray();
A: Turning it first into array might be an acceptable solution in case if your result set is comparatively small. But if you want to make SQL server do the job, you better do it this way:
var results = items
.OrderBy(item => item.Agenda.Date).Asc
.ThenBy(item => item.OutcomeType).Asc
.ThenBy(item => item.OutcomeNumber).Asc
.Skip((page - 1)*pageSize)
.Take(pageSize)
.ToArray();
You should always add Asc or Desc modifier afterwards whenever you use OrderBy or OrderByAlias method in NHibernate dialect of Linq.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Getting random row through SQLAlchemy How do I select one or more random rows from a table using SQLAlchemy?
A: Some SQL DBMS, namely Microsoft SQL Server, DB2, and PostgreSQL have implemented the SQL:2003 TABLESAMPLE clause. Support was added to SQLAlchemy in version 1.1. It allows returning a sample of a table using different sampling methods – the standard requires SYSTEM and BERNOULLI, which return a desired approximate percentage of a table.
In SQLAlchemy FromClause.tablesample() and tablesample() are used to produce a TableSample construct:
# Approx. 1%, using SYSTEM method
sample1 = mytable.tablesample(1)
# Approx. 1%, using BERNOULLI method
sample2 = mytable.tablesample(func.bernoulli(1))
There's a slight gotcha when used with mapped classes: the produced TableSample object must be aliased in order to be used to query model objects:
sample = aliased(MyModel, tablesample(MyModel, 1))
res = session.query(sample).all()
Since many of the answers contain performance benchmarks, I'll include some simple tests here as well. Using a simple table in PostgreSQL with about a million rows and a single integer column, select (approx.) 1% sample:
In [24]: %%timeit
...: foo.select().\
...: order_by(func.random()).\
...: limit(select([func.round(func.count() * 0.01)]).
...: select_from(foo).
...: as_scalar()).\
...: execute().\
...: fetchall()
...:
307 ms ± 5.72 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [25]: %timeit foo.tablesample(1).select().execute().fetchall()
6.36 ms ± 188 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [26]: %timeit foo.tablesample(func.bernoulli(1)).select().execute().fetchall()
19.8 ms ± 381 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Before rushing to use SYSTEM sampling method one should know that it samples pages, not individual tuples, so it might not be suitable for small tables, for example, and may not produce as random results, if the table is clustered.
If using a dialect that does not allow passing the sample percentage / number of rows and seed as parameters, and a driver that does not inline values, then either pass the values as literal SQL text if they are static, or inline them using a custom SQLA compiler extension:
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import TableSample
@compiles(TableSample)
def visit_tablesample(tablesample, self, asfrom=False, **kw):
""" Compile `TableSample` with values inlined.
"""
kw_literal_binds = {**kw, "literal_binds": True}
text = "%s TABLESAMPLE %s" % (
self.visit_alias(tablesample, asfrom=True, **kw),
tablesample._get_method()._compiler_dispatch(self, **kw_literal_binds),
)
if tablesample.seed is not None:
text += " REPEATABLE (%s)" % (
tablesample.seed._compiler_dispatch(self, **kw_literal_binds)
)
return text
from sqlalchemy import table, literal, text
# Static percentage
print(table("tbl").tablesample(text("5 PERCENT")))
# Compiler inlined values
print(table("tbl").tablesample(5, seed=literal(42)))
A: Here's four different variations, ordered from slowest to fastest. timeit results at the bottom:
from sqlalchemy.sql import func
from sqlalchemy.orm import load_only
def simple_random():
return random.choice(model_name.query.all())
def load_only_random():
return random.choice(model_name.query.options(load_only('id')).all())
def order_by_random():
return model_name.query.order_by(func.random()).first()
def optimized_random():
return model_name.query.options(load_only('id')).offset(
func.floor(
func.random() *
db.session.query(func.count(model_name.id))
)
).limit(1).all()
timeit results for 10,000 runs on my Macbook against a PostgreSQL table with 300 rows:
simple_random():
90.09954111799925
load_only_random():
65.94714171699889
order_by_random():
23.17819356000109
optimized_random():
19.87806927999918
You can easily see that using func.random() is far faster than returning all results to Python's random.choice().
Additionally, as the size of the table increases, the performance of order_by_random() will degrade significantly because an ORDER BY requires a full table scan versus the COUNT in optimized_random() can use an index.
A: If you are using the orm and the table is not big (or you have its amount of rows cached) and you want it to be database independent the really simple approach is.
import random
rand = random.randrange(0, session.query(Table).count())
row = session.query(Table)[rand]
This is cheating slightly but thats why you use an orm.
A: There is a simple way to pull a random row that IS database independent.
Just use .offset() . No need to pull all rows:
import random
query = DBSession.query(Table)
rowCount = int(query.count())
randomRow = query.offset(int(rowCount*random.random())).first()
Where Table is your table (or you could put any query there).
If you want a few rows, then you can just run this multiple times, and make sure that each row is not identical to the previous.
A: This is my function to select random row(s) of a table:
from sqlalchemy.sql.expression import func
def random_find_rows(sample_num):
if not sample_num:
return []
session = DBSession()
return session.query(Table).order_by(func.random()).limit(sample_num).all()
A: This is very much a database-specific issue.
I know that PostgreSQL, SQLite, MySQL, and Oracle have the ability to order by a random function, so you can use this in SQLAlchemy:
from sqlalchemy.sql.expression import func, select
select.order_by(func.random()) # for PostgreSQL, SQLite
select.order_by(func.rand()) # for MySQL
select.order_by('dbms_random.value') # For Oracle
Next, you need to limit the query by the number of records you need (for example using .limit()).
Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; here is good article about it.
A: This is the solution I use:
from random import randint
rows_query = session.query(Table) # get all rows
if rows_query.count() > 0: # make sure there's at least 1 row
rand_index = randint(0,rows_query.count()-1) # get random index to rows
rand_row = rows_query.all()[rand_index] # use random index to get random row
A: Theres a couple of ways through SQL, depending on which data base is being used.
(I think SQLAlchemy can use all these anyways)
mysql:
SELECT colum FROM table
ORDER BY RAND()
LIMIT 1
PostgreSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
MSSQL:
SELECT TOP 1 column FROM table
ORDER BY NEWID()
IBM DB2:
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
Oracle:
SELECT column FROM
(SELECT column FROM table
ORDER BY dbms_random.value)
WHERE rownum = 1
However I don't know of any standard way
A: this solution will select a single random row
This solution requires that the primary key is named id, it should be if its not already:
import random
max_model_id = YourModel.query.order_by(YourModel.id.desc())[0].id
random_id = random.randrange(0,max_model_id)
random_row = YourModel.query.get(random_id)
print random_row
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "99"
} |
Q: Find out how much memory is being used by an object in C#? Does anyone know of a way to find out how much memory an instance of an object is taking?
For example, if I have an instance of the following object:
TestClass tc = new TestClass();
Is there a way to find out how much memory the instance tc is taking?
The reason for asking, is that although C# has built in memory management, I often run into issues with not clearing an instance of an object (e.g. a List that keeps track of something).
There are couple of reasonably good memory profilers (e.g. ANTS Profiler) but in a multi-threaded environment is pretty hard to figure out what belongs where, even with those tools.
A: If you are not trying to do it in code itself, which I'm assuming based on your ANTS reference, try taking a look at CLRProfiler (currently v2.0). It's free and if you don't mind the rather simplistic UI, it can provide valuable information. It will give you a in-depth overview of all kinds of stats. I used it a while back as one tool for finding a memory leek.
Download here: https://github.com/MicrosoftArchive/clrprofiler
If you do want to do it in code, the CLR has profiling APIs you could use. If you find the information in CLRProfiler, since it uses those APIs, you should be able to do it in code too. More info here:
http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx
(It's not as cryptic as using WinDbg, but be prepared to do mighty deep into the CLR.)
A: The CLR Profiler, which is provide free by Microsoft does a very good job at this type of thing.
An introduction to the whole profiler can be downloaded here. Also the Patterns & Practices team put something together a while back detailing how to use the profiler.
It does a fairly reasonable job at showing you the different threads and objects created in those threads.
Hope this sheds some light. Happy profiling!
A: I have good experiences with MemProfiler. It gives you stack traces of when the object was created and all the graphs of why the object is still not garbage collected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Can anyone recommend a Silverlight 2 book? Even though Silverlight2 is still in it's infancy, can anyone recommend a book to get started with? One that has more of a developer focus than a designer one?
A: I have this one pre-ordered: "Programming Silverlight 2"
by Jesse Liberty and Tim Heuer. The authors are both employed by Microsoft working on Silverlight 2, and their blogs are great, so I expect the book (to be released after RTM) to be up to date.
A: I have seen some of the work done by Laurent... wait for his book
(source: galasoft.ch)
Sams Silverlight 2 Unleashed
A: I'm currently working my way through Introducing Microsoft Silverlight 2, so far so good.
It's a typical Microsoft book serving up the koolaid, but gives a good introduction. I saw the guy speak at one of the local .NET User Groups in the Metro Detroit area and was impressed.
alt text http://ecx.images-amazon.com/images/I/51YD6H7PQyL._SL500_BO2,204,203,200_PIsitb-dp-500-arrow,TopRight,45,-64_OU01_AA240_SH20_.jpg
A: I've started reading Silverlight 2 in Action which seems pretty ok. One good thing is that because they have an early access program, you can get most of the book as an electronic copy already now. Even though the full book is not due to be released until sometime in October.
A: A lot of the books available are simply a rehash of the help files. Your best bet would be to start at silverlight.net and read the Help files that get installed with the SDK. Then when Jesse Liberty's book is released read that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Any tool similar to Hyperterminal application?
HyperTerminal is a program that you can use to connect to other
computers, Telnet sites, bulletin
board systems (BBSs), online services,
and host computers, using either your
modem, a null modem cable or Ethernet
connection.
But My main usage of Hyperterminal is to communicate with hardware through local (virtual )COM ports. I suppose it is removed in Vista for some reason.
Are there any other tools that functions similar to Hyperterminal?
[I am curious to know even if it is not for vista]
A: PuTTY can do serial communication nowdays.
A: Here are two:
Tera Term
Tera Term (Pro) is a free software terminal emulator (communication program) for MS-Windows. It supports VT100 emulation, telnet connection, serial port connection, and so on.
Kermit 95
Kermit 95: Internet and serial communications for Microsoft Windows® 95, Windows 98, Windows ME, Windows NT (4.0 and later), Windows 2000, Windows XP, and IBM OS/2 from the Kermit Project at Columbia University, offers you text-based terminal connections to Unix, VMS, and many other kinds of hosts, allowing you to interact directly with their shells and applications, to transfer files, and, if desired, to automate interactions and file transfers with its built-in platform- and transport-independent scripting language.
A: I had the same problem trying to connect to an RFID device over RS323/serial and found SerialMonitor.
There are two links to that application. A free version that I found here (and that's the one I used and it works with Vista):
http://www.softhypermarket.com/Free-Serial-Port-Monitor-download_29681.html
But if you follow the email address to the main site, there are a couple of versions of the tool. They aren't free, but they seem to have more features than the one I used.
http://www.hhdsoftware.com/Products/home/serial-monitor.html
Hope that helps.
A: Here is a better tool specificaly designed to test serial devices: http://www.caerustech.com/UDT.php . You can save settings and commands for various devices - I use it often at work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: international characters in Javascript I am working on a web application, where I transfer data from the server to the browser in XML.
Since I'm danish, I quickly run into problems with the characters æøå.
I know that in html, I use the "&aelig;&oslash;&aring;" for æøå.
however, as soon as the chars pass through JavaScript, I get black boxes with "?" in them when using æøå, and "æøå" is printed as is.
I've made sure to set it to utf-8, but that isn't helping much.
Ideally, I want it to work with any special characters (naturally).
The example that isn't working is included below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" charset="utf-8">
alert("æøå");
alert("æøå");
</script>
</head>
<body>
</body>
</html>
What am I doing wrong?
Ok, thanks to Grapefrukts answer, I got it working.
I actually needed it for data coming from an MySQL server. Since the saving of the files in UTF-8 encoding only solves the problem for static content, I figure I'd include the solution for strings from a MySQL server, pulled out using PHP:
utf8_encode($MyStringHere)
A: You can also use String.fromCharCode() to output a character from a numeric entity.
e.g. String.fromCharCode( 8226 ) will create a bullet character.
A: If you ever can't set the response encoding, you can use \u escape sequence in the JavaScript string literal to display these characters.
alert("\u00e6\u00f8\u00e5")
A: Just specifying UTF-8 in the header is not enough. I'd bet you haven't saved your file as UTF-8. Any reasonably advanced text editor will have this option. Try that and I'm sure it'll work!
A: I get "æøå" for the first one and some junk characters for the next. Could it be that the javascript is not mangling (or mojibake) your letters but the alert dialog uses the system default font, and the font is incapable of displaying the letters?
A: I use the code like this with Thai language. It's fine.
$message is my PHP variable.
echo("<html><head><meta charset='utf-8'></head><body><script type='text/javascript'>alert('" . $message . "');</script></body></html>");
Hope this can help. Thank you.
(I cannot post image of what I did as the system said "I don't have enough reputation", so I leave the image, here. http://goo.gl/9P3DtI Sorry for inconvenience.)
Sorry for my weak English.
A: This works as expected for me:
alert("æøå");
... creates an alert containing the string "æøå" whereas
alert("æøå");
... creates an alert with the non-ascii characters.
Javascript is pretty utf-8 clean and doesn't tend to put obstacles in your way.
Maybe you're putting this on a web server that serves it as ISO-8859-1? If you use Apache, in your Apache config file (or in .httaccess, if you can override), you should have a line
AddCharset utf-8 .js
(Note: edited to escape the ampersands... otherwise it didn't make sense.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: What is wrong with using inline functions? While it would be very convenient to use inline functions at some situations,
Are there any drawbacks with inline functions?
Conclusion:
Apparently, There is nothing wrong with using inline functions.
But it is worth noting the following points!
*
*Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. - Google Guidelines
*The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost - Source
*There are few situations where an inline function may not work:
*
*For a function returning values; if a return statement exists.
*For a function not returning any values; if a loop, switch or goto statement exists.
*If a function is recursive. -Source
*The __inline keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not __inline is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the __inline keyword to be ignored. -Source
A: There is a problem with inline - once you defined a function in a header file (which implies inline, either explicit or implicit by defining a body of a member function inside class) there is no simple way to change it without forcing your users to recompile (as opposed to relink). Often this causes problems, especially if the function in question is defined in a library and header is part of its interface.
A: I agree with the other posts:
*
*inline may be superfluous because the compiler will do it
*inline may bloat your code
A third point is it may force you to expose implementation details in your headers, .e.g.,
class OtherObject;
class Object {
public:
void someFunc(OtherObject& otherObj) {
otherObj.doIt(); // Yikes requires OtherObj declaration!
}
};
Without the inline a forward declaration of OtherObject was all you needed. With the inline your
header needs the definition for OtherObject.
A: As others have mentioned, the inline keyword is only a hint to the compiler. In actual fact, most modern compilers will completely ignore this hint. The compiler has its own heuristics to decide whether to inline a function, and quite frankly doesn't want your advice, thank you very much.
If you really, really want to make something inline, if you've actually profiled it and looked at the disassembly to ensure that overriding the compiler heuristic actually makes sense, then it is possible:
*
*In VC++, use the __forceinline keyword
*In GCC, use __attribute__((always_inline))
The inline keyword does have a second, valid purpose however - declaring functions in header files but not inside a class definition. The inline keyword is needed to tell the compiler not to generate multiple definitions of the function.
A: It worth pointing out that the inline keyword is actually just a hint to the compiler. The compiler may ignore the inline and simply generate code for the function someplace.
The main drawback to inline functions is that it can increase the size of your executable (depending on the number of instantiations). This can be a problem on some platforms (eg. embedded systems), especially if the function itself is recursive.
I'd also recommend making inline'd functions very small - The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost.
A: I doubt it. Even the compiler automatically inlines some functions for optimization.
A: I don't know if my answer's related to the question but:
Be very careful about inline virtual methods! Some buggy compilers (previous versions of Visual C++ for example) would generate inline code for virtual methods where the standard behaviour was to do nothing but go down the inheritance tree and call the appropriate method.
A: It could increase the size of the
executable, and I don't think
compilers will always actually make
them inline even though you used the
inline keyword. (Or is it the other
way around, like what Vaibhav
said?...)
I think it's usually OK if the
function has only 1 or 2 statements.
Edit: Here's what the linux CodingStyle document says about it:
Chapter 15: The inline disease
There appears to be a common
misperception that gcc has a magic
"make me faster" speedup option called
"inline". While the use of inlines can
be appropriate (for example as a means
of replacing macros, see Chapter 12),
it very often is not. Abundant use of
the inline keyword leads to a much
bigger kernel, which in turn slows the
system as a whole down, due to a
bigger icache footprint for the CPU
and simply because there is less
memory available for the pagecache.
Just think about it; a pagecache miss
causes a disk seek, which easily takes
5 miliseconds. There are a LOT of cpu
cycles that can go into these 5
miliseconds.
A reasonable rule of thumb is to not
put inline at functions that have more
than 3 lines of code in them. An
exception to this rule are the cases
where a parameter is known to be a
compiletime constant, and as a result
of this constantness you know the
compiler will be able to optimize most
of your function away at compile time.
For a good example of this later case,
see the kmalloc() inline function.
Often people argue that adding inline
to functions that are static and used
only once is always a win since there
is no space tradeoff. While this is
technically correct, gcc is capable of
inlining these automatically without
help, and the maintenance issue of
removing the inline when a second user
appears outweighs the potential value
of the hint that tells gcc to do
something it would have done anyway.
A: You should also note that the inline keyword is only a request. The compiler may choose not to inline it, likewise the compiler may choose to make a function inline that you did not define as inline if it thinks the speed/size tradeoff is worth it.
This decision is generaly made based on a number of things, such as the setting between optimise for speed(avoids the function call) and optimise for size (inlining can cause code bloat, so isn't great for large repeatedly used functions).
with the VC++ compiler you can overide this decision by using __forceinline
SO in general:
Use inline if you really want to have a function in a header, but elsewhere theres little point because if your going to gain anything from it, a good compiler will be making it inline for you anyway.
A: Inlining larger functions can make the program larger, resulting in more instruction cache misses and making it slower.
Deciding when a function is small enough that inlining will increase performance is quite tricky. Google's C++ Style Guide recommends only inlining functions of 10 lines or less.
(Simplified) Example:
Imagine a simple program that just calls function "X" 5 times.
If X is small and all calls are inlined: Potentially all instructions will be prefetched into the instruction cache with a single main memory access - great!
If X is large, let's say approaching the capacity of the instruction cache:
Inlining X will potentially result in fetching instructions from memory once for each inline instance of X.
If X isn't inlined, instructions may be fetched from memory on the first call to X, but could potentially remain in the cache for subsequent calls.
A: Excessive inlining of functions can increase size of compiled executable which can have negative impact on cache performance, but nowadays compiler decide about function inlining on their own (depending on many criterias) and ignore inline keyword.
A: Among other issues with inline functions, which I've seen heavily overused (I've seen inline functions of 500 lines), what you have to be aware of are:
*
*build instability
*
*Changing the source of an inline function causes all the users of the header to recompile
*#includes leak into the client. This can be very nasty if you rework an inlined function and remove a no-longer used header which some client has relied on.
*executable size
*
*Every time an inline is inlined instead of a call instruction the compiler has to generate the whole code of the inline. This is OK if the code of the function is short (one or two lines), not so good if the function is long
*Some functions can produce a lot more code than at first appears. I case in point is a 'trivial' destructor of a class that has a lot of non-pod member variables (or two or 3 member variables with rather messy destructors). A call has to be generated for each destructor.
*execution time
*
*this is very dependent on your CPU cache and shared libraries, but locality of reference is important. If the code you might be inlining happens to be held in cpu cache in one place, a number of clients can find the code an not suffer from a cache miss and the subsequent memory fetch (and worse, should it happen, a disk fetch). Sadly this is one of those cases where you really need to do performance analysis.
The coding standard where I work limit inline functions to simple setters/getters, and specifically say destructors should not be inline, unless you have performance measurements to show the inlining confers a noticeable advantage.
A: In addition to other great answers, at least once I saw a case where forced inlining actually slowed down the affected code by 1.5x. There was a nested loop inside (pretty small one) and when this function was compiled as a separate unit, compiler managed to efficiently unroll and optimize it. But when same function was inlined into much bigger outer function, compiler (MSVC 2017) failed to optimize this loop.
A: *
*As other people said that inline function can create a problem if the the code is large.As each instruction is stored in a specific memory location ,so overloading of inline function make a code to take more time to get exicuted.
*there are few other situations where inline may not work
*
*does not work in case of recursive function.
*It may also not work with static variable.
*it also not work in case there is use of a loop,switch etc.or we can say that with multiple statements.
*And the function main cannot work as inline function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: How do you retrieve items from a dictionary in the order that they're inserted? Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
A: The standard Python dict does this by default if you're using CPython 3.6+ (or Python 3.7+ for any other implementation of Python).
On older versions of Python you can use collections.OrderedDict.
A: You can't do this with the base dict class -- it's ordered by hash. You could build your own dictionary that is really a list of key,value pairs or somesuch, which would be ordered.
A: Or, just make the key a tuple with time.now() as the first field in the tuple.
Then you can retrieve the keys with dictname.keys(), sort, and voila!
Gerry
A: I've used StableDict before with good success.
http://pypi.python.org/pypi/StableDict/0.2
A: As of Python 3.7, the standard dict preserves insertion order. From the docs:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was implementation detail of CPython from 3.6.
So, you should be able to iterate over the dictionary normally or use popitem().
A: Use OrderedDict(), available since version 2.7
Just a matter of curiosity:
from collections import OrderedDict
a = {}
b = OrderedDict()
c = OrderedDict()
a['key1'] = 'value1'
a['key2'] = 'value2'
b['key1'] = 'value1'
b['key2'] = 'value2'
c['key2'] = 'value2'
c['key1'] = 'value1'
print a == b # True
print a == c # True
print b == c # False
A: The other answers are correct; it's not possible, but you could write this yourself. However, in case you're unsure how to actually implement something like this, here's a complete and working implementation that subclasses dict which I've just written and tested. (Note that the order of values passed to the constructor is undefined but will come before values passed later, and you could always just not allow ordered dicts to be initialized with values.)
class ordered_dict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self._order = self.keys()
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
if key in self._order:
self._order.remove(key)
self._order.append(key)
def __delitem__(self, key):
dict.__delitem__(self, key)
self._order.remove(key)
def order(self):
return self._order[:]
def ordered_items(self):
return [(key,self[key]) for key in self._order]
od = ordered_dict()
od["hello"] = "world"
od["goodbye"] = "cruel world"
print od.order() # prints ['hello', 'goodbye']
del od["hello"]
od["monty"] = "python"
print od.order() # prints ['goodbye', 'monty']
od["hello"] = "kitty"
print od.order() # prints ['goodbye', 'monty', 'hello']
print od.ordered_items()
# prints [('goodbye','cruel world'), ('monty','python'), ('hello','kitty')]
A: Or use any of the implementations for the PEP-372 described here, like the odict module from the pythonutils.
I successfully used the pocoo.org implementation, it is as easy as replacing your
my_dict={}
my_dict["foo"]="bar"
with
my_dict=odict.odict()
my_dict["foo"]="bar"
and require just this file
A: It's not possible unless you store the keys in a separate list for referencing later.
A: if you don't need the dict functionality, and only need to return tuples in the order you've inserted them, wouldn't a queue work better?
A: What you can do is insert the values with a key representing the order inputted, and then call sorted() on the items.
>>> obj = {}
>>> obj[1] = 'Bob'
>>> obj[2] = 'Sally'
>>> obj[3] = 'Joe'
>>> for k, v in sorted(obj.items()):
... print v
...
Bob
Sally
Joe
>>>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "66"
} |
Q: mod_rewrite equivalent for IIS 7.0 Is there a mod_rewrite equivalent for IIS 7.0 that's
a) more or less complete
b) suitable for a production environment, i.e. battle-tested/dependable/secure
Do you have an experience-based recommendation?
A: If you have $99.00 to spare you may want to take a look at http://www.isapirewrite.com/
[Excerpt from thier website]
Product overview
ISAPI_Rewrite is a powerful URL manipulation engine based on regular expressions. It acts mostly like Apache's mod_Rewrite, but is designed specifically for Microsoft's Internet Information Server (IIS). ISAPI_Rewrite is an ISAPI filter written in pure C/C++ so it is extremely fast. ISAPI_Rewrite gives you the freedom to go beyond the standard URL schemes and develop your own scheme.
[Example of use] available at http://www.helicontech.com/articles/provocative_SEF_URLs.htm
A: Check out the URL Rewrite Module for IIS 7 created by Microsoft
A: Have a look at URLRewriter. Used it in production once without problems. But don't rely on that as the only quality check:
http://www.codeplex.com/urlrewriter
(It's free and has a Microsoft Public License)
Managed Fusion URL Rewriter is a powerful URL manipulation engine based on the Apache mod_rewrite extension. It is designed, from the ground up to bring all the features of Apache mod_rewrite to IIS 6.0 and IIS 7.0. Managed Fusion Url Rewriter works with ASP.NET on Microsoft's Internet Information Server (IIS) 6.0 and Mono XPS Server and is fully supported, for all languages, in IIS 7.0, including ASP.NET and PHP. Managed Fusion Url Rewriter gives you the freedom to go beyond the standard URL schemes and develop your own scheme.
A: IIRF
*
*works with IIS5, 6 or 7.
*Free
*open source
*well maintained
*Free
*supports regular expression pattern matching
*uses .htaccess syntax
*RewriteRule
*RedirectRule
*RewriteHeader
*RewriteCond
*Free
*use separate config file for each IIS application or site
*rule changes are loaded automatically
*ProxyPass
*Did I mention it is Free?
A: A pefect alternative to Apache mod_rewrite and other Apache modules on IIS7 is Helicon Ape. The syntax is 99% Apache compatible.
A: http://www.iis.net/extensions/URLRewrite was designed for IIS 7.0 and features great performance and administration UI.
A: IIS mod-rewrite is the best option I know, but it's not free.
A: ISAPI Rewrite is suitable for IIS 5 or 6. There's a Lite version available for free, or you can pay for the full version to get more features, such as proxying capabilities. It's been a while since I've used it, but it worked fine at the time.
A: I'm using Helicon Ape since jumped off from Apache and moved to IIS. It's syntax compatible with Apache.
A: You can read my article on how to use Managed Fusion URL Rewriter here:
http://carlos.mendible.com/2010/02/runnig-apache-behind-iis-server-net.html
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: How to solve Memory Fragmentation We've occasionally been getting problems whereby our long-running server processes (running on Windows Server 2003) have thrown an exception due to a memory allocation failure. Our suspicion is these allocations are failing due to memory fragmentation.
Therefore, we've been looking at some alternative memory allocation mechanisms that may help us and I'm hoping someone can tell me the best one:
1) Use Windows Low-fragmentation Heap
2) jemalloc - as used in Firefox 3
3) Doug Lea's malloc
Our server process is developed using cross-platform C++ code, so any solution would be ideally cross-platform also (do *nix operating systems suffer from this type of memory fragmentation?).
Also, am I right in thinking that LFH is now the default memory allocation mechanism for Windows Server 2008 / Vista?... Will my current problems "go away" if our customers simply upgrade their server os?
A: As you suggest, Doug Lea's malloc might work well. It's cross platform and it has been used in shipping code. At the very least, it should be easy to integrate into your code for testing.
Having worked in fixed memory environments for a number of years, this situation is certainly a problem, even in non-fixed environments. We have found that the CRT allocators tend to stink pretty bad in terms of performance (speed, efficiency of wasted space, etc). I firmly believe that if you have extensive need of a good memory allocator over a long period of time, you should write your own (or see if something like dlmalloc will work). The trick is getting something written that works with your allocation patterns, and that has more to do with memory management efficiency as almost anything else.
Give dlmalloc a try. I definitely give it a thumbs up. It's fairly tunable as well, so you might be able to get more efficiency by changing some of the compile time options.
Honestly, you shouldn't depend on things "going away" with new OS implementations. A service pack, patch, or another new OS N years later might make the problem worse. Again, for applications that demand a robust memory manager, don't use the stock versions that are available with your compiler. Find one that works for your situation. Start with dlmalloc and tune it to see if you can get the behavior that works best for your situation.
A: First, I agree with the other posters who suggested a resource leak. You really want to rule that out first.
Hopefully, the heap manager you are currently using has a way to dump out the actual total free space available in the heap (across all free blocks) and also the total number of blocks that it is divided over. If the average free block size is relatively small compared to the total free space in the heap, then you do have a fragmentation problem. Alternatively, if you can dump the size of the largest free block and compare that to the total free space, that will accomplish the same thing. The largest free block would be small relative to the total free space available across all blocks if you are running into fragmentation.
To be very clear about the above, in all cases we are talking about free blocks in the heap, not the allocated blocks in the heap. In any case, if the above conditions are not met, then you do have a leak situation of some sort.
So, once you have ruled out a leak, you could consider using a better allocator. Doug Lea's malloc suggested in the question is a very good allocator for general use applications and very robust most of the time. Put another way, it has been time tested to work very well for most any application. However, no algorithm is ideal for all applications and any management algorithm approach can be broken by the right pathelogical conditions against it's design.
Why are you having a fragmentation problem? - Sources of fragmentation problems are caused by the behavior of an application and have to do with greatly different allocation lifetimes in the same memory arena. That is, some objects are allocated and freed regularly while other types of objects persist for extended periods of time all in the same heap.....think of the longer lifetime ones as poking holes into larger areas of the arena and thereby preventing the coalesce of adjacent blocks that have been freed.
To address this type of problem, the best thing you can do is logically divide the heap into sub arenas where the lifetimes are more similar. In effect, you want a transient heap and a persistent heap or heaps that group things of similar lifetimes.
Some others have suggested another approach to solve the problem which is to attempt to make the allocation sizes more similar or identical, but this is less ideal because it creates a different type of fragmentation called internal fragmentation - which is in effect the wasted space you have by allocating more memory in the block than you need.
Additionally, with a good heap allocator, like Doug Lea's, making the block sizes more similar is unnecessary because the allocator will already be doing a power of two size bucketing scheme that will make it completely unnecessary to artificially adjust the allocation sizes passed to malloc() - in effect, his heap manager does that for you automatically much more robustly than the application will be able to make adjustments.
A: You can help reduce fragmentation by reducing the amount you allocate deallocate.
e.g. say for a web server running a server side script, it may create a string to output the page to. Instead of allocating and deallocating these strings for every page request, just maintain a pool of them, so your only allocating when you need more, but your not deallocating (meaning after a while you get the situation you not allocating anymore either, because you have enough)
You can use _CrtDumpMemoryLeaks(); to dump memory leaks to the debug window when running a debug build, however I believe this is specific to the Visual C compiler. (it's in crtdbg.h)
A: I think you’ve mistakenly ruled out a memory leak too early.
Even a tiny memory leak can cause a severe memory fragmentation.
Assuming your application behaves like the following:
Allocate 10MB
Allocate 1 byte
Free 10MB
(oops, we didn’t free the 1 byte, but who cares about 1 tiny byte)
This seems like a very small leak, you will hardly notice it when monitoring just the total allocated memory size.
But this leak eventually will cause your application memory to look like this:
.
.
Free – 10MB
.
.
[Allocated -1 byte]
.
.
Free – 10MB
.
.
[Allocated -1 byte]
.
.
Free – 10MB
.
.
This leak will not be noticed... until you want to allocate 11MB
Assuming your minidumps had full memory info included, I recommend using DebugDiag to spot possible leaks.
In the generated memory report, examine carefully the allocation count (not size).
A: I'd suspect a leak before suspecting fragmentation.
For the memory-intensive data structures, you could switch over to a re-usable storage pool mechanism. You might also be able to allocate more stuff on the stack as opposed to the heap, but in practical terms that won't make a huge difference I think.
I'd fire up a tool like valgrind or do some intensive logging to look for resources not being released.
A: @nsaners - I'm pretty sure the problem is down to memory fragmentation. We've analyzed minidumps that point to a problem when a large (5-10mb) chunk of memory is being allocated. We've also monitored the process (on-site and in development) to check for memory leaks - none were detected (the memory footprint is generally quite low).
A: The problem does happen on Unix, although it's usually not as bad.
The Low-framgmentation heap helped us, but my co-workers swear by Smart Heap
(it's been used cross platform in a couple of our products for years). Unfortunately due to other circumstances we couldn't use Smart Heap this time.
We also look at block/chunking allocating and trying to have scope-savvy pools/strategies, i.e.,
long term things here, whole request thing there, short term things over there, etc.
A: As usual, you can usually waste memory to gain some speed.
This technique isn't useful for a general purpose allocator, but it does have it's place.
Basically, the idea is to write an allocator that returns memory from a pool where all the allocations are the same size. This pool can never become fragmented because any block is as good as another. You can reduce memory wastage by creating multiple pools with different size chunks and pick the smallest chunk size pool that's still greater than the requested amount. I've used this idea to create allocators that run in O(1).
A: if you talking about Win32 - you can try to squeeze something by using LARGEADDRESSAWARE. You'll have ~1Gb extra defragmented memory so your application will fragment it longer.
A: The simple, quick and dirty, solution is to split the application into several process, you should get fresh HEAP each time you create the process.
Your memory and speed might suffer a bit (swapping) but fast hardware and big RAM should be able to help.
This was old UNIX trick with daemons, when threads did not existed yet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
} |
Q: Advanced directory switching in bash I know a few advanced ways, to change directories. pushd and popd (directory stack) or cd - (change to last directory).
But I am looking for quick way to achieve the following:
Say, I am in a rather deep dir:
/this/is/a/very/deep/directory/structure/with\ lot\ of\ nasty/names
and I want to switch to
/this/is/another/very/deep/directory/structure/with\ lot\ of\ nasty/names
Is there a cool/quick/geeky way to do it (without the mouse)?
A: What about setting up your CDPATH variable?
A: Do you mean that the path names are the same, and only one directory name changes ("a" becomes "another")? In that case:
cd ${PWD/a/another}
will switch to the other directory. $PWD holds your current directory, and ${var/foo/bar} gives you $var with the string 'foo' replaced by 'bar'.
A: cd ^/a/^/another/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.