I'm trying to drawing SVG image file on CanvasRenderingContext2d element using CanvasRenderingContext2d::draw_image_with_svg_image_element.
To get SVGImageElement of my SVG image, I created SVGElement with document.create_element_ns and converted to SVGImageElement with dyn_into::<SVGImageElement>() but got following error on conversion.
panicked at 'called `Result::unwrap()` on an `Err` value: SvgElement { obj: Element { obj: Node { obj: EventTarget { obj: Object { obj: JsValue(SVGSVGElement) } } } } }'
Here is my code:
use gloo_utils::document;
use wasm_bindgen::JsCast;
use web_sys::{SvgElement, SvgImageElement};
fn get_svg_image_element() -> SVGImageElement {
let svg = document()
.create_element_ns(Some("http://www.w3.org/2000/svg"), "svg")
.unwrap();
svg.set_inner_html(include_str!("example.svg"));
svg.dyn_into::<SvgImageElement>() // dyn_into() returns Err()
.unwrap()
}
Cloud you tell me the way to get SVGImageElement from file?
Related
I tried this code
static HOST_FILE: &'static [u8] = include_bytes!("C:\\Users\\Downloads\\cbimage.png");
fn main() {
let host_str = std::str::from_utf8(HOST_FILE). unwrap();
println!("Hosts are:\n{}", &host_str[..42]);
}
But it shows me an error:
thread 'main' panicked at 'called Result::unwrap() on an Err value: Utf8Error { valid_up_to: 66, error_len: Some(1) }', src\main.rs:48:51
stack backtrace
static IMAGE: &'static [u8] = include_bytes!("C:\\Users\\Downloads\\cbimage.png");
fn main() {
println!("Image: {:?}", IMAGE);
}
Although I recommend using a path relative to your source code, like
static IMAGE: &'static [u8] = include_bytes!("../cbimage.png");
fn main() {
println!("Image: {:?}", IMAGE);
}
And place cbimage.png next to your Cargo.toml.
This is in relation to the solution posted here: How to push data from a csv::StringRecord to each column vector in a struct?
I just changed the csv data to match my own csv.
extern crate csv;
use std::error::Error;
use csv::StringRecord;
#[derive(Debug)]
struct DataFrame {
header: csv::StringRecord,
date: Vec<String>,
close: Vec<f32>,
volumn: Vec<f32>,
open: Vec<f32>,
high:Vec<f32>,
low: Vec<f32>,
}
impl DataFrame {
fn new() -> DataFrame {
DataFrame {
header: csv::StringRecord::new(),
date: Vec::new(),
close: Vec::new(),
volumn: Vec::new(),
open: Vec::new(),
high: Vec::new(),
low: Vec::new(),
}
}
fn read_csv(filepath: &str, has_headers: bool) -> DataFrame {
// Open file
let file = std::fs::File::open(filepath).unwrap();
let mut rdr = csv::ReaderBuilder::new()
.has_headers(has_headers)
.from_reader(file);
let mut data_frame = DataFrame::new();
// push all the records
for result in rdr.records().into_iter() {
let record = result.unwrap();
data_frame.push(&record);
}
return data_frame;
}
fn push(&mut self, row: &csv::StringRecord) {
self.date.push(row[0].to_string());
self.close.push(row[1].parse().unwrap());
self.volumn.push(row[2].parse().unwrap());
self.open.push(row[3].parse().unwrap());
self.high.push(row[4].parse().unwrap());
self.low.push(row[5].parse().unwrap());
}
}
fn main() {
let data = DataFrame::read_csv("path to file", true);
println!("{:?}", data)
}
sample csv:
Date,Close/Last,Volume,Open,High,Low
08/19/2022,$171.52,70346300,$173.03,$173.74,$171.3101
08/18/2022,$174.15,62290080,$173.75,$174.9,$173.12
08/17/2022,$174.55,79542040,$172.77,$176.15,$172.57
08/16/2022,$173.03,56377050,$172.78,$173.71,$171.6618
But when I try to run it with my CSV file I keep getting this error:
~/rust/vectors/target/debug$ ls
build deps examples HistoricalData_1661097361659.csv incremental vectors vectors.d
~/rust/vectors/target/debug$ ./vectors < HistoricalData_1661097361659.csv
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:34:51
~/rust/vectors/target/debug$ ./vectors HistoricalData_1661097361659.csv
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:34:51
As you can see the file HistoricalData_xxxx.csv is really there. but whenever I try to run the code it always says 'no such file or directory' and i can't see why.
At no point are you taking any argument from the command line. The code only says "path to file" instead of actually passing a filename.
Have a look at the Rust book to find how to parse the argument and pass it to the function instead.
https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html
I have some code which needs to perform an asynchronous operation on a PathBuf variable, but the rust compiler keeps giving me the error message creates a temporary which is freed while still in use, with the explanation temporary value is freed at the end of this statement.
Here is my code:
use std::path::Path;
#[allow(unused_imports)]
use iced::{
alignment, button, scrollable, slider, text_input, Alignment, Button, Checkbox, Color, Column,
Command, Container, ContentFit, Element, Image, Length, Radio, Row, Sandbox, Scrollable,
Settings, Slider, Space, Text, TextInput, Toggler,
};
use faerber::palettize;
use native_dialog::FileDialog;
pub fn main() -> iced::Result {
Faerber::run(Settings::default())
}
#[derive(Debug)]
enum Faerber {
Fresh { upload: button::State },
Finished { upload: button::State },
}
#[derive(Debug, Clone)]
enum Message {
Completed(Result<(), Error>),
ButtonPressed,
}
impl Sandbox for Faerber {
type Message = Message;
fn new() -> Self {
Self::Fresh {
upload: button::State::new(),
}
}
fn title(&self) -> String {
String::from("Farbenfroh")
}
fn update(&mut self, message: Self::Message) {
match message {
Message::ButtonPressed => {
println!("Button pressed");
let path = FileDialog::new()
.set_location("~")
.add_filter("PNG Image", &["png"])
.add_filter("JPEG Image", &["jpg", "jpeg"])
.show_open_single_file()
.unwrap();
match path {
Some(ref path) => {
println!("File selected: {:?}", path);
//palettize(path.to_str(), "latte", "result.png");
}
None => return,
};
let newpath = Path::new(&path.unwrap());
Command::perform(magic(newpath.to_str()), Message::Completed);
}
Message::Completed(Ok(())) => {
*self = Self::Finished {
upload: button::State::new(),
}
}
Message::Completed(Err(_error)) => {
*self = Self::Fresh {
upload: button::State::new(),
};
println!("An error occured.");
}
}
}
fn view(&mut self) -> Element<Self::Message> {
let content = match self {
Self::Fresh { upload } => Column::new()
.padding(20)
.align_items(Alignment::Center)
.push(Text::new("faerber!").size(100))
.push(Button::new(upload, Text::new("Upload")).on_press(Message::ButtonPressed)),
Self::Finished { upload } => Column::new()
.padding(20)
.align_items(Alignment::Center)
.push(Text::new("faerber!").size(100))
.push(Button::new(upload, Text::new("Upload")).on_press(Message::ButtonPressed))
.push(Image::new("result.png")),
};
Container::new(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
}
}
async fn magic(path: Option<&str>) -> Result<(), Error> {
palettize(path.unwrap(), "latte", "result.png");
Ok(())
}
#[derive(Debug, Clone)]
enum Error {
APIError,
LanguageError,
}
The error itself occurs at line 60, where the unwrapped path is sent to the magic function. The palettize function simply takes the image and performs a few operations on it, before saving it to a result.png file.
I am learning Rust. This is the code I'm running
Struct Object {
width: u32,
height:u32,
}
impl Object {
fn area(&slef) --> u32 {
}
fn new(width: u32, height: u32) --> Object {
Object {
width,
height,
}
}
}
fn main() {
let o = Object {
width: 35,
height: 55,
};
let obj = Object ::new(57,83);
println!("{}x{} with area: {}", o.width, o.height, o.area());
println!("{}x{} with area: {}", obj.width, obj.height, obj.area());
This the error I receive. Any help would be greatly appreciated.
PS C:\Users\Jessica\play_ground> cargo new play_ground --bin
warning: compiling this new package may not work due to invalid workspace configuration
failed to parse manifest at `C:\Users\Jessica\Cargo.toml`
Caused by:
no targets specified in the manifest
either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section must be present
Created binary (application) `play_ground` package
PS C:\Users\Jessica\play_ground> cargo run
error: failed to parse manifest at `C:\Users\Jessica\Cargo.toml`
Caused by:
no targets specified in the manifest
either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section must be present
PS C:\Users\Jessica\play_ground
Your code have some syntax errors, should be something like this
struct Object {
width: u32,
height:u32
}
impl Object {
fn area(&self) -> u32 {
self.width * self.height
}
fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
}
}
}
fn main() {
let o = Object {
width: 35,
height: 55,
};
let obj = Object ::new(57,83);
println!("{}x{} with area: {}", o.width, o.height, o.area());
println!("{}x{} with area: {}", obj.width, obj.height, obj.area());
}
You can try it in playgound online https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1c4f18874d42608a35b7e825aaf19619
Or in your computer you run:
cargo init atest
cd atest
[code, notepad, or your prefer editor] src/main.rs "update main.rs
cargo run
I have been trying to write some data with struct type to solana blockchain but have been stuck at an error which says ->
Transaction simulation failed: Error processing Instruction 0: Program failed to complete
Program 2qCpEJASM553foMRmd4MHRLxEFywKwvaUXRtypXJp4zv invoke [1]
Program consumption: 199505 units remaining
Program log: Instruction_data message object LoveRecord { groom: "a", created_on: "0" }
Program log: libstd rust_begin_panic
Program log: panicked at 'called `Option::unwrap()` on a `None` value', src/lib.rs:67:98
Program 2qCpEJASM553foMRmd4MHRLxEFywKwvaUXRtypXJp4zv consumed 200000 of 200000 compute units
Program failed to complete: BPF program panicked
Program 2qCpEJASM553foMRmd4MHRLxEFywKwvaUXRtypXJp4zv failed: Program failed to complete
Code for solana program entrypoint in Rust language is ->
use borsh::{ BorshDeserialize, BorshSerialize };
use solana_program::{
account_info::{ next_account_info, AccountInfo },
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
pubkey::Pubkey,
};
use std::io::ErrorKind::InvalidData;
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct LoveRecord {
pub groom: String,
pub created_on: String
}
const DUMMY_TX_ID: &str = "a";
const DUMMY_CREATED_ON: &str = "0"; // milliseconds, 16 digits
pub fn get_init_love_record() -> LoveRecord {
LoveRecord{ groom: String::from(DUMMY_TX_ID), created_on: String::from(DUMMY_CREATED_ON) }
}
pub fn get_init_love_records() -> Vec<LoveRecord> {
let mut records = Vec::new();
for _ in 0..10 {
records.push(get_init_love_record());
}
return records;
}
entrypoint!(process_instruction);
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8]
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let account = next_account_info(accounts_iter)?;
if account.owner != program_id {
msg!("Greeted account does not have the correct program id");
return Err(ProgramError::IncorrectProgramId);
}
let instruction_data_message = LoveRecord::try_from_slice(instruction_data).map_err(|err| {
msg!("Attempt to deserialize instruction data has failed. {:?}", err);
ProgramError::InvalidInstructionData
})?;
solana_program::msg!("pass");
msg!("pass");
msg!("Instruction_data message object {:?}", instruction_data_message);
let mut existing_data_messages = match <Vec<LoveRecord>>::try_from_slice(&account.data.borrow_mut()) {
Ok(data) => data,
Err(err) => {
if err.kind() == InvalidData {
msg!("InvalidData so initializing account data");
get_init_love_records()
} else {
msg!("Unknown error decoding account data {:?}", err)
}
}
};
let index = existing_data_messages.iter().position(|p| p.groom == String::from(DUMMY_TX_ID)).unwrap(); // find first dummy data entry
msg!("Found index {}", index);
existing_data_messages[index] = instruction_data_message; // set dummy data to new entry
let updated_data = existing_data_messages.try_to_vec().expect("Failed to encode data."); // set records object back to vector data
msg!("Final existing_data_messages[index] {:?}", existing_data_messages[index]);
// data algorithm for storing data into account and then archiving into Arweave
// 1. Each LoveRecord object will be prepopulated for txt field having 1 characters (length of a arweave tx).
// Each LoveRecordContainer will be prepopulated with 10 LoveRecord objects with dummy data.
// 2. Client will submit an arweave tx for each message; get back the tx id; and submit it to our program.
// 3. This tx id will be saved to the Solana program and be used for querying back to arweave to get actual data.
let data = &mut &mut account.data.borrow_mut();
msg!("Attempting save data.");
data[..updated_data.len()].copy_from_slice(&updated_data);
let saved_data = <Vec<LoveRecord>>::try_from_slice(data)?;
msg!("LoveRecord has been saved to account data. {:?}", saved_data[index]);
msg!("End program.");
Ok(())
}
Code to send transaction using Borsch Serialize is ->
static async sayHello(data) {
let config = DappLib.getConfig();
console.log(data);
let DUMMY_TX_ID = "a";
let DUMMY_CREATED_ON = "0";
class LoveRecord {
constructor(fields = undefined) {
this.groom = DUMMY_TX_ID;
this.created_on = DUMMY_CREATED_ON; // max milliseconds in dat
if (fields) {
this.groom = fields.groom;
this.created_on = fields.created_on;
}
}
}
const LoveRecordSchema = new Map([[
LoveRecord,
{
kind: "struct",
fields: [
["groom", "string"],
["created_on", "string"],
],
},
]]);
const loveobj = new LoveRecord();
loveobj.groom = "a";
loveobj.created_on = "0";
const res = borsh.serialize(LoveRecordSchema,loveobj);
let result = await Blockchain.put({ config }, 'greeting', res);
console.log("Pass")
return {
type: DappLib.DAPP_RESULT_OBJECT,
label: 'Transaction Result',
result
}
}
Code to send and sign transaction has been taken care of.
Any help would be really appreciated.
This is quite a specific question around your code, but the error message is probably the best place to look:
Program log: panicked at 'called `Option::unwrap()` on a `None` value', src/lib.rs:67:98
This seems to correspond with the line:
let index = existing_data_messages.iter().position(|p| p.groom == String::from(DUMMY_TX_ID)).unwrap();
You're calling unwrap() on a None value, which makes sense, considering nothing has been written to this account before. You'll need to handle the case where DUMMY_TX_ID is not found in your vector.
You can find more information about how position() works at https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.position