posts - 7, comments - 18, trackbacks - 1, articles - 0
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

2009年12月10日

So a little while back we wrote about the confusing crashes on the device that we eventually figured out were caused by [UIImage imageNamed:] running out of memory when it tried to cache lots of big images. So we apparently solved the problem by making a thumbnail-sized image set and caching those, some 2.9 meg worth, whilst loading in the full sized ones uncached and only as needed.

Well, apparently turned out to be not good enough. See, it’s a few days later and we’ve finalized the design and got everything implemented and all seems to be good … except that it gets terminated without warning sooner or later. And quite often, Springboard terminates as well. Absolutely no correlation to any action or sequence in the program, no leaks, no out of bounds memory accesses, memory usage of the program barely a pittance. Yet, somehow, look at the console and you see system memory warnings scrolling by, you see it quitting background processes, and eventually quitting Springboard and/or the active application. Whilst that active application hums merrily along in blithe ignorance of the system crashing to the ground behind its back.

So apparently not only is 2.9 meg of images cached with +imageNamed enough to bring the iPhone OS to its knees, it’s not smart enough to, you know, actually do anything about it, like oh I don’t know, empty the cache or something?

It’s not like this is hard or anything, you can replicate the caching functionality precisely by declaring yourself an  NSMutableDictionary *thumbnailCache and populating it like

- (UIImage*)thumbnailImage:(NSString*)fileName
{
   UIImage *thumbnail = [thumbnailCache objectForKey:fileName];

   if (nil == thumbnail)
   {
      NSString *thumbnailFile = [NSString stringWithFormat:@"%@/thumbnails/%@.jpg", [[NSBundle mainBundle] resourcePath], fileName];
      thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
      [thumbnailCache setObject:thumbnail forKey:fileName];
   }
   return thumbnail;
}

and if you do get a low memory issue, just [thumbnailCache removeAllObjects] and you’re good. But you know what? After replacing the various +imageNamed calls with this … not a single quibble anywhere, the whole 2.9 meg worth of cached thumbnails go right in there and not a single problem for, literally, hours.

(Not that there were any problems after those hours, we hasten to add; simply that, you know, if you think about it, there probably really isn’t a lot of point extending testing of an iPhone application much past the lifespan of a full battery charge…)

So the moral of the story is: DO NOT USE [UIImage imageNamed] for any significant amount of images. It is EVIL. It WILL bring down your application and/or Springboard, even when your application is putting along using just barely a nibble of memory on its own. Take the handful of lines above and implement your own cache!

 

原文: http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/

posted @ 2009-12-10 19:46 Jerry Hu 阅读(81) 评论(0) 编辑

2009年11月30日

Jeff Perrin needed a function to return the first N words in a string (to create a small summary or a snippet thingy). He did it using the manual and awkward method of parsing the string manually. That method is more error prone and usually makes for less readable code. Fortunately, you can use regular expressions here quite nicely. Here's a test that makes sure that we get the first 4 words in a string and the function "FindFirstWords" that does this very easily using a simple regular expression.

What I'm doing here is that I'm using the expression to find the first 4 occurrences of text that is composed of alphanumeric text with one or more spaces after it. Then I simply iterate over the match I found. The match should contain 4 captures inside it - one for each "word" that was found.

It's not fully tested as you can see. I only wrote one test to see it works on this sort of sentence. More tests could and should be added to test other cases. In fact, if this were reall TDD, I would have started with a test of an empty string, and continued on to test getting only one word, and then two and so on.

[Test]

public void TestRegexFindFirstNWords()

{

      const string INPUT =

"this is word four five six seven eight nine ten eleven twelve thirteen!";

      const int NUM_WORDS_TO_RETURN = 4;

 

      string output = FindFirstWords (INPUT, NUM_WORDS_TO_RETURN);

 

      string expectedOutput = "this is word four ";

      Assert.AreEqual(expectedOutput,output);

}

 

private string FindFirstWords (string input, int howManyToFind)

{

     // thanks to Jeff Attwood for making this code even simpler!

      string REGEX = @"([\w]+\s+){" + howManyToFind + "}";

      return Regex.Match(input,REGEX).Value;

}


原文地址: http://weblogs.asp.net/rosherove/archive/2005/01/07/348138.aspx

 

posted @ 2009-11-30 10:05 Jerry Hu 阅读(71) 评论(0) 编辑

2009年11月10日

Problem. You need help with DateTime formatting strings in C# or .NET languages. The framework provides powerful formatting capabilities, but the syntax is confusing and there are some tricks. Solution. Here we see examples of using DateTime formats, and also the different values you can get with the individual formats.

