java(Syntax error, insert ";" to complete LocalVariableDeclarationStatement)

java(Syntax error, insert “;” to complete LocalVariableDeclarationStatement)

1、缺少“;”标点在句尾
2、句中有中文空格
3、“;”的大小写问题
4、String[][] getFileInput(String Path) throws Exception {
private static double[][] getFileInput(String pathName) throws Exception {

txt转化为二维数组
(1)private static double[][] getFileInput(String pathName) throws Exception {
FileInputStream inputStream = null;
Scanner sc = null;
List<double[]> list = new ArrayList<>();
inputStream = new FileInputStream(pathName);
sc = new Scanner(inputStream, “utf-8”);
while (sc.hasNextLine()) {
String line = sc.nextLine();
int s = 0;
String[] arr = line.split(",");
double[] dArr = new double[arr.length];
for (String ss : arr) {
if (ss != null) {
dArr[s++] = Double.parseDouble(ss);
}
}
list.add(dArr);
}
int max = 0;
for (int i = 0; i < list.size(); i++) {
if (max < list.get(i).length)
max = list.get(i).length;
}
double[][] array = new double[list.size()][max];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < list.get(i).length; j++) {
array[i][j] = list.get(i)[j];
}
}
inputStream.close();
sc.close();
return array;
}

(2)private static double[][] getFileInput(String pathName) throws Exception {
FileInputStream inputStream = null;
Scanner sc = null;
List<double[]> list = new ArrayList<>();
inputStream = new FileInputStream(pathName);
sc = new Scanner(inputStream, “utf-8”);
while (sc.hasNextLine()) {
String line = sc.nextLine();
int s = 0;
String[] arr = line.split(",");
double[] dArr = new double[arr.length];
for (String ss : arr) {
if (ss != null) {
dArr[s++] = Double.parseDouble(ss);
}
}
list.add(dArr);
}
int max = 0;
for (int i = 0; i < list.size(); i++) {
if (max < list.get(i).length)
max = list.get(i).length;
}
double[][] array = new double[list.size()][max];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < list.get(i).length; j++) {
array[i][j] = list.get(i)[j];
}
}
inputStream.close();
sc.close();
return array;
}

