How can I force clang-format to indent struct field initializers consistently regardless of length? - clang-format

Consider the following two formats.
const struct CanFrames_FrameMetaData BCM_Status_metaData = {.dlc = BCM_Status_DATA_LENGTH,
.getPeriodicTxEnabled = KamagBattery_IsPeriodicTxEnabled34343,
.txInterval_ms = 50,
.txHoldoff_ms = 0,
.rxTimeout_ms = 1000};
const struct J1939_PgnMetaData J1939PropData1_metaData = {
.pgnId = 0xFF01U, // J1939 PGN "Proprietary B, Group 1"
.priority = J1939_COMMAND_PRIO, // Deviation from J1939 default for backwards compatibility
.pgnLength = J1939PropData1_DATA_LENGTH,
.getDynamicLength = NULL,
.getPeriodicTxEnabled = NULL,
.txInterval_ms = 50,
.txHoldoff_ms = 0,
.rxTimeout_ms = 0};
Which one clang-format produces seems to depend on the length of the fields, init values and comments. How can I force clang-format to always use the latter?

Related

Generation of types in zig (zig language)

Is it possible to create a comptime function in zig that would generate a new struct type? The function would receive an array of strings and an array of types. The strings are the names of subsequent struct fields.
This has been implemented now as https://github.com/ziglang/zig/pull/6099
const builtin = #import("std").builtin;
const A = #Type(.{
.Struct = .{
.layout = .Auto,
.fields = &[_]builtin.TypeInfo.StructField{
.{ .name = "one", .field_type = i32, .default_value = null, .is_comptime = false, .alignment = 0 },
},
.decls = &[_]builtin.TypeInfo.Declaration{},
.is_tuple = false,
},
});
test "" {
const a: A = .{ .one = 25 };
}
The TypeInfo struct is defined here.
Partially. This has been long proposed at https://github.com/ziglang/zig/issues/383
You can only do so with fields, not with custom decls.

Haskell: Converting a .lua table to Haskell workable types

