URL functions and classes

一个中科大差生的8年程序员工作总结 今年终于从大菊花厂离职了,离职前收入大概60w不到吧,在某乎属于比较差的,今天终于有空写一下自己的职场故事,也算是给自己近8年的程序员工作做个总结复盘。近8年有些事情做对了,也有更多事情做错了,在这里记录一下,希望能够给后人一些帮助吧,也欢迎私信交流。文笔不好,见谅,有些细节记不清了,如果有出入,就当是我编的这个故事吧。 PS:有几个问题先在这里解释一下,评论就不一一回复了 1、关于差生,我本人在科大时确实成绩偏下,差生主要讲这一点,没其他意思。 2、因为买房是我人生中的大事,我认为需要记录和总结一下 阅读详情
$INCLUDE ../cDefines.inc}
unit cURL;

{                                                                              }
{                              URL Utilities 3.07                              }
{                                                                              }
{             This unit is copyright ?2000-2004 by David J Butler             }
{                                                                              }
{                  This unit is part of Delphi Fundamentals.                   }
{                     Its original file name is cURL.pas                       }
{       The latest version is available from the Fundamentals home page        }
{                     http://fundementals.sourceforge.net/                     }
{                                                                              }
{                I invite you to use this unit, free of charge.                }
{        I invite you to distibute this unit, but it must be for free.         }
{             I also invite you to contribute to its development,              }
{             but do not distribute a modified copy of this file.              }
{                                                                              }
{          A forum is available on SourceForge for general discussion          }
{             http://sourceforge.net/forum/forum.php?forum_id=2117             }
{                                                                              }
{ Revision history:                                                            }
{   17/10/2000  1.01  Unit cInternetStandards.                                 }
{   22/12/2001  1.02  Unit cMIME.                                              }
{   12/12/2002  3.03  Unit cInternetUtils.                                     }
{   21/02/2004  3.04  Added URL protocol base class.                           }
{   22/02/2004  3.05  Added URL File Protocol implementation class.            }
{   05/03/2004  3.06  Unit cURL.                                               }
{   12/03/2004  3.07  Added asynchronous URL content functions.                }
{                                                                              }

interface

uses
  { Delphi }
  SysUtils,

  { Fundamentals }
  cReaders,
  cThreads;



{                                                                              }
{ URL protocol                                                                 }
{   URL protocol implementations must use AURLProtocol as their base class.    }
{   URL protocol implementations must call RegisterURLProtocol to register     }
{   the implementation object.                                                 }
{                                                                              }
type
  AURLProtocol = class
  public
    { URL }
    function  DecodeURL(const URL: String; var Protocol, Host, Path: String): Boolean; virtual;

    { Content }
    function  IsContentSupported(const Protocol, Host, Path: String): Boolean; virtual;
    function  GetContentReader(const Protocol, Host, Path: String;
              var ContentType: String): AReaderEx; virtual;
    function  GetContentString(const Protocol, Host, Path: String;
              var Content, ContentType: String): Boolean; virtual;
  end;
  EURLProtocol = class(Exception);

procedure RegisterURLProtocol(const Handler: AURLProtocol);



{                                                                              }
{ URL string                                                                   }
{                                                                              }
const
  protoHTTP   = 'http';
  protoNNTP   = 'news';
  protoFTP    = 'ftp';
  protoGopher = 'gopher';
  protoEMail  = 'mailto';
  protoHTTPS  = 'https';
  protoIRC    = 'irc';
  protoFile   = 'file';
  protoTelnet = 'telnet';

procedure DecodeURL(const URL: String; var Protocol, Host, Path: String);
function  EncodeURL(const Protocol, Host, Path: String): String;



{                                                                              }
{ URL content (blocking functions)                                             }
{                                                                              }
function  GetURLProtocolContentReader(const Protocol, Host, Path: String;
          var ContentType: String): AReaderEx;
function  GetURLProtocolContentString(const Protocol, Host, Path: String;
          var Content, ContentType: String): Boolean;

function  GetURLContentReader(const URL: String;
          var ContentType: String): AReaderEx;
function  GetURLContentString(const URL: String;
          var Content, ContentType: String): Boolean;

function  RequireURLProtocolContentReader(const Protocol, Host, Path: String;
          var ContentType: String): AReaderEx;
function  RequireURLProtocolContentString(const Protocol, Host, Path: String;
          var ContentType: String): String;

function  RequireURLContentReader(const URL: String; var ContentType: String): AReaderEx;
function  RequireURLContentString(const URL: String; var ContentType: String): String;



{                                                                              }
{ URL content (asynchronous functions)                                         }
{   Call GetURLContentAsync to retrieve URL content asynchronously.            }
{   Caller must free the returned TURLContentAsync object.                     }
{                                                                              }
type
  TURLContentAsync = class;
  TURLContentNotifyEvent = procedure (const URLContent: TURLContentAsync;
      const Data: Pointer) of object;
  TURLContentProgressEvent = procedure (const URLContent: TURLContentAsync;
      const Data: Pointer; const Buffer; const Size: Integer;
      var Abort: Boolean) of object;
  TURLContentMode = (
      ucGetContentString,        // Return content in ContentString property
      ucSaveContentFile,         // Save content to ContentFileName
      ucNotifyContentBlocks);    // Call OnProgress with content blocks
  TURLContentAsync = class(TThreadEx)
  private
    FProtocol        : String;
    FHost            : String;
    FPath            : String;
    FContentMode     : TURLContentMode;
    FContentFileName : String;
    FData            : Pointer;
    FOnProgress      : TURLContentProgressEvent;
    FOnFinished      : TURLContentNotifyEvent;
    FFinished        : Boolean;
    FSuccess         : Boolean;
    FErrorMessage    : String;
    FContentSize     : Integer;
    FContentProgress : Integer;
    FContentType     : String;
    FContentString   : String;

  protected
    procedure TriggerProgress(const Buffer; const Size: Integer;
              var Abort: Boolean); virtual;
    procedure TriggerFinished; virtual;
   
    procedure Execute; override;

  public
    constructor Create(
                const Protocol, Host, Path: String;
                const ContentMode: TURLContentMode = ucGetContentString;
                const ContentFileName: String = '';
                const Data: Pointer = nil;
                const OnProgress: TURLContentProgressEvent = nil;
                const OnFinished: TURLContentNotifyEvent = nil);

    property  Protocol: String read FProtocol;
    property  Host: String read FHost;
    property  Path: String read FPath;
    property  ContentMode: TURLContentMode read FContentMode;
    property  ContentFileName: String read FContentFileName;
    property  Data: Pointer read FData;

    property  Finished: Boolean read FFinished;
    property  Success: Boolean read FSuccess;
    property  ErrorMessage: String read FErrorMessage;

    property  ContentSize: Integer read FContentSize;
    property  ContentProgress: Integer read FContentProgress;
    property  ContentType: String read FContentType;
    property  ContentString: String read FContentString;
  end;

function  GetURLProtocolContentAsync(
          const Protocol, Host, Path: String;
          const ContentMode: TURLContentMode = ucGetContentString;
          const ContentFileName: String = '';
          const Data: Pointer = nil;
          const OnProgress: TURLContentProgressEvent = nil;
          const OnFinished: TURLContentNotifyEvent = nil): TURLContentAsync;
function  GetURLContentAsync(
          const URL: String;
          const ContentMode: TURLContentMode = ucGetContentString;
          const ContentFileName: String = '';
          const Data: Pointer = nil;
          const OnProgress: TURLContentProgressEvent = nil;
          const OnFinished: TURLContentNotifyEvent = nil): TURLContentAsync;



{                                                                              }
{ URL file protocol                                                            }
{                                                                              }
type
  TURLFileProtocol = class(AURLProtocol)
  public
    function  IsContentSupported(const Protocol, Host, Path: String): Boolean; override;
    function  GetContentReader(const Protocol, Host, Path: String;
              var ContentType: String): AReaderEx; override;
    function  GetContentString(const Protocol, Host, Path: String;
              var Content, ContentType: String): Boolean; override;
  end;

procedure RegisterURLFileProtocol;



{                                                                              }
{ Self-testing code                                                            }
{                                                                              }
procedure SelfTest;



implementation

uses
  { Fundamentals }
  cUtils,
  cStrings,
  cWriters,
  cStreams,
  cFileUtils,
  cInternetUtils;



{                                                                              }
{ AURLProtocol                                                                 }
{                                                                              }
function AURLProtocol.DecodeURL(const URL: String; var Protocol, Host, Path: String): Boolean;
begin
  Protocol := '';
  Host := '';
  Path := '';
  Result := False;
end;

function AURLProtocol.IsContentSupported(const Protocol, Host, Path: String): Boolean;
begin
  Result := False;
end;

function AURLProtocol.GetContentReader(const Protocol, Host, Path: String;
    var ContentType: String): AReaderEx;
begin
  ContentType := '';
  Result := nil;
end;

function AURLProtocol.GetContentString(const Protocol, Host, Path: String;
    var Content, ContentType: String): Boolean;
begin
  Content := '';
  ContentType := '';
  Result := False;
end;



{                                                                              }
{ URL Protocol implementations                                                 }
{                                                                              }
var
  URLProtocols : Array of AURLProtocol = nil;

procedure RegisterURLProtocol(const Handler: AURLProtocol);
begin
  if not Assigned(Handler) then
    raise EURLProtocol.Create('URL protocol handler required');
  Append(ObjectArray(URLProtocols), Handler);
end;



{                                                                              }
{ URL string                                                                   }
{                                                                              }
function urlDecodeHTTP(const S: String; var Protocol, Host, Path: String): Boolean;
var I, J: Integer;
begin
  Protocol := '';
  Host := '';
  Path := '';
  if StrMatchLeft(S, 'http:', False) then
    Protocol := protoHTTP else
  if StrMatchLeft(S, 'https:', False) then
    Protocol := protoHTTPS;
  Result := Protocol <> '';
  if not Result then
    exit;
  I := PosChar(':', S);
  Assert(I > 0, 'I > 0');
  if StrMatch(S, '//', I + 1) then
    Inc(I, 2);
  J := PosChar('/', S, I + 1);
  if J = 0 then
    Host := CopyFrom(S, I + 1) else
    begin
      Host := CopyRange(S, I + 1, J - 1);
      Path := CopyFrom(S, J);
    end;
end;

function urlDecodeEMail(const S: String; var Protocol, Host, Path: String): Boolean;
begin
  Protocol := '';
  Host := '';
  Path := '';
  if StrMatchLeft(S, 'mailto:', False) then
    begin
      Protocol := protoEMail;
      Host := CopyFrom(S, 8);
    end else
  if (PosChar([':', '/', '/'], S) = 0) and
     (PosChar('@', S) > 1) then
    begin
      Protocol := protoEMail;
      Host := S;
    end;
  Result := Protocol <> '';
  if not Result then
    exit;
  TrimInPlace(Host, SPACE);
end;

function urlDecodeFile(const S: String; var Protocol, Host, Path: String): Boolean;
begin
  Protocol := '';
  Host := '';
  Path := '';
  if S <> '' then
    if StrMatchLeft(S, 'file:', False) then
      begin
        Protocol := protoFile;
        Path := CopyFrom(S, 6);
      end else
    if (PChar(S)^ = '/') or
       (PathHasDriveLetter(S) and StrMatch(S, '/', 3))  then
      begin
        Protocol := protoFile;
        Path := S;
      end;
  Result := Protocol <> '';
end;

function urlDecodeKnownProtocol(const S: String; var Protocol, Host, Path: String): Boolean;
begin
  Result := urlDecodeHTTP(S, Protocol, Host, Path);
  if Result then
    exit;
  Result := urlDecodeEMail(S, Protocol, Host, Path);
  if Result then
    exit;
  Result := urlDecodeFile(S, Protocol, Host, Path);
  if Result then
    exit;
end;

function urlDecodePath(const S: String; var Protocol, Host, Path: String): Boolean;
var I: Integer;
begin
  Protocol := '';
  Host := '';
  Path := '';
  Result := False;
  // special cases
  if (S = '') or (S = '*') or (S = '/') then
    begin
      Path := S;
      Result := True;
    end else
  // relative path
  if StrMatchLeft(S, '../') or StrMatchLeft(S, './') then
    begin
      Path := S;
      Result := True;
    end else
  // "/" prefix
  if PChar(S)^ = '/' then
    begin
      if StrMatchLeft(S, '//') then
        begin
          // "//"host["/"path]
          I := PosChar('/', S, 3);
          if I = 0 then
            // "//"host
            Host := CopyFrom(S, 3) else
            begin
              // "//"host"/"path
              Host := CopyRange(S, 3, I - 1);
              Path := CopyFrom(S, I);
            end;
        end else
        // "/"path
        Path := S;
      Result := True;
    end;
end;

procedure urlDecodeGeneral(const S: String; var Protocol, Host, Path: String);
var I, J : Integer;
    T    : String;
begin
  Protocol := '';
  Host := '';
  Path := '';
  I := PosStr('://', S);
  J := PosChar('/', S);
  if (I > 0) and (J = I + 1) then
    begin
      // protocol"://"
      Protocol := Trim(CopyLeft(S, I - 1), SPACE);
      J := PosChar('/', S, I + 3);
      if J = 0 then
        begin
          Host := Trim(CopyFrom(S, I + 3), SPACE);
          Path := '';
        end else
        begin
          Host := Trim(CopyRange(S, I + 3, J - 1), SPACE);
          Path := Trim(CopyFrom(S, J), SPACE);
        end;
      exit;
    end;
  I := PosChar(':', S);
  if (I = 0) or ((I > 0) and (J > 0) and (J < I)) then
    begin
      // no protocol
      Path := S;
      exit;
    end;
  // check text between ":" and "/"
  if J > 0 then
    T := CopyRange(S, I + 1, J - 1) else
    T := CopyFrom(S, I + 1);
  if StrIsNumeric(T) then
    begin
      // address":"port/path
      if J = 0 then
        Host := S else
        begin
          Host := CopyLeft(S, J - 1);
          Path := CopyFrom(S, J);
        end;
      exit;
    end;
  // protocol":"host"/"path
  Protocol := Trim(CopyLeft(S, I - 1), SPACE);
  if J = 0 then
    Host := CopyFrom(S, I + 1) else
    begin
      Host := CopyRange(S, I + 1, J - 1);
      Path := CopyFrom(S, J);
    end;
end;

procedure DecodeURL(const URL: String; var Protocol, Host, Path: String);
const KnownProtocols = 3;
      KnownProtocol: Array [1..KnownProtocols] of String = (protoEMail,
                    protoNNTP, protoFile);
var S : String;
    I : Integer;
begin
  Protocol := '';
  Host := '';
  Path := '';
  // clean URL
  S := Trim(URL, SPACE);
  if S = '' then
    exit;
  // check if url is a path only
  if urlDecodePath(S, Protocol, Host, Path) then
    exit;
  // check url protocol handlers
  For I := 0 to Length(URLProtocols) - 1 do
    if URLProtocols[I].DecodeURL(URL, Protocol, Host, Path) then
      exit;
  // check known protocol
  if urlDecodeKnownProtocol(S, Protocol, Host, Path) then
    exit;
  // check general format
  urlDecodeGeneral(S, Protocol, Host, Path);
end;

function EncodeURL(const Protocol, Host, Path: String): String;
begin
  Result := '';
  if Protocol <> '' then
    if StrEqualNoCase(protoHTTP, Protocol) or
       StrEqualNoCase(protoHTTPS, Protocol) then
      Result := Protocol + '://' else
      Result := Protocol + ':';
  Result := Result + Host;
  if Path <> '' then
    if not (Path [1] in [':', '/', '/', '@', ',']) then
      Result := Result + '/' + Path else
      Result := Result + Path;
end;



{                                                                              }
{ URL content (blocking functions)                                             }
{                                                                              }
function GetURLProtocolContentReader(const Protocol, Host, Path: String;
    var ContentType: String): AReaderEx;
var I : Integer;
    P : AURLProtocol;
    S : String;
begin
  For I := 0 to Length(URLProtocols) - 1 do
    begin
      P := URLProtocols[I];
      if P.IsContentSupported(Protocol, Host, Path) then
        begin
          Result := P.GetContentReader(Protocol, Host, Path, ContentType);
          if Assigned(Result) then
            exit;
          if P.GetContentString(Protocol, Host, Path, S, ContentType) then
            begin
              Result := TStringReader.Create(S);
              exit;
            end;
        end;
    end;
  ContentType := '';
  Result := nil;
end;

function GetURLProtocolContentString(const Protocol, Host, Path: String;
    var Content, ContentType: String): Boolean;
var I : Integer;
    P : AURLProtocol;
    R : AReaderEx;
begin
  For I := 0 to Length(URLProtocols) - 1 do
    begin
      P := URLProtocols[I];
      if P.IsContentSupported(Protocol, Host, Path) then
        begin
          Result := P.GetContentString(Protocol, Host, Path, Content, ContentType);
          if Result then
            exit;
          R := P.GetContentReader(Protocol, Host, Path, ContentType);
          if Assigned(R) then
            begin
              try
                Content := R.GetToEOF;
              finally
                R.Free;
              end;
              Result := True;
              exit;
            end;
        end;
    end;
  Content := '';
  ContentType := '';
  Result := False;
end;

function GetURLContentReader(const URL: String; var ContentType: String): AReaderEx;
var Protocol, Host, Path : String;
begin
  if URL = '' then
    raise EURLProtocol.Create('URL required');
  DecodeURL(URL, Protocol, Host, Path);
  Result := GetURLProtocolContentReader(Protocol, Host, Path, ContentType);
end;

function GetURLContentString(const URL: String;
    var Content, ContentType: String): Boolean;
var Protocol, Host, Path : String;
begin
  if URL = '' then
    raise EURLProtocol.Create('URL required');
  DecodeURL(URL, Protocol, Host, Path);
  Result := GetURLProtocolContentString(Protocol, Host, Path, Content, ContentType);
end;

function RequireURLProtocolContentReader(const Protocol, Host, Path: String;
    var ContentType: String): AReaderEx;
begin
  Result := GetURLProtocolContentReader(Protocol, Host, Path, ContentType);
  if not Assigned(Result) then
    raise EURLProtocol.Create('URL not supported');
end;

function RequireURLProtocolContentString(const Protocol, Host, Path: String;
    var ContentType: String): String;
begin
  if not GetURLProtocolContentString(Protocol, Host, Path, Result, ContentType) then
    raise EURLProtocol.Create('URL not supported');
end;

function RequireURLContentReader(const URL: String; var ContentType: String): AReaderEx;
begin
  Result := GetURLContentReader(URL, ContentType);
  if not Assigned(Result) then
    raise EURLProtocol.Create('URL not supported');
end;

function RequireURLContentString(const URL: String; var ContentType: String): String;
begin
  if not GetURLContentString(URL, Result, ContentType) then
    raise EURLProtocol.Create('URL not supported');
end;



{                                                                              }
{ URL content (asynchronous functions)                                         }
{                                                                              }
const
  ProgressBlockSize = 4096;

constructor TURLContentAsync.Create(
    const Protocol, Host, Path: String;
    const ContentMode: TURLContentMode;
    const ContentFileName: String;
    const Data: Pointer;
    const OnProgress: TURLContentProgressEvent;
    const OnFinished: TURLContentNotifyEvent);
begin
  FProtocol := Protocol;
  FHost := Host;
  FPath := Path;
  FContentMode := ContentMode;
  FContentFileName := ContentFileName;
  FData := Data;
  FOnProgress := OnProgress;
  FOnFinished := OnFinished;
  FreeOnTerminate := False;
  inherited Create(False);
end;

procedure TURLContentAsync.TriggerProgress(const Buffer; const Size: Integer;
    var Abort: Boolean);
begin
  if Assigned(FOnProgress) then
    FOnProgress(self, FData, Buffer, Size, Abort);
end;

procedure TURLContentAsync.TriggerFinished;
begin
  if Assigned(FOnFinished) then
    FOnFinished(self, FData);
end;

procedure TURLContentAsync.Execute;
var Reader : AReaderEx;
    Writer : TFileWriter;
    Buf    : Array[0..ProgressBlockSize - 1] of Byte;
    I      : Integer;
    A      : Boolean;
begin
  FErrorMessage := '';
  try try
    if FContentMode = ucGetContentString then
      begin
        FContentString := RequireURLProtocolContentString(FProtocol, FHost, FPath, FContentType);
        FContentSize := Length(FContentString);
        FSuccess := True;
      end else
    if FContentMode in [ucNotifyContentBlocks, ucSaveContentFile] then
      begin
        Reader := RequireURLProtocolContentReader(FProtocol, FHost, FPath, FContentType);
        try
          FContentSize := Reader.Size;
          if FContentMode = ucSaveContentFile then
            begin
              if FContentFileName = '' then
                raise EURLProtocol.Create('Filename required');
              Writer := TFileWriter.Create(FContentFileName, fwomCreate)
            end
          else
            Writer := nil;
          try
            A := False;
            While not Reader.EOF and not Terminated do
              begin
                I := Reader.Read(Buf[0], ProgressBlockSize);
                if (I = 0) and not Reader.EOF then
                  raise EURLProtocol.Create('Read error');
                Inc(FContentProgress, I);
                if Terminated then
                  exit;
                TriggerProgress(Buf[0], I, A);
                if A then
                  raise EURLProtocol.Create('Aborted');
                if Assigned(Writer) then
                  Writer.WriteBuffer(Buf[0], I);
              end;
          finally
            Writer.Free;
          end;
        finally
          Reader.Free;
        end;
        FContentSize := FContentProgress;
        FSuccess := True;
      end;
  except
    on E : Exception do
      FErrorMessage := E.Message;
  end;
  finally
    FFinished := True;
    TriggerFinished;
  end;
end;

function GetURLProtocolContentAsync(const Protocol, Host, Path: String;
    const ContentMode: TURLContentMode;
    const ContentFileName: String;
    const Data: Pointer;
    const OnProgress: TURLContentProgressEvent;
    const OnFinished: TURLContentNotifyEvent): TURLContentAsync;
begin
  Result := TURLContentAsync.Create(Protocol, Host, Path,
      ContentMode, ContentFileName, Data, OnProgress, OnFinished);
end;

function GetURLContentAsync(
    const URL: String;
    const ContentMode: TURLContentMode;
    const ContentFileName: String;
    const Data: Pointer;
    const OnProgress: TURLContentProgressEvent;
    const OnFinished: TURLContentNotifyEvent): TURLContentAsync;
var Protocol, Host, Path : String;
begin
  DecodeURL(URL, Protocol, Host, Path);
  Result := GetURLProtocolContentAsync(Protocol, Host, Path,
      ContentMode, ContentFileName, Data, OnProgress, OnFinished);
end;



{                                                                              }
{ URL File Protocol                                                            }
{                                                                              }
function TURLFileProtocol.IsContentSupported(const Protocol, Host, Path: String): Boolean;
begin
  Result := StrEqualNoCase(Protocol, protoFile) and (Host = '') and (Path <> '');
end;

function TURLFileProtocol.GetContentReader(const Protocol, Host, Path: String;
    var ContentType: String): AReaderEx;
begin
  ContentType := MIMEContentTypeFromExtention(ExtractFileExt(Path));
  Result := TFileReader.Create(Path);
end;

function TURLFileProtocol.GetContentString(const Protocol, Host, Path: String;
    var Content, ContentType: String): Boolean;
begin
  Content := ReadFileToStr(Path);
  ContentType := MIMEContentTypeFromExtention(ExtractFileExt(Path));
  Result := True;
end;

var
  URLFileProtocol : AURLProtocol = nil;

procedure RegisterURLFileProtocol;
begin
  if Assigned(URLFileProtocol) then
    exit;
  URLFileProtocol := TURLFileProtocol.Create;
  RegisterURLProtocol(URLFileProtocol);
end;



{                                                                              }
{ Self-testing code                                                            }
{                                                                              }
{$ASSERTIONS ON}
procedure SelfTest;
var P, M, U : String;
begin
  { DecodeURL                                                                  }
  DecodeURL('http://abc.com/index.html', P, M, U);
  Assert((P = protoHTTP) and (M = 'abc.com') and (U = '/index.html'), 'DecodeURL');
  DecodeURL('a://b.c/1/2/3', P, M, U);
  Assert((P = 'a') and (M = 'b.c') and (U = '/1/2/3'), 'DecodeURL');
  DecodeURL('http://b:80/i.html', P, M, U);
  Assert((P = protoHTTP) and (M = 'b:80') and (U = '/i.html'), 'DecodeURL');
  DecodeURL('mailto:a@b', P, M, U);
  Assert((P = protoEMail) and (M = 'a@b') and (U = ''), 'DecodeURL');

  { EncodeURL                                                                  }
  Assert(EncodeURL('http', 'abc.com', '/') = 'http://abc.com/', 'EncodeURL');
  Assert(EncodeURL('news', 'a.b', '') = 'news:a.b', 'EncodeURL');
  Assert(EncodeURL('https', 'abc.com', '/') = 'https://abc.com/', 'EncodeURL');
end;



initialization
finalization
  FreeAndNil(URLFileProtocol);
end.


Jetson AGX Orin平台Jetpack5升级Jetpack6,自研载板USB不工作问题调试 1. 问题描述将AGX Orin工业的新板放到定制的载板上当在ubuntu 22和Jetpack 6.1上使用SDKManager刷机时,lsusb为空,并且在引导时没有发现/注册xusb设备。USB C端口正常打开并供电,但似乎没有数据传输。在Ubuntu 18 Jetpack 5.1.4 SDKManager上同样刷机之后,usb C集线器在引导时被正确地发现,显示在lsusb中,并识别/挂载外部驱动器。 阅读详情

相关推荐

保姆级教程:在RV1126开发板上跑通YOLOv5口罩检测(从数据集到摄像头实时识别)

本文提供了一份详细的RV1126开发板部署YOLOv5口罩检测系统的全流程指南,涵盖数据集准备、模型训练优化、边缘部署及实时摄像头识别等关键步骤。重点解析了RV1126开发板的性能特征、YOLOv5模型训练调优技巧、RKNN模型转换量化策略,以及部署过程中的性能优化方案,帮助开发者高效实现边缘端目标检测应用。

weixin_27310985的博客 108

Delphi使用IdHttp 获取 HttpsURL内容

uses IdHTTP, IdSSLOpenSSL; function HttpsGet(const aURL, aContentFile: string): Boolean; var vIdHTTP: TIdHTTP; vSSL: TIdSSLIOHandlerSocket; vMemory: TMemoryStream; begin try vIdHTTP := TI

七级风科技 8988

【数据清洗】数据清洗流程及经验

预处理阶段 预处理阶段主要做两件事情: 一是将数据导入处理工具。 二是看数据。包含两个部分:一是看元数据,包括字段解释、数据来源、代码表等等一切描述数据的信息;二是抽取一部分数据,对数据本身有一个直观的了解,并且初步发现一些问题,为之后的处理做准备。 第一步:缺失值清洗 四个步骤: 1、确定缺失值范围:对每个字段都计算其缺失值比例,然后按照缺失比例和字段重要性,分别制定策略。 2、去除不需要的...

JoJo93723的博客 6493

delphi httpserver 使用方法

unit main; interface uses   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,   Dialogs, IdBaseComponent,IdContext ,IdComponent, IdCustomTCPServer, IdC

云中雁012345之成长 1万+

智能车图像处理去畸变+逆透视教程

图像处理,去畸变与逆透视整合

wu58430的博客 1万+

CSP-J 初赛模拟卷1 题解

只有一棵子树有后继,其他的都是叶结点才能保证树的深度最大,此时还剩(n-5)个结点,最后加上2,得到(n-3),即为答案。题解:先修改p的指针域,让它的左指针域指向q,然后再让q的右指针域赋值给p的右指针域,再然后修改q的右指针域使其指向p,最后需要改变的指针域就是原先q结点的后继节点的左指针域内容。设n个元素的入栈序列是1,2,3,...,n,出栈序列为p1,p2,...,pn,若p1=n,则pi(1≤i≤n)的值为(1)输入的三个数中,第二个数应是[0,11]上的整数,否则会出现数组越界的问题。

Sat77GryHp_Pro的博客 2805

Mac OS 下 mysql 找不到 mysql.sock 的问题

mysql.sock 无法找到一般存在两种问题,一是mysql服务未启动,mysql.sock没有生成,二是mysql.sock的指向位置出错,在指向位置加个mysql.sock的软链接就可以解决。 mac下可以通过下方的命令启动mysql sudo /usr/local/mysql/support-files/mysql.server start 转载于:https://www...

weixin_34378969的博客 1979

Python画常见分布的概率密度图

因为做概随大作业,了解了一些python画概率分布图的方法。

qq_44807946的博客 5204

mac mysql.sock_Mac OS 下 mysql 找不到 mysql.sock 的解决过程

mysql.sock 无法找到一般存在两种问题,一是mysql服务未启动,mysql.sock没有生成,二是mysql.sock的指向位置出错,在指向位置加个mysql.sock的软链接就可以解决。我这里遇到的情况是第一种,mysql服务无法正常启动。执行 /usr/local/mysql/bin/mysqld start 无法启动mysql 并出现如下提示0 [Warning] TIMESTAM...

weixin_35690449的博客 1058

Fiddler Everywhere保姆级教程:10分钟搞定手机HTTPS抓包(附证书配置避坑指南)

本文提供Fiddler Everywhere移动端HTTPS抓包的保姆级教程,涵盖环境配置、代理设置、证书安装及常见问题排查。重点解析如何正确安装并信任Fiddler根证书以解密HTTPS流量,帮助开发者快速搭建抓包环境,高效分析应用网络行为,提升调试效率。

git9versioner的博客 704

手把手教你用XC7A35T FPGA搭建低成本机器视觉系统(含开发板选型指南)

本文详细介绍了如何利用AMD(原Xilinx)Artix-7系列中的XC7A35T FPGA芯片,搭建一套低成本的机器视觉系统。内容涵盖从芯片选型深度剖析、开发板(如黑金AX7035B)对比指南,到使用Vivado创建工程、编写图像处理模块(如RGB转灰度),以及资源优化和与上位机(如OpenCV)协同工作的完整流程,旨在为开发者提供一套可实践的高性价比硬件加速视觉解决方案。

beta5的博客 353

mac mysql mysql.socket 位置_Mac os 解决无法使用localhost连接mysql问题

今天在mac上搭建好了php的环境,把先前在window、linux下运行良好的程序放在mac上,居然出现访问不了数据库,数据库连接的host用的是localhost,可以确认数据库配置是正确的,因为在java中使用localhost访问正常,另外通过命令行工具也能正常访问。当把localhost换成127.0.0.1或者本机的IP时,居然正常了。以前一直认为localhost与127.0.0.1...

weixin_39710249的博客 851

六轴机械臂正逆解计算

机械臂运动学就是。包括(Forward Kinematics)和(InverseKinematics)两部分。正运动学就是逆运动学则是关节变量->机械臂末端执行器的姿势=正向运动学机械臂未端执行器的位姿->关节变量=逆向运动学。

gaoxiaochan的博客 1万+

Mac上MySQL出现错误:mysql.sock 错误

刚开始安装MySQL时,是直接使用brew安装的。安装之后直接能够使用,无需配置相关参数。使用一段时间之后,由于导出数据的需要,所以进行了相关配置,但出现了/tmp/mysql.sock error的问题。这里分享我解决此问题的方案。 环境1、MAC OS; 2、MySQL V5.7; 修改配置信息主要是修改/private/etc/my.cnf文件,如果不存在,将安装文件下面support-fil

探索技术世界 4693

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

mysql mac 10.10_Mac OS X 10.10 MySQL 安装总结

一、安装 MySQL 客户端Download MySQL Community Server由于是 Mac 版,因此,下载【Download MySQL Community Server】,下载完成直接安装即可,安装完成后在系统的设置里面会多出一个管理器。设置里面会多出一个管理器注意,该服务器管理器首次安装结束的时候,或弹出一个窗口,其中包含一个默认的 root 用户的随机密码,一定要记住,因为后面...

weixin_35682082的博客 300

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

mac 找不到mysql.sock_Mac OS 下 mysql 找不到 mysql.sock 的问题

Linode Centos6&period;5从零开始装环境&period;&period;&period;流水账安装JDK 下载. 先通过oracle网站, 下载, 得到link后, 在linode命令行里wget, 速度飞快, 但是文件名要改下. 其中JDK6是.bin, 其他都是tar.gz, bin直接执 ...mysql-mysql悲观锁和乐观锁1.mys...

weixin_34336527的博客 485

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Mac Pro下卸载安装Mysql

Mac Pro下卸载安装Mysql系统版本:OS X 10.11.5昨天为了修改我的Mysql密码,找了一堆教程在不明所以的情况下各种乱试,终于把我的mysql玩脱了,走上了曲折的mysql重装之路。一、Mac 关于Mysql的卸载:如使用brew安装:brew uninstall mysql 或者 brew remove mysql但是又有点怕某些东西没有卸载完全影响到下一次的安装(我第一次重装就

Sarahhuangzht的专栏 2万+

如何在Mac OS X中安装MySQL

MBP 自带的系统有有apache ,php,python 但是没有mysql ,于是需要自己倒腾下。‘倒腾’这词用得好,因为我的确倒腾了好久。刚开始用brew search mysql ...能找到,按照提示一步一步安装,结果到最后就是启动不起来,老提示一个sock相关的错误。。后来我还是直接到mysql 的官网下载了适合MAC 平台的mysql-5.5.17-osx10.6-x86_64...

weixin_30752377的博客 106

yosemite mysql 启动,升级Mac OS X Yosemite(Mac OS 10.10)后,Mysql无法启动

Right after upgrading to Mac OS Yosemite (10.10), my Mysql won't start anymore. Instead I getMacBook-Pro:/ user$ sudo /usr/local/mysql/support-files/mysql.server startStarting MySQL. ERROR! The server...

weixin_39862697的博客 149

mac笔记本安装mysql_在MAC OS X上安装MYSQL

我在网上找到了一篇文章,简直堪称神器。刚开始用brew search mysql ...能找到,按照提示一步一步安装,结果到最后就是启动不起来,老提示一个sock相关的错误。。后来我还是直接到mysql 的官网下载了适合MAC 平台的 mysql-5.5.17-osx10.6-x86_64.dmg打开后发现3个文件,安装顺序:1。mysql-5.5.17-osx10.6-x86_64.pkg 数据...

weixin_39569112的博客 94

macbook pro 卸载mysql_Mac Pro下卸载安装Mysql

Mac Pro下卸载安装Mysql 系统版本: OS X 10.11.5 昨天为了修改我的Mysql密码,找了一堆教程在不明所以的情况下各种乱试,终于把我的mysql玩脱了,走上了曲折的mysql重装之路。 一、Mac 关于Mysql的卸载: 如使用brew安装 : brew uninstall mysql 或者 brewMac Pro下卸载安装Mysql系统版本:OS X 10.11.5昨天为了...

weixin_29648175的博客 677

Mac OS 10.10 php不能连接mysql问题解决

php连接数据库都没问题,升级到10.10这后, 突然连接不上了. 这个问题放了很久, 今天突然搜索到一篇文章. 用链接的方式解决了. 原文如下: So you installed Ubuntu, got all excited about developing your Rails application on it, and then… No such file or direc

TerrenceRao 健康,快乐,进取 1132

mac mysql 列表_mac版本的mysql workbench如何可以选中查询结果的一列

满意答案wentaoye2018.04.13采纳率:56%等级:9已帮助:564人首先进入mysql的官方下载页面。http://www.mysql.com/downloads/在页面最下面,我选择的是community edition。点击Community (GPL) Downloads进入下一个页面。1.2这个页面下选择MySQL Community Server,点击DOWNLOA...

weixin_39603357的博客 209

Mac环境下 打开Mysql报错 Can‘t connect to local MySQL server through socket ‘/tmp/mysql.sock‘ (2)

【2020年12月13日记录】之前mac重启之后也出现了相同的问题,后来用brew 更新mysql 之后出现了同样的问题,原因是mysql服务没有打开。 解决方法: 一、首先查找自己mysql的安装地址 1、(参考链接:https://blog.youkuaiyun.com/zhangvalue/article/details/94664944) 【macOS升级11.0.1这个方法不能用了???!!!】 2、直接在mac自带的聚焦搜索里找,搜个mysql.server,然后切换到在访达中搜索,右键找到的文件-&gt

qq_31910395的博客 2064
上一篇: File utility functions v3.02
下一篇: Internet Utilities
SafeF8
博客等级 码龄22年 10粉丝 104原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值