Apart from using open-source libraries for web and application development, data science, and machine learning, it is also used by hackers and cybersecurity experts to build solutions that can identify a break in computer networks and compromise security protocols. Worldwide ethical hackers employ open-source components to develop effective hacking tools and techniques that can help find malware and vulnerabilities in a digital system, which, if not detected, can lower the system’s efficiency.

Open-source libraries and codes remove the headache of developing code for your applications from scratch. With readily available well-formulated code libraries, developers can easily use them to build ethical hacking solutions. Python is among the most popular open-source programming languages for developing hacking solutions, as it offers excellent versatility and the support of the global open-source community.

Popular New Releases in Hacking

pwntools

Release 4.9.0beta0

Atmosphere

Atmosphère 1.3.1

DOMPurify

DOMPurify 2.3.6

peda

v1.2

gef

2022.01 - Irritating Cookie

Popular Libraries in Hacking

wifiphisher

by wifiphisher doticonpythondoticon

star image 10043 doticonGPL-3.0

The Rogue Access Point Framework

routersploit

by threat9 doticonpythondoticon

star image 9634 doticonNOASSERTION

Exploitation Framework for Embedded Devices

XSStrike

by s0md3v doticonpythondoticon

star image 9515 doticonGPL-3.0

Most advanced XSS scanner.

pwntools

by Gallopsled doticonpythondoticon

star image 8935 doticonNOASSERTION

CTF framework and exploit development library

Atmosphere

by Atmosphere-NX doticonc++doticon

star image 8864 doticonGPL-2.0

Atmosphère is a work-in-progress customized firmware for the Nintendo Switch.

DOMPurify

by cure53 doticonjavascriptdoticon

star image 8441 doticonNOASSERTION

DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks. Demo:

fsociety

by Manisso doticonpythondoticon

star image 6906 doticonMIT

fsociety Hacking Tools Pack – A Penetration Testing Framework

hackingtool

by Z4nzu doticonpythondoticon

star image 6783 doticonMIT

ALL IN ONE Hacking Tool For Hackers

ipwndfu

by axi0mX doticonpythondoticon

star image 6248 doticonGPL-3.0

open-source jailbreaking tool for many iOS devices

Trending New libraries in Hacking

hackingtool

by Z4nzu doticonpythondoticon

star image 6783 doticonMIT

ALL IN ONE Hacking Tool For Hackers

traitor

by liamg doticongodoticon

star image 3789 doticonMIT

:arrow_up: :skull_and_crossbones: Automatic Linux privesc via exploitation of low-hanging fruit e.g. gtfobins, pwnkit, dirty pipe, +w docker.sock

CyberEngineTweaks

by yamashi doticonc++doticon

star image 3705 doticonNOASSERTION

Cyberpunk 2077 tweaks, hacks and scripting framework

MHDDoS

by MHProDev doticonpythondoticon

star image 2416 doticonMIT

Best DDoS Attack Script Python3, Cyber Attack With 43 Methods

exploits

by r4j0x00 doticonjavascriptdoticon

star image 2298 doticonBSD-2-Clause

dalfox

by hahwul doticongodoticon

star image 1617 doticonMIT

🌙🦊 DalFox is an powerful open source XSS scanning tool and parameter analyzer, utility

WebHackersWeapons

by hahwul doticongodoticon

star image 1346 doticonMIT

⚔️ Web Hacker's Weapons / A collection of cool tools used by Web hackers. Happy hacking , Happy bug-hunting

nexphisher

by htr-tech doticonshelldoticon

star image 1316 doticonGPL-3.0

Advanced Phishing tool for Linux & Termux

Tiny-XSS-Payloads

by terjanq doticonjavascriptdoticon

star image 1188 doticon

A collection of tiny XSS Payloads that can be used in different contexts. https://tinyxss.terjanq.me

Top Authors in Hacking

1

TermuxHackz

25 Libraries

star icon395

2

noob-hackers

16 Libraries

star icon4520

3

htr-tech

14 Libraries

star icon2697

4

hackclub

12 Libraries

star icon127

5

HackerDom

11 Libraries

star icon147

6

in-s-ane

10 Libraries

star icon45

7

Bhai4You

10 Libraries

star icon580

8

swagkarna

10 Libraries

star icon187

9

mhaskar

10 Libraries

star icon157

10

Cn33liz

10 Libraries

star icon238

1

25 Libraries

star icon395

2

16 Libraries

star icon4520

3

14 Libraries

star icon2697

4

12 Libraries

star icon127

5

11 Libraries

star icon147

6

10 Libraries

star icon45

7

10 Libraries

star icon580

8

10 Libraries

star icon187

9

10 Libraries

star icon157

10

10 Libraries

star icon238

Trending Kits in Hacking

No Trending Kits are available at this moment for Hacking

Trending Discussions on Hacking

Xcode 13.2 SwiftUI Preview Crashes

Padding scipy affine_transform output to show non-overlapping regions of transformed images

How to make isort always produce multi-line output when there are multiple imports on a line?

Specialising Range or overloading ".."

Why is there extra space alongside my carousel images?

How to start a new jthread on a class member

Spec - how to change the color (or background color) of a presenter

What is the best way to build event counts for certain time resolution over multiple names in Spark dataframe while groupby?

Getting Cluster Running State Using Ansible

Rxjs how to get all values that are buffered during a concatMap

QUESTION

Xcode 13.2 SwiftUI Preview Crashes

Asked 2022-Mar-29 at 10:26

I am learning SwiftUI on 100 Days of SwiftUI on Hacking with Swift. My Xcode SwiftUI Preview crashes and I don't know why. Running on Simulator works though. I tried to completely reinstall Xcode (deleting the app, preferences, libraries etc), but it still doesn't work. I am using Xcode 13.2.1 on iMac 2019 i9 9900K 64GB RAM.

Here is the problem details. (cannot contain full report because of 30000 word limit)

1Exception Type:  EXC_BAD_INSTRUCTION (SIGILL)
2Exception Codes: 0x0000000000000001, 0x0000000000000000
3Exception Note:  EXC_CORPSE_NOTIFY
4Termination Reason: SIGNAL 4 Illegal instruction: 4
5Terminating Process: exc handler [4180]
6
7Triggered by Thread:  0
8
9Application Specific Information:
10CoreSimulator 783.5 - Device: iPod touch (7th generation) (B14B5709-F815-4854-ADB6-E7102668056B) - Runtime: iOS 15.2 (19C51) - DeviceType: iPod touch (7th generation)
11dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
12dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
13
14
15Thread 0 Crashed::  Dispatch queue: BSXPCCnx:com.apple.dt.xcode-previews.systemservices (BSCnx:client:com.apple.dt.uv.agent-preview-nonui-service)
160   SwiftUI                             0x7fff5c970f89 static FocusState._makeProperty<A>(in:container:fieldOffset:inputs:) + 160
171   SwiftUI                             0x7fff5c97141e protocol witness for static DynamicProperty._makeProperty<A>(in:container:fieldOffset:inputs:) in conformance FocusState<A> + 25
182   SwiftUI                             0x7fff5d17717c _DynamicPropertyBuffer.addFields<A>(_:container:inputs:baseOffset:) + 131
193   SwiftUI                             0x7fff5d17709a _DynamicPropertyBuffer.init<A>(fields:container:inputs:baseOffset:) + 111
204   SwiftUI                             0x7fff5ce5d24c project #1 <A><A1>(flags:) in closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 413
215   SwiftUI                             0x7fff5ce5d0a4 closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 113
226   SwiftUI                             0x7fff5ce5ebf1 partial apply for closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 54
237   SwiftUI                             0x7fff5ce5ec12 partial apply for thunk for @callee_guaranteed (@unowned UnsafeMutablePointer<_GraphInputs>) -> (@out _GraphValue<A.BodyAccessor.Body>, @out _DynamicPropertyBuffer?, @error @owned Error) + 27
248   libswiftCore.dylib                  0x7fff3083190c withUnsafePointer<A, B>(to:_:) + 12
259   libswiftCore.dylib                  0x7fff309f2259 withUnsafeMutablePointer<A, B>(to:_:) + 9
2610  SwiftUI                             0x7fff5ce5c68a BodyAccessor.makeBody(container:inputs:fields:) + 286
2711  SwiftUI                             0x7fff5c94b39e static View.makeBody(view:inputs:fields:) + 160
2812  SwiftUI                             0x7fff5c94b0f6 static View.makeViewList(view:inputs:) + 342
2913  SwiftUI                             0x7fff5c94a5f4 static View._makeViewList(view:inputs:) + 104
3014  WeSplit                                0x102730029 protocol witness for static View._makeViewList(view:inputs:) in conformance ContentView + 9
3115  SwiftUI                             0x7fff5ce641cb AnyViewStorage.makeViewList(view:inputs:) + 550
3216  SwiftUI                             0x7fff5ce6526a closure #2 in AnyViewList.updateValue() + 587
3317  SwiftUI                             0x7fff5ce64e76 AnyViewList.updateValue() + 976
3418  SwiftUI                             0x7fff5c83af29 partial apply for specialized implicit closure #2 in implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 15
3519  AttributeGraph                      0x7fff4ff9b37b AG::Graph::UpdateStack::update() + 553
3620  AttributeGraph                      0x7fff4ff9b971 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 411
3721  AttributeGraph                      0x7fff4ffa1656 AG::Graph::value_ref(AG::AttributeID, AGSwiftMetadata const*, unsigned char&) + 128
3822  AttributeGraph                      0x7fff4ffb877a AGGraphGetValue + 291
3923  SwiftUI                             0x7fff5c8b67bd TestableViewContent.list.getter + 47
4024  SwiftUI                             0x7fff5c8b64a6 TestableViewContent.children.getter + 41
4125  SwiftUI                             0x7fff5c8b61f2 View.withChildrenForTest<A>(environment:options:body:) + 181
4226  SwiftUI                             0x7fff5cc7de3f View._allPreviews.getter + 88
4327  SwiftUI                             0x7fff5cc7ddbe MakePreviews.visit<A>(type:) + 128
4428  SwiftUI                             0x7fff5d1a5afc _callVisitViewType2 + 34
4529  SwiftUI                             0x7fff5cc7dd18 static _PreviewProvider._allPreviews.getter + 165
4630  PreviewsInjection                      0x102ae7f6f 0x102ac4000 + 147311
4731  PreviewsInjection                      0x102ae7ea3 0x102ac4000 + 147107
4832  PreviewsInjection                      0x102ae04b6 0x102ac4000 + 115894
4933  PreviewsInjection                      0x102adc85d 0x102ac4000 + 100445
5034  PreviewsInjection                      0x102adc265 0x102ac4000 + 98917
5135  PreviewsInjection                      0x102adc519 0x102ac4000 + 99609
5236  BoardServices                       0x7fff261a2c1c +[BSXPCServiceConnectionProxy invokeMethod:onTarget:withMessage:forConnection:] + 1596
5337  BoardServices                       0x7fff261b0884 __63-[BSXPCServiceConnectionEventHandler connection:handleMessage:]_block_invoke + 562
5438  BoardServices                       0x7fff261d9879 BSXPCServiceConnectionExecuteCallOut + 325
5539  BoardServices                       0x7fff261b04cf -[BSXPCServiceConnectionEventHandler connection:handleMessage:] + 172
5640  BoardServices                       0x7fff261d8bd7 -[BSXPCServiceConnection _connection_handleMessage:fromPeer:withHandoff:] + 679
5741  libdispatch.dylib                   0x7fff2011265a _dispatch_call_block_and_release + 12
5842  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
5943  libdispatch.dylib                   0x7fff20119e0c _dispatch_lane_serial_drain + 743
6044  libdispatch.dylib                   0x7fff2011aa07 _dispatch_lane_invoke + 455
6145  libdispatch.dylib                   0x7fff20120ba5 _dispatch_main_queue_callback_4CF + 848
6246  CoreFoundation                      0x7fff2036c84d __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
6347  CoreFoundation                      0x7fff203670aa __CFRunLoopRun + 2772
6448  CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
6549  GraphicsServices                    0x7fff2c995cd3 GSEventRunModal + 139
6650  UIKitCore                           0x7fff25059f42 -[UIApplication _run] + 928
6751  UIKitCore                           0x7fff2505eb5e UIApplicationMain + 101
6852  SwiftUI                             0x7fff5d0d5dcf closure #1 in KitRendererCommon(_:) + 196
6953  SwiftUI                             0x7fff5d0d5d09 runApp<A>(_:) + 148
7054  SwiftUI                             0x7fff5cabdbad static App.main() + 61
7155  WeSplit                                0x102732a08 static WeSplitApp.$main() + 72 (WeSplitApp.swift:10)
7256  WeSplit                                0x102732ab3 main + 67
7357  dyld_sim                               0x102969ee9 start_sim + 10
7458  dyld                                   0x108ced4fe start + 462
75
76Thread 1:
770   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
78
79Thread 2::  Dispatch queue: com.apple.root.utility-qos
800   dyld_sim                               0x102973a78 bool SwiftHashTable::equal<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 4
811   dyld_sim                               0x102985e3a unsigned int SwiftHashTable::getIndex<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 126
822   dyld_sim                               0x102985d86 unsigned int SwiftHashTable::getPotentialTarget<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 14
833   dyld_sim                               0x102984ebe dyld4::APIs::_dyld_find_protocol_conformance(void const*, void const*, void const*) const + 168
844   libswiftCore.dylib                  0x7fff30a40b9f swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 191
855   libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
866   libswiftCore.dylib                  0x7fff30a00cea swift::_conformsToProtocol(swift::OpaqueValue const*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptorRef<swift::InProcess>, swift::TargetWitnessTable<swift::InProcess> const**) + 42
877   libswiftCore.dylib                  0x7fff30a3ff3f swift::_checkGenericRequirements(__swift::__runtime::llvm::ArrayRef<swift::TargetGenericRequirementDescriptor<swift::InProcess> >, __swift::__runtime::llvm::SmallVectorImpl<void const*>&, std::__1::function<swift::TargetMetadata<swift::InProcess> const* (unsigned int, unsigned int)>, std::__1::function<swift::TargetWitnessTable<swift::InProcess> const* (swift::TargetMetadata<swift::InProcess> const*, unsigned int)>) + 1839
888   libswiftCore.dylib                  0x7fff30a3f742 swift::TargetProtocolConformanceDescriptor<swift::InProcess>::getWitnessTable(swift::TargetMetadata<swift::InProcess> const*) const + 290
899   libswiftCore.dylib                  0x7fff30a41391 swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 2225
9010  libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
9111  AttributeGraph                      0x7fff4ffaa1e8 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 102
9212  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9313  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9414  AttributeGraph                      0x7fff4ffaa2a4 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 290
9515  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9616  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9717  AttributeGraph                      0x7fff4ffab04b AG::LayoutDescriptor::make_layout(AG::swift::metadata const*, AGComparisonMode, AG::LayoutDescriptor::HeapMode) + 474
9818  AttributeGraph                      0x7fff4ffac36c AG::(anonymous namespace)::LayoutCache::drain_queue(void*) + 142
9919  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
10020  libdispatch.dylib                   0x7fff20124077 _dispatch_root_queue_drain + 788
10121  libdispatch.dylib                   0x7fff20124867 _dispatch_worker_thread2 + 155
10222  libsystem_pthread.dylib             0x7fff6da2f02e _pthread_wqthread + 256
10323  libsystem_pthread.dylib             0x7fff6da2dffb start_wqthread + 15
104
105Thread 3:
1060   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
107
108Thread 4:
1090   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
110
111Thread 5:
1120   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
113
114Thread 6:: com.apple.uikit.eventfetch-thread
1150   libsystem_kernel.dylib              0x7fff6d9d4aba mach_msg_trap + 10
1161   libsystem_kernel.dylib              0x7fff6d9d4e2b mach_msg + 59
1172   CoreFoundation                      0x7fff2036c440 __CFRunLoopServiceMachPort + 319
1183   CoreFoundation                      0x7fff20366ae3 __CFRunLoopRun + 1293
1194   CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
1205   Foundation                          0x7fff2081c754 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 213
1216   Foundation                          0x7fff2081c9cb -[NSRunLoop(NSRunLoop) runUntilDate:] + 72
1227   UIKitCore                           0x7fff2511a2d1 -[UIEventFetcher threadMain] + 491
1238   Foundation                          0x7fff20845550 __NSThread__start__ + 1025
1249   libsystem_pthread.dylib             0x7fff6da324f4 _pthread_start + 125
12510  libsystem_pthread.dylib             0x7fff6da2e00f thread_start + 15
126
127
128Thread 0 crashed with X86 Thread State (64-bit):
129  rax: 0x0000000000000002  rbx: 0x0000000000000000  rcx: 0x00007fff4ffc4b50  rdx: 0x0001000000000028
130  rdi: 0x0000000000000000  rsi: 0x00007fff8b43c050  rbp: 0x00007ff7bd7d2fb0  rsp: 0x00007ff7bd7d2f70
131   r8: 0x00007fff5d231685   r9: 0x00007fff86bdd330  r10: 0x0000000000000004  r11: 0x0000000000000072
132  r12: 0x0000000000000002  r13: 0x00007ff7bd7d30a0  r14: 0x0000000000000040  r15: 0x00007fff8a918d88
133  rip: 0x00007fff5c970f89  rfl: 0x0000000000010246  cr2: 0x00007fff5d2316b7
134  
135Logical CPU:     0
136Error Code:      0x00000000 
137Trap Number:     6
138
139
140Binary Images:
141    0x7fff5c697000 -     0x7fff5d4f2fff com.apple.SwiftUI (3.2.5.0.100) <c680d16f-a317-3c6e-87fa-141c22a715da> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI
142    0x7fff30710000 -     0x7fff30acffff libswiftCore.dylib (*) <6013ecdd-c54d-3948-8b7c-e9f5613107f6> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift/libswiftCore.dylib
143       0x102728000 -        0x102733fff me.choo.minsoo.WeSplit (1.0) <d0012a27-d11a-39a0-b4eb-f874af3b5857> /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/B14B5709-F815-4854-ADB6-E7102668056B/data/Containers/Bundle/Application/BA738B59-7D89-47AA-8012-6234AA6E65B0/WeSplit.app/WeSplit
144    0x7fff4ff96000 -     0x7fff4ffcafff com.apple.AttributeGraph (3.2.1) <20c3feeb-4d9b-3501-be47-de9ae60ae297> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/AttributeGraph.framework/AttributeGraph
145       0x102ac4000 -        0x102af5fff com.apple.dt.PreviewsInjection (13.0) <385f7334-89cd-3998-bc1b-54dd898b38ad> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection
146    0x7fff2619e000 -     0x7fff261edfff com.apple.BoardServices (1.0) <d4742ff1-1051-348e-afb4-dcb3bc434c50> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/BoardServices.framework/BoardServices
147    0x7fff20110000 -     0x7fff20157fff libdispatch.dylib (*) <20999e62-bcc2-377e-8ce7-afda271eb914> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/libdispatch.dylib
148    0x7fff202ec000 -     0x7fff2068bfff com.apple.CoreFoundation (6.9) <c6308add-135b-3a70-9b81-1ce4d994c215> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
149    0x7fff2c992000 -     0x7fff2c99afff com.apple.GraphicsServices (1.0) <adea8ae1-c723-351b-ac2e-22fd2c861c30> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
150    0x7fff2438c000 -     0x7fff25934fff com.apple.UIKitCore (1.0) <3ef2c381-8193-3e3c-801f-925bd1050bd7> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
151       0x102968000 -        0x1029b5fff dyld_sim (*) <3f15c197-2d43-3490-98ff-de85f18dadf2> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/dyld_sim
152       0x108ce8000 -        0x108d53fff dyld (*) <7de33963-bbc5-3996-ba6e-f1d562c17c95> /usr/lib/dyld
153    0x7fff6da2c000 -     0x7fff6da37fff libsystem_pthread.dylib (*) <ee564342-d8f2-396d-b642-40092cf34d82> /usr/lib/system/libsystem_pthread.dylib
154    0x7fff6d9d4000 -     0x7fff6da0afff libsystem_kernel.dylib (*) <c1d58a50-5a4d-3bcb-a1fc-ec0902ce34d3> /usr/lib/system/libsystem_kernel.dylib
155    0x7fff206fa000 -     0x7fff209b0fff com.apple.Foundation (6.9) <61dcc68e-1236-3624-bb6d-a3a850adf63a> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework/Foundation
156
157EOF
158

And the diagnostics:

