Posts with tag langs

@StateObject passing rules

2025-07-04
langsswift

This is bad and ViewB reinits at unexpected time (can run directly)import SwiftUI class Manager: ObservableObject { @Published var cnt: Int = 0 } class Manager2: ObservableObject { @ObservedObject var m: Manager; init(m: Manager) { self.m = m } func f() { self.m.cnt += 1 } } struct ViewB: View { @ObservedObject var m: Manager @ObservedObject var m2: Manager2 init(m: Manager) { print("init") self.m = m self.m2 = .init(m: m) } var body: some View { Button(action: { print("Clicked") self.m2.f() print("After Clicked") }) { Text("Click me") .font(.system(size: 40)) } } } struct ContentView: View { @ObservedObject var m = Manager(); var body: some View { ViewB(m: self.m) } } #Preview { ContentView() }To fix it (can run directly)import SwiftUI class Manager: ObservableObject { @Published var cnt: Int = 0 } class Manager2: ObservableObject { var m = Manager(); init() { } func f() { self.m.cnt += 1 } } struct ViewB: View { @ObservedObject var m2: Manager2 @ObservedObject var m: Manager var printer = DeallocPrinter() var body: some View { Button(action: { print("***\nClicked") self.m2.f() print(self.m.cnt) print("After Clicked") }) { Text("\(self.m.cnt)") .font(.system(size: 40)) } } } class DeallocPrinter { deinit { print("deallocated") } } struct ContentView: View { @StateObject private var m2: Manager2 init() { self._m2 = StateObject(wrappedValue: Manager2()) } var body: some View { ViewB(m2: self.m2, m: self.m2.m) } } #Preview { ContentView()

@ObservedObject or @StateObject

2025-07-02
ai-then-melangsswift

@ObservedObject or @StateObject在 SwiftUI 中,@ObservedObject 和 @StateObject 均可传播 @Published 更新.ViewA has @ObservedObject manager. 则 manager 可在 ViewA.init() 中使用 self.manager = .init() 初始化.@StateObject 则不行,它是一个属性包装器,Swift 编译器会将其转换为两个属性:一个带下划线的存储属性 _myStateObject (实际类型是 StateObject<MyModel> )一个计算属性 myStateObject (实际类型是 MyModel )| 场景 | 使用 | SwiftUI 是否负责生命周期 | 是否能被观察更新 | | ------------ | ----------------- | ---------------- | -------- | | 当前 View 创建对象 | @StateObject | ✅ 是 | ✅ 是 | | 外部传入的对象 | @ObservedObject | ❌ 否 | ✅ 是 | | 值类型,或不需触发更新 | 不用 | ❌ 否 | ❌ 否

Specify cuda version in setup.py when pip install -e .

2024-11-26
installlangspippython

Specify cuda version in setup.py when pip install -e .see: https://stackoverflow.com/questions/66738473/installing-pytorch-with-cuda-in-setup-pyIn setup function, use something like:"torch@https://download.pytorch.org/whl/cu111/torch-1.8.0%2Bcu111-cp37-cp37m-linux_x86_64.whl", "torchvision@https://download.pytorch.org/whl/cu111/torchvision-0.9.0%2Bcu111-cp37-cp37m-linux_x86_64.wh", "torchaudio@https://download.pytorch.org/whl/torchaudio-0.8.0-cp36-cp36m-linux_x86_64.whl"version links are from: https://download.pytorch.org/whl/torch_stable.htmlmethod above is ok to download, but still failed to build.The following succeeds for building sam-2 with cu118:pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://download.pytorch.org/whl/cu118 pip install --no-build-isolation -e . # and delete these packages in `setup.py

Plot 3D

2024-08-21
langsmatplotlibpython

