Rust vs Go:常用语法对比(六)
题图来自[1]
101. Load from HTTP GET request into a string
Make an HTTP request with method GET to URL u, then store the body of the response in string s.
发起http请求
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
)
func main() {
u := "http://" + localhost + "/hello?name=Inigo+Montoya"
res, err := http.Get(u)
check(err)
buffer, err := ioutil.ReadAll(res.Body)
res.Body.Close()
check(err)
s := string(buffer)
fmt.Println("GET response:", res.StatusCode, s)
}
const localhost = "127.0.0.1:3000"
func init() {
http.HandleFunc("/hello", myHandler)
startServer()
}
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello %s", r.FormValue("name"))
}
func startServer() {
listener, err := net.Listen("tcp", localhost)
check(err)
go http.Serve(listener, nil)
}
func check(err error) {
if err != nil {
panic(err)
}
}
res has type *http.Response. buffer has type []byte. It is idiomatic and strongly recommended to check errors at each step.
GET response: 200 Hello Inigo Montoya
extern crate reqwest;
use reqwest::Client;
let client = Client::new();
let s = client.get(u).send().and_then(|res| res.text())?;
or
[dependencies]
ureq = "1.0"
let s = ureq::get(u).call().into_string()?;
or
[dependencies]
error-chain = "0.12.4"
reqwest = { version = "0.11.2", features = ["blocking"] }
use error_chain::error_chain;
use std::io::Read;
let mut response = reqwest::blocking::get(u)?;
let mut s = String::new();
response.read_to_string(&mut s)?;
102. Load from HTTP GET request into a file
Make an HTTP request with method GET to URL u, then store the body of the response in file result.txt. Try to save the data as it arrives if possible, without having all its content in memory at once.
发起http请求
package main
import (
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
)
func main() {
err := saveGetResponse()
check(err)
err = readFile()
check(err)
fmt.Println("Done.")
}
func saveGetResponse() error {
u := "http://" + localhost + "/hello?name=Inigo+Montoya"
fmt.Println("Making GET request")
resp, err := http.Get(u)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("Status: %v", resp.Status)
}
fmt.Println("Saving data to file")
out, err := os.Create("/tmp/result.txt")
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
func readFile() error {
fmt.Println("Reading file")
buffer, err := ioutil.ReadFile("/tmp/result.txt")
if err != nil {
return err
}
fmt.Printf("Saved data is %q\n", string(buffer))
return nil
}
const localhost = "127.0.0.1:3000"
func init() {
http.HandleFunc("/hello", myHandler)
startServer()
}
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello %s", r.FormValue("name"))
}
func startServer() {
listener, err := net.Listen("tcp", localhost)
check(err)
go http.Serve(listener, nil)
}
func check(err error) {
if err != nil {
panic(err)
}
}
resp has type *http.Response. It is idiomatic and strongly recommended to check errors at each step, except for the calls to Close.
Making GET request
Saving data to file
Reading file
Saved data is "Hello Inigo Montoya"
Done.
extern crate reqwest;
use reqwest::Client;
use std::fs::File;
let client = Client::new();
match client.get(&u).send() {
Ok(res) => {
let file = File::create("result.txt")?;
::std::io::copy(res, file)?;
},
Err(e) => eprintln!("failed to send request: {}", e),
};
105. Current executable name
Assign to string s the name of the currently executing program (but not its full path).
当前可执行文件名称
将当前正在执行的程序的名称分配给字符串s(但不是它的完整路径)。
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
var s string
path := os.Args[0]
s = filepath.Base(path)
fmt.Println(s)
}
play
fn get_exec_name() -> Option<String> {
std::env::current_exe()
.ok()
.and_then(|pb| pb.file_name().map(|s| s.to_os_string()))
.and_then(|s| s.into_string().ok())
}
fn main() -> () {
let s = get_exec_name().unwrap();
println!("{}", s);
}
playground
or
fn main() {
let s = std::env::current_exe()
.expect("Can't get the exec path")
.file_name()
.expect("Can't get the exec name")
.to_string_lossy()
.into_owned();
println!("{}", s);
}
playground
106. Get program working directory
Assign to string dir the path of the working directory. (This is not necessarily the folder containing the executable itself)
获取程序的工作路径
package main
import (
"fmt"
"os"
)
func main() {
dir, err := os.Getwd()
fmt.Println(dir, err)
}
/ <nil>
use std::env;
fn main() {
let dir = env::current_dir().unwrap();
println!("{:?}", dir);
}
"/playground"
107. Get folder containing current program
Assign to string dir the path of the folder containing the currently running executable. (This is not necessarily the working directory, though.)
获取包含当前程序的文件夹
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
var dir string
programPath := os.Args[0]
absolutePath, err := filepath.Abs(programPath)
if err != nil {
panic(err)
}
dir = filepath.Dir(absolutePath)
fmt.Println(dir)
}
/tmpfs
let dir = std::env::current_exe()?
.canonicalize()
.expect("the current exe should exist")
.parent()
.expect("the current exe should be a file")
.to_string_lossy()
.to_owned();
Rust doesn't represent paths as Strings, so we need to convert the Path returned from Path::parent. This code chooses to do this lossily, replacing characters it doesn't recognize with �
109. Number of bytes of a type
Set n to the number of bytes of a variable t (of type T).
获取某个类型的字节数
package main
import (
"fmt"
"reflect"
)
func main() {
var t T
tType := reflect.TypeOf(t)
n := tType.Size()
fmt.Println("A", tType, "object is", n, "bytes.")
}
type Person struct {
FirstName string
Age int
}
// T is a type alias, to stick to the idiom statement.
// T has the same memory footprint per value as Person.
type T Person
A main.T object is 24 bytes.
// T has (8 + 4) == 12 bytes of data
struct T(f64, i32);
fn main() {
let n = ::std::mem::size_of::<T>();
println!("{} bytes", n);
// T has size 16, which is "the offset in bytes between successive elements in an array with item type T"
}
16 bytes
110. Check if string is blank
Set boolean blank to true if string s is empty, or null, or contains only whitespace ; false otherwise.
检查字符串是否空白
package main
import (
"fmt"
"strings"
)
func main() {
for _, s := range []string{
"",
"a",
" ",
"\t \n",
"_",
} {
blank := strings.TrimSpace(s) == ""
if blank {
fmt.Printf("%q is blank\n", s)
} else {
fmt.Printf("%q is not blank\n", s)
}
}
}
"" is blank
"a" is not blank
" " is blank
"\t \n" is blank
"_" is not blank
fn main() {
let list = vec!["", " ", " ", "\t", "\n", "a", " b "];
for s in list {
let blank = s.trim().is_empty();
if blank {
println!("{:?}\tis blank", s)
} else {
println!("{:?}\tis not blank", s)
}
}
}
"" is blank
" " is blank
" " is blank
"\t" is blank
"\n" is blank
"a" is not blank
" b " is not blank
111. Launch other program
From current process, run program x with command-line parameters "a", "b".
运行其他程序
package main
import (
"fmt"
"os/exec"
)
func main() {
err := exec.Command("x", "a", "b").Run()
fmt.Println(err)
}
exec: "x": executable file not found in $PATH
use std::process::Command;
fn main() {
let child = Command::new("ls")
.args(&["/etc"])
.spawn()
.expect("failed to execute process");
let output = child.wait_with_output().expect("Failed to wait on child");
let output = String::from_utf8(output.stdout).unwrap();
println!("{}", output);
}
X11
adduser.conf
alternatives
apt
bash.bashrc
bash_completion.d
bindresvport.blacklist
ca-certificates
ca-certificates.conf
cron.d
cron.daily
debconf.conf
debian_version
default
deluser.conf
dpkg
e2scrub.conf
emacs
environment
ethertypes
fstab
gai.conf
group
group-
gshadow
gshadow-
gss
host.conf
hostname
hosts
init.d
inputrc
issue
issue.net
kernel
ld.so.cache
ld.so.conf
ld.so.conf.d
ldap
legal
libaudit.conf
localtime
logcheck
login.defs
logrotate.d
lsb-release
machine-id
magic
magic.mime
mailcap
mailcap.order
mime.types
mke2fs.conf
mtab
networks
nsswitch.conf
opt
os-release
pam.conf
pam.d
passwd
passwd-
perl
profile
profile.d
protocols
python2.7
rc0.d
rc1.d
rc2.d
rc3.d
rc4.d
rc5.d
rc6.d
rcS.d
resolv.conf
rmt
rpc
security
selinux
services
shadow
shadow-
shells
skel
ssh
ssl
subgid
subgid-
subuid
subuid-
sysctl.conf
sysctl.d
systemd
terminfo
timezone
update-motd.d
xattr.conf
xdg
or
use std::process::Command;
fn main() {
let output = Command::new("ls")
.args(&["/etc"])
.output()
.expect("failed to execute process");
let output = String::from_utf8(output.stdout).unwrap();
println!("{}", output);
}
or
use std::process::Command;
fn main() {
let status = Command::new("ls")
.args(&["/etc"])
.status()
.expect("failed to execute process");
// exit code is outputted after _ls_ runs
println!("{}", status);
}
112. Iterate over map entries, ordered by keys
Print each key k with its value x from an associative array mymap, in ascending order of k.
遍历map,按key排序
package main
import (
"fmt"
"sort"
)
func main() {
mymap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
keys := make([]string, 0, len(mymap))
for k := range mymap {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
x := mymap[k]
fmt.Println("Key =", k, ", Value =", x)
}
}
Key = four , Value = 4
Key = one , Value = 1
Key = three , Value = 3
Key = two , Value = 2
use std::collections::BTreeMap;
fn main() {
let mut mymap = BTreeMap::new();
mymap.insert("one", 1);
mymap.insert("two", 2);
mymap.insert("three", 3);
mymap.insert("four", 4);
mymap.insert("five", 5);
mymap.insert("six", 6);
// Iterate over map entries, ordered by keys, which is NOT the numerical order
for (k, x) in mymap {
println!("({}, {})", k, x);
}
}
(five, 5)
(four, 4)
(one, 1)
(six, 6)
(three, 3)
(two, 2)
113. Iterate over map entries, ordered by values
Print each key k with its value x from an associative array mymap, in ascending order of x. Note that multiple entries may exist for the same value x.
遍历map,按值排序
package main
import (
"fmt"
"sort"
)
type entry struct {
key string
value int
}
type entries []entry
func (list entries) Len() int { return len(list) }
func (list entries) Less(i, j int) bool { return list[i].value < list[j].value }
func (list entries) Swap(i, j int) { list[i], list[j] = list[j], list[i] }
func main() {
mymap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"dos": 2,
"deux": 2,
}
entries := make(entries, 0, len(mymap))
for k, x := range mymap {
entries = append(entries, entry{key: k, value: x})
}
sort.Sort(entries)
for _, e := range entries {
fmt.Println("Key =", e.key, ", Value =", e.value)
}
}
Key = one , Value = 1
Key = dos , Value = 2
Key = deux , Value = 2
Key = two , Value = 2
Key = three , Value = 3
Key = four , Value = 4
or
package main
import (
"fmt"
"sort"
)
func main() {
mymap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"dos": 2,
"deux": 2,
}
type entry struct {
key string
value int
}
entries := make([]entry, 0, len(mymap))
for k, x := range mymap {
entries = append(entries, entry{key: k, value: x})
}
sort.Slice(entries, func(i, j int) bool {
return entries[i].value < entries[j].value
})
for _, e := range entries {
fmt.Println("Key =", e.key, ", Value =", e.value)
}
}
Key = one , Value = 1
Key = two , Value = 2
Key = dos , Value = 2
Key = deux , Value = 2
Key = three , Value = 3
Key = four , Value = 4
use itertools::Itertools;
use std::collections::HashMap;
fn main() {
let mut mymap = HashMap::new();
mymap.insert(1, 3);
mymap.insert(2, 6);
mymap.insert(3, 4);
mymap.insert(4, 1);
for (k, x) in mymap.iter().sorted_by_key(|x| x.1) {
println!("[{},{}]", k, x);
}
}
[4,1]
[1,3]
[3,4]
[2,6]
or
use std::collections::HashMap;
fn main() {
let mut mymap = HashMap::new();
mymap.insert(1, 3);
mymap.insert(2, 6);
mymap.insert(3, 4);
mymap.insert(4, 1);
let mut items: Vec<_> = mymap.iter().collect();
items.sort_by_key(|item| item.1);
for (k, x) in items {
println!("[{},{}]", k, x);
}
}
[4,1]
[1,3]
[3,4]
[2,6]
114. Test deep equality
Set boolean b to true if objects x and y contain the same values, recursively comparing all referenced elements in x and y. Tell if the code correctly handles recursive types.
深度判等
package main
import (
"fmt"
"reflect"
)
func main() {
x := Foo{9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}}
list := []Foo{
{9, "Bye", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}},
{9, "Hello", []bool{false, false}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}},
{9, "Hello", []bool{false, true}, map[int]float64{1: 3.0, 2: 2.0}, &Bar{"Babar"}},
{9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 5: 2.0}, &Bar{"Babar"}},
{9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Batman"}},
{9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}},
}
for i, y := range list {
b := reflect.DeepEqual(x, y)
if b {
fmt.Println("x deep equals list[", i, "]")
} else {
fmt.Println("x doesn't deep equal list[", i, "]")
}
}
}
type Foo struct {
int
str string
bools []bool
mapping map[int]float64
bar *Bar
}
type Bar struct {
name string
}
x doesn't deep equal list[ 0 ]
x doesn't deep equal list[ 1 ]
x doesn't deep equal list[ 2 ]
x doesn't deep equal list[ 3 ]
x doesn't deep equal list[ 4 ]
x deep equals list[ 5 ]
let b = x == y;
The == operator can only be used by having a type implement PartialEq.
115. Compare dates
Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.
日期比较
package main
import (
"fmt"
"time"
)
func main() {
d1 := time.Now()
d2 := time.Date(2020, time.November, 10, 23, 0, 0, 0, time.UTC)
b := d1.Before(d2)
fmt.Println(b)
}
true
extern crate chrono;
use chrono::prelude::*;
let b = d1 < d2;
doc -- Struct chrono::Date[2]
116. Remove occurrences of word from string
Remove all occurrences of string w from string s1, and store the result in s2.
去除指定字符串
package main
import "fmt"
import "strings"
func main() {
var s1 = "foobar"
var w = "foo"
s2 := strings.Replace(s1, w, "", -1)
fmt.Println(s2)
}
bar
fn main() {
let s1 = "foobar";
let w = "foo";
let s2 = s1.replace(w, "");
println!("{}", s2);
}
bar
or
fn main() {
let s1 = "foobar";
let w = "foo";
let s2 = str::replace(s1, w, "");
println!("{}", s2);
}
bar
117. Get list size
获取list的大小
package main
import "fmt"
func main() {
// x is a slice
x := []string{"a", "b", "c"}
n := len(x)
fmt.Println(n)
// y is an array
y := [4]string{"a", "b", "c"}
n = len(y)
fmt.Println(n)
}
3
4
fn main() {
let x = vec![11, 22, 33];
let n = x.len();
println!("x has {} elements", n);
}
x has 3 elements
118. List to set
Create set y from list x. x may contain duplicates. y is unordered and has no repeated values.
从list到set
package main
import "fmt"
func main() {
x := []string{"b", "a", "b", "c"}
fmt.Println("x =", x)
y := make(map[string]struct{}, len(x))
for _, v := range x {
y[v] = struct{}{}
}
fmt.Println("y =", y)
}
x = [b a b c]
y = map[a:{} b:{} c:{}]
use std::collections::HashSet;
fn main() {
let x: Vec<i32> = vec![1, 7, 3, 1];
println!("x: {:?}", x);
let y: HashSet<_> = x.into_iter().collect();
println!("y: {:?}", y);
}
x: [1, 7, 3, 1]
y: {1, 7, 3}
119. Deduplicate list
Remove duplicates from list x. Explain if original order is preserved.
list去重
package main
import "fmt"
func main() {
type T string
x := []T{"b", "a", "b", "c"}
fmt.Println("x =", x)
y := make(map[T]struct{}, len(x))
for _, v := range x {
y[v] = struct{}{}
}
x2 := make([]T, 0, len(y))
for _, v := range x {
if _, ok := y[v]; ok {
x2 = append(x2, v)
delete(y, v)
}
}
x = x2
fmt.Println("x =", x)
}
x = [b a b c]
x = [b a c]
or
package main
import "fmt"
func main() {
type T string
x := []T{"b", "a", "b", "b", "c", "b", "a"}
fmt.Println("x =", x)
seen := make(map[T]bool)
j := 0
for _, v := range x {
if !seen[v] {
x[j] = v
j++
seen[v] = true
}
}
x = x[:j]
fmt.Println("x =", x)
}
x = [b a b b c b a]
x = [b a c]
or
package main
import "fmt"
type T *int64
func main() {
var a, b, c, d int64 = 11, 22, 33, 11
x := []T{&b, &a, &b, &b, &c, &b, &a, &d}
print(x)
seen := make(map[T]bool)
j := 0
for _, v := range x {
if !seen[v] {
x[j] = v
j++
seen[v] = true
}
}
for i := j; i < len(x); i++ {
// Avoid memory leak
x[i] = nil
}
x = x[:j]
// Now x has only distinct pointers (even if some point to int64 values that are the same)
print(x)
}
func print(a []T) {
glue := ""
for _, p := range a {
fmt.Printf("%s%d", glue, *p)
glue = ", "
}
fmt.Println()
}
22, 11, 22, 22, 33, 22, 11, 11
22, 11, 33, 11
fn main() {
let mut x = vec![1, 2, 3, 4, 3, 2, 2, 2, 2, 2, 2];
x.sort();
x.dedup();
println!("{:?}", x);
}
[1, 2, 3, 4]
or
use itertools::Itertools;
fn main() {
let x = vec![1, 2, 3, 4, 3, 2, 2, 2, 2, 2, 2];
let dedup: Vec<_> = x.iter().unique().collect();
println!("{:?}", dedup);
}
[1, 2, 3, 4]
120. Read integer from stdin
Read an integer value from the standard input into variable n
从标准输入中读取整数
package main
import (
"fmt"
"io/ioutil"
"os"
)
// This string simulates the keyboard entry.
var userInput string = `42 017`
func main() {
var i int
_, err := fmt.Scan(&i)
fmt.Println(i, err)
// The second value starts with 0, thus is interpreted as octal!
var j int
_, err = fmt.Scan(&j)
fmt.Println(j, err)
}
// The Go Playground doesn't actually read os.Stdin, so this
// workaround writes some data on virtual FS in a file, and then
// sets this file as the new Stdin.
//
// Note that the init func is run before main.
func init() {
err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644)
if err != nil {
panic(err)
}
fileIn, err := os.Open("/tmp/stdin")
if err != nil {
panic(err)
}
os.Stdin = fileIn
}
42 <nil>
15 <nil>
or
package main
import (
"fmt"
"io/ioutil"
"os"
)
// This string simulates the keyboard entry.
var userInput string = `42 017`
func main() {
var i int
_, err := fmt.Scanf("%d", &i)
fmt.Println(i, err)
var j int
_, err = fmt.Scanf("%d", &j)
fmt.Println(j, err)
}
// The Go Playground doesn't actually read os.Stdin, so this
// workaround writes some data on virtual FS in a file, and then
// sets this file as the new Stdin.
//
// Note that the init func is run before main.
func init() {
err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644)
if err != nil {
panic(err)
}
fileIn, err := os.Open("/tmp/stdin")
if err != nil {
panic(err)
}
os.Stdin = fileIn
}
42 <nil>
17 <nil>
fn get_input() -> String {
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).expect("Failed");
buffer
}
let n = get_input().trim().parse::<i64>().unwrap();
or
use std::io;
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();s
or
use std::io::BufRead;
let n: i32 = std::io::stdin()
.lock()
.lines()
.next()
.expect("stdin should be available")
.expect("couldn't read from stdin")
.trim()
.parse()
.expect("input was not an integer");
参考资料
题图来自: https://picx.zhimg.com/v2-363b653b2429b2f8073bc067b6c55f2d_720w.jpg?source=172ae18b
[2]doc -- Struct chrono::Date: https://docs.rs/chrono/0.4.3/chrono/struct.Date.html
本文由 mdnice 多平台发布
相关文章:
Rust vs Go:常用语法对比(六)
题图来自[1] 101. Load from HTTP GET request into a string Make an HTTP request with method GET to URL u, then store the body of the response in string s. 发起http请求 package mainimport ( "fmt" "io/ioutil" "net" "net/http…...
css元素定位:通过元素的标签或者元素的id、class属性定位
前言 大部分人在使用selenium定位元素时,用的是xpath元素定位方式,因为xpath元素定位方式基本能解决定位的需求。xpath元素定位方式更直观,更好理解一些。 css元素定位方式往往被忽略掉了,其实css元素定位方式也有它的价值&…...
java享元模式
在Java中实现享元模式,可以通过创建一个享元工厂(FlyweightFactory)和享元对象(Flyweight)来完成。享元模式用于共享可复用对象,以节省内存和提高性能。 下面是一个简单的示例: 首先ÿ…...
ESP32(MicroPython) 两轮差速五自由度机械臂小车
这次的项目在软件上没多少调整,但本人希望分享一下硬件上的经验。 小车使用两轮差速底盘,驱动轮在小车中间,前后都要万向轮。这种形式可以实现0转弯半径,但受万向轮及用于加高的铜柱的规格限制,两个万向轮难以调到相同…...
mysql基本函数(五)
目录 一、数字函数二、字符函数三、日期时间函数3.1 获取系统日期时间的函数3.2 日期格式化函数3.3 日期偏移计算3.4 日期之间相隔的天数 四、条件函数4.1 IF语句4.2 条件语句 一、数字函数 函数功能用例ABS绝对值ABS(-100)ROUND四舍五入ROUND(4.62)FLOOR向下取值FLOOR(9.9)CE…...
liteflow 2.10 配置中心简单记录
除nacos是一个key 同时管理chain和script node外,可以理解为配置文件整体放到一个key下nacos下的文件必须是xml格式,系统只实现了xml parser其它etcd,zk,Apollo 是两个namespace/path(chain及script node各一)下多个key,每个key对应一个chain/node所有配置中心的核心代码…...
【C++】引用、内联函数等
文章目录 一、引用1.引用概念2.引用特性3.引用时的权限问题4 .使用场景5 .引用和指针的联系与区别 二、内联函数1.概念2.注意点 三、auto关键字1.概念2.auto的使用细则 四、 基于范围的for循环1.概念2.范围for的使用条件 五、 指针空值nullptr1.概念2.使用注意 一、引用 1.引用…...
RocketMQ教程-(4)-主题(Topic)
本文介绍 Apache RocketMQ 中主题(Topic)的定义、模型关系、内部属性、行为约束、版本兼容性及使用建议。 定义 主题是 Apache RocketMQ 中消息传输和存储的顶层容器,用于标识同一类业务逻辑的消息。 主题的作用主要如下: 定义…...
睡眠健康数据分析
项目背景 背景描述 本数据集涵盖了与睡眠和日常习惯有关的诸多变量。如性别、年龄、职业、睡眠时间、睡眠质量、身体活动水平、压力水平、BMI类别、血压、心率、每日步数、以及是否有睡眠障碍等细节。 数据集的主要特征: 综合睡眠指标: 探索睡眠持续时…...
Spring Boot 3.x 系列【47】启动流程 | 启动监听器
有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot版本3.1.0 源码地址:https://gitee.com/pearl-organization/study-spring-boot3 文章目录 1. 前言2. 核心类2.1 SpringApplicationRunListener2.2 ApplicationStartup2.3 ApplicationListener3. 执行流程3.1 获取监…...
【KD】知识蒸馏与迁移学习的不同
知识蒸馏与迁移学习的不同 (1)数据域不同. 知识蒸馏中的知识通常是在同一个目标数据集上进行迁移,而迁移学习中的知识往往是在不同目标的数据集上进行转移. (2)网络结构不同. 知识蒸馏的两个网络可以是同构或者异构的,而迁移学习通常是在单个网络上利用其…...
计算机内存中的缓存Cache Memories
这篇写一下计算机系统中的缓存Cache应用场景和实现方式介绍。 Memory hierarchy 在讲缓存之前,首先要了解计算机中的内存结构层次Memory hierarchy。也就是下图金字塔形状的结构。 从上到下,内存层次结构如下: 寄存器:这是计算机…...
Flask的send file和send_from_directory的区别
可以自行查看flask 文档。 send file高效; send from directory安全,且适用于静态资源交互。 都是实现相同的功能的。 send_file send_from_directory...
Java 队列
基本介绍 数组模拟队列 思路分析 代码实现 import java.util.Scanner;public class Test {public static void main(String[] args) {// 创建一个队列ArrayQueue queue new ArrayQueue(3);int select;Scanner scanner new Scanner(System.in);boolean loop true;while (lo…...
【算法基础:搜索与图论】3.6 二分图(染色法判定二分图匈牙利算法)
文章目录 二分图介绍染色法判定二分图例题:860. 染色法判定二分图 匈牙利匹配二分图最大匹配匈牙利匹配算法思想例题:861. 二分图的最大匹配 二分图介绍 https://oi-wiki.org/graph/bi-graph/ 二分图是图论中的一个概念,它的所有节点可以被…...
SpringMVC 怎么和 AJAX 相互调用的
通过 Jackson 框架就可以把 Java 里面的对象直接转化成 Js 可以识别的 Json 对象。 步骤如下 : a、加入 Jackson.jar b、在配置文件中配置 json 的映射 c、在接受 Ajax 方法里面可以直接返回 Object,List 等,但方法前面要加上ResponseBody 详细步骤: …...
UCDOS和WPS推动计算机领域的汉字化发展,中文编程该谁力扛大旗?
你还记得UCDOS吗? 从DOS时代过来的人,还知道UCDOS的,现在可能已经是中年人了! 当时,鲍岳桥的UCDOS可以称得上是中国的国产操作系统。 在Windows还没来得及进入中国市场时,UCDOS可以说是走向了巅峰时刻&a…...
golang+layui提升界面美化度--[推荐]
一、背景 golanglayui提升界面美化度--[推荐]; golang后端写的页面很难看,如何好看点呢,那就是layui https://layui.dev/ 也是一个简单上手容易使用的框架,类似jquery,对于后端开发来说满足使用需求 二、使用注意点…...
42. 接雨水
题目介绍 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 示例 1: 输入:height [0,1,0,2,1,0,1,3,2,1,2,1] 输出:6 解释:上面是由数组 [0,1,0,2,1,0,1,3…...
Python学习阶段路线和内容
Python学习阶段路线和内容 这是我的看法和认识,供参考。 Python学习路线主要分为三个阶段:入门阶段、提高阶段和深入阶段。 入门阶段 入门阶段需要学习Python的基本语法,掌握变量和数据类型、条件语句和循环语句、函数和模块等内容。并通过…...
基于算法竞赛的c++编程(28)结构体的进阶应用
结构体的嵌套与复杂数据组织 在C中,结构体可以嵌套使用,形成更复杂的数据结构。例如,可以通过嵌套结构体描述多层级数据关系: struct Address {string city;string street;int zipCode; };struct Employee {string name;int id;…...
网络六边形受到攻击
大家读完觉得有帮助记得关注和点赞!!! 抽象 现代智能交通系统 (ITS) 的一个关键要求是能够以安全、可靠和匿名的方式从互联车辆和移动设备收集地理参考数据。Nexagon 协议建立在 IETF 定位器/ID 分离协议 (…...
C++:std::is_convertible
C++标志库中提供is_convertible,可以测试一种类型是否可以转换为另一只类型: template <class From, class To> struct is_convertible; 使用举例: #include <iostream> #include <string>using namespace std;struct A { }; struct B : A { };int main…...
DockerHub与私有镜像仓库在容器化中的应用与管理
哈喽,大家好,我是左手python! Docker Hub的应用与管理 Docker Hub的基本概念与使用方法 Docker Hub是Docker官方提供的一个公共镜像仓库,用户可以在其中找到各种操作系统、软件和应用的镜像。开发者可以通过Docker Hub轻松获取所…...
关于nvm与node.js
1 安装nvm 安装过程中手动修改 nvm的安装路径, 以及修改 通过nvm安装node后正在使用的node的存放目录【这句话可能难以理解,但接着往下看你就了然了】 2 修改nvm中settings.txt文件配置 nvm安装成功后,通常在该文件中会出现以下配置&…...
让回归模型不再被异常值“带跑偏“,MSE和Cauchy损失函数在噪声数据环境下的实战对比
在机器学习的回归分析中,损失函数的选择对模型性能具有决定性影响。均方误差(MSE)作为经典的损失函数,在处理干净数据时表现优异,但在面对包含异常值的噪声数据时,其对大误差的二次惩罚机制往往导致模型参数…...
在QWebEngineView上实现鼠标、触摸等事件捕获的解决方案
这个问题我看其他博主也写了,要么要会员、要么写的乱七八糟。这里我整理一下,把问题说清楚并且给出代码,拿去用就行,照着葫芦画瓢。 问题 在继承QWebEngineView后,重写mousePressEvent或event函数无法捕获鼠标按下事…...
MySQL 知识小结(一)
一、my.cnf配置详解 我们知道安装MySQL有两种方式来安装咱们的MySQL数据库,分别是二进制安装编译数据库或者使用三方yum来进行安装,第三方yum的安装相对于二进制压缩包的安装更快捷,但是文件存放起来数据比较冗余,用二进制能够更好管理咱们M…...
怎么让Comfyui导出的图像不包含工作流信息,
为了数据安全,让Comfyui导出的图像不包含工作流信息,导出的图像就不会拖到comfyui中加载出来工作流。 ComfyUI的目录下node.py 直接移除 pnginfo(推荐) 在 save_images 方法中,删除或注释掉所有与 metadata …...
手机平板能效生态设计指令EU 2023/1670标准解读
手机平板能效生态设计指令EU 2023/1670标准解读 以下是针对欧盟《手机和平板电脑生态设计法规》(EU) 2023/1670 的核心解读,综合法规核心要求、最新修正及企业合规要点: 一、法规背景与目标 生效与强制时间 发布于2023年8月31日(OJ公报&…...