1Exception Type:  EXC_BAD_INSTRUCTION (SIGILL)
2Exception Codes: 0x0000000000000001, 0x0000000000000000
3Exception Note:  EXC_CORPSE_NOTIFY
4Termination Reason: SIGNAL 4 Illegal instruction: 4
5Terminating Process: exc handler [4180]
6
7Triggered by Thread:  0
8
9Application Specific Information:
10CoreSimulator 783.5 - Device: iPod touch (7th generation) (B14B5709-F815-4854-ADB6-E7102668056B) - Runtime: iOS 15.2 (19C51) - DeviceType: iPod touch (7th generation)
11dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
12dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
13
14
15Thread 0 Crashed::  Dispatch queue: BSXPCCnx:com.apple.dt.xcode-previews.systemservices (BSCnx:client:com.apple.dt.uv.agent-preview-nonui-service)
160   SwiftUI                             0x7fff5c970f89 static FocusState._makeProperty<A>(in:container:fieldOffset:inputs:) + 160
171   SwiftUI                             0x7fff5c97141e protocol witness for static DynamicProperty._makeProperty<A>(in:container:fieldOffset:inputs:) in conformance FocusState<A> + 25
182   SwiftUI                             0x7fff5d17717c _DynamicPropertyBuffer.addFields<A>(_:container:inputs:baseOffset:) + 131
193   SwiftUI                             0x7fff5d17709a _DynamicPropertyBuffer.init<A>(fields:container:inputs:baseOffset:) + 111
204   SwiftUI                             0x7fff5ce5d24c project #1 <A><A1>(flags:) in closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 413
215   SwiftUI                             0x7fff5ce5d0a4 closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 113
226   SwiftUI                             0x7fff5ce5ebf1 partial apply for closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 54
237   SwiftUI                             0x7fff5ce5ec12 partial apply for thunk for @callee_guaranteed (@unowned UnsafeMutablePointer<_GraphInputs>) -> (@out _GraphValue<A.BodyAccessor.Body>, @out _DynamicPropertyBuffer?, @error @owned Error) + 27
248   libswiftCore.dylib                  0x7fff3083190c withUnsafePointer<A, B>(to:_:) + 12
259   libswiftCore.dylib                  0x7fff309f2259 withUnsafeMutablePointer<A, B>(to:_:) + 9
2610  SwiftUI                             0x7fff5ce5c68a BodyAccessor.makeBody(container:inputs:fields:) + 286
2711  SwiftUI                             0x7fff5c94b39e static View.makeBody(view:inputs:fields:) + 160
2812  SwiftUI                             0x7fff5c94b0f6 static View.makeViewList(view:inputs:) + 342
2913  SwiftUI                             0x7fff5c94a5f4 static View._makeViewList(view:inputs:) + 104
3014  WeSplit                                0x102730029 protocol witness for static View._makeViewList(view:inputs:) in conformance ContentView + 9
3115  SwiftUI                             0x7fff5ce641cb AnyViewStorage.makeViewList(view:inputs:) + 550
3216  SwiftUI                             0x7fff5ce6526a closure #2 in AnyViewList.updateValue() + 587
3317  SwiftUI                             0x7fff5ce64e76 AnyViewList.updateValue() + 976
3418  SwiftUI                             0x7fff5c83af29 partial apply for specialized implicit closure #2 in implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 15
3519  AttributeGraph                      0x7fff4ff9b37b AG::Graph::UpdateStack::update() + 553
3620  AttributeGraph                      0x7fff4ff9b971 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 411
3721  AttributeGraph                      0x7fff4ffa1656 AG::Graph::value_ref(AG::AttributeID, AGSwiftMetadata const*, unsigned char&) + 128
3822  AttributeGraph                      0x7fff4ffb877a AGGraphGetValue + 291
3923  SwiftUI                             0x7fff5c8b67bd TestableViewContent.list.getter + 47
4024  SwiftUI                             0x7fff5c8b64a6 TestableViewContent.children.getter + 41
4125  SwiftUI                             0x7fff5c8b61f2 View.withChildrenForTest<A>(environment:options:body:) + 181
4226  SwiftUI                             0x7fff5cc7de3f View._allPreviews.getter + 88
4327  SwiftUI                             0x7fff5cc7ddbe MakePreviews.visit<A>(type:) + 128
4428  SwiftUI                             0x7fff5d1a5afc _callVisitViewType2 + 34
4529  SwiftUI                             0x7fff5cc7dd18 static _PreviewProvider._allPreviews.getter + 165
4630  PreviewsInjection                      0x102ae7f6f 0x102ac4000 + 147311
4731  PreviewsInjection                      0x102ae7ea3 0x102ac4000 + 147107
4832  PreviewsInjection                      0x102ae04b6 0x102ac4000 + 115894
4933  PreviewsInjection                      0x102adc85d 0x102ac4000 + 100445
5034  PreviewsInjection                      0x102adc265 0x102ac4000 + 98917
5135  PreviewsInjection                      0x102adc519 0x102ac4000 + 99609
5236  BoardServices                       0x7fff261a2c1c +[BSXPCServiceConnectionProxy invokeMethod:onTarget:withMessage:forConnection:] + 1596
5337  BoardServices                       0x7fff261b0884 __63-[BSXPCServiceConnectionEventHandler connection:handleMessage:]_block_invoke + 562
5438  BoardServices                       0x7fff261d9879 BSXPCServiceConnectionExecuteCallOut + 325
5539  BoardServices                       0x7fff261b04cf -[BSXPCServiceConnectionEventHandler connection:handleMessage:] + 172
5640  BoardServices                       0x7fff261d8bd7 -[BSXPCServiceConnection _connection_handleMessage:fromPeer:withHandoff:] + 679
5741  libdispatch.dylib                   0x7fff2011265a _dispatch_call_block_and_release + 12
5842  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
5943  libdispatch.dylib                   0x7fff20119e0c _dispatch_lane_serial_drain + 743
6044  libdispatch.dylib                   0x7fff2011aa07 _dispatch_lane_invoke + 455
6145  libdispatch.dylib                   0x7fff20120ba5 _dispatch_main_queue_callback_4CF + 848
6246  CoreFoundation                      0x7fff2036c84d __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
6347  CoreFoundation                      0x7fff203670aa __CFRunLoopRun + 2772
6448  CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
6549  GraphicsServices                    0x7fff2c995cd3 GSEventRunModal + 139
6650  UIKitCore                           0x7fff25059f42 -[UIApplication _run] + 928
6751  UIKitCore                           0x7fff2505eb5e UIApplicationMain + 101
6852  SwiftUI                             0x7fff5d0d5dcf closure #1 in KitRendererCommon(_:) + 196
6953  SwiftUI                             0x7fff5d0d5d09 runApp<A>(_:) + 148
7054  SwiftUI                             0x7fff5cabdbad static App.main() + 61
7155  WeSplit                                0x102732a08 static WeSplitApp.$main() + 72 (WeSplitApp.swift:10)
7256  WeSplit                                0x102732ab3 main + 67
7357  dyld_sim                               0x102969ee9 start_sim + 10
7458  dyld                                   0x108ced4fe start + 462
75
76Thread 1:
770   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
78
79Thread 2::  Dispatch queue: com.apple.root.utility-qos
800   dyld_sim                               0x102973a78 bool SwiftHashTable::equal<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 4
811   dyld_sim                               0x102985e3a unsigned int SwiftHashTable::getIndex<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 126
822   dyld_sim                               0x102985d86 unsigned int SwiftHashTable::getPotentialTarget<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 14
833   dyld_sim                               0x102984ebe dyld4::APIs::_dyld_find_protocol_conformance(void const*, void const*, void const*) const + 168
844   libswiftCore.dylib                  0x7fff30a40b9f swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 191
855   libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
866   libswiftCore.dylib                  0x7fff30a00cea swift::_conformsToProtocol(swift::OpaqueValue const*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptorRef<swift::InProcess>, swift::TargetWitnessTable<swift::InProcess> const**) + 42
877   libswiftCore.dylib                  0x7fff30a3ff3f swift::_checkGenericRequirements(__swift::__runtime::llvm::ArrayRef<swift::TargetGenericRequirementDescriptor<swift::InProcess> >, __swift::__runtime::llvm::SmallVectorImpl<void const*>&, std::__1::function<swift::TargetMetadata<swift::InProcess> const* (unsigned int, unsigned int)>, std::__1::function<swift::TargetWitnessTable<swift::InProcess> const* (swift::TargetMetadata<swift::InProcess> const*, unsigned int)>) + 1839
888   libswiftCore.dylib                  0x7fff30a3f742 swift::TargetProtocolConformanceDescriptor<swift::InProcess>::getWitnessTable(swift::TargetMetadata<swift::InProcess> const*) const + 290
899   libswiftCore.dylib                  0x7fff30a41391 swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 2225
9010  libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
9111  AttributeGraph                      0x7fff4ffaa1e8 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 102
9212  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9313  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9414  AttributeGraph                      0x7fff4ffaa2a4 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 290
9515  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9616  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9717  AttributeGraph                      0x7fff4ffab04b AG::LayoutDescriptor::make_layout(AG::swift::metadata const*, AGComparisonMode, AG::LayoutDescriptor::HeapMode) + 474
9818  AttributeGraph                      0x7fff4ffac36c AG::(anonymous namespace)::LayoutCache::drain_queue(void*) + 142
9919  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
10020  libdispatch.dylib                   0x7fff20124077 _dispatch_root_queue_drain + 788
10121  libdispatch.dylib                   0x7fff20124867 _dispatch_worker_thread2 + 155
10222  libsystem_pthread.dylib             0x7fff6da2f02e _pthread_wqthread + 256
10323  libsystem_pthread.dylib             0x7fff6da2dffb start_wqthread + 15
104
105Thread 3:
1060   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
107
108Thread 4:
1090   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
110
111Thread 5:
1120   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
113
114Thread 6:: com.apple.uikit.eventfetch-thread
1150   libsystem_kernel.dylib              0x7fff6d9d4aba mach_msg_trap + 10
1161   libsystem_kernel.dylib              0x7fff6d9d4e2b mach_msg + 59
1172   CoreFoundation                      0x7fff2036c440 __CFRunLoopServiceMachPort + 319
1183   CoreFoundation                      0x7fff20366ae3 __CFRunLoopRun + 1293
1194   CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
1205   Foundation                          0x7fff2081c754 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 213
1216   Foundation                          0x7fff2081c9cb -[NSRunLoop(NSRunLoop) runUntilDate:] + 72
1227   UIKitCore                           0x7fff2511a2d1 -[UIEventFetcher threadMain] + 491
1238   Foundation                          0x7fff20845550 __NSThread__start__ + 1025
1249   libsystem_pthread.dylib             0x7fff6da324f4 _pthread_start + 125
12510  libsystem_pthread.dylib             0x7fff6da2e00f thread_start + 15
126
127
128Thread 0 crashed with X86 Thread State (64-bit):
129  rax: 0x0000000000000002  rbx: 0x0000000000000000  rcx: 0x00007fff4ffc4b50  rdx: 0x0001000000000028
130  rdi: 0x0000000000000000  rsi: 0x00007fff8b43c050  rbp: 0x00007ff7bd7d2fb0  rsp: 0x00007ff7bd7d2f70
131   r8: 0x00007fff5d231685   r9: 0x00007fff86bdd330  r10: 0x0000000000000004  r11: 0x0000000000000072
132  r12: 0x0000000000000002  r13: 0x00007ff7bd7d30a0  r14: 0x0000000000000040  r15: 0x00007fff8a918d88
133  rip: 0x00007fff5c970f89  rfl: 0x0000000000010246  cr2: 0x00007fff5d2316b7
134  
135Logical CPU:     0
136Error Code:      0x00000000 
137Trap Number:     6
138
139
140Binary Images:
141    0x7fff5c697000 -     0x7fff5d4f2fff com.apple.SwiftUI (3.2.5.0.100) <c680d16f-a317-3c6e-87fa-141c22a715da> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI
142    0x7fff30710000 -     0x7fff30acffff libswiftCore.dylib (*) <6013ecdd-c54d-3948-8b7c-e9f5613107f6> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift/libswiftCore.dylib
143       0x102728000 -        0x102733fff me.choo.minsoo.WeSplit (1.0) <d0012a27-d11a-39a0-b4eb-f874af3b5857> /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/B14B5709-F815-4854-ADB6-E7102668056B/data/Containers/Bundle/Application/BA738B59-7D89-47AA-8012-6234AA6E65B0/WeSplit.app/WeSplit
144    0x7fff4ff96000 -     0x7fff4ffcafff com.apple.AttributeGraph (3.2.1) <20c3feeb-4d9b-3501-be47-de9ae60ae297> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/AttributeGraph.framework/AttributeGraph
145       0x102ac4000 -        0x102af5fff com.apple.dt.PreviewsInjection (13.0) <385f7334-89cd-3998-bc1b-54dd898b38ad> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection
146    0x7fff2619e000 -     0x7fff261edfff com.apple.BoardServices (1.0) <d4742ff1-1051-348e-afb4-dcb3bc434c50> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/BoardServices.framework/BoardServices
147    0x7fff20110000 -     0x7fff20157fff libdispatch.dylib (*) <20999e62-bcc2-377e-8ce7-afda271eb914> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/libdispatch.dylib
148    0x7fff202ec000 -     0x7fff2068bfff com.apple.CoreFoundation (6.9) <c6308add-135b-3a70-9b81-1ce4d994c215> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
149    0x7fff2c992000 -     0x7fff2c99afff com.apple.GraphicsServices (1.0) <adea8ae1-c723-351b-ac2e-22fd2c861c30> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
150    0x7fff2438c000 -     0x7fff25934fff com.apple.UIKitCore (1.0) <3ef2c381-8193-3e3c-801f-925bd1050bd7> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
151       0x102968000 -        0x1029b5fff dyld_sim (*) <3f15c197-2d43-3490-98ff-de85f18dadf2> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/dyld_sim
152       0x108ce8000 -        0x108d53fff dyld (*) <7de33963-bbc5-3996-ba6e-f1d562c17c95> /usr/lib/dyld
153    0x7fff6da2c000 -     0x7fff6da37fff libsystem_pthread.dylib (*) <ee564342-d8f2-396d-b642-40092cf34d82> /usr/lib/system/libsystem_pthread.dylib
154    0x7fff6d9d4000 -     0x7fff6da0afff libsystem_kernel.dylib (*) <c1d58a50-5a4d-3bcb-a1fc-ec0902ce34d3> /usr/lib/system/libsystem_kernel.dylib
155    0x7fff206fa000 -     0x7fff209b0fff com.apple.Foundation (6.9) <61dcc68e-1236-3624-bb6d-a3a850adf63a> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework/Foundation
156
157EOF
158MessageSendFailure: Message send failure for update
159
160==================================
161
162|  MessageError: Connection interrupted
163

Code:

ContentView.swift