Plot 3Dimport matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import sys def d3(tuples): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 解包三元组列表到X, Y, Z坐标 X, Y, Z = zip(*tuples) # 绘制点 ax.scatter(X, Y, Z, color='b') # 绘制线,连接相邻的点 ax.plot(X, Y, Z, color='r') # 设置图表标题和坐标轴标签 ax.set_title('3D Line Plot') ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_zlabel('Z axis') ax.set_aspect('auto') max_range = max(max(X) - min(X), max(Y) - min(Y), max(Z) - min(Z)) mid_x = (max(X) + min(X)) * 0.5 mid_y = (max(Y) + min(Y)) * 0.5 mid_z = (max(Z) + min(Z)) * 0.5 ax.set_xlim(mid_x - max_range * 0.5, mid_x + max_range * 0.5) ax.set_ylim(mid_y - max_range * 0.5, mid_y + max_range * 0.5) ax.set_zlim(mid_z - max_range * 0.5, mid_z + max_range * 0.5) # 显示图表 plt.show() # 示例:使用函数绘制图像 with open(sys.argv[1], 'r') as f: ps = [] for line in f: ps.append(tuple(map(float, line.strip().split()[:3]))) d3(ps)

Ignoring CMAKE_OSX_SYSROOT value

2024-07-31
cmakelangs

Ignoring CMAKE_OSX_SYSROOT value??? info "Problem environment"- author: Julyfun MacOS14.5 M1 - edited date: 2024-07-31 - expected environment: Darwin 192.168.124.13 23.5.0 Darwin Kernel Version 23.5.0: Wed May 1 20:16:51 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T8103 arm64Details of the problem / Steps to reproduce the errorcli cmake an old project warns:CMake Warning at /opt/homebrew/Cellar/cmake/3.29.2/share/cmake/Modules/Platform/Darwin-Initialize.cmake:308 (message): Ignoring CMAKE_OSX_SYSROOT value: /Library/Developer/CommandLineTools/SDKs/MacOSX14.0.sdk because the directory does not exist. Call Stack (most recent call first): /opt/homebrew/Cellar/cmake/3.29.2/share/cmake/Modules/CMakeSystemSpecificInitialize.cmake:34 (include) CMakeLists.txt:2 (project)and build failed.Answer 1??? info "Answer environment"- author: As in the problem - edited date: As in the problem - verified environment: As in the problem - assume readers know: _No assumption_ref: https://stackoverflow.com/questions/32720564/cmake-broken-after-update-to-xcode-7-0rm -r * in your build cache folder. Done

To show output

2024-04-28
langsrusttest

ref: https://stackoverflow.com/questions/54585804/how-to-run-a-specific-unit-test-in-rustrustc --test <file>This generates a binary file. Then if you run the binary file, all tests will be conducted. Source code format be like:#[cfg(test)] mod tests { use super::*; #[test] fn test_tuple_out_of_range_positive() { assert_eq!( Color::try_from((256, 1000, 10000)), Err(IntoColorError::IntConversion) ); }To run a specific test, run:./xxx --exact test::test_tuple_out_of_range_positiveCargo waycargo test test_fn_name # filters with test_fn_name cargo test test_fn_name -- --exact cargo test test_mod_name::test_fn_name -- --exact cargo test --package school_info repeat_students_should_not_get_full_marks -- --exact # To show output cargo test --package py-like --test io -- tests::main --exact --nocapture # test1() in helper.rs cargo test helper::test1 -- --exac

classic-structure

2024-03-28
langspackagerust

ref: https://course.rs/basic/crate-module/crate.html典型的 Package 结构上面创建的 Package 中仅包含 src/main.rs 文件,意味着它仅包含一个二进制同名包 my-project。如果一个 Package 同时拥有 src/main.rs 和 src/lib.rs,那就意味着它包含两个包:库包和二进制包,这两个包名也都是 my-project —— 都与 Package 同名。一个真实项目中典型的 Package,会包含多个二进制包,这些包文件被放在 src/bin 目录下,每一个文件都是独立的二进制包,同时也会包含一个库包,该包只能存在一个 src/lib.rs:. ├── Cargo.toml ├── Cargo.lock ├── src │ ├── main.rs │ ├── lib.rs │ └── bin │ └── main1.rs │ └── main2.rs ├── tests │ └── some_integration_tests.rs ├── benches │ └── simple_bench.rs └── examples └── simple_example.rs唯一库包:src/lib.rs默认二进制包:src/main.rs,编译后生成的可执行文件与 Package 同名其余二进制包:src/bin/main1.rs 和 src/bin/main2.rs,它们会分别生成一个文件同名的二进制可执行文件集成测试文件:tests 目录下基准性能测试 benchmark 文件:benches 目录下项目示例:examples 目录下这种目录结构基本上是 Rust 的标准目录结构,在 GitHub 的大多数项目上,你都将看到它的身影

