Rust PathBuf issues when building relative dir from home - rust

static CONFIG_FILE: &str = "/.config/myapp/config.toml";
but I want to build an os agnostic path:
$HOME/.config/myapp/config.toml
Tried variations of:
static CONFIG_FILE: &str = dirs::home_dir().unwrap().join(".config").join("myapp").join("config.toml").to_str().unwrap();
but I get:
|
28 | static CONFIG_FILE: &str = dirs::home_dir().unwrap().join(".config").join("myapp").join("config.toml").to_str().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `~const Deref` is not implemented for `PathBuf`
The following seems to compile however the end part of the path is not platform agnostic.
/// Application configuration filename
static HOME: Lazy<String> = Lazy::new(|| { env::var("HOME").unwrap() } );
static CONFIG_FILE: Lazy<PathBuf> = Lazy::new(||{Path::new(&HOME.as_str()).join(".config/assimilate/config.toml")});

Try this:
static CONFIG_FILE: Lazy<PathBuf> = Lazy::new(||{dirs::home_dir().unwrap().join(".config").join("myapp").join("config.toml")});

Related

How can I rectify static scope error when referencing a static variable in my groovy script?

I have a script which exports excel worksheets to csv, and I am attempting to escape commas, quotes and the like. I have created a static method that encodes the value of the cell being accessed. This method references a static variable which stores a Pattern.compile() value.
I have tried using def rxquote within the method but this gives me a different error stating that using static modifier before declaring my rxquote variable is illegal. Code is below followed by error message.
#!/usr/bin/env groovy
#Grab(group = 'org.apache.poi', module = 'poi', version = '4.1.0')
#Grab(group = 'org.apache.poi', module = 'poi-ooxml', version = '4.1.0')
import java.util.regex.*
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.apache.poi.ss.usermodel.*
static Pattern rxquote = Pattern.compile("\"")
static private String encodeValue(String value) {
boolean needQuotes = false;
if ( value.indexOf(',') != -1 || value.indexOf('"') != -1 ||
value.indexOf('\n') != -1 || value.indexOf('\r') != -1 ){
needQuotes = true;
}
Matcher m = rxquote.matcher(value)
if ( m.find() ) {
needQuotes = true
value = m.replaceAll("\"\"")
}
if ( needQuotes ) {
return "\"" + value + "\""
}
else return value;
}
//for(){
// ... export csv code (which works on its own)
//}
Error message on compile:
Apparent variable 'rxquote' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'rxquote' but left out brackets in a place not allowed by the grammar.
# line 27, column 17.
Matcher m = rxquote.matcher(value);
^
I've tried researching the issue and have found several similar questions here, but none of the solutions appear to apply to this situation as far as I can tell. I expected a static declaration of the variable to avoid this problem, but it seems there's something I'm missing.
you can't declare static variable in groovy script.
it's allowed only in groovy/java class.
error does not correspond to situation.
should be : Modifier 'static' not allowed here.
as workaround for static variables you can use some class:
class Const{
static String bar = 'test'
}
static private String foo() {
return Const.bar
}
foo()

Storing associated variables

I have around 30 api's in my application and each api url has associated custom error code and error message . For now, I have them all in constants , ungrouped. What is the best way to group them.. like to use structs? or enums? Any suggestion is appreciated. Thanks!
class ApplicationAPIS {
My_API1 {
static let API_URL = "http:www.google.com"
static let API_CODE = "ER0012"
static let API_ERROR_MSG = "Cannot Load URL" }
My_API2{
static let API_URL = "http:www.google.com"
static let API_CODE = "ER0012"
static let API_ERROR_MSG = "Cannot Load URL" }
.
.
.
}
The usual thing for constant strings (such as keys into UserDefaults, etc.) is a struct with static constant properties. For example:
struct My_API1 {
static let API_URL = "http:www.google.com"
static let API_CODE = "ER0012"
static let API_ERROR_MSG = "Cannot Load URL"
}
Now you can speak of e.g. My_API1.API_URL from anywhere in your program.
However, if these really are always errors, then you might be happier making these the cases of an enum that conforms to the Error type.
enum My_API1 : String, Error {
case API_URL = "http:www.google.com"
case API_CODE = "ER0012"
case API_ERROR_MSG = "Cannot Load URL"
}

Swift 4.1 Failed to get a bitmap representation of this NSImage

This code sample was working in a macOS playground:
import Cocoa
import XCPlayground
func getResImg(name: String, ext: String) -> CIImage {
guard let fileURL = Bundle.main.url(forResource: name, withExtension: ext) else {
fatalError("can't find image")
}
guard let img = CIImage(contentsOf: fileURL) else {
fatalError("can't load image")
}
return img
}
var img = getResImg(name: "noise", ext: "jpg")
After upgrading to Swift 4.1 it doesn't. Error: Failed to get a bitmap representation of this NSImage.
How does it work now in Swift 4.1?
I ran into the same issue even though I was using a macOS project and wasn't able to pinpoint what's going wrong here, but I found a workaround which fixes playground rendering for CIImage by using a CustomPlaygroundDisplayConvertible
Just add the following code to the top of your playground and your images will render again
extension CIImage: CustomPlaygroundDisplayConvertible {
static let playgroundRenderContext = CIContext()
public var playgroundDescription: Any {
let jpgData = CIImage.playgroundRenderContext.jpegRepresentation(of: self, colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, options: [:])!
return NSImage(data: jpgData)!
}
}

Why is the struct unknown at compiletime in the code?

I was wondering how I could change the code below such the bmBc is computed at compile time . The one below works for runtime but it is not ideal since I need to know the bmBc table at compile-time . I could appreciate advice on how I could improve on this.
import std.conv:to;
import std.stdio;
int [string] bmBc;
immutable string pattern = "GCAGAGAG";
const int size = to!int(pattern.length);
struct king {
void calculatebmBc(int i)()
{
static if ( i < size -1 )
bmBc[to!string(pattern[i])]=to!int(size-i-1);
// bmBc[pattern[i]] ~= i-1;
calculatebmBc!(i+1)();
}
void calculatebmBc(int i: size-1)() {
}
}
void main(){
king myKing;
const int start = 0;
myKing.calculatebmBc!(start)();
//1. enum bmBcTable = bmBc;
}
The variables bmBc and bmh can't be read at compile time because you define them as regular runtime variables.
You need to define them as enums, or possibly immutable, to read them at compile time, but that also means that you cannot modify them after initialization. You need to refactor your code to return values instead of using out parameters.
Alternatively, you can initialize them at runtime inside of a module constructor.

Swift - accessing structs

If I have a struct defined like this:
struct Cat {
static let Siamese = "Siamese"
static let Tabby = "Tabby"
static let Fluffy = "Fluffy"
static func cat () -> [String] {
return [Siamese, Tabby, Fluffy]
}
}
Why can't I access it like this?
var cat:Cat = Cat.Siamese //"NSString" is not a subtype of Cat
You are trying to assign a String to a variable defined as a Cat. That is why you are getting an error.
All of your static members in your Cat struct are strings, not Cats.
Also, your struct doesn't have any actual members. I think you are intending to have a name property:
struct Cat {
let name: String
static let Siamese = Cat(name: "Siamese")
static let Tabby = Cat(name: "Tabby")
static let Fluffy = Cat(name: "Fluffy")
}
var cat : Cat = Cat.Siamese
You may be better served with an enum:
enum Cat : String {
case Siamese = "Siamese"
case Tabby = "Tabby"
case Fluffy = "Fluffy"
}
var cat: Cat = .Tabby
println(cat.toRaw()) // "Tabby"

Resources