1Exception Type:  EXC_BAD_INSTRUCTION (SIGILL)
2Exception Codes: 0x0000000000000001, 0x0000000000000000
3Exception Note:  EXC_CORPSE_NOTIFY
4Termination Reason: SIGNAL 4 Illegal instruction: 4
5Terminating Process: exc handler [4180]
6
7Triggered by Thread:  0
8
9Application Specific Information:
10CoreSimulator 783.5 - Device: iPod touch (7th generation) (B14B5709-F815-4854-ADB6-E7102668056B) - Runtime: iOS 15.2 (19C51) - DeviceType: iPod touch (7th generation)
11dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
12dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
13
14
15Thread 0 Crashed::  Dispatch queue: BSXPCCnx:com.apple.dt.xcode-previews.systemservices (BSCnx:client:com.apple.dt.uv.agent-preview-nonui-service)
160   SwiftUI                             0x7fff5c970f89 static FocusState._makeProperty<A>(in:container:fieldOffset:inputs:) + 160
171   SwiftUI                             0x7fff5c97141e protocol witness for static DynamicProperty._makeProperty<A>(in:container:fieldOffset:inputs:) in conformance FocusState<A> + 25
182   SwiftUI                             0x7fff5d17717c _DynamicPropertyBuffer.addFields<A>(_:container:inputs:baseOffset:) + 131
193   SwiftUI                             0x7fff5d17709a _DynamicPropertyBuffer.init<A>(fields:container:inputs:baseOffset:) + 111
204   SwiftUI                             0x7fff5ce5d24c project #1 <A><A1>(flags:) in closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 413
215   SwiftUI                             0x7fff5ce5d0a4 closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 113
226   SwiftUI                             0x7fff5ce5ebf1 partial apply for closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 54
237   SwiftUI                             0x7fff5ce5ec12 partial apply for thunk for @callee_guaranteed (@unowned UnsafeMutablePointer<_GraphInputs>) -> (@out _GraphValue<A.BodyAccessor.Body>, @out _DynamicPropertyBuffer?, @error @owned Error) + 27
248   libswiftCore.dylib                  0x7fff3083190c withUnsafePointer<A, B>(to:_:) + 12
259   libswiftCore.dylib                  0x7fff309f2259 withUnsafeMutablePointer<A, B>(to:_:) + 9
2610  SwiftUI                             0x7fff5ce5c68a BodyAccessor.makeBody(container:inputs:fields:) + 286
2711  SwiftUI                             0x7fff5c94b39e static View.makeBody(view:inputs:fields:) + 160
2812  SwiftUI                             0x7fff5c94b0f6 static View.makeViewList(view:inputs:) + 342
2913  SwiftUI                             0x7fff5c94a5f4 static View._makeViewList(view:inputs:) + 104
3014  WeSplit                                0x102730029 protocol witness for static View._makeViewList(view:inputs:) in conformance ContentView + 9
3115  SwiftUI                             0x7fff5ce641cb AnyViewStorage.makeViewList(view:inputs:) + 550
3216  SwiftUI                             0x7fff5ce6526a closure #2 in AnyViewList.updateValue() + 587
3317  SwiftUI                             0x7fff5ce64e76 AnyViewList.updateValue() + 976
3418  SwiftUI                             0x7fff5c83af29 partial apply for specialized implicit closure #2 in implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 15
3519  AttributeGraph                      0x7fff4ff9b37b AG::Graph::UpdateStack::update() + 553
3620  AttributeGraph                      0x7fff4ff9b971 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 411
3721  AttributeGraph                      0x7fff4ffa1656 AG::Graph::value_ref(AG::AttributeID, AGSwiftMetadata const*, unsigned char&) + 128
3822  AttributeGraph                      0x7fff4ffb877a AGGraphGetValue + 291
3923  SwiftUI                             0x7fff5c8b67bd TestableViewContent.list.getter + 47
4024  SwiftUI                             0x7fff5c8b64a6 TestableViewContent.children.getter + 41
4125  SwiftUI                             0x7fff5c8b61f2 View.withChildrenForTest<A>(environment:options:body:) + 181
4226  SwiftUI                             0x7fff5cc7de3f View._allPreviews.getter + 88
4327  SwiftUI                             0x7fff5cc7ddbe MakePreviews.visit<A>(type:) + 128
4428  SwiftUI                             0x7fff5d1a5afc _callVisitViewType2 + 34
4529  SwiftUI                             0x7fff5cc7dd18 static _PreviewProvider._allPreviews.getter + 165
4630  PreviewsInjection                      0x102ae7f6f 0x102ac4000 + 147311
4731  PreviewsInjection                      0x102ae7ea3 0x102ac4000 + 147107
4832  PreviewsInjection                      0x102ae04b6 0x102ac4000 + 115894
4933  PreviewsInjection                      0x102adc85d 0x102ac4000 + 100445
5034  PreviewsInjection                      0x102adc265 0x102ac4000 + 98917
5135  PreviewsInjection                      0x102adc519 0x102ac4000 + 99609
5236  BoardServices                       0x7fff261a2c1c +[BSXPCServiceConnectionProxy invokeMethod:onTarget:withMessage:forConnection:] + 1596
5337  BoardServices                       0x7fff261b0884 __63-[BSXPCServiceConnectionEventHandler connection:handleMessage:]_block_invoke + 562
5438  BoardServices                       0x7fff261d9879 BSXPCServiceConnectionExecuteCallOut + 325
5539  BoardServices                       0x7fff261b04cf -[BSXPCServiceConnectionEventHandler connection:handleMessage:] + 172
5640  BoardServices                       0x7fff261d8bd7 -[BSXPCServiceConnection _connection_handleMessage:fromPeer:withHandoff:] + 679
5741  libdispatch.dylib                   0x7fff2011265a _dispatch_call_block_and_release + 12
5842  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
5943  libdispatch.dylib                   0x7fff20119e0c _dispatch_lane_serial_drain + 743
6044  libdispatch.dylib                   0x7fff2011aa07 _dispatch_lane_invoke + 455
6145  libdispatch.dylib                   0x7fff20120ba5 _dispatch_main_queue_callback_4CF + 848
6246  CoreFoundation                      0x7fff2036c84d __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
6347  CoreFoundation                      0x7fff203670aa __CFRunLoopRun + 2772
6448  CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
6549  GraphicsServices                    0x7fff2c995cd3 GSEventRunModal + 139
6650  UIKitCore                           0x7fff25059f42 -[UIApplication _run] + 928
6751  UIKitCore                           0x7fff2505eb5e UIApplicationMain + 101
6852  SwiftUI                             0x7fff5d0d5dcf closure #1 in KitRendererCommon(_:) + 196
6953  SwiftUI                             0x7fff5d0d5d09 runApp<A>(_:) + 148
7054  SwiftUI                             0x7fff5cabdbad static App.main() + 61
7155  WeSplit                                0x102732a08 static WeSplitApp.$main() + 72 (WeSplitApp.swift:10)
7256  WeSplit                                0x102732ab3 main + 67
7357  dyld_sim                               0x102969ee9 start_sim + 10
7458  dyld                                   0x108ced4fe start + 462
75
76Thread 1:
770   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
78
79Thread 2::  Dispatch queue: com.apple.root.utility-qos
800   dyld_sim                               0x102973a78 bool SwiftHashTable::equal<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 4
811   dyld_sim                               0x102985e3a unsigned int SwiftHashTable::getIndex<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 126
822   dyld_sim                               0x102985d86 unsigned int SwiftHashTable::getPotentialTarget<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 14
833   dyld_sim                               0x102984ebe dyld4::APIs::_dyld_find_protocol_conformance(void const*, void const*, void const*) const + 168
844   libswiftCore.dylib                  0x7fff30a40b9f swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 191
855   libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
866   libswiftCore.dylib                  0x7fff30a00cea swift::_conformsToProtocol(swift::OpaqueValue const*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptorRef<swift::InProcess>, swift::TargetWitnessTable<swift::InProcess> const**) + 42
877   libswiftCore.dylib                  0x7fff30a3ff3f swift::_checkGenericRequirements(__swift::__runtime::llvm::ArrayRef<swift::TargetGenericRequirementDescriptor<swift::InProcess> >, __swift::__runtime::llvm::SmallVectorImpl<void const*>&, std::__1::function<swift::TargetMetadata<swift::InProcess> const* (unsigned int, unsigned int)>, std::__1::function<swift::TargetWitnessTable<swift::InProcess> const* (swift::TargetMetadata<swift::InProcess> const*, unsigned int)>) + 1839
888   libswiftCore.dylib                  0x7fff30a3f742 swift::TargetProtocolConformanceDescriptor<swift::InProcess>::getWitnessTable(swift::TargetMetadata<swift::InProcess> const*) const + 290
899   libswiftCore.dylib                  0x7fff30a41391 swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 2225
9010  libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
9111  AttributeGraph                      0x7fff4ffaa1e8 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 102
9212  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9313  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9414  AttributeGraph                      0x7fff4ffaa2a4 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 290
9515  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9616  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9717  AttributeGraph                      0x7fff4ffab04b AG::LayoutDescriptor::make_layout(AG::swift::metadata const*, AGComparisonMode, AG::LayoutDescriptor::HeapMode) + 474
9818  AttributeGraph                      0x7fff4ffac36c AG::(anonymous namespace)::LayoutCache::drain_queue(void*) + 142
9919  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
10020  libdispatch.dylib                   0x7fff20124077 _dispatch_root_queue_drain + 788
10121  libdispatch.dylib                   0x7fff20124867 _dispatch_worker_thread2 + 155
10222  libsystem_pthread.dylib             0x7fff6da2f02e _pthread_wqthread + 256
10323  libsystem_pthread.dylib             0x7fff6da2dffb start_wqthread + 15
104
105Thread 3:
1060   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
107
108Thread 4:
1090   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
110
111Thread 5:
1120   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
113
114Thread 6:: com.apple.uikit.eventfetch-thread
1150   libsystem_kernel.dylib              0x7fff6d9d4aba mach_msg_trap + 10
1161   libsystem_kernel.dylib              0x7fff6d9d4e2b mach_msg + 59
1172   CoreFoundation                      0x7fff2036c440 __CFRunLoopServiceMachPort + 319
1183   CoreFoundation                      0x7fff20366ae3 __CFRunLoopRun + 1293
1194   CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
1205   Foundation                          0x7fff2081c754 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 213
1216   Foundation                          0x7fff2081c9cb -[NSRunLoop(NSRunLoop) runUntilDate:] + 72
1227   UIKitCore                           0x7fff2511a2d1 -[UIEventFetcher threadMain] + 491
1238   Foundation                          0x7fff20845550 __NSThread__start__ + 1025
1249   libsystem_pthread.dylib             0x7fff6da324f4 _pthread_start + 125
12510  libsystem_pthread.dylib             0x7fff6da2e00f thread_start + 15
126
127
128Thread 0 crashed with X86 Thread State (64-bit):
129  rax: 0x0000000000000002  rbx: 0x0000000000000000  rcx: 0x00007fff4ffc4b50  rdx: 0x0001000000000028
130  rdi: 0x0000000000000000  rsi: 0x00007fff8b43c050  rbp: 0x00007ff7bd7d2fb0  rsp: 0x00007ff7bd7d2f70
131   r8: 0x00007fff5d231685   r9: 0x00007fff86bdd330  r10: 0x0000000000000004  r11: 0x0000000000000072
132  r12: 0x0000000000000002  r13: 0x00007ff7bd7d30a0  r14: 0x0000000000000040  r15: 0x00007fff8a918d88
133  rip: 0x00007fff5c970f89  rfl: 0x0000000000010246  cr2: 0x00007fff5d2316b7
134  
135Logical CPU:     0
136Error Code:      0x00000000 
137Trap Number:     6
138
139
140Binary Images:
141    0x7fff5c697000 -     0x7fff5d4f2fff com.apple.SwiftUI (3.2.5.0.100) <c680d16f-a317-3c6e-87fa-141c22a715da> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI
142    0x7fff30710000 -     0x7fff30acffff libswiftCore.dylib (*) <6013ecdd-c54d-3948-8b7c-e9f5613107f6> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift/libswiftCore.dylib
143       0x102728000 -        0x102733fff me.choo.minsoo.WeSplit (1.0) <d0012a27-d11a-39a0-b4eb-f874af3b5857> /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/B14B5709-F815-4854-ADB6-E7102668056B/data/Containers/Bundle/Application/BA738B59-7D89-47AA-8012-6234AA6E65B0/WeSplit.app/WeSplit
144    0x7fff4ff96000 -     0x7fff4ffcafff com.apple.AttributeGraph (3.2.1) <20c3feeb-4d9b-3501-be47-de9ae60ae297> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/AttributeGraph.framework/AttributeGraph
145       0x102ac4000 -        0x102af5fff com.apple.dt.PreviewsInjection (13.0) <385f7334-89cd-3998-bc1b-54dd898b38ad> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection
146    0x7fff2619e000 -     0x7fff261edfff com.apple.BoardServices (1.0) <d4742ff1-1051-348e-afb4-dcb3bc434c50> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/BoardServices.framework/BoardServices
147    0x7fff20110000 -     0x7fff20157fff libdispatch.dylib (*) <20999e62-bcc2-377e-8ce7-afda271eb914> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/libdispatch.dylib
148    0x7fff202ec000 -     0x7fff2068bfff com.apple.CoreFoundation (6.9) <c6308add-135b-3a70-9b81-1ce4d994c215> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
149    0x7fff2c992000 -     0x7fff2c99afff com.apple.GraphicsServices (1.0) <adea8ae1-c723-351b-ac2e-22fd2c861c30> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
150    0x7fff2438c000 -     0x7fff25934fff com.apple.UIKitCore (1.0) <3ef2c381-8193-3e3c-801f-925bd1050bd7> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
151       0x102968000 -        0x1029b5fff dyld_sim (*) <3f15c197-2d43-3490-98ff-de85f18dadf2> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/dyld_sim
152       0x108ce8000 -        0x108d53fff dyld (*) <7de33963-bbc5-3996-ba6e-f1d562c17c95> /usr/lib/dyld
153    0x7fff6da2c000 -     0x7fff6da37fff libsystem_pthread.dylib (*) <ee564342-d8f2-396d-b642-40092cf34d82> /usr/lib/system/libsystem_pthread.dylib
154    0x7fff6d9d4000 -     0x7fff6da0afff libsystem_kernel.dylib (*) <c1d58a50-5a4d-3bcb-a1fc-ec0902ce34d3> /usr/lib/system/libsystem_kernel.dylib
155    0x7fff206fa000 -     0x7fff209b0fff com.apple.Foundation (6.9) <61dcc68e-1236-3624-bb6d-a3a850adf63a> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework/Foundation
156
157EOF
158MessageSendFailure: Message send failure for update
159
160==================================
161
162|  MessageError: Connection interrupted
163import SwiftUI
164
165struct ContentView: View {
166    @State private var checkAmount = 0.0
167    @State private var numberOfPeople = 2
168    @State private var tipPercentage = 20
169    let tipPercentages = 0..<101
170    
171    var totalPerPerson: Double {
172        let peopleCount = Double(numberOfPeople + 2)
173        let tipSelection = Double(tipPercentage)
174
175        let tipValue = checkAmount / 100 * tipSelection
176        let grandTotal = checkAmount + tipValue
177        let amountPerPerson = grandTotal / peopleCount
178
179        return amountPerPerson
180    }
181    
182    var total: Double {
183        checkAmount + checkAmount / 100 * Double(tipPercentage)
184    }
185    
186    @FocusState private var amountIsFocused: Bool
187    
188    var body: some View {
189        NavigationView {
190            Form {
191                Section {
192                    TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
193                        .keyboardType(.decimalPad)
194                        .focused($amountIsFocused)
195                
196                    Picker("Number of People", selection: $numberOfPeople) {
197                        ForEach(2..<100) {
198                            Text("\($0) people")
199                        }
200                    }
201                }
202                
203                Section {
204                    Picker("Tip Percentage", selection: $tipPercentage) {
205                        ForEach(tipPercentages, id: \.self) {
206                            Text($0, format: .percent)
207                        }
208                    }
209                } header: {
210                    Text("How much tip do you want to leave?")
211                }
212            
213                Section {
214                    Text(totalPerPerson, format: .currency(code: Locale.current.currencyCode ?? "USD"))
215                } header: {
216                    Text("Amount per person")
217                }
218                
219                Section {
220                    Text(total, format: .currency(code: Locale.current.currencyCode ?? "USD"))
221                }
222            }
223            .navigationTitle("WeSplit")
224        }
225        .toolbar {
226            ToolbarItemGroup(placement: .keyboard) {
227                Spacer()
228                
229                Button("Done") {
230                    amountIsFocused = false
231                }
232            }
233        }
234    }
235}
236
237struct ContentView_Previews: PreviewProvider {
238    static var previews: some View {
239        ContentView()
240    }
241}
242

WeSplitApp.swift

1Exception Type:  EXC_BAD_INSTRUCTION (SIGILL)
2Exception Codes: 0x0000000000000001, 0x0000000000000000
3Exception Note:  EXC_CORPSE_NOTIFY
4Termination Reason: SIGNAL 4 Illegal instruction: 4
5Terminating Process: exc handler [4180]
6
7Triggered by Thread:  0
8
9Application Specific Information:
10CoreSimulator 783.5 - Device: iPod touch (7th generation) (B14B5709-F815-4854-ADB6-E7102668056B) - Runtime: iOS 15.2 (19C51) - DeviceType: iPod touch (7th generation)
11dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
12dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
13
14
15Thread 0 Crashed::  Dispatch queue: BSXPCCnx:com.apple.dt.xcode-previews.systemservices (BSCnx:client:com.apple.dt.uv.agent-preview-nonui-service)
160   SwiftUI                             0x7fff5c970f89 static FocusState._makeProperty<A>(in:container:fieldOffset:inputs:) + 160
171   SwiftUI                             0x7fff5c97141e protocol witness for static DynamicProperty._makeProperty<A>(in:container:fieldOffset:inputs:) in conformance FocusState<A> + 25
182   SwiftUI                             0x7fff5d17717c _DynamicPropertyBuffer.addFields<A>(_:container:inputs:baseOffset:) + 131
193   SwiftUI                             0x7fff5d17709a _DynamicPropertyBuffer.init<A>(fields:container:inputs:baseOffset:) + 111
204   SwiftUI                             0x7fff5ce5d24c project #1 <A><A1>(flags:) in closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 413
215   SwiftUI                             0x7fff5ce5d0a4 closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 113
226   SwiftUI                             0x7fff5ce5ebf1 partial apply for closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 54
237   SwiftUI                             0x7fff5ce5ec12 partial apply for thunk for @callee_guaranteed (@unowned UnsafeMutablePointer<_GraphInputs>) -> (@out _GraphValue<A.BodyAccessor.Body>, @out _DynamicPropertyBuffer?, @error @owned Error) + 27
248   libswiftCore.dylib                  0x7fff3083190c withUnsafePointer<A, B>(to:_:) + 12
259   libswiftCore.dylib                  0x7fff309f2259 withUnsafeMutablePointer<A, B>(to:_:) + 9
2610  SwiftUI                             0x7fff5ce5c68a BodyAccessor.makeBody(container:inputs:fields:) + 286
2711  SwiftUI                             0x7fff5c94b39e static View.makeBody(view:inputs:fields:) + 160
2812  SwiftUI                             0x7fff5c94b0f6 static View.makeViewList(view:inputs:) + 342
2913  SwiftUI                             0x7fff5c94a5f4 static View._makeViewList(view:inputs:) + 104
3014  WeSplit                                0x102730029 protocol witness for static View._makeViewList(view:inputs:) in conformance ContentView + 9
3115  SwiftUI                             0x7fff5ce641cb AnyViewStorage.makeViewList(view:inputs:) + 550
3216  SwiftUI                             0x7fff5ce6526a closure #2 in AnyViewList.updateValue() + 587
3317  SwiftUI                             0x7fff5ce64e76 AnyViewList.updateValue() + 976
3418  SwiftUI                             0x7fff5c83af29 partial apply for specialized implicit closure #2 in implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 15
3519  AttributeGraph                      0x7fff4ff9b37b AG::Graph::UpdateStack::update() + 553
3620  AttributeGraph                      0x7fff4ff9b971 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 411
3721  AttributeGraph                      0x7fff4ffa1656 AG::Graph::value_ref(AG::AttributeID, AGSwiftMetadata const*, unsigned char&) + 128
3822  AttributeGraph                      0x7fff4ffb877a AGGraphGetValue + 291
3923  SwiftUI                             0x7fff5c8b67bd TestableViewContent.list.getter + 47
4024  SwiftUI                             0x7fff5c8b64a6 TestableViewContent.children.getter + 41
4125  SwiftUI                             0x7fff5c8b61f2 View.withChildrenForTest<A>(environment:options:body:) + 181
4226  SwiftUI                             0x7fff5cc7de3f View._allPreviews.getter + 88
4327  SwiftUI                             0x7fff5cc7ddbe MakePreviews.visit<A>(type:) + 128
4428  SwiftUI                             0x7fff5d1a5afc _callVisitViewType2 + 34
4529  SwiftUI                             0x7fff5cc7dd18 static _PreviewProvider._allPreviews.getter + 165
4630  PreviewsInjection                      0x102ae7f6f 0x102ac4000 + 147311
4731  PreviewsInjection                      0x102ae7ea3 0x102ac4000 + 147107
4832  PreviewsInjection                      0x102ae04b6 0x102ac4000 + 115894
4933  PreviewsInjection                      0x102adc85d 0x102ac4000 + 100445
5034  PreviewsInjection                      0x102adc265 0x102ac4000 + 98917
5135  PreviewsInjection                      0x102adc519 0x102ac4000 + 99609
5236  BoardServices                       0x7fff261a2c1c +[BSXPCServiceConnectionProxy invokeMethod:onTarget:withMessage:forConnection:] + 1596
5337  BoardServices                       0x7fff261b0884 __63-[BSXPCServiceConnectionEventHandler connection:handleMessage:]_block_invoke + 562
5438  BoardServices                       0x7fff261d9879 BSXPCServiceConnectionExecuteCallOut + 325
5539  BoardServices                       0x7fff261b04cf -[BSXPCServiceConnectionEventHandler connection:handleMessage:] + 172
5640  BoardServices                       0x7fff261d8bd7 -[BSXPCServiceConnection _connection_handleMessage:fromPeer:withHandoff:] + 679
5741  libdispatch.dylib                   0x7fff2011265a _dispatch_call_block_and_release + 12
5842  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
5943  libdispatch.dylib                   0x7fff20119e0c _dispatch_lane_serial_drain + 743
6044  libdispatch.dylib                   0x7fff2011aa07 _dispatch_lane_invoke + 455
6145  libdispatch.dylib                   0x7fff20120ba5 _dispatch_main_queue_callback_4CF + 848
6246  CoreFoundation                      0x7fff2036c84d __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
6347  CoreFoundation                      0x7fff203670aa __CFRunLoopRun + 2772
6448  CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
6549  GraphicsServices                    0x7fff2c995cd3 GSEventRunModal + 139
6650  UIKitCore                           0x7fff25059f42 -[UIApplication _run] + 928
6751  UIKitCore                           0x7fff2505eb5e UIApplicationMain + 101
6852  SwiftUI                             0x7fff5d0d5dcf closure #1 in KitRendererCommon(_:) + 196
6953  SwiftUI                             0x7fff5d0d5d09 runApp<A>(_:) + 148
7054  SwiftUI                             0x7fff5cabdbad static App.main() + 61
7155  WeSplit                                0x102732a08 static WeSplitApp.$main() + 72 (WeSplitApp.swift:10)
7256  WeSplit                                0x102732ab3 main + 67
7357  dyld_sim                               0x102969ee9 start_sim + 10
7458  dyld                                   0x108ced4fe start + 462
75
76Thread 1:
770   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
78
79Thread 2::  Dispatch queue: com.apple.root.utility-qos
800   dyld_sim                               0x102973a78 bool SwiftHashTable::equal<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 4
811   dyld_sim                               0x102985e3a unsigned int SwiftHashTable::getIndex<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 126
822   dyld_sim                               0x102985d86 unsigned int SwiftHashTable::getPotentialTarget<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 14
833   dyld_sim                               0x102984ebe dyld4::APIs::_dyld_find_protocol_conformance(void const*, void const*, void const*) const + 168
844   libswiftCore.dylib                  0x7fff30a40b9f swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 191
855   libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
866   libswiftCore.dylib                  0x7fff30a00cea swift::_conformsToProtocol(swift::OpaqueValue const*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptorRef<swift::InProcess>, swift::TargetWitnessTable<swift::InProcess> const**) + 42
877   libswiftCore.dylib                  0x7fff30a3ff3f swift::_checkGenericRequirements(__swift::__runtime::llvm::ArrayRef<swift::TargetGenericRequirementDescriptor<swift::InProcess> >, __swift::__runtime::llvm::SmallVectorImpl<void const*>&, std::__1::function<swift::TargetMetadata<swift::InProcess> const* (unsigned int, unsigned int)>, std::__1::function<swift::TargetWitnessTable<swift::InProcess> const* (swift::TargetMetadata<swift::InProcess> const*, unsigned int)>) + 1839
888   libswiftCore.dylib                  0x7fff30a3f742 swift::TargetProtocolConformanceDescriptor<swift::InProcess>::getWitnessTable(swift::TargetMetadata<swift::InProcess> const*) const + 290
899   libswiftCore.dylib                  0x7fff30a41391 swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 2225
9010  libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
9111  AttributeGraph                      0x7fff4ffaa1e8 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 102
9212  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9313  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9414  AttributeGraph                      0x7fff4ffaa2a4 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 290
9515  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9616  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9717  AttributeGraph                      0x7fff4ffab04b AG::LayoutDescriptor::make_layout(AG::swift::metadata const*, AGComparisonMode, AG::LayoutDescriptor::HeapMode) + 474
9818  AttributeGraph                      0x7fff4ffac36c AG::(anonymous namespace)::LayoutCache::drain_queue(void*) + 142
9919  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
10020  libdispatch.dylib                   0x7fff20124077 _dispatch_root_queue_drain + 788
10121  libdispatch.dylib                   0x7fff20124867 _dispatch_worker_thread2 + 155
10222  libsystem_pthread.dylib             0x7fff6da2f02e _pthread_wqthread + 256
10323  libsystem_pthread.dylib             0x7fff6da2dffb start_wqthread + 15
104
105Thread 3:
1060   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
107
108Thread 4:
1090   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
110
111Thread 5:
1120   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
113
114Thread 6:: com.apple.uikit.eventfetch-thread
1150   libsystem_kernel.dylib              0x7fff6d9d4aba mach_msg_trap + 10
1161   libsystem_kernel.dylib              0x7fff6d9d4e2b mach_msg + 59
1172   CoreFoundation                      0x7fff2036c440 __CFRunLoopServiceMachPort + 319
1183   CoreFoundation                      0x7fff20366ae3 __CFRunLoopRun + 1293
1194   CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
1205   Foundation                          0x7fff2081c754 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 213
1216   Foundation                          0x7fff2081c9cb -[NSRunLoop(NSRunLoop) runUntilDate:] + 72
1227   UIKitCore                           0x7fff2511a2d1 -[UIEventFetcher threadMain] + 491
1238   Foundation                          0x7fff20845550 __NSThread__start__ + 1025
1249   libsystem_pthread.dylib             0x7fff6da324f4 _pthread_start + 125
12510  libsystem_pthread.dylib             0x7fff6da2e00f thread_start + 15
126
127
128Thread 0 crashed with X86 Thread State (64-bit):
129  rax: 0x0000000000000002  rbx: 0x0000000000000000  rcx: 0x00007fff4ffc4b50  rdx: 0x0001000000000028
130  rdi: 0x0000000000000000  rsi: 0x00007fff8b43c050  rbp: 0x00007ff7bd7d2fb0  rsp: 0x00007ff7bd7d2f70
131   r8: 0x00007fff5d231685   r9: 0x00007fff86bdd330  r10: 0x0000000000000004  r11: 0x0000000000000072
132  r12: 0x0000000000000002  r13: 0x00007ff7bd7d30a0  r14: 0x0000000000000040  r15: 0x00007fff8a918d88
133  rip: 0x00007fff5c970f89  rfl: 0x0000000000010246  cr2: 0x00007fff5d2316b7
134  
135Logical CPU:     0
136Error Code:      0x00000000 
137Trap Number:     6
138
139
140Binary Images:
141    0x7fff5c697000 -     0x7fff5d4f2fff com.apple.SwiftUI (3.2.5.0.100) <c680d16f-a317-3c6e-87fa-141c22a715da> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI
142    0x7fff30710000 -     0x7fff30acffff libswiftCore.dylib (*) <6013ecdd-c54d-3948-8b7c-e9f5613107f6> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift/libswiftCore.dylib
143       0x102728000 -        0x102733fff me.choo.minsoo.WeSplit (1.0) <d0012a27-d11a-39a0-b4eb-f874af3b5857> /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/B14B5709-F815-4854-ADB6-E7102668056B/data/Containers/Bundle/Application/BA738B59-7D89-47AA-8012-6234AA6E65B0/WeSplit.app/WeSplit
144    0x7fff4ff96000 -     0x7fff4ffcafff com.apple.AttributeGraph (3.2.1) <20c3feeb-4d9b-3501-be47-de9ae60ae297> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/AttributeGraph.framework/AttributeGraph
145       0x102ac4000 -        0x102af5fff com.apple.dt.PreviewsInjection (13.0) <385f7334-89cd-3998-bc1b-54dd898b38ad> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection
146    0x7fff2619e000 -     0x7fff261edfff com.apple.BoardServices (1.0) <d4742ff1-1051-348e-afb4-dcb3bc434c50> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/BoardServices.framework/BoardServices
147    0x7fff20110000 -     0x7fff20157fff libdispatch.dylib (*) <20999e62-bcc2-377e-8ce7-afda271eb914> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/libdispatch.dylib
148    0x7fff202ec000 -     0x7fff2068bfff com.apple.CoreFoundation (6.9) <c6308add-135b-3a70-9b81-1ce4d994c215> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
149    0x7fff2c992000 -     0x7fff2c99afff com.apple.GraphicsServices (1.0) <adea8ae1-c723-351b-ac2e-22fd2c861c30> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
150    0x7fff2438c000 -     0x7fff25934fff com.apple.UIKitCore (1.0) <3ef2c381-8193-3e3c-801f-925bd1050bd7> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
151       0x102968000 -        0x1029b5fff dyld_sim (*) <3f15c197-2d43-3490-98ff-de85f18dadf2> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/dyld_sim
152       0x108ce8000 -        0x108d53fff dyld (*) <7de33963-bbc5-3996-ba6e-f1d562c17c95> /usr/lib/dyld
153    0x7fff6da2c000 -     0x7fff6da37fff libsystem_pthread.dylib (*) <ee564342-d8f2-396d-b642-40092cf34d82> /usr/lib/system/libsystem_pthread.dylib
154    0x7fff6d9d4000 -     0x7fff6da0afff libsystem_kernel.dylib (*) <c1d58a50-5a4d-3bcb-a1fc-ec0902ce34d3> /usr/lib/system/libsystem_kernel.dylib
155    0x7fff206fa000 -     0x7fff209b0fff com.apple.Foundation (6.9) <61dcc68e-1236-3624-bb6d-a3a850adf63a> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework/Foundation
156
157EOF
158MessageSendFailure: Message send failure for update
159
160==================================
161
162|  MessageError: Connection interrupted
163import SwiftUI
164
165struct ContentView: View {
166    @State private var checkAmount = 0.0
167    @State private var numberOfPeople = 2
168    @State private var tipPercentage = 20
169    let tipPercentages = 0..<101
170    
171    var totalPerPerson: Double {
172        let peopleCount = Double(numberOfPeople + 2)
173        let tipSelection = Double(tipPercentage)
174
175        let tipValue = checkAmount / 100 * tipSelection
176        let grandTotal = checkAmount + tipValue
177        let amountPerPerson = grandTotal / peopleCount
178
179        return amountPerPerson
180    }
181    
182    var total: Double {
183        checkAmount + checkAmount / 100 * Double(tipPercentage)
184    }
185    
186    @FocusState private var amountIsFocused: Bool
187    
188    var body: some View {
189        NavigationView {
190            Form {
191                Section {
192                    TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
193                        .keyboardType(.decimalPad)
194                        .focused($amountIsFocused)
195                
196                    Picker("Number of People", selection: $numberOfPeople) {
197                        ForEach(2..<100) {
198                            Text("\($0) people")
199                        }
200                    }
201                }
202                
203                Section {
204                    Picker("Tip Percentage", selection: $tipPercentage) {
205                        ForEach(tipPercentages, id: \.self) {
206                            Text($0, format: .percent)
207                        }
208                    }
209                } header: {
210                    Text("How much tip do you want to leave?")
211                }
212            
213                Section {
214                    Text(totalPerPerson, format: .currency(code: Locale.current.currencyCode ?? "USD"))
215                } header: {
216                    Text("Amount per person")
217                }
218                
219                Section {
220                    Text(total, format: .currency(code: Locale.current.currencyCode ?? "USD"))
221                }
222            }
223            .navigationTitle("WeSplit")
224        }
225        .toolbar {
226            ToolbarItemGroup(placement: .keyboard) {
227                Spacer()
228                
229                Button("Done") {
230                    amountIsFocused = false
231                }
232            }
233        }
234    }
235}
236
237struct ContentView_Previews: PreviewProvider {
238    static var previews: some View {
239        ContentView()
240    }
241}
242import SwiftUI
243
244@main
245struct WeSplitApp: App {
246    var body: some Scene {
247        WindowGroup {
248            ContentView()
249        }
250    }
251}
252