default-parameters

2024-03-27
langsrust

ref: https://www.thecodedmessage.com/posts/default-params/Sol 1impl Default for WindowConfig { fn default() -> Self { Self { width: 100, height: 100, visibility: WindowVisibility::Visible, window_style: WindowStyle::Standard, z_position: -1, autoclose: AutoclosePolicy::Disable, } } } let handle = create_window(WindowConfig { width: 500, z_position: 2, autoclose: AutoclosePolicy::Enable, ..Default::default() });Sol 2..impl WindowBuilder { fn height(mut self, height: u32) -> Self { self.height = height; self } // ... } impl WindowBuilder { fn height(self, height: u32) -> Self { Self { height, ..self } } // ... } impl WindowBuilder { fn autoclose_enable(mut self) -> Self { self.autoclose = AutoclosePolicy::Enable; self } fn autoclose_disable(mut self) -> Self { self.autoclose = AutoclosePolicy::Disable; self } } impl WindowBuilder { fn build(self) { window_create(self) } } let handle = WindowBuilder::new() .width(500) .z_position(2) .autoclose_enable() .build()

thread-spawn

2024-03-06
exampleslangsrust

use std::thread; fn is_prime(n: i32) -> bool { let mut result = true; for k in 2..(n as f32).powf(0.5) as i32 + 1 { if n % k == 0 { result = false; break; } } result } fn count_primes(start: i32, end: i32) -> i32 { let mut count = 0; for k in start..end { if is_prime(k) { count += 1; } } count } fn main() { const THREAD_COUNT: usize = 15; // 设置线程数量 let n = 1e8 as i32; let chunk_size = n / THREAD_COUNT as i32; let mut handles = vec![]; for i in 0..THREAD_COUNT { let start = i as i32 * chunk_size + 2; let end = if i == THREAD_COUNT - 1 { n } else { (i + 1) as i32 * chunk_size + 2 }; let handle = thread::spawn(move || count_primes(start, end)); handles.push(handle); } let mut total_count = 0; for handle in handles { total_count += handle.join().unwrap(); } println!("{}", total_count);

attempted-ssh-agent-authentication

2024-03-04
cargoinstalllangsrust

✗ cargo build Updating crates.io index error: failed to get `async-std` as a dependency of package `app-name v0.1.0 (/Users/sathia/Developer/rust-codebase/app-name)` Caused by: failed to load source for dependency `async-std` Caused by: Unable to update registry `https://github.com/rust-lang/crates.io-index` Caused by: failed to fetch `https://github.com/rust-lang/crates.io-index` Caused by: failed to authenticate when downloading repository: [email protected]:rust-lang/crates.io-index * attempted ssh-agent authentication, but no usernames succeeded: `git` if the git CLI succeeds then `net.git-fetch-with-cli` may help here https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli Caused by: no authentication availableSolref: https://stackoverflow.com/questions/62640383/how-to-make-gitconfigs-insteadof-work-with-cargoFor bash, export CARGO_NET_GIT_FETCH_WITH_CLI=true.For fish , set -gx CARGO_NET_GIT_FETCH_WITH_CLI true

现在 s 就是 '123 + 1234 = 1357' 了,太神奇了

2024-02-05
langspythontutorials

1. 常规读入输出我们常规读入和输出用的是 input() 和 print():n = int(input()) li = list(map(int, input().split())) # 读入一行数,存储到列表 print('Hello world') print(li[0])2. 格式化字符串用 f 作为前缀的字符串可以将其中花括号中的内容自动转换:n = 123 m = 1234 s = f'{n} + {m} = {n + m}' # 现在 s 就是 '123 + 1234 = 1357' 了,太神奇了这种字符串叫做格式化字符串。3. 文件输入输出USACO 比赛中用不上,但是平时可能有用。# 这里新建了一个变量 fin,后面 open 表示打开文件,'1.in' 是文件名,'r' 表示要读入 # 必须保证 1.in 与 python 源文件在同一个文件夹下哦 fin = open('1.in', 'r') # 'w' 表示要输出 fout = open('1.txt', 'w') # 接下来就是把 input() 换成 fin.readline(),从文件中读入 n = int(fin.readline()) li = list(map(int, fin.readline().split())) # 如果要输出到文件,那么可以用格式化字符串 fout.write('Hello world\n') fout.write(f'{li[0]}\n')4. 如何用 USACO test data 自行评测打开形如这样的地址下载题目的 test data,你可以把下面这行的 jan22 改成 dec21 之类的来切换比赛:http://www.usaco.org/index.php?page=jan22results下载完以后解压得到 1.in 1.out 2.in 2.out 等文件。其中 1.in 1.out 表示第一个测试点的输入数据和标准答案。你可以在运行 python 的时候复制粘贴,也可以用文件读入输出。fout = open('1.txt', 'w') # ... 下面输出到 1.txt 中输出到 1.txt 后,你可以在终端使用 diff 命令比较两个文件。diff 1.txt 1.out如果你的答案和标准答案一样,那么 diff 命令不会有任何输出。如果不一样,他就会告诉你哪里不一样,例如:$ diff 2.out 2.txt 1c1 < hello world: 58 --- > hello world: 59 \ No newline at end of fil

输出为 {1, 2},已经自动排序

2024-02-05
langspythontutorials

1. 函数 def func():语法def func(r): # 函数名为 func,这是自定义的 PI = 3.1415926 return r * PI * PI # 函数需要一个返回值,用 return函数可以被多次利用,就像 len() 函数用来求列表长度一样。例题 1写一个函数,求半径为 r 的圆的面积。def S(r): # 求半径为 r 的圆的面积 PI = 3.1415926 return r * PI * PI print(S(5)) # 输出 49.3480203218738例题 2判断一个整数是否是偶数,如果是,返回 True。def even(n): if n % 2 == 0: return True return False # 可以按条件写多条 return 语句2. 集合 set()语法集合可以用来存数据。它和 list 相似,不同的是 set 中数据自动排序,而且不会重复出现。s = set() s.add(2) s.add(2) # 添加元素,但如果已存在就什么都不做 s.add(1) print(s) # 输出为 {1, 2},已经自动排序 s.remove(1) # 删除元素,如果元素不存在,则会发生错误 print(s) # 输出为 {2} s.clear() # 清空元素 print(2 in s) # 判断元素是否在集合中存在,输出为 False你还可以这样创建一个 set:basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) # 输出为 {'orange', 'banana', 'pear', 'apple'}注意:basket = {} 这种写法创建的是一个空的字典,不是一个空的集合。创建空集合应该使用 basket = set()。例题 1输入 $n$ 个数,去掉其中重复的数并从小到大输出,最后输出去重后还剩几个数。n = int(input()) s = set(map(int, input().split())) # 将读入的一行数转换为 set print(*s) # 输出 s 中的所有数字 print(len(s))详细介绍https://www.runoob.com/python3/python3-set.html3. 字典 dict()语法# 创建字典 d1 = { 'abc': 456 } d2 = { 'abc': 123, 98.6: 37 } # 获取字典中对应 key 的值 print(d1['abc']) # 456 print(d2[98.6]) # 37 # 修改字典 d1['abc'] = 123 print(d1['abc']) # 123 # 删除字典元素 del d1['abc'] # 删除一个键 d2.clear() # 清空字典例题 1https://blog.csdn.net/wc19862274581/article/details/124285529问题描述:输入字符串,输出字符串中出现次数最多的字母及其出现次数。如果有多个字母出现次数一样,则按字符从小到大顺序输出字母及其出现次数。输入形式:一个字符串。输出形式:出现次数最多的字母以及其出现次数。样例输入:abcccd样例输出:c 3代码实现:s = input() ma = {} for c in s: if c not in ma: # 如果这个字母没有出现过就初始化为 1 ma[c] = 1 else: # 否则加 1 ma[c] += 1 ans = max(ma.values()) # ma.values() 获取所有的值 # items() 获取所有的键值对,用 sorted() 进行排序后重新用 dict() 重新组成一个有序字典 。这种排序是优先按键排序,其次按值排序 ma = dict(sorted(ma.items())) for c, cnt in ma.items(): if cnt == ans: print(c, cnt)4. 排序 .sort() sorted()ref: https://www.freecodecamp.org/chinese/news/python-sort-how-to-sort-a-list-in-python/a = [2, 1, 3] b = sorted(a) # 不改变 a a.sort() # 改变 a a.sort(reverse=True) # 按特定函数排序 programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"] programming_languages.sort(key=len) programming_languages.sort(key=len, reverse=True) # 按自定义函数排序 programming_languages = [{'language':'Python','year':1991}, {'language':'Swift','year':2014}, {'language':'Java', 'year':1995}, {'language':'C++','year':1985}, {'language':'Go','year':2007}, {'language':'Rust','year':2010}, ] def get_year(element): return element['year'] programming_languages.sort(key=get_year) programming_languages.sort(key=get_year, reverse=True

按自定义函数排序

2024-02-02
base-and-builtinlangspython

ref: https://www.freecodecamp.org/chinese/news/python-sort-how-to-sort-a-list-in-python/a = [2, 1, 3] b = sorted(a) # 不改变 a a.sort() # 改变 a a.sort(reverse=True) # 按自定义函数排序 programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"] programming_languages.sort(key=len) programming_languages.sort(key=len, reverse=True) # 按自定义函数排序 programming_languages = [{'language':'Python','year':1991}, {'language':'Swift','year':2014}, {'language':'Java', 'year':1995}, {'language':'C++','year':1985}, {'language':'Go','year':2007}, {'language':'Rust','year':2010}, ] def get_year(element): return element['year'] programming_languages.sort(key=get_year) programming_languages.sort(key=get_year, reverse=True

allocate-function-error

2024-02-01
langspythontaichi

/home/julyfun/code/taichi-mpm/taichi/external/include/spdlog/fmt/bundled/format.h: In instantiation of ‘void fmt::internal::MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t) [with T = char; long unsigned int SIZE = 500; Allocator = std::allocator<char>; std::size_t = long unsigned int]’: /home/julyfun/code/taichi-mpm/taichi/external/include/spdlog/fmt/bundled/format.h:797:6: required from here /home/julyfun/code/taichi-mpm/taichi/external/include/spdlog/fmt/bundled/format.h:801:30: error: no matching function for call to ‘fmt::internal::MemoryBuffer<char, 500, std::allocator<char> >::allocate(std::size_t&, std::nullptr_t)’ 801 | T *new_ptr = this->allocate(new_capacity, FMT_NULL); | ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~可能你在使用错误环境下的 taichi。检查 .bashrc 之类的配置文件中是否指定了 TAICHI_REPO_DIR 等环境变量,如果指定了,删掉试试,2024-2-1 以此解决

