Dart语言参考

Dart语言学习入门过程中的一些记录,仅记录有差异的。可能会跟go等其他语言进行一个对比。 语言基础 运算符 截断除法运算符(truncating division operator) 比如计算 23➗ 7 使用 23/7 使用下面的代码 void main (){ print(23/7); } // 输出 3.2857142857142856 使用~/运算符 void main (){ print(23~/7); } // 输出 3 String 变量值内插 Dart使用下面的方式进行值的内插 void main() { var greeter = "Dart🐟"; print("打印机:$greeter"); } 这一点跟C#有一点相似,C#使用下面的方式: void main() { var greeter = "C#🐟"; print($"打印机:{greeter}"); } Dart中如果变量需要进行值计算,那么跟开始的例子相似。 void main() { var greeter = "Dart🐟"; print("打印机:${greeter.length}"); } 函数 Dart函数不支持重载,但是提供了可选命名参数和可选参数等方式。 可选参数 String Fake(String UserName, [String? carIdentifier]) { if (carIdentifier != null) { return "hello,$UserName,your car is $carIdentifier"; } else { return "hello,$UserName,you don't have car"; } } 必选参数 String Fake({required String UserName, String? carIdentifier}) { if (carIdentifier != null) { return "hello,$UserName,your car is $carIdentifier"; } else { return "hello,$UserName,you don't have car"; } } // 调用时,必须要显式申明参数名称,必须参数也不能设置默认值 // √ var result = Fake(UserName: "czyt", carIdentifier: "川A12134"); // × var result = Fake("czyt", "川A12134"); 默认值 String Fake({ String UserName="czyt", String? carIdentifier}) { if (carIdentifier != null) { return "hello,$UserName,your car is $carIdentifier"; } else { return "hello,$UserName,you don't have car"; } } // 调用:var result = Fake(carIdentifier: "川A12134"); 箭头函数 又称匿名函数,下面两个函数等价 ...

2023-05-21 · 15 分钟 · czyt

使用aws go-sdk访问cloudflare R2文件

准备 需要准备Cloudflare的accountId,相应的R2 ak sk 和bucketName等信息. var ( accountId = "xxxxx" accessKeyId = "cbdade718b2ca877882csssssfcf" accessKeySecret = "04917c7d745422022e266f6b06" bucketName = "gopher" ) 完整代码 package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" "log" ) func main() { var ( accountId = "xxxxx" accessKeyId = "cbdade718b2ca877882csssssfcf" accessKeySecret = "04917c7d745422022e266f6b06" bucketName = "gopher" ) var r2Resolver = aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) { return aws.Endpoint{ URL: fmt.Sprintf("https://%s.r2.cloudflarestorage.com", accountId), }, nil }) cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithEndpointResolverWithOptions(r2Resolver), config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyId, accessKeySecret, "")), ) if err != nil { log.Fatal(err) } client := s3.NewFromConfig(cfg) listObjectsOutput, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{ Bucket: &bucketName, }) if err != nil { log.Fatal(err) } presignClient := s3.NewPresignClient(client) for _, object := range listObjectsOutput.Contents { // 创建文件访问链接 presignResult, err := presignClient.PresignGetObject(context.TODO(), &s3.GetObjectInput{ Bucket: aws.String(bucketName), Key: aws.String(*object.Key), }) if err != nil { panic("Couldn't get presigned URL for PutObject") } fmt.Printf("get URL For object: %s\n", presignResult.URL) } }

2023-05-21 · 1 分钟 · czyt

使用C#连接wifi