ANSWER

Answered 2022-Mar-29 at 10:26

Solved by adding ZStack in Preview struct solved it.. This is maybe a bug. Solution

1Exception Type:  EXC_BAD_INSTRUCTION (SIGILL)
2Exception Codes: 0x0000000000000001, 0x0000000000000000
3Exception Note:  EXC_CORPSE_NOTIFY
4Termination Reason: SIGNAL 4 Illegal instruction: 4
5Terminating Process: exc handler [4180]
6
7Triggered by Thread:  0
8
9Application Specific Information:
10CoreSimulator 783.5 - Device: iPod touch (7th generation) (B14B5709-F815-4854-ADB6-E7102668056B) - Runtime: iOS 15.2 (19C51) - DeviceType: iPod touch (7th generation)
11dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
12dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection DYLD_FRAMEWORK_PATH=/Users/minsoochoo/Library/Developer/Xcode/DerivedData/WeSplit-ctmzuorhwkvroxgikiijvbbbfwyq/Build/Intermediates.noindex/Previews/WeSplit/Products/Debug-iphonesimulator
13
14
15Thread 0 Crashed::  Dispatch queue: BSXPCCnx:com.apple.dt.xcode-previews.systemservices (BSCnx:client:com.apple.dt.uv.agent-preview-nonui-service)
160   SwiftUI                             0x7fff5c970f89 static FocusState._makeProperty<A>(in:container:fieldOffset:inputs:) + 160
171   SwiftUI                             0x7fff5c97141e protocol witness for static DynamicProperty._makeProperty<A>(in:container:fieldOffset:inputs:) in conformance FocusState<A> + 25
182   SwiftUI                             0x7fff5d17717c _DynamicPropertyBuffer.addFields<A>(_:container:inputs:baseOffset:) + 131
193   SwiftUI                             0x7fff5d17709a _DynamicPropertyBuffer.init<A>(fields:container:inputs:baseOffset:) + 111
204   SwiftUI                             0x7fff5ce5d24c project #1 <A><A1>(flags:) in closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 413
215   SwiftUI                             0x7fff5ce5d0a4 closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 113
226   SwiftUI                             0x7fff5ce5ebf1 partial apply for closure #1 in BodyAccessor.makeBody(container:inputs:fields:) + 54
237   SwiftUI                             0x7fff5ce5ec12 partial apply for thunk for @callee_guaranteed (@unowned UnsafeMutablePointer<_GraphInputs>) -> (@out _GraphValue<A.BodyAccessor.Body>, @out _DynamicPropertyBuffer?, @error @owned Error) + 27
248   libswiftCore.dylib                  0x7fff3083190c withUnsafePointer<A, B>(to:_:) + 12
259   libswiftCore.dylib                  0x7fff309f2259 withUnsafeMutablePointer<A, B>(to:_:) + 9
2610  SwiftUI                             0x7fff5ce5c68a BodyAccessor.makeBody(container:inputs:fields:) + 286
2711  SwiftUI                             0x7fff5c94b39e static View.makeBody(view:inputs:fields:) + 160
2812  SwiftUI                             0x7fff5c94b0f6 static View.makeViewList(view:inputs:) + 342
2913  SwiftUI                             0x7fff5c94a5f4 static View._makeViewList(view:inputs:) + 104
3014  WeSplit                                0x102730029 protocol witness for static View._makeViewList(view:inputs:) in conformance ContentView + 9
3115  SwiftUI                             0x7fff5ce641cb AnyViewStorage.makeViewList(view:inputs:) + 550
3216  SwiftUI                             0x7fff5ce6526a closure #2 in AnyViewList.updateValue() + 587
3317  SwiftUI                             0x7fff5ce64e76 AnyViewList.updateValue() + 976
3418  SwiftUI                             0x7fff5c83af29 partial apply for specialized implicit closure #2 in implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 15
3519  AttributeGraph                      0x7fff4ff9b37b AG::Graph::UpdateStack::update() + 553
3620  AttributeGraph                      0x7fff4ff9b971 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 411
3721  AttributeGraph                      0x7fff4ffa1656 AG::Graph::value_ref(AG::AttributeID, AGSwiftMetadata const*, unsigned char&) + 128
3822  AttributeGraph                      0x7fff4ffb877a AGGraphGetValue + 291
3923  SwiftUI                             0x7fff5c8b67bd TestableViewContent.list.getter + 47
4024  SwiftUI                             0x7fff5c8b64a6 TestableViewContent.children.getter + 41
4125  SwiftUI                             0x7fff5c8b61f2 View.withChildrenForTest<A>(environment:options:body:) + 181
4226  SwiftUI                             0x7fff5cc7de3f View._allPreviews.getter + 88
4327  SwiftUI                             0x7fff5cc7ddbe MakePreviews.visit<A>(type:) + 128
4428  SwiftUI                             0x7fff5d1a5afc _callVisitViewType2 + 34
4529  SwiftUI                             0x7fff5cc7dd18 static _PreviewProvider._allPreviews.getter + 165
4630  PreviewsInjection                      0x102ae7f6f 0x102ac4000 + 147311
4731  PreviewsInjection                      0x102ae7ea3 0x102ac4000 + 147107
4832  PreviewsInjection                      0x102ae04b6 0x102ac4000 + 115894
4933  PreviewsInjection                      0x102adc85d 0x102ac4000 + 100445
5034  PreviewsInjection                      0x102adc265 0x102ac4000 + 98917
5135  PreviewsInjection                      0x102adc519 0x102ac4000 + 99609
5236  BoardServices                       0x7fff261a2c1c +[BSXPCServiceConnectionProxy invokeMethod:onTarget:withMessage:forConnection:] + 1596
5337  BoardServices                       0x7fff261b0884 __63-[BSXPCServiceConnectionEventHandler connection:handleMessage:]_block_invoke + 562
5438  BoardServices                       0x7fff261d9879 BSXPCServiceConnectionExecuteCallOut + 325
5539  BoardServices                       0x7fff261b04cf -[BSXPCServiceConnectionEventHandler connection:handleMessage:] + 172
5640  BoardServices                       0x7fff261d8bd7 -[BSXPCServiceConnection _connection_handleMessage:fromPeer:withHandoff:] + 679
5741  libdispatch.dylib                   0x7fff2011265a _dispatch_call_block_and_release + 12
5842  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
5943  libdispatch.dylib                   0x7fff20119e0c _dispatch_lane_serial_drain + 743
6044  libdispatch.dylib                   0x7fff2011aa07 _dispatch_lane_invoke + 455
6145  libdispatch.dylib                   0x7fff20120ba5 _dispatch_main_queue_callback_4CF + 848
6246  CoreFoundation                      0x7fff2036c84d __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
6347  CoreFoundation                      0x7fff203670aa __CFRunLoopRun + 2772
6448  CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
6549  GraphicsServices                    0x7fff2c995cd3 GSEventRunModal + 139
6650  UIKitCore                           0x7fff25059f42 -[UIApplication _run] + 928
6751  UIKitCore                           0x7fff2505eb5e UIApplicationMain + 101
6852  SwiftUI                             0x7fff5d0d5dcf closure #1 in KitRendererCommon(_:) + 196
6953  SwiftUI                             0x7fff5d0d5d09 runApp<A>(_:) + 148
7054  SwiftUI                             0x7fff5cabdbad static App.main() + 61
7155  WeSplit                                0x102732a08 static WeSplitApp.$main() + 72 (WeSplitApp.swift:10)
7256  WeSplit                                0x102732ab3 main + 67
7357  dyld_sim                               0x102969ee9 start_sim + 10
7458  dyld                                   0x108ced4fe start + 462
75
76Thread 1:
770   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
78
79Thread 2::  Dispatch queue: com.apple.root.utility-qos
800   dyld_sim                               0x102973a78 bool SwiftHashTable::equal<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 4
811   dyld_sim                               0x102985e3a unsigned int SwiftHashTable::getIndex<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 126
822   dyld_sim                               0x102985d86 unsigned int SwiftHashTable::getPotentialTarget<SwiftTypeProtocolConformanceLocationKey, SwiftTypeProtocolConformanceLocationKey>(SwiftTypeProtocolConformanceLocationKey const&, unsigned char const*) const + 14
833   dyld_sim                               0x102984ebe dyld4::APIs::_dyld_find_protocol_conformance(void const*, void const*, void const*) const + 168
844   libswiftCore.dylib                  0x7fff30a40b9f swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 191
855   libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
866   libswiftCore.dylib                  0x7fff30a00cea swift::_conformsToProtocol(swift::OpaqueValue const*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptorRef<swift::InProcess>, swift::TargetWitnessTable<swift::InProcess> const**) + 42
877   libswiftCore.dylib                  0x7fff30a3ff3f swift::_checkGenericRequirements(__swift::__runtime::llvm::ArrayRef<swift::TargetGenericRequirementDescriptor<swift::InProcess> >, __swift::__runtime::llvm::SmallVectorImpl<void const*>&, std::__1::function<swift::TargetMetadata<swift::InProcess> const* (unsigned int, unsigned int)>, std::__1::function<swift::TargetWitnessTable<swift::InProcess> const* (swift::TargetMetadata<swift::InProcess> const*, unsigned int)>) + 1839
888   libswiftCore.dylib                  0x7fff30a3f742 swift::TargetProtocolConformanceDescriptor<swift::InProcess>::getWitnessTable(swift::TargetMetadata<swift::InProcess> const*) const + 290
899   libswiftCore.dylib                  0x7fff30a41391 swift_conformsToProtocolMaybeInstantiateSuperclasses(swift::TargetMetadata<swift::InProcess> const*, swift::TargetProtocolDescriptor<swift::InProcess> const*, bool) + 2225
9010  libswiftCore.dylib                  0x7fff30a408ce swift_conformsToProtocol + 78
9111  AttributeGraph                      0x7fff4ffaa1e8 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 102
9212  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9313  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9414  AttributeGraph                      0x7fff4ffaa2a4 AG::LayoutDescriptor::Builder::visit_element(AG::swift::metadata const*, AG::swift::metadata::ref_kind, unsigned long) + 290
9515  AttributeGraph                      0x7fff4ff98ea7 AG::swift::metadata_visitor::visit_field(AG::swift::metadata const*, AG::swift::field_record const&, unsigned long) + 79
9616  AttributeGraph                      0x7fff4ff986b8 AG::swift::metadata::visit(AG::swift::metadata_visitor&) const + 648
9717  AttributeGraph                      0x7fff4ffab04b AG::LayoutDescriptor::make_layout(AG::swift::metadata const*, AGComparisonMode, AG::LayoutDescriptor::HeapMode) + 474
9818  AttributeGraph                      0x7fff4ffac36c AG::(anonymous namespace)::LayoutCache::drain_queue(void*) + 142
9919  libdispatch.dylib                   0x7fff2011383a _dispatch_client_callout + 8
10020  libdispatch.dylib                   0x7fff20124077 _dispatch_root_queue_drain + 788
10121  libdispatch.dylib                   0x7fff20124867 _dispatch_worker_thread2 + 155
10222  libsystem_pthread.dylib             0x7fff6da2f02e _pthread_wqthread + 256
10323  libsystem_pthread.dylib             0x7fff6da2dffb start_wqthread + 15
104
105Thread 3:
1060   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
107
108Thread 4:
1090   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
110
111Thread 5:
1120   libsystem_pthread.dylib             0x7fff6da2dfec start_wqthread + 0
113
114Thread 6:: com.apple.uikit.eventfetch-thread
1150   libsystem_kernel.dylib              0x7fff6d9d4aba mach_msg_trap + 10
1161   libsystem_kernel.dylib              0x7fff6d9d4e2b mach_msg + 59
1172   CoreFoundation                      0x7fff2036c440 __CFRunLoopServiceMachPort + 319
1183   CoreFoundation                      0x7fff20366ae3 __CFRunLoopRun + 1293
1194   CoreFoundation                      0x7fff203660f3 CFRunLoopRunSpecific + 567
1205   Foundation                          0x7fff2081c754 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 213
1216   Foundation                          0x7fff2081c9cb -[NSRunLoop(NSRunLoop) runUntilDate:] + 72
1227   UIKitCore                           0x7fff2511a2d1 -[UIEventFetcher threadMain] + 491
1238   Foundation                          0x7fff20845550 __NSThread__start__ + 1025
1249   libsystem_pthread.dylib             0x7fff6da324f4 _pthread_start + 125
12510  libsystem_pthread.dylib             0x7fff6da2e00f thread_start + 15
126
127
128Thread 0 crashed with X86 Thread State (64-bit):
129  rax: 0x0000000000000002  rbx: 0x0000000000000000  rcx: 0x00007fff4ffc4b50  rdx: 0x0001000000000028
130  rdi: 0x0000000000000000  rsi: 0x00007fff8b43c050  rbp: 0x00007ff7bd7d2fb0  rsp: 0x00007ff7bd7d2f70
131   r8: 0x00007fff5d231685   r9: 0x00007fff86bdd330  r10: 0x0000000000000004  r11: 0x0000000000000072
132  r12: 0x0000000000000002  r13: 0x00007ff7bd7d30a0  r14: 0x0000000000000040  r15: 0x00007fff8a918d88
133  rip: 0x00007fff5c970f89  rfl: 0x0000000000010246  cr2: 0x00007fff5d2316b7
134  
135Logical CPU:     0
136Error Code:      0x00000000 
137Trap Number:     6
138
139
140Binary Images:
141    0x7fff5c697000 -     0x7fff5d4f2fff com.apple.SwiftUI (3.2.5.0.100) <c680d16f-a317-3c6e-87fa-141c22a715da> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI
142    0x7fff30710000 -     0x7fff30acffff libswiftCore.dylib (*) <6013ecdd-c54d-3948-8b7c-e9f5613107f6> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift/libswiftCore.dylib
143       0x102728000 -        0x102733fff me.choo.minsoo.WeSplit (1.0) <d0012a27-d11a-39a0-b4eb-f874af3b5857> /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/B14B5709-F815-4854-ADB6-E7102668056B/data/Containers/Bundle/Application/BA738B59-7D89-47AA-8012-6234AA6E65B0/WeSplit.app/WeSplit
144    0x7fff4ff96000 -     0x7fff4ffcafff com.apple.AttributeGraph (3.2.1) <20c3feeb-4d9b-3501-be47-de9ae60ae297> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/AttributeGraph.framework/AttributeGraph
145       0x102ac4000 -        0x102af5fff com.apple.dt.PreviewsInjection (13.0) <385f7334-89cd-3998-bc1b-54dd898b38ad> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/PreviewsInjection.framework/PreviewsInjection
146    0x7fff2619e000 -     0x7fff261edfff com.apple.BoardServices (1.0) <d4742ff1-1051-348e-afb4-dcb3bc434c50> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/BoardServices.framework/BoardServices
147    0x7fff20110000 -     0x7fff20157fff libdispatch.dylib (*) <20999e62-bcc2-377e-8ce7-afda271eb914> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/libdispatch.dylib
148    0x7fff202ec000 -     0x7fff2068bfff com.apple.CoreFoundation (6.9) <c6308add-135b-3a70-9b81-1ce4d994c215> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
149    0x7fff2c992000 -     0x7fff2c99afff com.apple.GraphicsServices (1.0) <adea8ae1-c723-351b-ac2e-22fd2c861c30> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
150    0x7fff2438c000 -     0x7fff25934fff com.apple.UIKitCore (1.0) <3ef2c381-8193-3e3c-801f-925bd1050bd7> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
151       0x102968000 -        0x1029b5fff dyld_sim (*) <3f15c197-2d43-3490-98ff-de85f18dadf2> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/dyld_sim
152       0x108ce8000 -        0x108d53fff dyld (*) <7de33963-bbc5-3996-ba6e-f1d562c17c95> /usr/lib/dyld
153    0x7fff6da2c000 -     0x7fff6da37fff libsystem_pthread.dylib (*) <ee564342-d8f2-396d-b642-40092cf34d82> /usr/lib/system/libsystem_pthread.dylib
154    0x7fff6d9d4000 -     0x7fff6da0afff libsystem_kernel.dylib (*) <c1d58a50-5a4d-3bcb-a1fc-ec0902ce34d3> /usr/lib/system/libsystem_kernel.dylib
155    0x7fff206fa000 -     0x7fff209b0fff com.apple.Foundation (6.9) <61dcc68e-1236-3624-bb6d-a3a850adf63a> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework/Foundation
156
157EOF
158MessageSendFailure: Message send failure for update
159
160==================================
161
162|  MessageError: Connection interrupted
163import SwiftUI
164
165struct ContentView: View {
166    @State private var checkAmount = 0.0
167    @State private var numberOfPeople = 2
168    @State private var tipPercentage = 20
169    let tipPercentages = 0..<101
170    
171    var totalPerPerson: Double {
172        let peopleCount = Double(numberOfPeople + 2)
173        let tipSelection = Double(tipPercentage)
174
175        let tipValue = checkAmount / 100 * tipSelection
176        let grandTotal = checkAmount + tipValue
177        let amountPerPerson = grandTotal / peopleCount
178
179        return amountPerPerson
180    }
181    
182    var total: Double {
183        checkAmount + checkAmount / 100 * Double(tipPercentage)
184    }
185    
186    @FocusState private var amountIsFocused: Bool
187    
188    var body: some View {
189        NavigationView {
190            Form {
191                Section {
192                    TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
193                        .keyboardType(.decimalPad)
194                        .focused($amountIsFocused)
195                
196                    Picker("Number of People", selection: $numberOfPeople) {
197                        ForEach(2..<100) {
198                            Text("\($0) people")
199                        }
200                    }
201                }
202                
203                Section {
204                    Picker("Tip Percentage", selection: $tipPercentage) {
205                        ForEach(tipPercentages, id: \.self) {
206                            Text($0, format: .percent)
207                        }
208                    }
209                } header: {
210                    Text("How much tip do you want to leave?")
211                }
212            
213                Section {
214                    Text(totalPerPerson, format: .currency(code: Locale.current.currencyCode ?? "USD"))
215                } header: {
216                    Text("Amount per person")
217                }
218                
219                Section {
220                    Text(total, format: .currency(code: Locale.current.currencyCode ?? "USD"))
221                }
222            }
223            .navigationTitle("WeSplit")
224        }
225        .toolbar {
226            ToolbarItemGroup(placement: .keyboard) {
227                Spacer()
228                
229                Button("Done") {
230                    amountIsFocused = false
231                }
232            }
233        }
234    }
235}
236
237struct ContentView_Previews: PreviewProvider {
238    static var previews: some View {
239        ContentView()
240    }
241}
242import SwiftUI
243
244@main
245struct WeSplitApp: App {
246    var body: some Scene {
247        WindowGroup {
248            ContentView()
249        }
250    }
251}
252struct ContentView_Previews: PreviewProvider {
253    static var previews: some View {
254       ZStack {
255           ContentView()
256       }
257    }
258}
259