I'm a beginner trying to practice coding haskell by translating some simple repo from different languages to Haskell.
Many simple games use .lua to store character/ability data.
What I want is to take that .lua table and convert it into haskell workable types.
This is what the .lua file looks like
local Data =
{
["Weapons"] = {
["AB"] = {
Name = "AB",
Cost = {
Spells = 65000,
BCost = 15000,
MCost = 150,
sh = 35,
Time = 24,
Parts = {
{ Name = "Top",Type = "Item",Count = 1,},},
},
Resist = 0.85,
Class = "Shield",
Attack = {
Damage = {
["First"] = 5,
["Second"] = 5,
["Third"] = 40,},
Chance = 0.2,
X = 2,
},
},
["PG"] = {
...
...
...
}
return Data
When woking with Aeson, there's this simple function decode which you can use as decode someJSON :: Maybe Object and get the entirety of JSON file content put in default Aeson datatypes which you can work on with library functions. I haven't been able to find something similar for .lua.

String formatting in Dart

I was looking up string classes and some other resources, trying to see how to format strings. Primarily, I am trying to Pad out a number to a string, but not precision.
example:
int a = 0, b = 5, c = 15, d = 46;
String aout = "", bout = "", cout="", dout="";
//aout = "00"
//bout = "05"
//cout = "15"
//dout = "46"
When i was looking at int to fixed string precision, it was mostly when dealing with decimals and not prepended padding.
My original thought is that I could do something related to sprintf, such as:
String out = sprintf("%02d", a);
but that didnt seem to work, mostly because It was saying that i am getting a nosuchmethod error. I was not sure if sprintf is in a different package other than core, as i thought this would be related directly to strings.
There's a String.padLeft method you can use:
String out = a.toString().padLeft(2, '0');

Swift enum operator overloading

I have define an enum, and I want to use it as a key for a dictionary.
When I'm trying to access a value using the enum as a key, i get an error about the enum not being convertible to DictionaryIndex<Constants.PieceValue, Array<String>> where Constants.PieceValue is an enum that looks like this:
public enum PieceValue: Int {
case Empty = 0,
WKing = 16,
WQueen = 15,
WRook = 14,
WBishop = 13,
WKnight = 12,
WPawn = 11,
BKing = 26,
BQueen = 25,
BRook = 24,
BBishop = 23,
BKnight = 22,
BPawn = 21
}
I read a few threads but haven't found any clear answers.
I also declared the operator overloading function for the enum outside the Constants class.
func == (left:Constants.PieceValue, right:Constants.PieceValue) -> Bool {
return Int(left) == Int(right)
}
This is the line that Xcode complains about:
self.label1.text = Constants.pieceMapping[self.pieceValue][0]
Constants.pieceMapping has the following type: Dictionary<PieceValue, Array<String>>
That's the typical optional problem: when you query a dictionary, it returns an optional value, to account for cases when the key is not found. So this:
Constants.pieceMapping[self.pieceValue]
is of Array<String>? type. In order to access to that array, you first have to unwrap from the optional, using either forced unwrapping:
Constants.pieceMapping[Constants.PieceValue.BPawn]![0]
or in a safer way using optional binding:
if let array = Constants.pieceMapping[Constants.PieceValue.BPawn] {
let elem = array[0]
}

NSDictionary annidate in swift

I have this json result.
I would take the field "alert".
I try this:
var alert: NSString = jsonResult["features"]["properties"]["alert"]
but this is the error: does not have a member named 'subscript'.
I can not how to access a field in a nested dictionary
{
features = (
{
geometry = {
coordinates = (
"-97.95359999999999",
"37.2382",
5
);
type = Point;
};
id = usb000si7g;
properties = {
alert = green;
cdi = "5.8";
code = b000si7g;
detail = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/usb000si7g.geojson";
dmin = "0.017";
felt = 1258;
gap = 38;
ids = ",usb000si7g,";
mag = "4.3";
magType = mwr;
mmi = "4.94";
net = us;
nst = "<null>";
place = "8km SE of Harper, Kansas";
rms = "0.51";
sig = 864;
sources = ",us,";
status = reviewed;
time = 1412272884590;
title = "M 4.3 - 8km SE of Harper, Kansas";
tsunami = "<null>";
type = earthquake;
types = ",cap,dyfi,general-link,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,";
tz = "-300";
updated = 1412614943519;
url = "http://earthquake.usgs.gov/earthquakes/eventpage/usb000si7g";
};
type = Feature;
}
);
metadata = {
api = "1.0.13";
count = 1;
generated = 1412617232000;
status = 200;
title = "USGS Significant Earthquakes, Past Week";
url = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_week.geojson";
};
type = FeatureCollection;
}
I don't know what to do. swift is changed every beta.
As #Kirsteins said is his answer, you have to do a lot of unwrapping, and it's recommended to use a JSON library.
If you still want to stick with hand made extraction, then I suggest you to made it programmatically, such as adding an extension to NSDictionary as follows:
extension NSDictionary {
func objectForTreeKeys<T>(keys:[String]) -> T? {
var dict: NSDictionary? = self
var retValue: T?
for key in keys {
var value: AnyObject? = dict?.objectForKey(key)
if let unwrapped = value as? NSDictionary {
dict = unwrapped
} else if let unwrapped = value as? T {
retValue = unwrapped
break
} else {
retValue = nil
break
}
}
return retValue
}
}
You pass an array of keys to the function, and it traverses all nested dictionaries until:
a value of type T is encountered
a value having type different than NSDictionary and T is found
a nil value is found
In the first case, it returns the value of T type - in the other cases it returns nil.
You can use it as follows:
let ret: String? = jsonResult.objectForTreeKeys(["features", "properties", "alert"])
As you can see, it's a generic method, and the return type is inferred from the type of the variable the result is assigned to - so it's necessary to explicitly define its type, which must be optional (String? in this specific case).

Resources