libGL-error-MESA-LOADER-failed-to-open-iris-usr-lib-dri-iris_dri-so

2024-01-22
langspython

libGL error: failed to load driver: iris libGL error: MESA-LOADER: failed to open iris: /usr/lib/dri/iris_dri.so: cannot open shared object file: No such file or directory (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri) libGL error: failed to load driver: iris libGL error: MESA-LOADER: failed to open swrast: /usr/lib/dri/swrast_dri.so: cannot open shared object file: No such file or directory (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri) libGL error: failed to load driver: swrast 2024-01-22 18:06:31.038 ( 26.810s) [ 7F77B303A740]vtkXOpenGLRenderWindow.:651 ERR| vtkXOpenGLRenderWindow (0x77ecfd0): Cannot create GLX context. Aborting.https://stackoverflow.com/questions/72110384/libgl-error-mesa-loader-failed-to-open-irisOn Ubuntu 22.04, 24-1-22, python 3.11, using conda, taichi:conda install -c conda-forge libstdcxx-ng this fixes the erro

tarjan

2024-01-15
algolangs

缩点(有向图找强连通分量(互通块))https://www.luogu.com.cn/problem/P3387#include <bits/stdc++.h> using namespace std; const int N = 1e4 + 10, E = 2e5 + 10; int n, m; struct A { int first[N], to[E], nxt[E], cnt; void adde(int u, int v) { ++cnt; to[cnt] = v; nxt[cnt] = first[u]; first[u] = cnt; } } o, asd; int w[N]; queue<int> q; int dfn[N], id, low[N], insta[N], sta[N], top; int col[N], colcnt, colw[N]; int f[N], in[N]; void dfs(int u) { dfn[u] = low[u] = ++id; sta[++top] = u; insta[u] = 1; for (int p = o.first[u]; p; p = o.nxt[p]) { int v = o.to[p]; if (dfn[v] == 0) { dfs(v); // v 在搜索树上搜完了 // low[u] 的定义:搜索树上 u 的子树最多经过一条后向边能到达的时间戳 low[u] = min(low[u], low[v]); } else { if (insta[v]) low[u] = min(low[u], dfn[v]); // 注意!这里 insta 不是搜索栈,而是未确定强连通块的点的栈 // 为什么这里是 insta 才更新呢? // 如果不 insta[v],注意此时 dfn[v] != 0 说明 v 已经访问过了,然而这说明访问 v 所在强连通块并不包含 u // 如果 insta[v],就很抽象了,我也不好说,你自己记住吧 } } if (low[u] == dfn[u]) { ++colcnt; do { col[sta[top]] = colcnt; colw[colcnt] += w[sta[top]]; insta[sta[top]] = 0; } while (sta[top--] != u); } } int main() { ios::sync_with_stdio(0); cin >> n >> m; for (int i = 1; i <= n; ++i) { cin >> w[i]; } for (int i = 1; i<= m; ++i) { int u, v; cin >> u >> v; o.adde(u, v); } for (int i = 1; i <= n; ++i) { if (not dfn[i]) dfs(i); } for (int u = 1; u <= n; ++u) for (int p = o.first[u]; p; p = o.nxt[p]) { int v = o.to[p]; if (col[u] != col[v]) asd.adde(col[u], col[v]), ++in[col[v]]; } int ans = 0; for (int i = 1; i <= colcnt; ++i) if (in[i] == 0) q.push(i); while (not q.empty()) { int u = q.front(); q.pop(); f[u] += colw[u]; if (f[u] > ans) ans = f[u]; for (int p = asd.first[u]; p ; p= asd.nxt[p]) { int v = asd.to[p]; if (f[u] > f[v]) f[v] = f[u]; --in[v]; if (in[v] == 0) q.push(v); } } cout << ans << endl; return 0;