Source https://stackoverflow.com/questions/71272975

QUESTION

Padding scipy affine_transform output to show non-overlapping regions of transformed images

Asked 2022-Mar-28 at 11:54

I have source (src) image(s) I wish to align to a destination (dst) image using an Affine Transformation whilst retaining the full extent of both images during alignment (even the non-overlapping areas).

I am already able to calculate the Affine Transformation rotation and offset matrix, which I feed to scipy.ndimage.interpolate.affine_transform to recover the dst-aligned src image.

The problem is that, when the images are not fuly overlapping, the resultant image is cropped to only the common footprint of the two images. What I need is the full extent of both images, placed on the same pixel coordinate system. This question is almost a duplicate of this one - and the excellent answer and repository there provides this functionality for OpenCV transformations. I unfortunately need this for scipy's implementation.

Much too late, after repeatedly hitting a brick wall trying to translate the above question's answer to scipy, I came across this issue and subsequently followed to this question. The latter question did give some insight into the wonderful world of scipy's affine transformation, but I have as yet been unable to crack my particular needs.

The transformations from src to dst can have translations and rotation. I can get translations only working (an example is shown below) and I can get rotations only working (largely hacking around the below and taking inspiration from the use of the reshape argument in scipy.ndimage.interpolation.rotate). However, I am getting thoroughly lost combining the two. I have tried to calculate what should be the correct offset (see this question's answers again), but I can't get it working in all scenarios.

Translation-only working example of padded affine transformation, which follows largely this repo, explained in this answer:

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106

e.g.:

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106affine_test(0, (-20, 40))
107

gives:

enter image description here

With a zoom in showing the aligned in the padded images:

enter image description here

I require the full extent of the src and dst images aligned on the same pixel coordinates, with both rotations and translations.

Any help is greatly appreciated!

ANSWER

Answered 2022-Mar-22 at 16:44

If you have two images that are similar (or the same) and you want to align them, you can do it using both functions rotate and shift :

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106affine_test(0, (-20, 40))
107from scipy.ndimage import rotate, shift
108

You need to find first the difference of angle between the two images angle_to_rotate, having that you apply a rotation to src:

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106affine_test(0, (-20, 40))
107from scipy.ndimage import rotate, shift
108angle_to_rotate = 25
109rotated_src = rotate(src, angle_to_rotate , reshape=True, order=1, mode="constant")
110

With reshape=True you avoid losing information from your original src matrix, and it pads the result so the image could be translated around the 0,0 indexes. You can calculate this translation as it is (x*cos(angle),y*sin(angle) where x and y are the dimensions of the image, but it probably won't matter.

Now you will need to translate the image to the source, for doing that you can use the shift function:

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106affine_test(0, (-20, 40))
107from scipy.ndimage import rotate, shift
108angle_to_rotate = 25
109rotated_src = rotate(src, angle_to_rotate , reshape=True, order=1, mode="constant")
110rot_translated_src = shift(rotated_src , [distance_x, distance_y])
111

In this case there is no reshape (because otherwise you wouldn't have any real translation) so if the image was not previously padded some information will be lost.

But you can do some padding with

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106affine_test(0, (-20, 40))
107from scipy.ndimage import rotate, shift
108angle_to_rotate = 25
109rotated_src = rotate(src, angle_to_rotate , reshape=True, order=1, mode="constant")
110rot_translated_src = shift(rotated_src , [distance_x, distance_y])
111np.pad(src, number, mode='constant')
112

To calculate distance_x and distance_y you will need to find a point that serves you as a reference between the rotated_src and the destination, then just calculate the distance in the x and y axis.

Summary

  1. Make some padding in src, and dst
  2. Find the angular distance between them.
  3. Rotate src with scipy.ndimage.rotate using reshape=True
  4. Find the horizontal and vertical distance distance_x, distance_y between the rotated image and dst
  5. Translate your 'rotated_src' with scipy.ndimage.shift

Code

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106affine_test(0, (-20, 40))
107from scipy.ndimage import rotate, shift
108angle_to_rotate = 25
109rotated_src = rotate(src, angle_to_rotate , reshape=True, order=1, mode="constant")
110rot_translated_src = shift(rotated_src , [distance_x, distance_y])
111np.pad(src, number, mode='constant')
112from scipy.ndimage import rotate, shift
113import matplotlib.pyplot as plt
114import numpy as np
115

First we make the destination image:

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106affine_test(0, (-20, 40))
107from scipy.ndimage import rotate, shift
108angle_to_rotate = 25
109rotated_src = rotate(src, angle_to_rotate , reshape=True, order=1, mode="constant")
110rot_translated_src = shift(rotated_src , [distance_x, distance_y])
111np.pad(src, number, mode='constant')
112from scipy.ndimage import rotate, shift
113import matplotlib.pyplot as plt
114import numpy as np
115# make and plot dest
116dst = np.ones([40,20])
117dst = np.pad(dst,10)
118dst[17,[14,24]]=4
119dst[27,14:25]=4
120dst[26,[14,25]]=4
121rotated_dst = rotate(dst, 20, order=1)
122
123plt.imshow(dst) # plot it
124plt.imshow(rotated_dst)
125plt.show()
126

We make the Source image:

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106affine_test(0, (-20, 40))
107from scipy.ndimage import rotate, shift
108angle_to_rotate = 25
109rotated_src = rotate(src, angle_to_rotate , reshape=True, order=1, mode="constant")
110rot_translated_src = shift(rotated_src , [distance_x, distance_y])
111np.pad(src, number, mode='constant')
112from scipy.ndimage import rotate, shift
113import matplotlib.pyplot as plt
114import numpy as np
115# make and plot dest
116dst = np.ones([40,20])
117dst = np.pad(dst,10)
118dst[17,[14,24]]=4
119dst[27,14:25]=4
120dst[26,[14,25]]=4
121rotated_dst = rotate(dst, 20, order=1)
122
123plt.imshow(dst) # plot it
124plt.imshow(rotated_dst)
125plt.show()
126# make_src image and plot it
127src = np.zeros([40,20])
128src = np.pad(src,10)
129src[0:20,0:20]=1
130src[7,[4,14]]=4
131src[17,4:15]=4
132src[16,[4,15]]=4
133plt.imshow(src)
134plt.show()
135

Then we align the src to the destination:

1from scipy.ndimage import rotate, affine_transform
2import numpy as np
3import matplotlib.pyplot as plt
4
5nblob = 50
6shape = (200, 100)
7buffered_shape = (300, 200)  # buffer for rotation and translation
8
9
10def affine_test(angle=0, translate=(0, 0)):
11    np.random.seed(42)
12    # Maxiumum translation allowed is half difference between shape and buffered_shape
13
14    # Generate a buffered_shape-sized base image with random blobs
15    base = np.zeros(buffered_shape, dtype=np.float32)
16    random_locs = np.random.choice(np.arange(2, buffered_shape[0] - 2), nblob * 2, replace=False)
17    i = random_locs[:nblob]
18    j = random_locs[nblob:]
19    for k, (_i, _j) in enumerate(zip(i, j)):
20        # Use different values, just to make it easier to distinguish blobs
21        base[_i - 2 : _i + 2, _j - 2 : _j + 2] = k + 10
22
23    # Impose a rotation and translation on source
24    src = rotate(base, angle, reshape=False, order=1, mode="constant")
25    bsc = (np.array(buffered_shape) / 2).astype(int)
26    sc = (np.array(shape) / 2).astype(int)
27    src = src[
28        bsc[0] - sc[0] + translate[0] : bsc[0] + sc[0] + translate[0],
29        bsc[1] - sc[1] + translate[1] : bsc[1] + sc[1] + translate[1],
30    ]
31    # Cut-out destination from the centre of the base image
32    dst = base[bsc[0] - sc[0] : bsc[0] + sc[0], bsc[1] - sc[1] : bsc[1] + sc[1]]
33
34    src_y, src_x = src.shape
35
36    def get_matrix_offset(centre, angle, scale):
37        """Follows OpenCV.getRotationMatrix2D"""
38        angle = angle * np.pi / 180
39        alpha = scale * np.cos(angle)
40        beta = scale * np.sin(angle)
41        return (
42            np.array([[alpha, beta], [-beta, alpha]]),
43            np.array(
44                [
45                    (1 - alpha) * centre[0] - beta * centre[1],
46                    beta * centre[0] + (1 - alpha) * centre[1],
47                ]
48            ),
49        )
50    # Obtain the rotation matrix and offset that describes the transformation
51    # between src and dst
52    matrix, offset = get_matrix_offset(np.array([src_y / 2, src_x / 2]), angle, 1)
53    offset = offset - translate
54
55    # Determine the outer bounds of the new image
56    lin_pts = np.array([[0, src_x, src_x, 0], [0, 0, src_y, src_y]])
57    transf_lin_pts = np.dot(matrix.T, lin_pts) - offset[::-1].reshape(2, 1)
58
59    # Find min and max bounds of the transformed image
60    min_x = np.floor(np.min(transf_lin_pts[0])).astype(int)
61    min_y = np.floor(np.min(transf_lin_pts[1])).astype(int)
62    max_x = np.ceil(np.max(transf_lin_pts[0])).astype(int)
63    max_y = np.ceil(np.max(transf_lin_pts[1])).astype(int)
64
65    # Add translation to the transformation matrix to shift to positive values
66    anchor_x, anchor_y = 0, 0
67    if min_x < 0:
68        anchor_x = -min_x
69    if min_y < 0:
70        anchor_y = -min_y
71    shifted_offset = offset - np.dot(matrix, [anchor_y, anchor_x])
72
73    # Create padded destination image
74    dst_h, dst_w = dst.shape[:2]
75    pad_widths = [anchor_y, max(max_y, dst_h) - dst_h, anchor_x, max(max_x, dst_w) - dst_w]
76    dst_padded = np.pad(
77        dst,
78        ((pad_widths[0], pad_widths[1]), (pad_widths[2], pad_widths[3])),
79        "constant",
80        constant_values=-1,
81    )
82    dst_pad_h, dst_pad_w = dst_padded.shape
83
84    # Create the aligned and padded source image
85    source_aligned = affine_transform(
86        src,
87        matrix.T,
88        offset=shifted_offset,
89        output_shape=(dst_pad_h, dst_pad_w),
90        order=3,
91        mode="constant",
92        cval=-1,
93    )
94
95    # Plot the images
96    fig, axes = plt.subplots(1, 4, figsize=(10, 5), sharex=True, sharey=True)
97    axes[0].imshow(src, cmap="viridis", vmin=-1, vmax=nblob)
98    axes[0].set_title("Source")
99    axes[1].imshow(dst, cmap="viridis", vmin=-1, vmax=nblob)
100    axes[1].set_title("Dest")
101    axes[2].imshow(source_aligned, cmap="viridis", vmin=-1, vmax=nblob)
102    axes[2].set_title("Source aligned to Dest padded")
103    axes[3].imshow(dst_padded, cmap="viridis", vmin=-1, vmax=nblob)
104    axes[3].set_title("Dest padded")
105    plt.show()
106affine_test(0, (-20, 40))
107from scipy.ndimage import rotate, shift
108angle_to_rotate = 25
109rotated_src = rotate(src, angle_to_rotate , reshape=True, order=1, mode="constant")
110rot_translated_src = shift(rotated_src , [distance_x, distance_y])
111np.pad(src, number, mode='constant')
112from scipy.ndimage import rotate, shift
113import matplotlib.pyplot as plt
114import numpy as np
115# make and plot dest
116dst = np.ones([40,20])
117dst = np.pad(dst,10)
118dst[17,[14,24]]=4
119dst[27,14:25]=4
120dst[26,[14,25]]=4
121rotated_dst = rotate(dst, 20, order=1)
122
123plt.imshow(dst) # plot it
124plt.imshow(rotated_dst)
125plt.show()
126# make_src image and plot it
127src = np.zeros([40,20])
128src = np.pad(src,10)
129src[0:20,0:20]=1
130src[7,[4,14]]=4
131src[17,4:15]=4
132src[16,[4,15]]=4
133plt.imshow(src)
134plt.show()
135rotated_src = rotate(src, 20, order=1) # find the angle 20, reshape true is by default
136plt.imshow(rotated_src)
137plt.show()
138distance_y = 8 # find this distances from rotated_src and dst
139distance_x = 12 # use any visual reference or even the corners
140translated_src = shift(rotated_src, [distance_y,distance_x])
141plt.imshow(translated_src)
142plt.show()
143

pd: If you find problems to find the angle and the distances in a programmatic way, please leave a comment providing a bit more of insight of what can be used as a reference that could be for example the frame of the image or some image features / data)

Source https://stackoverflow.com/questions/71516584

QUESTION

How to make isort always produce multi-line output when there are multiple imports on a line?

Asked 2022-Mar-07 at 06:44

I'm currently using isort --profile=black --line-length=79 as a linter in my project for python files.

This produces the Vertical Hanging Indent (mode 3 in isort's documentation kind of output:

1from third_party import (
2    lib1,
3    lib2,
4    lib3,
5    lib4,
6)
7

This multiline mode only applies if the line is longer than 79 characters, though. Is there a mode that cause a multiline output as soon as there are two or more imports on the same line, no matter how long the line is?

I tried hacking it with isort -m=3 --trailing-comma --line-length=1, but shorter line length will cause multiline output even when there is a single import, which I don't want:

1from third_party import (
2    lib1,
3    lib2,
4    lib3,
5    lib4,
6)
7from third_party import (
8    lib1,
9)
10

ANSWER

Answered 2022-Mar-07 at 06:44

You should use the --force-grid-wrap 2 flag in the CLI or set in the settings file like pyproject.toml option force_grid_wrap = 2. This would force isort to produce multiline output for 2 or more imports, regardless of line length. More info about this option

Source https://stackoverflow.com/questions/69205085

QUESTION

Specialising Range or overloading ".."

Asked 2022-Feb-10 at 05:54

I have a little library where I can define integer types. These are intended for type-safe indexing into arrays and strings in the kind of algorithms I often write. For example, I can use it to define an offset type, Offset and an index type, Idx such that you can get an Offset by subtracting two Idx, you can get Idx by adding or subtracting Offset, but you cannot for example multiple or add Idx.

1let (i,j): (Idx,Idx) = ...;
2let offset: Offset = j - i; // Subtracting indices gives an offset
3let k: Idx = j + offset; // Adding an offset to an index gives an index
4// let _ = i + j; -- You can't add indices
5

I managed (with some difficulty) to implement std::iter::Step so I can also iterate through a range of indices

1let (i,j): (Idx,Idx) = ...;
2let offset: Offset = j - i; // Subtracting indices gives an offset
3let k: Idx = j + offset; // Adding an offset to an index gives an index
4// let _ = i + j; -- You can't add indices
5for k in i .. j { /* ... */ }
6

but now I've set my eyes on a higher goal: I also want to use ranges of these types to slice into sequences

1let (i,j): (Idx,Idx) = ...;
2let offset: Offset = j - i; // Subtracting indices gives an offset
3let k: Idx = j + offset; // Adding an offset to an index gives an index
4// let _ = i + j; -- You can't add indices
5for k in i .. j { /* ... */ }
6let v: Vec<sometype> = vec![...];
7let w: &[sometype] = &v[i..j]; // Slice with a range of Idx
8

This should be a simple matter of implementing std::ops::Index and std::ops::IndexMut, except that the type system won't let me implement

1let (i,j): (Idx,Idx) = ...;
2let offset: Offset = j - i; // Subtracting indices gives an offset
3let k: Idx = j + offset; // Adding an offset to an index gives an index
4// let _ = i + j; -- You can't add indices
5for k in i .. j { /* ... */ }
6let v: Vec<sometype> = vec![...];
7let w: &[sometype] = &v[i..j]; // Slice with a range of Idx
8impl<I,T> std::ops::Index<std::ops::Range<I>> for Vec<T>
9where I: /* my types */
10{ ... }
11

for a wrapper type, or a generic

1let (i,j): (Idx,Idx) = ...;
2let offset: Offset = j - i; // Subtracting indices gives an offset
3let k: Idx = j + offset; // Adding an offset to an index gives an index
4// let _ = i + j; -- You can't add indices
5for k in i .. j { /* ... */ }
6let v: Vec<sometype> = vec![...];
7let w: &[sometype] = &v[i..j]; // Slice with a range of Idx
8impl<I,T> std::ops::Index<std::ops::Range<I>> for Vec<T>
9where I: /* my types */
10{ ... }
11impl<I,T> std::ops::Index<std::ops::Range<Wrapper<I>>> for Vec<T>
12where I: /* my types */
13{ ... }
14

where Wrapper is the type I actually use and I a trait that helps me write generic code.

The problem is that both Index and Range are defined outside of my crate, so this kind of specialisation is not allowed. Or is it?

Is there any way that I can implement a trait for a generic type outside my crate when its generic parameters are from within my crate?

Or, better still, is there any way to tap into the syntactic sugar of the .. operator, so I can get a wrapped type? What I really want is to wrap Range to get the same behaviour and then some. I can do that by wrapping Range and implementing Deref, but if I go that route, I lose the syntactic sugar of the .. operator.

It is not a big problem, but I can imagine some confusion when you could write

1let (i,j): (Idx,Idx) = ...;
2let offset: Offset = j - i; // Subtracting indices gives an offset
3let k: Idx = j + offset; // Adding an offset to an index gives an index
4// let _ = i + j; -- You can't add indices
5for k in i .. j { /* ... */ }
6let v: Vec<sometype> = vec![...];
7let w: &[sometype] = &v[i..j]; // Slice with a range of Idx
8impl<I,T> std::ops::Index<std::ops::Range<I>> for Vec<T>
9where I: /* my types */
10{ ... }
11impl<I,T> std::ops::Index<std::ops::Range<Wrapper<I>>> for Vec<T>
12where I: /* my types */
13{ ... }
14for k in i .. j { /* ... */ }
15

like you can for the built-in types, but you have to use

1let (i,j): (Idx,Idx) = ...;
2let offset: Offset = j - i; // Subtracting indices gives an offset
3let k: Idx = j + offset; // Adding an offset to an index gives an index
4// let _ = i + j; -- You can't add indices
5for k in i .. j { /* ... */ }
6let v: Vec<sometype> = vec![...];
7let w: &[sometype] = &v[i..j]; // Slice with a range of Idx
8impl<I,T> std::ops::Index<std::ops::Range<I>> for Vec<T>
9where I: /* my types */
10{ ... }
11impl<I,T> std::ops::Index<std::ops::Range<Wrapper<I>>> for Vec<T>
12where I: /* my types */
13{ ... }
14for k in i .. j { /* ... */ }
15let w: &[type] = &v[range(i,j)];
16

for slicing. It gets even more cumbersome if I want to allow slices such as i.., ..j to be wrapped. (The .. slice doesn't matter here, it won't get my types anyway). If I did that, I would need constructors for three types of ranges, or some ugly wrapping using Option, I think.

The .. syntactic sugar is really neat, but from what I have explored you just cannot use that much for ranges of your own types. You can define ranges and you can, with some hacking, iterate through them, but you can't index with them.

Tell me I'm wrong, or let me know if there are any tricks that gets the job done, or even half-done. Or, if this is indeed impossible, let me know so I can stop wasting time on it and write a wrapper class and give up on the .. operator.

Update I have put a simplified example in playgrounds

ANSWER

Answered 2022-Feb-10 at 05:54

No, you can't.

By definition of the orphan rules:

Given impl<P1..=Pn> Trait<T1..=Tn> for T0, an impl is valid only if at least one of the following is true:

  • Trait is a local trait
  • All of
    • At least one of the types T0..=Tn must be a local type. Let Ti be the first such type.
    • No uncovered type parameters P1..=Pn may appear in T0..Ti (excluding Ti)

Only the appearance of uncovered type parameters is restricted. Note that for the purposes of coherence, fundamental types are special. The T in Box is not considered covered, and Box is considered local.

Local trait

A trait which was defined in the current crate. A trait definition is local or not independent of applied type arguments. Given trait Foo<T, U>, Foo is always local, regardless of the types substituted for T and U.

Local type

A struct, enum, or union which was defined in the current crate. This is not affected by applied type arguments. struct Foo is considered local, but Vec<Foo> is not. LocalType<ForeignType> is local. Type aliases do not affect locality.

As neither Index nor Range nor Vec are local, and Range is not a fundamental type, you cannot impl<T> Index<Range<...>> for Vec<T>, no matter what you put in the place of the ....

The reason for these rules is that nothing prevents Range or Vec from implementing impl<T, Idx> Index<Range<Idx>> for Vec<T>. Such impl does not exist, and probably never will, but the rules are the same among all types, and in the general case this definitely can happen.

You cannot overload the range operator either - it always creates a Range (or RangeInclusive, RangeFull, etc.).

The only solution I can think about is to create a newtype wrapper for Vec, as suggested in the comments.

If you want your vector to return a wrapped slice, you can use a bit of unsafe code:

1let (i,j): (Idx,Idx) = ...;
2let offset: Offset = j - i; // Subtracting indices gives an offset
3let k: Idx = j + offset; // Adding an offset to an index gives an index
4// let _ = i + j; -- You can't add indices
5for k in i .. j { /* ... */ }
6let v: Vec&lt;sometype&gt; = vec![...];
7let w: &amp;[sometype] = &amp;v[i..j]; // Slice with a range of Idx
8impl&lt;I,T&gt; std::ops::Index&lt;std::ops::Range&lt;I&gt;&gt; for Vec&lt;T&gt;
9where I: /* my types */
10{ ... }
11impl&lt;I,T&gt; std::ops::Index&lt;std::ops::Range&lt;Wrapper&lt;I&gt;&gt;&gt; for Vec&lt;T&gt;
12where I: /* my types */
13{ ... }
14for k in i .. j { /* ... */ }
15let w: &amp;[type] = &amp;v[range(i,j)];
16use std::ops::{Index, IndexMut, Range, Deref, DerefMut};
17
18#[repr(transparent)] // Because of this we can soundly cast `&amp;{mut }[T]` to `&amp;{mut }MySlice&lt;T&gt;`.
19pub struct MySlice&lt;T&gt;([T]);
20
21impl&lt;'a, T&gt; From&lt;&amp;'a [T]&gt; for &amp;'a MySlice&lt;T&gt; {
22    fn from(v: &amp;'a [T]) -&gt; &amp;'a MySlice&lt;T&gt; {
23        unsafe { &amp;*(v as *const [T] as *const MySlice&lt;T&gt;) }
24    }
25}
26impl&lt;'a, T&gt; From&lt;&amp;'a mut [T]&gt; for &amp;'a mut MySlice&lt;T&gt; {
27    fn from(v: &amp;'a mut [T]) -&gt; &amp;'a mut MySlice&lt;T&gt; {
28        unsafe { &amp;mut *(v as *mut [T] as *mut MySlice&lt;T&gt;) }
29    }
30}
31
32impl&lt;T&gt; Index&lt;usize&gt; for MySlice&lt;T&gt; {
33    type Output = T;
34    fn index(&amp;self, idx: usize) -&gt; &amp;Self::Output { &amp;self.0[idx] }
35}
36impl&lt;T&gt; IndexMut&lt;usize&gt; for MySlice&lt;T&gt; {
37    fn index_mut(&amp;mut self, idx: usize) -&gt; &amp;mut Self::Output { &amp;mut self.0[idx] }
38}
39
40impl&lt;T&gt; Index&lt;Range&lt;usize&gt;&gt; for MySlice&lt;T&gt; {
41    type Output = MySlice&lt;T&gt;;
42    fn index(&amp;self, idx: Range&lt;usize&gt;) -&gt; &amp;Self::Output { self.0[idx].into() }
43}
44impl&lt;T&gt; IndexMut&lt;Range&lt;usize&gt;&gt; for MySlice&lt;T&gt; {
45    fn index_mut(&amp;mut self, idx: Range&lt;usize&gt;) -&gt; &amp;mut Self::Output { (&amp;mut self.0[idx]).into() }
46}
47// And so on, for all range types...
48
49pub struct MyVec&lt;T&gt;(pub Vec&lt;T&gt;);
50
51impl&lt;T&gt; Deref for MyVec&lt;T&gt; {
52    type Target = MySlice&lt;T&gt;;
53    fn deref(&amp;self) -&gt; &amp;Self::Target { self.0.as_slice().into() }
54}
55impl&lt;T&gt; DerefMut for MyVec&lt;T&gt; {
56    fn deref_mut(&amp;mut self) -&gt; &amp;mut Self::Target { self.0.as_mut_slice().into() }
57}
58

Source https://stackoverflow.com/questions/71017029

QUESTION

Why is there extra space alongside my carousel images?

Asked 2022-Feb-01 at 19:44

I am not a coder by trade, but am working on hacking together an image carousel for our website. I've gotten everything to work except for this last weird problem I am having with spacing. In the attached image, you'll see there is too much spacing between the screenshot and the next-image button to the right of it.

Here is a screenshot of the spacing problem

Here is the code (apologies in advance, it is truly terrible):

1// Declaring variable array of images. You can put as many as you want.
2const myimages = ["https://www.agathos.io/hs-fs/hubfs/text%20v2%20gimp.png?width=534&amp;height=1136&amp;name=text%20v2%20gimp.png", "https://i.imgur.com/uoAHQ17.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg"];
3const mycaptions = ["Once a week, physicians receive a text letting them know specific information about how they are handling a particular practice area. Curious to learn more, they follow the link for a deeper look. What is nice about this approach is that it is easy and can be accessed at a time convenient to physician.", "Test caption 2", "Test caption 3", "Test caption 4", "Test caption 5"]; 
4
5const prevBtn = document.getElementById("p-10-s-i-s-prev-btn");  // assigning variable for previous button
6const nextBtn = document.getElementById("p-10-s-i-s-next-btn");  // assigning variable for next button
7const imageContainer = document.getElementById("p-10-s-i-s-image-container"); // assigning variable for image container div
8const captionContainer = document.getElementById("p-11-s-i-s-caption-place-holder");
9var myimage = myimages[0]; // Assigning initial value for the varibale to show on page loading and showing first image.
10var mycaption = mycaptions[0]; // Assigning and showing the first caption of the first image.
11
12imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
13captionContainer.innerHTML = mycaption;
14
15
16var counter = 0;
17prevBtn.addEventListener("click", function(){
18    if (counter &gt; 0 &amp;&amp; counter &lt; myimages.length){
19            counter--;
20            myimage = myimages[counter];
21            mycaption = mycaptions[counter];
22            imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
23            captionContainer.innerHTML = mycaption;
24        }
25    });
26
27nextBtn.addEventListener("click", function(){
28    if (counter &lt; myimages.length-1){
29        counter++;
30        myimage = myimages[counter];
31        mycaption = mycaptions[counter];
32        imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
33        captionContainer.innerHTML = mycaption;
34    }
35});
1// Declaring variable array of images. You can put as many as you want.
2const myimages = ["https://www.agathos.io/hs-fs/hubfs/text%20v2%20gimp.png?width=534&amp;height=1136&amp;name=text%20v2%20gimp.png", "https://i.imgur.com/uoAHQ17.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg"];
3const mycaptions = ["Once a week, physicians receive a text letting them know specific information about how they are handling a particular practice area. Curious to learn more, they follow the link for a deeper look. What is nice about this approach is that it is easy and can be accessed at a time convenient to physician.", "Test caption 2", "Test caption 3", "Test caption 4", "Test caption 5"]; 
4
5const prevBtn = document.getElementById("p-10-s-i-s-prev-btn");  // assigning variable for previous button
6const nextBtn = document.getElementById("p-10-s-i-s-next-btn");  // assigning variable for next button
7const imageContainer = document.getElementById("p-10-s-i-s-image-container"); // assigning variable for image container div
8const captionContainer = document.getElementById("p-11-s-i-s-caption-place-holder");
9var myimage = myimages[0]; // Assigning initial value for the varibale to show on page loading and showing first image.
10var mycaption = mycaptions[0]; // Assigning and showing the first caption of the first image.
11
12imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
13captionContainer.innerHTML = mycaption;
14
15
16var counter = 0;
17prevBtn.addEventListener("click", function(){
18    if (counter &gt; 0 &amp;&amp; counter &lt; myimages.length){
19            counter--;
20            myimage = myimages[counter];
21            mycaption = mycaptions[counter];
22            imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
23            captionContainer.innerHTML = mycaption;
24        }
25    });
26
27nextBtn.addEventListener("click", function(){
28    if (counter &lt; myimages.length-1){
29        counter++;
30        myimage = myimages[counter];
31        mycaption = mycaptions[counter];
32        imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
33        captionContainer.innerHTML = mycaption;
34    }
35});.p-10-s-i-s-page-background{
36    width: 100%;
37    height: 100%;
38    display: flex;
39    flex-direction: column;
40    align-items: center;
41}
42
43.p-10-simple-image-slider-wrapper{
44    max-width: 45%;
45    height: auto;
46    display: flex;
47    align-items: center;
48    justify-content: center;
49    margin-bottom: 20px;
50}
51
52#p-10-s-i-s-image-container{
53    max-width: 70%;
54    height: auto;
55    display: flex;
56    justify-content: space-between;
57}
58
59#p-10-s-i-s-image-container img{
60    max-width: 70%;
61    height: auto;
62    display: flex;
63    align-items: center;
64    animation: p-10-image-animation 1s;
65    
66}
67
68#p-10-s-i-s-prev-btn, #p-10-s-i-s-next-btn{
69    width: 50px;
70    font-family: 'Open Sans', sans-serif;
71    font-size: 50px;
72    display: flex;
73    flex: 1;
74    align-items: center;
75    cursor: pointer;
76    color: orange;
77}
78
79#p-10-s-i-s-prev-btn:hover, #p-10-s-i-s-next-btn:hover{
80    
81    transition: all 1s;
82    
83}
84
85.p-10-s-i-s-page-background h1{
86    color: rgb(243, 236, 176);
87}
88
89@keyframes p-10-image-animation{
90    0%{
91        opacity: 0.5;
92    }
93    100%{
94        opacity: 1;
95    }
96}
97
98#p-11-s-i-s-caption-place-holder{
99    padding: 5px 150px 5px 150px;
100    font-family: 'Open Sans', sans-serif;
101    color: #565555;
102    text-align: left;
103    font-size: 18px;
104    line-height: 150%;
105    margin-bottom: 20px;
106}
107
108.yvanaplaceholder{
109  display: flex;
110  text-align: center;
111  justify-content: center;
112}
113
114.yvana{
115  color: darkgreen;
116  text-decoration: none;
117 }
118
119.name{
120  color: crimson;
121}
1// Declaring variable array of images. You can put as many as you want.
2const myimages = ["https://www.agathos.io/hs-fs/hubfs/text%20v2%20gimp.png?width=534&amp;height=1136&amp;name=text%20v2%20gimp.png", "https://i.imgur.com/uoAHQ17.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg"];
3const mycaptions = ["Once a week, physicians receive a text letting them know specific information about how they are handling a particular practice area. Curious to learn more, they follow the link for a deeper look. What is nice about this approach is that it is easy and can be accessed at a time convenient to physician.", "Test caption 2", "Test caption 3", "Test caption 4", "Test caption 5"]; 
4
5const prevBtn = document.getElementById("p-10-s-i-s-prev-btn");  // assigning variable for previous button
6const nextBtn = document.getElementById("p-10-s-i-s-next-btn");  // assigning variable for next button
7const imageContainer = document.getElementById("p-10-s-i-s-image-container"); // assigning variable for image container div
8const captionContainer = document.getElementById("p-11-s-i-s-caption-place-holder");
9var myimage = myimages[0]; // Assigning initial value for the varibale to show on page loading and showing first image.
10var mycaption = mycaptions[0]; // Assigning and showing the first caption of the first image.
11
12imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
13captionContainer.innerHTML = mycaption;
14
15
16var counter = 0;
17prevBtn.addEventListener("click", function(){
18    if (counter &gt; 0 &amp;&amp; counter &lt; myimages.length){
19            counter--;
20            myimage = myimages[counter];
21            mycaption = mycaptions[counter];
22            imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
23            captionContainer.innerHTML = mycaption;
24        }
25    });
26
27nextBtn.addEventListener("click", function(){
28    if (counter &lt; myimages.length-1){
29        counter++;
30        myimage = myimages[counter];
31        mycaption = mycaptions[counter];
32        imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
33        captionContainer.innerHTML = mycaption;
34    }
35});.p-10-s-i-s-page-background{
36    width: 100%;
37    height: 100%;
38    display: flex;
39    flex-direction: column;
40    align-items: center;
41}
42
43.p-10-simple-image-slider-wrapper{
44    max-width: 45%;
45    height: auto;
46    display: flex;
47    align-items: center;
48    justify-content: center;
49    margin-bottom: 20px;
50}
51
52#p-10-s-i-s-image-container{
53    max-width: 70%;
54    height: auto;
55    display: flex;
56    justify-content: space-between;
57}
58
59#p-10-s-i-s-image-container img{
60    max-width: 70%;
61    height: auto;
62    display: flex;
63    align-items: center;
64    animation: p-10-image-animation 1s;
65    
66}
67
68#p-10-s-i-s-prev-btn, #p-10-s-i-s-next-btn{
69    width: 50px;
70    font-family: 'Open Sans', sans-serif;
71    font-size: 50px;
72    display: flex;
73    flex: 1;
74    align-items: center;
75    cursor: pointer;
76    color: orange;
77}
78
79#p-10-s-i-s-prev-btn:hover, #p-10-s-i-s-next-btn:hover{
80    
81    transition: all 1s;
82    
83}
84
85.p-10-s-i-s-page-background h1{
86    color: rgb(243, 236, 176);
87}
88
89@keyframes p-10-image-animation{
90    0%{
91        opacity: 0.5;
92    }
93    100%{
94        opacity: 1;
95    }
96}
97
98#p-11-s-i-s-caption-place-holder{
99    padding: 5px 150px 5px 150px;
100    font-family: 'Open Sans', sans-serif;
101    color: #565555;
102    text-align: left;
103    font-size: 18px;
104    line-height: 150%;
105    margin-bottom: 20px;
106}
107
108.yvanaplaceholder{
109  display: flex;
110  text-align: center;
111  justify-content: center;
112}
113
114.yvana{
115  color: darkgreen;
116  text-decoration: none;
117 }
118
119.name{
120  color: crimson;
121}&lt;div class="p-10-s-i-s-page-background"&gt;
122    &lt;div id="p-11-s-i-s-caption-place-holder"&gt;
123    &lt;/div&gt;
124  
125  &lt;div class="p-10-simple-image-slider-wrapper"&gt;
126        &lt;div id="p-10-s-i-s-prev-btn"&gt;&amp;#60;&lt;/div&gt;
127        &lt;div id="p-10-s-i-s-image-container" &gt;&lt;/div&gt;
128        &lt;div id="p-10-s-i-s-next-btn"&gt;&amp;#62;&lt;/div&gt;
129    &lt;/div&gt;
130&lt;/div&gt;