作者:fengzhimohan
来源:CSDN
原文:https://blog.csdn.net/fengzhimohan/article/details/84644523

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
v3.17 * updated libFLAC to version 1.2.1 * added a flush after every log line to help GUIs * "eac3to some.mpls" now also works if the stream files aren't there, anymore * fixed: number of subtitles was not appended to demuxed subtitles' file name * fixed: dialnorm removal (for Nero decoder) failed with some 2.0 TrueHD files v3.16 * added undocumented "-no2ndpass" switch to turn off 2nd pass processing * fixed: two pass processing sometimes produced superfluous sup files * fixed: MPG/EVO/VOB audio tracks with "PES extension 2" were not detected * fixed: very small W64/RF64 files were not detected correctly * fixed: when processing was aborted, log file was sometimes not created * fixed: sometimes specifying a title number addressed the wrong HD DVD title v3.15 * "24.975" is now interpreted as "25.000/1.001" * Blu-Ray "sup" are demuxed with DTS set to 0 again, proper fix will come later * fixed: error code not set for "source file format could not be detected" * fixed: audio resampling from/to 24.975 didn't work properly * fixed: WAV files beginning with lots of zeroes were sometimes not accepted v3.14 * WAV reading was broken for all but very small files (introduced in v3.13) v3.13 * fields and frames are counted and displayed separately now * added DIRAC bitstream parser * added support for "-24.975" and "-changeto24.975" * Blu-Ray subtitle demuxing: PTS value is now written to both PTS + DTS * joining MKV files is now declined with a proper error message * last chapter is now removed, if it's less than 10 seconds from end of movie * fixed: "-normalize" didn't work with stdout, anymore * fixed: audio delay was incorrect when 1st m2ts part contained no audio data * fixed: very small WAV files were not detected correctly * fixed: "eac3to source.eac3 dest.dts -core" crashed v3.12 * fixed: track languages for HD DVD discs were not shown * fixed: MLP channel order was wrong for some specific channel configurations * fixed: "DirectShow reported 255 channels" happened sometimes v3.11 * fixed: MKV subtitle track language wasn't shown v3.10 * Blu-Ray title listing now includes chapter information * fixed: v3.09 didn't show track languages for Blu-Rays v3.09 * added support for MKV "SRT/UTF8", "SRT/ASCII", "ASS" and "SSA" subtitles * increased some internal buffers to avoid AC3 overflow in the "thd ac3 joiner" * fixed: frame counting didn't work for MKV video tracks * fixed: video track FPS change was sometimes declined * fixed: video tracks with "strange" FPS were sometimes handled incorrectly * fixed: clipping removal 2nd pass was executed even for "stdout" * fixed: "eac3to -test" displayed an outdated Nero download link * fixed: specifying a specific playlist still used default playlist's chapters v3.08 * fixed: reading physical disc speed was abysmal (introduced in v3.07) * fixed: read error from physical drive resulted in crash v3.07 * added support for MKV video tracks without sequence headers in bitstream * added support for old style MKV AAC tracks * added support for various MKV "A_MS/ACM" audio formats * added support for various MKV "V_MS/VFW/FOURCC" video formats * added warning for tracks where bitstream parsing failed * demuxing a video track now also complains about video gaps/overlaps * the "-check" option now also complains about video gaps/overlaps * optimized memory allocation * fixed: adding subtitle caption count to filenames sometimes didn't work * fixed: subtitle caption counts in log sometimes had wrong track numbers * fixed: all non-supported MKV tracks shared the same description * fixed: incorrect framerate mismatch complaint was shown for pulldown sources * fixed: FLAC tracks in MKV files don't slow down detection, anymore * fixed: source file detection read 300MB from every source file v3.06 * added MKV reading/parsing support * added demux support for MKV (E-)AC3, DTS(-HD), AAC, MPx, FLAC and WAV tracks * added demux support for MKV "modern style" MPEG2, VC-1 and h264/AVC tracks * reading from (HD) DVD and Blu-Ray drives uses different reading APIs now * empty tracks in TS/m2ts container are not listed, anymore * for 24.000 fps video tracks a little warning is displayed now * when demuxing subtitle files, the number of captions is added to the filename * timestamp derived FPS is used for gap checking instead of video bitstream FPS * fixed: 44.1khz AC3 encoding was still broken * fixed: zero byte stripping pass was done for true 24bit TrueHD tracks * fixed: downconverting WAV files with 0x3f channel mask didn't work * fixed: log output "remaining delay [...]" was sometimes wrong for AC3 tracks * fixed: silent frame creation was tried for E-AC3 although it can't work v3.05 * warning is shown if h264 video bitstream contains "full range" flag * h264 video bitstream "full range" flag is automatically removed * you can disable removal of the "full range" flag by doing "-keepFullRange" * added reader for external DVD, HD DVD and Blu-Ray SUP files * external SUP files can be delayed now * number of HD DVD and DVD subtitles in SUP track is counted and displayed * number of forced and non-forced Blu-Ray subtitles in SUP track is displayed * "-check" option now also works for demuxed audio, video and subtitle tracks * when reading from physical disc drive, 2KB (instead of 1MB) blocks are read * improved automatic skipping over damaged first 5MB of TS/m2ts files * fixed: resampling and Surcode encoding didn't work in one step * fixed: TRP detection crashed * fixed: track listing sometimes contained tracks without description * fixed: h264 with missing framerate in 1st sequence header made eac3to crash * fixed: some AC3WAV files were not detected correctly * fixed: video frame count was not displayed when 2nd pass was executed v3.04 * video track framerates are now shown with up to 3 decimals, if necessary * m2ts/TS framerate is determined by interpreting video track timestamps * m2ts/TS framerate is displayed in the format description (if available) * warning is shown if container timestamps don't match video framerate * warning is shown if video bitstream has a non-standard framerate * video without framerate information: container framerate is used * video without framerate information: framerate can be set (e.g. "-23.976") * video without framerate information: new framerate is written to bitstream * remaining non-fixed audio delay is now shown in log * command prompt colors are restored after eac3to has run through * fixed: 2-pass processing for stripping zero bytes sometimes crashed * fixed: CA (Conditional Access) tracks were shown as "Unknown audio track" v3.03 * fixed: MPEG2 1088 to 1080 cropping was still incomplete v3.02 * fixed: VC-1 stream handling was broken * fixed: destination file extension "*.lpcm" didn't work with 2pass processing * fixed: MPEG2 1088 to 1080 cropping was incomplete * fixed: no log was being created when "temp file could not be interpreted" v3.01 * fixed: m2ts LCPM demuxing didn't work with v3.00 * fixed: TrueHD -> TrueHD+AC3 conversion didn't work with v3.00 v3.00 * broken AC3, DTS, AAC and MPx streams are now automatically repaired * errors in TS/m2ts files are now reported (with runtime) and ignored * damaged first max 5MB and max 5% of a TS/m2ts file are automatically skipped * video/audio tracks which can't be parsed, are now demuxed in raw form * added support for "line 21" closed captions in ATSC/NTSC broadcasts and DVDs * added reading of movie / network name from "line 21" XDS information * for gaps, edits & repairs > 1000ms eac3to now inserts silence by default * for gaps, edits & repairs < 1000ms eac3to now loops audio by default * option "-silence" forces eac3to to insert silence instead of looping audio * option "-loop" forces eac3to to loop audio instead of inserting silence * newly encoded AC3 frame is now used for "silence" instead of file's 1st frame * increased reading block size (might improve reading performance) * optimized TS/m2ts demuxing performance * optimized MPEG2, VC-1 and h264 parsing performance * command line output is colored now (e.g. errors drawn in red) * MPEG2 1920x1088 bitstream is now automatically patched/cropped to 1920x1080 * log file now contains "<WARNING>" and "<ERROR>" indicators * workaround for movie playlists which want the same m2ts file played twice * added version check for eac3to (doh!) * when a read error occurs, reading is tried again up to 3 times * (E-)AC3 frames with -0db dialnorm are now automatically patched to -31db * updated to newer libAften build -> fixes 44.1khz encoding * fixed: sometimes "The last DTS frame is incomplete" was a false alarm * fixed: mkvtoolnix version check didn't work, anymore * fixed: errors were meant to be output to stderr, but they weren't * fixed: automatic gap/overlap fixing with AAC targets aborted processing * fixed: positive edit began a bit too early * fixed: two ID3 tags after each other made eac3to fail detecting the format * fixed: some VOB files were not detected properly v2.87 * fixed: negative edit was done too late (introduced in v2.86) v2.86 * fixed: "1:some.ac3" instead of "1: some.ac3" failed for 2 digit track numbers * fixed: "eac3to source movie.mkv" demuxed video instead of muxing to MKV * negative edit now begins at the specified runtime instead of ending there v2.85 * using "eac3to source video.h264" doesn't demux audio/subtitle tracks, anymore * using "eac3to source movie.*" demuxes video, audio and subtitle tracks * using "eac3to source 1: video.* 2: audio.*" demuxes the specified tracks * AC3 and E-AC3 dialnorm removal now uses "-31db" instead of "-0db" * workaround for DTS files where last byte is missing in each audio frame * fixed: v2.84 sometimes crashed when parsing HD DVD XML files * fixed: v2.84 sometimes chose incorrect XML file * fixed: v2.84 sometimes chose wrong m2ts playlist file * fixed: some actions were eventually applied twice when "-2pass" was used * fixed: AAC encoding quality "quality=0.0x" was passed to Nero as "0.x" v2.84 * fixed: 2nd pass gap removal was tried (and failed) for TrueHD+AC3 targets * fixed: processing aborted when trying to fix gaps in PCM destination files * fixed: more than one RAW/PCM overlaps resulted in lost sync (since v2.81) * fixed: demuxing TrueHD+AC3 stream by title number didn't renew the AC3 part * new option for removing or looping audio data, e.g. "-edit=0:20:47,-100ms" * title sorting criteria changed: resolution is more important than runtime * new option "-lowPriority" sets eac3to to background/idle priority * libav warnings are now assigned to the affected audio track * fixed: "lossless check failed" false alarms for seamless branching movies * fixed: spike removal filter was not active for the very last overlap/gap * improved muxing h264 streams which begin with double sequence headers * source files are now opened with "share read + write access" * destination files are now opened with "share read access" v2.83 * fixed: gap/overlap correction didn't work for FLAC and WAV files * fixed: when clipping was detected, 2nd pass was not always executed correctly v2.82 * fixed: sometimes eac3to stalled before processing (introduced in v2.81) v2.81 * audio gap/overlap fixing is now automatically done in a 2nd pass * option "-normalize" maximizes the volume of the audio data, needs 2 passes * audio clipping is detected and automatically removed in a 2nd pass * "-2pass" activates 2 pass mode (can speedup seamless branching processing) * superfluous zero bytes are now automatically removed in 2nd pass * "-phaseShift" shifts surround channel phase by 90?for DPL II downmixing * spike removal post processing filter now always produces 16bit samples * empty channels are now reported by the bitdepth analyzer as "no audio data" * option "-shutdown" shuts the PC down automatically after processing is done * the HD DVD XPL with the longest title is now loaded instead of VPLST000.XPL * eac3to can now open selected XPL files (e.g. "eac3to ADV_OBJ\VPLS002.XPL") * eac3to can now open selected mpls files (e.g. "eac3to PLAYLIST\00002.mpls") * fixed: TrueHD streams starting with a non-major header failed to decode * fixed: WAV files created by eac3to with empty channels had incorrect header * fixed: RAW/PCM gap/overlap remover sometimes didn't work correctly v2.80 * fixed: FLAC files with missing runtime information were not accepted * gone back to old VOB/EVO auto delay calculation method, more reliable for me * improved TS broadcast audio delay detection * added support for constant bitrate AAC encoding * added support for AAC encoding 0.00 and 1.00 quality v2.79 * improved m2ts file joining overlap detection (mainly for interlaced video) * vob/evo audio delay detection now uses "vobu start presentation time" * program streams which are neither VOB nor EVO are now reported as "MPG" * resampling is now automatically activated for AC3/DTS encoding, if necessary * "Mersenne Twister" random number generator is used for dithering now * zero padded DTS tracks are now displayed as such * fixed: 32bit PCM conversion to floating point was broken * fixed: with some (rare) movies first subtitle began after 50 minutes runtime * only plugins with the extension *.dll are loaded now v2.78 * fixed: h264 interlaced muxing to MKV could result in too long runtime * fixed: transcoding DTS-HD/E-AC3 core sometimes failed to work correctly * improved TS/m2ts audio delay detection * added filter to remove spikes when fixing gaps/overlaps in RAW/PCM audio * each eac3to instance has its own log file now * playlist output now also works with "-log" option * default bitrate for mono & stereo AC3 encodes lowered to 448kbps * default bitrate for mono & stereo DTS encodes lowered to 768kbps * it should be possible to handle TsSplitter splitted TS files via "+" now v2.77 * pcm/raw audio delay is now applied before resampling and fps change * parsing of command line with multiple sources files sometimes failed v2.76 * "-slowdown" now works to convert 24.000 movies to 23.976 * "-speedup" now works to convert 24.000 movies to 25.000 * option "-xx.xxx" (e.g. "-24.000") sets the FPS of the source track * option "-changeToXx.xxx" (e.g. "-changeTo23.976") changes video/audio FPS * modified FPS information is written to video bitstream (VC-1, MPEG2, h264) * demuxing with FPS change option now activates audio track transcoding * SSRC resampling parameters modified slightly to reduce steepness and ringing * fixed incorrect h264 movie slowdown gap/overlap complaints * fixed DTS-HD High Resolution bitrate calculation * dithering is now done differently per channel v2.75 * added (E-)AC3 5.1 "EX" detection * added (E-)AC3 2.0 "Surround" detection * added (E-)AC3 2.0 "Headphone" detection * NeroAacEnc is now fed with up to 32bit float (if available) * resampling option "-quality=low|high|ultra" not supported, anymore * new option "-fast" switches SSRC resampler to fast, but low quality mode * new option "-r8brain" forces use of r8brain resampler instead of SSRC * added support for AES3 PCM streams in TS container * started working on encoder plugin interface v2.74 * "-demux" failed to work for DTS-HD and "TrueHD/AC3" tracks in v2.73 * fixed: DTS-HD tracks could make processing abort at the very end of the movie v2.73 * changed TS demuxing logic to make the broken (!) new SkyHD broadcasts work * DTS core and "TrueHD/AC3" AC3 parameters are displayed separately now * when using "-core" option, eac3to now bases its decisions on core parameters * added WAV/W64/RF64 read/write support for 32bit PCM and 32/64 bit float * option "-full" allows WAV/W64/RF64 output to be native (default <= 24bit PCM) * Surcode DTS encoding is now done with up to 32bit float (if available) * Aften AC3 encoding is now done with up to 64bit float (if available) v2.72 * fixed: per channel bitdepth analyzation didn't work correctly v2.71 * fixed: v2.70 detected Blu-Rays as "TS" without chapters and track languages * fixed: TrueHD downmixing to 2.0 didn't work v2.70 * added floating point support to the complete audio processing chain * added gain functionality, e.g. "-3db" or "+1db" * bitdepth analyzation is now done separately for each channel * fixed: when decoding lossy audio with libav, peaks were clipped incorrectly * fixed: libav MP1/2/3 decoder output was cut down to 24bit * fixed: with some EVO sources the AC3 track was not listed * fixed: if no key frame was found, h264 track in m2(ts) was not listed * fixed: video/audio data before first PAT/PMT was discarded * Blu-Ray chapters now don't contain link points, anymore, unless necessary * added 10db boost to LFE channel, when "-down2" and "-mixlfe" are used * ArcSoft output can now be overwritten to "-2", "-6", "-7" or "-8" channels v2.69 * added high precision SSRC resampler * resampling "-quality" now allows "low", "high" (SSRC) or "ultra" (r8brain) * resampling quality now defaults to "high" (SSRC) * bitdepth is now analyzed separately for original vs. processed data * fixed: downmixing 16 bit DTS tracks to 5.1 or 2.0 didn't work * fixed: Sonic Decoder was incorrectly assumed to decode XXCh DTS files to 6.1 * for movies the Haali Muxer can't handle "-seekToIFrames" is suggested now v2.68 * fixed crash when transcoding Blu-Ray/HD DVD track to FLAC v2.67 * information about HDCD and real bitdepth is now stored into FLAC metadata * information about real bitdepth is now read from FLAC metadata * PTS break: PTS is increased by 1 frame (fixes some false overlap warnings) * fixed: video gap log text was sometimes not correct (runtime information) * added undocumented switch "-neroaacenc="c:\whatever\neroaacenc.exe"" * error log messages are now output to stderr instead of stdout * improved "which mkvtoolnix is currently installed?" check * fixed: mkvtoolnix version check "Oct" date was not interpreted correctly v2.66 * changed eac3to to allow AAC encoding with 7.1 channels (for new Nero encoder) * fixed AGM creation for files bigger than 4GB * added support for Nero's new AAC Encoder download URL * lowered volume of error/success sounds * when there are 2 similar playlists the one with less chapters is ignored now v2.65 * automatic channel remapping for 6.1 tracks with wrong channel mask * automatic channel remapping for ArcSoft DTS decoder 6.1 tracks * fixed: TrueHD -> Surcode encoding didn't work, anymore * fixed: MPEG2 + h264 video gap/overlap removal didn't work properly v2.64 * added channel mask reading support to Blu-Ray PCM track parser * added channel mask reading support to TrueHD parser * added channel mask reading & writing support to FLAC decoder / encoder * changed 5.x channel mask from $03x to $60x * changed 6.x channel mask from $13x to $70x * mono wavs output now creates correct names for some channel masks * when transcoding 6.1 sources to PCM, 7 channel doubling is activated now * fixed: DTS channelmask detection was incorrect for very strange configs * fixed: sometimes the h264 video stream of a Blu-Ray m2ts was not detected v2.63 * fixed: incorrect detection of 6.0 DTS tracks as 5.0 * fixed: incorrect libav DTS channel remapping for 6.x or 7.x tracks * fixed: incorrect ArcSoft DTS channel remapping for "6.0" and "2/2.1" tracks * fixed: v2.61+62 incorrectly decoded 16bit TrueHD tracks to 24bit FLAC/WAV/RAW * fixed: some DTSWAV files made HDCD decoder crash * fixed: DTSWAV and AC3WAV samplerate and bitdepth were reported incorrectly * improved DirectShow channel configuration reporting * undocumented option -progressnumbers now outputs "analyze:" and "process:" v2.62 * fixed: downmixing 16 bit 7.1 DTS tracks to 5.1 stopped working in v2.61 v2.61 * option "-no7doubling" is not supported anymore * option "-double7" added which upconverts 6.1 to 7.1 * added read/write support for Sony wave64 (*.w64) format * added read/write support for RF64 wave64 (*.rf64) format * added write support for AGM format * true bitdepth (e.g. 18 bits) is written to extensible wav header now * when reading 16/24 (true/storage) WAV files, zero bytes are stripped now * added HDCD detection for WAV and FLAC files * added HDCD detection for PCM tracks in VOB/EVO/m2ts containers * added HDCD decoder written by Christopher Key * added new option "-decodeHdcd" to decode HDCD information * HDCD track -> lossy format: HDCD decoding is automatically activated * when DTS-MA and TrueHD tracks are decoded, a check for HDCD is done * fixed some incorrect DTS channel masks * added automatic libav DTS channel remapping * added automatic ArcSoft DTS channel remapping * added channel map manipulation to make funny DTS tracks decode with Sonic * added channel map manipulation to make funny DTS tracks decode with ArcSoft * added channel volume modification to undo ArcSoft mono surround splitting * for TrueHD+AC3 creation AC3 delay and gap correction are disabled now * fixed: DTSWAV and DTSAC3 readers reported too long runtime * fixed: sometimes processing aborted with a "bitdepth reducer" complaint v2.60 * fixed: in v2.59 "-analyzeBitdepth" stopped working for Blu-Ray TrueHD tracks v2.59 * extension ".thd+ac3" is supported now to define destination format * TrueHD tracks without AC3 core can be converted to TrueHD/AC3 now * demuxing a single-part Blu-Ray title keeps the original "TrueHD/AC3" data * demuxing a multi-part Blu-Ray title automatically redoes the AC3 substream * added workaround for Blu-Ray playlists with multiple last "invalid" parts * fixed: "-check" didn't work for LPCM tracks v2.58 * h264 parser rewritten: framerate, pulldown etc is detected reliably now * h264 pulldown is automatically removed from progressive movie sources now * h264 pulldown removal can be disabled by using "-keepPulldown" * h264 muxing now fully supports streams with mixed 23.976 and 29.970 content * h264 1920x1088 bitstream is now automatically patched/cropped to 1920x1080 * h264 filler data is now already removed during demuxing * h264 sources with funny framerates (e.g. Luxe.tv HD) are patched to 25fps now * mixed video/movie h264 streams are now always muxed with 29.970 timestamps * speedup/slowdown now changes framerate information in the h264 bitstream * options "-24p", "-60i" and "-30p" are no longer supported * fixed Blu-Ray seamless branching subtitle remuxing * added workaround for Blu-Ray playlists with a last small "invalid" m2ts part * bitdepth analyzation is now done for decoded FLAC, WAV, PCM, DTS MA, too * bitrate is now also reported for FLAC, WAV and PCM tracks * when encoding AC3, DTS or AAC, the encoding bitrate is reported * fixed: v2.57 incorrectly decoded 16bit TrueHD tracks to 24bit FLAC/WAV/RAW * (M2)TS discontinuities before the first unit start are ignored now * new option "-progressnumbers" replaces progress bar with percentage numbers v2.57 * added automated support for Nero AAC command line encoder * added "quality=0.xx" (0.00 - 0.99) parameter to control AAC encoder quality * added Nero AAC encoder check to the "-test" list * "-test" checks whether a new Haali Matroska Muxer version is available * "-test" checks whether a new MkvToolnix release build is available * "-test" checks whether a new MkvToolnix beta build is available * "-test" checks whether a new Nero AAC encoder version is available * added TRP container support (TS files without PMT/PAT) * parameter "-extensible" is no longer supported (it's default now) * new parameter "-simple" can be used to disable the "-extensible" wav header * decoded TrueHD tracks: bitdepth is now automatically analyzed in more detail * option "-analyzeBitdepth" manually activates extended bitdepth analyzation * DVB subtitle tracks are listed now - can't be demuxed, though * option "-check" doesn't fail on DTS Express tracks, anymore v2.56 * fixed: processing aborted when a VC-1 sequence end code was found v2.55 * AAC bitstream parser added * AAC auto detection added * AAC bitstream delay added * AAC bitstream gap/overlap correction added * AAC decoding (Nero & Sonic) added * old MP2 parser now "officially" and properly supports MP1, MP2 and MP3 * MP3 decoding (libav & Nero) added * added support for MPEG Audio version 2 and version 2.5 * added (limited) support for ID3, APE and LYRICS tags in MP3 and AAC tracks * improved VOB/EVO audio delay detection algorithm * detection and automatic skipping of invalid vob units * options "-60i" and "-24p" are no longer supported for MPEG2 video * improved detection of MPEG2 framerate / pulldown state / mode * improved MPEG2 muxing warnings * several bugs in MPEG2 video muxing fixed * fixed interlaced VC-1 muxing with user data (Nine Inch Nails) v2.54 * VC-1 pulldown removal rewritten (comparable to vc1conv 0.4, but faster) * VC-1 pulldown removal is activated by default * VC-1 pulldown removal can be manually deactivated by "-keepPulldown" option * VC-1 pulldown removal is also available and activated when muxing to MKV now * fixed Blu-Ray subtitle demuxing for seamless branching movies * better task separation when doing multiple operations with an audio track v2.53 * Blu-Ray PGS subtitle demuxing support added * added support for EVO/VOB subtitles which begin very late in the file * MPEG2 video muxing doesn't rely on GOP headers, anymore * all (M2)TS discontinuities are now reported with exact file position * fixed: reading language information from TS files didn't work correctly v2.52 * fixed muxing of MPEG2 broadcasts where "temporal_reference" overruns * MPEG2 bitstream headers are now updated correctly when speedup is performed * MPEG2 bitstream headers are now updated correctly when slowdown is performed * MPEG2 bitstream headers are now updated correctly when pulldown is removed * pulldown removal is now automatically disabled for MPEG2 broadcasts * AC3WAV (SPDIF formatted) support added v2.51 * DTS Express bitstream parser added * DTS Express auto detection added * DTS Express bitstream delay added * DTS Express bitstream gap/overlap correction added * DTS Express decoding (Nero & ArcSoft) added * fixed: 6.1 -> 7.1 channel doubling resulted in wrong channel order * added (undocum.) option "-no7doubling" to disable 6.1 -> 7.1 channel doubling * DTS tracks with funny speaker settings are displayed as "7.1 (strange setup)" * warning is displayed when decoding "7.1 (strange setup)" tracks with ArcSoft v2.50 * ArcSoft DTS Decoder DLL is now directly accessed instead of using DirectShow v2.49 * DTS parser sets correct channel mask now * DTS-HD parser now properly detects format, channels and samplerate * added support for ArcSoft DTS(-HD) Decoder * added several tweaks to make ArcSoft Decoder behave correctly * added ArcSoft test to the "-test" processing * made ArcSoft Decoder default for DTS and DTS-HD decoding v2.48 * 96kHz LPCM tracks in (M2)TS and EVO/VOB containers didn't work correctly * "Applying (E-)AC3 delay" now only shows if the bitstream is actually modified * fixed crash in MP2 reader when checking some PCM tracks * added support for MLP formats 13 - 16 * improved/corrected MLP channel descriptions * MLP parser sets correct channel mask * added proper channel remaps for libav MLP decoding of "funny" channel formats * added proper channel remaps for Nero MLP decoding of "funny" channel formats * added proper channel remaps for Nero AC3 decoding of "funny" channel formats * when doubling 7th channel the channel mask is set correctly now * channel mask is corrected if a decoder doesn't output all channels * channel mask is corrected if channel downmixing is performed v2.47 * improved detection of AC3/DTS tracks in TS/M2TS container * added support for Blu-Ray style LPCM tracks in TS container * fixed 44.1kHz AC3 tracks * fixed crazy audio delay values when no video track was detected * sometimes video/audio tracks were not properly detected in (M2)TS container * MPEG2 demuxing/remuxing incorrectly output the first sequence headers twice * sequence end codes are removed when demuxing video now, too * MPEG2 pulldown removal is automatically activated only for EVO HD sources now * MPEG2 pulldown removal can be manually activated by using "-stripPulldown" * MPEG2 pulldown removal can be disabled by using "-keepPulldown" v2.46 * MPEG2 muxing now fully supports streams with mixed 23.976 and 29.970 content * mixed video/movie MPEG2 streams are now always muxed with 29.970 timestamps * if a movie MPEG2 stream goes video, processing is automatically restarted * MPEG2 pulldown is now automatically removed whenever an MPEG2 stream is read * new option "-keepPulldown" can be used to disable MPEG2 pulldown removal * corrected default WAV channel masks for 4.0, 6.1 and 7.1 * added proper channel remaps for libav AC3 decoding of "funny" channel formats * added general channel mask support * WAV parser reads channel mask from extensible header * (E-)AC3 parser sets correct channel mask v2.45 * Blu-Ray angles are now reported as separate titles * duplicate playlists are not listed in the "folder view", anymore * reduced TrueHD and RAW/PCM gap/overlap threshold to 7ms * reduced (E-)AC3 gap/overlap threshold to 60% of the runtime of one audio frame * reduced MP2 gap/overlap threshold to 60% of the runtime of one MP2 frame * reduced DTS threshold to 60% of the runtime of one DTS frame, but at least 7ms * fixed: Blu-Ray chapter export sometimes wrote incorrect "00:00:00.000" items * improved handling of MPEG2 streams (changes from interlaced to progressive) * video information now shows "with pulldown flags", if applicable * removed "-ignoreDiscon" from help; hint is shown when a discontinuity occurs * added "-ignoreEncrypt" option; hint is shown when a source is encrypted * new option "-extensible" creates WAV files with a slightly different header * fixed some smaller bugs v2.44 * libav is now automatically used when Nero/Sonic decoders are not working * gap/overlap correction of RAW/PCM tracks sometimes aborted * rerunning de/remuxing to correct gaps/overlaps ignored RAW/PCM tracks * "lossless check failed" messages are surpressed on join points now v2.43 * added automatic Blu-Ray playlist parsing * added support for multi part (e.g. seamless branching) Blu-Ray titles * audio gap/overlap detection rewrite completed * added audio gap/overlap correction functionality * added Blu-Ray chapter support * log lines are now prefixed with a track identifier * RAW/PCM delay is used instead of bitstream delay, if possible * fixed: video framecount was missing v2.42 * added support for 16bit DTSWAV files * fixed: Blu-Ray TrueHD support was broken v2.41 * added full MP2 (MPEG2 audio) support including decoding + bitstream delay * added TS/M2TS runtime detection * improved VOB/EVO runtime detection * added TrueHD gap/overlap detection * audio gap/overlap detection logic rewritten (not complete yet) * fixed: log file option didn't work correctly * fixed: some DTS tracks in PAL TS broadcasts weren't detected correctly * fixed: some E-AC3 tracks in PAL TS broadcasts weren't detected correctly v2.40 * video framecount is now also shown for TS/M2TS demuxing/remuxing * "-check" option added to check container for corruption * TS/M2TS: discontinuity check sometimes fired false alarms * HD DVD subtitle language/description was not always correct * title listing is only shown if there are at least 2 titles * if there is only one title, the title is automatically selected * TS/M2TS audio delay detection was broken * improved audio delay detection for broadcasts and badly mastered discs * TS/M2TS video demuxing could eventually add some invalid data * new option "log=c:\whatever\log.txt" specifies the log file path/name v2.39 * simple audio transcoding was broken v2.38 * fixed file path handling bug v2.37 * added HD DVD chapter support * added HD DVD subtitle demuxing support * added pre-freeze detection for Haali Matroska Muxer bug * invalid characters are removed from file names now * log file is copied to destination path (of first destination file) v2.36 * TS/M2TS: discontinuity is only checked for tracks which are de- or remuxed * TS/M2TS: "-demux" creates both a "thd" and an "ac3" file for "thd/ac3" tracks * TS/M2TS: "eac3to source.m2ts movie.mkv" transcodes "thd/ac3" tracks to FLAC * M2TS: track language is displayed (if the file "xxxxx.clpi" is available) * TS: track language is displayed (if the source file contains this info) * video gaps/overlaps in the last 5 seconds of the movie are ignored now v2.35 * fixed broken EVO support v2.34 * TS/M2TS: fixed PAT/PMT reading bug * TS/M2TS: new "-ignoreDiscon" option makes eac3to ignore discontinuity errors v2.33 * added full TS and M2TS support (file joining not supported yet, though) * further improved "-demux" file names * help text and HD DVD track listing is now also written to the log v2.32 * added automatic "VPLST000.XPL" and "HVA00001.VTI" parsing * "eac3to" or "eac3to ." inside of a HD DVD folder lists all title sets * "eac3to someHdDvdMovieFolder" lists all title sets * "eac3to someHdDvdMovieFolder whatever.mkv" converts the longest title set * "eac3to someHdDvdMovieFolder x) whatever.mkv" converts the selected title set * EVO report now contains the EVO display name (if "VPLST000.XPL" is available) * added language to EVO audio track listing (if "VPLST000.XPL" is available) * added EVO audio track display names (if "VPLST000.XPL" is available) * sequence end codes are stripped from VC-1, MPEG2 and h264/AVC * put "-stripPulldown" option back in on request * option "-demux" now writes to "current directory" instead of source directory * option "-demux" now creates files with meaningful names * doing "eac3to src.evo dst.mkv" now creates audio files with meaningful names * doing "eac3to src.evo dst.mkv" writes the audio files to same path as the MKV * after successful (erroneous) processing "success.wav" (error.wav) is played v2.31 * DTSWAV input support added * fixed bitstream delaying of 96khz DTS tracks * improved DTS runtime calculation * fixed DTS audio gap/overlap correction for strange DTS formats * fixed E-AC3 audio gap/overlap correction for strange bitrates * fixed incorrect MKV "default duration" when using "-24p" or "-30p" * fixed incorrect MKV "default duration" when using "-slowdown" or "-speedup" * improved support for "open bitrate" DTS files * slightly improved automatic (E-)AC3 delaying exactness v2.30 * fixed wrong MPEG2 framerate (bug introduced in v2.29) v2.29 * added automatic audio gap/overlap correction for (E-)AC3, DTS(-HD) and LPCM * options "-slowdown" and "-speedup" can now also be used for video muxing * added support for muxing of EVO's secondary video track to MKV * added "-24p", "-30p" and "-60i" options to overwrite detected h264 framerate * fixed some MPEG2 muxing problems * temporarily disabled "-stripPulldown" because vc1conv 0.3 is better v2.28 * new "-seekToIFrames" switch makes Basic Instinct (h264) muxing work v2.27 * fixed h264/AVC muxing crash with some movies (due to too high RAM usage) * fixed missing frames at the end of the movie when doing h264/AVC muxing * fixed non-working "eac3to -test" v2.26 * Haali Splitter replaced with internal splitter for EVO h264/AVC tracks * external raw h264/AVC tracks can now be muxed directly to Matroska * timestamps for h264/AVC MKV videos don't need to be rewritten, anymore * gaps/overlaps in h264/AVC track of EVO files are detected now * h264 aspect ratio is detected and written into MKV now * Haali Media Splitter is not being used at all, anymore * mkvtoolnix is not being used at all, anymore * added detection for MPEG2 interlaced -> progressive mode change * workaround for eacGui bug v2.25 * fixed MPEG2 muxing for interlaced content v2.24 * Haali Splitter replaced with internal splitter for EVO MPEG2 tracks * external raw MPEG2 tracks can now be muxed directly to Matroska * timestamps for MPEG2 MKV videos don't need to be rewritten, anymore * gaps/overlaps in MPEG2 track of EVO files are detected now * VC-1 and MPEG2 aspect ratios are detected and written into MKV now * fixed bug with "-down2" option v2.23 * fixed bug which made some DTS tracks appear dirty although they weren't * fixed extremely big gap detection with Fantastic Four 2 * fixed non cleaned up gaps file bug v2.22 * gap/overlap logic changed completely (optional two pass muxing now) * "-ignoreGaps" parameter is gone v2.21 * latest libav MLP/TrueHD decoder fixes "lossless check failed" bug * latest libav MLP/TrueHD decoder supports & decodes 7.1 TrueHD tracks * Matroska muxing speed dramatically improved * eac3to now detects and handles E-AC3 7.1 tracks correctly * option "-core" extracts 5.1 core from E-AC3 7.1 tracks * added support for small DTS files (< 300kb) v2.20 * changed VC-1 muxing method to fix problems with several movies, e.g. - Unforgiven - Phantom of the Opera - Million Dollar Baby - Fantastic Four 2 * fps value is now also added to MKV header when muxing raw VC-1 stream * added new "-skip" option to skip corruption in the beginning of an EVO file * added extra handling which fixes some EVO authoring bugs v2.19 * fixed h264 bitstream parsing of framerate information format * fixed (again) muxing of some rare VC-1 titles like e.g. POTO USA v2.18 * fixed bug which stopped eac3to v2.15-17 from working on some PCs * fixed h264 bitstream parsing bug (Sum of all Fears) * fps value is added to MKV header now * relaxed VC-1 gap detection once more * TrueHD decoding to stdout fixed (always output as 24 bit now) v2.17 * fixed VC-1 pulldown removal * VC-1 pulldown removal must now be activated by the new option "-stripPulldown" * improved VC-1 gap/overlap detection * new option "-ignoreGaps" disables VC-1 gap/overlap detection * libav E-AC3 decoder background decoding removed again v2.16 * fixed "eac3to -test" crash * fixed "eac3to some.ddp some.wav" crash * made video gap/overlap detection a little more relaxed * WAV header is initialized to 4GB instead of 0GB (for stdout) * fixed incorrect "primary/secondary" text v2.15 * Haali Splitter replaced with internal splitter for EVO VC-1 tracks * external raw VC-1 tracks can now be muxed directly to Matroska * timestamps for VC-1 MKV videos don't need to be rewritten, anymore * some problematic VC-1 movies should mux fine to MKV now (e.g. POTO USA) * gaps/overlaps in VC-1 track of EVO files are detected and displayed now * pulldown can be removed from external raw VC-1 tracks now * pulldown is automatically removed when demuxing EVO VC-1 tracks now * updated to the latest revision of the libav E-AC3 decoder * some minor changes and bugfixes v2.14 * libav TrueHD decoder "end of stream" bug should be fixed now * fixed libav DTS decoder - subwoofer channels is properly decoded now, too * patched libav DTS decoder to output full 24 bit * updated to the latest revision of the libav E-AC3 decoder * when decoding E-AC3 with Nero, libav decoding is also executed at the same time v2.13 * added option to downmix multi channel audio to stereo * added support for VC-1 custom aspect ratios * added stdout output support v2.12 (thanks to Ron/drmpeg for all his help) * video resolution, framerate and mode (progressive/interlaced) are displayed * rewriting timestamps should now always write the correct framerate * after a full EVO/VOB processing the number of video frames is shown * EVO 16 bit and 24 bit LPCM demuxing supported now (need samples for 20 bit) * (E-)AC3 bitstream can be delayed now (similar to delaycut) * DTS bitstream can be delayed now (similar to delaycut) * DTS-HD High-Res and Master Audio bitstream can be delayed now * when demuxing bitstream audio tracks from EVO delay is automatically applied * some little bugs fixed v2.11 * libav E-AC3 decoding is without DRC now * libav AC3 decoding added (without DRC) * libav E-AC3 and AC3 decoding hacked to return full 24 bit * fixed: delay was not applied for lossless audio tracks * fixed crash when parsing PCM files without doing any conversion * TrueHD dialnorm was displayed incorrectly * changed 23.976 to 24/1.001 * fixed some more minor bugs v2.10 * fixed crash which occurred when doing "EVO/VOB -> Surcode DTS encoding" * "eac3to source.evo movie.mkv" syntax replaces "-auto" option * "eac3to 1.evo+2.evo movie.evo" syntax supported now for simple EVO/VOB joining v2.09 * EVO demuxing added with proper delays for all audio tracks * EVO file joining/rebuilding added * automated EVO video remuxing (Matroska) added * automated rewriting of Matroska timestamps to 24p via mkvtoolnix added * multiple operations on the source file can now be run at the same time * switch "-test" tests all external DirectShow filters and tools * latest ffmpeg/libav TrueHD and E-AC3 decoder patches included * latest libAften build included * libav TrueHD decoder is now the default decoder for TrueHD/MLP * support for libav DTS decoding added * fixed a whole lot of bugs (and might have added a few new ones) v2.08 * fixed: bitdepth reducer sometimes crashed when being fed a PCM file * fixed: FLAC encoder sometimes crashed when delay was applied * fixed: some TrueHD files were dithered/processed by Nero when they shouldn't * fixed: Surcode 1.0.29 encoding automation * fixed: source file was deleted when source and dest file names were identical * eac3to output is now always written to "log.txt" * when a crash occurs, "log.txt" is added to the bug report * improved help text + hints slightly * undocumented switch "-check16bit" added * undocumented switch "-mono" added v2.07 * fixed libAV MLP decoding support * added automatic MLP ID20 channel remapping * Surcode 1.0.29 (or newer) home directory detection added v2.06 * doing FLAC -> FLAC now copies metadata from source to destination file * MLP files are correctly decoded now (by both Nero and libav/ffmpeg) * runtime for padded DTS files is shown correctly now v2.05 * added support for libav/ffmpeg decoding of TrueHD/MLP and E-AC3 * added "-libav" switch to force libav decoding v2.04 * don't need dtsac3source.ax, anymore * don't need Nero Splitter, anymore * don't need Sonic HD Demuxer, anymore * replaced hacked DirectShow feeding with a cleaner approach * added support for DTS-HD Master Audio 7.1 tracks (only 5.1 decoding) * little performance boost for PAL speedup/down on DualCore CPUs * fixed some bugs v2.03 * new "-debug" switch added v2.02 * fixed: automatic registering of the dtsac3source filter crashed v2.01 * fixed: AC3 encoding sometimes crashed when being fed 24 bit audio data * fixed: AC3 encoded files were invalid when being fed 24 bit audio data * eac3toGUI didn't work with eac3to v2.0 * "eac3to source.ac3 dest.ac3 -slowdown" didn't do anything useful * when a crash occurs, the bug report is automatically copied to clipboard now * some minor cosmetic improvements v2.00 totally new features * AC3 decoding support (Nero's decoder without DRC/dialnorm) * resampling to 44.1/48/96 kHz (by using "r8brain") * apply/reverse PAL speedup (by using "r8brain") * "eac3to sourceFile" will print out source file details strongly enhanced features * dramatically improved performance (no intermediate files, anymore!) * proper 6.1/7.1 downmixing to 5.1 instead of just dropping the back surround channels * RAW/PCM file detection now auto detects channels, bitdepth and endian * WAV is now fully supported as source file format * destination file extension "PCM" creates Blu-Ray style LPCM tracks * bitdepth can be reduced to anything between 14 bits and 23 bits DTS related improvements/changes * DTS-96/24 support added * "open bitrate" support added * strange channel configuration support added * removal of zero padding from DTS files added * eac3to can fix broken DTS-ES files (they decode to 5.1 instead of 6.1 without the fix) * dialog normalization can be removed without removing the additional DTS-HD data now * core extraction must be specifically asked for now (see "-core" switch) AC3 related improvements * did I mention that eac3to can decode AC3 now? * strange channel configuration support added TrueHD related improvements * delay problem (hopefully) solved * fixed: sometimes some audio data in the middle of a track was lost * TrueHD/AC3 interweaved file can be stripped to TrueHD only now various minor improvements/changes * progress bar added * eac3to detects file format independently of file extension * multiple input files can be treated as one big file * "sox" is not needed, anymore * "dump" filter not needed, anymore * "aften.exe" replaced by "libAften.dll" * "flac.exe" replaced by "libFlac.dll" * DTS/DD+/AC3 source filter ships with eac3to now * 8bit support added * crash analyzer and bug reporting added v1.23 * bugfix: sometimes TrueHD decoding resulted in incorrect sampling rate v1.22 * 6.1 -> 7.1 channel doubling was sometimes incorrectly skipped * OS speaker settings now don't have to be 7.1, anymore * added detection of 5.1 output when 6.1 was expected * DTS and DTS-ES files are now forcefully patched to 24 bit by eac3to (workaround for Sonic decoder) * Sonic Audio Decoder is now always used by default for DTS decoding v1.21 * bugfix: 2 channel DTS files were not accepted * added: DTS-ES 6.1 support * added: DTS-HD High Resolution Matrix 5.1 support * added: DTS-HD Master Audio 6.1 support v1.20 * bugfix: some Blu-Ray TrueHD tracks were not accepted * change: eac3to output text slightly improved v1.19 * bugfix: still some TrueHD files were not accepted ("The source file format is unknown") * added: FLAC supported as source/input file format now * added: full delay functionality v1.18 * bugfix: some TrueHD files were not accepted ("The source file format is unknown") * change: EVO files are not accepted as source files, anymore * added: detection and repacking of 16 bit TrueHD tracks * added: proper detection of "DTS-HD Master Audio" and "DTS-HD High Resolution" tracks * added: runtime information for "DTS-HD High Resolution" tracks * bugfix: bitrate information for "DTS-HD High Resolution" tracks * added: decoding of "DTS-HD Master Audio" tracks (Sonic) * added: decoding of "DTS-HD High Resolution" tracks (Sonic) * added: decoding of conventional DTS tracks (Sonic/Nero) v1.17 * TrueHD dialog normalization removal added v1.16 * added decoding support for Blu-Ray TrueHD files v1.15 * bugfixes v1.14 * DTS dialog normalization can be removed now * DTS core can be extracted from DTS-HD track now v1.13 * "eac3to src.ac3 dst.ac3" removes dialog normalization from AC3 files * "eac3to src.eac3 dst.eac3" removes dialog normalization from E-AC3 files * "eac3to src.thd dst.ac3" extracts the AC3 frames from a Blu-Ray TrueHD track and removes dialog normalization v1.12 * tools "flac.exe", "aften.exe" and "sox.exe" are now distributed in the eac3to zip * correct channel mapping for 7.1 LPCM tracks is default now * new option "-down6" allows downconverting of 7.1 tracks to 5.1 * modded "flac.exe" ships with eac3to now, which has no problems with 2GB file output, anymore v1.11 * bugfix: (L)PCM -> DTS encoding automation failed when source and destination folders differed * added: new "-allowDnr" switch allows Nero's audio decoder to apply DNR * added: new "-keepDialnorm" switch disables removal of E-AC3 dialnorm information v1.10 * E-AC3 dialog normalization detection and removal * DRC turned off for Nero E-AC3 decoder * Surcode automation improved * Nero is now the default E-AC3 and TrueHD decoder * the flag "/nero" is no more * there is a flag "/sonic" now to force the use of the Sonic filters v1.09 * multi channel mono wav output added * automated SurCode DTS encoding added * 24bit PCM handling works now (was buggy before) * "-blu-ray" option removed * with PCM input files "bigendian" is default now * with 5.1 PCM input blu-ray style channel remapping is default now * switches "-16" and "-24" are valid for both TrueHD and PCM input now * eac3to now creates the WAV files on its own instead of using sox * target extension ".wavs" results in one mono wav for each channel being created * SurCode DVD DTS encoding automation added * new options "-768" and "-1536" for DTS encoding * TrueHD output is not downconverted to 16bit by default, anymore * new option "-down16" downconverts the raw data from 24 -> 16 bit (not limited to TrueHD input) v1.08 * added PCM input support * automatic detection of PCM bitdepth added (16bit or 24bit) * "-blu-ray" switch remaps PCM channels correctly v1.07 * added "-8" switch for 8 channel support v1.06 * mono E-AC3 support added v1.05 * support for 5.1 TrueHD audio tracks added v1.04 * E-AC3 files bigger than 4GB are supported now v1.03 * AC3 files bigger than 2GB are supported now v1.02 * FLAC encoding works now without any input/output size limits v1.01 * support for FLAC encoding added * bitrate can be specified via command line parameter * ffdshow removed from the filter chain * "ddp" and "ec3" file extensions are accepted now, too * fix: "dd+" file extension didn't work correctly. v1.00 * initial release * can convert a 2.0 or 5.1 channel E-AC3 file to AC3.
集合了 所有的 Unix命令大全 登陆服务器时输入 公帐号 openlab-open123 telnet 192.168.0.23 自己帐号 sd08077-you0 ftp工具 192.168.0.202 tools-toolss 老师测评网址 http://172.16.0.198:8080/poll/ 各个 shell 可互相切换 ksh:$ sh:$ csh:guangzhou% bash:bash-3.00$ 一、注意事项 命令和参数之间必需用空格隔开,参数和参数之间也必需用空格隔开。 一行不能超过256个字符;大小写有区分。 二、特殊字符含义 文件名以“.”开头的都是隐藏文件/目录,只需在文件/目录名前加“.”就可隐藏它。 ~/ 表示主目录。 ./ 当前目录(一个点)。 ../ 上一级目录(两个点)。 ; 多个命令一起用。 > >> 输出重定向 。将一个命令的输出内容写入到一个文件里面。如果该文件存在, 就将该文件的内容覆盖; 如果不存在就先创建该文件, 然后再写入内容。 输出重定向,意思就是说,将原来屏幕输出变为文件输出,即将内容输到文件中。 < << 输入重定向。 本来命令是通过键盘得到输入的,但是用小于号,就能够使命令从文件中得到输入。 \ 表示未写完,回车换行再继续。 * 匹配零个或者多个字符。 ? 匹配一个字符。 [] 匹配中括号里的内容[a-z][A-Z][0-9]。 ! 事件。 $ 取环境变量的值。 | 管道。把前一命令的输出作为后一命令的输入,把几个命令连接起来。 |经常跟tee连用,tee 把内容保存到文档并显示出来。 三、通用后接命令符 -a 所有(all)。 -e 所有(every),比a更详细。 -f 取消保护。 -i 添加提示。 -p 强制执行。 -r 目录管理。 分屏显示的中途操作 空格<space> 继续打开下一屏; 回车<return> 继续打开下一行; b 另外开上一屏; f 另外开下一屏; h 帮助; q或Ctrl+C 退出; /字符串 从上往下查找匹配的字符串; ?字符串 从下往上查找匹配的字符串; n 继续查找。 四、退出命令 exit 退出; DOS内部命令 用于退出当前的命令处理器(COMMAND.COM) 恢复前一个命令处理器。 Ctrl+d 跟exit一样效果,表中止本次操作。 logout 当csh时可用来退出,其他shell不可用。 clear 清屏,清除(之前的内容并未删除,只是没看到,拉回上面可以看回)。 五、目录管理命令 pwd 显示当前所在目录,打印当前目录的绝对路径。 cd 进入某目录,DOS内部命令 显示或改变当前目录。 cd回车/cd ~ 都是回到自己的主目录。 cd . 当前目录(空格再加一个点)。 cd .. 回到上一级目录(空格再加两个点)。 cd ../.. 向上两级。 cd /user/s0807 从绝对路径去到某目录。 cd ~/s0807 直接进入主目录下的某目录(“cd ~"相当于主目录的路径的简写)。 ls 显示当前目录的所有目录和文件。 用法 ls [-aAbcCdeEfFghHilLmnopqrRstux1@] [file...] ls /etc/ 显示某目录下的所有文件和目录,如etc目录下的。 ls -l (list)列表显示文件(默认按文件名排序), 显示文件的权限、硬链接数(即包含文件数,普通文件是1,目录1+)、用户、组名、大小、修改日期、文件名。 ls -t (time)按修改时间排序,显示目录和文件。 ls -lt 是“-l”和“-t”的组合,按时间顺序显示列表。 ls -F 显示文件类型,目录“/ ”结尾;可执行文件“*”结尾;文本文件(none),没有结尾。 ls -R 递归显示目录结构。即该目录下的文件和各个副目录下的文件都一一显示。 ls -a 显示所有文件,包括隐藏文件。 文件权限 r 读权限。对普通文件来说,是读取该文件的权限;对目录来说,是获得该目录下的文件信息。 w 写权限。对文件,是修改;对目录,是增删文件与子目录。 (注 删除没有写权限的文件可以用 rm -f ,这是为了操作方便,是人性化的设计)。 x 执行权限;对目录,是进入该目录 - 表示没有权限 形式 - rw- r-- r-- 其中 第一个是文件类型(-表普通文件,d表目录,l表软链接文件) 第2~4个是属主,生成文件时登录的人,权限最高,用u表示 第5~7个是属组,系统管理员分配的同组的一个或几个人,用g表示 第8~10个是其他人,除属组外的人,用o表示 所有人,包括属主、属组及其他人,用a表示 chmod 更改权限; 用法 chmod [-fR] <绝对模式> 文件 ... chmod [-fR] <符号模式列表> 文件 ... 其中 <符号模式列表> 是一个用逗号分隔的表 [ugoa]{+|-|=}[rwxXlstugo] chmod u+rw 给用户加权限。同理,u-rw也可以减权限。 chmod u=rw 给用户赋权限。与加权限不一样,赋权限有覆盖的效果。 主要形式有如下几种 chmod u+rw chmod u=rw chmod u+r, u+w chmod u+rw,g+w, o+r chmod 777( 用数字的方式设置权限是最常用的) 数字表示权限时,各数位分别表示属主、属组及其他人; 其中,1是执行权(Execute),2是写权限(Write),4是读权限(Read), 具体权限相当于三种权限的数相加,如7=1+2+4,即拥有读写和执行权。 另外,临时文件/目录的权限为rwt,可写却不可删,关机后自动删除;建临时目录:chmod 777 目录名,再chmod +t 目录名。 id 显示用户有效的uid(用户字)和gid(组名) 用法 id [-ap] [user] id 显示自己的。 id root 显示root的。 id -a root 显示用户所在组的所有组名(如root用户,是所有组的组员) df 查看文件系统,查看数据区 用法 df [-F FSType] [-abeghklntVvZ] [-o FSType 特定选项] [目录 | 块设备 | 资源] df -k 以kbytes显示文件大小的查看文件系统方式 六、显示文件内容 more 分屏显示文件的内容。 用法 more [-cdflrsuw] [-行] [+行号] [+/模式] [文件名 ...]。 显示7个信息:用户名 密码 用户id(uid) 组id(gid) 描述信息(一般为空) 用户主目录 login shell(登录shell) cat 显示文件内容,不分屏(一般用在小文件,大文件显示不下);合并文件,仅在屏幕上合并,并不改变原文件。 用法 cat [ -usvtebn ] [-|文件] ... tail 实时监控文件,一般用在日志文件,可以只看其中的几行。 用法 tail [+/-[n][lbc][f]] [文件] tail [+/-[n][l][r|f]] [文件] 七、文件/目录的增删 echo 显示一行内容。 touch 如果文件/目录不存在,则创建新文件/目录;如果文件存在,那么就是更新该文件的最后访问时间, 用法 touch [-acm] [-r ref_file] 文件... touch [-acm] [MMDDhhmm[yy]] 文件... touch [-acm] [-t [[CC]YY]MMDDhhmm[.SS]] file... mkdir 创建目录(必须有创建目录的权限) 用法 mkdir [-m 模式] [-p] dirname ... mkdir dir1/dir2 在dir1下建dir2 mkdir dir13 dir4 dir5 连建多个 mkdir ~/games 用户主目录下建(默认在当前目录下创建) mkdir -p dir6/dir7/dir8 强制创建dir8;若没有前面的目录,会自动创建dir6和dir7。 不用-p时,若没有dir6/dir7,则创建失败。 cp 复制文件/目录 cp 源文件 目标文件 复制文件;若已有文件则覆盖 cp -r 源目录 目标目录 复制目录;若已有目录则把源目录复制到目标目录下, 没有目标目录时,相当于完全复制源目录,只是文件名不同。 cp beans apple dir2 把beans、apple文件复制到dir2目录下 cp -i beans apple 增加是否覆盖的提示 mv 移动或重命名文件/目录 用法 mv [-f] [-i] f1 f2 mv [-f] [-i] f1 ... fn d1 mv [-f] [-i] d1 d2 mv 源文件名 目标文件名 若目标文件名还没有,则是源文件重命名为目标文件;若目标文件已存在,则源文件覆盖目标文件。 mv 源文件名 目标目录 移动文件 mv 源目录 目标目录 若目标目录不存在,则源目录重命名;若目标目录已存在,则源目录移动到目标目录下。 rm 删除文件/目录 用法 rm [-fiRr] 文件 ... rm 文件名 删除文件。 rm -r 目录名 删除目录。 rm –f 文件 只要是该文件或者目录的拥有者,无论是否有权限删除,都可以用这个命令参数强行删除。 rm -rf * 删除所有文件及目录 rmdir 删除空目录。只可以删除空目录。 ln 创建硬链接或软链接,硬链接=同一文件的多个名字;软链接=快捷方式 用法 ln [-f] [-n] [-s] f1 [f2] ln [-f] [-n] [-s] f1 ... fn d1 ln [-f] [-n] -s d1 d2 ln file1 file1.ln 创建硬链接。感觉是同一文件,删除一个,对另一个没有影响;须两个都删除才算删除。 ln -s file1 file1.sln 创建软链接。可跨系统操作,冲破操作权限;也是快捷方式。 八、时间显示 date 显示时间,精确到秒 用法 date [-u] mmddHHMM[[cc]yy][.SS] date [-u] [+format] date -a [-]sss[.fff] cal 显示日历 cal 9 2008 显示2008年9月的日历; cal 显示当月的 用法 cal [ [月] 年 ] 九、帮助 man 帮助( format and display the on-line manual pages) 用法 man [-] [-adFlrt] [-M 路径] [-T 宏软件包] [-s 段] 名称 ... man [-] [-adFlrt] [-M path] [-T macro-package] [-s section] name... man [-M 路径] -k 关键字 ... man [-M 路径] -f 文件 ... awk 按一定格式输出(pattern scanning and processing language) 用法 awk [-Fc] [-f 源代码 | 'cmds'] [文件] 十、vi 底行模式 /? 命令模式 i a o 输入模式 vi 的使用方法 1、光标 h 左 j 下 k 上 l 右 set nu 显示行号(set nonu) 21 光标停在指定行 21G 第N行 (G到文件尾,1G到文件头) 如果要将光标移动到文件第一行,那么就按 1G H 屏幕头 M 屏幕中间 L 屏幕底 ^ 或 shift+6 行首 $ 或 shift+4 行尾 Ctrl+f 下翻 Ctrl+b 上翻 2、输入 (输入模式) o 光标往下换一行 O (大写字母o)在光标所在行上插入一空行 i 在光标所在位置的前面插入字母 a 在光标所在位置的后面插入一个新字母 <Esc> 退出插入状态。 3、修改替换 r 替换一个字符 dd 删除行,剪切行 (5dd删除5行) 5,10d 删除 5 至 10 行(包括第 5行和第 10 行) x 删除一个字符 dw 删除词,剪切词。 ( 3dw删除 3 单词) cw 替换一个单词。 (cw 和 dw 的区别 cw 删除某一个单词后直接进入编辑模式,而dw删除词后仍处于命令模式) cc 替换一行 C 替换从光标到行尾 yy 复制行 (用法同下的 Y ,见下行) Y 将光标移动到要复制行位置,按yy。当你想粘贴的时候,请将光标移动到你想复制的位置的前一个位置,然后按 p yw 复制词 p 当前行下粘贴 1,2co3 复制行1,2在行3之后 4,5m6 移动行4,5在行6之后 u 当你的前一个命令操作是一个误操作的时候,那么可以按一下 u键,即可复原。只能撤销一次 r file2 在光标所在处插入另一个文件 ~ 将字母变成大写 J 可以将当前行与下一行连接起来 /字符串 从上往下找匹配的字符串 ?字符串 从下往上找匹配的字符串 n 继续查找 1,$s/旧串/新串/g 替换全文(或者 %s/旧串/新串/g) (1表示从第一行开始) 没有g则只替换一次,加g替换所有 3、存盘和退出 w 存盘 w newfile 存成新文件 wq 存盘再退出VI(或者ZZ或 X) q! 强行退出不存盘 查看用户 users 显示在线用户(仅显示用户名)。 who 显示在线用户,但比users更详细,包括用户名、终端号、登录时间、IP地址。 who am i 仅显示自己,(但包括用户名、端口、登录时间、IP地址;信息量=who)。 whoami 也仅显示自己,但只有用户名(仅显示自己的有效的用户名)。 w 显示比who更多内容,还包括闲置时间、占CPU、平均占用CPU、执行命令。 用法 w [ -hlsuw ] [ 用户 ] su 改变用户,需再输入密码。 用法 su [-] [ username [ arg ... ] ] su - 相当于退出再重新登录。 查找 find 查找文件 用法 find [-H | -L] 路径列表 谓词列表 find / -name perl 从根目录开始查找名为perl的文件。 find . -mtime 10 -print 从当前目录查找距离现在10天时修改的文件,显示在屏幕上。 (注 “10”表示第10天的时候;如果是“+10”表示10天以外的范围;“-10”表示10天以内的范围。) grep 文件中查找字符;有过滤功能,只列出想要的内容 用法 grep -hblcnsviw 模式 文件 . . . 如 grep abc /etc/passwd 在passwd文件下找abc字符 wc 统计 -l 统计行数; -w统计单词数; -c 统计字符数 如 grep wang /etc/passwd|wc -l 统计passwd文件含“wang”的行数 du 查看目录情况 如 du -sk * 不加-s会显示子目录,-k按千字节排序 用法 du [-a] [-d] [-h|-k] [-r] [-o|-s] [-H|-L] [文件...] 进程管理 ps 显示进程。 用法 ps [ -aAdeflcjLPyZ ] [ -o 格式 ] [ -t 项列表 ] [ -u 用户列表 ] [ -U 用户列表 ] [ -G 组列表 ] [ -p 进程列表 ] [ -g 程序组列表 ] [ -s 标识符列表 ] [ -z 区域列表 ] ps 显示自己的进程。 ps -e 显示每个进程,包括空闲进程。 ps -f 显示详情。 ps -ef 组合-e和-f,所有进程的详情。 ps -U uidlist(用户列表) 具体查看某人的进程。 kill pkill sleep jobs 用法 jobs [-l ] fg %n bg %n stop %n 挂起(仅csh能用) Ctrl+C Ctrl+Z 网络链接 ping usage ping host [timeout] usage ping -s [-l | U] [adLnRrv] [-A addr_family] [-c traffic_class] [-g gateway [-g gateway ...]] [-F flow_label] [-I interval] [-i interface] [-P tos] [-p port] [-t ttl] host [data_size] [npackets] ifconfig -a /sbin/ifconfig 查看本机的IP地址 netstat -rn rlogin ftp 帮助文件 [sd0807@localhost ~]$ help GNU bash, version 3.1.17(1)-release (i686-redhat-linux-gnu) These shell commands are defined internally. Type `help' to see this list. Type `help name' to find out more about the function `name'. Use `info bash' to find out more about the shell in general. Use `man -k' or `info' to find out more about commands not in this list. A star (*) next to a name means that the command is disabled. JOB_SPEC [&] (( expression )) . filename [arguments] [ arg... ] [[ expression ]] alias [-p] [name[=value] ... ] bg [job_spec ...] bind [-lpvsPVS] [-m keymap] [-f fi break [n] builtin [shell-builtin [arg ...]] caller [EXPR] case WORD in [PATTERN [| PATTERN]. cd [-L|-P] [dir] command [-pVv] command [arg ...] compgen [-abcdefgjksuv] [-o option complete [-abcdefgjksuv] [-pr] [-o continue [n] declare [-afFirtx] [-p] [name[=val dirs [-clpv] [+N] [-N] disown [-h] [-ar] [jobspec ...] echo [-neE] [arg ...] enable [-pnds] [-a] [-f filename] eval [arg ...] exec [-cl] [-a name] file [redirec exit [n] export [-nf] [name[=value] ...] or false fc [-e ename] [-nlr] [first] [last fg [job_spec] for NAME [in WORDS ... ;] do COMMA for (( exp1; exp2; exp3 )); do COM function NAME { COMMANDS ; } or NA getopts optstring name [arg] hash [-lr] [-p pathname] [-dt] [na help [-s] [pattern ...] history [-c] [-d offset] [n] or hi if COMMANDS; then COMMANDS; [ elif jobs [-lnprs] [jobspec ...] or job kill [-s sigspec | -n signum | -si let arg [arg ...] local name[=value] ... logout popd [+N | -N] [-n] printf [-v var] format [arguments] pushd [dir | +N | -N] [-n] pwd [-LP] read [-ers] [-u fd] [-t timeout] [ readonly [-af] [name[=value] ...] return [n] select NAME [in WORDS ... ;] do CO set [--abefhkmnptuvxBCHP] [-o option] [arg ...] shift [n] shopt [-pqsu] [-o long-option] opt source filename [arguments] suspend [-f] test [expr] time [-p] PIPELINE times trap [-lp] [arg signal_spec ...] true type [-afptP] name [name ...] typeset [-afFirtx] [-p] name[=valu ulimit [-SHacdfilmnpqstuvx] [limit umask [-p] [-S] [mode] unalias [-a] name [name ...] unset [-f] [-v] [name ...] until COMMANDS; do COMMANDS; done variables - Some variable names an wait [n] while COMMANDS; do COMMANDS; done { COMMANDS ; } 输入 man help BASH_BUILTINS(1) BASH_BUILTINS(1) NAME bash, :, ., [, alias, bg, bind, break, builtin, cd, command, compgen, complete, continue, declare, dirs, disown, echo, enable, eval, exec, exit, export, fc, fg, getopts, hash, help, history, jobs, kill, let, local, logout, popd, printf, pushd, pwd, read, readonly, return, set, shift, shopt, source, suspend, test, times, trap, type, typeset, ulimit, umask, una- lias, unset, wait - bash built-in commands, see bash(1) BASH BUILTIN COMMANDS Unless otherwise noted, each builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options. For example, the :, true, false, and test builtins do not accept options. : [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned. . filename [arguments] source filename [arguments] Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing file- name. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read. alias [-p] [name[=value] ...] Alias with no arguments or with the -p option prints the list of aliases in the form alias name=value on standard output. When arguments are supplied, an alias is defined for each name whose value is given. A trailing space in value causes the next word to be checked for alias substitution when the alias is expanded. For each name in the argument list for which no value is supplied, the name and value of the alias is printed. Alias returns true unless a name is given for which no alias has been defined. bg [jobspec ...] Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell’s notion of the current job is used. bg jobspec returns 0 unless run when job control is disabled or, when run with job con- trol enabled, any specified jobspec was not found or was started without job control. bind [-m keymap] [-lpsvPSV] bind [-m keymap] [-q function] [-u function] [-r keyseq] bind [-m keymap] -f filename bind [-m keymap] -x keyseq:shell-command bind [-m keymap] keyseq:function-name bind readline-command Display current readline key and function bindings, bind a key sequence to a readline function or macro, or set a readline variable. Each non-option argument is a command as it would appear in .inputrc, but each binding or command must be passed as a sepa- rate argument; e.g., ’"\C-x\C-r": re-read-init-file’. Options, if supplied, have the following meanings: -m keymap Use keymap as the keymap to be affected by the subsequent bindings. Accept- able keymap names are emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard. -l List the names of all readline functions. -p Display readline function names and bindings in such a way that they can be re-read. -P List current readline function names and bindings. -v Display readline variable names and values in such a way that they can be re- read. -V List current readline variable names and values. -s Display readline key sequences bound to macros and the strings they output in such a way that they can be re-read. -S Display readline key sequences bound to macros and the strings they output. -f filename Read key bindings from filename. -q function Query about which keys invoke the named function. -u function Unbind all keys bound to the named function. -r keyseq Remove any current binding for keyseq. -x keyseq:shell-command Cause shell-command to be executed whenever keyseq is entered. The return value is 0 unless an unrecognized option is given or an error occurred. break [n] Exit from within a for, while, until, or select loop. If n is specified, break n levels. n must be ≥ 1. If n is greater than the number of enclosing loops, all enclosing loops are exited. The return value is 0 unless the shell is not executing a loop when break is executed. builtin shell-builtin [arguments] Execute the specified shell builtin, passing it arguments, and return its exit sta- tus. This is useful when defining a function whose name is the same as a shell builtin, retaining the functionality of the builtin within the function. The cd builtin is commonly redefined this way. The return status is false if shell-builtin is not a shell builtin command. cd [-L|-P] [dir] Change the current directory to dir. The variable HOME is the default dir. The variable CDPATH defines the search path for the directory containing dir. Alterna- tive directory names in CDPATH are separated by a colon (:). A null directory name in CDPATH is the same as the current directory, i.e., ‘‘.’’. If dir begins with a slash (/), then CDPATH is not used. The -P option says to use the physical directory structure instead of following symbolic links (see also the -P option to the set builtin command); the -L option forces symbolic links to be followed. An argument of - is equivalent to $OLDPWD. If a non-empty directory name from CDPATH is used, or if - is the first argument, and the directory change is successful, the absolute path- name of the new working directory is written to the standard output. The return value is true if the directory was successfully changed; false otherwise. caller [expr] Returns the context of any active subroutine call (a shell function or a script exe- cuted with the . or source builtins. Without expr, caller displays the line number and source filename of the current subroutine call. If a non-negative integer is supplied as expr, caller displays the line number, subroutine name, and source file corresponding to that position in the current execution call stack. This extra information may be used, for example, to print a stack trace. The current frame is frame 0. The return value is 0 unless the shell is not executing a subroutine call or expr does not correspond to a valid position in the call stack. command [-pVv] command [arg ...] Run command with args suppressing the normal shell function lookup. Only builtin com- mands or commands found in the PATH are executed. If the -p option is given, the search for command is performed using a default value for PATH that is guaranteed to find all of the standard utilities. If either the -V or -v option is supplied, a description of command is printed. The -v option causes a single word indicating the command or file name used to invoke command to be displayed; the -V option produces a more verbose description. If the -V or -v option is supplied, the exit status is 0 if command was found, and 1 if not. If neither option is supplied and an error occurred or command cannot be found, the exit status is 127. Otherwise, the exit status of the command builtin is the exit status of command. compgen [option] [word] Generate possible completion matches for word according to the options, which may be any option accepted by the complete builtin with the exception of -p and -r, and write the matches to the standard output. When using the -F or -C options, the vari- ous shell variables set by the programmable completion facilities, while available, will not have useful values. The matches will be generated in the same way as if the programmable completion code had generated them directly from a completion specification with the same flags. If word is specified, only those completions matching word will be displayed. The return value is true unless an invalid option is supplied, or no matches were generated. complete [-abcdefgjksuv] [-o comp-option] [-A action] [-G globpat] [-W wordlist] [-P prefix] [-S suffix] [-X filterpat] [-F function] [-C command] name [name ...] complete -pr [name ...] Specify how arguments to each name should be completed. If the -p option is sup- plied, or if no options are supplied, existing completion specifications are printed in a way that allows them to be reused as input. The -r option removes a completion specification for each name, or, if no names are supplied, all completion specifica- tions. The process of applying these completion specifications when word completion is attempted is described above under Programmable Completion. Other options, if specified, have the following meanings. The arguments to the -G, -W, and -X options (and, if necessary, the -P and -S options) should be quoted to protect them from expansion before the complete builtin is invoked. -o comp-option The comp-option controls several aspects of the compspec’s behavior beyond the simple generation of completions. comp-option may be one of: bashdefault Perform the rest of the default bash completions if the compspec gen- erates no matches. default Use readline’s default filename completion if the compspec generates no matches. dirnames Perform directory name completion if the compspec generates no matches. filenames Tell readline that the compspec generates filenames, so it can per- form any filename-specific processing (like adding a slash to direc- tory names or suppressing trailing spaces). Intended to be used with shell functions. nospace Tell readline not to append a space (the default) to words completed at the end of the line. plusdirs After any matches defined by the compspec are generated, directory name completion is attempted and any matches are added to the results of the other actions. -A action The action may be one of the following to generate a list of possible comple- tions: alias Alias names. May also be specified as -a. arrayvar Array variable names. binding Readline key binding names. builtin Names of shell builtin commands. May also be specified as -b. command Command names. May also be specified as -c. directory Directory names. May also be specified as -d. disabled Names of disabled shell builtins. enabled Names of enabled shell builtins. export Names of exported shell variables. May also be specified as -e. file File names. May also be specified as -f. function Names of shell functions. group Group names. May also be specified as -g. helptopic Help topics as accepted by the help builtin. hostname Hostnames, as taken from the file specified by the HOSTFILE shell variable. job Job names, if job control is active. May also be specified as -j. keyword Shell reserved words. May also be specified as -k. running Names of running jobs, if job control is active. service Service names. May also be specified as -s. setopt Valid arguments for the -o option to the set builtin. shopt Shell option names as accepted by the shopt builtin. signal Signal names. stopped Names of stopped jobs, if job control is active. user User names. May also be specified as -u. variable Names of all shell variables. May also be specified as -v. -G globpat The filename expansion pattern globpat is expanded to generate the possible completions. -W wordlist The wordlist is split using the characters in the IFS special variable as delimiters, and each resultant word is expanded. The possible completions are the members of the resultant list which match the word being completed. -C command command is executed in a subshell environment, and its output is used as the possible completions. -F function The shell function function is executed in the current shell environment. When it finishes, the possible completions are retrieved from the value of the COMPREPLY array variable. -X filterpat filterpat is a pattern as used for filename expansion. It is applied to the list of possible completions generated by the preceding options and argu- ments, and each completion matching filterpat is removed from the list. A leading ! in filterpat negates the pattern; in this case, any completion not matching filterpat is removed. -P prefix prefix is added at the beginning of each possible completion after all other options have been applied. -S suffix suffix is appended to each possible completion after all other options have been applied. The return value is true unless an invalid option is supplied, an option other than -p or -r is supplied without a name argument, an attempt is made to remove a comple- tion specification for a name for which no specification exists, or an error occurs adding a completion specification. continue [n] Resume the next iteration of the enclosing for, while, until, or select loop. If n is specified, resume at the nth enclosing loop. n must be ≥ 1. If n is greater than the number of enclosing loops, the last enclosing loop (the ‘‘top-level’’ loop) is resumed. The return value is 0 unless the shell is not executing a loop when con- tinue is executed. declare [-afFirtx] [-p] [name[=value] ...] typeset [-afFirtx] [-p] [name[=value] ...] Declare variables and/or give them attributes. If no names are given then display the values of variables. The -p option will display the attributes and values of each name. When -p is used, additional options are ignored. The -F option inhibits the display of function definitions; only the function name and attributes are printed. If the extdebug shell option is enabled using shopt, the source file name and line number where the function is defined are displayed as well. The -F option implies -f. The following options can be used to restrict output to variables with the specified attribute or to give variables attributes: -a Each name is an array variable (see Arrays above). -f Use function names only. -i The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION ) is performed when the variable is assigned a value. -r Make names readonly. These names cannot then be assigned values by subsequent assignment statements or unset. -t Give each name the trace attribute. Traced functions inherit the DEBUG and RETURN traps from the calling shell. The trace attribute has no special mean- ing for variables. -x Mark names for export to subsequent commands via the environment. Using ‘+’ instead of ‘-’ turns off the attribute instead, with the exception that +a may not be used to destroy an array variable. When used in a function, makes each name local, as with the local command. If a variable name is followed by =value, the value of the variable is set to value. The return value is 0 unless an invalid option is encountered, an attempt is made to define a function using ‘‘-f foo=bar’’, an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax (see Arrays above), one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-exis- tent function with -f. dirs [-clpv] [+n] [-n] Without options, displays the list of currently remembered directories. The default display is on a single line with directory names separated by spaces. Directories are added to the list with the pushd command; the popd command removes entries from the list. +n Displays the nth entry counting from the left of the list shown by dirs when invoked without options, starting with zero. -n Displays the nth entry counting from the right of the list shown by dirs when invoked without options, starting with zero. -c Clears the directory stack by deleting all of the entries. -l Produces a longer listing; the default listing format uses a tilde to denote the home directory. -p Print the directory stack with one entry per line. -v Print the directory stack with one entry per line, prefixing each entry with its index in the stack. The return value is 0 unless an invalid option is supplied or n indexes beyond the end of the directory stack. disown [-ar] [-h] [jobspec ...] Without options, each jobspec is removed from the table of active jobs. If the -h option is given, each jobspec is not removed from the table, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If no jobspec is present, and neither the -a nor the -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. The return value is 0 unless a jobspec does not specify a valid job. echo [-neE] [arg ...] Output the args, separated by spaces, followed by a newline. The return status is always 0. If -n is specified, the trailing newline is suppressed. If the -e option is given, interpretation of the following backslash-escaped characters is enabled. The -E option disables the interpretation of these escape characters, even on systems where they are interpreted by default. The xpg_echo shell option may be used to dynamically determine whether or not echo expands these escape characters by default. echo does not interpret -- to mean the end of options. echo interprets the following escape sequences: \a alert (bell) \b backspace \c suppress trailing newline \e an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \0nnn the eight-bit character whose value is the octal value nnn (zero to three octal digits) \nnn the eight-bit character whose value is the octal value nnn (one to three octal digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) enable [-adnps] [-f filename] [name ...] Enable and disable builtin shell commands. Disabling a builtin allows a disk command which has the same name as a shell builtin to be executed without specifying a full pathname, even though the shell normally searches for builtins before disk commands. If -n is used, each name is disabled; otherwise, names are enabled. For example, to use the test binary found via the PATH instead of the shell builtin version, run ‘‘enable -n test’’. The -f option means to load the new builtin command name from shared object filename, on systems that support dynamic loading. The -d option will delete a builtin previously loaded with -f. If no name arguments are given, or if the -p option is supplied, a list of shell builtins is printed. With no other option arguments, the list consists of all enabled shell builtins. If -n is supplied, only disabled builtins are printed. If -a is supplied, the list printed includes all builtins, with an indication of whether or not each is enabled. If -s is supplied, the output is restricted to the POSIX special builtins. The return value is 0 unless a name is not a shell builtin or there is an error loading a new builtin from a shared object. eval [arg ...] The args are read and concatenated together into a single command. This command is then read and executed by the shell, and its exit status is returned as the value of eval. If there are no args, or only null arguments, eval returns 0. exec [-cl] [-a name] [command [arguments]] If command is specified, it replaces the shell. No new process is created. The arguments become the arguments to command. If the -l option is supplied, the shell places a dash at the beginning of the zeroth arg passed to command. This is what login(1) does. The -c option causes command to be executed with an empty environ- ment. If -a is supplied, the shell passes name as the zeroth argument to the exe- cuted command. If command cannot be executed for some reason, a non-interactive shell exits, unless the shell option execfail is enabled, in which case it returns failure. An interactive shell returns failure if the file cannot be executed. If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1. exit [n] Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell termi- nates. export [-fn] [name[=word]] ... export -p The supplied names are marked for automatic export to the environment of subsequently executed commands. If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed. The -n option causes the export property to be removed from each name. If a variable name is followed by =word, the value of the variable is set to word. export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is sup- plied with a name that is not a function. fc [-e ename] [-nlr] [first] [last] fc -s [pat=rep] [cmd] Fix Command. In the first form, a range of commands from first to last is selected from the history list. First and last may be specified as a string (to locate the last command beginning with that string) or as a number (an index into the history list, where a negative number is used as an offset from the current command number). If last is not specified it is set to the current command for listing (so that ‘‘fc -l -10’’ prints the last 10 commands) and to first otherwise. If first is not speci- fied it is set to the previous command for editing and -16 for listing. The -n option suppresses the command numbers when listing. The -r option reverses the order of the commands. If the -l option is given, the commands are listed on standard output. Otherwise, the editor given by ename is invoked on a file contain- ing those commands. If ename is not given, the value of the FCEDIT variable is used, and the value of EDITOR if FCEDIT is not set. If neither variable is set, is used. When editing is complete, the edited commands are echoed and executed. In the second form, command is re-executed after each instance of pat is replaced by rep. A useful alias to use with this is ‘‘r="fc -s"’’, so that typing ‘‘r cc’’ runs the last command beginning with ‘‘cc’’ and typing ‘‘r’’ re-executes the last command. If the first form is used, the return value is 0 unless an invalid option is encoun- tered or first or last specify history lines out of range. If the -e option is sup- plied, the return value is the value of the last command executed or failure if an error occurs with the temporary file of commands. If the second form is used, the return status is that of the command re-executed, unless cmd does not specify a valid history line, in which case fc returns failure. fg [jobspec] Resume jobspec in the foreground, and make it the current job. If jobspec is not present, the shell’s notion of the current job is used. The return value is that of the command placed into the foreground, or failure if run when job control is dis- abled or, when run with job control enabled, if jobspec does not specify a valid job or jobspec specifies a job that was started without job control. getopts optstring name [args] getopts is used by shell procedures to parse positional parameters. optstring con- tains the option characters to be recognized; if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. The colon and question mark characters may not be used as option char- acters. Each time it is invoked, getopts places the next option in the shell vari- able name, initializing name if it does not exist, and the index of the next argument to be processed into the variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the variable OPTARG. The shell does not reset OPTIND auto- matically; it must be manually reset between multiple calls to getopts within the same shell invocation if a new set of parameters is to be used. When the end of options is encountered, getopts exits with a return value greater than zero. OPTIND is set to the index of the first non-option argument, and name is set to ?. getopts normally parses the positional parameters, but if more arguments are given in args, getopts parses those instead. getopts can report errors in two ways. If the first character of optstring is a colon, silent error reporting is used. In normal operation diagnostic messages are printed when invalid options or missing option arguments are encountered. If the variable OPTERR is set to 0, no error messages will be displayed, even if the first character of optstring is not a colon. If an invalid option is seen, getopts places ? into name and, if not silent, prints an error message and unsets OPTARG. If getopts is silent, the option character found is placed in OPTARG and no diagnostic message is printed. If a required argument is not found, and getopts is not silent, a question mark (?) is placed in name, OPTARG is unset, and a diagnostic message is printed. If getopts is silent, then a colon (:) is placed in name and OPTARG is set to the option charac- ter found. getopts returns true if an option, specified or unspecified, is found. It returns false if the end of options is encountered or an error occurs. hash [-lr] [-p filename] [-dt] [name] For each name, the full file name of the command is determined by searching the directories in $PATH and remembered. If the -p option is supplied, no path search is performed, and filename is used as the full file name of the command. The -r option causes the shell to forget all remembered locations. The -d option causes the shell to forget the remembered location of each name. If the -t option is supplied, the full pathname to which each name corresponds is printed. If multiple name arguments are supplied with -t, the name is printed before the hashed full pathname. The -l option causes output to be displayed in a format that may be reused as input. If no arguments are given, or if only -l is supplied, information about remembered commands is printed. The return status is true unless a name is not found or an invalid option is supplied. help [-s] [pattern] Display helpful information about builtin commands. If pattern is specified, help gives detailed help on all commands matching pattern; otherwise help for all the builtins and shell control structures is printed. The -s option restricts the infor- mation displayed to a short usage synopsis. The return status is 0 unless no command matches pattern. history [n] history -c history -d offset history -anrw [filename] history -p arg [arg ...] history -s arg [arg ...] With no options, display the command history list with line numbers. Lines listed with a * have been modified. An argument of n lists only the last n lines. If the shell variable HISTTIMEFORMAT is set and not null, it is used as a format string for strftime(3) to display the time stamp associated with each displayed history entry. No intervening blank is printed between the formatted time stamp and the history line. If filename is supplied, it is used as the name of the history file; if not, the value of HISTFILE is used. Options, if supplied, have the following meanings: -c Clear the history list by deleting all the entries. -d offset Delete the history entry at position offset. -a Append the ‘‘new’’ history lines (history lines entered since the beginning of the current bash session) to the history file. -n Read the history lines not already read from the history file into the current history list. These are lines appended to the history file since the begin- ning of the current bash session. -r Read the contents of the history file and use them as the current history. -w Write the current history to the history file, overwriting the history file’s contents. -p Perform history substitution on the following args and display the result on the standard output. Does not store the results in the history list. Each arg must be quoted to disable normal history expansion. -s Store the args in the history list as a single entry. The last command in the history list is removed before the args are added. If the HISTTIMEFORMAT is set, the time stamp information associated with each history entry is written to the history file. The return value is 0 unless an invalid option is encountered, an error occurs while reading or writing the history file, an invalid offset is supplied as an argument to -d, or the history expansion supplied as an argument to -p fails. jobs [-lnprs] [ jobspec ... ] jobs -x command [ args ... ] The first form lists the active jobs. The options have the following meanings: -l List process IDs in addition to the normal information. -p List only the process ID of the job’s process group leader. -n Display information only about jobs that have changed status since the user was last notified of their status. -r Restrict output to running jobs. -s Restrict output to stopped jobs. If jobspec is given, output is restricted to information about that job. The return status is 0 unless an invalid option is encountered or an invalid jobspec is sup- plied. If the -x option is supplied, jobs replaces any jobspec found in command or args with the corresponding process group ID, and executes command passing it args, returning its exit status. kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ... kill -l [sigspec | exit_status] Send the signal named by sigspec or signum to the processes named by pid or jobspec. sigspec is either a case-insensitive signal name such as SIGKILL (with or without the SIG prefix) or a signal number; signum is a signal number. If sigspec is not present, then SIGTERM is assumed. An argument of -l lists the signal names. If any arguments are supplied when -l is given, the names of the signals corresponding to the arguments are listed, and the return status is 0. The exit_status argument to -l is a number specifying either a signal number or the exit status of a process termi- nated by a signal. kill returns true if at least one signal was successfully sent, or false if an error occurs or an invalid option is encountered. let arg [arg ...] Each arg is an arithmetic expression to be evaluated (see ARITHMETIC EVALUATION). If the last arg evaluates to 0, let returns 1; 0 is returned otherwise. local [option] [name[=value] ...] For each argument, a local variable named name is created, and assigned value. The option can be any of the options accepted by declare. When local is used within a function, it causes the variable name to have a visible scope restricted to that function and its children. With no operands, local writes a list of local variables to the standard output. It is an error to use local when not within a function. The return status is 0 unless local is used outside a function, an invalid name is sup- plied, or name is a readonly variable. logout Exit a login shell. popd [-n] [+n] [-n] Removes entries from the directory stack. With no arguments, removes the top direc- tory from the stack, and performs a cd to the new top directory. Arguments, if sup- plied, have the following meanings: +n Removes the nth entry counting from the left of the list shown by dirs, start- ing with zero. For example: ‘‘popd +0’’ removes the first directory, ‘‘popd +1’’ the second. -n Removes the nth entry counting from the right of the list shown by dirs, starting with zero. For example: ‘‘popd -0’’ removes the last directory, ‘‘popd -1’’ the next to last. -n Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated. If the popd command is successful, a dirs is performed as well, and the return status is 0. popd returns false if an invalid option is encountered, the directory stack is empty, a non-existent directory stack entry is specified, or the directory change fails. printf [-v var] format [arguments] Write the formatted arguments to the standard output under the control of the format. The format is a character string which contains three types of objects: plain charac- ters, which are simply copied to standard output, character escape sequences, which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. In addition to the standard printf(1) formats, %b causes printf to expand backslash escape sequences in the cor- responding argument (except that \c terminates output, backslashes in \', \", and \? are not removed, and octal escapes beginning with \0 may contain up to four digits), and %q causes printf to output the corresponding argument in a format that can be reused as shell input. The -v option causes the output to be assigned to the variable var rather than being printed to the standard output. The format is reused as necessary to consume all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied. The return value is zero on success, non-zero on failure. pushd [-n] [dir] pushd [-n] [+n] [-n] Adds a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the current working directory. With no arguments, exchanges the top two directories and returns 0, unless the directory stack is empty. Arguments, if supplied, have the following meanings: +n Rotates the stack so that the nth directory (counting from the left of the list shown by dirs, starting with zero) is at the top. -n Rotates the stack so that the nth directory (counting from the right of the list shown by dirs, starting with zero) is at the top. -n Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. dir Adds dir to the directory stack at the top, making it the new current working directory. If the pushd command is successful, a dirs is performed as well. If the first form is used, pushd returns 0 unless the cd to dir fails. With the second form, pushd returns 0 unless the directory stack is empty, a non-existent directory stack element is specified, or the directory change to the specified new current directory fails. pwd [-LP] Print the absolute pathname of the current working directory. The pathname printed contains no symbolic links if the -P option is supplied or the -o physical option to the set builtin command is enabled. If the -L option is used, the pathname printed may contain symbolic links. The return status is 0 unless an error occurs while reading the name of the current directory or an invalid option is supplied. read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt] [-n nchars] [-d delim] [name ...] One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, and the first word is assigned to the first name, the second word to the second name, and so on, with leftover words and their intervening separators assigned to the last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values. The characters in IFS are used to split the line into words. The backslash character (\) may be used to remove any special meaning for the next character read and for line continuation. Options, if supplied, have the following meanings: -a aname The words are assigned to sequential indices of the array variable aname, starting at 0. aname is unset before any new values are assigned. Other name arguments are ignored. -d delim The first character of delim is used to terminate the input line, rather than newline. -e If the standard input is coming from a terminal, readline (see READLINE above) is used to obtain the line. -n nchars read returns after reading nchars characters rather than waiting for a com- plete line of input. -p prompt Display prompt on standard error, without a trailing newline, before attempt- ing to read any input. The prompt is displayed only if input is coming from a terminal. -r Backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation. -s Silent mode. If input is coming from a terminal, characters are not echoed. -t timeout Cause read to time out and return failure if a complete line of input is not read within timeout seconds. This option has no effect if read is not reading input from the terminal or a pipe. -u fd Read input from file descriptor fd. If no names are supplied, the line read is assigned to the variable REPLY. The return code is zero, unless end-of-file is encountered, read times out, or an invalid file descriptor is supplied as the argument to -u. readonly [-apf] [name[=word] ...] The given names are marked readonly; the values of these names may not be changed by subsequent assignment. If the -f option is supplied, the functions corresponding to the names are so marked. The -a option restricts the variables to arrays. If no name arguments are given, or if the -p option is supplied, a list of all readonly names is printed. The -p option causes output to be displayed in a format that may be reused as input. If a variable name is followed by =word, the value of the vari- able is set to word. The return status is 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function. return [n] Causes a function to exit with the return value specified by n. If n is omitted, the return status is that of the last command executed in the function body. If used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. If used outside a function and not during execution of a script by ., the return status is false. Any command associated with the RETURN trap is executed before execution resumes after the function or script. set [--abefhkmnptuvxBCHP] [-o option] [arg ...] Without options, the name and value of each shell variable are displayed in a format that can be reused as input for setting or resetting the currently-set variables. Read-only variables cannot be reset. In posix mode, only shell variables are listed. The output is sorted according to the current locale. When options are specified, they set or unset shell attributes. Any arguments remaining after the options are processed are treated as values for the positional parameters and are assigned, in order, to $1, $2, ... $n. Options, if specified, have the following meanings: -a Automatically mark variables and functions which are modified or created for export to the environment of subsequent commands. -b Report the status of terminated background jobs immediately, rather than before the next primary prompt. This is effective only when job control is enabled. -e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or ││ list, or if the command’s return value is being inverted via !. A trap on ERR, if set, is executed before the shell exits. -f Disable pathname expansion. -h Remember the location of commands as they are looked up for execution. This is enabled by default. -k All arguments in the form of assignment statements are placed in the environ- ment for a command, not just those that precede the command name. -m Monitor mode. Job control is enabled. This option is on by default for interactive shells on systems that support it (see JOB CONTROL above). Back- ground processes run in a separate process group and a line containing their exit status is printed upon their completion. -n Read commands but do not execute them. This may be used to check a shell script for syntax errors. This is ignored by interactive shells. -o option-name The option-name can be one of the following: allexport Same as -a. braceexpand Same as -B. emacs Use an emacs-style command line editing interface. This is enabled by default when the shell is interactive, unless the shell is started with the --noediting option. errtrace Same as -E. functrace Same as -T. errexit Same as -e. hashall Same as -h. histexpand Same as -H. history Enable command history, as described above under HISTORY. This option is on by default in interactive shells. ignoreeof The effect is as if the shell command ‘‘IGNOREEOF=10’’ had been exe- cuted (see Shell Variables above). keyword Same as -k. monitor Same as -m. noclobber Same as -C. noexec Same as -n. noglob Same as -f. nolog Currently ignored. notify Same as -b. nounset Same as -u. onecmd Same as -t. physical Same as -P. pipefail If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all command
Contents Overview 1 Lesson 1: Concepts – Locks and Lock Manager 3 Lesson 2: Concepts – Batch and Transaction 31 Lesson 3: Concepts – Locks and Applications 51 Lesson 4: Information Collection and Analysis 63 Lesson 5: Concepts – Formulating and Implementing Resolution 81 Module 4: Troubleshooting Locking and Blocking Overview At the end of this module, you will be able to:  Discuss how lock manager uses lock mode, lock resources, and lock compatibility to achieve transaction isolation.  Describe the various transaction types and how transactions differ from batches.  Describe how to troubleshoot blocking and locking issues.  Analyze the output of blocking scripts and Microsoft® SQL Server™ Profiler to troubleshoot locking and blocking issues.  Formulate hypothesis to resolve locking and blocking issues. Lesson 1: Concepts – Locks and Lock Manager This lesson outlines some of the common causes that contribute to the perception of a slow server. What You Will Learn After completing this lesson, you will be able to:  Describe locking architecture used by SQL Server.  Identify the various lock modes used by SQL Server.  Discuss lock compatibility and concurrent access.  Identify different types of lock resources.  Discuss dynamic locking and lock escalation.  Differentiate locks, latches, and other SQL Server internal “locking” mechanism such as spinlocks and other synchronization objects. Recommended Reading  Chapter 14 “Locking”, Inside SQL Server 2000 by Kalen Delaney  SOX000821700049 – SQL 7.0 How to interpret lock resource Ids  SOX000925700237 – TITLE: Lock escalation in SQL 7.0  SOX001109700040 – INF: Queries with PREFETCH in the plan hold lock until the end of transaction Locking Concepts Delivery Tip Prior to delivering this material, test the class to see if they fully understand the different isolation levels. If the class is not confident in their understanding, review appendix A04_Locking and its accompanying PowerPoint® file. Transactions in SQL Server provide the ACID properties: Atomicity A transaction either commits or aborts. If a transaction commits, all of its effects remain. If it aborts, all of its effects are undone. It is an “all or nothing” operation. Consistency An application should maintain the consistency of a database. For example, if you defer constraint checking, it is your responsibility to ensure that the database is consistent. Isolation Concurrent transactions are isolated from the updates of other incomplete transactions. These updates do not constitute a consistent state. This property is often called serializability. For example, a second transaction traversing the doubly linked list mentioned above would see the list before or after the insert, but it will see only complete changes. Durability After a transaction commits, its effects will persist even if there are system failures. Consistency and isolation are the most important in describing SQL Server’s locking model. It is up to the application to define what consistency means, and isolation in some form is needed to achieve consistent results. SQL Server uses locking to achieve isolation. Definition of Dependency: A set of transactions can run concurrently if their outputs are disjoint from the union of one another’s input and output sets. For example, if T1 writes some object that is in T2’s input or output set, there is a dependency between T1 and T2. Bad Dependencies These include lost updates, dirty reads, non-repeatable reads, and phantoms. ANSI SQL Isolation Levels An isolation level determines the degree to which data is isolated for use by one process and guarded against interference from other processes. Prior to SQL Server 7.0, REPEATABLE READ and SERIALIZABLE isolation levels were synonymous. There was no way to prevent non-repeatable reads while not preventing phantoms. By default, SQL Server 2000 operates at an isolation level of READ COMMITTED. To make use of either more or less strict isolation levels in applications, locking can be customized for an entire session by setting the isolation level of the session with the SET TRANSACTION ISOLATION LEVEL statement. To determine the transaction isolation level currently set, use the DBCC USEROPTIONS statement, for example: USE pubs GO SET TRANSACTION ISOLATION LEVEL REPEATABLE READ GO DBCC USEROPTIONS GO Multigranular Locking Multigranular Locking In our example, if one transaction (T1) holds an exclusive lock at the table level, and another transaction (T2) holds an exclusive lock at the row level, each of the transactions believe they have exclusive access to the resource. In this scenario, since T1 believes it locks the entire table, it might inadvertently make changes to the same row that T2 thought it has locked exclusively. In a multigranular locking environment, there must be a way to effectively overcome this scenario. Intent lock is the answer to this problem. Intent Lock Intent Lock is the term used to mean placing a marker in a higher-level lock queue. The type of intent lock can also be called the multigranular lock mode. An intent lock indicates that SQL Server wants to acquire a shared (S) lock or exclusive (X) lock on some of the resources lower down in the hierarchy. For example, a shared intent lock placed at the table level means that a transaction intends on placing shared (S) locks on pages or rows within that table. Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. Intent locks improve performance because SQL Server examines intent locks only at the table level to determine whether a transaction can safely acquire a lock on that table. This removes the requirement to examine every row or page lock on the table to determine whether a transaction can lock the entire table. Lock Mode The code shown in the slide represents how the lock mode is stored internally. You can see these codes by querying the master.dbo.spt_values table: SELECT * FROM master.dbo.spt_values WHERE type = N'L' However, the req_mode column of master.dbo.syslockinfo has lock mode code that is one less than the code values shown here. For example, value of req_mode = 3 represents the Shared lock mode rather than the Schema Modification lock mode. Lock Compatibility These locks can apply at any coarser level of granularity. If a row is locked, SQL Server will apply intent locks at both the page and the table level. If a page is locked, SQL Server will apply an intent lock at the table level. SIX locks imply that we have shared access to a resource and we have also placed X locks at a lower level in the hierarchy. SQL Server never asks for SIX locks directly, they are always the result of a conversion. For example, suppose a transaction scanned a page using an S lock and then subsequently decided to perform a row level update. The row would obtain an X lock, but now the page would require an IX lock. The resultant mode on the page would be SIX. Another type of table lock is a schema stability lock (Sch-S) and is compatible with all table locks except the schema modification lock (Sch-M). The schema modification lock (Sch-M) is incompatible with all table locks. Locking Resources Delivery Tip Note the differences between Key and Key Range locks. Key Range locks will be covered in a couple of slides. SQL Server can lock these resources: Item Description DB A database. File A database file Index An entire index of a table. Table An entire table, including all data and indexes. Extent A contiguous group of data pages or index pages. Page An 8-KB data page or index page. Key Row lock within an index. Key-range A key-range. Used to lock ranges between records in a table to prevent phantom insertions or deletions into a set of records. Ensures serializable transactions. RID A Row Identifier. Used to individually lock a single row within a table. Application A lock resource defined by an application. The lock manager knows nothing about the resource format. It simply compares the 'strings' representing the lock resources to determine whether it has found a match. If a match is found, it knows that resource is already locked. Some of the resources have “sub-resources.” The followings are sub-resources displayed by the sp_lock output: Database Lock Sub-Resources: Full Database Lock (default) [BULK-OP-DB] – Bulk Operation Lock for Database [BULK-OP-LOG] – Bulk Operation Lock for Log Table Lock Sub-Resources: Full Table Lock (default) [UPD-STATS] – Update statistics Lock [COMPILE] – Compile Lock Index Lock sub-Resources: Full Index Lock (default) [INDEX_ID] – Index ID Lock [INDEX_NAME] – Index Name Lock [BULK_ALLOC] – Bulk Allocation Lock [DEFRAG] – Defragmentation Lock For more information, see also… SOX000821700049 SQL 7.0 How to interpret lock resource Ids Lock Resource Block The resource type has the following resource block format: Resource Type (Code) Content DB (2) Data 1: sub-resource; Data 2: 0; Data 3: 0 File (3) Data 1: File ID; Data 2: 0; Data 3: 0 Index (4) Data 1: Object ID; Data 2: sub-resource; Data 3: Index ID Table (5) Data 1: Object ID; Data 2: sub-resource; Data 3: 0. Page (6) Data 1: Page Number; Data 3: 0. Key (7) Data 1: Object ID; Data 2: Index ID; Data 3: Hashed Key Extent (8) Data 1: Extent ID; Data 3: 0. RID (9) Data 1: RID; Data 3: 0. Application (10) Data 1: Application resource name The rsc_bin column of master..syslockinfo contains the resource block in hexadecimal format. For an example of how to decode value from this column using the information above, let us assume we have the following value: 0x000705001F83D775010002014F0BEC4E With byte swapping within each field, this can be decoded as: Byte 0: Flag – 0x00 Byte 1: Resource Type – 0x07 (Key) Byte 2-3: DBID – 0x0005 Byte 4-7: ObjectID – 0x 75D7831F (1977058079) Byte 8-9: IndexID – 0x0001 Byte 10-16: Hash Key value – 0x 02014F0BEC4E For more information about how to decode this value, see also… Inside SQL Server 2000, pages 803 and 806. Key Range Locking Key Range Locking To support SERIALIZABLE transaction semantics, SQL Server needs to lock sets of rows specified by a predicate, such as WHERE salary BETWEEN 30000 AND 50000 SQL Server needs to lock data that does not exist! If no rows satisfy the WHERE condition the first time the range is scanned, no rows should be returned on any subsequent scans. Key range locks are similar to row locks on index keys (whether clustered or not). The locks are placed on individual keys rather than at the node level. The hash value consists of all the key components and the locator. So, for a nonclustered index over a heap, where columns c1 and c2 where indexed, the hash would contain contributions from c1, c2 and the RID. A key range lock applied to a particular key means that all keys between the value locked and the next value would be locked for all data modification. Key range locks can lock a slightly larger range than that implied by the WHERE clause. Suppose the following select was executed in a transaction with isolation level SERIALIZABLE: SELECT * FROM members WHERE first_name between ‘Al’ and ‘Carl’ If 'Al', 'Bob', and 'Dave' are index keys in the table, the first two of these would acquire key range locks. Although this would prevent anyone from inserting either 'Alex' or 'Ben', it would also prevent someone from inserting 'Dan', which is not within the range of the WHERE clause. Prior to SQL Server 7.0, page locking was used to prevent phantoms by locking the entire set of pages on which the phantom would exist. This can be too conservative. Key Range locking lets SQL Server lock only a much more restrictive area of the table. Impact Key-range locking ensures that these scenarios are SERIALIZABLE:  Range scan query  Singleton fetch of nonexistent row  Delete operation  Insert operation However, the following conditions must be satisfied before key-range locking can occur:  The transaction-isolation level must be set to SERIALIZABLE.  The operation performed on the data must use an index range access. Range locking is activated only when query processing (such as the optimizer) chooses an index path to access the data. Key Range Lock Mode Again, the req_mode column of master.dbo.syslockinfo has lock mode code that is one less than the code values shown here. Dynamic Locking When modifying individual rows, SQL Server typically would take row locks to maximize concurrency (for example, OLTP, order-entry application). When scanning larger volumes of data, it would be more appropriate to take page or table locks to minimize the cost of acquiring locks (for example, DSS, data warehouse, reporting). Locking Decision The decision about which unit to lock is made dynamically, taking many factors into account, including other activity on the system. For example, if there are multiple transactions currently accessing a table, SQL Server will tend to favor row locking more so than it otherwise would. It may mean the difference between scanning the table now and paying a bit more in locking cost, or having to wait to acquire a more coarse lock. A preliminary locking decision is made during query optimization, but that decision can be adjusted when the query is actually executed. Lock Escalation When the lock count for the transaction exceeds and is a multiple of ESCALATION_THRESHOLD (1250), the Lock Manager attempts to escalate. For example, when a transaction acquired 1250 locks, lock manager will try to escalate. The number of locks held may continue to increase after the escalation attempt (for example, because new tables are accessed, or the previous lock escalation attempts failed due to incompatible locks held by another spid). If the lock count for this transaction reaches 2500 (1250 * 2), Lock Manager will attempt escalation again. The Lock Manager looks at the lock memory it is using and if it is more than 40 percent of SQL Server’s allocated buffer pool memory, it tries to find a scan (SDES) where no escalation has already been performed. It then repeats the search operation until all scans have been escalated or until the memory used drops under the MEMORY_LOAD_ESCALATION_THRESHOLD (40%) value. If lock escalation is not possible or fails to significantly reduce lock memory footprint, SQL Server can continue to acquire locks until the total lock memory reaches 60 percent of the buffer pool (MAX_LOCK_RESOURCE_MEMORY_PERCENTAGE=60). Lock escalation may be also done when a single scan (SDES) holds more than LOCK_ESCALATION_THRESHOLD (765) locks. There is no lock escalation on temporary tables or system tables. Trace Flag 1211 disables lock escalation. Important Do not relay this to the customer without careful consideration. Lock escalation is a necessary feature, not something to be avoided completely. Trace flags are global and disabling lock escalation could lead to out of memory situations, extremely poor performing queries, or other problems. Lock escalation tracing can be seen using the Profiler or with the general locking trace flag, -T1200. However, Trace Flag 1200 shows all lock activity so it should not be usable on a production system. For more information, see also… SOX000925700237 “TITLE: SQL 7.0 Lock escalation in SQL 7.0” Lock Timeout Application Lock Timeout An application can set lock timeout for a session with the SET option: SET LOCK_TIMEOUT N where N is a number of milliseconds. A value of -1 means that there will be no timeout, which is equivalent to the version 6.5 behavior. A value of 0 means that there will be no waiting; if a process finds a resource locked, it will generate error message 1222 and continue with the next statement. The current value of LOCK_TIMEOUT is stored in the global variable @@lock_timeout. Note After a lock timeout any transaction containing the statement, is rolled back or canceled by SQL Server 2000 (bug#352640 was filed). This behavior is different from that of SQL Server 7.0. With SQL Server 7.0, the application must have an error handler that can trap error 1222 and if an application does not trap the error, it can proceed unaware that an individual statement within a transaction has been canceled, and errors can occur because statements later in the transaction may depend on the statement that was never executed. Bug#352640 is fixed in hotfix build 8.00.266 whereby a lock timeout will only Internal Lock Timeout At time, internal operations within SQL Server will attempt to acquire locks via lock manager. Typically, these lock requests are issued with “no waiting.” For example, the ghost record processing might try to clean up rows on a particular page, and before it can do that, it needs to lock the page. Thus, the ghost record manager will request a page lock with no wait so that if it cannot lock the page, it will just move on to other pages; it can always come back to this page later. If you look at SQL Profiler Lock: Timeout events, internal lock timeout typically have a duration value of zero. Lock Duration Lock Mode and Transaction Isolation Level For REPEATABLE READ transaction isolation level, update locks are held until data is read and processed, unless promoted to exclusive locks. "Data is processed" means that we have decided whether the row in question matched the search criteria; if not then the update lock is released, otherwise, we get an exclusive lock and make the modification. Consider the following query: use northwind go dbcc traceon(3604, 1200, 1211) -- turn on lock tracing -- and disable escalation go set transaction isolation level repeatable read begin tran update dbo.[order details] set discount = convert (real, discount) where discount = 0.0 exec sp_lock Update locks are promoted to exclusive locks when there is a match; otherwise, the update lock is released. The sp_lock output verifies that the SPID does not hold any update locks or shared locks at the end of the query. Lock escalation is turned off so that exclusive table lock is not held at the end. Warning Do not use trace flag 1200 in a production environment because it produces a lot of output and slows down the server. Trace flag 1211 should not be used unless you have done extensive study to make sure it helps with performance. These trace flags are used here for illustration and learning purposes only. Lock Ownership Most of the locking discussion in this lesson relates to locks owned by “transactions.” In addition to transaction, cursor and session can be owners of locks and they both affect how long locks are held. For every row that is fetched, when SCROLL_LOCKS option is used, regardless of the state of a transaction, a cursor lock is held until the next row is fetched or when the cursor is closed. Locks owned by session are outside the scope of a transaction. The duration of these locks are bounded by the connection and the process will continue to hold these locks until the process disconnects. A typical lock owned by session is the database (DB) lock. Locking – Read Committed Scan Under read committed isolation level, when database pages are scanned, shared locks are held when the page is read and processed. The shared locks are released “behind” the scan and allow other transactions to update rows. It is important to note that the shared lock currently acquired will not be released until shared lock for the next page is successfully acquired (this is commonly know as “crabbing”). If the same pages are scanned again, rows may be modified or deleted by other transactions. Locking – Repeatable Read Scan Under repeatable read isolation level, when database pages are scanned, shared locks are held when the page is read and processed. SQL Server continues to hold these shared locks, thus preventing other transactions to update rows. If the same pages are scanned again, previously scanned rows will not change but new rows may be added by other transactions. Locking – Serializable Read Scan Under serializable read isolation level, when database pages are scanned, shared locks are held not only on rows but also on scanned key range. SQL Server continues to hold these shared locks until the end of transaction. Because key range locks are held, not only will this prevent other transactions from modifying the rows, no new rows can be inserted. Prefetch and Isolation Level Prefetch and Locking Behavior The prefetch feature is available for use with SQL Server 7.0 and SQL Server 2000. When searching for data using a nonclustered index, the index is searched for a particular value. When that value is found, the index points to the disk address. The traditional approach would be to immediately issue an I/O for that row, given the disk address. The result is one synchronous I/O per row and, at most, one disk at a time working to evaluate the query. This does not take advantage of striped disk sets. The prefetch feature takes a different approach. It continues looking for more record pointers in the nonclustered index. When it has collected a number of them, it provides the storage engine with prefetch hints. These hints tell the storage engine that the query processor will need these particular records soon. The storage engine can now issue several I/Os simultaneously, taking advantage of striped disk sets to execute multiple operations simultaneously. For example, if the engine is scanning a nonclustered index to determine which rows qualify but will eventually need to visit the data page as well to access columns that are not in the index, it may decide to submit asynchronous page read requests for a group of qualifying rows. The prefetch data pages are then revisited later to avoid waiting for each individual page read to complete in a serial fashion. This data access path requires that a lock be held between the prefetch request and the row lookup to stabilize the row on the page so it is not to be moved by a page split or clustered key update. For our example, the isolation level of the query is escalated to REPEATABLE READ, overriding the transaction isolation level. With SQL Server 7.0 and SQL Server 2000, portions of a transaction can execute at a different transaction isolation level than the entire transaction itself. This is implemented as lock classes. Lock classes are used to control lock lifetime when portions of a transaction need to execute at a stricter isolation level than the underlying transaction. Unfortunately, in SQL Server 7.0 and SQL Server 2000, the lock class is created at the topmost operator of the query and hence released only at the end of the query. Currently there is no support to release the lock (lock class) after the row has been discarded or fetched by the filter or join operator. This is because isolation level can be set at the query level via a lock class, but no lower. Because of this, locks acquired during the query will not be released until the query completes. If prefetch is occurring you may see a single SPID that holds hundreds of Shared KEY or PAG locks even though the connection’s isolation level is READ COMMITTED. Isolation level can be determined from DBCC PSS output. For details about this behavior see “SOX001109700040 INF: Queries with PREFETCH in the plan hold lock until the end of transaction”. Other Locking Mechanism Lock manager does not manage latches and spinlocks. Latches Latches are internal mechanisms used to protect pages while doing operations such as placing a row physically on a page, compressing space on a page, or retrieving rows from a page. Latches can roughly be divided into I/O latches and non-I/O latches. If you see a high number of non-I/O related latches, SQL Server is usually doing a large number of hash or sort operations in tempdb. You can monitor latch activities via DBCC SQLPERF(‘WAITSTATS’) command. Spinlock A spinlock is an internal data structure that is used to protect vital information that is shared within SQL Server. On a multi-processor machine, when SQL Server tries to access a particular resource protected by a spinlock, it must first acquire the spinlock. If it fails, it executes a loop that will check to see if the lock is available and if not, decrements a counter. If the counter reaches zero, it yields the processor to another thread and goes into a “sleep” (wait) state for a pre-determined amount of time. When it wakes, hopefully, the lock is free and available. If not, the loop starts again and it is terminated only when the lock is acquired. The reason for implementing a spinlock is that it is probably less costly to “spin” for a short time rather than yielding the processor. Yielding the processor will force an expensive context switch where:  The old thread’s state must be saved  The new thread’s state must be reloaded  The data stored in the L1 and L2 cache are useless to the processor On a single-processor computer, the loop is not useful because no other thread can be running and thus, no one can release the spinlock for the currently executing thread to acquire. In this situation, the thread yields the processor immediately. Lesson 2: Concepts – Batch and Transaction This lesson outlines some of the common causes that contribute to the perception of a slow server. What You Will Learn After completing this lesson, you will be able to:  Review batch processing and error checking.  Review explicit, implicit and autocommit transactions and transaction nesting level.  Discuss how commit and rollback transaction done in stored procedure and trigger affects transaction nesting level.  Discuss various transaction isolation level and their impact on locking.  Discuss the difference between aborting a statement, a transaction, and a batch.  Describe how @@error, @@transcount, and @@rowcount can be used for error checking and handling. Recommended Reading  Charter 12 “Transactions and Triggers”, Inside SQL Server 2000 by Kalen Delaney Batch Definition SQL Profiler Statements and Batches To help further your understanding of what is a batch and what is a statement, you can use SQL Profiler to study the definition of batch and statement.  Try This: Using SQL Profiler to Analyze Batch 1. Log on to a server with Query Analyzer 2. Startup the SQL Profiler against the same server 3. Start a trace using the “StandardSQLProfiler” template 4. Execute the following using Query Analyzer: SELECT @@VERSION SELECT @@SPID The ‘SQL:BatchCompleted’ event is captured by the trace. It shows both the statements as a single batch. 5. Now execute the following using Query Analyzer {call sp_who()} What shows up? The ‘RPC:Completed’ with the sp_who information. RPC is simply another entry point to the SQL Server to call stored procedures with native data types. This allows one to avoid parsing. The ‘RPC:Completed’ event should be considered the same as a batch for the purposes of this discussion. Stop the current trace and start a new trace using the “SQLProfilerTSQL_SPs” template. Issue the same command as outlines in step 5 above. Looking at the output, not only can you see the batch markers but each statement as executed within the batch. Autocommit, Explicit, and Implicit Transaction Autocommit Transaction Mode (Default) Autocommit mode is the default transaction management mode of SQL Server. Every Transact-SQL statement, whether it is a standalone statement or part of a batch, is committed or rolled back when it completes. If a statement completes successfully, it is committed; if it encounters any error, it is rolled back. A SQL Server connection operates in autocommit mode whenever this default mode has not been overridden by either explicit or implicit transactions. Autocommit mode is also the default mode for ADO, OLE DB, ODBC, and DB-Library. A SQL Server connection operates in autocommit mode until a BEGIN TRANSACTION statement starts an explicit transaction, or implicit transaction mode is set on. When the explicit transaction is committed or rolled back, or when implicit transaction mode is turned off, SQL Server returns to autocommit mode. Explicit Transaction Mode An explicit transaction is a transaction that starts with a BEGIN TRANSACTION statement. An explicit transaction can contain one or more statements and must be terminated by either a COMMIT TRANSACTION or a ROLLBACK TRANSACTION statement. Implicit Transaction Mode SQL Server can automatically or, more precisely, implicitly start a transaction for you if a SET IMPLICIT_TRANSACTIONS ON statement is run or if the implicit transaction option is turned on globally by running sp_configure ‘user options’ 2. (Actually, the bit mask 0x2 must be turned on for the user option so you might have to perform an ‘OR’ operation with the existing user option value.) See SQL Server 2000 Books Online on how to turn on implicit transaction under ODBC and OLE DB (acdata.chm::/ac_8_md_06_2g6r.htm). Transaction Nesting Explicit transactions can be nested. Committing inner transactions is ignored by SQL Server other than to decrements @@TRANCOUNT. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. If the outer transaction is committed, the inner nested transactions are also committed. If the outer transaction is rolled back, then all inner transactions are also rolled back, regardless of whether the inner transactions were individually committed. Each call to COMMIT TRANSACTION applies to the last executed BEGIN TRANSACTION. If the BEGIN TRANSACTION statements are nested, then a COMMIT statement applies only to the last nested transaction, which is the innermost transaction. Even if a COMMIT TRANSACTION transaction_name statement within a nested transaction refers to the transaction name of the outer transaction, the commit applies only to the innermost transaction. If a ROLLBACK TRANSACTION statement without a transaction_name parameter is executed at any level of a set of nested transaction, it rolls back all the nested transactions, including the outermost transaction. The @@TRANCOUNT function records the current transaction nesting level. Each BEGIN TRANSACTION statement increments @@TRANCOUNT by one. Each COMMIT TRANSACTION statement decrements @@TRANCOUNT by one. A ROLLBACK TRANSACTION statement that does not have a transaction name rolls back all nested transactions and decrements @@TRANCOUNT to 0. A ROLLBACK TRANSACTION that uses the transaction name of the outermost transaction in a set of nested transactions rolls back all the nested transactions and decrements @@TRANCOUNT to 0. When you are unsure if you are already in a transaction, SELECT @@TRANCOUNT to determine whether it is 1 or more. If @@TRANCOUNT is 0 you are not in a transaction. You can also find the transaction nesting level by checking the sysprocess.open_tran column. See SQL Server 2000 Books Online topic “Nesting Transactions” (acdata.chm::/ac_8_md_06_66nq.htm) for more information. Statement, Transaction, and Batch Abort One batch can have many statements and one transaction can have multiple statements, also. One transaction can span multiple batches and one batch can have multiple transactions. Statement Abort Currently executing statement is aborted. This can be a bit confusing when you start talking about statements in a trigger or stored procedure. Let us look closely at the following trigger: CREATE TRIGGER TRG8134 ON TBL8134 AFTER INSERT AS BEGIN SELECT 1/0 SELECT 'Next command in trigger' END To fire the INSERT trigger, the batch could be as simple as ‘INSERT INTO TBL8134 VALUES(1)’. However, the trigger contains two statements that must be executed as part of the batch to satisfy the clients insert request. When the ‘SELECT 1/0’ causes the divide by zero error, a statement abort is issued for the ‘SELECT 1/0’ statement. Batch and Transaction Abort On SQL Server 2000 (and SQL Server 7.0) whenever a non-informational error is encountered in a trigger, the statement abort is promoted to a batch and transactional abort. Thus, in the example the statement abort for ‘select 1/0’ promotion results in an entire batch abort. No further statements in the trigger or batch will be executed and a rollback is issued. On SQL Server 6.5, the statement aborts immediately and results in a transaction abort. However, the rest of the statements within the trigger are executed. This trigger could return ‘Next command in trigger’ as a result set. Once the trigger completes the batch abort promotion takes effect. Conversely, submitting a similar set of statements in a standalone batch can result in different behavior. SELECT 1/0 SELECT 'Next command in batch' Not considering the set option possibilities, a divide by zero error generally results in a statement abort. Since it is not in a trigger, the promotion to a batch abort is avoided and subsequent SELECT statement can execute. The programmer should add an “if @@ERROR” check immediately after the ‘select 1/0’ to T-SQL execution to control the flow correctly. Aborting and Set Options ARITHABORT If SET ARITHABORT is ON, these error conditions cause the query or batch to terminate. If the errors occur in a transaction, the transaction is rolled back. If SET ARITHABORT is OFF and one of these errors occurs, a warning message is displayed, and NULL is assigned to the result of the arithmetic operation. When an INSERT, DELETE, or UPDATE statement encounters an arithmetic error (overflow, divide-by-zero, or a domain error) during expression evaluation when SET ARITHABORT is OFF, SQL Server inserts or updates a NULL value. If the target column is not nullable, the insert or update action fails and the user receives an error. XACT_ABORT When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back. When OFF, only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. For example: CREATE TABLE t1 (a int PRIMARY KEY) CREATE TABLE t2 (a int REFERENCES t1(a)) GO INSERT INTO t1 VALUES (1) INSERT INTO t1 VALUES (3) INSERT INTO t1 VALUES (4) INSERT INTO t1 VALUES (6) GO SET XACT_ABORT OFF GO BEGIN TRAN INSERT INTO t2 VALUES (1) INSERT INTO t2 VALUES (2) /* Foreign key error */ INSERT INTO t2 VALUES (3) COMMIT TRAN SELECT 'Continue running batch 1...' GO SET XACT_ABORT ON GO BEGIN TRAN INSERT INTO t2 VALUES (4) INSERT INTO t2 VALUES (5) /* Foreign key error */ INSERT INTO t2 VALUES (6) COMMIT TRAN SELECT 'Continue running batch 2...' GO /* Select shows only keys 1 and 3 added. Key 2 insert failed and was rolled back, but XACT_ABORT was OFF and rest of transaction succeeded. Key 5 insert error with XACT_ABORT ON caused all of the second transaction to roll back. Also note that 'Continue running batch 2...' is not Returned to indicate that the batch is aborted. */ SELECT * FROM t2 GO DROP TABLE t2 DROP TABLE t1 GO Compile and Run-time Errors Compile Errors Compile errors are encountered during syntax checks, security checks, and other general operations to prepare the batch for execution. These errors can prevent the optimization of the query and thus lead to immediate abort. The statement is not run and the batch is aborted. The transaction state is generally left untouched. For example, assume there are four statements in a particular batch. If the third statement has a syntax error, none of the statements in the batch is executed. Optimization Errors Optimization errors would include rare situations where the statement encounters a problem when attempting to build an optimal execution plan. Example: “too many tables referenced in the query” error is reported because a “work table” was added to the plan. Runtime Errors Runtime errors are those that are encountered during the execution of the query. Consider the following batch: SELECT * FROM pubs.dbo.titles UPDATE pubs.dbo.authors SET au_lname = au_lname SELECT * FROM foo UPDATE pubs.dbo.authors SET au_lname = au_lname If you run the above statements in a batch, the first two statements will be executed, the third statement will fail because table foo does not exist, and the batch will terminate. Deferred Name Resolution is the feature that allows this batch to start executing before resolving the object foo. This feature allows SQL Server to delay object resolution and place a “placeholder” in the query’s execution. The object referenced by the placeholder is resolved until the query is executed. In our example, the execution of the statement “SELECT * FROM foo” will trigger another compile process to resolve the name again. This time, error message 208 is returned. Error: 208, Level 16, State 1, Line 1 Invalid object name 'foo'. Message 208 can be encountered as a runtime or compile error depending on whether the Deferred Name Resolution feature is available. In SQL Server 6.5 this would be considered a compile error and on SQL Server 2000 (and SQL Server7.0) as a runtime error due to Deferred Name Resolution. In the following example, if a trigger referenced authors2, the error is detected as SQL Server attempts to execute the trigger. However, under SQL Server 6.5 the create trigger statement fails because authors2 does not exist at compile time. When errors are encountered in a trigger, generally, the statement, batch, and transaction are aborted. You should be able to observe this by running the following script in pubs database: Create table tblTest(iID int) go create trigger trgInsert on tblTest for INSERT as begin select * from authors select * from authors2 select * from titles end go begin tran select 'Before' insert into tblTest values(1) select 'After' go select @@TRANCOUNT go When run in a batch, the statement and the batch are aborted but the transaction remains active. The follow script illustrates this: begin tran select 'Before' select * from authors2 select 'After' go select @@TRANCOUNT go One other factor in a compile versus runtime error is implicit data type conversions. If you were to run the following statements on SQL Server 6.5 and SQL Server 2000 (and SQL Server 7.0): create table tblData(dtData datetime) go select 1 insert into tblData values(12/13/99) go On SQL Server 6.5, you get an error before execution of the batch begins so no statements are executed and the batch is aborted. Error: 206, Level 16, State 2, Line 2 Operand type clash: int is incompatible with datetime On SQL Server 2000, you get the default value (1900-01-01 00:00:00.000) inserted into the table. SQL Server 2000 implicit data type conversion treats this as integer division. The integer division of 12/13/99 is 0, so the default date and time value is inserted, no error returned. To correct the problem on either version is to wrap the date string with quotes. See Bug #56118 (sqlbug_70) for more details about this situation. Another example of a runtime error is a 605 message. Error: 605 Attempt to fetch logical page %S_PGID in database '%.*ls' belongs to object '%.*ls', not to object '%.*ls'. A 605 error is always a runtime error. However, depending on the transaction isolation level, (e.g. using the NOLOCK lock hint), established by the SPID the handling of the error can vary. Specifically, a 605 error is considered an ACCESS error. Errors associated with buffer and page access are found in the 600 series of errors. When the error is encountered, the isolation level of the SPID is examined to determine proper handling based on information or fatal error level. Transaction Error Checking Not all errors cause transactions to automatically rollback. Although it is difficult to determine exactly which errors will rollback transactions and which errors will not, the main idea here is that programmers must perform error checking and handle errors appropriately. Error Handling Raiserror Details Raiserror seems to be a source of confusion but is really rather simple. Raiserror with severity levels of 20 or higher will terminate the connection. Of course, when the connection is terminated a full rollback of any open transaction will immediately be instantiated by the SQL Server (except distributed transaction with DTC involved). Severity levels lower than 20 will simply result in the error message being returned to the client. They do not affect the transaction scope of the connection. Consider the following batch: use pubs begin tran update authors set au_lname = 'smith' raiserror ('This is bad', 19, 1) with log select @@trancount With severity set at 19, the 'select @@trancount' will be executed after the raiserror statement and will return a value of 1. If severity is changed to 20, then the select statement will not run and the connection is broken. Important Error handling must occur not only in T-SQL batches and stored procedures, but also in application program code. Transactions and Triggers (1 of 2) Basic behavior assumes the implicit transactions setting is set to OFF. This behavior makes it possible to identify business logic errors in a trigger, raise an error, rollback the action, and add an audit table entry. Logically, the insert to the audit table cannot take place before the ROLLBACK action and you would not want to build in the audit table insert into every applications error handler that violated the business rule of the trigger. For more information, see also… SQL Server 2000 Books Online topic “Rollbacks in stored procedure and triggers“ (acdata.chm::/ac_8_md_06_4qcz.htm) IMPLICIT_TRANSACTIONS ON Behavior The behavior of firing other triggers on the same table can be tricky. Say you added a trigger that checks the CODE field. Read only versions of the rows contain the code ‘RO’ and read/write versions use ‘RW.’ Whenever someone tries to delete a row with a code ‘RO’ the trigger issues the rollback and logs an audit table entry. However, you also have a second trigger that is responsible for cascading delete operations. One client could issue the delete without implicit transactions on and only the current trigger would execute and then terminate the batch. However, a second client with implicit transactions on could issue the same delete and the secondary trigger would fire. You end up with a situation in which the cascading delete operations can take place (are committed) but the initial row remains in the table because of the rollback operation. None of the delete operations should be allowed but because the transaction scope was restarted because of the implicit transactions setting, they did. Transactions and Triggers (2 of 2) It is extremely difficult to determine the execution state of a trigger when using explicit rollback statements in combination with implicit transactions. The RETURN statement is not allowed to return a value. The only way I have found to set the @@ERROR is using a ‘raiserror’ as the last execution statement in the last trigger to execute. If you modify the example, this following RAISERROR statement will set @@ERROR to 50000: CREATE TRIGGER trgTest on tblTest for INSERT AS BEGIN ROLLBACK INSERT INTO tblAudit VALUES (1) RAISERROR('This is bad', 14,1) END However, this value does not carry over to a secondary trigger for the same table. If you raise an error at the end of the first trigger and then look at @@ERROR in the secondary trigger the @@ERROR remains 0. Carrying Forward an Active/Open Transaction It is possible to exit from a trigger and carry forward an open transaction by issuing a BEGIN TRAN or by setting implicit transaction on and doing INSERT, UPDATE, or DELETE. Warning It is never recommended that a trigger call BEGIN TRANSACTION. By doing this you increment the transaction count. Invalid code logic, not calling commit transaction, can lead to a situation where the transaction count remains elevated upon exit of the trigger. Transaction Count The behavior is better explained by understanding how the server works. It does not matter whether you are in a transaction, when a modification takes place the transaction count is incremented. So, in the simplest form, during the processing of an insert the transaction count is 1. On completion of the insert, the server will commit (and thus decrement the transaction count). If the commit identifies the transaction count has returned to 0, the actual commit processing is completed. Issuing a commit when the transaction count is greater than 1 simply decrements the nested transaction counter. Thus, when we enter a trigger, the transaction count is 1. At the completion of the trigger, the transaction count will be 0 due to the commit issued at the end of the modification statement (insert). In our example, if the connection was already in a transaction and called the second INSERT, since implicit transaction is ON, the transaction count in the trigger will be 2 as long as the ROLLBACK is not executed. At the end of the insert, the commit is again issued to decrement the transaction reference count to 1. However, the value does not return to 0 so the transaction remains open/active. Subsequent triggers are only fired if the transaction count at the end of the trigger remains greater than or equal to 1. The key to continuation of secondary triggers and the batch is the transaction count at the end of a trigger execution. If the trigger that performs a rollback has done an explicit begin transaction or uses implicit transactions, subsequent triggers and the batch will continue. If the transaction count is not 1 or greater, subsequent triggers and the batch will not execute. Warning Forcing the transaction count after issuing a rollback is dangerous because you can easily loose track of your transaction nesting level. When performing an explicit rollback in a trigger, you should immediately issue a return statement to maintain consistent behavior between a connection with and without implicit transaction settings. This will force the trigger(s) and batch to terminate immediately. One of the methods of dealing with this issue is to run ‘SET IMPLICIT_TRANSACTIONS OFF’ as the first statement of any trigger. Other methods may entails checking @@TRANCOUNT at the end of the trigger and continue to COMMIT the transaction as long as @@TRANCOUNT is greater than 1. Examples The following examples are based on this table: create table tbl50000Insert (iID int NOT NULL) go Note If more than one trigger is used, to guarantee the trigger firing sequence, the sp_settriggerorder command should be used. This command is omitted in these examples to simplify the complexity of the statements. First Example In the first example, the second trigger was never fired and the batch, starting with the insert statement, was aborted. Thus, the print statement was never issued. print('Trigger issues rollback - cancels batch') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback tran select 'End of trigger', @@TRANCOUNT as 'TRANCOUNT' end go create trigger trg50000Insert2 on tbl50000Insert for INSERT as begin select 'In Trigger2' select 'Trigger 2 Inserted', * from inserted end go insert into tbl50000Insert values(1) print('---------------------- In same batch') select * from tbl50000Insert go -- Cleanup drop trigger trg50000Insert drop trigger trg50000Insert2 go delete from tbl50000Insert Second Example The next example shows that since a new transaction is started, the second trigger will be fired and the print statement in the batch will be executed. Note that the insert is rolled back. print('Trigger issues rollback - increases tran count to continue batch') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback tran begin tran end go create trigger trg50000Insert2 on tbl50000Insert for INSERT as begin select 'In Trigger2' select 'Trigger 2 Inserted', * from inserted end go insert into tbl50000Insert values(2) print('---------------------- In same batch') select * from tbl50000Insert go -- Cleanup drop trigger trg50000Insert drop trigger trg50000Insert2 go delete from tbl50000Insert Third Example In the third example, the raiserror statement is used to set the @@ERROR value and the BEGIN TRAN statement is used in the trigger to allow the batch to continue to run. print('Trigger issues rollback - uses raiserror to set @@ERROR') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback tran begin tran -- Increase @@trancount to allow -- batch to continue select @@trancount as ‘Trancount’ raiserror('This is from the trigger', 14,1) end go insert into tbl50000Insert values(3) select @@ERROR as 'ERROR', @@TRANCOUNT as 'Trancount' go -- Cleanup drop trigger trg50000Insert go delete from tbl50000Insert Fourth Example For the fourth example, a second trigger is added to illustrate the fact that @@ERROR value set in the first trigger will not be seen in the second trigger nor will it show up in the batch after the second trigger is fired. print('Trigger issues rollback - uses raiserror to set @@ERROR, not seen in second trigger and cleared in batch') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback begin tran -- Increase @@trancount to -- allow batch to continue select @@TRANCOUNT as 'Trancount' raiserror('This is from the trigger', 14,1) end go create trigger trg50000Insert2 on tbl50000Insert for INSERT as begin select @@ERROR as 'ERROR', @@TRANCOUNT as 'Trancount' end go insert into tbl50000Insert values(4) select @@ERROR as 'ERROR', @@TRANCOUNT as 'Trancount' go -- Cleanup drop trigger trg50000Insert drop trigger trg50000Insert2 go delete from tbl50000Insert Lesson 3: Concepts – Locks and Applications This lesson outlines some of the common causes that contribute to the perception of a slow server. What You Will Learn After completing this lesson, you will be able to:  Explain how lock hints are used and their impact.  Discuss the effect on locking when an application uses Microsoft Transaction Server.  Identify the different kinds of deadlocks including distributed deadlock. Recommended Reading  Charter 14 “Locking”, Inside SQL Server 2000 by Kalen Delaney  Charter 16 “Query Tuning”, Inside SQL Server 2000 by Kalen Delaney Q239753 – Deadlock Situation Not Detected by SQL Server Q288752 – Blocked SPID Not Participating in Deadlock May Incorrectly be Chosen as victim Locking Hints UPDLOCK If update locks are used instead of shared locks while reading a table, the locks are held until the end of the statement or transaction. UPDLOCK has the advantage of allowing you to read data (without blocking other readers) and update it later with the assurance that the data has not changed since you last read it. READPAST READPAST is an optimizer hint for use with SELECT statements. When this hint is used, SQL Server will read past locked rows. For example, assume table T1 contains a single integer column with the values of 1, 2, 3, 4, and 5. If transaction A changes the value of 3 to 8 but has not yet committed, a SELECT * FROM T1 (READPAST) yields values 1, 2, 4, 5. Tip READPAST only applies to transactions operating at READ COMMITTED isolation and only reads past row-level locks. This lock hint can be used to implement a work queue on a SQL Server table. For example, assume there are many external work requests being thrown into a table and they should be serviced in approximate insertion order but they do not have to be completely FIFO. If you have 4 worker threads consuming work items from the queue they could each pick up a record using read past locking and then delete the entry from the queue and commit when they're done. If they fail, they could rollback, leaving the entry on the queue for the next worker thread to pick up. Caution The READPAST hint is not compatible with HOLDLOCK.  Try This: Using Locking Hints 1. Open a Query Window and connect to the pubs database. 2. Execute the following statements (--Conn 1 is optional to help you keep track of each connection): BEGIN TRANSACTION -- Conn 1 UPDATE titles SET price = price * 0.9 WHERE title_id = 'BU1032' 3. Open a second connection and execute the following statements: SELECT @@lock_timeout -- Conn 2 GO SELECT * FROM titles SELECT * FROM authors 4. Open a third connection and execute the following statements: SET LOCK_TIMEOUT 0 -- Conn 3 SELECT * FROM titles SELECT * FROM authors 5. Open a fourth connection and execute the following statement: SELECT * FROM titles (READPAST) -- Conn 4 WHERE title_ID < 'C' SELECT * FROM authors How many records were returned? 3 6. Open a fifth connection and execute the following statement: SELECT * FROM titles (NOLOCK) -- Conn 5 WHERE title_ID 0 the lock manager also checks for deadlocks every time a SPID gets blocked. So a single deadlock will trigger 20 seconds of more immediate deadlock detection, but if no additional deadlocks occur in that 20 seconds, the lock manager no longer checks for deadlocks at each block and detection again only happens every 5 seconds. Although normally not needed, you may use trace flag -T1205 to trace the deadlock detection process. Note Please note the distinction between application lock and other locks’ deadlock detection. For application lock, we do not rollback the transaction of the deadlock victim but simply return a -3 to sp_getapplock, which the application needs to handle itself. Deadlock Resolution How is a deadlock resolved? SQL Server picks one of the connections as a deadlock victim. The victim is chosen based on either which is the least expensive transaction (calculated using the number and size of the log records) to roll back or in which process “SET DEADLOCK_PRIORITY LOW” is specified. The victim’s transaction is rolled back, held locks are released, and SQL Server sends error 1205 to the victim’s client application to notify it that it was chosen as a victim. The other process can then obtain access to the resource it was waiting on and continue. Error 1205: Your transaction (process ID #%d) was deadlocked with another process and has been chosen as the deadlock victim. Rerun your transaction. Symptoms of deadlocking Error 1205 usually is not written to the SQL Server errorlog. Unfortunately, you cannot use sp_altermessage to cause 1205 to be written to the errorlog. If the client application does not capture and display error 1205, some of the symptoms of deadlock occurring are:  Clients complain of mysteriously canceled queries when using certain features of an application.  May be accompanied by excessive blocking. Lock contention increases the chances that a deadlock will occur. Triggers and Deadlock Triggers promote the deadlock priority of the SPID for the life of the trigger execution when the DEADLOCK PRIORITY is not set to low. When a statement in a trigger causes a deadlock to occur, the SPID executing the trigger is given preferential treatment and will not become the victim. Warning Bug 235794 is filed against SQL Server 2000 where a blocked SPID that is not a participant of a deadlock may incorrectly be chosen as a deadlock victim if the SPID is blocked by one of the deadlock participants and the SPID has the least amount of transaction logging. See KB article Q288752: “Blocked Spid Not Participating in Deadlock May Incorrectly be Chosen as victim” for more information. Distributed Deadlock – Scenario 1 Distributed Deadlocks The term distributed deadlock is ambiguous. There are many types of distributed deadlocks. Scenario 1 Client application opens connection A, begins a transaction, acquires some locks, opens connection B, connection B gets blocked by A but the application is designed to not commit A’s transaction until B completes. Note SQL Server has no way of knowing that connection A is somehow dependent on B – they are two distinct connections with two distinct transactions. This situation is discussed in scenario #4 in “Q224453 INF: Understanding and Resolving SQL Server 7.0 Blocking Problems”. Distributed Deadlock – Scenario 2 Scenario 2 Distributed deadlock involving bound connections. Two connections can be bound into a single transaction context with sp_getbindtoken/sp_bindsession or via DTC. Spid 60 enlists in a transaction with spid 61. A third spid 62 is blocked by spid 60, but spid 61 is blocked by spid 62. Because they are doing work in the same transaction, spid 60 cannot commit until spid 61 finishes his work, but spid 61 is blocked by 62 who is blocked by 60. This scenario is described in article “Q239753 - Deadlock Situation Not Detected by SQL Server.” Note SQL Server 6.5 and 7.0 do not detect this deadlock. The SQL Server 2000 deadlock detection algorithm has been enhanced to detect this type of distributed deadlock. The diagram in the slide illustrates this situation. Resources locked by a spid are below that spid (in a box). Arrows indicate blocking and are drawn from the blocked spid to the resource that the spid requires. A circle represents a transaction; spids in the same transaction are shown in the same circle. Distributed Deadlock – Scenario 3 Scenario 3 Distributed deadlock involving linked servers or server-to-server RPC. Spid 60 on Server 1 executes a stored procedure on Server 2 via linked server. This stored procedure does a loopback linked server query against a table on Server 1, and this connection is blocked by a lock held by Spid 60. Note No version of SQL Server is currently designed to detect this distributed deadlock. Lesson 4: Information Collection and Analysis This lesson outlines some of the common causes that contribute to the perception of a slow server. What You Will Learn After completing this lesson, you will be able to:  Identify specific information needed for troubleshooting issues.  Locate and collect information needed for troubleshooting issues.  Analyze output of DBCC Inputbuffer, DBCC PSS, and DBCC Page commands.  Review information collected from master.dbo.sysprocesses table.  Review information collected from master.dbo.syslockinfo table.  Review output of sp_who, sp_who2, sp_lock.  Analyze Profiler log for query usage pattern.  Review output of trace flags to help troubleshoot deadlocks. Recommended Reading Q244455 - INF: Definition of Sysprocesses Waittype and Lastwaittype Fields Q244456 - INF: Description of DBCC PSS Command for SQL Server 7.0 Q271509 - INF: How to Monitor SQL Server 2000 Blocking Q251004 - How to Monitor SQL Server 7.0 Blocking Q224453 - Understanding and Resolving SQL Server 7.0 Blocking Problem Q282749 – BUG: Deadlock information reported with SQL Server 2000 Profiler Locking and Blocking  Try This: Examine Blocked Processes 1. Open a Query Window and connect to the pubs database. Execute the following statements: BEGIN TRAN -- connection 1 UPDATE titles SET price = price + 1 2. Open another connection and execute the following statement: SELECT * FROM titles-- connection 2 3. Open a third connection and execute sp_who; note the process id (spid) of the blocked process. (Connection 3) 4. In the same connection, execute the following: SELECT spid, cmd, waittype FROM master..sysprocesses WHERE waittype 0 -- connection 3 5. Do not close any of the connections! What was the wait type of the blocked process?  Try This: Look at locks held Assumes all your connections are still open from the previous exercise. • Execute sp_lock -- Connection 3 What locks is the process from the previous example holding? Make sure you run ROLLBACK TRAN in Connection 1 to clean up your transaction. Collecting Information See Module 2 for more about how to gather this information using various tools. Recognizing Blocking Problems How to Recognize Blocking Problems  Users complain about poor performance at a certain time of day, or after a certain number of users connect.  SELECT * FROM sysprocesses or sp_who2 shows non-zero values in the blocked or BlkBy column.  More severe blocking incidents will have long blocking chains or large sysprocesses.waittime values for blocked spids.  Possibl
******************************************* ************ WPTOOLS 6 History ************ ********** http://www.wpcubed.com ********* **** Copyright (C) 2012 J. Ziersch and **** **** WPCubed GmbH, Munich, Germany ******** ******************************************* * - = bug fix * + = new feature * * = changed, expanded feature ******************************************* * IMPORTANT: Please edit file WPINC.INC to * activate WPREPORTER, WPSPELL, wPDF, TBX * and GraphicEx / PNGImage support! * Delphi 2009 and later as inbuilt PNGImage ******************************************* * THE MANUAL (PDF) AND REFERENCE (HLP,CHM) * ARE PROVIDED AS SEPERATE DOWNLOADS! ******************************************* ~~~~~~~~~~ Important Notes ~~~~~~~~~~~~ - With Delphi XE2 or XE3 it is possible to compile WPTools into a 64 bit applications. You need WPTools 6 PRO or WPTools 6 Premium for this. - Localization and Inch/CM selection see http://www.wpcubed.com/manuals/wp5man/index.html?localization.htm Also see demo\tasks\localization. There are the required XML files. - if flag wpDontAddExternalFontLeading is active in property FormatOptionsEx the text will be formatted more like WPTools4/MS-Word. You can alternatively set global variable WPDoNotAddExternalFontLeading := TRUE and select the Printer WYSIWYG mode: TWPRichText1.HeaderFooter.UpdateReformatMode(true) - The FormatOption wpDisableAutosizeTables can be required for good display of tables. wpNoMinimumCellPadding for narrow layout, too. - If you plan to use DBWPRichText please check http://www.wpcubed.com/forum/viewtopic.php?p=3456 - The reader/writer receive their options through "FormatStrings" please see list at http://www.wpcubed.com/manuals/formatstrings.htm - WPTools is configured using the file WPINC.INC, here WPREPORTER is activated and the optional WPShared, WPSPell and wPDF can be selected to be compiled into main WPTools package. - also see FAQ: http://www.wpcubed.com/forum/viewforum.php?f=15 - and support forum: http://www.wpcubed.com/forum/ - WPTools 6 PRO and PREMIUM will be compiled as Version 5 if $define "WP6" is not set ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We recommend to use TMS components to create modern user interfaces, toolbars and ribbons. 19.2.2013 - WPTools 6.29.1 - fix in rtf writing code to solve problem with merged cells - fix possible rangecheck error - fix problem with TextObject.LoadFromFile and Delphi XE3 * RTF reader now handles UNC file links which use "\\" in the path * the cursor was not painted if DoubleBuffered was set to true for the parent of the editor + WPTools Premium: Saves and loads \column * improved theming of TWPToolbar and TWPToolPanel + new event: OnPaintDesktopBackground. It can be used to draw the parent of the editor, for example if it is a TMS panel or pager control. Example: procedure TForm1.WPRichText1PaintDesktopBackground(Sender: TObject; Canvas: TCanvas; R: TRect); begin // This would paint the TWPRichText, too - but TWPRichText is locked for repaint during this event AdvOfficePager1.PaintTo(Canvas, -WPRichText1.Left, -WPRichText1.Top); end; - HighlightTextColor can now also be used if 2Pass Painting is used 21.12.2012 - WPTools 6.29 - images in RTF label were not painted when label was moved + added support for XE3 to WPTools STD edition * stream RTFvariables were not loaded from WPT format. They are loaded now. 9.11.2012 - WPTools 6.28 - Update to RTF reader to load landscape flag for sections better - when page mirror was used, after a page break the text indentation was sometimes wrong - hyphenation code was broken - workaround for word files which have space characters in table definitions 16.10.2012 - WPTools 6.27'' * some additions to the PRO edition for XE3 26.9.2012 - WPTools 6.27' * The PRO Version now supports Delphi XE3 3.8.2012 - WPTools 6.27 - fix for wrong display of tables with header and footer rows. Sometimes both were painted without any data. + to load old Hiedit templates as RTF code use the formatstring -HiEditFields. This will create merge fields for ALL fields. - NL sign was not shown right after CTRL+ENTER was pressed (requires ShowNL) - fix for rangecheck exception with paintpages array - fix for footer and page mirror - doubleclick word selection now stops at NL - Workaround for Windows Spooler problems - some images would get lost - sections use footer and header of previous section, not general - ASetBorder did change all border types 12.3.2012 - WPTools 6.25.4 * allows changing of column width in redonly editors. Can be switchoed off in EditOptions or set compiler define TOTALREADONLY + wpDisableSelectAll in EditOptionsEx2 * changed reformat/repaint after Undo/Redo - pro and premium: Due to a problem with precompiler cursoir selection did not work correctly 8.3.2012 - WPTools 6.25.3' - borders for paragraphs with multiple lines were not drawn correctly - change in DBWPRich.pas to use LoadFromString instead of Text - fix possible range check error - change in WPTbar.pas to use different default for BevelOuter - change in WPIOHTML to use default charattr of paragraph is a paragraph is empty 9.2.2012 - WPTools 6.25.2 * new 2-pass painting triggers CustomPaint event only on second loop (when the text is painted) * changed protection of empty paragraph to WPTools 5 way + inside of the OnPrepareImageForSaving event it is now possible to set Writer.CurrentImageName to the name of the file which should be saved. This is only useful if ObjRef = nil and so no ObjRef.Filename can be set. + TParagraph.GetSubText now has optional parameter to disable the object reference char codes #1, #2 and #3 * HTML writer ignores #13 codes when writing the text. * additional savety code in HTML writer * HTML reader sets image width and height to contents, (if possible) * HTML reader: changes UTF8 handling for UTF8Sequence=1 * HTML reader does not stop on \0 anymore * HTML writer writes img tag also for empty images IF a name is provided in event PrepareImageforSaving * HTML reader does not add space at end anymore - the UNICODE reader uses attribute of current paragraph. This is important for consistent behaviour between ANSI and UNICODE version - when writing HTML background color is not set to white when shading is 0. 0 is treated as default value. - image align center and right now works in HTML - fix an endless loop when image was too large - improvement of table border drawing - improvement for right align in table cells + numbering will be used when wpFormatAsWebpage was set in AsWebpage 10.1.2012 - WPTools 6.25 + HTML reader reads cell heighs - RTF writer writes background color easier to understand by Word * improved XML reader/writer (unit WPIOXml1) * improved word wise cursor movement when fields are used + new "paint attributes" mode. Use WPRichText1.BrushStart to select this mode. - dashes were not painted using the current font color - some stability improvements 7.11.2011 - WPTools 6.22 + procedure TParagraph.CellSelectionAdd; + procedure CellSelectionRemove; + EditOptionsEx2: wpCellMultiSelect - allows multiselection in tables when CTRL is pressed + improved XML import/export (unit WPIOXML1.PAS) - some smaller bugs fixed 3.11.2011 - WPTools 6.21.2 - fix problem with TWPToolButton - improved HTML writer to write parameters in "" - improved display of arabic text 24.10.2011 - WPTools 6.21.1 - fix problem when painting insertpoints after tab stops. They were painted two times. - fix in XML and HTML writer. Close tags when extracting text from fields 19.10.2011 - WPTools 6.21 + CodeLocate can now also accessed in non-visual TWPRTFDataCollection and not just TWPCustomRtfEdit + CodeSelect can now also accessed in non-visual TWPRTFDataCollection and not just TWPCustomRtfEdit + TWPRTFDataCollection.CodeLocatePair( FormatName : String; var spar, epar : TParagraph; var spos, epos, : Integer ) :Integer; - solves problem with integrated Bin64 decoder + DeleteField now has optional "Contents" parameter to delete a certain field with contents + the text writer now understand the option -softlinebreaks to create a \n at the end of every line. In fact all soft line breaks will be handled like the #10 code. + CodeLoadSaveEmbeddedText - load or save text in fields, bookmarks, hyperlinks + the regular save and load methods (LoadFromFile, SaveToFile) can now access text wrapped by paired objects. specify the fieldname in the format string, i.e. "f:name=RTF" to save or load the contents of the field "name". + There is an overloaded LoadFromString which expects a WideString as parameter (Delphi 6+) - The Setup named the Delphi 2009 files "Delphi 2005" due to a typo. (Delphi 2005 units are not included anymore) - fix probable range check error in WPRTEDEFS 13.10.2011 - WPTools 6.20 + completely new setup procedure. The PRO and Premium releases don't include object files which makes them much smaller. * compiled new WPTools 6 Reference (CHM file) * Delphi XE2: several small changes to improve theming support * Delphi XE2: several small changes to provide compatibilty to 64bit compiler (requires WPTools PRO) + new demo developed with Delphi XE2, showcases actions, splitscreen, simulated MDI and property dialogs (Demos\XE2\WPWord) + wpDeleteAtEOFRemovesSpaceAfter in EditOptionsEx2 - TextObjectsGetList did not work * WPRuler uses Delphi XE2 VCL Theme plus * added defaults to properties TWPRichText - change in RTF reader to let section inherit the default layout, not the current page layout - fix of problem with table borders when also PageMirror was used. * change to DeleteMarkedChar. It now has additional parameter DeleteEmptyParAndTables : Boolean * change in unit WPWordConv to handle RTF as DOC files if they do not start with "{\rtf" * updated border dialog TWPParagraphBorderDlgEx * updated border drawing code - now supports dotted lines with wider lines. * modified method DeleteColumn * modified WPT reading code to repair table width which were negative + improved image rendering code for transparent (PNG) images. They will be drawn transparently also when scaled and also in high resolution rendering mode. + new code to draw dotted lines which also supports wider lines + new function WPReplaceTokens (unit WPUtils.PAS). It is a ReplaceTokens function to be used on a TWPRTFDataCollection, not TWPRichText - WPPremium - fix problem when there were too columns * MergeText now restores before Merge Cursor position and selection (except for cell selection) * resizing a table column does not move the cursor to the nearby cell anymore * different frame line when resizing columns and rows + InsertColumn now also works if wpAllowSplitOfCombinedCellsOnly was used in EditOptionsEx + new event OnPaintTextFrameRect let you paint background and borders for text frames, i.e. the text body or, with WPTools Premium, custom frames. + WPPREMIUM: In OnMeasureTextPage it is possible to set columns for certain pages. Using PageInfo.colflags=1 it is possible to activate a line between the columns It is also possible to add custom frames using PageInfo.rtfpage.AddFrameRect. + new ViewOptionEx: wpHideParBordersBeforAndAfterPageBreaks + improved paint routine now avoids clipping of characters which were overlapping their bounding box, such as italic letters or "f". The improvement is especially visible when selecting text or using character background colors + WPPREMIUM: it is now possible to print a line between columns using wpShowColumnCenterLine in ViewOptionsEx + With WPTools Premium it is now possible to print a line between certain colums - use par.ASet(WPAT_COLFLAGS, WPCOLUM_LINE); + paragraph styles can now contain border definion for paragraphs + TWPTextObjList now has a IndexOfSource function and a Source[] string array to access the objects * revised code to draw double borders - always draws twou lines on screen even when zoomed * improved saving of numbering attributes with styles * style dialog can now apply number level even if style does not have numbering yet. * revised wpNoEditOutsideTable - was not checked for keyboard input * fix problem with - - - - - at end of line - fix problem with spell-as-you go after hyperlinks - fix problem with page numbers in sections when tables were spanning pages - fix problem with right aligned negative numbers in merge fields * automatic text attribute was not inherited to tables inserted in fields * images with mode "under text " can now be also clicked at positiones where there is no text. - WPLngCtr now defines DONT_OVERRIDE_COM, that fixes the IDE problem with DevExpress Toolbar controls 18.7.2011 - WPTools 6.16.2 * ObjectMode wpobjPositionAtCenter can be used to aligh character based images to the center line. (Other RTF reader will not understand this feature) * some changes to prepare 64bit compatibility (requires WPTools 6 PRO) 7.7.2011 - WPTools 6.16.1 * change to avoid flickering when doing auto scroll * message strings are now loaded from resource strings - modified DBCS support for RTF reader * outerborder action now works for sinle cells and paragraphs 15.6.2011 - WPTools 6.16 + Many improvements to new Border Dialog. It is now possible to apply borders and colors to odd and even rows only. * RTF reader defines symbol IGNORE_AUTOWIDTH_TBL. This disable the Word2010 auto width columns which are not read correctly. Reason: Word 2010 seem to always add an empty column to the end. + using WPRichText1.Caret.Blink:=true it is possible to activate the blinking caret (0.5sec interval). * updated actions to apply inner and outer borders to selected cells * update to ExSymbolDialog, Tab and Table dialog - improved WPTOOLS reader to read and apply outline properties to current outline setting (unless wpLoadDoesNotOverride is used) - wpsec_ResetPageNumber flag is now saved in WPTOOLS format * tripple click in margin selects paragraph + double click in margin selects current cell + tripple click in margin selects current row - change for PaintEngine and TWPRichTextLabel to not shrink tables which are small enough to fit the page This solves a problem with dissapearing text in WPRichTextLabel - fix selection problem when several images were linked to same paragraph - when moving images the Z order will not be reset - HTML Writer: A style with name "DIV" will be added to the style sheet to save the default font - HTML Writer: BaseFont tag will now be written with font size (requires -writebasefont option) - improved display of character background color for fields and other special code - Saving a style sheet did not work with Unicode Compiler 8.5.2011 - WPTools 6.15 * updated border painting * updated Inner/Outer Border Action * new object sizing routine lets the user make the size larger than the page - update in WPTools reader to overwrite outline styles when loading tzhe same group 9.3.2011 - WPTools 6.14.6 * change in format routine to fix problem when a nested table cell caused a page break. 14.12.2010 - WPTools 6.14 * fix for SetAsString code (Unicode Delphi) * several fixes and updates in editor * WPTools Premium: $define DONT_AUTOENTER_TEXTBOXES in WPINC.INC to switch of the behavior, that when editing a textbox the user can click on any other and edit that. 22.9.2010 - WPTools 6.13.3 * WPCtrMemo.PAS now defines TEXT_IS_UNICODE fro Delphi 2009 and later. Now the property Text and SelText reads and writes unicode strigs * change in RTF reader to read ANSI characters in the range 128..255 * Tables and rows can now be hidden. (TParagraph.Hidden) * The Lines property now supports unicode strings (Delphi 2009 and later) + HTML reader and writer now use the entitly ­ as soft hyphen 27.8.2010 - WPTools 6.13.2a + new ViewOptionEx wpUnderlineWebLinks. If active links like http://www.wptools.de will be drawn using the attributes for hyperlinks The HyperlinkCursor will be selected and the hyperlink event will be triggered * other fixes in RTF engine - Memo._OverrideCharset was not set to -1 27.7.2010 - WPTools 6.13.1 + WPRichText1.Memo.ColorGridLines can be used to change the color of the grid lines (ViewOptions) 23.7.2010 - WPTools 6.13 * several improvements of editor * improvement to RTF writer to when writing table cells * improved right aligned text * fixed problem with line heights of lines which are empty except for new line character 22.6.2010 - WPTools 6.12.1b - fix for problem when pressing Accent + Backspace - fix for WPReporter to assign default attribute to destination - fix for WPReporter to move images when converting templates 18.6.2010 - WPTools 6.12.1a * the new border dialog now reads the current border attributes from table cells, tables or selections - Premium: fix problem when loading columns which started on first line - fix in wpfUseKerning mode (FormatOptionsEx2) - it did not work as expected with some texts (We recommend to use wpfUseKerning - it produces better print quality on screen) * Pasting of HTML now works better - fix for right tabs when also borders were used 13.6.2010 - WPTools 6.12 + all new, powerful yet intuitive Border dialog. The border dialog can modify a range of selected cells, columns, rows, tables and also only modify certain properties while leaving the others unchanged. You need to activate the compiler symbol NEWBORDER to use it by default + new method: procedure SetBorderProperties(Inner, Outer: TWPTextStyle; ApplyMode : TWPParagraphBordApply; Mode : TWPUpdateBorderProperties = [wpSetBorderFlags, wpSetBorderType, wpSetBorderWidth, wpSetBorderColor, wpSetParColor, wpSetParShading]); This method is mainly used by the new border dialog. + new flags in ViewOptionsEx: wpShowCurrentCellAsSelected, // Displays current cell to be selected. Disables current selection wpShowCurrentRowAsSelected, // Displays current table row to be selected. Disables current selection wpShowCurrentTableAsSelected // Displays current table to be selected. Disables current selection + new property YOffsetNormal to defined an upper border for normal and wordwrap view. * feature Header.MarginMirror changed to work like MS Word new flag: wpMarginMirrorBookPrint in FormatOptionsEx2 to enable the previous logic * workaround for MouseWheel UP beeing triggered too often (10 mms check) + ClipboardOption wpcoDontPasteHTML to disable HTML pasting completely (avoid problems with firefox) + it is now possible to load base64 embedded JPEGs from HTML * it is now possible to change width of tables which exceed right margin - fix bug in HTML writer for lists in table cells - fix in RTF writer to write character colors also for text which is using a character style - fix: numbering was not always updated - fix: better use fonts in certain RTF files written by MS Word + Update to WPLanguageControl to make Localization easier to use. Only< this code is not required: procedure TForm1.WPLanguageControl1Loaded(Sender: TObject); begin WPLangInterface := TWPLocalizationInterface.Create(WPLanguageControl1); WPLocalizeAllStrings; end; 6.5.2010 - WPTools 6.11.2 * improvement to border rendering * improvement to XML unit WPIOXML1 (Premium) 5.5.2010 - WPTools 6.11.1 + ConvertTableToText now supports option to also handle soft line breaks - fix problems with underlines at end of line - fix problem when loading hyperlinks in RTF - fix problem when saving attributes to XML (WPTools Premium) - fix problem with text rendering - fix problem with tables which habe header row and pages with different header margin 19.4.2010 - WPTools 6.11 + EditOptionEx: wpRowMultiSelect + new event: OnInternPaintPar + new event: RTFDataCollection AfterApplyUndoObject 14.4.2010 - WPTools 6.10.6 * fields are now passed as unicode strings to PDF exporter * Delphi 2010/2009 import has been improved to load unicode values which are stroed in fields. 5.4.2010 - WPTools 6.10.5 + flag: wpDontExtendSelectionToRightMargin. Do not extend selection to end of line + wpInvertActiveRow in ViewOptionsEx - some fixes for Delphi 2009 and Delphi 2010 - fix for section support - WPTools premium: Fix for images in text boxes - workwaround to load RTF which use emfblib for pngblib 28.2.2010 - WPTools 6.10 - improve word left/right movement to skip hidden text - improve http load of images - improve support for numbering - improve saving of character style attributes 11.2.2010 - WPTools 6.09.1 + LoadFromString now has a "WithClear" parameter - fix in RTF reader to better load files which do not define codepage - fix in paint routine to solve a rare lockup - fix in format routine to improve section support 6.2.2010 - WPTools 6.09.1 - fix of problem in save routine when footnotes were used (WPTools premium) - fix in HTML writer - Image optiions now have a Rotation property which allows 90, 180 and 270 setting. - HTML reader and writer now support different colors for left,right,top, bottom lines 1.2.2010 - WPTools 6.09 - HTML writer will write 8 hard spaces for TAB stops at the start of a paragraph - HTML writer will write page information only if -PageInfo was used in format string - fix problem with left aligned text and image wrap around (wrong alignment) - fix problem with sometimes duplicated images in PDF export - fix problem with black rectangle in first line under Windows 7, 64 bit - Improvment to RTF reader to ignore section properties which are not followed by \sect 14.12.2009 - WPTools 6.08 - graphics are resized to fill text area - fixed problems in numbering - fixed problem with one word paragraphs in justified paragraphs - other improvements in editor 27.10.2009 - WPTools 6.07 - fixed one leaking TList per TWPRichText * improved layout of most important dialogs * improved extended insert symbol dialog - fix in RTF reader to load sections and header+footer written by Word 2003 - don't add unwanted cell padding when loading table cells - fix in WPTools reader to read custom number styles - if paragraph styles use number styles the indent defined in the style has priority over numberstyle - LabelDef now also works for one row and one column - better handling of mousewheel event - fix for tabs in tables + GIF animation (requires GifImage) library (not threaded) to use it You need to set ViewOption wpUseOwnDoubleBuffer and call the method RefreshAniImages using a timer object. - fix problem when sections were used with LabeDef.Active = true * change in HTML writer to close tags before paragraph end 4.10.2009 - WPTools 6.06 - fix problem with Delphi 2010 support (language control) - fix problem with PDF export to reduce PDF size - improve support for IME * improve AsWebPage format mode. Now WordWrap propery is supported. - fix searching text upwards with "Whole Word" selected + RTF writer now can use format option "-writehighlight" to writh \highlight instead of \cb 14.9.2009 - WPTools 6.05.9 + added Delphi 2010 Support - problem when pasting from "The Bat" - fix problem in Delphi 2009 (Assign Method) 3.8.2009 - WPTools 6.05.8' * when using "Delete All" in the tabstop dialog, all tabs will be cleared added to manual: Tabstop Category - fixed problem when deleting text in a paragraph. The alignment was cleared unexpectedly. - fix problem with installer, WPMangeHeaderFooter.DFM was not included - fix for IPara in mail merge field objects - improved handling of hoover effect for hyperlinks - improved text rendering for wPDF output (CID Mode) - add correct WPManHeadFoot.dfm 23.7.2009 - WPTools 6.05.7 + WRITE_PROP_WPTOOLSOBJ $define in WPIOWriteRTF. Avoid problems when saving RTF and opting in Word In case of special objects, such as SPAN codes, \*\wpfldinst is beeing written what is ignored by WOrd + Dialog HeaderFooter can optionally create and manage header&footer for the current section + new KeepN Handling. This is by default activated in FormatOptionsEx2 + new wpfHideParagraphWithHiddenText in FormatOptionsEx2. Now paragraphs will be hidden if empty or only contain hidden text. + new format option -zap1 will remove the every first byte to convert a two byte stream into singly byte -zap2 will remove every second byte. Usie this option when loading data from unicode data sets - bugfix for table loading in RTF 15.7.2009 - WPTools 6.05 + TParagraph.Trim method to remove white spaces at start and end + Vertical Scrolling by pressing the middle mouse button now works. + improved auto thumbnail mode * enhancement to HTML reader / writer to handle embedded SPAN objects + new method: ApplySPANStyles(and_remove : Boolean=false; ignore_charattr : Boolean = false); can be used to apply SPAN styles to the text which it embeds + The function InputSpanObjects( Attributes : TWPAbstractCharAttrInterface ) : TWPTextObj; can be used to wrap the selected text into SPAN objects + method LoadCSSheet can be used to load paragraph styles in CSS format from a string - fix problem with Wordrwap and centered text + new even OnTextObjectMovePosition (move event) - OnTextObjectMove is still used for resize (unchanged) 28.6.2009 - WPTools 6.04 + WPTools Premium: Column Balancing * many improvements in RTF reader. Word documents are now understood better * Improvement in check for protected text (ppMergedText) + new ViewOptionsEx property - auto hyperlinks were not working + TWPComboBox has an event OnUpdateItems which will be triggered after the items had been automatically assigned. 24.6.2009 - WPTools 6.03.6 * thinner page borders in thumbnail mode. ViewOptionsEx: wpAutoThumbnailMode will show pagenumbers only when in thubmbnail mode (= wpShowPageNRinGap in ViewOptions) + property ColorDesktop and DeskGradientHorizontal to render the background with a gradient fill * fix for protected text handling (CR after a field) * fix for text alignment near a movable image - EditOption AutoDetectHyperlinks was not working anymore * WPReporter: SuperMerge.Stack.PageBreakAFterGroup := true was ot working when footers were used 1.6.2009 - WPTools 6.03.5 - fix problem with display of character attributes when attributes were inherited from paragraph styles - fix problems with selection deletion in single column, single row tables - improvement of RTF writer when writing sections 11.5.2009 - WPTools 6.03.3 - improved report band dialog, new ShowOptions property - fix in RTF reader to load header/footer - change in HTML writer to save SPAN instead of FONT tag - several fixes in editor * WPTools Premium: better column support. Fixed column height now splits correctly on 2 pages. 28.4.2009 - WPTools 6.03.2 - fix problem with justified text in PDF 21.4.2009 - WPTools 6.03.1 - fix problem with images when used in Delphi 2009 - better support for header/footer in RTF files created by word. (Ignore bogus header/footer) - soome stability fixes 25.3.2009 - WPTools 6.03 + improved text rendering - optimation for character distances on screen to provide better display + improvement on ShowMergeFieldNames to improve cursor movement and drag and drop + automatic disable dragging of fields inside of fields + improved merge field selection. TextObject.SelectedObject now returns the mergefield if it was completely selected + change in HTML saving code to save src in after width adn height (for outlook) * various bugfixes 17.1.2009 - WPTools 6.02 - WPPREMIUM: Text after Columns initialized with WPAT_COLUMNS_Y is now allowed + TWPToolBar FontName drop down now lists fonts used by document first - fix for tables which use a fixed row height and are splitted on different pages + improvements necessary for Delphi 2009 - the Locaization demo now works + EditOptionEx wpDontPreserveObjectsAgainstDeletion - fix problem in ImageObject LoadFromStream when GraphicEx is used - fix problem with Delphi 2009 when loading WPReporter templates - fix problem with HTML reader with paragraph style of first paragraph + GetFontUnicodeRanges dynamically linked to avoid Win98 problem 26.10.2008 - WPTools 6.01 * updated HTTP Demo, now with "Source View" + DELETE/BACKSPC at start of line removes right/center alignment + loads background images for paragraphs, tables and styles * improvement to text protection (empty lines) - improvements to HTML and CSS reader - improved HTML format routine - improved MIME loading - now supports binary data despite Synapse does not) + MIME reader capturesHTML body for SourceVIew * DataProvider now uses MergeText('',true) instead of MergeText + boolean wphttp_Disable to disconnect HTTP temporarily * several changes to improve compatibility with Delphi 2009 17.10.2008 - WPTools 6.00.1 - several changes to fix problems which occured with use of Delphi 2009 * update to WPIO_MIME to also load binary encoded GIFS and JPEGS from EML files 16.10.2008 - WPTools 6.00 * new installer + VCL demo * fixed problem with TWPComboBox and default attributes * updated "Tasks\Mini" demo project - fix in default actions 3.10.2008 - WPTools 6 Beta c - remove not required unit reference form WPRTEReport * update to manual 2.10.2008 - WPTools 6 Beta b - fix in Installation script 30.9.2008 - WPTools 6 Beta a 1) Application-Server-Mode WPTools 6 introduces a feature which is called "Application-Server-Mode". This is only available when you have the PREMIUM version. This mode is activated when true is assigned to the global boolean variable WPAppServerMode. When this mode is activated the editor does not use the double buffered output anymore. While this can cause some flickering the network traffic is reduced when the application runs on an application server, such as Citrix. Please note, effective with WPTools 6, software which was written for application servers (such as clinic software) may only be distributed when a TEAM or SITE license of WPTools was acquired.END 2) Integrated Label Printing When activated the integrated label printing shows multiple labels on one virtual sheet of paper. The cursor can move from label to label freely. The user can so edit the labels, add new or delete unwanted labels before the complete sheet is printed. This is a very unique and versatile feature. 3) Additions to the PDF export with wPDF V3 Create embedded data objects Create edit / memo fields Create a check box field Also the creation of PDF tags was enhanced. So now hints to paragraph styles will be also exported. 4) Additional Control over Clipboard Actions a) properties to select the format b) added security 5) Added Section API + WPRichText1.ActiveSection + WPRichText1.InputSection + TWPPagePropDlg has new method ExecuteEx. Use it to change current page size or Section WPPagePropDlg1.ExecuteEx(WPRichText1.ActiveSection); 6) Load over HTTP connections (requires Synapse) 7) Load and save MIME encoded HTML with embedded images (requires Synapse) 8) Integrated XML syntax highlighting (non destructive) 9) WPReporter: Token to Template conversion with syntax highlighting 10) Additions to paragraph API 11) Special mode to format HTML documents
Release history (reverse chronological order) This release 1.3.7.1 Release date: December 11, 2006 Known bugs: none Fixes/features added from previous release: a) added support for multiple filters per process in VsDrvr.dll b) updated manual Previous release 1.3.5 Release date: October 11th, 2005 Known bugs: none Fixes/features added from previous release a) added VsSetWavelengthStep and VsGetWavelengthStep functions b) added VsSetWavelengthWavesConfirm() function c) fixed error-handling of VsSetWavelength() In earlier revisions, the error status light was cleared after a VsSetWavelength() call failed, so the user did not see the light turn red to alert that an error had occurred. This has been fixed in 1.35 so the error light remains lit, and an error code is returned. d) added range-check to VsDefinePalette() Previous revisions did not range-check the palette index number, and hard crashes could be produced if out-of-range values were supplied to this routine. Previous release 1.33b Release date: February 9, 2005 Known bugs: none Fixes/features changed from previous release: a) Fixed installer: programmers?guide (vsdrvr.pdf) installed when SDK is selected. Previous release 1.33a Release date: January 10th, 2005 Known bugs: i) SDK programmers?guide is not installed even if SDK is selected. Fixes/features added from previous release a) VsDrvr.dll fixed handling of COMx ports that do not support 460kb The autobaud sequence tries a variety of baud rates, some of which are not supported by RS-232 interfaces (but are supported on USB virtual COM ports). This was not handled properly, so if a call was made to VsOpen when no VariSpec was present, but a later call was made when a filter was present, the latter would fail. b) VsGui added check of which COMx ports are present on computer This program now filters its COMx list and only shows ports which actually exist; it used to show COM1 ?COM8 even if not all of these were present. c) VsGui added automatic filter detection on Configure dialog This checks all ports in turn, and reports the first detected filter. The search order is determined by the order in which the computer lists ports in the Registry. d) VsGui changed to recognize filters as present while initializing In prior revisions, VsGui would not report no filter found if a filter was present but still going through its power-up initialization. Now, a message box is posted to indicate that a filter was found, and the program checks whether initialization is complete, at 1 second intervals. When the filter is done initializing, the VsGui controls become active and report the filter information (serial number, wavelength range, etc). e) VsGui added filter status item to Configure dialog Adjacent the COMx combo box, there is now a text field that indicates filter status as 揘ot found? 揑nitializing? or 揜eady? This field is updated whenever the combo box selection is changed. Previous release 1.32 Release date: July 27th, 2004 Known bugs: COMx port described above as 1.33 fix item a) Fixes/features added from previous release a) VsGui added a sweep feature to enable cycling the filter The wavelength start, stop, and step are adjustable. Cycling can be done a fixed number of times or indefinitely. Previous release 1.30 Release date: June 23rd, 2004 Known bugs: none Fixes/features added from previous release a) New commands VsSetWaveplateAndWaves(), VsGetWaveplateAndWaves(), VsGetWaveplateLimits(), and VsGetWaveplateStages() were added for support of variable retarder models. b) New commands VsSetRetries() and VsSetLatencyMs() were added for control of serial port latency and automatic retry in case of error. c) New commands VsSetMode() and VsGetMode() were added for control of the VariSpec filter抯 triggering and sweep modes d) New command VsGetSettleMs() was added to learn optics settling time e) New commands VsIsDiagnostic() and VsIsEngagedInBeam() were added. These are reserved for CRI use and are not supported for use by end users. f) The command syntax and functionality of the VsSendCommand() function was changed - see description of this command for details g) The VsGui program was modified to add sweep function, and the associated files were added to the file manifest. The new functions are assigned higher ordinal numbers than the earlier commands, so the ordinal numbers assigned to routines in the earlier VsDrvr routines are preserved. This means one may use the new VsDrvr.dll file with applications that were developed and linked with the earlier release, without any need to recompile or relink the application. Of course, to use the new functions one must link the application code with the new .lib file containing these functions. Previous release: 1.20 Release date December 3rd, 2003 Known bugs: a) there is a conflict when one uses the implicit palette to set wavelengths, and also defines palette states explicitly using the VsDefinePalette() function. When the explicitly set palette state overwrites a palette state implicitly associated with a certain wavelength, that wavelength will not be accurately set when one issues the VsSetWavelength() command. This is fixed in release 1.30 Fixes/features added from previous release a) fixes bug with implicit palette in September 8 release b) incorporates implicit retry for command send/reply if error in transmission c) recognizes filters with serial numbers > 60000 (normally VariLC numbers) d) supports binary transfer of >127 bytes Previous release 1.11 Release date September 8, 2003 Known bugs a) implicit palette can fail to create palette entry, causing tuning error b) VsSendBinary() fails if 128 chars or more sent (signed char error) Fixes/features added from previous release a) included VsIsPresent() function omitted from function list of 1.10 release Previous release 1.10 Release date: August 28th, 2003 Known bugs: a) VsIsPresent function not included ?generates 搖nresolved external?at link-time Fixes/features added from previous release: b) added command VsEnableImplicitPalette() to code and documentation added command VsConnect() to code and documentation added command VsClose() to code and documentation added local variable to avoid unnecessary querying of diagnostic status documented that command VsConnect() will not be supported in future documented that command VsDisconnect() will not be supported in future documented that command VsIsConnected() will not be supported in future changed to Windows Installer from previous ZIP file added table summary of commands to this manual Previous release 1.00 Release date: November 5th, 2002 Known bugs: a) none Fixes/features added from previous release b) n/a ?initial releaseDescription This package provides a set of functions to control the VariSpec filter, which may be called from C or C++ programs. It incorporates all aspects of the filter communication, including low-level serial routines. With these routines, one can address the filter as a virtual object, with little need for detailed understanding of its behavior. This simplifies the programming task for those who want to integrate the VariSpec into larger software packages. File manifest All files are contained in a single installer file which includes the following: vsdrvr.h declaration file vsdrvr.lib library stub file vsdrvr.dll run-time library vsdrvr_r1p30.pdf (this file) release notes and programmer抯 guide {sample program using VsDrvr package} registryAccess.cpp registryAccess.h resource.h stdafx.h VsConfigDlg.cpp VsConfigfDlg.h VsGui.cpp VsGui.h VsGui.mak VsGui.rc VsGuiDlg.cpp VsGuiDlg.h VsSweep.cpp VsSweep.h Development cycle In order to use the DLL, one should take the following steps: a) Add #include 搗sdrvr.h?statements to all files that access the VariSpec software b) Add vsdrvr.lib to the list of modules searched by the linker c) Place a copy of vsdrvr.dll in either the folder that includes the executable code for the program being developed; or, preferably, in the windows system folder. Failures in step a) will lead to compiler errors; in step b) to linker errors; in step c) to a run-time error message that 揳 required .DLL file, vsdrvr.dll, was not found? VariSpec filter configuration The VariSpec filter communicates via ASCII commands sent over an RS-232 interface or USB. The RS232 can operate at 9600 or 19,200 baud, while the USB appears as a virtual COMx device. While it appears to be present at either 9600 baud or 115.2 kbaud , the actual data transmission occurs at 12 MBaud over the USB. Each command is terminated with an end-of-line terminator which can be either a carriage-return <c/r> or line feed <l/f>. For RS-232 models, the baud rate and terminator character are selected using DIP switches inside the VariSpec electronics module. Default settings are 9600 baud, and the <c/r> character (denoted 慭r?in the C language). For USB devices, the terminator is always <c/r>. For latest information, or to determine how to alter the settings from the factory defaults, consult the VariSpec manual. Timing and latency The VariSpec filter takes a finite time to process commands, which adds an additional delay to that imposed by simple communication delays. In general, the time to process a given command is short except for the following operations: ?filter initialization ?wavelength selection ?palette definition The first of these is quite lengthy (30 seconds or more) because it involves measurements and exercising of the liquid crystal optics. The latter two are much faster but still can take a significant amount of time (up to 300 ms) on the older RS-232 electronics due to the computations involved. On the newer, USB electronics, the latter two functions are completed in less than 5 ms. For this reason, the functions that handle these actions offer the option of waiting until the action is complete before returning (so-called synchronous operation); although they can be called in an asynchronous mode where the function returns as soon as all commands have been sent to the VariSpec, without waiting for them to run to completion. Another option is to use implicit palette tables. If this is enabled, by calling the VsEnableImplicitPalette() function, the driver will define the settings for a given wavelength once, then saves the results within the VariSpec for faster access next time that wavelength is used. Subsequent access times are essentially instantaneous, until either all of the 128 palette states are in use, or the palette is cleared via the VsClearPalette() command. The VsIsReady() function can be used to determine whether a filter is done processing all commands. Ideally, one should check VsIsReady() using a timer or the like to wait efficiently, so that the host PC is free to do other tasks while waiting for the VariSpec. The VariSpec always processes each command to completion before starting on the next command, and it has a 256 byte input buffer, so there is no problem issuing several commands at once; they will all be executed, and in the order given. This also indicates another way to coordinate one抯 program with the VariSpec filter: one can issue any of the VsGetxxx() functions, which query the filter. Since these do not return until the filter has responded, one may be sure that there are no pending commands when the VsGetxxx() function completes. The VsDrvr package provides for automatic re-try of commands up to 3 times, in the event that communications are garbled, and will wait up to 2 seconds for completion of serial commands. The number of retries can be set from 0 to 10, and the latency adjusted, if desired. However, there should be no need to do so. The hardware and software have been tested and observed to execute several million commands without a single communications error, so in practice the need for the retry protocol is very slight. Communication speed is not improved by reducing the latency, since commands proceed when all characters are received, and the latency time to time-out is only relevent when there is a communications lapse ?and as noted, these are very unlikely so the performance burden of retries should not be a practical consideration. Multiple Filters and Multiple Processes These routines only permit one VariSpec per process, and one process per VariSpec. So, these routines cannot control multiple filters at once from a single process; nor can several active processes seek to control the same filter at the same time. The VsDrvr package anticipates a future upgrade to enable control of multiple filters per process, so it makes use of an integer handle to identify which VariSpec is being controlled, even though (for now) only a single filter can be active. This handle is checked, and the correct handle must be used in all calls. Program flow and sequence Typical programs should use the following API calls (all applications, upon initiating link to the filter) ?call VsOpen() to establish communications link (required) ?call VsIsPresent() to confirm a filter is actually present ?call VsIsReady() in case filter is still doing power-up sequence <wait until no longer busy> ?call VsGetFilterIdentity() to learn wavelength limits and serial number if needed (if setting wavelengths via implicit palettes; recommended especially with older filters) ?call VsEnableImplicitPalettes() ? (to set wavelengths, either directly or via implicit palettes) ?call VsSetWavelength() and VsGetWavelength() to select and retrieve tuning (if setting wavelengths by means of palettes, and managing palettes explicity) ?call VsDefinePaletteEntry() and VsClearPalette() to define palette entries ?call VsSetPalette() and VsGetPalette() to select and retrieve palette state (all applications, when done with the filter) ?call VsClose() to release the communications link (required) Sample program Source code for a sample program, VsGui, is provided, which illustrates how to control a VariSpec filter using the VsDrvr package. All filter control code lives in the VsGuiDlg.cpp module, specifically in the Connect(), RequestToSetWavelength(), and VsWriteTimerProc() functions. The latter two use a system timer to decouple the GUI from the actual filter control, for more responsive feedback to the user. Such an approach is unnecessary if palettes are used, which is preferable when one wishes the best real-time performance. See the VariSpec manual for further information. Auxiliary commands Certain commands are normally only used at the factory when filters are being built and configured, or in specialized configurations. These appear after the normal command set in the listing below. Obsolescent commands The VsConnect(), VsIsConnected(), and VsDisconnect() functions are obsolescent. They are supported in this release, but will not necessarily exist in releases after 1.3x. As they are obsolescent, they are not recommended for new code. These function calls are not documented further in this manual.Summary of commands Normal Commands VsClearError(vsHnd) VsClearPalette(vsHnd) VsClearPendingCommands(vsHnd) VsClose(vsHnd) VsDefinePalette(vsHnd, palEntry, wl) VsEnableImplicitPalette(vsHnd, isEnabled) VsGetError(vsHnd, *pErr) VsGetFilterIdentity(vsHnd, *pVer, *pSerno, *pminWl, *pmaxWl) VsGetMode(vsHnd, int *pMode) VsGetPalette(vsHnd, *ppalEntryNo) VsGetSettleMs(vsHnd, *psettleMs) VsGetTemperature(vsHnd, *pTemperature) VsGetWavelength(vsHnd, *pwl) VsGetWavelengthAndWaves(vsHnd, double *pWl, double *pwaves) VsGetWaveplateLimits(vsHnd, double *pminWaves, double *pmaxWaves) VsGetWaveplateStages(vsHnd, int *pnStages) VsIsPresent(vsHnd) VsIsReady(vsHnd) VsOpen(*pvsHnd, portName, *pErrorCode) VsSetLatencyMs(vsHnd, nLatencyMs) VsSetMode(vsHnd, mode) VsSetPalette(vsHnd, palEntry) VsSetRetries(vsHnd, nRetries) VsSetWavelength(vsHnd, wl, confirm) VsSetWavelengthAndWaves(vsHnd, wl, waveplateVector) Auxiliary commands VsGetAllDrive(vsHnd, *pStages, drive[]) VsGetNstages(vsHnd, *pStages) VsGetPendingReply(vsHnd, reply, nChars, *pQuit, firstMs, subsequentMs) VsGetReply(vsHnd, reply, nChars, waitMs) VsIsDiagnostic(vsHnd) VsIsEngagedInBeam(vsHnd) VsSendBinary(vsHnd, bin[], nChars, clearEcho) VsSendCommand(vsHnd, cmd, sendEolChar) VsSetStageDrive(vsHnd, stage, drive) VsThermistorCounts(vsHnd, *pCounts) Alphabetical list of function calls Syntax Throughout this manual, the following conventions are used: VSDRVR_API Int32 VsOpen( VS_HANDLE *vsHnd, LPCSTR port, Int32 *pErrorCode ) Bold text is used for function names Italics indicate variables whose names (or values) are supplied by the user in their code Name-mangling The declaration file vsdrvr.h includes statements that render the API names accurately in a C++ environment, i.e. free of the name-mangling decoration suffix that is normally added by C++ compilers. Thus the functions can be called freely from either C or C++ programs, using the names exactly as shown in this manual or in the VsDrvr.h file. Call and argument declarations The call protocol type, VSDRVR_API, is declared in vsdrvr.h, as are the types Int32 and VS_HANDLE. Errors All functions return an Int32 status value, which is TRUE if the routine completed successfully and FALSE if there was an error. If there is an error in the VsOpen() function, the error is returned in *pErrorCode. If there is an error in communicating with a filter after a successful VsOpen(), one should use the VsGetError() function to obtain the specific error code involved. This function returns VSD_ERR_NOERROR if there is no error pending. Main and auxiliary functions The next section provides a description of the main functions, in alphabetic order; followed by the auxiliary functions, also in alphabetical order. In normal use, one will probably have no need for the auxiliary functions, but this list is provided for completeness. VSDRVR_API Int32 VsClearError( VS_HANDLE vsHnd ) Arguments: vsHnd handle value returned by VsOpen() Purpose: this function clears any pending error on the VariSpec. This resets the error LED on the filter, and sets the pending error to VS_ERR_NOERROR. Returns: TRUE if successful, FALSE otherwise Notes: noneVSDRVR_API Int32 VsClearPalette( VS_HANDLE vsHnd ) Arguments: vsHnd handle value returned by VsOpen() Function: clears all elements of the current filter palette and renders the current palette element undefined. Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsClearPendingCommands( VS_HANDLE vsHnd ) Arguments: vsHnd handle value returned by VsOpen() Function: clears all pending commands including any presently in-process Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsClose( VS_HANDLE vsHnd ) Arguments: vsHnd handle value returned by VsOpen(). May also be NULL, in which case all VariSpec filters are disconnected. Function: Disconnects the filter. Returns: TRUE if successful, FALSE otherwise Notes: No other functions will work until VsOpen() is called to re-establish communications with the filter. VSDRVR_API Int32 VsDefinePalette( VS_HANDLE vsHnd, Int32 palEntry, double wl) Arguments: vsHnd handle value returned by VsOpen() palEntry palette entry to be defined, in the range [0, 127] wl wavelength associated with this palette entry Function: creates a palette entry for the entry and wavelength specified. This palette entry can then be accessed using VsSetPalette() and VsGetPalette() functions. Returns: TRUE if successful, FALSE otherwise Notes: palettes provide a fast way to define filter settings for wavelengths that are to be repeatedly accessed. The calculations are performed once, at the time the palette element is defined, and the results are saved in a palette table to tune to that wavelength without repeating the underlying calculations. And, one may cycle through the palette table, once defined, by means of TTL a trigger signal to the filter electronics. For more information about using palettes, consult the VariSpec user抯 manual. VSDRVR_API Int32 VsEnableImplicitPalette( VS_HANDLE vsHnd, BOOL imlEnabled) Arguments: vsHnd handle value returned by VsOpen() implEnabled selects whether to use implicit palette definition Function: enables or disables implicit palette generation when wavelengths are defined using the VsSetWavelength function. If enabled, a new palette entry is created whenever a new wavelength is accessed, and the VsSetWavelength function will use this palette entry whenever that wavelength is accessed again, until the palette is cleared. The result is improved tuning speed; however, it means that the palette contents are altered dynamically, which can be a problem if one relies upon the palette contents remaining fixed. Clearing the palette with VsClearPalette() will clear all implicit palette entries as well as explicitly defined palette entries. This is useful if one knows that wavelengths used previously will not be used again, or that a new set of wavelengths is about to be defined and one wishes to make sure there is sufficient room in the palette. Returns: TRUE if successful, FALSE otherwise Notes: By default, the implicit palette is enabled for VariSpec filters that have RS-232 interface, and is disabled for newer VariSpec filters that have the USB interface. This is because the newer filters perform the filter tuning calculations fast enough that no performance improvement is obtained by using the implicit palette to set wavelength. For more information about using palettes, consult the VariSpec user抯 manual. VSDRVR_API Int32 VsGetError( VS_HANDLE vsHnd, Int32 *pErr) Arguments: vsHnd handle value returned by VsOpen() pErr pointer to the int that will receive the most recent error code Purpose: this function clears any pending error on the VariSpec. This resets the error LED on the filter, and sets the pending error to VS_ERR_NOERROR. Returns: TRUE if successful, FALSE otherwise Notes: noneVSDRVR_API Int32 VsGetFilterIdentity( VS_HANDLE vsHnd, Int32 *pVer, Int32 *pSerno, double *pminWl, double *pmaxWl ) Arguments: vsHnd handle value returned by VsOpen() pVer pointer to variable that receives the filter firmware version pSerno pointer to variable that receives the filter serial number pminWl pointer to variable that receives the filter抯 minimum wavelength pmaxWl pointer to variable that receives the filter抯 maximum wavelength Purpose: this function reads the filter抯 information using the VariSpec 慥?command, and puts it to the call variables. Any one of the pointers may be NULL, in which case that piece of information is not returned. Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsGetMode( VS_HANDLE vsHnd, Int32 *pMode ) Arguments: vsHnd handle value returned by VsOpen() pMode pointer to variable that receives the filter mode Purpose: this function enables one to read the filter抯 present mode. The mode describes how the filter responds to hardware triggers, and is described in the filter manual. If the pointer *pMode is NULL, no information is returned. Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsGetPalette( VS_HANDLE vsHnd, Int32 *ppalEntry ) Arguments: vsHnd handle value returned by VsOpen() ppalEntry pointer to int that receives the 0-based palette entry number. This pointer may not be NULL. Purpose: this function determines what palette entry is currently active and returns it to *ppalEntry. If the present palette entry is undefined, it sets *ppalEntry to ? and returns a successful status code. Returns: TRUE if successful, FALSE otherwise Notes: noneVSDRVR_API Int32 VsGetSettleMs( VS_HANDLE vsHnd, Int32 *pSettleMs ) Arguments: vsHnd handle value returned by VsOpen() pSettleMs pointer to variable that receives the filter settling time Purpose: this function returns the filter抯 settling time, in milliseconds. This is useful for establishing overall system timing. The settling time is defined as beginning at the moment that the electronics have processed the request to change wavelength, as determined by VsIsReady() or equivalent. At that moment, the new set of drive signals are applied to the optics, and the optics will settle in *psettleMs milliseconds. The settling time is defined as a 95% settling time, meaning the filter has settled to 95% of its ultimate transmission value at the new wavelength being tuned to. Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsGetTemperature( VS_HANDLE vsHnd, double *pTemperature ) Arguments: vsHnd handle value returned by VsOpen() pTemperature pointer to double that will receive the filter temperature, in C This pointer may not be NULL Purpose: this function determines the filter temperature using the VariSpec 慪?command, and puts the result to *pTemperature. Returns: TRUE if successful, FALSE otherwise Notes: noneVSDRVR_API Int32 VsGetWavelength( VS_HANDLE vsHnd, double *pwl ) Arguments: vsHnd handle value returned by VsOpen() pwl pointer to double that will receive the filter wavelength, in nm This pointer may not be NULL Purpose: this function determines the current filter wavelength and returns it to *pwl. If the present wavelength is undefined, it sets *pwl to ? and returns a successful status code. Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsGetWavelengthAndWaves( VS_HANDLE vsHnd, double *pwl, double *pwaves ) Arguments: vsHnd handle value returned by VsOpen() pwl pointer to double that will receive the filter wavelength, in nm. This pointer may not be NULL pwaves pointer to double array that will receive one or more waveplate settings. The actual number of settings may be determined by VsGetWaveplateStages(). Purpose: this function determines the current filter wavelength and returns it to *pwl. If the present wavelength is undefined, it sets *pwl to ? and returns a successful status code. If the present wavelength is defined, it also returns the waves of retardance at each of the polarization analysis waveplates in the optics, in the pwaves[] array. Returns: TRUE if successful, FALSE otherwise Notes: See the description of the VsGetWaveplateStages() command for more detail on what stages are considered waveplates. VSDRVR_API Int32 VsGetWaveplateLimits( VS_HANDLE vsHnd, double *pminWaves, double *pmaxWaves ) Arguments: vsHnd handle value returned by VsOpen() pminWaves pointer to double array that will receive the minimum retardances possible at each of the waveplate stages in the filter optics. pmaxWaves pointer to double array that will receive the maximum retardances possible at each of the waveplate stages in the filter optics Purpose: this function determines the range of retardances that are possible at each waveplate stage, in waves, at the present wavelength setting. Note that the retardance range is itself a function of wavelength, so the results will vary as the wavelength is changed. Returns: TRUE if successful, FALSE otherwise Notes: See the description of the VsGetWaveplateStages command for more detail on what stages are considered waveplates. VSDRVR_API Int32 VsGetWaveplateStages( VS_HANDLE vsHnd, Int32 *pnwpStages ) Arguments: vsHnd handle value returned by VsOpen() pnwpStages pointer to Int32 that will receive the number of waveplate stages in the filter optics. This pointer may not be NULL Purpose: this function determines how many polarization analysis stages are present in the optics and returns this number. Note that although all VariSpec filters operate by means of variable retarder element, optical stages that perform wavelength tuning rather than polarization analysis are not treated as waveplate stages. For example, most VariSpec filters do not include any polarization analysis stages and thus report no waveplates. VsGetWaveplateStages will return a value of 2 for conventional PolScope optics. In contrast, VsGetNstages() reports the total number of stages in a filter, including stages that perform polarization analysis and stages that perform wavelength tuning. Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsIsPresent( VS_HANDLE vsHnd ) Arguments: vsHnd handle value returned by VsOpen() Function: determines whether a filter is actually present and responding. This is done using the status-check character ??as described in the VariSpec manual. Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsIsReady( VS_HANDLE vsHnd ) Arguments: vsHnd handle value returned by VsOpen() Function: determines whether the filter is done processing all commands, and is ready to receive new commands. Returns: TRUE if successful, FALSE otherwise Notes: this is useful when sending commands such as VsSetWavelength(), VsInitialize(), VsExercise(), and VsDefinePaletteEntry() in asynchronous mode. These commands take a prolonged time, and running them synchronously ties up the processor waiting. Alternatively, one can create a loop that uses CreateWaitableTimer(), SetWaitableTimer(), and WaitForSingleObject() to call VsIsReady() at intervals, checking whether the filter is ready. This approach, though more work for the programmer, leaves most of the processor capacity free for other tasks such as GUI update and the like. VSDRVR_API Int32 VsOpen (VS_HANDLE *pvsHnd, LPCSTR port, Int32 *pErrorCode ) Arguments: pvsHnd pointer to handle. This pointer may not be NULL. port port name, such as 揅OM1? pErrorCode pointer to Int32 to receive an error code if VsOpen() fails Purpose: establishes a connection to the VariSpec using the port specified, and automatically determines the baud rate and end-of-line character for subsequent communications. It also retrieves the filter抯 serial number and wavelength range, to confirm that it is a VariSpec and not some other similar device. However, these are retrieved purely as an integrity check, and the values are not returned to the calling application. See VsGetFilterInfo() to access this information. If the device responds as a VariSpec does when it is not ready (i.e. still initializing), VsOpen() fails and returns the error code VSD_ERR_BUSY. However, one may not be sure that the device is a VariSpec until VsOpen() completes successfully The error codes returned by this function are listed in VsDrvr.h. When VsOpen() runs successfully, *pErrorCode is set to VSD_ERR_NOERROR. The handle associated with this filter is set by VsOpen() to a nonzero handle value if successful, or to NULL if no connection is established. The port may refer to COM1 through COM8. Return: TRUE if successful, FALSE otherwise Notes: Until this function is called, none of the other functions will work. VSDRVR_API Int32 VsSetLatency( VS_HANDLE vsHnd, Int32 latencyMs ) Arguments: vsHnd handle value returned by VsOpen() latencyMs the serial port latency, in ms, in the range [1, 5000] Purpose: this function sets the latency time for USB or RS-232 commands to the value given by latencyMs. Commands that do not conclude in this time are considered to have timed-out. Returns: TRUE if successful, FALSE otherwise Notes: increasing the latency time does not increase the time for commands to complete, nor does it insert any delays in normal processing. It merely defines the window for maximum transmission time, beyond which time an error is reported. VSDRVR_API Int32 VsSetPalette( VS_HANDLE vsHnd, Int32 palEntry ) Arguments: vsHnd handle value returned by VsOpen() palEntry the palette entry to be set, in the range [0, 127] Purpose: this function sets the filter to the palette entry specified by palEntry Returns: TRUE if successful, FALSE otherwise Notes: palettes are a good way to control the filter in applications where it will be cycled repeatedly to various, fixed wavelength settings. Palettes calculate the filter settings once, and save the results for rapid access later, rather than calculating them each time, as occurs when one sets the wavelength directly with VsSetWavelength(). See the VariSpec manual for more information on palettes.VSDRVR_API Int32 VsSetRetries( VS_HANDLE vsHnd, Int32 nRetries ) Arguments: vsHnd handle value returned by VsOpen() nRetries the number serial communications retries, in the range [0, 10] Purpose: The VsDrvr software automatically detects errors in communication and re-sends if an error is detected. This function sets the number of times to retry sending any single command, before reporting a communications failure. The default is 3, which should be adequate, and one should rarely need to change this, if ever. The primary purpose of this function is to enable setting the number of retries to zero, to force single-error events to cause detectable errors (as they would normally be fixed automatically via the retry mechanism) Returns: TRUE if successful, FALSE otherwise Notes: noneVSDRVR_API Int32 VsSetWavelength( VS_HANDLE vsHnd, double wl, BOOL confirm ) Arguments: vsHnd handle value returned by VsOpen() wl wavelength to tune to, in nm confirm logical flag, indicating whether to confirm actual wavelength value Purpose: this function sets the filter wavelength to the value in wl. If confirm is TRUE, it waits for the filter to complete the command, and then reads back the actual wavelength to confirm it was implemented successfully. Note that the only time there can be a disparity is when the wavelength requested by wl lies outside the legal range for that filter, or if the wavelength is specified to a finer resolution than the filter recognizes (normally, 0.01 nm). Returns: TRUE if successful, FALSE otherwise Notes: noneVSDRVR_API Int32 VsGetAllDrive( VS_HANDLE vsHnd, Int32 *pStages, Int32 drive[] ) Arguments: vsHnd handle value returned by VsOpen() pStages pointer to int that will receive the number of stages in the filter drive[] int array to receive the filter drive levels. Purpose: this function reports the number of filter stages in *pStages. If this argument is NULL, it is ignored. The function returns the actual drive level at each stage, in counts, in drive[] , which must not be NULL. Returns: TRUE if successful, FALSE otherwise Notes: The array drive[] must be large enough to receive all the drive levels ?if the exact number of stages is not known, call VsGetNstages() first, or allocate enough array elements (12) to accommodate the largest filter design.VSDRVR_API Int32 VsGetNstages( VS_HANDLE vsHnd, Int32 *pStages ) Arguments: vsHnd handle value returned by VsOpen() pStages pointer to int that will receive the number of stages in the filter Purpose: this function determines the number of optical stages in the filter and returns it in *pStages, which may not be NULL. Returns: TRUE if successful, FALSE otherwise Notes: noneVSDRVR_API Int32 VsGetPendingReply( VS_HANDLE vsHnd, LPSTR reply, Int32 nChars, Int32 *pQuit, Int32 firstMs, Int32 subsequentMs ) Arguments: vsHnd handle value returned by VsOpen() reply pointer to buffer that is to receive the reply nChars number of characters to receive pQuit pointer to flag to control this function ?see Notes below firstMs maximum time to wait, in ms, for first character of reply subsequentMs maximum time to wait, in ms, for each subsequent character Purpose: this function is used to exploit some of the less-common aspects of the filter, and it is likely that most programs will require its use. It receives a reply from the filter that may not arrive for a long time. The routine waits up to firstMs for the first character to arrive. Subsequent characters must arrive within subsequentMs of one another. Typically, this routine is called with a high value for firstMs and a lower value for subsequentMs. Returns: TRUE if successful, FALSE otherwise Notes: pQuit can be used to cancel this function while it is waiting for the reply, if that is desired, such as to respond to a user cancellation request. To use this feature, pQuit must be non-NULL and *pQuit must be FALSE at the time VsGetPendingReply() is called. VsGetPendingReply() checks this address periodically, and if it discovers that *pQuit is TRUE, it will cancel and return immediately.VSDRVR_API Int32 VsGetReply( VS_HANDLE vsHnd, LPSTR reply, Int32 nChars, Int32 waitMs ) Arguments: vsHnd handle value returned by VsOpen() reply pointer to buffer that will receive the filter reply nChars the number of characters sought waitMs the maximum time, in ms, to wait for the reply Purpose: this function is used to exploit those filter commands that are not directly provided by other functions, and most programmers will not need to use it. If the reply is not received in the time indicated by waitMs, or if less than nChars are received, the function returns with an unsuccessful status code. Returns: TRUE if successful, FALSE otherwise Notes: noneVSDRVR_API Int32 VsIsDiagnostic( VS_HANDLE vsHnd ) Arguments: vsHnd handle value returned by VsOpen() Function: determines whether the filter is in the diagnostic mode that is used at the factory for setup and calibration. This command is reserved for CRI use only. Returns: TRUE if diagnostic, FALSE otherwise. VSDRVR_API Int32 VsIsEngagedInBeam( VS_HANDLE vsHnd ) Arguments: vsHnd handle value returned by VsOpen() Function: determines whether the filter is engaged in the beam, when configured into certain CRI systems. This function is reserved for CRI use only Returns: TRUE if engaged in the beam, FALSE otherwise VSDRVR_API Int32 VsSendBinary( VS_HANDLE vsHnd, char *bin, Int32 nChars, BOOL clearEcho ) Arguments: vsHnd handle value returned by VsOpen() bin pointer a buffer that contains binary data to be sent to the filter nChars the number of binary characters to be sent clearEcho flag indicating whether to clear echo characters from the queue Purpose: this routine sends binary blocks of data to the filter. This is only necessary when programming calibration data to the filter, and it is not anticipated that this function will be necessary in any normal use. Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsSendCommand( VS_HANDLE vsHnd, LPCSTR cmd, BOOL sendEolChar) Arguments: vsHnd handle value returned by VsOpen() cmd pointer to the command to be sent to the filter sendEolChar flag indicating whether to append the end-of-line character or not Purpose: this function sends the command in cmd to the filter, and appends an end-of-line terminator (or not) based on sendEolChar. It automatically retrieves and discards the character echo of this command by the VariSpec. It does not automatically retrieve the reply, if any, from the VariSpec. Returns: TRUE if successful, FALSE otherwise Notes: The parameter sendEolChar should normally be true in all cases, unless one is sending individual character commands such as the ??or 慇?commands described in the VariSpec user抯 manual.VSDRVR_API Int32 VsSetStageDrive( VS_HANDLE vsHnd, Int32 stage, Int32 drive ) Arguments: vsHnd handle value returned by VsOpen() stage stage number whose drive level is to be adjusted drive drive level, in counts, for that stage Purpose: this function provides a way to manually adjust the drive levels at each of the filter抯 optical stages. It is normally used only during manufacture, and is not a function that most software programs will have any reason to use. Returns: TRUE if successful, FALSE otherwise Notes: none VSDRVR_API Int32 VsThermistorCounts( VS_HANDLE vsHnd, Int32 *pCounts ) Arguments: vsHnd handle value returned by VsOpen() pCounts pointer to int that will receive the thermistor signal, in counts Purpose: this function provides a way to determine the signal level, in counts, at the thermistor. It is normally used only during manufacture, and is not a function that most software programs will have any reason to use. Returns: TRUE if successful, FALSE otherwise Notes: none
回答: "Syntax error, insert ";" to complete" 这个错误提示通常表示在代码中缺少了分号。这可能是由于以下几种情况导致的:\[1\] 1. 可能是在代码的某一行末尾忘记了加上分号。请检查你的代码,确保每一行的末尾都有正确的分号。 2. 可能是在代码块的末尾缺少了一个闭合的大括号。请检查你的代码,确保每一个代码块都有正确的大括号配对。 3. 可能是在条件语句或循环语句中,忘记了在语句的末尾加上分号。请检查你的代码,确保在条件语句和循环语句中的每一个语句末尾都有正确的分号。 如果你确定以上情况都没有出现,那么可能是其他语法错误导致的。你可以仔细检查你的代码,确保没有其他的语法错误。另外,你也可以尝试使用调试工具来定位错误的位置。 总结起来,"Syntax error, insert ";" to complete" 错误通常是由于缺少分号或其他语法错误导致的。请仔细检查你的代码,确保每一行的末尾都有正确的分号,并排除其他可能的语法错误。 #### 引用[.reference_title] - *1* [【龙头鱼的解惑】Syntax error, insert “}“ to complete ClassBody](https://blog.csdn.net/qq_45726293/article/details/112549510)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值