Add the parent directory to the Python path

2024-01-15
langspythonworkspace

对于一个项目,你执行 python somewhere/main.py则 main.py 运行的所有东西,包括 main.py import 的 py,其中的 import 的 sys.path(sys.path 会决定 import 的位置) 均为 somewhere/(即 main.py 所在的位置)。例如 main.py 中 from pkg1.animal import eat, animal.py 有 from mantis import something,则 mantis 必须在 main.py 所在文件夹下,不可以在 pkg1/ 中。但是 vscode 的智能提示比较呆,当前文件 init.py 的祖先文件夹都会自动加入智能提示的 sys.path.other solutions你也可以 from .somedir import xxx[what] 这啥玩意sys.path.append 的作用范围?cur_dir = os.path.dirname(__file__) print(cur_dir) # Add the parent directory to the Python path sys.path.append(cur_dir) print(sys.path, type(sys.path))该语句后所有的 import (就算 import 文件中的 import 也可以)都会用这个新的 path.注意 import 后不再能文件夹寻址如果有 plant/apple/eat.py你可以 import plant.apple.eat.some但不可以 import plant 之后再 a = plant.apple.eat.some(

networkx

2024-01-15
langspython

this package works together with matplotlib.import networkx as nx from matplotlib import pyplot as plt g = nx.Graph() g.add_node(1) list(g.nodes()) g.add_nodes_from([3, 4]) print(g.nodes) nx.draw(g) nx.draw(g, with_labels=True) plt.show() g.add_node('coin') g.add_edge(1, 2) e = (2, 3) g.add_edge(*e) g.add_edges_from([(1, 3), (1, 4), (1, 5)]) G.remove_node(2) G.remove_nodes_from([4, 5, H, 'coin']) print("les sommets de G sont : ", G.nodes) edgelist = [(0, 1), (1, 2), (2, 3)] I = nx.Graph(edgelist) edgelist1 = [(0, 1), (0, 2), (0, 3)] edgelist2 = [(0, 4), (0, 5), (0, 6)] G1 = nx.Graph(edgelist1) G2 = nx.Graph(edgelist2) H1 = nx.disjoint_union(G1, G2) # make two graph in the same one H2 = nx.compose(G1, G2) # make the same considering the node id g = nx.petersen_graph() # a special graph nx.draw_shell(g, nlist=[range(5, 10), range(5)]) # make 0, 1, 2, 3, 4 in a shell options = { 'node_color': 'yellow', 'node_size': 500, 'width': 2, 'with_labels': True } nx.draw_random(G, **options) plt.show() nx.draw_circular(G, **options) plt.show() nx.draw_shell(G, nlist=[range(5, 10), range(5)], **options) plt.show() nx.draw(G) plt.savefig("graph.png") G2= nx.DiGraph () G2.add_edges_from([(0, 1),(1,0), (0, 2), (0, 3)]) nx.draw_random(G2, with_labels=True, font_weight='bold') plt.show()draw in particular positionG=nx.Graph() G.add_edges_from([[1,2],[2,3],[3,1]]) position={1:[0,2],2:[2,0],3:[0,0]} #dictionnaire où on précise les coordonnées de chacun des sommets nx.draw(G,pos=position