需要安装库 Managed Native Wifi 获取Wifi列表 示例代码 private List<AvailableNetworkPack> GetAvaliableNetworks() { var networks = new List<AvailableNetworkPack>(); foreach (var network in NativeWifi.EnumerateAvailableNetworks()) { if (!networks.Contains(network)) { networks.Add(network); } } return networks; } 连接wifi 创建Profile 应该支持这些类型open, WEP and WPA-PSK的网络 private static string CreateSecurityWifiProfile(string ssid, string password) { string hex = CreateHexSSIDName(ssid); return string.Format(@"<?xml version=""1.0""?> <WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1""> <name>{0}</name> <SSIDConfig> <SSID> <hex>{2}</hex> <name>{0}</name> </SSID> </SSIDConfig> <connectionType>ESS</connectionType> <connectionMode>auto</connectionMode> <MSM> <security> <authEncryption> <authentication>WPA2PSK</authentication> <encryption>AES</encryption> <useOneX>false</useOneX> </authEncryption> <sharedKey> <keyType>passPhrase</keyType> <protected>false</protected> <keyMaterial>{1}</keyMaterial> </sharedKey> </security> </MSM> <MacRandomization xmlns=""http://www.microsoft.com/networking/WLAN/profile/v3""> <enableRandomization>false</enableRandomization> </MacRandomization> </WLANProfile>", ssid, password, hex); } private static string CreateOpenWifiProfile(string ssid) { string hex = CreateHexSSIDName(ssid); return string.Format(@"<?xml version=""1.0""?> <WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1""> <name>{0}</name> <SSIDConfig> <SSID> <hex>{1}</hex> <name>{0}</name> </SSID> </SSIDConfig> <connectionType>ESS</connectionType> <connectionMode>auto</connectionMode> <MSM> <security> <authEncryption> <authentication>open</authentication> <encryption>none</encryption> <useOneX>false</useOneX> </authEncryption> </security> </MSM> </WLANProfile>", ssid, hex); } private static string CreateHexSSIDName(string ssid) { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(ssid); return BitConverter.ToString(bytes).Replace("-", ""); } 连接到wifi var networks = GetAvaliableNetworks(); var network = networks.First(n => n.Ssid.ToString() == "gophers"); var profile = NativeWifi.EnumerateProfiles().FirstOrDefault(x => x.Name == "NTSP_CD"); if (profile is null) { var profileXml = CreateProfile("gophers", "gopherspwd"); // create a profile var profileResult = NativeWifi.SetProfile(network.Interface.Id, ProfileType.PerUser, profileXml, "AES", true); } // do connect var wasConnected = NativeWifi.ConnectNetwork(network.Interface.Id, network.Ssid.ToString(), network.BssType); 附录 一些常用的profile配置xml 摘自 项目https://github.com/DigiExam/simplewifi/ ...

2023-04-24 · 4 分钟 · czyt

在树莓派3b上部署minio服务

安装 我的树莓派安装的是manjaro,直接执行如下命令即可 yay -S minio 官方的安装文档开源参考 https://min.io/docs/minio/linux/operations/install-deploy-manage/deploy-minio-single-node-single-drive.html 启用服务 systemctl enable minio 修改配置 主要修改mino的设置文件,文件位置为/etc/minio/minio.conf # Local export path. MINIO_VOLUMES="/srv/minio/data/" # Server user. MINIO_ROOT_USER=gopher # Server password. MINIO_ROOT_PASSWORD=gopher # Use if you want to run Minio on a custom port. MINIO_OPTS="--console-address :8888" MINIO_SERVER_URL="https://minio.xxx.org" MINIO_BROWSER_REDIRECT_URL="https://minio-console.xxx.org" 修改 MINIO_OPTS 主要是为了自定义Console的端口,而这个参数主要是在service定义中使用,安装软件后自动使用的service(路径为/usr/lib/systemd/system/minio.service)定义如下 [Unit] Description=Minio Documentation=https://docs.minio.io Wants=network-online.target After=network-online.target AssertFileIsExecutable=/usr/bin/minio [Service] # Specifies the maximum file descriptor number that can be opened by this process LimitNOFILE=65536 Type=simple User=minio Group=minio EnvironmentFile=/etc/minio/minio.conf ExecStartPre=/bin/bash -c "{ [ -z \"${MINIO_VOLUMES}\" ] && echo \"Variable MINIO_VOLUMES not set in /etc/minio/minio.conf\" && ex> ExecStart=/usr/bin/minio server $MINIO_OPTS $MINIO_VOLUMES Restart=always 启动服务 systemctl start minio ...

2023-04-12 · 1 分钟 · czyt

一些Rust的学习资料

在线教程 concurrency programming via rust https://blog.fudenglong.site/Programming-Rust/ jetbrains出品的rust教程 Rust Book experiment 微软出品:写给.net开发人员的Rust教程 Google Android团队写的Rust教程 通过例子学rust https://cheats.rs/ Rust语言圣经 Brown 大学版本rust程序设计实验版 learn how to write macros in Rust Operating System development tutorials in Rust on the Raspberry Pi Rust语言实战 inside rust std library A Plugin System in Rust https://learning-rust.github.io https://github.com/CleanCut/ultimate_rust_crash_course Writing a JVM in Rust Rust 宏小册 Writing an OS in Rust 清华大学程序设计训练(Rust) Rust 异步编程指南 rust ffi guide Rust基础教程 rCore-Tutorial-Book 第三版 OffensiveRust RustPrimer Rust Atomics and Locks中文版 Rust 程序设计语言 2021版 中文 The Rust on ESP Book中文版 rust 教程资料收集 - fkysly case studies Y分钟速成X=Rust Rust 101 https://teach-rs.tweede.golf/index.html https://www.howtocodeit.com 100个练习题学习Rust 英文版 Rust Design Patterns 中文版 / pdf 学习 wgpu Effective rust 中文版 翻译的仓库 CS110L: Safety in Systems Programming https://www.howtocodeit.com https://speedsheet.io/s/rust https://roadmap.sh/rust Fast Track to Rust gRPC相关 https://blog.logrocket.com/rust-and-grpc-a-complete-guide/ MongoDB https://www.freecodecamp.org/news/mongodb-in-rust/ https://medium.com/geekculture/async-rust-with-tokio-and-mongodb-ae75594c65b8 https://betterprogramming.pub/build-an-api-to-count-github-profile-views-with-rust-actix-and-mongodb-5a6532b6d2eb https://auth0.com/blog/build-an-api-in-rust-with-jwt-authentication-using-nickelrs/ 跨语言调用 https://words.filippo.io/rustgo/ ...

2023-03-28 · 1 分钟 · czyt

我和AI讨论的一些C#话题

很久没有用C#,最近需要使用。下面是跟AI问的一些C#的问题,未作整理。 基础 Span类型 c# Span的应用场景及具体例子 Span是一种新的引用类型,它允许存储和操作连续的内存块。它特别适用于那些需要高效处理内存块的应用场景,例如字符串处理、IO操作和序列化/反序列化。 下面是一些具体的例子: 字符串处理:Span可以用于快速地操作字符串,例如从字符串中截取子串、替换子串、查找子串等。下面是一个例子: string str = "hello world"; Span<char> span = str.AsSpan(6, 5); // 从第6个字符开始,截取长度为5的子串 IO操作:Span可以用于将IO操作映射到内存中,以提高性能。下面是一个例子: using (FileStream stream = File.OpenRead("file.txt")) { byte[] buffer = new byte[1024 * 1024]; while (stream.Read(buffer) > 0) { Span<byte> span = buffer.AsSpan(); // 将字节数组映射为Span // 处理Span } } 序列化/反序列化:Span可以用于快速地序列化和反序列化数据,尤其是在网络传输等场景中。下面是一个例子: public static void Serialize<T>(T value, Span<byte> buffer) where T : struct { unsafe { fixed (byte* ptr = buffer) { *(T*)ptr = value; // 将值拷贝到Span中 } } } public static T Deserialize<T>(Span<byte> buffer) where T : struct { unsafe { fixed (byte* ptr = buffer) { return *(T*)ptr; // 从Span中读取值 } } } 异步 c# SynchronizationContext的使用场景及例子 SynchronizationContext是一个抽象类,定义了一种同步上下文的机制,允许代码在指定的线程中执行。通常情况下,SynchronizationContext的实现会将执行代码的操作封装成一个任务,并将该任务分配到与指定的上下文相关的线程中执行。 SynchronizationContext通常用于以下情况: Windows Forms应用程序中的UI线程处理 在Windows Forms应用程序中,UI线程负责处理用户界面操作。如果其他线程尝试在UI线程之外更新用户界面,则可能会引发异常。这时 ,可以使用WindowsFormsSynchronizationContext类,该类可以将执行代码封装到UI线程上下文中,并在其相关的线程上执行。 例如: textBox1.Invoke(new Action(() => { textBox1.Text = "Hello World"; })); ASP.NET Web应用程序中的请求处理 在ASP.NET Web应用程序中,每个请求都在单独的线程上执行,处理请求时可以使用AspNetSynchronizationContext类将代码封装到请求 线程上下文中,并在其相关的线程上执行。 例如: ...

2023-03-24 · 3 分钟 · czyt

【译】如何使用 http.ResponseController 类型

本文原文地址 https://www.alexedwards.net/blog/how-to-use-the-http-responsecontroller-type ,使用chatGPT翻译 One of my favorite things about the recent Go 1.20 release is the new http.ResponseController type, which brings with it three nice benefits: 关于最近的 Go 1.20 版本,我最喜欢的事情之一是新的 http.ResponseController 类型,它带来了三个好处: You can now override your server-wide read and write deadlines on a per request basis. 您现在可以根据每个请求覆盖服务器范围内的读取和写入截止日期。 The pattern for using the http.Flusher and http.Hijacker interfaces is clearer and feels less hacky. No more type assertions necessary! 使用 http.Flusher 和 http.Hijacker 接口的模式更清晰,感觉更轻松。不再需要类型断言! It makes it easier and safer to create and use custom http.ResponseWriter implementations. 它使创建和使用自定义 http.ResponseWriter 实现变得更容易和更安全。 The first two benefits are mentioned in the release notes, but the third one seems to have gone under the radar a bit… which is a shame, because it’s very helpful! 发行说明中提到了前两个好处,但第三个好处似乎有点不为人知……这很遗憾,因为它非常有帮助! ...

2023-03-09 · 6 分钟 · czyt

golang CGO参考

开源项目 https://github.com/dolthub/go-library-sample https://github.com/draffensperger/go-interlang https://github.com/kbehouse/go_call_cxx_so https://github.com/tailscale/libtailscale https://github.com/iikira/golang-msvc https://github.com/vladimirvivien/go-cshared-examples https://github.com/tailscale/libtailscale/tree/main 文档 Embedding Go in C Calling C code from go C? Go? Cgo! CGO编程(Go语言高级编程) https://stackoverflow.com/questions/14581063/golang-cgo-converting-union-field-to-go-type https://sunzenshen.github.io/tutorials/2015/05/09/cgotchas-intro.html https://totallygamerjet.hashnode.dev/the-smallest-go-binary-5kb 代码片段 Convert ‘C’ array to golang slice func carray2slice(array *C.int, len int) []C.int { var list []C.int sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&list))) sliceHeader.Cap = len sliceHeader.Len = len sliceHeader.Data = uintptr(unsafe.Pointer(array)) return list }

2023-02-03 · 1 分钟 · czyt

命令行的艺术

本文摘自项目 https://github.com/jlevy/the-art-of-command-line 命令行的艺术 熟练使用命令行是一种常常被忽视,或被认为难以掌握的技能,但实际上,它会提高你作为工程师的灵活性以及生产力。本文是一份我在 Linux 上工作时,发现的一些命令行使用技巧的摘要。有些技巧非常基础,而另一些则相当复杂,甚至晦涩难懂。这篇文章并不长,但当你能够熟练掌握这里列出的所有技巧时,你就学会了很多关于命令行的东西了。 这篇文章是许多作者和译者 共同的成果。 这里的部分内容 首次 出现 于 Quora , 但已经迁移到了 GitHub,并由众多高手做出了许多改进。 如果你在本文中发现了错误或者存在可以改善的地方,请贡献你的一份力量 。 前言 涵盖范围: 这篇文章不仅能帮助刚接触命令行的新手,而且对具有经验的人也大有裨益。本文致力于做到覆盖面广(涉及所有重要的内容),具体(给出具体的最常用的例子),以及简洁(避免冗余的内容,或是可以在其他地方轻松查到的细枝末节)。在特定应用场景下,本文的内容属于基本功或者能帮助您节约大量的时间。 本文主要为 Linux 所写,但在仅限 OS X 系统 章节和仅限 Windows 系统 章节中也包含有对应操作系统的内容。除去这两个章节外,其它的内容大部分均可在其他类 Unix 系统或 OS X,甚至 Cygwin 中得到应用。 本文主要关注于交互式 Bash,但也有很多技巧可以应用于其他 shell 和 Bash 脚本当中。 除去“标准的”Unix 命令,本文还包括了一些依赖于特定软件包的命令(前提是它们具有足够的价值)。 注意事项: 为了能在一页内展示尽量多的东西,一些具体的信息可以在引用的页面中找到。我们相信机智的你知道如何使用 Google 或者其他搜索引擎来查阅到更多的详细信息。文中部分命令需要您使用 apt-get,yum,dnf,pacman, pip 或 brew(以及其它合适的包管理器)来安装依赖的程序。 遇到问题的话,请尝试使用 Explainshell 去获取相关命令、参数、管道等内容的解释。 基础 学习 Bash 的基础知识。具体地,在命令行中输入 man bash 并至少全文浏览一遍; 它理解起来很简单并且不冗长。其他的 shell 可能很好用,但 Bash 的功能已经足够强大并且到几乎总是可用的( 如果你只学习 zsh,fish 或其他的 shell 的话,在你自己的设备上会显得很方便,但过度依赖这些功能会给您带来不便,例如当你需要在服务器上工作时)。 ...

2023-02-02 · 9 分钟 · czyt

Golang Web框架Buffalo 简单使用

官方文档 https://gobuffalo.io 安装 安装要求 Before installing make sure you have the required dependencies installed: A working Go environment Go version v1.16.0. Frontend Requirements# The following requirements are optional. You don’t need them if you want to build an API or if you prefer to build your app in an old-fashioned way. node version 8 or greater either yarn or npm for the asset pipeline built upon webpack . Database Specific Requirements# Again, if you don’t need a database, you won’t need these. ...

2023-01-29 · 1 分钟 · czyt