ANSWER

Answered 2022-Feb-01 at 19:44

Replacing justify-content: space-between with justify-content: center in #p-10-s-i-s-image-container will fix that.

1// Declaring variable array of images. You can put as many as you want.
2const myimages = ["https://www.agathos.io/hs-fs/hubfs/text%20v2%20gimp.png?width=534&amp;height=1136&amp;name=text%20v2%20gimp.png", "https://i.imgur.com/uoAHQ17.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg"];
3const mycaptions = ["Once a week, physicians receive a text letting them know specific information about how they are handling a particular practice area. Curious to learn more, they follow the link for a deeper look. What is nice about this approach is that it is easy and can be accessed at a time convenient to physician.", "Test caption 2", "Test caption 3", "Test caption 4", "Test caption 5"]; 
4
5const prevBtn = document.getElementById("p-10-s-i-s-prev-btn");  // assigning variable for previous button
6const nextBtn = document.getElementById("p-10-s-i-s-next-btn");  // assigning variable for next button
7const imageContainer = document.getElementById("p-10-s-i-s-image-container"); // assigning variable for image container div
8const captionContainer = document.getElementById("p-11-s-i-s-caption-place-holder");
9var myimage = myimages[0]; // Assigning initial value for the varibale to show on page loading and showing first image.
10var mycaption = mycaptions[0]; // Assigning and showing the first caption of the first image.
11
12imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
13captionContainer.innerHTML = mycaption;
14
15
16var counter = 0;
17prevBtn.addEventListener("click", function(){
18    if (counter &gt; 0 &amp;&amp; counter &lt; myimages.length){
19            counter--;
20            myimage = myimages[counter];
21            mycaption = mycaptions[counter];
22            imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
23            captionContainer.innerHTML = mycaption;
24        }
25    });
26
27nextBtn.addEventListener("click", function(){
28    if (counter &lt; myimages.length-1){
29        counter++;
30        myimage = myimages[counter];
31        mycaption = mycaptions[counter];
32        imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
33        captionContainer.innerHTML = mycaption;
34    }
35});.p-10-s-i-s-page-background{
36    width: 100%;
37    height: 100%;
38    display: flex;
39    flex-direction: column;
40    align-items: center;
41}
42
43.p-10-simple-image-slider-wrapper{
44    max-width: 45%;
45    height: auto;
46    display: flex;
47    align-items: center;
48    justify-content: center;
49    margin-bottom: 20px;
50}
51
52#p-10-s-i-s-image-container{
53    max-width: 70%;
54    height: auto;
55    display: flex;
56    justify-content: space-between;
57}
58
59#p-10-s-i-s-image-container img{
60    max-width: 70%;
61    height: auto;
62    display: flex;
63    align-items: center;
64    animation: p-10-image-animation 1s;
65    
66}
67
68#p-10-s-i-s-prev-btn, #p-10-s-i-s-next-btn{
69    width: 50px;
70    font-family: 'Open Sans', sans-serif;
71    font-size: 50px;
72    display: flex;
73    flex: 1;
74    align-items: center;
75    cursor: pointer;
76    color: orange;
77}
78
79#p-10-s-i-s-prev-btn:hover, #p-10-s-i-s-next-btn:hover{
80    
81    transition: all 1s;
82    
83}
84
85.p-10-s-i-s-page-background h1{
86    color: rgb(243, 236, 176);
87}
88
89@keyframes p-10-image-animation{
90    0%{
91        opacity: 0.5;
92    }
93    100%{
94        opacity: 1;
95    }
96}
97
98#p-11-s-i-s-caption-place-holder{
99    padding: 5px 150px 5px 150px;
100    font-family: 'Open Sans', sans-serif;
101    color: #565555;
102    text-align: left;
103    font-size: 18px;
104    line-height: 150%;
105    margin-bottom: 20px;
106}
107
108.yvanaplaceholder{
109  display: flex;
110  text-align: center;
111  justify-content: center;
112}
113
114.yvana{
115  color: darkgreen;
116  text-decoration: none;
117 }
118
119.name{
120  color: crimson;
121}&lt;div class="p-10-s-i-s-page-background"&gt;
122    &lt;div id="p-11-s-i-s-caption-place-holder"&gt;
123    &lt;/div&gt;
124  
125  &lt;div class="p-10-simple-image-slider-wrapper"&gt;
126        &lt;div id="p-10-s-i-s-prev-btn"&gt;&amp;#60;&lt;/div&gt;
127        &lt;div id="p-10-s-i-s-image-container" &gt;&lt;/div&gt;
128        &lt;div id="p-10-s-i-s-next-btn"&gt;&amp;#62;&lt;/div&gt;
129    &lt;/div&gt;
130&lt;/div&gt;// Declaring variable array of images. You can put as many as you want.
131const myimages = ["https://www.agathos.io/hs-fs/hubfs/text%20v2%20gimp.png?width=534&amp;height=1136&amp;name=text%20v2%20gimp.png", "https://i.imgur.com/uoAHQ17.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg"];
132const mycaptions = ["Once a week, physicians receive a text letting them know specific information about how they are handling a particular practice area. Curious to learn more, they follow the link for a deeper look. What is nice about this approach is that it is easy and can be accessed at a time convenient to physician.", "Test caption 2", "Test caption 3", "Test caption 4", "Test caption 5"];
133
134const prevBtn = document.getElementById("p-10-s-i-s-prev-btn"); // assigning variable for previous button
135const nextBtn = document.getElementById("p-10-s-i-s-next-btn"); // assigning variable for next button
136const imageContainer = document.getElementById("p-10-s-i-s-image-container"); // assigning variable for image container div
137const captionContainer = document.getElementById("p-11-s-i-s-caption-place-holder");
138var myimage = myimages[0]; // Assigning initial value for the varibale to show on page loading and showing first image.
139var mycaption = mycaptions[0]; // Assigning and showing the first caption of the first image.
140
141imageContainer.innerHTML = '&lt;img src="' + myimage + '" /&gt;';
142captionContainer.innerHTML = mycaption;
143
144
145var counter = 0;
146prevBtn.addEventListener("click", function() {
147  if (counter &gt; 0 &amp;&amp; counter &lt; myimages.length) {
148    counter--;
149    myimage = myimages[counter];
150    mycaption = mycaptions[counter];
151    imageContainer.innerHTML = '&lt;img src="' + myimage + '" /&gt;';
152    captionContainer.innerHTML = mycaption;
153  }
154});
155
156nextBtn.addEventListener("click", function() {
157  if (counter &lt; myimages.length - 1) {
158    counter++;
159    myimage = myimages[counter];
160    mycaption = mycaptions[counter];
161    imageContainer.innerHTML = '&lt;img src="' + myimage + '" /&gt;';
162    captionContainer.innerHTML = mycaption;
163  }
164});
1// Declaring variable array of images. You can put as many as you want.
2const myimages = ["https://www.agathos.io/hs-fs/hubfs/text%20v2%20gimp.png?width=534&amp;height=1136&amp;name=text%20v2%20gimp.png", "https://i.imgur.com/uoAHQ17.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg"];
3const mycaptions = ["Once a week, physicians receive a text letting them know specific information about how they are handling a particular practice area. Curious to learn more, they follow the link for a deeper look. What is nice about this approach is that it is easy and can be accessed at a time convenient to physician.", "Test caption 2", "Test caption 3", "Test caption 4", "Test caption 5"]; 
4
5const prevBtn = document.getElementById("p-10-s-i-s-prev-btn");  // assigning variable for previous button
6const nextBtn = document.getElementById("p-10-s-i-s-next-btn");  // assigning variable for next button
7const imageContainer = document.getElementById("p-10-s-i-s-image-container"); // assigning variable for image container div
8const captionContainer = document.getElementById("p-11-s-i-s-caption-place-holder");
9var myimage = myimages[0]; // Assigning initial value for the varibale to show on page loading and showing first image.
10var mycaption = mycaptions[0]; // Assigning and showing the first caption of the first image.
11
12imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
13captionContainer.innerHTML = mycaption;
14
15
16var counter = 0;
17prevBtn.addEventListener("click", function(){
18    if (counter &gt; 0 &amp;&amp; counter &lt; myimages.length){
19            counter--;
20            myimage = myimages[counter];
21            mycaption = mycaptions[counter];
22            imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
23            captionContainer.innerHTML = mycaption;
24        }
25    });
26
27nextBtn.addEventListener("click", function(){
28    if (counter &lt; myimages.length-1){
29        counter++;
30        myimage = myimages[counter];
31        mycaption = mycaptions[counter];
32        imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
33        captionContainer.innerHTML = mycaption;
34    }
35});.p-10-s-i-s-page-background{
36    width: 100%;
37    height: 100%;
38    display: flex;
39    flex-direction: column;
40    align-items: center;
41}
42
43.p-10-simple-image-slider-wrapper{
44    max-width: 45%;
45    height: auto;
46    display: flex;
47    align-items: center;
48    justify-content: center;
49    margin-bottom: 20px;
50}
51
52#p-10-s-i-s-image-container{
53    max-width: 70%;
54    height: auto;
55    display: flex;
56    justify-content: space-between;
57}
58
59#p-10-s-i-s-image-container img{
60    max-width: 70%;
61    height: auto;
62    display: flex;
63    align-items: center;
64    animation: p-10-image-animation 1s;
65    
66}
67
68#p-10-s-i-s-prev-btn, #p-10-s-i-s-next-btn{
69    width: 50px;
70    font-family: 'Open Sans', sans-serif;
71    font-size: 50px;
72    display: flex;
73    flex: 1;
74    align-items: center;
75    cursor: pointer;
76    color: orange;
77}
78
79#p-10-s-i-s-prev-btn:hover, #p-10-s-i-s-next-btn:hover{
80    
81    transition: all 1s;
82    
83}
84
85.p-10-s-i-s-page-background h1{
86    color: rgb(243, 236, 176);
87}
88
89@keyframes p-10-image-animation{
90    0%{
91        opacity: 0.5;
92    }
93    100%{
94        opacity: 1;
95    }
96}
97
98#p-11-s-i-s-caption-place-holder{
99    padding: 5px 150px 5px 150px;
100    font-family: 'Open Sans', sans-serif;
101    color: #565555;
102    text-align: left;
103    font-size: 18px;
104    line-height: 150%;
105    margin-bottom: 20px;
106}
107
108.yvanaplaceholder{
109  display: flex;
110  text-align: center;
111  justify-content: center;
112}
113
114.yvana{
115  color: darkgreen;
116  text-decoration: none;
117 }
118
119.name{
120  color: crimson;
121}&lt;div class="p-10-s-i-s-page-background"&gt;
122    &lt;div id="p-11-s-i-s-caption-place-holder"&gt;
123    &lt;/div&gt;
124  
125  &lt;div class="p-10-simple-image-slider-wrapper"&gt;
126        &lt;div id="p-10-s-i-s-prev-btn"&gt;&amp;#60;&lt;/div&gt;
127        &lt;div id="p-10-s-i-s-image-container" &gt;&lt;/div&gt;
128        &lt;div id="p-10-s-i-s-next-btn"&gt;&amp;#62;&lt;/div&gt;
129    &lt;/div&gt;
130&lt;/div&gt;// Declaring variable array of images. You can put as many as you want.
131const myimages = ["https://www.agathos.io/hs-fs/hubfs/text%20v2%20gimp.png?width=534&amp;height=1136&amp;name=text%20v2%20gimp.png", "https://i.imgur.com/uoAHQ17.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg"];
132const mycaptions = ["Once a week, physicians receive a text letting them know specific information about how they are handling a particular practice area. Curious to learn more, they follow the link for a deeper look. What is nice about this approach is that it is easy and can be accessed at a time convenient to physician.", "Test caption 2", "Test caption 3", "Test caption 4", "Test caption 5"];
133
134const prevBtn = document.getElementById("p-10-s-i-s-prev-btn"); // assigning variable for previous button
135const nextBtn = document.getElementById("p-10-s-i-s-next-btn"); // assigning variable for next button
136const imageContainer = document.getElementById("p-10-s-i-s-image-container"); // assigning variable for image container div
137const captionContainer = document.getElementById("p-11-s-i-s-caption-place-holder");
138var myimage = myimages[0]; // Assigning initial value for the varibale to show on page loading and showing first image.
139var mycaption = mycaptions[0]; // Assigning and showing the first caption of the first image.
140
141imageContainer.innerHTML = '&lt;img src="' + myimage + '" /&gt;';
142captionContainer.innerHTML = mycaption;
143
144
145var counter = 0;
146prevBtn.addEventListener("click", function() {
147  if (counter &gt; 0 &amp;&amp; counter &lt; myimages.length) {
148    counter--;
149    myimage = myimages[counter];
150    mycaption = mycaptions[counter];
151    imageContainer.innerHTML = '&lt;img src="' + myimage + '" /&gt;';
152    captionContainer.innerHTML = mycaption;
153  }
154});
155
156nextBtn.addEventListener("click", function() {
157  if (counter &lt; myimages.length - 1) {
158    counter++;
159    myimage = myimages[counter];
160    mycaption = mycaptions[counter];
161    imageContainer.innerHTML = '&lt;img src="' + myimage + '" /&gt;';
162    captionContainer.innerHTML = mycaption;
163  }
164});.p-10-s-i-s-page-background {
165  width: 100%;
166  height: 100%;
167  display: flex;
168  flex-direction: column;
169  align-items: center;
170}
171
172.p-10-simple-image-slider-wrapper {
173  max-width: 45%;
174  height: auto;
175  display: flex;
176  align-items: center;
177  justify-content: center;
178  margin-bottom: 20px;
179}
180
181#p-10-s-i-s-image-container {
182  max-width: 70%;
183  height: auto;
184  display: flex;
185  justify-content: center;
186}
187
188#p-10-s-i-s-image-container img {
189  max-width: 70%;
190  height: auto;
191  display: flex;
192  align-items: center;
193  /* changed */
194  animation: p-10-image-animation 1s;
195}
196
197#p-10-s-i-s-prev-btn,
198#p-10-s-i-s-next-btn {
199  width: 50px;
200  font-family: 'Open Sans', sans-serif;
201  font-size: 50px;
202  display: flex;
203  flex: 1;
204  align-items: center;
205  justify-content: center;
206  cursor: pointer;
207  color: orange;
208}
209
210#p-10-s-i-s-prev-btn:hover,
211#p-10-s-i-s-next-btn:hover {
212  transition: all 1s;
213}
214
215.p-10-s-i-s-page-background h1 {
216  color: rgb(243, 236, 176);
217}
218
219@keyframes p-10-image-animation {
220  0% {
221    opacity: 0.5;
222  }
223  100% {
224    opacity: 1;
225  }
226}
227
228#p-11-s-i-s-caption-place-holder {
229  padding: 5px 150px 5px 150px;
230  font-family: 'Open Sans', sans-serif;
231  color: #565555;
232  text-align: left;
233  font-size: 18px;
234  line-height: 150%;
235  margin-bottom: 20px;
236}
237
238.yvanaplaceholder {
239  display: flex;
240  text-align: center;
241  justify-content: center;
242}
243
244.yvana {
245  color: darkgreen;
246  text-decoration: none;
247}
248
249.name {
250  color: crimson;
251}
1// Declaring variable array of images. You can put as many as you want.
2const myimages = ["https://www.agathos.io/hs-fs/hubfs/text%20v2%20gimp.png?width=534&amp;height=1136&amp;name=text%20v2%20gimp.png", "https://i.imgur.com/uoAHQ17.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg"];
3const mycaptions = ["Once a week, physicians receive a text letting them know specific information about how they are handling a particular practice area. Curious to learn more, they follow the link for a deeper look. What is nice about this approach is that it is easy and can be accessed at a time convenient to physician.", "Test caption 2", "Test caption 3", "Test caption 4", "Test caption 5"]; 
4
5const prevBtn = document.getElementById("p-10-s-i-s-prev-btn");  // assigning variable for previous button
6const nextBtn = document.getElementById("p-10-s-i-s-next-btn");  // assigning variable for next button
7const imageContainer = document.getElementById("p-10-s-i-s-image-container"); // assigning variable for image container div
8const captionContainer = document.getElementById("p-11-s-i-s-caption-place-holder");
9var myimage = myimages[0]; // Assigning initial value for the varibale to show on page loading and showing first image.
10var mycaption = mycaptions[0]; // Assigning and showing the first caption of the first image.
11
12imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
13captionContainer.innerHTML = mycaption;
14
15
16var counter = 0;
17prevBtn.addEventListener("click", function(){
18    if (counter &gt; 0 &amp;&amp; counter &lt; myimages.length){
19            counter--;
20            myimage = myimages[counter];
21            mycaption = mycaptions[counter];
22            imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
23            captionContainer.innerHTML = mycaption;
24        }
25    });
26
27nextBtn.addEventListener("click", function(){
28    if (counter &lt; myimages.length-1){
29        counter++;
30        myimage = myimages[counter];
31        mycaption = mycaptions[counter];
32        imageContainer.innerHTML = '&lt;img src="'+myimage+'" /&gt;';
33        captionContainer.innerHTML = mycaption;
34    }
35});.p-10-s-i-s-page-background{
36    width: 100%;
37    height: 100%;
38    display: flex;
39    flex-direction: column;
40    align-items: center;
41}
42
43.p-10-simple-image-slider-wrapper{
44    max-width: 45%;
45    height: auto;
46    display: flex;
47    align-items: center;
48    justify-content: center;
49    margin-bottom: 20px;
50}
51
52#p-10-s-i-s-image-container{
53    max-width: 70%;
54    height: auto;
55    display: flex;
56    justify-content: space-between;
57}
58
59#p-10-s-i-s-image-container img{
60    max-width: 70%;
61    height: auto;
62    display: flex;
63    align-items: center;
64    animation: p-10-image-animation 1s;
65    
66}
67
68#p-10-s-i-s-prev-btn, #p-10-s-i-s-next-btn{
69    width: 50px;
70    font-family: 'Open Sans', sans-serif;
71    font-size: 50px;
72    display: flex;
73    flex: 1;
74    align-items: center;
75    cursor: pointer;
76    color: orange;
77}
78
79#p-10-s-i-s-prev-btn:hover, #p-10-s-i-s-next-btn:hover{
80    
81    transition: all 1s;
82    
83}
84
85.p-10-s-i-s-page-background h1{
86    color: rgb(243, 236, 176);
87}
88
89@keyframes p-10-image-animation{
90    0%{
91        opacity: 0.5;
92    }
93    100%{
94        opacity: 1;
95    }
96}
97
98#p-11-s-i-s-caption-place-holder{
99    padding: 5px 150px 5px 150px;
100    font-family: 'Open Sans', sans-serif;
101    color: #565555;
102    text-align: left;
103    font-size: 18px;
104    line-height: 150%;
105    margin-bottom: 20px;
106}
107
108.yvanaplaceholder{
109  display: flex;
110  text-align: center;
111  justify-content: center;
112}
113
114.yvana{
115  color: darkgreen;
116  text-decoration: none;
117 }
118
119.name{
120  color: crimson;
121}&lt;div class="p-10-s-i-s-page-background"&gt;
122    &lt;div id="p-11-s-i-s-caption-place-holder"&gt;
123    &lt;/div&gt;
124  
125  &lt;div class="p-10-simple-image-slider-wrapper"&gt;
126        &lt;div id="p-10-s-i-s-prev-btn"&gt;&amp;#60;&lt;/div&gt;
127        &lt;div id="p-10-s-i-s-image-container" &gt;&lt;/div&gt;
128        &lt;div id="p-10-s-i-s-next-btn"&gt;&amp;#62;&lt;/div&gt;
129    &lt;/div&gt;
130&lt;/div&gt;// Declaring variable array of images. You can put as many as you want.
131const myimages = ["https://www.agathos.io/hs-fs/hubfs/text%20v2%20gimp.png?width=534&amp;height=1136&amp;name=text%20v2%20gimp.png", "https://i.imgur.com/uoAHQ17.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg", "https://i.imgur.com/rk3KK2p.jpeg"];
132const mycaptions = ["Once a week, physicians receive a text letting them know specific information about how they are handling a particular practice area. Curious to learn more, they follow the link for a deeper look. What is nice about this approach is that it is easy and can be accessed at a time convenient to physician.", "Test caption 2", "Test caption 3", "Test caption 4", "Test caption 5"];
133
134const prevBtn = document.getElementById("p-10-s-i-s-prev-btn"); // assigning variable for previous button
135const nextBtn = document.getElementById("p-10-s-i-s-next-btn"); // assigning variable for next button
136const imageContainer = document.getElementById("p-10-s-i-s-image-container"); // assigning variable for image container div
137const captionContainer = document.getElementById("p-11-s-i-s-caption-place-holder");
138var myimage = myimages[0]; // Assigning initial value for the varibale to show on page loading and showing first image.
139var mycaption = mycaptions[0]; // Assigning and showing the first caption of the first image.
140
141imageContainer.innerHTML = '&lt;img src="' + myimage + '" /&gt;';
142captionContainer.innerHTML = mycaption;
143
144
145var counter = 0;
146prevBtn.addEventListener("click", function() {
147  if (counter &gt; 0 &amp;&amp; counter &lt; myimages.length) {
148    counter--;
149    myimage = myimages[counter];
150    mycaption = mycaptions[counter];
151    imageContainer.innerHTML = '&lt;img src="' + myimage + '" /&gt;';
152    captionContainer.innerHTML = mycaption;
153  }
154});
155
156nextBtn.addEventListener("click", function() {
157  if (counter &lt; myimages.length - 1) {
158    counter++;
159    myimage = myimages[counter];
160    mycaption = mycaptions[counter];
161    imageContainer.innerHTML = '&lt;img src="' + myimage + '" /&gt;';
162    captionContainer.innerHTML = mycaption;
163  }
164});.p-10-s-i-s-page-background {
165  width: 100%;
166  height: 100%;
167  display: flex;
168  flex-direction: column;
169  align-items: center;
170}
171
172.p-10-simple-image-slider-wrapper {
173  max-width: 45%;
174  height: auto;
175  display: flex;
176  align-items: center;
177  justify-content: center;
178  margin-bottom: 20px;
179}
180
181#p-10-s-i-s-image-container {
182  max-width: 70%;
183  height: auto;
184  display: flex;
185  justify-content: center;
186}
187
188#p-10-s-i-s-image-container img {
189  max-width: 70%;
190  height: auto;
191  display: flex;
192  align-items: center;
193  /* changed */
194  animation: p-10-image-animation 1s;
195}
196
197#p-10-s-i-s-prev-btn,
198#p-10-s-i-s-next-btn {
199  width: 50px;
200  font-family: 'Open Sans', sans-serif;
201  font-size: 50px;
202  display: flex;
203  flex: 1;
204  align-items: center;
205  justify-content: center;
206  cursor: pointer;
207  color: orange;
208}
209
210#p-10-s-i-s-prev-btn:hover,
211#p-10-s-i-s-next-btn:hover {
212  transition: all 1s;
213}
214
215.p-10-s-i-s-page-background h1 {
216  color: rgb(243, 236, 176);
217}
218
219@keyframes p-10-image-animation {
220  0% {
221    opacity: 0.5;
222  }
223  100% {
224    opacity: 1;
225  }
226}
227
228#p-11-s-i-s-caption-place-holder {
229  padding: 5px 150px 5px 150px;
230  font-family: 'Open Sans', sans-serif;
231  color: #565555;
232  text-align: left;
233  font-size: 18px;
234  line-height: 150%;
235  margin-bottom: 20px;
236}
237
238.yvanaplaceholder {
239  display: flex;
240  text-align: center;
241  justify-content: center;
242}
243
244.yvana {
245  color: darkgreen;
246  text-decoration: none;
247}
248
249.name {
250  color: crimson;
251}&lt;div class="p-10-s-i-s-page-background"&gt;
252  &lt;div id="p-11-s-i-s-caption-place-holder"&gt;
253  &lt;/div&gt;
254
255  &lt;div class="p-10-simple-image-slider-wrapper"&gt;
256    &lt;div id="p-10-s-i-s-prev-btn"&gt;&amp;#60;&lt;/div&gt;
257    &lt;div id="p-10-s-i-s-image-container"&gt;&lt;/div&gt;
258    &lt;div id="p-10-s-i-s-next-btn"&gt;&amp;#62;&lt;/div&gt;
259  &lt;/div&gt;
260&lt;/div&gt;

