instruction stringlengths 0 30k ⌀ |
|---|
I have a secondary Exchange mailbox configured on my iPhone using IMAP. This all appears to work fine except when a message is deleted on the phone, it still shows normally in Outlook. It does not seem to matter what I set the "remove deleted messages" setting to on the phone.
I understand this is due to a combination of the phone not expunging the deleted messages and Exchange showing deleted but not expunged messages in Outlook.
I'm looking for an automated solution to this that does not have a large delay between deleting the message on the phone and it disappearing in Outlook. The message should also show in the Deleted Items when deleted from the phone.
----------
I've thought about creating a background process which connects to the mailbox via IMAP and sits in IDLE mode until there's a deleted message in the folder. It will then expunge the folder and return to IDLE mode. This wouldn't work with more than one folder (without multiple instances) but it would probably do the job.
Any recommendations on an easily scriptable tool or library that supports IMAP IDLE? |
A jump table can be either an array of pointers to functions or an array of machine code jump instructions. If you have a relatively static set of functions (such as system calls or virtual functions for a class) then you can create this table once and call the functions using a simple index into the array. This would mean retrieving the pointer and calling a function or jumping to the machine code depending on the type of table used.
The benefits of doing this in embedded programming are:
1. Indexes are more memory efficient than machine code or pointers, so there is a potential for memory savings in constrained environments.
2. For any particular function the index will remain stable and changing the function merely requires swapping out the function pointer.
If does cost you a tiny bit of performance for accessing the table, but this is no worse than any other virtual function call. |
A jump table, also known as a branch table, is a series of instructions, all unconditionally branching to another point in code.
You can think of them as a switch (or select) statement where all the cases are filled:
MyJump(int c)
{
switch(state)
{
case 0:
goto func0label;
case 1:
goto func1label;
case 2:
goto func2label;
}
}
Note that there's no return - the code that it jumps to will execute the return, and it will jump back to wherever myjump was called.
This is useful for state machines where you execute certain code based on the state variable. There are many, many other uses, but this is one of the main uses.
It's used where you don't want to waste time fiddling with the stack, and want to save code space. It is especially of use in interrupt handlers where speed is extremely important, and the peripheral that caused the interrupt is only known by a single variable. This is similar to the vector table in processors with interrupt controllers.
One use would be taking a $0.60 microcontroller and generating a composite (TV) signal for video applications. the micro isn't powerful - in fact it's just barely fast enough to write each scan line. A jump table would be used to draw characters, because it would take too long to load a bitmap from memory, and use a for() loop to shove the bitmap out. Instead there's a separate jump to the letter and scan line, and then 8 or so instructions that actually write the data directly to the port.
-Adam |
You might need something more complicated than a regular expression. Web pages often have angle brackets that aren't part of a tag, like this:
<div>5 < 7</div>
Stripping the tags with regex will return the string "5 " and treat
< 7</div>
as a single tag and strip it out.
I suggest looking for already-written code that does this for you. I did a search and found this: [http://zesty.ca/python/scrape.html][1] It also can resolve HTML entities.
[1]: http://zesty.ca/python/scrape.html |
Use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)! It's perfect for this, where you have incoming markup of dubious virtue and need to get something reasonable out of it. Just pass in the original text, extract all the string tags, and join them. |
[List of .NET Framework versions][1].
[1]: http://en.wikipedia.org/wiki/.NET_Framework_version_list |
List of ASP.NET Versions? |
|asp.net| |
Thanks to a Q&A on stackoverflow I just found out how to determine the installed version on my hosting provider's server. Now I need to know what that number means.
Using <%=Environment.Version%> on my local machine returns 2.0.50727.3053. Which I've found to mean v3.5 SP1.
Can someone give me a list of the version 1, 1.1, 2, ect.. to the actual Environment.Version codes or break down what that code means? |
Thanks to a Q&A on stackoverflow I just found out how to determine the installed version on my hosting provider's server. Now I need to know what that number means.
Using <%=Environment.Version%> on my local machine returns 2.0.50727.3053.
Can someone give me a list of the version 1, 1.1, 2, ect.. to the actual Environment.Version codes or break down what that code means? |
Is it possible to convert projects wizard created for MSVS 2005 to MSVS 2008 format autom |
|visual-studio|templates| |
I have a bunch of wizards created for MSVS 2005. Is it possible to convert them to MSVS 2008 format automatically? |
Is it possible to convert projects wizard created for MSVS 2005 to MSVS 2008 format automatically |
Thanks!
I just dropped <%=Environment.Version%> on a page and got 2.0.50727.3053, which from what I found is v3.5 SP1. |
Thanks!
I just dropped <%=Environment.Version%> on a page and got 2.0.50727.3053 |
Just a note, LoginGenerator and SaltedLoginGenerator have been superseded by Restful Authentication and are unsupported on newer Rails releases -- dont waste any time on them, though they were great at the time.
|
@Vaibhav
The [Using Google Analytics with rich (managed) web applications in Silverlight](http://blogs.msdn.com/jeffwilcox/archive/2007/10/01/using-google-analytics-with-rich-managed-web-applications-in-silverlight.aspx) article is very interesing but is more focused on how to get your Silverlight app to send messages to Google Analytics.
@Cd-MaN
Yeah, I thought that too but I have tried running my page with Nikhil's javascript and Google Analytics didn't pick it up. But I could have screwed something up somewhere.
I'm just interested to know if anyone else has managed to do this (track Silverlight-ness) successfully. |
I'm running some [JMeter][1] tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap.
I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using `ps` like this:
PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`
...running the command every X seconds and appending the results to a text file. (for anyone wondering, `pmem` = % mem usage and `nlwp` is number of threads)
However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, `pcpu` is defined as:
>cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage.
In other words, `pcpu` gives me the % CPU utilization for the process for the *lifetime* of the process.
Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what `top` would give me
(CPU utilization of the process since the last update).
How can I collect this from within a shell script?
[1]: http://jakarta.apache.org/jmeter/ |
Optimizing a LINQ query. |
|linq|linq-to-sql|optimization| |
I have a query that looks like this:
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
DatabaseDataContext db = new DatabaseDataContext();
return (from o in db.Orders
orderby o.CreatedDate descending
select o).Skip(pageIndex * recordCount).Take(recordCount).ToList();
}
I need to print the information of the order and the user who created it:
foreach (var o in FetchLatestOrders(0, 10))
{
Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}
This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings each order and it's customers in one SQL query?
Thanks
|
Optimizing a LINQ to SQL query. |
I have a query that looks like this:
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
DatabaseDataContext db = new DatabaseDataContext();
return (from o in db.Orders
orderby o.CreatedDate descending
select o).Skip(pageIndex * recordCount).Take(recordCount).ToList();
}
I need to print the information of the order and the user who created it:
foreach (var o in FetchLatestOrders(0, 10))
{
Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}
This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?
Thanks
|
|linq|optimization|linq-to-sql| |
I have a query that looks like this:
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
DatabaseDataContext db = new DatabaseDataContext();
return (from o in db.Orders
orderby o.CreatedDate descending
select o).Skip(pageIndex * recordCount).Take(recordCount).ToList();
}
I need to print the information of the order and the user who created it:
foreach (var o in FetchLatestOrders(0, 10))
{
Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}
This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?
Thanks
UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated:
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(o => o.Customer);
using (var db = new DatabaseDataContext())
{
db.LoadOptions = options;
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
}
Thanks sirrocco.
|
It looks you can still pass arguments to the constructor, here's my test code:
<?php
class Test {
function __construct($x) {
echo $x;
}
}
$class = 'Test';
$object = new $class('test'); // echoes "test"
?>
That is what you meant, right?
So the only other problem you mentioned and that I can think of is the security of it, but it shouldn't be too difficult to make it secure, and it's obviously a lot more secure than using eval(). |
Or you can just hide the option you don't want to show...
function hideSelected($one, $two)
{
$one.bind('change', function()
{
var val = $one.val();
$two.find('option:not(:visible)').show().end()
.find('option[value='+val+']').hide().end();
})
}
hideSelected($one, $two);
hideSelected($two, $one);
|
Or you can just hide the option you don't want to show...
function hideSelected($one, $two)
{
$one.bind('change', function()
{
var val = $one.val();
$two.find('option:not(:visible)').show().end()
.find('option[value='+val+']').hide().end();
})
}
hideSelected($one, $two);
hideSelected($two, $one);
EDIT: Oh sorry, this code does not work with IE6...
|
Hbase / Hadoop Query Help |
|hadoop|hbase| |
I'm working on a project with a friend that will utilize Hbase to store it's data. Are there any good query examples? I seem to be writing a ton of Java code to iterate through lists of RowResult's when, in SQL land, I could write a simple query. Am I missing something? Or is Hbase missing something? |
Some suggestions:
- No write permission (get permission from the owner, or take it if you're an Administrator)
- File is locked (close any program that may have the file open, then reboot if that doesn't help)
- File has the read-only DOS attribute set (unset it from file Properties window, or with `attrib -r`) |
Some suggestions:
- No write permission (get permission from the owner, or take it if you're an Administrator)
- File is locked (close any program that may have the file open, then reboot if that doesn't help)
- File has the read-only DOS attribute set (unset it from file Properties window, or with `attrib -r`)
Edit: Only the second item (file is locked) has a possible solution that all users are likely to be able to do without help. For the first and third, you'll probably want to provide guidance (and hope the file wasn't made read-only intentionally!). |
Some suggestions:
- No write permission (get permission through Security tab on file Properties window; you must be the file owner or an Administrator)
- File is locked (close any program that may have the file open, then reboot if that doesn't help)
- File has the read-only DOS attribute set (unset it from file Properties window, or with `attrib -r`; you must be the file owner or an Administrator)
Edit: Only the second item (file is locked) has a possible solution that all users are likely to be able to do without help. For the first and third, you'll probably want to provide guidance (and hope the file wasn't made read-only intentionally!).
Edit 2: Technicially, the user does need write and execute (chdir) permissions on all directories up to the root. Windows may skip some of the recursive checks up the tree as a performance optimization, but you should not rely on this. |
Is it a List<string>? If so then this should work:
List<string> stringList = new List<string>();
// ... some list populating code here ...
string[] stringArray = stringList.Where(a => a == Foo.Bar).Distinct().ToArray(); |
This should work if you want to use the fluent pattern:
string[] arrayStrings = fooList.Select(a => a.Bar).Distinct().ToArray(); |
Row isn't an array unless there are multiple Row elements. It is annoying. You have to do something like this, but I haven't written AS3 in a while so I forget if there's an exists function.
if (exists(event.result.DataTable) && exists(event.result.DataTable.Row)){
if (exists(event.result.DataTable.Row.length)) {
for(var i:int=0;i<event.result.DataTable.Row.length;i++)
{
if (exists(event.result.DataTable.Row[i].text)
&& "foo" == event.result.DataTable.Row[i].text)
mx.controls.Alert.show('foo found!');
}
}
if (exists(event.result.DataTable.Row.text)
&& "foo" == event.result.DataTable.Row.text)
mx.controls.Alert.show('foo found!');
} |
I don't know about Java, but I remember running into [Quercus][1] a while ago. It's a 100% Java interpreter for PHP code.
So yes, you could have PHP templates on your Java app. **Update**: see [Quercus: PHP in Java][2] for more info.
[1]: http://www.caucho.com/resin-3.0/quercus/
[2]: http://caucho.com/resin/doc/quercus.xtp |
I don't know much about Java, but I remember running into [Quercus][1] a while ago. It's a 100% Java interpreter for PHP code.
So yes, you could have PHP templates on your Java app. **Update**: see [Quercus: PHP in Java][2] for more info.
[1]: http://www.caucho.com/resin-3.0/quercus/
[2]: http://caucho.com/resin/doc/quercus.xtp |
**[@Konrad](http://stackoverflow.com/questions/38746/how-to-detect-file-ends-in-newline#39185)**: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail:
$ cat test_no_newline.txt
this file doesn't end in newline$
$ cat test_with_newline.txt
this file ends in newline
$ |
**[@Konrad](http://stackoverflow.com/questions/38746/how-to-detect-file-ends-in-newline#39185)**: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail:
$ cat test_no_newline.txt
this file doesn't end in newline$
$ cat test_with_newline.txt
this file ends in newline
$
Though I found that tail has get last byte option. So I modified your script to:
#!/bin/sh
c=`tail -c 1 $1`
if [ "$c" != "" ]; then echo "no newline"; fi |
I think WPF can greatly improve user experience.
However there are no much business oriented controls out there which means you need to do a lot by yourself.
As for designers I think it's really hard to find WPF designer now days, it still would be a dedicated programmer rather then design-only guy.
I hope that this situation will change in nearest feature.
I think it's worth at least start experimenting with WPF to be able to compete with upcoming solutions. |
Use `top -b` (and other switches if you want different outputs). It will just dump to stdout instead of jumping into a curses window. |
I believe the error lies in the mark up that the color picker is generating. I saved the page and removed that code for the color picker and it renders fine in IE/FF/SF. |
What are the Agile tools for PHP? |
|php| |
- Unit Testing
- Mocking
- Inversion of Control
- Refactoring
- Object Relational Mapping
- Others?
I have found [simpletest][1] for unit testing and mocking and, though it leaves much to be desired, it kind-of sort of works.
I have yet to find any reasonable Inversion of Control framework (there is one that came up on phpclasses but no documentation and doesn't seem like anyone's tried it).
[1]: http://www.lastcraft.com/simple_test.php |
How about [AIML][1]? Not so much a programming language, but you get instant fulfillment and because its all about artificial intelligence it will likely trigger his (her?) sense of excitement.
[1]: http://www.alicebot.org/aiml.html |
Python package [VPython][2] -- 3D Programming for Ordinary Mortal ([video tutorial][1]).
[Code example:][3]
from visual import *
floor = box (pos=(0,0,0), length=4, height=0.5, width=4, color=color.blue)
ball = sphere (pos=(0,4,0), radius=1, color=color.red)
ball.velocity = vector(0,-1,0)
dt = 0.01
while 1:
rate (100)
ball.pos = ball.pos + ball.velocity*dt
if ball.y < ball.radius:
ball.velocity.y = -ball.velocity.y
else:
ball.velocity.y = ball.velocity.y - 9.8*dt
![VPython bouncing ball][4]
[1]: http://showmedo.com/videos/video?name=pythonThompsonVPython1&fromSeriesID=30
[2]: http://vpython.org
[3]: http://vpython.org/vpythonprog.htm
[4]: http://vpython.org/bounce.gif |
I would start by reading this article:
<http://decipherinfosys.wordpress.com/2007/03/27/using-stored-procedures-vs-dynamic-sql-generated-by-orm/>
Here is a speed test between the two:
<http://www.blackwasp.co.uk/SpeedTestSqlSproc.aspx>
|
For most people, the best way to convince them is to "show them the proof." In this case, I would create a couple basic test cases to retrieve the same set of data, and then time how long it takes using stored procedures versus NHibernate. Once you have the results, hand it over to them and most skeptical people should yield to the evidence. |
Round 1 - You can start a profiler trace and compare the execution times. |
There is now Grails plugin that enables the use of multiple datasources directly with Grails' GORM layer:
http://burtbeckwith.com/blog/?p=70 |
Measure it, but in a non-micro-benchmark, i.e. something that represents real operations in your system. Even if there would be a tiny performance benefit for a stored procedure it will be insignificant against the other costs your code is incurring: actually retrieving data, converting it, displaying it, etc. Not to mention that using stored procedures amounts to spreading your logic out over your app **and** your database with no significant version control, unit tests or refactoring support in the latter. |
I don't know what ruby would do if you used extended UTF8 characters as identifiers in your source code, but I know what I would do, which would be to slap you upside the back of the head and tell you DON'T DO THAT |
Read the paper: **Porikli, Fatih, Oncel Tuzel, and Peter Meer. “Covariance Tracking Using Model Update Based
on Means on Riemannian Manifolds”. (2006) IEEE Computer Vision and Pattern Recognition.**
I was successfully able to detect overlapping regions in images captured from adjacent webcams using the technique presented in this paper. My covariance matrix was composed of Sobel, canny and SUSAN aspect/edge detection outputs, as well as the original greyscale pixels. |
[Here](http://pimpmysafari.com/plugins/keywurl) is a Safari plugin whereby you can customize it to search other sites. May work with Stack Overflow (I haven't tried it). Check out that site too for other Safari plugins. |
Best method to get objects from a BlockingQueue in a concurrent program? |
|java|concurrency| |
What is the best method to get objects out of a BlockingQueue, in a concurrent program, without hitting a race condition? I'm currently doing the following and I'm not convinced it is the best method:
BlockingQueue<Violation> vQueue;
/*
in the constructor I pass in a BlockingQueue object
full of violations that need to be processed - cut out for brevity
*/
Violation v;
while ( ( v = vQueue.poll(500, TimeUnit.MILLISECONDS) ) != null ) {
// do stuff with the violation
}
I have yet to hit a race condition... but, I'm none too sure if this is truly safe.
Matt |
To quote the great authors of [SICP](http://www.amazon.com/Structure-Interpretation-Computer-Programs-Engineering/dp/0262011530/sr=8-1/qid=1163785017?ie=UTF8&s=books),
_Programs must be written for people to read, and only incidentally for machines to execute_
I prefer to have both methods 1 and 2 at hand. Using ruby as an example, it comes with `.include?` which is used like this
haystack.include? needle
=> returns true if the haystack includes the needle
Sometimes though, purely for readability reasons, I want to flip it round. Ruby doesn't come with an `in?` method, but it's a one-liner, so I often do this:
needle.in? haystack
=> exactly the same as above
If it's "more important" to emphasise the haystack, or the operation of searching, I prefer to write `include?`.
Often though, neither the haystack or the search is really what you care about, just that the object is present - in this case I find `in?` better conveys the meaning of the program. |
> @Peter Meyer
> You get the idea. I think going as loosely coupled as possible is a good thing, but maybe I was getting a bit carried away! :)
Errr... yeah... I think the `IStuffSmallEnoughToBeLostInAHaystack` kind of is a red flag :-) |
What to do about ScanAlert? |
|performance|security| |
One of my clients uses McAfee ScanAlert (i.e., HackerSafe). It basically hits the site with about 1500 bad requests a day looking for security holes. Since it demonstrates malicious behavior it is tempting to just block it after a couple bad requests, but maybe I should let it exercise the UI. Is it a true test if I don't let it finish? |
I've always done it with a function like this:
public function keyExists(myCollection as collection, sKey as string) as Boolean
on error goto handleerror:
dim val as variant
val = myCollection(sKey)
keyExists = true
exit sub
handleerror:
keyExists = false
end function |
Loading a JSON |
|php|json| |
I've been using PHP for too long, but I'm new to JavaScript integration in some places. I'm trying to find the fastest way to pass database information into a page where it can be modified and displayed dynamically in JavaScript. Right now, I'm looking at loading a JSON with PHP echo statements because it's fast and effective, but I saw that I could use PHP's JSON library (PHP 5.2). Has anybody tried the new JSON library, and is it better than my earlier method?
Thanks |
Loading JSON with PHP |
If I get this right, you want a vector that is normal to the screen plane, but in world coordinates?
In that case you want to INVERT the transformation from World -> Screen and do Screen -> World of (0,0,-1) or (0,0,1) depending on which axis the screen points down.
Since the ModelView matrix is just a rotation matrix (ignoring the homogenous transformation part), you can simply pull this out by taking the transpose of the rotational part, or simple reading in the bottom row - as this transposes onto the Z coordinate column under transposition. |
One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).
These sorts of things are fairly common when doing Hibernate mappings for example.
If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.
The simplest solution is to not include the getChildren collection in the methods. |
It means outer join, a simple = means inner join.
*= is LEFT JOIN and =* is RIGHT JOIN.
(or vice versa, I keep forgetting since I'm not using it any more, and Google isn't helpful when searching for *=) |
You can edit the default template for excel -
There is a file called Book.xlt in the XLSTART directory, normally located at "C:\Program Files\Microsoft Office\Office\XLStart\"
You should be able to add a macro called Workbook_Open
Private Sub Workbook_Open()
If ActiveWorkBook.Sheets(1).Range("A1") = ""
ActiveWorkBook.Sheets(1).Range("A1") = Now
End IfEnd Sub
My vba is a little rusty, but you might find something like this works.
|
To answer your questions one by one.
Get v2.0 of the CTP. I have used 1.0 and 2.0 and have not found any stability issues with the later version and it has more [functionality][1].
The best way to get started is to learn ***three*** basic commands and start playing with it.
**Step 1 - Discover the available commands using Get-Command**
To find all of the "get" commands, for example, you just type:
*Get-Command get**
To find all of the "set" commands, for example, you just type:
*Get-Command set**
**Step 2 - Learn how to use each command using Get-Help**
To get basic help about the Get-Command commandlet type:
Get-Help Get-Command
To get more information type:
Get-Help Get-Command -full
**Step 3 - Discover object properties and methods using Get-Member**
Powershell is an object oriented scripting language. Everything is a fully fledged .Net object with properties and methods.
For example to get the properties and methods on the object emitted by the Get-Process commandlet type:
Get-Process | Get-Member
There are a few other concepts that you need to understand like pipes and regular expressions, but those should already be familiar if you have already done some scripting.
**What am I using it for?**
Two things:
1. Processing log files from a massively distributed grid application. For this it has proven to be incredibly valuable and powerful.
2. Quick testing of .Net classes.
[1]: http://blogs.msdn.com/powershell/archive/2007/11/06/what-s-new-in-ctp-of-powershell-2-0.aspx |
Some suggestions:
- No write permission (get permission through Security tab on file Properties window; you must be the file owner or an Administrator)
- File is locked (close any program that may have the file open, then reboot if that doesn't help)
- File has the read-only DOS attribute set (unset it from file Properties window, or with `attrib -r`; you must be the file owner or an Administrator)
Edit 1: Only the second item (file is locked) has a possible solution that all users are likely to be able to do without help. For the first and third, you'll probably want to provide guidance (and hope the file wasn't made read-only intentionally!).
Edit 2: Technicially, the user does need write and execute (chdir) permissions on all directories up to the root. Windows may skip some of the recursive checks up the tree as a performance optimization, but you should not rely on this.
Edit 3: @RobM: Yes, you should check that there is no obvious reason that the user should not have the permissions she needs but does not have. I alluded to this in a less direct way in my first edit. However, in some cases users should have write permission to a file but do not because of filesystem corruption, a misbehaving program, or a mistake on their own part. |
Some suggestions:
- No write permission (get permission through Security tab on file Properties window; you must be the file owner or an Administrator)
- File is locked (close any program that may have the file open, then reboot if that doesn't help)
- File has the read-only DOS attribute set (unset it from file Properties window, or with `attrib -r`; you must be the file owner or an Administrator)
Edit 1: Only the second item (file is locked) has a possible solution that all users are likely to be able to do without help. For the first and third, you'll probably want to provide guidance (and hope the file wasn't made read-only intentionally!).
Edit 2: Technically, the user does need write and execute (chdir) permissions on all directories up to the root. Windows may skip some of the recursive checks up the tree as a performance optimization, but you should not rely on this because admins can force on these so-called "traverse checks" for certain users.
Edit 3: @RobM: Yes, you should check that there is no obvious reason that the user should not have the permissions she needs but does not have. I alluded to this in a less direct way in my first edit. However, in some cases users should have write permission to a file but do not because of filesystem corruption, a misbehaving program, or a mistake on their own part. |
As well as the answers supplied above, one small advantage of splinting up your code into modules (separate files) is that if you have to have any global variables, you can limit their scope to a single module by the use of the key word 'static'. (You could also apply this to functions). Note that this use of 'static' is different from its use inside a function. |
Actually, auto-completion does work for `.`. The completion options are found by calling `#methods` on the object. You can see this for yourself by overriding `Object.methods`:
>> def Object.methods; ["foo", "bar"]; end
=> nil
>> Object.[TAB]
Object.foo Object.bar
>> Object.
Note that this only works when the expression to the left of the `.` is a literal. Otherwise, getting the object to call `#methods` on would involve evaluating the left-hand side, which could have side-effects. You can see this for yourself as well:
[continuing from above...]
>> def Object.baz; Object; end
=> nil
>> Object.baz.[TAB]
Display all 1022 possibilities? (y or n)
We add a method `#baz` to `Object` which returns `Object` itself. Then we auto-complete to get the methods we can call on `Object.baz`. If IRB called `Object.baz.methods`, it would get the same thing as `Object.methods`. Instead, IRB has 1022 suggestions. I'm not sure where they come from, but it's clearly a generic list which isn't actually based on context.
The `::` operator is (also) used for getting a module's constants, while `.` is not. That's why `HTTP` will show up in the completion for `Net::`, but not for `Net.`. `Net.HTTP` isn't correct, but `Net::HTTP` is. |
Google Suggestish text box |
|c#|windows-app| |
What would be the easiest way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#. |
What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#. |
|c#|winforms| |
Try this:
> public static int? ParseNullableInt(this string value)
{
int intValue;
if (int.TryParse(value, out intValue))
return intValue;
return null;
} |
Don't forget about integrity here. There are forgery attacks against out-of-the-box crypto when the attacker doesn't know the key, but can manipulate the ciphertext. These can be particularly nasty when:
* encrypting short strings,
* with known substrings
That's exactly the case for credit cards. So using System.Security.Cryptography AES or 3DES in CBC mode without rolling your own checksum can be dangerous. Read: there's some chance an attacker without the secret key could replace one credit card number with another.
|
How to parse a string into a nullable int in C# (.NET 3.5) |
|c#|.net-3.5|string|nullable|parsing| |
I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.
I was kind of hoping that this would work
int? val = stringVal as int?;
But that won't work, so the way I'm doing it now is I've written this extension method
public static int? ParseNullableInt(this string value)
{
if (value == null || value.Trim() == string.Empty)
{
return null;
}
else
{
try
{
return int.Parse(value);
}
catch
{
return null;
}
}
}
Is there a better way of doing this? |
|c#|.net-3.5|string|parsing|nullable| |
I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.
I was kind of hoping that this would work
int? val = stringVal as int?;
But that won't work, so the way I'm doing it now is I've written this extension method
public static int? ParseNullableInt(this string value)
{
if (value == null || value.Trim() == string.Empty)
{
return null;
}
else
{
try
{
return int.Parse(value);
}
catch
{
return null;
}
}
}
Is there a better way of doing this?
**EDIT:** Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int? |
Int32.TryParse is probably a tad easier:
public static int? ToNullableInt32(this string s)
{
int i;
if (Int32.TryParse(s, out i)) return i;
return null;
} |
Benchmark it yourself. Write a testbed class that executes a sampled stored procedure a few hundred times, and run the NHibernate code the same amount of times. Compare the average and median execution time of each method. |
It is just as fast if the query is the same each time. Sql Server 2005 caches query plans at the level of each statement in a batch, regardless of where the SQL comes from.
The long-term difference might be that stored procedures are many, many times easier for a DBA to manage and tune, whereas hundreds of different queries that have to be gleaned from profiler traces are a nightmare. |
I've had this argument many times over.
Almost always I end up grabbing a really good dba, and running a proc and a piece of code with the profiler running, and get the dba to show that the results are so close its negligible. |
Off the top of my head, I'd use the /proc filesystem view of the system state - Look at _man 5 proc_ to see the format of the entry for /proc/PID/stat, which contains total CPU usage information, and use /proc/stat to get global system information. To obtain "current time" usage, you probably really mean "CPU used in the last N seconds"; take two samples a short distance apart to see the current rate of CPU consumption. You can then munge these values into something useful. Really though, this is probably more a Perl/Ruby/Python job than a pure shell script.
You might be able to get the rough data you're after with /proc/PID/status, which gives a Sleep average for the process. Pretty coarse data though. |
Measure it.
Really, any discussion on this topic is probably futile until you've measured it. |
Image library that will auto-crop |
|.net|image-manipulation| |