Getting array only from one variable that belongs to enum and is included in struct within array - Swift
In original example code there was no struct TokenStruct that now except of var tokens includes also var position to track/associate error positions with existing error cases. Figuring out what change/s do I have to do related to print("Lexer output: (tokens)") when I want that it prints "Lexer output: [Number: 10, Symbol: +, Number: 11]", without position. I tried approach described on How do I access variables in an array of type struct in Swift? however could not figure it out during stage - assigning name found in another list, using subscript syntax. Original example code:
enum Token0: CustomStringConvertible {
case number (Int)
case plus
var description: String {
switch self {
case .number (let n):
return "Number: \(n)"
case .plus:
return "Symbol: +"
}
}
}
var tokens0 = [Token0]()
var value0 = 10
tokens0.append(.number(value0))
tokens0.append(.plus)
value0 = 11
tokens0.append(.number(value0))
print("Lexer0 output: \(tokens0)")
Below code with struct TokenStruct. What change/s to do related to print("Lexer output: (tokens)") when I want that it prints "Lexer output: [Number: 10, Symbol: +, Number: 11]", without position.
enum Token: CustomStringConvertible {
case number (Int)
case plus
var description: String {
switch self {
case .number (let n):
return "Number: \(n)"
case .plus:
return "Symbol: +"
}
}
}
struct TokenStruct {
var token: Token
var position: Int
}
var tokens = [TokenStruct]()
var posChar = 0
var value = 10
tokens.append(TokenStruct(token: .number(value), position: posChar))
posChar = 1
tokens.append(TokenStruct(token: .plus, position: posChar))
posChar = 2
value = 11
tokens.append(TokenStruct(token: .number(value), position: posChar))
print("Lexer output: \(tokens)")
do you know?
how many words do you know
See also questions close to this topic
-
How to get pass an array through a function with a user input?
I want to ask the user for the size of a 2D array arr[][], but also pass it through the function initializeArray. However, if I pass it through the function, I would have to have a size declarator for col, which doesn't allow the user to enter their own value for the size
#include<iostream> using namespace std; void initializeArray(arr[][10], int N); int main() { int N; cout << "enter an array size: "; cin >> N; int arr[N][N]; initializeArray(arr, N); // I get an error here for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) cout << arr[i][j] << " "; cout << endl; } } void initializeArray(int arr[][10], int N) { for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) arr[i][j] = 0; }
The only solution I found was the make arr[][] a global array, but in that case, I would have to still declare the size parameters, and I want the user to enter whatever they want. Is there another way to fix this?
-
Two-dimensional array C++
Problem: Write a program of a two dimensional integer array of exactly four rows and four columns, and find the sum of the integers each row of the array as well as determine the smallest inputted element/data in the array. The user will input the elements. Display the elements in tabular form. Make the program user friendly. Use a Class and a member function for the process involve.
-
Pass Associative Array from Symfony Controller to Twig and JavaScript
So, I have 2 arrays that I've combined into one array after making sure they're the same length as such.
//Fetching Ratings for All Coaches & Making a Key, Value Associative Array with Coach id as Key and Rating as Value $coaches = $coachRepository->findAll(); $rating = $coachRepository->findRatingByCoach(); //Array of coach IDs $id_array = array(); foreach ($coaches as $c){ $id_array[] = $c->getId(); } $combined = array_combine($id_array, $rating);
Now I want to pass this key, value array to Twig template and JavaScript. I'm currently doing this
return $this->render('...', [ ..., 'combined'=>$combined ]);
And I'm accessing the array in Twig as such
{% for key, value in combined %} {{ key }} - {{ value }} {% endfor %}
And I'm getting this error.
Object of class App\Entity\Coach could not be converted to string
Looking at the Stack Trace I can see that the array combined is being passed in this form.
'combined' => array(object(Coach))
After a bit of debugging it turns out that I thought the issue was with the $
id_array
when in fact it's the $rating
variable that's presenting an issue. I'm not sure why but I'm getting a single float value. I fixed the issue by changing how I'm fetching the $rating, now instead of using a QueryBuilder to get it from the DB, I'm getting it from list of Coaches as such//Array of coach IDs and array of Ratings $id_array = array(); $rating_array = array(); foreach ($coaches as $c){ $id_array[] = $c->getId(); $rating_array [] = $c->getRating(); }
Even if I set the array
-
SwiftUI, apply drawGesture only when over Image
I'm try to apply the gesture only when the user is over the Image display not when tapped outside the image.
Any suggestion how I can do? this following code draw also when user tap outside the image.
struct ContentView: View { @StateObject var am = AppManager() @State var switchToTakePicture = false @State var paths: [PathContainer] = [] @State var currentDraggingId = UUID() @State var spikoPic = #imageLiteral(resourceName: "spiko-16.jpeg") @State var centerOFimage = CGSize(width: 0, height: 0) var body: some View { GeometryReader { proxy in ZStack { Image(uiImage: spikoPic) .resizable() .scaledToFit() .position(x: proxy.size.width/2, y: proxy.size.height/2) .background(GeometryReader { Color.clear.preference(key: ViewRectKey.self, value: [$0.frame(in: .global)]) }) .gesture(drawGesture) // not correct ForEach(paths) { container in // draw and set the foreground color of the paths to red container.path .stroke(Color.red, lineWidth: 4) } } .onPreferenceChange(ViewRectKey.self) { rects in print(rects.first ?? .zero) } } } var drawGesture: some Gesture { DragGesture(minimumDistance: 0) .onChanged { value in // The point that the gesture started from let start = value.startLocation // The point that the gesture ended to let end = value.location // the properties of the rectangle to be drawn let rectangle: CGRect = .init(origin: end, size: .init(width: start.x - end.x, height: start.y - end.y)) // create a path for the rectangle let path: Path = .init { path in path.addRect(rectangle) } print("rettangolo = \(rectangle) orig \(rectangle.origin) - height \(rectangle.height) width = \(rectangle.width)") // remove the previous rectangle that was drawen in current // process of drawing paths.removeAll { $0.id == currentDraggingId } // append the new rectangle paths.append(.init(id: currentDraggingId, path: path)) } .onEnded { _ in // renew the dragging id so the app know that the next // drag gesture is drawing a completely new rectangle, // and is not continuing the drawing of the last rectangle currentDraggingId = .init() } } }
i want no box outside
-
How to navigate between NavigationLink while leave a part of main window stay the same in SwiftUI
I would like to navigate between different
NavigationLink
s inNavigationView
while some part of the main window stay the same. For example, I want to make a music app and I want to let the play controller always on top, while I can display different navigation contents (songs page, artists page...) using the rest of the window.Like what's showed in the picture below, I want to keep the red part always there while the blue part changes.
My code would be like below, but it won't work correctly. The
AlwaysStayView()
disappears when I click anyNavigationLink
on sidebar. So, how can I correct it or is there any solution (prefer in SwiftUI, but framework like UIKit would also be OK). I would appreciate it.NavigationView { List { NavigationLink { DiscoverView() } label: { Label("Discover", systemImage: "magnifyingglass") } NavigationLink { SongsView() } label: { Label("Songs", systemImage: "music.note") } NavigationLink { ArtistsView() } label: { Label("Artists", systemImage: "music.mic") } } } .listStyle(SidebarListStyle()) VStack { AlwaysStayView() SongsView() } }
-
NumberFormatter and unsigned with UInt64.max
I'm trying to create a string representing
UInt64.max
usingNumberFormatter
. Here's the code:let formatter = NumberFormatter() formatter.usesGroupingSeparator = true formatter.numberStyle = .decimal formatter.positiveFormat = "# ##0.#########" formatter.maximumSignificantDigits = 20 formatter.usesSignificantDigits = false formatter.maximumFractionDigits = 20 formatter.minimumFractionDigits = 0 formatter.alwaysShowsDecimalSeparator = false // formatter.roundingMode = .halfUp let text1 = formatter.string(for: NSNumber(value: Int64.max)) let text2 = formatter.string(for: NSNumber(value: UInt64.max)) print(text1) print(text2)
which prints:
Optional("9,223,372,036,854,780,000")
Optional("-1")but should print
Optional("9223372036854775807")
Optional("18,446,744,073,709,551,615")It looks like
NSNumber
is roundingInt64
and isn't taking theUIn64
. The obj-c version ofNSNumberFormatter
works fine.Am I missing something or is there a problem with
NumberFormatter
? - Broken project in XCODE objective c
-
Lokalise: How to change default NSStringFormatValueTypeKey
The default
NSStringFormatValueTypeKey
property in Lokalise always returns the stringli
. In my code, the stringd
.When exporting the modified stringsdict file from Lokalise to Github, the
NSStringFormatValueTypeKey
is alwaysli
. Currently, there is no way to change this hardcoded value in the Lokalise platform. What is a trick to change the value besides manually changing them in the stringsdict file in Xcode? I want to change the value tod
Export from Lokalise:
<key>plural.day</key> <dict> <key>NSStringLocalizedFormatKey</key> <string>%#@day@</string> <key>day</key> <dict> <key>NSStringFormatSpecTypeKey</key> <string>NSStringPluralRuleType</string> <key>NSStringFormatValueTypeKey</key> <string>li</string> <key>one</key> <string></string> <key>other</key> <string></string> </dict> </dict>
Desired outcome:
<key>plural.day</key> <dict> <key>NSStringLocalizedFormatKey</key> <string>%#@day@</string> <key>day</key> <dict> <key>NSStringFormatValueTypeKey</key> <string>d</string> <key>NSStringFormatSpecTypeKey</key> <string>NSStringPluralRuleType</string> <key>one</key> <string>%d day ago</string> <key>other</key> <string>%d days ago</string> </dict> </dict>
-
Xcode clean build folder command not working
Not sure what happened but suddenly, my xcode clean build folder option under Product -> Clean Build Folder no longer works. Instead it gives me an error:
Could not delete
/Users/...build
because it was not created by the build system.Is there a way I can reset the xcode settings? Or does someone have any idea how to fix this?
-
golang: BaseRepository usage with different struct return type
I have the following code with two repositories that have the same functionality but different return types. I want to call the
findAll
method from theBaseRepository
to prevent writing the same logic for fetching entries multiple times. I want to keep different return types. Is this possible?Currently I get the following error (in the
UserRepository
):// Error: cannot use r.baseRepository.FindAll(user) (value of type []interface{}) as []User
I understand the problem, but is there an easy solution for that? Maybe I have to use another approach?
package main type Address struct { street string } type User struct { Firstname string Lastname string } // BaseRepository type BaseRepository struct{} func (r *BaseRepository) FindAll(dest interface{}) []interface{} { // Return []Address or []User return []interface{}{} } // UserRepository type UserRepository struct { baseRepository *BaseRepository } func (r *UserRepository) FindAll() []User { var user User return r.baseRepository.FindAll(user) // Error: cannot use r.baseRepository.FindAll(user) (value of type []interface{}) as []User value in return statement } // AddressRepoistory type AddressRepository struct { baseRepository *BaseRepository } func (r *AddressRepository) FindAll() []Address { var address Address return r.baseRepository.FindAll(address) // Error: cannot use r.baseRepository.FindAll(address) (value of type []interface{}) as []Address value in return statement } func main() { }
-
C: get sizeof typedef struct array inside of function when passed as parameter
I have a bit of code here that I wrote that demonstrates a problem I am having.
I am getting a different value for sizeof when I do sizeof of a pointer that represents a struct array. I think that when I do sizeof inside the function, it is just the sizeof the pointer, rather than the sizeof the array itself.
so here is my question: Is there any way to get the sizeof of a typedef struct array from inside of a function when it is passed in as a pointer?
#include <printf.h> typedef struct { int value_1; int value_2; } example_struct_t; example_struct_t struct_a[] = { { .value_1 = 4, .value_2 = 0, }, { .value_1 = 8, .value_2 = 9, }, }; void printsizeof(example_struct_t *struct_array){ printf("size of struct_array inside func: %lu\r\n", sizeof struct_array); } int main() { printf("This demo shows that a typedef struct array shows a different size inside of main vs inside of a function:\r\n"); printf("sizeof struct_array outside func: %lu\r\n", sizeof struct_a); printsizeof(struct_a); return 1; }
this is how it is compiled and the terminal output:
~/ ❯ gcc -std=c99 -Wall -Wextra -Wpedantic -Werror struct_size_bug.c -o struct_size_bug ~/ ❯ ./struct_size_bug This demo shows that a typedef struct array shows a different size inside of main vs inside of a function: sizeof struct_array outside func: 16 size of struct_array inside func: 8
-
How do I know which endian to use in struct.unpack() when converting hexadecimal string to float?
I have data in form of hexadecimal string and I convert it to float as:
import struct, binascii a = '0X437A1AF6' x = struct.unpack('>f', binascii.unhexlify(str(a)[2:])) print(x[0])
I get the right result but How do I prove that using big endian '>f' is right choice or how do I determine what endian to use in general? Trial an error is one option but what are other?
-
Create macro to simplify declaration of deeply nested enum?
I want to use deeply nested enums to represent blocks in my game:
enum Element { Void, Materal(Material) } enum Material { Gas(Gas), NonGas(NonGas) } enum NonGas { Liquid(Liquid), Solid(Solid) } enum Solid { MovableSolid(MovableSolid), ImmovableSolid(ImmovableSolid) } enum Gas { Smoke } enum Liquid { Water } enum ImmovableSolid { Bedrock } enum MovableSolid { Sand, GunPowder }
I found it very verbose to declare an
Element
:let block: Element = Element::Materal(Material::NonGas(NonGas::Solid(Solid::ImmovableSolid(ImmovableSolid::Bedrock))));
Is it possible to create a macro to add syntactic sugar for my enum declaration?
I'm hoping to create a macro that can automagically resolve the enum path, for example
let block: Element = NewElement!(ImmovableSolid::Bedrock);
-
Is there a solution for a bitwise logical AND (&) operator between two Enum values in C#
Consider the following simple Flags Enum in C#:
[Flags] public enum CountingEnum { Zero = 0, One = 1 << 0, Two = 1 << 1, Three = Two | One, Four = 1 << 2, Five = Four | One, }
If I want to know whether one value contains another, I can write a simple extension method using the bitwise logical AND (&) operator:
public static class CountingEnumExtensions { public static bool Contains(this CountingEnum value, CountingEnum target) { return (value & target) == target; } }
This lends itself to a clean syntax for checking if one Flags value contains another:
if (CountingEnum.Five.Contains(CountingEnum.Four)) { // Yep! } if (CountingEnum.Four.Contains(CountingEnum.Five)) { // Nope! }
But what if I have another Flags Enum? I could make another extension method each time I want to do this, but that isn't very sustainable. I could just manually use this everywhere, but it isn't very readable for the bitwise non-literate:
if ((SomeEnum.Value & SomeEnum.Target) == SomeEnum.Target) { // Dunno! }
But is there a general solution? The following will not compile, of course, but it conveys the idea of what I'd like to have:
public static class EnumExtensions { public static bool Contains(this Enum value, Enum target) { // Cannot apply operation '&' to operands of // type 'System.Enum' and 'System.Enum' return (value & target) == target; } }
Is there a general solution to perform a bitwise logical AND against any two Flags Enum values of matching type?
-
Is there a neat way of converting lists into maps with the keys set to the elements of original collection and values set to an enum in java
Java newbie... I have a dictionary like so:
electronictypeModelsMap = { "laptops" => ["macbook", "thinkpad", "yoga"], "desktops" => ["macmini", "imac", "otherDesktop"], "smartphones" => ["iphone", "galaxy5", "oneplus"] }
There will only ever be a small number of keys like the 3 above but there will be a few hundred elements in each value (list)....
I want to be able to query it the other way around so :
dictionary.get("macbook")
would return "laptops"So I guess I want to convert into a new map with each element of each list as a key with the corresponding value set to the original key. like this:
{ "macbook" => "laptops", "thinkpad" => "laptops", "yoga"=> "laptops", "macmini" => "desktops", "imac" => "desktops", "otherDesktop" => "desktops", "iphone" => "smartphones", "galaxy5" => "smartphones", "oneplus" => "smartphones", }
Is there a neat way of doing this in Java 11?
In ruby you could do something like this
newMap = Hash.new electronictypeModelsMap.each do |k,v| v.each do |value| newMap[value] = k end end