Source https://stackoverflow.com/questions/70946318

QUESTION

How to start a new jthread on a class member

Asked 2022-Feb-01 at 12:18

I think the question is quite obvious. The I have tried so far:

1#include &lt;thread&gt;
2#include &lt;chrono&gt;
3
4using namespace std::literals::chrono_literals;
5
6class test
7{
8public:
9    void member(std::stop_token stoken)
10    {
11        std::this_thread::sleep_for(1s);
12    }
13
14    void run()
15    {
16        // None compiles correctly
17        // std::jthread jt(&amp;member);
18        // std::jthread jt(&amp;test::member, this);
19    }
20};
21
22int main()
23{
24    test t;
25    t.run();
26
27    return 0;
28}
29

Is it possible with the new jthread & with using stop_token? Ps.: Of course it's possible to workaround it by making the member function static or by removing the stop_token. But I'm curious if there's a real & clean solution instead of extra N lines of hacking.

ANSWER

Answered 2022-Feb-01 at 12:18

You can use std::bind_front to bind this to &test::member and pass it to jthread:

1#include &lt;thread&gt;
2#include &lt;chrono&gt;
3
4using namespace std::literals::chrono_literals;
5
6class test
7{
8public:
9    void member(std::stop_token stoken)
10    {
11        std::this_thread::sleep_for(1s);
12    }
13
14    void run()
15    {
16        // None compiles correctly
17        // std::jthread jt(&amp;member);
18        // std::jthread jt(&amp;test::member, this);
19    }
20};
21
22int main()
23{
24    test t;
25    t.run();
26
27    return 0;
28}
29#include &lt;thread&gt;
30#include &lt;chrono&gt;
31#include &lt;functional&gt;
32
33using namespace std::literals::chrono_literals;
34class test
35{
36public:
37    void member(std::stop_token stoken)
38    {
39        std::this_thread::sleep_for(1s);
40    }
41
42    void run()
43    {
44        std::jthread jt(std::bind_front(&amp;test::member, this));
45    }
46};
47
48int main()
49{
50    test t;
51    t.run();
52}
53

Source https://stackoverflow.com/questions/70940366

QUESTION

Spec - how to change the color (or background color) of a presenter

Asked 2022-Jan-31 at 20:30

I want to change the background color of a SpTextInputFieldPresenter

e.g. to provide a visual feedback of the input, I want to react to whenTextChangedDo: and change the background color of the field to show if the input is correct or wrong. I know this is not the best for everybody, but I still want to try it.
How can I do without hacking?

ANSWER

Answered 2022-Jan-28 at 14:01