runtime-error-attemp-to-start-a-new-process-before-the-current-process

2024-01-15
langsmultiprocessingpython

RuntimeError: Attempt to start a new process before the current process has finished its bootstrapping phase. This probably means that you are on Windows and you have forgotten to use the proper idiom in the main module: if name == 'main': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce a Windows executable.SolutionAs the note said, add __main__`` guard and add freeze_support()` and the begining.if __name__ == "__main__": # multiprocessing.freeze_support() # may be not needed start = time.time() ...Ref:https://discuss.pytorch.org/t/runtimeerror-an-attempt-has-been-made-to-start-a-new-process-before-the-current-process-has-finished-its-bootstrapping-phase/145462/

Sample image tensor dimensions: (channels=3, height=100, width=100)

2024-01-15
langspythonpytorch

ChatGPTimport cv2 import numpy as np import torch # Sample image tensor dimensions: (channels=3, height=100, width=100) image_tensor = torch.rand(3, 100, 100) # Replace with your actual tensor # Convert PyTorch tensor to NumPy array image_np = image_tensor.permute(1, 2, 0).cpu().numpy() # Channels last for OpenCV # Define the target size target_height = 64 target_width = 64 # Resize the image using OpenCV resized_image_np = cv2.resize(image_np, (target_width, target_height)) # Convert NumPy array back to PyTorch tensor resized_image_tensor = torch.from_numpy(resized_image_np).permute(2, 0, 1).float() # Print the shapes to verify print("Original tensor shape:", image_tensor.shape) print("Resized tensor shape:", resized_image_tensor.shape)import torch import torch.nn.functional as F # 假设你有一个480x480的RGB图片,可以表示为一个3维的torch.Tensor # 假设img是你的原始图像,大小为(1, 3, 480, 480) # (1, 3, 480, 480)表示(batch_size, channels, height, width) # 生成一个480x480的假图片,这里用随机数代替 img = torch.rand(1, 3, 480, 480) # 缩放成128x128的图像 scaled_img = F.interpolate(img, size=(128, 128), mode='bilinear', align_corners=False) # 输出缩放后图像的大小 print("缩放后图像大小:", scaled_img.size()) # 输出: torch.Size([1, 3, 128, 128]

No more posts to load.