Format your DateTimes in the best way for your application. 
You will not have to write elaborate custom routines.
The .NET Framework has a powerful DateTime format mechanism.

1. Using DateTime format string

Here we see an example of how you can use a specific formatting string with DateTime and ToString to obtain a special DateTime string. This is useful when interacting with other systems, or when you require a precise format.

=== Program that uses DateTime format (C#) ===

using System;

class Program
{
static void Main()
{
DateTime time = DateTime.Now; // Use current time
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format)); // Write to console
}
}

=== Output of the program ===

Feb Fri 27 11:41 2009

=== Format string pattern ===

MMM display three-letter month
ddd display three-letter day of the WEEK
d display day of the MONTH
HH display two-digit hours on 24-hour scale
mm display two-digit minutes
yyyy display four-digit year

Notes on the letters. The letters in the format string above specify the output you want to display. The final comment shows what the MMM, ddd, d, HH, mm, and yyyy will do.

2. Modifying DateTime format string

Here we see how you can modify the DateTime format string in the above example to get different output with ToString. We change some of the fields so the resulting value is shorter.

=== Program that uses different format (C#) ===

using System;

class Program
{
static void Main()
{
DateTime time = DateTime.Now; // Use current time
string format = "M d h:mm yy"; // Use this format
Console.WriteLine(time.ToString(format)); // Write to console
}
}

=== Output of the program ===

2 27 11:48 09

=== Format string pattern ===

M display one-digit month number [changed]
d display one-digit day of the MONTH [changed]
h display one-digit hour on 12-hour scale [changed]
mm display two-digit minutes
yy display two-digit year [changed]

Note on format string usages. You will also need to specify a format string when using DateTime.ParseExact and DateTime.ParseExact. This is because those methods require a custom pattern to parse.

3. Single-letter DateTime format strings

Here we see that you can use a single character with ToString or DateTime.ParseExact to specify a preset format available in the framework. These are standard formats and very useful in many programs. They can eliminate typos in the custom format strings.

=== Program that tests formats (C#) ===

using System;

class Program
{
static void Main()
{
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("d"));
Console.WriteLine(now.ToString("D"));
Console.WriteLine(now.ToString("f"));
Console.WriteLine(now.ToString("F"));
Console.WriteLine(now.ToString("g"));
Console.WriteLine(now.ToString("G"));
Console.WriteLine(now.ToString("m"));
Console.WriteLine(now.ToString("M"));
Console.WriteLine(now.ToString("o"));
Console.WriteLine(now.ToString("O"));
Console.WriteLine(now.ToString("s"));
Console.WriteLine(now.ToString("t"));
Console.WriteLine(now.ToString("T"));
Console.WriteLine(now.ToString("u"));
Console.WriteLine(now.ToString("U"));
Console.WriteLine(now.ToString("y"));
Console.WriteLine(now.ToString("Y"));
}
}

=== Output of the program ===

d 2/27/2009
D Friday, February 27, 2009
f Friday, February 27, 2009 12:11 PM
F Friday, February 27, 2009 12:12:22 PM
g 2/27/2009 12:12 PM
G 2/27/2009 12:12:22 PM
m February 27
M February 27
o 2009-02-27T12:12:22.1020000-08:00
O 2009-02-27T12:12:22.1020000-08:00
s 2009-02-27T12:12:22
t 12:12 PM
T 12:12:22 PM
u 2009-02-27 12:12:22Z
U Friday, February 27, 2009 8:12:22 PM
y February, 2009
Y February, 2009

4. ToLongDateString and ToShortDateString

Here we see the ToLongDateString, ToLongTimeString, ToShortDateString, and ToShortTimeString methods on DateTime. These methods are equivalent to the lowercase and uppercase D and T methods shown in the example above.

=== Program that uses ToString methods (C#) ===

using System;

class Program
{
static void Main()
{
DateTime now = DateTime.Now;
Console.WriteLine(now.ToLongDateString()); // Equivalent to D
Console.WriteLine(now.ToLongTimeString()); // Equivalent to T
Console.WriteLine(now.ToShortDateString()); // Equivalent to d
Console.WriteLine(now.ToShortTimeString()); // Equivalent to t
Console.WriteLine(now.ToString());
}
}

=== Output of the program ===

ToLongDateString Friday, February 27, 2009
ToLongTimeString 12:16:59 PM
ToShortDateString 2/27/2009
ToShortTimeString 12:16 PM
ToString 2/27/2009 12:16:59 PM

Note on default ToString method. The default ToString method on DateTime shown above is equivalent to the simple "G" formatting string in the previous example. In other words, ToString("G") and ToString() do the same thing.

5. Formatting characters

When you use DateTime.ParseExact, or ToString(), you need to specify a formatting string, which is a sequence of characters that designate how the final result will look. What follows are the author's notes on the strings from MSDN.

StringsNotes
dUse this to specify the numeric value for the day of the month.
It will be 1 or 2 digits long.
ddThis is the same as a single d, except there are always two digits, with a leading 0 prepended if necessary.
dddThis displays a three-letter string that indicates the current day of the week.
[See example after table]
ddddThis displays the full string for the day of the week.
[See example after table]
f
ff
fff
ffff
fffff
ffffff
fffffff
F
FF
FFF
FFFF
FFFFF
FFFFFF
FFFFFFF
Use the lowercase f to indicate the seconds to one digit length.
Use two lowercase fs to indicate the seconds to 2 digits.
Equivalent functionality for fff.
The uppercase F patterns do the same but work differently on trailing zeros.
ggUse this to display A.D. on your date.
It is unlikely that this will be B.C. in most programs.
[See example below table]
hDisplay the hours in one digit if possible.
If the hours is greater than 9, it will display two digits.
Range is 1-12.
hhDisplay the hours in two digits always, even if the hour is one digit.
The range here will be 01-12.
HThis represents the hours in a range of 0-23, which is called military time in some parts of the world. [See next row for two digits and link.]
HHThis represents the hours in a range of 00-23.
The only different here between the single H is that there is always a leading zero if the number is one digit. [C# 24-Hour and Military Time Methods - dotnetperls.com]
KUse this to display time zone information.
[Not shown]
m
mm
This formats the minutes in your date format string.
Here, the one m means that there is only one digit displayed if possible.
The two ms means that there are always two digits displayed, with a leading zero if necessary.
M
MM
These display the months in numeric form.
The one uppercase M does not have a leading zero on it.
The two uppercase Ms will format a number with a leading zero if it is required.
MMMThis displays the abbreviated three-letter form of the month represented in the DateTime.
[See example after table]
MMMMThis displays the full month string, properly capitalized.
[See example]
s
ss
The lowercase s displays seconds.
A single lowercase s means that you do not require a leading zero.
Two lowercase s characters means you always want two digits, such as 00-59.
tUse the lowercase t to indicate A, when the time is in the AM, and P, for when the time is in PM.
[See example]
ttUse two lowercase tts to display the full AM or PM string.
You will normally want this for when you are displaying the string to a user.
[See example after table]
y
yy
yyy
yyyy
yyyyy
These display the year to different digits.
In your programs, you won't need three digits for the year, or five.
Therefore, you should only consider 1 y, 2 ys, or 4 ys.
[See example]
z
zz
zzz
These represent the offset from the UTC time on the local operating system.
:This is the time separator.
/This is the date separator.
 Most other characters will be printed to the output string without any modification.

6. Difference between d and dd, ddd and dddd

It is important to note that d and dd (1 and 2 ds) mean something entirely different than ddd and dddd (3 and 4 ds). d and dd indicate the day of the MONTH, while ddd and dddd indicate the day of the WEEK, in a word. [See table above.]

7. Three-letter days

In some systems it may be useful to display the day of the week in a three-letter form. Here we see a simple program that prints out the days of the week in three-letter format. This will vary based on the language installed on the computer.

=== Program that tests days (C#) ===

using System;

class Program
{
static void Main()
{
DateTime now = DateTime.Today;
for (int i = 0; i < 7; i++)
{
Console.WriteLine(now.ToString("ddd"));
now = now.AddDays(1);
}
}
}

=== Output of the program ===

Thu
Fri
Sat
Sun
Mon
Tue
Wed

8. Displaying complete day

Often you need to display the complete day of the week in C#, and the four ds together will do this for you. This simple program shows all seven different day strings you can get from the dddd.

=== Program that shows day strings (C#) ===

using System;

class Program
{
static void Main()
{
DateTime now = DateTime.Today;
for (int i = 0; i < 7; i++)
{
Console.WriteLine(now.ToString("dddd"));
now = now.AddDays(1);
}
}
}

=== Output of the program ===

Thursday
Friday
Saturday
Sunday
Monday
Tuesday
Wednesday

9. Displaying the era

The .NET platform allows you to display the date with the era or period, which is usually A.D. or B.C. It is unlikely that you will need to use B.C., except in a rare theoretical application. Nevertheless, here is what the two gs will print. [Use the code |DateTime.Now.ToString("gg");|]

10. Month property and strings

You may need to display the month name in a three-letter format. This is equivalent, in English, to taking a substring of the first three letters, but using the 3 Ms next to each other may be easier and more terse for your code. Additionally, you may want full month strings. This site contains a useful article that covers DateTime month strings and the Month property in more detail. [C# DateTime.Month Property - dotnetperls.com]

11. Displaying AM/PM—first letter only

This isn't something you are likely to need, but interesting to find out. When you specify one t, you can get the first letter of the AM or PM string. This is equivalent to using Substring or getting the first char of the tt string. There is a space at the end of the format string because the value "t" can mean something else in the format string.

12. Displaying AM/PM—full string

Here we see how you can get the string AM or PM in your DateTime ToString code. The code adds 12 to ensure the second iteration is in the other half.

=== Program that displays AM and PM (C#) ===

using System;

class Program
{
static void Main()
{
DateTime now = DateTime.Now;
for (int i = 0; i < 2; i++)
{
Console.WriteLine(now.ToString("tt "));
now = now.AddHours(12);
}
}
}

=== Output of the program ===

PM
AM

Note on lack of periods. There are no periods in the output of tt in the example above. Therefore, if you require periods in your AM or PM, you would have to manipulate the string.

13. Displaying year to different digits

You can vary the number of digits displayed in the year string. You will always want to use y, yy, or yyyy for your programs. The framework accepts different numbers, but they are impractical in the real world. Occasionally two ys is useful for a user-oriented program, but for your back end code, you will want to use four ys. You do not need uppercase Ys.

=== Program that displays years (C#) ===

using System;

class Program
{
static void Main()
{
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("y "));
Console.WriteLine(now.ToString("yy"));
Console.WriteLine(now.ToString("yyy")); // <-- Don't use this
Console.WriteLine(now.ToString("yyyy"));
Console.WriteLine(now.ToString("yyyyy")); // <-- Don't use this
}
}

=== Output of the program ===

9
09
2009
2009
02009

14. Summary

Here we saw lots of information and examples regarding DateTime format strings. We covered single-letter preset format strings, and more complicated custom format strings with different character codes. We saw an overview of the custom code letters. Finally, we saw enumerations of all the values for days of the week, months, and also three-letter versions of those. More general examples that use the format string system in the .NET Framework are available. [C# string.Format Method - dotnetperls.com] [Page protected by Copyscape. Do not copy.]

 

原文链接: http://dotnetperls.com/datetime-format

 

 

posted @ 2009-11-10 15:29 Jerry Hu 阅读(10624) 评论(0) 编辑

2009年10月22日

不同服务器数据库之间的数据操作

--创建链接服务器
exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '远程服务器名或ip地址 '
exec sp_addlinkedsrvlogin 'ITSV ', 'false ',null, '用户名 ', '密码 '

--查询示例
select * from ITSV.数据库名.dbo.表名

--导入示例
select * into 表 from ITSV.数据库名.dbo.表名

--以后不再使用时删除链接服务器
exec sp_dropserver 'ITSV ', 'droplogins '

--连接远程/局域网数据(openrowset/openquery/opendatasource)
--1、openrowset

--查询示例
select * from openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)

--生成本地表
select * into 表 from openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)

--把本地表导入远程表
insert openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)
select *from 本地表

--更新本地表
update b
set b.列A=a.列A
from openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)as a inner join 本地表 b
on a.column1=b.column1

--openquery用法需要创建一个连接

--首先创建一个连接创建链接服务器
exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '远程服务器名或ip地址 '
--查询
select *
FROM openquery(ITSV, 'SELECT * FROM 数据库.dbo.表名 ')
--把本地表导入远程表
insert openquery(ITSV, 'SELECT * FROM 数据库.dbo.表名 ')
select * from 本地表
--更新本地表
update b
set b.列B=a.列B
FROM openquery(ITSV, 'SELECT * FROM 数据库.dbo.表名 ') as a
inner join 本地表 b on a.列A=b.列A

--3、opendatasource/openrowset
SELECT *
FROM opendatasource( 'SQLOLEDB ', 'Data Source=ip/ServerName;User ID=登陆名;Password=密码 ' ).test.dbo.roy_ta
--把本地表导入远程表
insert opendatasource( 'SQLOLEDB ', 'Data Source=ip/ServerName;User ID=登陆名;Password=密码 ').数据库.dbo.表名
select * from 本地表


posted @ 2009-10-22 09:51 Jerry Hu 阅读(53) 评论(0) 编辑

2009年4月1日

SQL Server 的事务日志意外增大或充满的处理方法

事务日志文件Transaction Log File是用来记录数据库更新情况的文件,扩展名为ldf。
在 SQL Server 7.0 和 SQL Server 2000 中,如果设置了自动增长功能,事务日志文件将会自动扩展。
一般情况下,在能够容纳两次事务日志截断之间发生的最大数量的事务时,事务日志的大小是稳定的,事务日志截断由检查点或者事务日志备份触发。
然而,在某些情况下,事务日志可能会变得非常大,以致用尽空间或变满。通常,在事务日志文件占尽可用磁盘空间且不能再扩展时,您将收到如下错误消息:
Error:9002, Severity:17, State:2
The log file for database '%.*ls' is full.
除了出现此错误消息之外,SQL Server 还可能因为缺少事务日志扩展空间而将数据库标记为 SUSPECT。有关如何从此情形中恢复的其他信息,请参见 SQL Server 联机帮助中的“磁盘空间不足”主题。

另外,事务日志扩展可能导致下列情形:
· 非常大的事务日志文件。
· 事务可能会失败并可能开始回滚。
· 事务可能会用很长时间才能完成。
· 可能发生性能问题。
· 可能发生阻塞现象。

原因
事务日志扩展可能由于以下原因或情形而发生:
· 未提交的事务
· 非常大的事务
· 操作:DBCC DBREINDEX 和 CREATE INDEX
· 在从事务日志备份还原时
· 客户端应用程序不处理所有结果
· 查询在事务日志完成扩展之前超时,您收到假的“Log Full”错误消息
· 未复制的事务

解决方法
日志文件满而造成SQL数据库无法写入文件时,可用两种方法:
一种方法:清空日志。
1.打开查询分析器,输入命令
DUMP TRANSACTION 数据库名 WITH NO_LOG
2.再打开企业管理器--右键你要压缩的数据库--所有任务--收缩数据库--收缩文件--选择日志文件--在收缩方式里选择收缩至XXM,这里会给出一个允许收缩到的最小M数,直接输入这个数,确定就可以了。

另一种方法有一定的风险性,因为SQL SERVER的日志文件不是即时写入数据库主文件的,如处理不当,会造成数据的损失。
1: 删除LOG
分离数据库 企业管理器->服务器->数据库->右键->分离数据库
2:删除LOG文件
附加数据库 企业管理器->服务器->数据库->右键->附加数据库
此法生成新的LOG,大小只有500多K。

注意:建议使用第一种方法。

如果以后,不想要它变大。
SQL2000下使用:
在数据库上点右键->属性->选项->故障恢复-模型-选择-简单模型。
或用SQL语句:
alter database 数据库名 set recovery simple


另外,如上图中数据库属性有两个选项,与事务日志的增长有关:
Truncate log on checkpoint
(此选项用于SQL7.0,SQL 2000中即故障恢复模型选择为简单模型)
当执行CHECKPOINT 命令时如果事务日志文件超过其大小的70% 则将其内容清除在开发数据库时时常将此选项设置为True
Auto shrink
定 期对数据库进行检查当数据库文件或日志文件的未用空间超过其大小的25%时,系统将会自动缩减文件使其未用空间等于25% 当文件大小没有超过其建立时的初始大小时不会缩减文件缩减后的文件也必须大于或等于其初始大小对事务日志文件的缩减只有在对其作备份时或将 Truncate log on checkpoint 选项设为True 时才能进行。


注意:一般立成建立的数据库默认属性已设好,但碰到意外情况使数据库属性被更改,请用户清空日志后,检查数据库的以上属性,以防事务日志再次充满。

 

摘自: http://www.bokesun.com/blogger/laobai/archives/2009/70717.shtml

 

P.S. 

The shrinking of  TL process is changed in SQL Server 2008. You just need to

(a) set the database to simple recovery model

(b) Shirnk the file

(c) Set back to Full (If required). ie. If you are not taking TL backup let it be in Simple recovery model only


 


posted @ 2009-04-01 12:28 Jerry Hu 阅读(892) 评论(0) 编辑

2006年8月30日

posted @ 2006-08-30 16:55 Jerry Hu 阅读(1387) 评论(16) 编辑

2006年8月11日

摘要: /**//////////////////////////////////////////////////////////////////////////////////SAMPLE:Generatesrandompassword,whichcomplieswiththestrongpassword//rulesanddoesnotcontainambiguouscharacters.////To...阅读全文

posted @ 2006-08-11 15:16 Jerry Hu 阅读(507) 评论(3) 编辑