Spec previews the use of styles to change (up to a point) how a component looks. Styles are added to an application (an instance of SpApplication or child of it) and can be used by any presenter that is part of the application.
Styles can be seen as CSS stylesheets, and in the case of Gtk they actually are CSS stylesheets, but in the case of Morphic backend they have a complete different implementation (you can see all properties you can define in the SpPropertyStyle hierarchy.

The following code will show how to

  • declare styles (in a scripting way, in a production scenario styles would be likely defined in a configuration for the application).
  • use them by adding or removing them.
1app := SpApplication new.
2
3&quot;If using Morphic&quot;
4app addStyleSheetFromString: '.application [
5    .red [ Draw { #color: #red } ],
6    .green [ Draw { #color: #green } ]  
7]'.
8
9&quot;If using GTK (you need to choose one, both options are not possible at the same time)&quot;
10app useBackend: #Gtk.
11app addCSSProviderFromString: '
12.red { background-color: red }
13.green { background-color: green }  
14'.
15 
16presenter := SpPresenter new.
17presenter application: app.
18
19presenter layout: (SpBoxLayout newTopToBottom
20    add: (textPresenter := presenter newTextInput) expand: false;
21    addLast: (SpBoxLayout newLeftToRight 
22            add: (presenter newButton
23                label: 'Red';
24                action: [ textPresenter removeStyle: 'green'; addStyle: 'red' ];
25                yourself);
26            add: (presenter newButton
27                label: 'Green';
28                action: [ textPresenter removeStyle: 'red'; addStyle: 'green' ];
29                yourself);
30            yourself)
31        expand: false;
32    yourself).
33    
34presenter asWindow 
35    title: 'Example applying styles';
36    open
37

This will produce (with the Gtk3 backend) this output:

green red

Source https://stackoverflow.com/questions/70894972

QUESTION

What is the best way to build event counts for certain time resolution over multiple names in Spark dataframe while groupby?

Asked 2022-Jan-31 at 19:38

Let's say I have the following Spark frame:

1+-------------------+--------+
2|timestamp          |UserName|
3+-------------------+--------+
4|2021-08-11 04:05:06|A       |
5|2021-08-11 04:15:06|B       |
6|2021-08-11 09:15:26|A       |
7|2021-08-11 11:04:06|B       |
8|2021-08-11 14:55:16|A       |
9|2021-08-13 04:12:11|B       |
10+-------------------+--------+
11

I want to build time-series data for desired time resolution based on events counts for each user.

  • Note1: obliviously after groupbying on UserName & counting based on desired time frame\resolution, time frames need to be kept with spark frame. (maybe use of Event-time Aggregation and Watermarking in Apache Spark’s Structured Streaming )
  • Note2: needs to fill the missing gap for a specific time frame and replace 0 if there are no events.
  • Note3: I'm not interested in using UDF or hacking it via toPandas().

So let's say for 24hrs (daily) time frame expected results should be like below after groupBy:

1+-------------------+--------+
2|timestamp          |UserName|
3+-------------------+--------+
4|2021-08-11 04:05:06|A       |
5|2021-08-11 04:15:06|B       |
6|2021-08-11 09:15:26|A       |
7|2021-08-11 11:04:06|B       |
8|2021-08-11 14:55:16|A       |
9|2021-08-13 04:12:11|B       |
10+-------------------+--------+
11+------------------------------------------+-------------+-------------+
12|window_frame_24_Hours                     | username A  | username B  |
13+------------------------------------------+-------------+-------------+
14|{2021-08-11 00:00:00, 2021-08-11 23:59:59}|3            |2            |
15|{2021-08-12 00:00:00, 2021-08-12 23:59:59}|0            |0            |
16|{2021-08-13 00:00:00, 2021-08-13 23:59:59}|0            |1            |
17+------------------------------------------+-------------+-------------+
18

Edit1: in case of 12hrs time frame\resolution:

1+-------------------+--------+
2|timestamp          |UserName|
3+-------------------+--------+
4|2021-08-11 04:05:06|A       |
5|2021-08-11 04:15:06|B       |
6|2021-08-11 09:15:26|A       |
7|2021-08-11 11:04:06|B       |
8|2021-08-11 14:55:16|A       |
9|2021-08-13 04:12:11|B       |
10+-------------------+--------+
11+------------------------------------------+-------------+-------------+
12|window_frame_24_Hours                     | username A  | username B  |
13+------------------------------------------+-------------+-------------+
14|{2021-08-11 00:00:00, 2021-08-11 23:59:59}|3            |2            |
15|{2021-08-12 00:00:00, 2021-08-12 23:59:59}|0            |0            |
16|{2021-08-13 00:00:00, 2021-08-13 23:59:59}|0            |1            |
17+------------------------------------------+-------------+-------------+
18+------------------------------------------+-------------+-------------+
19|window_frame_12_Hours                     | username A  | username B  |
20+------------------------------------------+-------------+-------------+
21|{2021-08-11 00:00:00, 2021-08-11 11:59:59}|2            |2            |
22|{2021-08-11 12:00:00, 2021-08-11 23:59:59}|1            |0            |
23|{2021-08-12 00:00:00, 2021-08-12 11:59:59}|0            |0            |
24|{2021-08-12 12:00:00, 2021-08-12 23:59:59}|0            |0            |
25|{2021-08-13 00:00:00, 2021-08-13 11:59:59}|0            |1            |
26|{2021-08-13 12:00:00, 2021-08-13 23:59:59}|0            |0            |
27+------------------------------------------+-------------+-------------+
28

ANSWER

Answered 2022-Jan-31 at 13:47

Group by time window '1 day' + UserName to count then group by window frame and pivot user names:

1+-------------------+--------+
2|timestamp          |UserName|
3+-------------------+--------+
4|2021-08-11 04:05:06|A       |
5|2021-08-11 04:15:06|B       |
6|2021-08-11 09:15:26|A       |
7|2021-08-11 11:04:06|B       |
8|2021-08-11 14:55:16|A       |
9|2021-08-13 04:12:11|B       |
10+-------------------+--------+
11+------------------------------------------+-------------+-------------+
12|window_frame_24_Hours                     | username A  | username B  |
13+------------------------------------------+-------------+-------------+
14|{2021-08-11 00:00:00, 2021-08-11 23:59:59}|3            |2            |
15|{2021-08-12 00:00:00, 2021-08-12 23:59:59}|0            |0            |
16|{2021-08-13 00:00:00, 2021-08-13 23:59:59}|0            |1            |
17+------------------------------------------+-------------+-------------+
18+------------------------------------------+-------------+-------------+
19|window_frame_12_Hours                     | username A  | username B  |
20+------------------------------------------+-------------+-------------+
21|{2021-08-11 00:00:00, 2021-08-11 11:59:59}|2            |2            |
22|{2021-08-11 12:00:00, 2021-08-11 23:59:59}|1            |0            |
23|{2021-08-12 00:00:00, 2021-08-12 11:59:59}|0            |0            |
24|{2021-08-12 12:00:00, 2021-08-12 23:59:59}|0            |0            |
25|{2021-08-13 00:00:00, 2021-08-13 11:59:59}|0            |1            |
26|{2021-08-13 12:00:00, 2021-08-13 23:59:59}|0            |0            |
27+------------------------------------------+-------------+-------------+
28from pyspark.sql import functions as F
29
30result = df.groupBy(
31    F.window(&quot;timestamp&quot;, &quot;1 day&quot;).alias(&quot;window_frame_24_Hours&quot;),
32    &quot;UserName&quot;
33).count().groupBy(&quot;window_frame_24_Hours&quot;).pivot(&quot;UserName&quot;).agg(
34   F.first(&quot;count&quot;)
35).na.fill(0)
36
37result.show(truncate=False)
38
39#+------------------------------------------+---+---+
40#|window_frame_24_Hours                     |A  |B  |
41#+------------------------------------------+---+---+
42#|{2021-08-13 00:00:00, 2021-08-14 00:00:00}|0  |1  |
43#|{2021-08-11 00:00:00, 2021-08-12 00:00:00}|3  |2  |
44#+------------------------------------------+---+---+
45

If you need the missing dates, you'll have to generate all dates using sequence on min and max timestamp then join with original dataframe:

1+-------------------+--------+
2|timestamp          |UserName|
3+-------------------+--------+
4|2021-08-11 04:05:06|A       |
5|2021-08-11 04:15:06|B       |
6|2021-08-11 09:15:26|A       |
7|2021-08-11 11:04:06|B       |
8|2021-08-11 14:55:16|A       |
9|2021-08-13 04:12:11|B       |
10+-------------------+--------+
11+------------------------------------------+-------------+-------------+
12|window_frame_24_Hours                     | username A  | username B  |
13+------------------------------------------+-------------+-------------+
14|{2021-08-11 00:00:00, 2021-08-11 23:59:59}|3            |2            |
15|{2021-08-12 00:00:00, 2021-08-12 23:59:59}|0            |0            |
16|{2021-08-13 00:00:00, 2021-08-13 23:59:59}|0            |1            |
17+------------------------------------------+-------------+-------------+
18+------------------------------------------+-------------+-------------+
19|window_frame_12_Hours                     | username A  | username B  |
20+------------------------------------------+-------------+-------------+
21|{2021-08-11 00:00:00, 2021-08-11 11:59:59}|2            |2            |
22|{2021-08-11 12:00:00, 2021-08-11 23:59:59}|1            |0            |
23|{2021-08-12 00:00:00, 2021-08-12 11:59:59}|0            |0            |
24|{2021-08-12 12:00:00, 2021-08-12 23:59:59}|0            |0            |
25|{2021-08-13 00:00:00, 2021-08-13 11:59:59}|0            |1            |
26|{2021-08-13 12:00:00, 2021-08-13 23:59:59}|0            |0            |
27+------------------------------------------+-------------+-------------+
28from pyspark.sql import functions as F
29
30result = df.groupBy(
31    F.window(&quot;timestamp&quot;, &quot;1 day&quot;).alias(&quot;window_frame_24_Hours&quot;),
32    &quot;UserName&quot;
33).count().groupBy(&quot;window_frame_24_Hours&quot;).pivot(&quot;UserName&quot;).agg(
34   F.first(&quot;count&quot;)
35).na.fill(0)
36
37result.show(truncate=False)
38
39#+------------------------------------------+---+---+
40#|window_frame_24_Hours                     |A  |B  |
41#+------------------------------------------+---+---+
42#|{2021-08-13 00:00:00, 2021-08-14 00:00:00}|0  |1  |
43#|{2021-08-11 00:00:00, 2021-08-12 00:00:00}|3  |2  |
44#+------------------------------------------+---+---+
45intervals_df = df.withColumn(
46    &quot;timestamp&quot;,
47    F.date_trunc(&quot;day&quot;, &quot;timestamp&quot;)
48).selectExpr(
49    &quot;sequence(min(timestamp), max(timestamp + interval 1 day), interval 1 day) as dates&quot;
50).select(
51    F.explode(
52        F.expr(&quot;transform(dates, (x, i) -&gt; IF(i!=0, struct(date_trunc('dd', dates[i-1]) as start, dates[i] as end), null))&quot;)
53    ).alias(&quot;frame&quot;)
54).filter(&quot;frame is not null&quot;).crossJoin(
55    df.select(&quot;UserName&quot;).distinct()
56)
57
58result = intervals_df.alias(&quot;a&quot;).join(
59    df.alias(&quot;b&quot;),
60    F.col(&quot;timestamp&quot;).between(F.col(&quot;frame.start&quot;), F.col(&quot;frame.end&quot;))
61    &amp; (F.col(&quot;a.UserName&quot;) == F.col(&quot;b.UserName&quot;)),
62    &quot;left&quot;
63).groupBy(
64    F.col(&quot;frame&quot;).alias(&quot;window_frame_24_Hours&quot;)
65).pivot(&quot;a.UserName&quot;).agg(
66    F.count(&quot;b.UserName&quot;)
67)
68
69result.show(truncate=False)
70
71#+------------------------------------------+----------+----------+
72#|window_frame_24_Hours                     |username_A|username_B|
73#+------------------------------------------+----------+----------+
74#|{2021-08-13 00:00:00, 2021-08-14 00:00:00}|0         |1         |
75#|{2021-08-11 00:00:00, 2021-08-12 00:00:00}|3         |2         |
76#|{2021-08-12 00:00:00, 2021-08-13 00:00:00}|0         |0         |
77#+------------------------------------------+----------+----------+
78

Source https://stackoverflow.com/questions/70924818

QUESTION

Getting Cluster Running State Using Ansible

Asked 2022-Jan-29 at 11:28

I have a playbook that performs some tasks on a GKE cluster. It works, but every now and again, the cluster will go into a "RECONCILING" state (we don't know why yet).

I want to add a task to wait for the cluster state to be in "RUNNING" before proceeding with the other tasks, in order to avoid tasks failing

This works:

1- name: Wait for cluster in RUNNING state
2  shell:
3    cmd: |
4      gcloud container clusters describe {{ cluster_name }} --zone {{ gke_location }} --format json | jq .status --raw-output
5  retries: 60
6  delay: 60
7  register: cluster_state
8  until: cluster_state.stdout == &quot;RUNNING&quot;
9

But it's rather crude and I would like to use the google.cloud collection if possible rather than hacking something that just uses the gcloud binary under the hood

I've gotten as far as doing this:

1- name: Wait for cluster in RUNNING state
2  shell:
3    cmd: |
4      gcloud container clusters describe {{ cluster_name }} --zone {{ gke_location }} --format json | jq .status --raw-output
5  retries: 60
6  delay: 60
7  register: cluster_state
8  until: cluster_state.stdout == &quot;RUNNING&quot;
9- name: Get clusters
10  gcp_container_cluster_info:
11    location: &quot;{{ gke_location }}&quot;
12    project: &quot;{{ project }}&quot;
13    auth_kind: serviceaccount
14    service_account_file: &quot;ansible-user.json&quot;
15  register: cluster_info
16

Which gives me a nice detailed resources list of all the clusters in my project.

However, based on the documentation on the cluster_info block, it does not appear I can filter for a single cluster, based on name and since I can't filter, I can't assume that the cluster in resources[0] will be the one I am looking for -- and even if it was, there's no guarantee it will be in the future.

How can I retrieve the cluster state (RUNNING, RECONCILING, etc) without using the shell or command modules (if it is even possible)?

UPDATE

I've been able to select my cluster from the list, but I cannot seem to get the until clause right

Here's the yaml I've been able to cobble together:

1- name: Wait for cluster in RUNNING state
2  shell:
3    cmd: |
4      gcloud container clusters describe {{ cluster_name }} --zone {{ gke_location }} --format json | jq .status --raw-output
5  retries: 60
6  delay: 60
7  register: cluster_state
8  until: cluster_state.stdout == &quot;RUNNING&quot;
9- name: Get clusters
10  gcp_container_cluster_info:
11    location: &quot;{{ gke_location }}&quot;
12    project: &quot;{{ project }}&quot;
13    auth_kind: serviceaccount
14    service_account_file: &quot;ansible-user.json&quot;
15  register: cluster_info
16- name: Get clusters info
17  gcp_container_cluster_info:
18    location: &quot;{{ gke_location }}&quot;
19    project: &quot;{{ project }}&quot;
20    auth_kind: serviceaccount
21    service_account_file: &quot;ansible-user.json&quot;
22  register: cluster_info
23
24- debug:
25    msg: &quot;{{ cluster_info.resources | selectattr('name','==',cluster_name) | map(attribute='status') }}&quot;
26
27- name: Wait for cluster to be in RUNNING
28  gcp_container_cluster_info:
29    location: &quot;{{ gke_location }}&quot;
30    project: &quot;{{ project }}&quot;
31    auth_kind: serviceaccount
32    service_account_file: &quot;ansible-user.json&quot;
33  register: cluster_info
34  retries: 60
35  delay: 30
36  until: (cluster_info.resources | selectattr('name','==', cluster_name) | map(attribute='status'))  == &quot;RUNNING&quot;
37

And here's the output

1- name: Wait for cluster in RUNNING state
2  shell:
3    cmd: |
4      gcloud container clusters describe {{ cluster_name }} --zone {{ gke_location }} --format json | jq .status --raw-output
5  retries: 60
6  delay: 60
7  register: cluster_state
8  until: cluster_state.stdout == &quot;RUNNING&quot;
9- name: Get clusters
10  gcp_container_cluster_info:
11    location: &quot;{{ gke_location }}&quot;
12    project: &quot;{{ project }}&quot;
13    auth_kind: serviceaccount
14    service_account_file: &quot;ansible-user.json&quot;
15  register: cluster_info
16- name: Get clusters info
17  gcp_container_cluster_info:
18    location: &quot;{{ gke_location }}&quot;
19    project: &quot;{{ project }}&quot;
20    auth_kind: serviceaccount
21    service_account_file: &quot;ansible-user.json&quot;
22  register: cluster_info
23
24- debug:
25    msg: &quot;{{ cluster_info.resources | selectattr('name','==',cluster_name) | map(attribute='status') }}&quot;
26
27- name: Wait for cluster to be in RUNNING
28  gcp_container_cluster_info:
29    location: &quot;{{ gke_location }}&quot;
30    project: &quot;{{ project }}&quot;
31    auth_kind: serviceaccount
32    service_account_file: &quot;ansible-user.json&quot;
33  register: cluster_info
34  retries: 60
35  delay: 30
36  until: (cluster_info.resources | selectattr('name','==', cluster_name) | map(attribute='status'))  == &quot;RUNNING&quot;
37TASK [Debug] *******************************************************************
38
39TASK [debug : Get clusters info] ***********************************************
40ok: [localhost]
41
42TASK [debug : debug] ***********************************************************
43ok: [localhost] =&gt; {
44    &quot;msg&quot;: [
45        &quot;RUNNING&quot;
46    ]
47}
48
49TASK [debug : Wait for cluster to be in RUNNING] *******************************
50FAILED - RETRYING: [localhost]: Wait for cluster to be in RUNNING (60 retries left).
51...
52

I know I have two gcp_container_cluster_info blocks, this is just for debugging. If I can get this to work, I'll only need one.

You can see from the output that the state is correctly being retrieved using the filter:

cluster_info.resources | selectattr('name','==',cluster_name) | map(attribute='status')

(Feel free to tell me if there's a better way of doing this ^_^)

However, when trying to use that in the until clause it always seems to evaluate as false, so never continues, even though the previous debug proved the filter works. Any ideas why?

ANSWER

Answered 2022-Jan-29 at 11:28

You've got it correct almost. The only thing is that the selectattr and map query is returning a list with 1 item, i.e.

1- name: Wait for cluster in RUNNING state
2  shell:
3    cmd: |
4      gcloud container clusters describe {{ cluster_name }} --zone {{ gke_location }} --format json | jq .status --raw-output
5  retries: 60
6  delay: 60
7  register: cluster_state
8  until: cluster_state.stdout == &quot;RUNNING&quot;
9- name: Get clusters
10  gcp_container_cluster_info:
11    location: &quot;{{ gke_location }}&quot;
12    project: &quot;{{ project }}&quot;
13    auth_kind: serviceaccount
14    service_account_file: &quot;ansible-user.json&quot;
15  register: cluster_info
16- name: Get clusters info
17  gcp_container_cluster_info:
18    location: &quot;{{ gke_location }}&quot;
19    project: &quot;{{ project }}&quot;
20    auth_kind: serviceaccount
21    service_account_file: &quot;ansible-user.json&quot;
22  register: cluster_info
23
24- debug:
25    msg: &quot;{{ cluster_info.resources | selectattr('name','==',cluster_name) | map(attribute='status') }}&quot;
26
27- name: Wait for cluster to be in RUNNING
28  gcp_container_cluster_info:
29    location: &quot;{{ gke_location }}&quot;
30    project: &quot;{{ project }}&quot;
31    auth_kind: serviceaccount
32    service_account_file: &quot;ansible-user.json&quot;
33  register: cluster_info
34  retries: 60
35  delay: 30
36  until: (cluster_info.resources | selectattr('name','==', cluster_name) | map(attribute='status'))  == &quot;RUNNING&quot;
37TASK [Debug] *******************************************************************
38
39TASK [debug : Get clusters info] ***********************************************
40ok: [localhost]
41
42TASK [debug : debug] ***********************************************************
43ok: [localhost] =&gt; {
44    &quot;msg&quot;: [
45        &quot;RUNNING&quot;
46    ]
47}
48
49TASK [debug : Wait for cluster to be in RUNNING] *******************************
50FAILED - RETRYING: [localhost]: Wait for cluster to be in RUNNING (60 retries left).
51...
52    &quot;msg&quot;: [
53        &quot;RUNNING&quot;
54    ]
55

That's why a string comparison == "RUNNING" will not work. We can either (i) use the index 0 (list[0]), to get that item in list or (ii) use the item in list syntax for this.

Here's is an example of using item in list syntax:

1- name: Wait for cluster in RUNNING state
2  shell:
3    cmd: |
4      gcloud container clusters describe {{ cluster_name }} --zone {{ gke_location }} --format json | jq .status --raw-output
5  retries: 60
6  delay: 60
7  register: cluster_state
8  until: cluster_state.stdout == &quot;RUNNING&quot;
9- name: Get clusters
10  gcp_container_cluster_info:
11    location: &quot;{{ gke_location }}&quot;
12    project: &quot;{{ project }}&quot;
13    auth_kind: serviceaccount
14    service_account_file: &quot;ansible-user.json&quot;
15  register: cluster_info
16- name: Get clusters info
17  gcp_container_cluster_info:
18    location: &quot;{{ gke_location }}&quot;
19    project: &quot;{{ project }}&quot;
20    auth_kind: serviceaccount
21    service_account_file: &quot;ansible-user.json&quot;
22  register: cluster_info
23
24- debug:
25    msg: &quot;{{ cluster_info.resources | selectattr('name','==',cluster_name) | map(attribute='status') }}&quot;
26
27- name: Wait for cluster to be in RUNNING
28  gcp_container_cluster_info:
29    location: &quot;{{ gke_location }}&quot;
30    project: &quot;{{ project }}&quot;
31    auth_kind: serviceaccount
32    service_account_file: &quot;ansible-user.json&quot;
33  register: cluster_info
34  retries: 60
35  delay: 30
36  until: (cluster_info.resources | selectattr('name','==', cluster_name) | map(attribute='status'))  == &quot;RUNNING&quot;
37TASK [Debug] *******************************************************************
38
39TASK [debug : Get clusters info] ***********************************************
40ok: [localhost]
41
42TASK [debug : debug] ***********************************************************
43ok: [localhost] =&gt; {
44    &quot;msg&quot;: [
45        &quot;RUNNING&quot;
46    ]
47}
48
49TASK [debug : Wait for cluster to be in RUNNING] *******************************
50FAILED - RETRYING: [localhost]: Wait for cluster to be in RUNNING (60 retries left).
51...
52    &quot;msg&quot;: [