instruction
stringlengths
0
30k
I am trying to use background audio and sound effects that can be triggered by events or UI actions in my Kivy application. However, I am struggling to find a way to load the audio files without the process freezing the UI. In the below examples, the "backgroundsound.ogg" is an audio file with size \~2MB, and causes the app to freeze for \~5 sec. on my test Android phone (running Android 12). (In the actual app, I'm loading this and similar tiny files for sound effects and already causing \~20 seconds freeze.) Any pointers or suggestions would be much appreciated. **(1) A basic example:** When built and run on Android, this would take approx 5 seconds on presplash screen then goes black for about 5 seconds (while loading the audio), only then the UI appears. When pressed, it plays the sound as expected. ``` kv_string = ''' FloatLayout: BoxLayout: orientation: "vertical" size: root.width, root.height Button: size_hint: (1, .5) font_size: 32 text: "Play sound" on_press: app.submit() ''' from kivy.lang import Builder from kivy.app import App from kivy.core.audio import SoundLoader # load sound sound = SoundLoader.load('backgroundsound.ogg') class MainApp(App): def build(self): return Builder.load_string(kv_string) # play sound def submit(self): sound.play() MainApp().run() ``` **(2) Using threads** Looking for solutions, I only found a few references to the problem, like <https://stackoverflow.com/questions/61718134/kivy-soundloader-makes-python-unresponsive>, with the suggestion always referring to using separate threads. After some reading and learning about threading, I tried a few different ways, with the aim of ideally having some background process loading the audio files into GLOBAL variables, so they can be called and played by different triggers from the app UI. For example: ``` kv_string = ''' FloatLayout: BoxLayout: orientation: "vertical" size: root.width, root.height Button: size_hint: (1, .5) font_size: 32 text: "Play sound" on_press: app.submit() ''' from kivy.lang import Builder from kivy.app import App from kivy.core.audio import SoundLoader import threading # parameter indication if sound is available or not sound_loaded = False # placeholder for loaded sound sound = '' # function to load sound and overwrite the parameter when done def load_sound(): global sound global sound_loaded sound = SoundLoader.load('backgroundsound.ogg') sound_loaded = True print('sound loaded') # initiate the sound loading thread sound_load_thread = threading.Thread(target=load_sound) class MainApp(App): def build(self): return Builder.load_string(kv_string) # play sound if loaded, else do nothing def submit(self): if sound_loaded == True: sound.play() else: pass if __name__ == '__main__': app = MainApp() # start the sound loading thread sound_load_thread.start() # start the app app.run() ``` \- this however doesn't seem to help and results in identical behaviour, i.e. presplash (\~5 sec.) \> black screen (\~5 sec.) \> app loaded and plays sound when button pressed **(3) Narrowing the problem down** Below code was modified to test 2 hypotheses: 1. Hypothesis 1: the whole new thread is freezing the UI - Test: adding time.sleep(N) to see if the App is unresponsive for the duration of sleep - Result: False. With the below code, app loads (without black screen) and button is responsive until the SoundLoader line, when it freezes for \~5 sec. 2. Hypothesis 2: the reason the UI freezes is that the new thread is loading the sound into a global variable ( impacting the main thread) - Test: do not load into global variable, instead, load and play the audio locally - Result: False. With the new code, the app still freezes during the SoundLoader action ``` kv_string = ''' FloatLayout: BoxLayout: orientation: "vertical" size: root.width, root.height Button: size_hint: (1, .5) font_size: 32 text: "Play sound" on_press: app.submit() ''' from kivy.lang import Builder from kivy.app import App from kivy.core.audio import SoundLoader import threading import time # function to load sound def load_sound(): # do something to delay the sound loading # UI is responsive during this time for i in range(6): time.sleep(1) print(i) # continue to loading the sound print('loading sound') # UI is not responsive while the load runs!!! SoundLoader.load('backgroundsound.ogg').play() print('sound loaded') class MainApp(App): def build(self): return Builder.load_string(kv_string) # function assigned to the button to test UI responsivness def submit(self): pass if __name__ == '__main__': app = MainApp() # start the sound loading thread threading.Thread(target=load_sound).start() # start the app app.run() ``` I also tried using this <https://github.com/kivy/kivy/wiki/Working-with-Python-threads-inside-a-Kivy-application> as a starting code, but as soon as I add SoundLoader into the function called by the thread, the same behaviour occurs and UI is not responsive during the audio load.
Kivi UI freezes while loading audio using SoundLoader, even if run in a separate thread
|python|multithreading|kivy|
null
Since `scaledDir` is a `Vector2`, `-scaleDir` is also a `Vector2`. Multiplying it with `slope` results in a `Vector2`. Etc. So the result of the expression `-(scaledDir) * slope * mass / density` is a `Vector2` object, which can't be added to the `float` variable `propertyGradient`. Your `operator+=` is for a `Vector2` on the **left**-hand side, not right. You either need a temporary `Vector2` variable, and use its `magnitude` function to add to `propertyGradient`. Or an implicit conversion operator which calls `magnitude` (which more often than not a bad idea).
A valid JPEG file must begin with the Start of Image (SOI) marker 0xff, 0xd8 and must contain Huffman tables and quantisation tables as well as the compressed image data. There are several other optional things it can contain too - many JPEGs out of a camera will have a thumbnail embedded. A bare JPEG file doesn't need much header info but it absolutely has to begin with SOI. In theory it should end with EOI too but only the strictest decoders are fussy about that. The second item 0xff, 0xe0 is for application specific metadata which allows the program opening the file to know what flavour of JPEG it is dealing with - in this case [JFIF](https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format). It specifies the JPEG File Interchange Format. A full list of all the various [JPEG markers](https://en.wikipedia.org/wiki/JPEG#Syntax_and_structure) is on Wiki The two most common flavours of JPEG files encountered are [Exif] (https://en.wikipedia.org/wiki/Exif) 0xff, 0xe1 from most modern cameras and older JFIF. Some can also include comments. There have been past threads here on SO about creating the [smallest possible valid JPEG image file](https://stackoverflow.com/questions/2253404/what-is-the-smallest-valid-jpeg-file-size-in-bytes) - using esoteric and rarely seen arithmetic encoding options. It is an interesting programming exercise to parse the markers and embedded strings in a JPEG file. I suggest trying one from a NASA or HST site as they sometimes have interesting spare thumbnails lurking in them. If you want more detail about the JPEG internals then Miano's book ["Compressed Image File Formats"](https://www.amazon.co.uk/Compressed-Image-File-Formats-Press/dp/0201604434) isn't a bad introduction and much more accessible than the JPEG standards document.
I have a circle that follows my cursor. I was wondering if I can add an effect so when the circle hovers over the text it turns only the text under the circle to black so you are able to see the text even when the white circle is on top of it. I have tried to make the text black when I hover over it using CSS but it wont work because the words are too big so the text out of the circle that are black blend in with the background. I want only the text under the circle to turn black and the rest of it to remain white. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> document.addEventListener('DOMContentLoaded', () => { const interBubble = document.getElementById('circle'); let curX = 0; let curY = 0; let tgX = 0; let tgY = 0; function move() { curX += (tgX - curX) / 10; curY += (tgY - curY) / 10; interBubble.style.transform = `translate(${Math.round(curX)}px, ${Math.round(curY)}px)`; requestAnimationFrame(() => { move(); }); } window.addEventListener('mousemove', (e) => { tgX = e.clientX; tgY = e.clientY; if (e.target.tagName === 'P' || e.target.tagName === 'A' || e.target.tagName === 'BUTTON' || e.target.parentNode.tagName === 'BUTTON') { interBubble.classList.add('big'); } else { interBubble.classList.remove('big'); } }); move(); }); <!-- language: lang-css --> Body { background-color: black; overflow: hidden; } div { position: relative; width: 100%; height: 100vh; display: flex; justify-content: center; align-items: center; z-index: 2; } p { color: white; font-size: 30px; } p:hover { color: black; } :root { --trans-bounce: cubic-bezier(.4,2.2,.6,1.0); --trans-time: .4s; } .mouseFollowCircle { width: 30px; height: 30px; border-radius: 999px; position: absolute; z-index: 1; top: -15px; left: -15px; box-shadow: 0 0 10px white; background-color: white; pointer-events: none; backdrop-filter: blur(2px); transition: width var(--trans-time) var(--trans-bounce), height var(--trans-time) var(--trans-bounce), top var(--trans-time) var(--trans-bounce), left var(--trans-time) var(--trans-bounce), background-color var(--trans-time) var(--trans-bounce); } .mouseFollowCircle.big { width: 70px; height: 70px; border-radius: 999px; position: absolute; z-index: 1; top: -35px; left: -35px; box-shadow: 0 0 10px white; background-color: white; pointer-events: none; backdrop-filter: blur(2px); transition: width var(--trans-time) var(--trans-bounce), height var(--trans-time) var(--trans-bounce), top var(--trans-time) var(--trans-bounce), left var(--trans-time) var(--trans-bounce), background-color var(--trans-time) var(--trans-bounce); } <!-- language: lang-html --> <div><p>Hello World</p></div> <section class="mouseFollowCircle" id="circle"></section> <!-- end snippet -->
I'm encountering an issue with Cubit in Flutter. In my `main.dart`, I have initialized three providers: one for language, one for theme, and one for connectivity. Everything seems to be set up correctly, and I'm able to change the theme without any problems. However, when I try to change the language by executing `context.read<LanguageCubit>().changeLanguage(LANGUAGE.tr.name);` from the home screen, the language value changes internally but the UI does not update to reflect this change. This issue seems to be specific to the language Cubit; the theme changes are reflected on the UI as expected. What could be causing the language changes not to trigger a UI update? Main.dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); await SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp], ); final appRouter = AppRouter(); runApp( EasyLocalization( supportedLocales: [ Locale(LANGUAGE.en.name, ''), Locale(LANGUAGE.tr.name, ''), ], path: ApplicationConstants.LANG_ASSET_PATH, startLocale: Locale(LANGUAGE.tr.name, ''), child: MyApp(appRouter: appRouter), ), ); } class MyApp extends StatelessWidget { const MyApp({required this.appRouter, super.key}); final AppRouter appRouter; @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider(create: (context) => ThemeCubit()..getSavedTheme()), BlocProvider(create: (context) => LanguageCubit()..getSavedLanguage()), BlocProvider(create: (context) => ConnectivityCubit()), ], child: Builder( builder: (context) { final languageCubit = context.watch<LanguageCubit>(); final themeCubit = context.watch<ThemeCubit>(); // final connectivityCubit = context.watch<ConnectivityCubit>(); return MaterialApp.router( routeInformationParser: appRouter.defaultRouteParser(), routerDelegate: appRouter.delegate(), localizationsDelegates: context.localizationDelegates, supportedLocales: context.supportedLocales, locale: languageCubit.state.locale, theme: themeCubit.state.themeData, debugShowCheckedModeBanner: false, builder: CustomResponsive.build, ); }, ), ); } } languageCubit.dart part 'language_state.dart'; class LanguageCubit extends Cubit<ChangeLanguageState> { LanguageCubit() : super(ChangeLanguageState( locale: Locale(ApplicationConstants.DEFAULT_LANGUAGE.name, ''))); Future<void> getSavedLanguage() async { final cachedLanguageCode = await LanguageCacheHelper().getCachedLanguage(); emit(ChangeLanguageState(locale: Locale(cachedLanguageCode, ''))); } Future<void> changeLanguage(String languageCode) async { emit(ChangeLanguageState(locale: Locale(languageCode, ''))); } } language_state.dart part of 'language_cubit.dart'; class ChangeLanguageState { ChangeLanguageState({ required this.locale, }); final Locale locale; } home.dart @RoutePage() class HomeView extends StatefulWidget { const HomeView({super.key}); @override State<HomeView> createState() => _HomeViewState(); } class _HomeViewState extends State<HomeView> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(LocaleKeys.home_title.tr()), ), body: Column( children: [ ElevatedButton( onPressed: () { context.read<LanguageCubit>().changeLanguage(LANGUAGE.tr.name); print(context.read<LanguageCubit>().state.locale.toString()); // context.setLocale(Locale('tr')); }, child: Text(LocaleKeys.tr_lang.tr()), ), ElevatedButton( onPressed: () { context.read<LanguageCubit>().changeLanguage(LANGUAGE.en.name); print(context.read<LanguageCubit>().state.locale.toString()); // context.setLocale(Locale('en')); }, child: Text(LocaleKeys.en_lang.tr()), ), ], ), ); } }
Flutter Cubit Not Updating UI for Language Change
Why back button on title bar isn't shown
|android|back-button|android-titlebar|
I have an error with SQLite database updating. I have created an application with a habit tracker. There is a list of habits with a title and a checkbox for each. I have put 2 habits already in there and I have set up actions for check-marking habits as well as creating and deleting habits. Every of those SQLite `updates` fails except the deleting habit `update`. Here are the SQLite's each `update's` script. `HabitIsCompleted`: ```UPDATE habits SET check=1 WHERE id=${id};``` `HabitNotCompleted`: ```UPDATE habits SET check=0 WHERE id=${id};``` `HabitDelete`: ```DELETE FROM habits WHERE id=${id};``` `HabitCreate`: ```INSERT INTO habits (title; done) VALUES (`${title}`; 0);``` Here is what the Android Studio's terminal said about these actions when I tried them in the application. Setting checkbox as true: ``` E/SQLiteLog(15872): (1) near "check": syntax error E/flutter (15872): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near "check": syntax error (code 1 SQLITE_ERROR): , while compiling: UPDATE habits SET check=1 WHERE id=2;) sql 'UPDATE habits SET check=1 WHERE id=2; E/flutter (15872): ' args [] ``` Creating a habit: ``` E/SQLiteLog(15872): (1) near ";": syntax error E/flutter (15872): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near ";": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO habits (title; done) VALUES (`xjfjfhx`; 0);) sql 'INSERT INTO habits (title; done) VALUES (`xjfjfhx`; 0); E/flutter (15872): ' args [] ``` Deleting a habit had no errors, nothing was showed. Here is the full log: ``` D/vndksupport( 9499): Loading /vendor/lib64/hw/android.hardware.graphics.mapper@2.0-impl.so from current namespace instead of sphal namespace. D/vndksupport( 9499): Loading /vendor/lib64/hw/gralloc.msm8998.so from current namespace instead of sphal namespace. D/ViewRootImpl( 9499): com.mycompany.achievepotentialsqltest: (1, 0, 0, 0, -1) E/SQLiteLog( 9499): (1) near "check": syntax error E/flutter ( 9499): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near "check": syntax error (code 1 SQLITE_ERROR): , while compiling: UPDATE habits SET check=1 WHERE id=2;) sql 'UPDATE habits SET check=1 WHERE id=2; E/flutter ( 9499): ' args [] E/flutter ( 9499): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #1 SqfliteDatabaseMixin.txnRawQuery.<anonymous closure> (package:sqflite_common/src/database_mixin.dart:586:30) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #4 _HomePageWidgetState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:achieve_potential_s_q_l_test/pages/home_page/home_page_widget.dart:154:45) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): D/ViewRootImpl( 9499): com.mycompany.achievepotentialsqltest: (1, 3, 1, 0, 38101) E/SQLiteLog( 9499): (1) near "check": syntax error E/flutter ( 9499): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near "check": syntax error (code 1 SQLITE_ERROR): , while compiling: UPDATE habits SET check=1 WHERE id=1;) sql 'UPDATE habits SET check=1 WHERE id=1; E/flutter ( 9499): ' args [] E/flutter ( 9499): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #1 SqfliteDatabaseMixin.txnRawQuery.<anonymous closure> (package:sqflite_common/src/database_mixin.dart:586:30) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #4 _HomePageWidgetState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:achieve_potential_s_q_l_test/pages/home_page/home_page_widget.dart:154:45) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): E/SQLiteLog( 9499): (1) near "check": syntax error E/flutter ( 9499): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near "check": syntax error (code 1 SQLITE_ERROR): , while compiling: UPDATE habits SET check=1 WHERE id=2;) sql 'UPDATE habits SET check=1 WHERE id=2; E/flutter ( 9499): ' args [] E/flutter ( 9499): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #1 SqfliteDatabaseMixin.txnRawQuery.<anonymous closure> (package:sqflite_common/src/database_mixin.dart:586:30) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #4 _HomePageWidgetState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:achieve_potential_s_q_l_test/pages/home_page/home_page_widget.dart:154:45) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): E/SQLiteLog( 9499): (1) near "check": syntax error E/flutter ( 9499): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near "check": syntax error (code 1 SQLITE_ERROR): , while compiling: UPDATE habits SET check=1 WHERE id=2;) sql 'UPDATE habits SET check=1 WHERE id=2; E/flutter ( 9499): ' args [] E/flutter ( 9499): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #1 SqfliteDatabaseMixin.txnRawQuery.<anonymous closure> (package:sqflite_common/src/database_mixin.dart:586:30) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #4 _HomePageWidgetState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:achieve_potential_s_q_l_test/pages/home_page/home_page_widget.dart:154:45) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): E/SQLiteLog( 9499): (1) near "check": syntax error E/flutter ( 9499): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near "check": syntax error (code 1 SQLITE_ERROR): , while compiling: UPDATE habits SET check=0 WHERE id=2;) sql 'UPDATE habits SET check=0 WHERE id=2; E/flutter ( 9499): ' args [] E/flutter ( 9499): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #1 SqfliteDatabaseMixin.txnRawQuery.<anonymous closure> (package:sqflite_common/src/database_mixin.dart:586:30) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #4 _HomePageWidgetState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:achieve_potential_s_q_l_test/pages/home_page/home_page_widget.dart:159:45) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): D/ViewRootImpl( 9499): com.mycompany.achievepotentialsqltest: (4, 4, 4, 0, 10190) W/otentialsqltes( 9499): Unknown chunk type '200'. D/InputConnectionAdaptor( 9499): The input method toggled cursor monitoring on D/ViewRootImpl( 9499): com.mycompany.achievepotentialsqltest: (1, 0, 1, 0, 10466) E/SQLiteLog( 9499): (1) near ";": syntax error E/flutter ( 9499): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near ";": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO habits (title; done) VALUES (`haodjf`; 0);) sql 'INSERT INTO habits (title; done) VALUES (`haodjf`; 0); E/flutter ( 9499): ' args [] E/flutter ( 9499): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #1 SqfliteDatabaseMixin.txnRawQuery.<anonymous closure> (package:sqflite_common/src/database_mixin.dart:586:30) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #4 _HabitCreateWidgetState.build.<anonymous closure> (package:achieve_potential_s_q_l_test/pages/habit_create/habit_create_widget.dart:113:19) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): #5 _FFButtonWidgetState.build.<anonymous closure> (package:achieve_potential_s_q_l_test/flutter_flow/flutter_flow_widgets.dart:110:19) E/flutter ( 9499): <asynchronous suspension> E/flutter ( 9499): W/IInputConnectionWrapper( 9499): requestCursorAnchorInfo on inactive InputConnection W/IInputConnectionWrapper( 9499): getTextBeforeCursor on inactive InputConnection W/IInputConnectionWrapper( 9499): getTextAfterCursor on inactive InputConnection W/IInputConnectionWrapper( 9499): getSelectedText on inactive InputConnection W/IInputConnectionWrapper( 9499): getTextBeforeCursor on inactive InputConnection W/IInputConnectionWrapper( 9499): getTextBeforeCursor on inactive InputConnection W/IInputConnectionWrapper( 9499): getTextBeforeCursor on inactive InputConnection W/IInputConnectionWrapper( 9499): requestCursorAnchorInfo on inactive InputConnection Application finished. PS C:\Users\renar\Documents\achieve_potential_s_q_l_test41\achieve_potential_s_q_l_test> flutter run Launching lib\main.dart on TA 1004 in debug mode... You are applying Flutter's app_plugin_loader Gradle plugin imperatively using the apply script method, which is deprecated and will be removed in a future release. Migrate to applying Gradle plugins with the declarative plugins block: https://flutter.dev/go/flutter-gradle-plugin-apply You are applying Flutter's main Gradle plugin imperatively using the apply script method, which is deprecated and will be removed in a future release. Migrate to applying Gradle plugins with the declarative plugins block: https://flutter.dev/go/flutter-gradle-plugin-apply Running Gradle task 'assembleDebug'... 23.8s √ Built build\app\outputs\flutter-apk\app-debug.apk. Installing build\app\outputs\flutter-apk\app-debug.apk... 19.8s Syncing files to device TA 1004... 211ms Flutter run key commands. r Hot reload. R Hot restart. h List all available interactive commands. d Detach (terminate "flutter run" but leave application running). c Clear the screen q Quit (terminate the application on the device). A Dart VM Service on TA 1004 is available at: http://127.0.0.1:54364/QK7grgP3soI=/ The Flutter DevTools debugger and profiler on TA 1004 is available at: http://127.0.0.1:9100?uri=http://127.0.0.1:54364/QK7grgP3soI=/ D/vndksupport(15872): Loading /vendor/lib64/hw/android.hardware.graphics.mapper@2.0-impl.so from current namespace instead of sphal namespace. D/vndksupport(15872): Loading /vendor/lib64/hw/gralloc.msm8998.so from current namespace instead of sphal namespace. D/ViewRootImpl(15872): com.mycompany.achievepotentialsqltest: (1, 0, 0, 0, -1) E/SQLiteLog(15872): (1) near "check": syntax error E/SQLiteLog(15872): (1) near "check": syntax error E/flutter (15872): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near "check": syntax error (code 1 SQLITE_ERROR): , while compiling: UPDATE habits SET check=1 WHERE id=2;) sql 'UPDATE habits SET check=1 WHERE id=2; E/flutter (15872): ' args [] E/flutter (15872): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #1 SqfliteDatabaseMixin.txnRawQuery.<anonymous closure> (package:sqflite_common/src/database_mixin.dart:586:30) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #4 _HomePageWidgetState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:achieve_potential_s_q_l_test/pages/home_page/home_page_widget.dart:154:45) E/flutter (15872): <asynchronous suspension> E/flutter (15872): E/flutter (15872): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near "check": syntax error (code 1 SQLITE_ERROR): , while compiling: UPDATE habits SET check=1 WHERE id=2;) sql 'UPDATE habits SET check=1 WHERE id=2; E/flutter (15872): ' args [] E/flutter (15872): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #1 SqfliteDatabaseMixin.txnRawQuery.<anonymous closure> (package:sqflite_common/src/database_mixin.dart:586:30) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #4 _HomePageWidgetState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:achieve_potential_s_q_l_test/pages/home_page/home_page_widget.dart:154:45) E/flutter (15872): <asynchronous suspension> E/flutter (15872): W/otentialsqltes(15872): Accessing hidden method Landroid/view/View;->getAccessibilityViewId()I (light greylist, reflection) D/ViewRootImpl(15872): com.mycompany.achievepotentialsqltest: (2, 0, 2, 0, 104182) W/otentialsqltes(15872): Unknown chunk type '200'. D/InputConnectionAdaptor(15872): The input method toggled cursor monitoring on E/SQLiteLog(15872): (1) near ";": syntax error E/flutter (15872): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(near ";": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO habits (title; done) VALUES (`xjfjfhx`; 0);) sql 'INSERT INTO habits (title; done) VALUES (`xjfjfhx`; 0); E/flutter (15872): ' args [] E/flutter (15872): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #1 SqfliteDatabaseMixin.txnRawQuery.<anonymous closure> (package:sqflite_common/src/database_mixin.dart:586:30) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #2 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #3 SqfliteDatabaseMixin.txnSynchronized (package:sqflite_common/src/database_mixin.dart:517:14) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #4 _HabitCreateWidgetState.build.<anonymous closure> (package:achieve_potential_s_q_l_test/pages/habit_create/habit_create_widget.dart:113:19) E/flutter (15872): <asynchronous suspension> E/flutter (15872): #5 _FFButtonWidgetState.build.<anonymous closure> (package:achieve_potential_s_q_l_test/flutter_flow/flutter_flow_widgets.dart:110:19) E/flutter (15872): <asynchronous suspension> E/flutter (15872): D/ViewRootImpl(15872): com.mycompany.achievepotentialsqltest: (2, 4, 3, 1, 46899) D/InputConnectionAdaptor(15872): The input method toggled cursor monitoring off ``` I followed many different tutorials, I made sure that I did everything correctly and didn't misspell anything. I have no idea what is wrong here.
SQLite acclaimed syntax error in code: UPDATE <table> SET <integer-variable>=1 WHERE id=${id}
|android|flutter|sqlite|
null
# Context I am using Symfony for a website and I worked on it during around two weeks. I'm on Windows 10, I use Symfony 5.8.12 and php 8.1.13 along with Wamp 3.3.0 for the database. Everything worked normally until last Friday : I tried refreshing a page but the loading was endless. There were no additional symfony logs. I stopped the server from running using Ctrl+C and it stopped when looking at the processes in task manager. I got the message : ``` TerminateProcess: Access is denied. ``` I tried `symfony server:start`\ I got the same message I again, but why ? **I am trying to run it not terminate it**. **Edit :I also discovered that Access is denied error I get is most likely because of the following, when running** `symfony server:status`:\ [![Server not running but Worker assigned to a non existent PID/Non symfony related PID][1]][1] # What I ended up doing as a temporary solution **Edit : I have admin rights now so it's not that big of a deal. I can logout then login again to solve the issue. The problem is it's happening several times on random days or times of the day.** The solution that worked was restarting the computer, but since I don't have my admin rights yet, I need the IT staff to enter admin credentials to execute Wamp. I also tried using `symfony server:start -d` so that whenever I wanna stop the server I use the proper command, `symfony server:stop`. # What happened today and why I am posting on stackoverflow Today, again I worked on my project for the day and everything went all good and my webpack compiled but the console in the dev tools didn't want to update my javascript code so I restarted symfony with `symfony server:stop` to which I get : ``` Stopping Web Server ``` Then I run `symfony server:start` and I get ``` TerminateProcess: Access is denied. ``` ### Questions **Edit - Why is the PID still assigned to a worker according to Symfony and is there a way to reset this "binding" without logging out ?**\ Why do I get this message about *TerminateProcess* when I am not terminating but starting the process ?\ Why does this happen kind of randomly ? (it happened once directly after a reboot, today after a whole day working normally...). [1]: https://i.stack.imgur.com/k3jaM.png
|php|windows|symfony|process|access-denied|
I gave it a go within an app router project with Next.js 14.1.1 and got it instanced on the client with these steps, see if it can help: 1. Place both `openjphjs.js` and `openjphjs.wasm` in your `/public` directory 2. Create a server page route (I went for `app/openjph/page.tsx`): ```Javascript import Openjph from "@/components/openjph/open"; import Script from "next/script"; export default async function Page(props) { return <> <Script strategy="beforeInteractive" src="/openjphjs.js" /> <Openjph /> </> } ``` 3. Create a client component (I went for `app/components/openjph/open.tsx`): ``` "use client"; import { useEffect } from 'react'; const Openjph = (props) => { useEffect(() => { try { const decoder = new Module.HTJ2KDecoder(); console.log(decoder); } catch (error) { console.log(error) } }, []) return ( <>[...more stuff...]</> ); }; export default Openjph; ``` This oughta print the instanced decoder: [![OpenJPHjs decoder][1]][1] And proceed as needed. My `tsconfig.json` has something along these lines: ``` "paths": { "@/components/*": ["app/components/*"], }, ``` Alternatively, you can simply import the `Openjph` component with relative paths or however you prefer. [1]: https://i.stack.imgur.com/hs8Ub.png
|flutter|dart|bloc|cubit|
The most frequent issue that arises while using kubectl kustomize for Json6902 patching is the failure to recognize that "add" might occasionally behave like "replace”. The same problem & its solution is explained in this **[Medium blog](https://pauldally.medium.com/the-most-common-problem-i-see-when-using-json6902-patching-with-kustomize-1d19a0f4a038)** by Paul Dally. By themselves, Kubernetes patches are made to work with resources that already exist; they do not automatically support adding missing directories to the path. However, if the "/root" directory doesn't already exist, you can create it and then use a strategic merge patch to modify "/root/subdir" in order to get the desired behavior. **Strategic Merge patch :** patchesJson6902: - target: kind: MyKind name: config version: v1beta1 group: mygroup.com patch: |- spec: array: - spec:{} #Empty object to create the nested structure newField: test #value to be added or replaced Refer to this official Kubernetes [doc][1] for more information about Strategic Merge patch. This patch attempts to merge the provided spec section which includes the nested “newfield” if the “spec/array/0/spec” does not exist, it will be created with the specified “newField” value By following this approach you can effectively create or update the nested structure within your kubernetes resources using patches. [1]: https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/#customizing
I'm developing a Fortran parser using ANTLR4, adhering to the ISO Fortran Standard 2018 specifications. While implementing lexer rules, I encountered a conflict between the `NAME` and `LETTERSPEC` rules. Specifically, when the input consists of just a letter, it is always tokenized as `NAME` and never as `LETTERSPEC`. Here's a partial simplified version of the grammer: ``` lexer grammar FortrantTestLex; // Lexer rules WS: [ \t\r\n]+ -> skip; // R603 name -> letter [alphanumeric-character]... NAME: LETTER (ALPHANUMERICCHARACTER)*; // R865 letter-spec -> letter [- letter] LETTERSPEC: LETTER (MINUS LETTER)?; MINUS: '-'; // R601 alphanumeric-character -> letter | digit | underscore ALPHANUMERICCHARACTER: LETTER | DIGIT | UNDERSCORE; // R0002 Letter -> // A | B | C | D | E | F | G | H | I | J | K | L | M | // N | O | P | Q | R | S | T | U | V | W | X | Y | Z LETTER: 'A'..'Z' | 'a'..'z'; // R0001 Digit -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 DIGIT: '0'..'9'; // R602 UNDERSCORE -> _ UNDERSCORE: '_'; ``` ``` grammer FortranTest; import FortranTestLex; // Parser rules programName: NAME; // R1402 program-stmt -> PROGRAM program-name programStmt: PROGRAM programName; letterSpecList: LETTERSPEC (COMMA LETTERSPEC)*; // R864 implicit-spec -> declaration-type-spec ( letter-spec-list ) implicitSpec: declarationTypeSpec LPAREN letterSpecList RPAREN; implicitSpecList: implicitSpec (COMMA implicitSpec)*; // R863 implicit-stmt -> IMPLICIT implicit-spec-list | IMPLICIT NONE [( [implicit-name-spec-list] )] implicitStmt: IMPLICIT implicitSpecList | IMPLICIT NONE ( LPAREN implicitNameSpecList? RPAREN )?; // R1403 end-program-stmt -> END [PROGRAM [program-name]] endProgramStmt: END (PROGRAM programName?)?; // R1401 main-program -> // [program-stmt] [specification-part] [execution-part] // [internal-subprogram-part] end-program-stmt mainProgram: programStmt? endProgramStmt; //R502 program-unit -> main-program | external-subprogram | module | submodule | block-data programUnit: mainProgram; //R501 program -> program-unit [program-unit]... program: programUnit (programUnit)*; ``` In this case, the tokenization always results in NAME even though it could also be a valid LETTERSPEC. How can I resolve this conflict in my lexer rules to ensure correct tokenization? Can I use ANTLR4 mode feature to resolve this issue? I've tried adjusting the order of the lexer rules and refining the patterns, but I haven't been able to achieve the desired behavior. Any insights or suggestions on how to properly handle this conflict would be greatly appreciated. Thank you!
**While k8s itself does not provide a specific API for file IO operations. Applications can communicate with PV in a standardized and scalable way due to its strong infrastructure for managing storage resources through PVs and PVCs.** So Persistent Volumes are the suggested method in this case, thus you are on the correct path for applications operating on K8s that require persistent storage for file IO. **As per official kubernetes doc on [Persistent volumes][1] and PVCs** : Pods consume node resources and PVCs consume PV resources. Pods can request specific levels of resources. Claims can request specific size and access modes. Pods use PVCs to define their storage requirements, which are then bound to PVs that are available. Kubernetes resources stand for persistent storage resources that the cluster has access to AWS EBS, GCP persistent disk, local storage, NFS and cloud storage providers are some of the technologies that can support PVs external storage. Choose the appropriate PV storage class based on your application performance capacity and cost requirements. As per **David Maze** suggestion, also try to avoid manually establishing StatefulSets or PersistentVolumeClaims and instead **use an external storage.** Perhaps a nice fit would be an object-storage system such as **MinIO** (or) a comparable cloud system like AWS S3). Keeping data in local files can cause issues if you wish to have several copies of a pod in the future. [1]: https://Stackoverflow%20%20link:%20https://stackoverflow.com/questions/78131784/%20%20%20%20LDAP%20ID%20:%20saichandini%20%20%20%20Posting%20Answer%20%20%20%20While%20k8s%20itself%20does%20not%20provide%20a%20specific%20API%20for%20file%20IO%20operations.%20Applications%20can%20%20communicate%20with%20PV%20in%20a%20standardized%20and%20scalable%20way%20due%20to%20its%20strong%20infrastructure%20for%20%20managing%20storage%20resources%20through%20PVs%20and%20PVCs.%20%20%20%20%20So%20Persistent%20Volumes%20are%20the%20suggested%20method%20in%20this%20case,%20thus%20you%20are%20on%20the%20%20correct%20path%20for%20applications%20operating%20on%20K8s%20that%20require%20persistent%20storage%20for%20file%20IO.%20%20%20%20As%20per%20official%20kubernetes%20don%20on%20%20Persistent%20volumes%20and%20PVCs%20:%20%20%20%20Pods%20consume%20node%20resources%20and%20PVCs%20consume%20PV%20resources.%20Pods%20can%20request%20specific%20%20levels%20of%20resources.%20Claims%20can%20request%20specific%20size%20and%20access%20modes.%20Pods%20use%20PVCs%20to%20%20define%20their%20storage%20requirements,%20which%20are%20then%20bound%20to%20PVs%20that%20are%20available.%20%20%20%20%20Kubernetes%20resources%20stand%20for%20persistent%20storage%20resources%20that%20the%20cluster%20has%20access%20to%20%20AWS%20EBS,%20GCP%20persistent%20disk,%20local%20storage,%20NFS%20and%20cloud%20storage%20providers%20are%20some%20of%20the%20%20technologies%20that%20can%20support%20PVs%20external%20storage.
I have updated the software to `pack4j` version 6 with play framework 2.9 + sbt 2.13. system complaining about `setServiceProviderMetadataPath `is missing for SAML SSO this property was not used for `pack4j `version 5. SSO work with out metadata data XML path is there a flag to disable ?
You want `<xsl:apply-templates select="/S//A/(* except (B, C))" mode="P"/>`, not `<xsl:apply-templates select="/S//A/* except (B, C)" mode="P"/>`.
I want to create a products page in which I can upload multiple images using Cloudinary in next. Here I created a component for uploading image # **Image Upload component** ``` "use client"; import { CldUploadWidget } from 'next-cloudinary'; import { useEffect, useState } from 'react'; import { Button } from '@/components/ui/button'; import Image from 'next/image'; import { ImagePlus, Trash } from 'lucide-react'; interface ImageUploadProps { disabled?: boolean; onChange: (value: string) => void; onRemove: (value: string) => void; value: string[]; } const ImageUpload: React.FC<ImageUploadProps> = ({ disabled, onChange, onRemove, value }) => { const [isMounted, setIsMounted] = useState(false); useEffect(() => { setIsMounted(true); }, []); const onUpload = (result: any) => { onChange(result.info.secure_url); }; if (!isMounted) { return null; } return ( <div> <div className="mb-4 flex items-center gap-4"> {value.map((url) => ( <div key={url} className="relative w-[200px] h-[200px] rounded-md overflow-hidden"> <div className="z-10 absolute top-2 right-2"> <Button type="button" onClick={() => onRemove(url)} variant="destructive" size="sm"> <Trash className="h-4 w-4" /> </Button> </div> <Image fill sizes='' className="object-cover" alt="Image" src={url} /> </div> )) } </div> <CldUploadWidget onSuccess={onUpload} uploadPreset="ox48luzl"> {({ open }) => { const onClick = () => { open(); }; return ( <Button type="button" disabled={disabled} variant="secondary" onClick={onClick} > <ImagePlus className="h-4 w-4 mr-2" /> Upload an Image </Button> ); }} </CldUploadWidget> </div> ); } export default ImageUpload; ``` and # **Product Form page** where I call my image upload ``` 'use client' import { Button } from "@/components/ui/button" import { Heading } from "@/components/ui/heading" import { Product, Image, Category } from "@prisma/client"; import { Trash } from "lucide-react" import { useParams, useRouter } from "next/navigation"; import { useState } from "react"; import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form"; import * as z from "zod" import { AlertModal } from "@/components/modals/alert-model"; import axios from "axios"; import toast from "react-hot-toast"; import { Separator } from "@/components/ui/separator"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import ImageUpload from "@/components/ui/image-upload"; const formSchema = z.object({ name: z.string().min(1), promocode: z.string().min(2), affiliateLink: z.string().min(1), description: z.string().min(1), images:z.object({url:z.string()}).array(), categoryId: z.string().min(1), price: z.coerce.number().min(1), }) type ProductFormValues = z.infer<typeof formSchema>; interface ProductFormProps { initialData: Product & { images: Image[] } | null; categories: Category[] }; const ProductForm: React.FC<ProductFormProps> = ({ initialData, categories }) => { const params = useParams(); const router = useRouter(); const [open, setOpen] = useState(false); const [loading, setLoading] = useState(false); const title = initialData ? 'Edit Product' : 'Create Product' const description = initialData ? 'Edit a Product' : 'Add a new Product'; const toastMassege = initialData ? 'Product Update' : 'Product Created'; const action = initialData ? 'Save Changes' : 'Create'; const defaultValues = initialData ? { ...initialData, price: parseFloat(String(initialData?.price)), promocode: initialData.promocode || "", } : { name: '', images:[], price:0, description: '', catogoryId: '', promocode: '', affiliateLink: '', } const form = useForm<ProductFormValues>({ resolver: zodResolver(formSchema),defaultValues }) const onDelete = async () => { try { setLoading(true) await axios.delete(`/api/products/${params.productId}`) router.push('/products') toast.success('Product Deleted Successfully!') } catch (error: any) { toast.error('something wen wrong') } finally { setLoading(false) } } return ( <> <AlertModal isOpen={open} onClose={() => setOpen(true)} onConfirm={onDelete} loading={loading} /> <div className="flex item-center justify-between"> <Heading title={title} description={description} /> {initialData &&( <Button disabled={loading} variant="destructive" size="sm" > <Trash className="h-4 w-4" /> </Button> )} </div> <Separator/> <Form {...form}> <form className="space-y-8 w-full"> <FormField control={form.control} name="images" render={({ field }) => ( <FormItem> <FormLabel>Images</FormLabel> <FormControl> <ImageUpload value={field.value.map((image)=>image.url)} disabled={loading} onChange={(url) => field.onChange([...field.value, { url }])} onRemove={(url) => field.onChange([...field.value.filter((current) => current.url !== url)])} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="name" render={({field})=>( <FormItem> <FormLabel>Product Name</FormLabel> <FormControl> <Input disabled={loading} placeholder="Enter Product Name" {...field}/> </FormControl> </FormItem> )} /> </form> </Form> </> ) } export default ProductForm ``` In this code, almost everything works fine but when trying to upload multiple images in the Cloudinary widget only the first or first uploaded image displays and is stored in the value. IU wanted to implement an array of image URLs uploaded and stored.
So from the loadUserFillenumber using sharedpreference Im getting the userfilled number, and displaying in the sudoku table and cell, but its onlying displaying the userfillednumber from loadstate instead of updating, because of this my isGamewon isnt triggring. I tried but its not working is there any thing i need to modify so that when userfilledNumber from loadstate is updated in the cell instead of displaying, here is the code I need to update the userfilled number from loadstate instead of displaying
Flutter from Loadstate the number is being displayed but not updated in the cell
|android|flutter|sudoku|
null
Where could be a mistake? ``` // Plot der dynamisch angepassten Fibonacci-Niveaus for i = 0 to NumAdditionalLevels - 1 plot(additional_levels[i], color=color.new(#ffffff, 0), linewidth=1, trackprice=true, show_last=1, title=f"F_level_{i+1}") ``` Hoppe someone could support. Thank you in advance! Hope someone will read my issue.
* `glPushMatrix()` just pushes the current matrix value onto the stack existing somewhere. * This is used to saving the current matrix value. * **This function does not cause any changes to the current matrix**. * `glPopMatrix()` pops the matrix value from top of the stack, and current matrix value is overwritten with this popped value. * This is used to loading the matrix value previously pushed. This is the all. They are useful to make local transformation. In your code, they surround: 1. local transformation for {Earth and Moon} only 2. local transformation for Moon only. ``` plot_circle(radius=1, color=[180 / 255, 180 / 255, 16 / 255]) //vvv [Start of local transformation(1) : for Earth and Moon] vvv glPushMatrix() glRotate(angles[0], 0, 0, 1) glTranslate(4, 0, 0) plot_circle(radius=0.75, color=[0 / 255, 59 / 255, 174 / 255]) //vvv [Start of local transformation(2) : for Moon only] vvv glPushMatrix() glRotate(angles[2], 0, 0, 1) glTranslate(0, 1.5, 0) plot_circle(radius=0.25, color=[128 / 255, 128 / 255, 128 / 255]) glPopMatrix() //End of local transformation(2) : for Moon only //^^^ [End of local transformation(2) : for Moon only] ^^^ glPopMatrix() //^^^ [End of local transformation(1) : for Earth and Moon] ^^^ ```
I am trying to include mosquitto.h into my project. I installed mosquitto from "mosquitto-2.0.18-install-windows-x64" installer to C:\Program Files\mosquitto\devel. It seems like I have to add that address to somewhere but I dont have any clear idea where to. When i build the program, i got this error: ``` [build] D:\RP_Pico_W_mqtt_test\RP_Pico_W_2_mqtt\main2.c:3:10: fatal error: mosquitto.h: No such file or directory [build] 3 | #include <mosquitto.h> [build] | ^~~~~~~~~~~~~ [build] compilation terminated. [build] mingw32-make[2]: *** [CMakeFiles\main2.dir\build.make:75: CMakeFiles/main2.dir/main2.c.obj] Error 1 [build] mingw32-make[1]: *** [CMakeFiles\Makefile2:1509: CMakeFiles/main2.dir/all] Error 2 [build] mingw32-make: *** [Makefile:90: all] Error 2 ``` And I wrote a simple code with raspberry pi pico w: ``` #include "pico/stdlib.h" #include "pico/cyw43_arch.h" #include <mosquitto.h> int main() { stdio_init_all(); if (cyw43_arch_init()) { printf("Wi-Fi init failed"); return -1; } while (true) { } return 0; } ``` I am new to all these Cmake, VScode and Pico w. Please help me!
Unable to upload multiple images in Cloudinary
Have you encountered a frustrating issue with your Jetpack Compose ModalBottomSheet? It works perfectly the first time you open it, but after hiding it, it becomes unresponsive and blocks all other UI interactions. You can see Screen Shot how we call and make ModalBottomSheet. ``` Button( onClick = { showBottomSheet = true } ) { Text(text = "Done") } if(showBottomSheet) StyleBottomSheet() ``` [ModelBottomSheet Composable Function][1] ``` @OptIn(ExperimentalMaterial3Api::class) @Composable fun StyleBottomSheet() { val scope = rememberCoroutineScope() val sheetState = rememberModalBottomSheetState() var showBottomSheet by remember { mutableStateOf(false) } ModalBottomSheet( onDismissRequest = { showBottomSheet = false }, sheetState = sheetState ) { // Sheet content Button(onClick = { scope.launch { sheetState.hide() }.invokeOnCompletion { if (!sheetState.isVisible) { showBottomSheet = false } } }) { Text("Hide bottom sheet") } } } ``` [1]: https://i.stack.imgur.com/CxCeh.png
I have Eclipse recently installed and the version is Eclipse IDE for Enterprise Java and Web Developers (includes Incubating components) Version: 2021-03 (4.19.0) Build id: 20210312-0638 OS: Windows 10, v.10.0, x86_64 / win32 Java version: 16 WindowBuilder is also installed version 1.9.5 and updated. I created new Java project and, for example, named it *Employee*. On *Employee* I click right click and go to the bottom where I pick other and scroll down to WindowBuilder and pick Swing Designer- Application window. Source code in new created Java file is OK. Everything is as it should be but when I click on Design tab all windows are blank (Structure, Palette, Properties) and cannot build anything. As I can see while Googling many people have this problem and there was no idea how to fix it. I tried reinstalling Eclipse and WindowBuilder but no luck. [![source code of java class][1]][1] [![Blank Designer view][2]][2] [![updated Window Builder][3]][3] [1]: https://i.stack.imgur.com/zLBMJ.jpg [2]: https://i.stack.imgur.com/FoPIC.jpg [3]: https://i.stack.imgur.com/GzMuA.jpg
Eclipse window builder with blank window and palette
|python|deep-learning|computer-vision|yolov8|object-tracking|
trying to track an object, bounding box jitters
`next()` is low-level and `StopIteration` is low-level too. Those are parts of the iteration protocol. The other side must obey the rules too, a `StopIteration` must be caught (or it becomes a `RuntimeError` - PEP479). The `StopIteration` exception is always raised at the end of the generator and if you don't see an error, the caller must have caught the exception directly (`try-except`) or indirectly, e.g.: gen = sample() # the for statement speaks the iteration protocol # behind the scenes for v in gen: print(f"got {v}")
Cannot open source file "mosquitto.h"C/C++(1696)
|c|mosquitto|raspberry-pi-pico|libmosquitto|
null
So from the loadUserFillenumber using sharedpreference Im getting the userfilled number, and displaying in the sudoku table and cell, but its onlying displaying the userfillednumber from loadstate instead of updating, because of this my isGamewon isnt triggring. I tried but its not working is there any thing i need to modify so that when userfilledNumber from loadstate is updated in the cell instead of displaying, import 'dart:async'; import 'package:flutter/material.dart'; import 'package:iconsax/iconsax.dart'; import 'package:sudoku/Pages/navigation_bar.dart'; import 'package:sudoku/Screens/win_page.dart'; import 'package:sudoku/constants/usefull_tips_slideshow.dart'; import 'package:sudoku/services/game_state_manager.dart'; import 'package:sudoku/widgets/buttons/number_button.dart'; import 'package:sudoku/functions/sudoku_points.dart'; import 'package:sudoku/functions/sudoku_validator.dart'; import 'package:sudoku/functions/sudoku_functions.dart'; import 'package:sudoku/widgets/buttons/tool_button.dart'; import 'package:unicons/unicons.dart'; // ignore: must_be_immutable class PausePlay extends StatefulWidget { PausePlay({required this.difficulty, super.key}); // ignore: prefer_typing_uninitialized_variables var difficulty; @override State<PausePlay> createState() => _PausePlayState(); } class _PausePlayState extends State<PausePlay> { final SudokuPoints _pointsManager = SudokuPoints(); List<List<int?>> _userFilledNumbers = List.generate(9, (_) => List<int?>.filled(9, null)); late List<List<int?>> _sudokuGrid; late List<List<bool>> _userFilled; late List<List<List<int?>>> _userPencilMarks; late List<Map<String, dynamic>> _moveHistory; late List<int> _remainingNumbers; late Timer _timer; int? _selectedNumber; int? _selectedRow; int? _selectedCol; int _remainingHints = 0; int _mistakeCount = 0; int _secondsElapsed = 0; bool _isPencilActivated = false; bool _isPaused = false; bool _isGameWon() { return SudokuValidator(_sudokuGrid).isSudokuSolved(); } @override void initState() { super.initState(); _initializeState(); _startTimer(); _loadGameState(); _loadTableState(); _loadUserPencilMarks(); _loadUserFilledNumbers(); } Future<void> _loadTableState() async { try { List<List<int?>> loadedGrid = await GameStateManager.loadTableState(); setState(() { _sudokuGrid = loadedGrid; }); } catch (e) { debugPrint('Error loading Sudoku table state: $e'); } } Future<void> _loadUserPencilMarks() async { try { List<List<List<int?>>> userPencilMarks = await GameStateManager.loadUserPencilMarks(); setState(() { _userPencilMarks = userPencilMarks; }); } catch (e) { debugPrint('Error loading user pencil marks: $e'); } } Future<void> _loadGameState() async { try { Map<String, dynamic> gameState = await GameStateManager.loadGameState(); setState(() { widget.difficulty = gameState['difficulty'] as String; _remainingHints = gameState['remainingHints'] as int; _mistakeCount = gameState['mistakeCount'] as int; _secondsElapsed = gameState['secondsElapsed'] as int; }); } catch (e) { debugPrint('Error loading game state: $e'); } } Future<void> _loadUserFilledNumbers() async { try { List<List<int?>> userFilledNumbers = await GameStateManager.loadUserFilledNumbers(); setState(() { _userFilledNumbers = userFilledNumbers.cast<List<int?>>(); }); } catch (e) { debugPrint('Error loading user pencil marks: $e'); } } void _handleGameWon() async { showDialog( context: context, builder: (BuildContext context) { return WinPage( totalTime: _formatTime(_secondsElapsed), difficultys: widget.difficulty, points: _pointsManager.points, ); }, ); } void _initializeState() { _sudokuGrid = List.generate(9, (_) => List<int?>.filled(9, null)); _userFilled = List.generate(9, (_) => List<bool>.filled(9, false)); _userPencilMarks = List.generate(9, (_) => List.generate(9, (_) => [])); _moveHistory = []; _remainingNumbers = List<int>.generate(9, (_) => 9); } void _togglePause() { setState(() { _isPaused = !_isPaused; }); } @override void dispose() { super.dispose(); _timer.cancel(); GameStateManager.saveGameState( difficulty: widget.difficulty, remainingHints: _remainingHints, mistakeCount: _mistakeCount, secondsElapsed: _secondsElapsed, ); GameStateManager.saveUserFilledNumbers( userFilledNumbers: _userFilledNumbers); GameStateManager.saveUserPencilMarks(userPencilMarks: _userPencilMarks); } // Start the timer void _startTimer() { const oneSec = Duration(seconds: 1); _timer = Timer.periodic(oneSec, (Timer timer) { setState(() { if (!_isPaused) { _secondsElapsed++; } }); }); } //time format String _formatTime(int seconds) { int minutes = seconds ~/ 60; int remainingSeconds = seconds % 60; String minutesStr = minutes < 10 ? '0$minutes' : '$minutes'; String secondsStr = remainingSeconds < 10 ? '0$remainingSeconds' : '$remainingSeconds'; return '$minutesStr:$secondsStr'; } //undo void _handleUndo() { if (_moveHistory.isNotEmpty) { setState(() { final lastMove = _moveHistory.removeLast(); final row = lastMove['row']; final col = lastMove['col']; final prevValue = lastMove['prevValue']; _sudokuGrid[row][col] = prevValue; _userFilled[row][col] = prevValue == null ? false : true; _calculateRemainingNumbers(); }); } } //eraser void _handleEraser() { SudokuFunctions.eraser( _sudokuGrid, _userFilled, _selectedRow, _selectedCol); setState(() {}); } //Pencil void handlePencil(int number) { if (_selectedRow != null && _selectedCol != null) { setState(() { if (_userPencilMarks[_selectedRow!][_selectedCol!].contains(number)) { _userPencilMarks[_selectedRow!][_selectedCol!].remove(number); } else { _userPencilMarks[_selectedRow!][_selectedCol!].add(number); } _selectedNumber = null; }); } } //hintt void _handleHint(BuildContext context) { if (_remainingHints > 0) { SudokuFunctions.hint(_sudokuGrid, _userFilled, context, (int row, int col, int number) { setState(() { _remainingHints--; _sudokuGrid[row][col] = number; _userFilled[row][col] = false; }); }); } else { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('No more hints available!'), duration: Duration(seconds: 1), backgroundColor: Colors.deepPurpleAccent, ), ); } } void _calculateRemainingNumbers() { _remainingNumbers = List<int>.generate(9, (_) => 9); for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (_sudokuGrid[row][col] != null) { _remainingNumbers[_sudokuGrid[row][col]! - 1]--; } } } } Widget _numTiles(BuildContext context, int index) { int row = index ~/ 9; int col = index % 9; int? value = _sudokuGrid[row][col]; bool isSelected = _selectedRow != null && _selectedCol != null && (_selectedRow == row || _selectedCol == col); bool isInSelectedSubgrid = _selectedRow != null && _selectedCol != null && _isInSelectedSubgrid(row, col); bool isEditable = value == null || _userFilled[row][col]; bool isWrongNumber = _userFilled[row][col] && value != null && !SudokuValidator(_sudokuGrid).isValidPlacement(row, col, value); bool hasUserPencilMarks = _userPencilMarks[row][col].isNotEmpty; Color? cellColor = isWrongNumber ? Colors.redAccent : isSelected || isInSelectedSubgrid ? Colors.deepPurple[100] : Colors.white; Color? textColor = isWrongNumber ? Colors.white : isSelected || isInSelectedSubgrid ? Colors.black : isEditable ? Colors.deepPurple[800] : Colors.black; if (_selectedRow == row && _selectedCol == col) { cellColor = Colors.deepPurpleAccent[100]; textColor = Colors.white; } if (_selectedNumber != null && value == _selectedNumber) { cellColor = Colors.deepPurple[400]; textColor = Colors.white; } if (!isEditable && hasUserPencilMarks) { _userPencilMarks[row][col] = []; } if (_userFilledNumbers[row][col] != null) { value = _userFilledNumbers[row][col]; textColor = Colors.deepPurpleAccent; // Set value to user-filled number } return GestureDetector( onTap: isEditable ? () { setState(() { _selectedRow = row; _selectedCol = col; _selectedNumber = value; }); } : null, child: Container( decoration: BoxDecoration( border: Border( top: BorderSide( color: Colors.deepPurple, width: _getBorderWidth(row, true), ), left: BorderSide( color: Colors.deepPurple, width: _getBorderWidth(col, false), ), right: col == 8 ? const BorderSide(color: Colors.deepPurpleAccent, width: 1.0) : BorderSide.none, bottom: row == 8 ? const BorderSide(color: Colors.deepPurpleAccent, width: 1.0) : BorderSide.none, ), color: cellColor, ), child: Stack( children: [ Center( child: Text( '${value ?? ''}', style: TextStyle( color: textColor, fontFamily: 'PoppinsBold', fontSize: 18.5, fontWeight: isWrongNumber ? FontWeight.bold : FontWeight.normal, ), ), ), if (isEditable && hasUserPencilMarks) _buildPencilMarks(row, col), ], ), ), ); } Widget _buildPencilMarks(int row, int col) { bool isSelected = _selectedRow != null && _selectedCol != null && (_selectedRow == row || _selectedCol == col); return AspectRatio( aspectRatio: 1, child: Container( color: Colors.transparent, child: GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, ), itemBuilder: (context, index) { int number = index + 1; bool isUserPencil = _userPencilMarks[row][col].contains(number); return Center( child: Text( isUserPencil ? '$number' : '', style: TextStyle( fontSize: 10, color: isSelected ? Colors.white : Colors.deepPurpleAccent, fontFamily: 'PoppinsBold', ), ), ); }, itemCount: 9, physics: const NeverScrollableScrollPhysics(), ), ), ); } double _getBorderWidth(int position, bool isRow) { if ((position % 3 == 0 && position > 0)) { return 2.5; } return 1.0; } bool _isInSelectedSubgrid(int row, int col) { if (_selectedRow == null || _selectedCol == null) { return false; } int subgridStartRow = (_selectedRow! ~/ 3) * 3; int subgridStartCol = (_selectedCol! ~/ 3) * 3; return row >= subgridStartRow && row < subgridStartRow + 3 && col >= subgridStartCol && col < subgridStartCol + 3; } void _updateCell(int number) async { if (_selectedRow != null && _selectedCol != null) { bool isValid = await SudokuValidator(_sudokuGrid) .validateCell(_selectedRow!, _selectedCol!, number); if (isValid) { _pointsManager.correctMove(); // Increment points for correct move } else { _pointsManager.wrongMove(); // Decrement points for wrong move } if (isValid) { _moveHistory.add({ 'row': _selectedRow!, 'col': _selectedCol!, 'prevValue': _sudokuGrid[_selectedRow!][_selectedCol!], }); } else { _moveHistory.add({ 'row': _selectedRow!, 'col': _selectedCol!, 'prevValue': _sudokuGrid[_selectedRow!][_selectedCol!], }); setState(() { _mistakeCount++; }); } setState(() { if (isValid) { _sudokuGrid[_selectedRow!][_selectedCol!] = number; _userFilled[_selectedRow!][_selectedCol!] = false; _userFilledNumbers[_selectedRow!][_selectedCol!] = number; } else { _sudokuGrid[_selectedRow!][_selectedCol!] = number; _userFilled[_selectedRow!][_selectedCol!] = true; _userFilledNumbers[_selectedRow!][_selectedCol!]; } _selectedRow = null; _selectedCol = null; _selectedNumber = null; _calculateRemainingNumbers(); if (_isGameWon()) { _handleGameWon(); _timer.cancel(); } }); if (!isValid) { // ignore: use_build_context_synchronously ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Wrong Sudoku move!'), duration: Duration(seconds: 1), backgroundColor: Colors.deepPurpleAccent, ), ); } } } void _updateSelectedNumber(int number) { setState(() { _selectedNumber = _selectedNumber == number ? null : number; }); } Widget _numberButton(int number) { return NumberButton( number: number, isPencilActivated: _isPencilActivated, selectedNumber: _selectedNumber, remainingNumbers: _remainingNumbers, handlePencil: handlePencil, updateSelectedNumber: _updateSelectedNumber, updateCell: _updateCell, ); } here is the code I need to update the userfilled number from loadstate instead of displaying
1. `char [2]` is needed hold a string with one character and the terminating '\0'. 1. Always use a maximum field width when reading a string with `scanf()`. 1. The format string `%s` requires a matching `char *` which you write as just `c`. 1. On success `scanf()` return the number of items successfully matched. If you don't check for that you may be operating on uninitialized variables. ``` #include <stdio.h> int main(void) { int a; int b; char c[2]; if(scanf("%i%i%1s", &a, &b, c) != 3) { printf("scanf failed\n"); return 1; }; printf("%i %i %s",a, b, c); } ``` If you only enter two numbers, `scanf()` will be waiting for the operator. If you don't want this behavior use `fgets()` or `getline()` then use `sscanf()` or lower level functions like `strtol()` to parse the line of input. Example run: ``` $ ./a.out 1 x scanf failed $ ./a.out 1 2 + 1 2 + ```
|c#|ms-word|
I'm sure i'm using the same id, but when send_message_process tries to edit the message with the provided message id gotten on queue, i get the following error: Error editing message: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: chat not found... Trying again ``` import telebot import threading import requests import re import multiprocessing from queue import Queue from telebot import types from defs_helper import * from datetime import datetime import time as tm gpid = 'xxxxx' Token = "xxxxx" bot = telebot.TeleBot(Token) def startloop(queue): global gpid while True: print('Starting search for new entry') try: bot.send_message('xxxxxx', 'Looking for new entry...') # Restante do seu código... except Exception as e: print(f'Erro ao enviar mensagem Telegram: {e}') tm.sleep(30)` verify_m_number = get_m_number() print(verify_m_number) if verify_m_number == 1: mlist = updatematchlist() while len(mlist) == 0: mlist = updatematchlist() mlist = updatematchlist() print(mlist) pattern = r'\((.*?)\)' matches = re.findall(pattern, mlist[0][2]) pl1 , pl2 = matches patterntm = r'\b([A-Z][a-zA-Z\s\d]+) \((.*?)\)' matchestm = re.findall(patterntm, mlist[0][2]) tm1 = matchestm[0][0] tm2 = matchestm[1][0] hEm = mlist[0][1].split('\n')[1].split(':') print(hEm) mint = str(getnt().minute).zfill(2) hr = str(getnt().hour).zfill(2) print("hEm[0]:", str(hEm[0]).zfill(2)) print("hEm[1]:", hEm[1]) print("hr:", hr) print("mint:", mint) med = overunderstat(pl1, pl2) if str(hEm[0]).zfill(2) != hr: print('different hr, looking for more') if str(hEm[0]).zfill(2) == hr and (int(mint) < int(hEm[1]) or (mint == '00' and hEm[1] != '00')): print('got it') event_minute = int(hEm[1]) print(event_minute) event_second = 0 current_minute = int(mint) current_second = int(getnt().second) print(pl1, pl2) # Aguardar até o próximo minuto time_to_sleep = (event_minute - current_minute - 1) * 60 + (60 - current_second) time_to_sleep = time_to_sleep - (time_to_sleep/3) time_to_sleep = round(float(time_to_sleep), 1) print(time_to_sleep) tm.sleep(time_to_sleep) # if (mint - hEm[1]) > 3: # tm.sleep(60) print('starting') mtchdata = [] while len(mtchdata) == 0: mtchdata = getmatchdata(pl1, pl2) print(mtchdata) print(f'med: | {med} > mtchdata: | {mtchdata} ?') print(chkourate(med, mtchdata)) odd = mtchdata[0].split("-")[1] if len(chkourate(med, mtchdata)) > 0: calc = chkourate(med, mtchdata) foundentry = (f""" Over Asiático ({mtchdata[0].split("-")[2]}) - @{odd}\n {pl1} vs {pl2} ({tm1}) vs ({tm2})\n""") fnde_sent = bot.send_message(gpid, foundentry) to_put = [fnde_sent.message_id, pl1, tm1, pl2, tm2, mtchdata, odd, calc] queue.put(to_put) tm.sleep(180) else: tm.sleep(60) continue elif verify_m_number == 2: mlist = updatematchlist() while len(mlist) == 0: mlist = updatematchlist() mlist = updatematchlist() print(f'\n\n\n{mlist}') pattern_pl = r'\((.*?)\)' matchespl_fi = re.findall(pattern_pl, mlist[0][2]) pl1_fi , pl2_fi = matchespl_fi # __________________________________________________ print(mlist) matchespl_se = re.findall(pattern_pl, mlist[1][2]) pl1_se , pl2_se = matchespl_se ################################################ ################################################ pattern_tm = r'\b([A-Z][a-zA-Z\s\d]+) \((.*?)\)' matchestm_fi = re.findall(pattern_tm, mlist[0][2]) tm1_fi = matchestm_fi[0][0] tm2_fi = matchestm_fi[1][0] # __________________________________________________ matchestm_se = re.findall(pattern_tm, mlist[1][2]) tm1_se = matchestm_se[0][0] tm2_se = matchestm_se[1][0] hEm = mlist[0][1].split('\n')[1].split(':') print(hEm) mint = str(getnt().minute).zfill(2) hr = str(getnt().hour).zfill(2) print("hEm[0]:", str(hEm[0]).zfill(2)) print("hEm[1]:", hEm[1]) print("hr:", hr) print("mint:", mint) med_fi = overunderstat(pl1_fi, pl2_fi) med_se = overunderstat(pl1_se, pl2_se) if str(hEm[0]).zfill(2) != hr: print('different hr, looking for more') if str(hEm[0]).zfill(2) == hr and (int(mint) < int(hEm[1]) or (mint == '00' and hEm[1] != '00')): print('got it') event_minute = int(hEm[1]) print(event_minute) event_second = 0 current_minute = int(mint) current_second = int(getnt().second) print(f'First: ({pl1_fi},{pl2_fi})\nSecond:({pl1_se},{pl2_se})') # Aguardar até o próximo minuto time_to_sleep = (event_minute - current_minute - 1) * 60 + (60 - current_second) time_to_sleep = time_to_sleep - (time_to_sleep/3) time_to_sleep = round(float(time_to_sleep), 1) print(time_to_sleep) tm.sleep(time_to_sleep) # ['Over-2.1-2.5', 'Under-1.67-2.5'] print('starting') mtchdata_fi = [] mtchdata_se = [] fi_ver = 0 se_ver = 0 while len(mtchdata_fi) == 0 or len(mtchdata_se) == 0: mtchdata_fi = getmatchdata(pl1_fi, pl2_fi) mtchdata_se = getmatchdata(pl1_se, pl2_se) print(f'mdata_fi: {mtchdata_fi} | mdata_se: {mtchdata_se}') if len(mtchdata_fi) > 0 or len(mtchdata_se) > 0: fi_ver = len(chkourate(med_fi, mtchdata_fi)) se_ver = len(chkourate(med_se, mtchdata_se)) if fi_ver > 0: mtchdata_se = ['Over-1.85-0.5'] break elif se_ver > 0: mtchdata_fi = ['Over-1.85-0.5'] break mtchdata_fi = getmatchdata(pl1_fi, pl2_fi) mtchdata_se = getmatchdata(pl1_se, pl2_se) xmidfi = float(med_fi) - 0.5 xmidse = float(med_se) - 0.5 print(f'med_fi: | {xmidfi} > mtchdata_fi: | {mtchdata_fi} ?') print(f'med_se: | {xmidse} > mtchdata_se: | {mtchdata_se} ?') # ['Over-2.1-2.5', 'Under-1.67-2.5'] if fi_ver > 0: mtchdata = mtchdata_fi med = med_fi pl1 = pl1_fi pl2 = pl2_fi tm1 = tm1_fi tm2 = tm2_fi odd = mtchdata[0].split("-")[1] calc = chkourate(med, mtchdata) foundentry = (f""" Over Asiático ({mtchdata[0].split("-")[2]}) - @{odd}\n {pl1} vs {pl2} ({tm1}) vs ({tm2})\n""") fnde_sent = bot.send_message(gpid, foundentry) print("message suposed to be sent") print(f'messageid: {fnde_sent.message_id}') to_put = [fnde_sent.message_id, pl1, tm1, pl2, tm2, mtchdata, odd, calc] queue.put(to_put) tm.sleep(180) elif se_ver > 0: mtchdata = mtchdata_se med = med_se pl1 = pl1_se pl2 = pl2_se tm1 = tm1_se tm2 = tm2_se odd = mtchdata[0].split("-")[1] calc = chkourate(med, mtchdata) foundentry = (f""" Over Asiático ({mtchdata[0].split("-")[2]}) - @{odd}\n {pl1} vs {pl2} ({tm1}) vs ({tm2})\n""") fnde_sent = bot.send_message(gpid, foundentry) print("message suposed to be sent") print(f'messageid: {fnde_sent.message_id}') to_put = [fnde_sent.message_id, pl1, tm1, pl2, tm2, mtchdata, odd, calc] queue.put(to_put) tm.sleep(180) else: tm.sleep(60) continue # except Exception as e: # bot.send_message('6162137618', f'Excpetion:\n\n{type(e)}\n{e}\n{e.__traceback__}') # tm.sleep(4) # continue else: print(verify_m_number) tm.sleep(3) def send_message_process(queue__): global gpid print('process started') while True: queue_data = queue__.get() if queue_data is not None: print(f"got queue_data: {queue_data}") msg_id = queue_data[0] pl1 = queue_data[1] tm1 = queue_data[2] pl2 = queue_data[3] tm2 = queue_data[4] mtchdata = queue_data[5] odd = queue_data[6] calc = queue_data[7] tm.sleep(1200) result = getfinalresult(pl1, tm1, pl2, tm2) sc_tm1, sc_tm2 = map(int, result.split("x")) totalgl = int(sc_tm1) + int(sc_tm2) resultmsg_green = (f""" Over Asiático ({mtchdata[0].split("-")[2]}) - @{odd}\n {pl1} vs {pl2} ({tm1}) vs ({tm2}) \U00002705\U00002705\U00002705\U00002705 GREEN\n""") resultmsg_red = (f""" Over Asiático ({mtchdata[0].split("-")[2]}) - @{odd}\n {pl1} vs {pl2} ({tm1}) vs ({tm2}) \U0000274C\U0000274C\U0000274C\U0000274C RED\n""") if float(totalgl) > float(calc): try: bot.edit_message_text(gpid, msg_id, resultmsg_green) print("Message edited: GREEN") except Exception as e: print(f"Error editing message: {e}... Trying again") try: bot.edit_message_text(gpid, msg_id, resultmsg_green) except Exception as e: print('Failed to edit message... Continuing loop') continue elif float(totalgl) <= float(calc): try: bot.edit_message_text(gpid, msg_id, resultmsg_red) print("Message edited: RED") except Exception as e: print(f"Error editing message: {e}... Trying again") try: bot.edit_message_text(gpid, msg_id, resultmsg_red) except Exception as e: print('Failed to edit message... Continuing loop') continue tm.sleep(3) if __name__ == '__main__': match_queue = multiprocessing.Queue() search_process = multiprocessing.Process(target=startloop, args=(match_queue,)) send_message_process = multiprocessing.Process(target=send_message_process, args=(match_queue,)) search_process.start() send_message_process.start() search_process.join() send_message_process.join() ```
Try using return and not echo (and avoid die()) public function sendJsonResponse($data) { ob_start(); ob_clean(); header('Content-type: application/json'); return json_encode($data); } anyway check if in your controller you are using others `return` or `echo` for other value somewhere in your code and refactor your code for avoid this. You should send all the value just in one return
Boolean sortAsc = Objects.nonNull(chooseRequest) ? chooseRequest.getSortAsc() : false; those code will throw NPE exception, why? chooseRequest is a DTO and chooseRequest.getSortAsc() will return null but Boolean sortAsc = Objects.nonNull(chooseRequest) ? null : false; is ok I cannot understand, JVM is 11
There is a lot of text printed on the terminal window from my C# code, some text is printed by an other app that I ran through C# `System.Diagnostics` (without `RedirectStandardOutput` neither I wanna use that `async` thing) and it printed it's own text and some text is printed by C# `Console.WriteLine` function. I want to save all of that text from top to bottom to a text file. I don't want to execute any file and store it's text since all the execution is already done and all the text is printed already. I just want to save all of that text to a file at the end of the program. > NOTE: *The following is not my real code (obviously) but it looks kind of like this.* ```python from rich.progress import track import time, os print("Python Test") for i in track(range(20), description="Processing..."): time.sleep(0.1) # Simulate work being done os.system("color 08") ``` ```csharp using System.Diagnostics; Console.WriteLine("Test"); // Create a new process instance Process process = new Process(); // Configure the process using StartInfo process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = $"/c echo Hello world! & timeout /t 2 & python test.py"; // Start the process process.Start(); // Wait for CMD to finish process.WaitForExit(); Console.WriteLine("Test1"); /* ---- Save all of that above text that was printed here at the end of the code. ---- */ ``` I don't want to use `RedirectStandardOutput` because as far as I know if I do that and print the things from the `process` using those `async` things, first, it will not be able to print live updates such as in that `timeout /t 2` part, it's also won't be able to account for change in color of the window `color 08`. I want such a system that will let the code execute normally but when the code reaches the end it exports the text to a file much like how the now Windows Terminal's `Export Text` feature works. This is what I want to achieve: The terminal should work normally no change in how it works. [![the terminal should work normally.][1]][1] After the all the things are done at the end of my C# code I want to save all of that text to a text file. [![what kind of output I want while exporting the text][2]][2] [1]: https://i.stack.imgur.com/XWWPp.gif [2]: https://i.stack.imgur.com/L3cQh.png
I'm trying to access datasets in PBI, but I can't get the correct permissions I created an application in Microsoft Entra ID To get a token I make a request: ```http POST /{{tenantId}}/oauth2/v2.0/token HTTP/1.1 Host: login.microsoftonline.com Content-Type: application/x-www-form-urlencoded Content-Length: ... client_id={{clientId}} &grant_type=client_credentials &scope=https://analysis.windows.net/powerbi/api/.default openid profile offline_access &client_secret={{clientSecret}} ``` I receive a response with a token: ```json { "token_type": "Bearer", "expires_in": 3599, "ext_expires_in": 3599, "access_token": "ey...Cw" } ``` After this, I make a request to get datasets: ```http GET /v1.0/myorg/groups/{{workspaceId}}/datasets/{{datasetId}} HTTP/1.1 Host: api.powerbi.com Authorization: Bearer ey...Cw ``` And I receive a 401 response: ```json { "error": { "code": "PowerBINotAuthorizedException", "pbi.error": { "code": "PowerBINotAuthorizedException", "parameters": {}, "details": [], "exceptionCulprit": 1 } } } ``` Following permissions are specified for the app in Microsoft Entra ID: [Microsoft Entra ID App API Permissions](https://i.stack.imgur.com/xLi3w.png)
Microsoft Power BI REST API PowerBINotAuthorizedException
|api|rest|powerbi|powerbi-desktop|
null
Suggestions to consider for your my.cnf [mysqld] section. Zaki, General Log is NORMALLY not ON. Until actually needed and will be used, general_log=OFF When needed from MySQL Command Prompt, SET GLOBAL general_log=ON then when you have sufficient logging completed, usually less than one minute - unless you have a VERY LONG executing process, SET GLOBAL general_log=OFF to avoid filling your storage with information you will NEVER look at. Trust me a full storage device is NO FUN to deal with. Do you have a REAL good reason for setting innodb_page_size anything other than the default of 16384? Consider editing your my.cnf to get back to the default from 64K This has helped the few instances where they have attempted anything other than 16384 and been troubled with incidents out of nowhere. Additional suggestions will be provided after posting the additional information requested in a comment above.
I am trying to follow the answer [here][1] to answer my question. I have data like this: [![enter image description here][2]][2] Columns A and B are my data. I want to aggregate the data in columns A and B for every integer value in A by averaging the values in column B. So for every value in A that starts with a 17 I want an average of the 4 corresponding values in B and so on. Here is what I have tried. In column C I round column A down to the nearest integer. In column D I use `=UNIQUE(C1:C11466)` to get only the unique values in C. Then in column E I am using `=AVERAGEIF($C$1:$C$11466,D1#,$B$1:$B$11466)` but you can see it isn't working. I'm reproducing the answer in the link (I think) but I'm not sure why it is not working. I think there should be an easier way to do this but so far this method is the closest I've gotten. I would prefer to not use pivot tables unless there is no other way, I understand that may work also. [1]: https://stackoverflow.com/questions/77645814/excel-how-can-i-group-by-column-a-and-calculate-the-average-according-to-the-val [2]: https://i.stack.imgur.com/IyhXl.png
Your code is using a single thread executor task which submits another task to same single thread executor, and then awaits that sub-task to exit. It is the same as this example which would print "ONE" and "THREE", and never print "TWO" or "cf": ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { log("ONE"); Future<?> cf = executor.submit(() -> log("TWO")); log("THREE"); try { log("cf"+cf.get()); } catch (Exception e) { throw new RuntimeException("It failed"); } log("FOUR"); executor.shutdown(); }, executor); The subtask could only run after the main task exits - if "FOUR" was printed - but is stuck awaiting `cf.get()`. The solution is easy - you should process the initial task on separate Thread or executor queue to the service used by the sub-tasks.
For reasons, I have remapped a directory on my computer: subst a: c:\Data\A For example, I start vscode with the path "A:\develop\Hello", which is the directory where my Javascript application is located. The require statements where the path starts with "./" are displayed correctly, e.g. require "./myModule" shows when hovering: module "A:\develop\Hello\myModule" If the require statement is like the following: require "myModule" is shows: module "c:\Data\A\develop\Hello\myModule" instead. How can I prevent this? The module path should of course always be within the project directory. Like in the first version. (The first version can only be used as an alternative at the top level.) Version: 1.87.0 (user setup) Commit: 019f4d1419fbc8219a181fab7892ebccf7ee29a2 Date: 2024-02-27T23:41:44.469Z Electron: 27.3.2 ElectronBuildId: 26836302 Chromium: 118.0.5993.159 Node.js: 18.17.1 V8: 11.8.172.18-electron.0 OS: Windows_NT x64 10.0.19045 Update: When I execute require.resolve I get the correct paths.
For me, installing this version worked: ``` tensorflow==2.15.1 ``` 2.12 was not found
With the fact that the provided link in the comment had slightly different outputs. Just so that no one else have to waste 20 minutes trying to find the question with an answer instead of reading the comments I'll put this answer here. The outputs like ``` <QueryDict: { 'csrfmiddlewaretoken': [''], 'data_products[0][record_id]': [''], 'data_products[0][product_id]': [''], 'data_products[0][foil]': ['false'], 'data_products[0][condition]': ['nm'], 'data_products[0][language]': ['eng'], 'data_products[0][quantity]': ['1'], 'data_products[1][record_id]': [''], 'data_products[1][product_id]': [''], 'data_products[1][foil]': ['false'], 'data_products[1][condition]': ['nm'], 'data_products[1][language]': ['eng'], 'data_products[1][quantity]': ['2'] }> ``` Happen when trying to send an actual json object instead of a string of json. So the relevant part in https://stackoverflow.com/questions/37698371/passing-a-dict-of-dict-with-ajax is ``` ... data : { 'values' : JSON.stringify(values) } , ... ```
I only append `export EDITOR=vim` in my `.zshrc` and it works! I think you forgot to run `source ~/.zshrc` after the changes.
Being new to the IT field, I want to create an entertainment and moderation bot but I encounter several problems: Process exited with code 1 Uncaught ReferenceError ReferenceError: client is not defined Here are my lines of code: const { Client } = require("discord.js"); const bot = new Client({ intents: ["Guilds"] }); console.log("Connexion au bot..."); bot.login("MY TOKEN") .then(() => console.log("Connecté au bot !")) .catch((error) => console.log("Impossible de se connecter au bot - " + error)); bot.on("ready", async () => { await bot.application.commands.set([ { name: "ping", description: "Pong!" } ]); console.log("Le bot est prêt !"); }); bot.on("interactionCreate", (interaction) => { if (!interaction.isCommand()) return; if (interaction.commandName === "ping") interaction.reply("Pong!"); if (interaction.commandName === "maj") interaction.reply("Pour connaître les derniers mises à jours du bot, merci de vous référencer à Xinfeng"); }); client.on("messageCreate", message => { if(message.author.bot) return; //+help if (message.content === prefix + "help"){ const embed = new Discord.EmbedBuilder() .setColor("#ffcc00") .setTitle("**__Les commandes du bot__**") .setURL("https://discord.js.org/") .setDescription("Vous trouverez toutes les commandes dont vous pouvez faire usage") .addFields( { name: '**__+commandes:__**', value: 'Affiche la liste des commandes' }, { name: '**__+description:__**', value: 'Affiche la description du bot' }, { name: '**__+info:__**', value: 'Affiche les informations du bot' }, { name: '**__Support Developpement:__**', value: 'https://discord.gg/H9mSXeAm8C' } ); message.channel.send({ embeds: [embed]}); } //+description if (message.content === prefix + "description"){ const embed = new Discord.EmbedBuilder() .setColor("#ffcc00") .setTitle("**__Description du bot__**") .setURL("https://discord.js.org/") .setDescription("Je suis Athéna, une déesse grec de l'artisanat et de la stratégie guerrière. Je m'occupe de la modération, jeux et de trackage d’information "); message.channel.send({ embeds: [embed]}); } console.log(message); if(message.content === "Salut"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "salut"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Coucou"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "coucou"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hey"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Heyyy"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hello"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hello tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "hello"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "hello tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hoyaa"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Hey tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "slt tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Slt tlm"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "hey"){ message.reply("Bonjour jeune aventurier"); } if(message.content === "Bonjour"){ message.reply("Bonjour jeune aventurier"); } else if(message.content === "help"){ message.channel.send("**__les commandes du bot ATHENA sont__**\n - +help: Il permettra de configurer et de mieux comprendre les commandes") } else if(message.content === "description"){ message.channel.send("**__Pour connaître la description du bot ATHENA sont__**\n - +description: Il permettra de connaître l'histoire et la naîssance du bot") } else if(message.content === "mention"){ message.reply("Mention d'un utilisateur : <@" + message.author.id + "> \n Mention d'un salon : <#" + message.channel.id + ">"); } }); I would like to know if we can resolve this problem and also if I did the lines of code correctly, thank you.
I have a coding problem and the bot does not do the requested function
|javascript|
Parent-Child vs `Range.IndentLevel` - [![enter image description here][1]][1] **The Calling Procedure (Example)** <!-- language: lang-vb --> Sub RunParentChild() Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Target") Dim rg As Range: Set rg = ws.Range("A1", ws.Cells(ws.Rows.Count, "A").End(xlUp)) With rg.EntireRow .Columns("B").Value = GetIndentLevels(rg) ' not necessary .Columns("C").Value = GetIndentedParentChildFromColumn(rg, "SUB") End With End Sub **The Called (Helper) Procedures** <!-- language: lang-vb --> Function GetIndentLevels(rg As Range) As Long() Dim rCount As Long: rCount = rg.Rows.Count Dim cCount As Long: cCount = rg.Columns.Count Dim Data() As Long: ReDim Data(1 To rCount, 1 To cCount) Dim r As Long, c As Long For r = 1 To rCount For c = 1 To cCount Data(r, c) = rg.Cells(r, c).IndentLevel Next c Next r GetIndentLevels = Data End Function <!-- language: lang-vb --> Function GetIndentedParentChildFromColumn( _ rg As Range, _ ChildBeginsWith As String, _ Optional ColumnIndex As Long = 1) _ As Variant Dim IndentLevels() As Long: IndentLevels = GetIndentLevels(rg) Dim cData As Variant: cData = GetRange(rg.Columns(ColumnIndex)) Dim rCount As Long: rCount = UBound(cData, 1) Dim r As Long, i As Long, IsFirstFound As Boolean For r = 1 To rCount If IsFirstFound Then i = IndentLevels(r, 1) Select Case IndentLevels(r - 1, 1) Case Is < i If r <> rCount Then If IndentLevels(r + 1, 1) > i Then cData(r, 1) = "P" Else cData(r, 1) = "C" End If Else cData(r, 1) = "C" End If Case i If r = rCount Then If InStr(1, CStr(cData(r, 1)), ChildBeginsWith, _ vbTextCompare) = 1 Then cData(r, 1) = "C" Else cData(r, 1) = "P" End If Else If IndentLevels(r + 1, 1) > i Then cData(r, 1) = "P" Else cData(r, 1) = "C" End If End If Case Is > i If InStr(1, CStr(cData(r, 1)), ChildBeginsWith, _ vbTextCompare) = 1 Then cData(r, 1) = "C" Else cData(r, 1) = "P" End If End Select Else cData(r, 1) = "P" IsFirstFound = True End If Next r GetIndentedParentChildFromColumn = cData End Function <!-- language: lang-vb --> Function GetRange(rg As Range) As Variant() If rg.Rows.Count + rg.Columns.Count = 2 Then ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value: GetRange = Data Else GetRange = rg.Value End If End Function [1]: https://i.stack.imgur.com/n6JBT.jpg
Excel - Aggregating Data in One Column Based on Values in Another Column
|excel|aggregate|average|
I depacketize the H264 video fragments from an IP.RTP stream and save them to video.ivf file. After depacketizing i have only [SPS] ,[PPS] and [non-IDR slice]. I try to create IDR slice by using x264 lib. x264 lib creates IDR frame which consists of 0x000001[SPS] 0x000001[PPS] 0x0001[SE slice] and 0x0001[I slice]. i insert it in the beginning of my file. But when i try to play this with VLC player it doesn't plays well. if i convert it to video.mp4 by ffmpeg i get playablr file. I think the problem is that after creating IDR frame with x264 lib I get SPS and PPS frames different from those that I get from the stream. My question is how to set parameters for x264 if i have real SPS and PPS frames to get the same SPS and PPS frames. Here is my code: `x264_param_t param;` ``` `x264_param_t param`; `/* Get default params for preset/tuning */ x264_param_default_preset(&param, "medium", NULL);` `/* Configure non-default params */ param.i_csp = X264_CSP_I420; param.i_width = width;//640 GET FROM SPS !!!!!!!!!! param.i_height = height;//360; GET FROM SPS !!!!!!!!!!!!!! param.b_vfr_input = 0; //frame rate param.b_repeat_headers = 1; param.b_annexb = 1; `x264_t *encoder = x264_encoder_open(&param);` if (encoder) { // These are the two picture structs. Input must be alloc() // Output will be created by the encode process x264_picture_t pic, pic_out; int r = x264_picture_alloc(&pic, X264_CSP_I420, width, height); if (r == 0) { pic.i_type = X264_TYPE_IDR; int y_bytes = width * height; int uv_bytes = width * height / 4; UCHAR* result = pic.img.plane[0]; // luma for (unsigned int y = 0; y < height; y++) { for (unsigned int x = 0; x < width; x++) pic.img.plane[0][y * width + x] = 0x16; } // chroma for (unsigned int y = 0; y < height / 2; y++) { for (unsigned int x = 0; x < width / 2; x++) { pic.img.plane[1][y * width / 2 + x] = 0x16; pic.img.plane[2][y * width / 2 + x] = 0x80; } } int i_frame_size = x264_encoder_encode(encoder, &nal, &i_nal, &pic, &pic_out); } }` ``` Maybe i should set another parameters for x264_param_t param which i can get from SPS and PPS can someone help me with this issue
How to create IDR I-slice frame for H264 bytestream?
|c++|x264|
null
|javascript|callback|
What you ask for is not possible with Subversion. Subversion is a *centralized* version control system. Centralized means there's one repository to which clients connect. The repository consists mainly of a database which contains all the content and the history of the changes. These are stored in a binary, optimized format. In contrast to that, any client has a *working copy* which contains (part of) the content, where the repository can be found and the last synchronized state of the local content as it would be found in the repository. Working copies usually contain textual data like source code and configuration files. Long story short: repositories and working copies are not the same and you cannot use them interchangeably. In your question, you do not explain where the repository resides. Is it also on "the-one" PC? If so, it should probably run a Subversion server to which clients can connect. It is also possible to copy an entire Subversion repository, e.g. through the `svnadmin` commands. This allows you to set up a repository in a more convenient location. If you really want to share a working copy between several contributors, note that nothing will prevent them from overwriting each other's changes. This defeats the purpose of using a VCS. You would need to put another means of version control in place. It may be tempting to consider `git svn` which creates a Git repository connected to a Subversion repository as an intermediary. Note however its [documented caveats](https://git-scm.com/docs/git-svn#_caveats). As for the `rsync` approach, that's essentially a very basic implementation of your own little VCS. I would not recommend it. Anyway, it might work until you run into trouble because ... * conflicting changes to the same file * timestamps are off * added/deleted files are not propagated correctly * anything else I can't foresee off the top of my head In any case, I'd advise to `rsync` only the content, not the metadata. That means ignoring the `.svn` directory in the working copy. We would not want to rewind the working copy to an earlier stage because somebody `rsync`'d last month's `.svn` dir back (which should be fixed with an `svn update` but better to prevent these things in the first place). FWIW, I've used `unison` (which is essentially a two-way `rsync`) for some rudimentary backup tasks. You might find it useful. I would still recommend to use a real VCS over a homegrown solution.
This issue can also be caused when using `pnpm deploy /path/here` and using a path such as `/dev/myapp` for example (this path is reserved for device files). Double check where you're deploying/installing pnpm.
Try to write the **index.html** in this way instead: iosocket.on('connect', function () { $('#incomingChatMessages').append($('<li>Connected</li>')); }); iosocket.on('message', function(message) { $('#incomingChatMessages').append($('<li></li>').text(message)); }); iosocket.on('disconnect', function() { $('#incomingChatMessages').append('<li>Disconnected</li>'); }); It may be caused by the other 2 eventlisteners was registered to the connect event. When the client disconnected, the other 2 listeners will still here and doesn't get unregistered. Official documentation about [Duplicate event registration][1] [1]: https://socket.io/docs/v4/troubleshooting-connection-issues/#duplicate-event-registration
Problem statement ================= You are given a row-wise sorted matrix 'mat' of size m x n where 'm' and 'n' are the numbers of rows and columns of the matrix, respectively. Your task is to find and return the median of the matrix. Note: 'm' and 'n' will always be odd. Example: Input: 'n' = 5, 'm' = 5 'mat' = [ [ 1, 5, 7, 9, 11 ], [ 2, 3, 4, 8, 9 ], [ 4, 11, 14, 19, 20 ], [ 6, 10, 22, 99, 100 ], [ 7, 15, 17, 24, 28 ] ] Output: 10 Explanation: If we arrange the elements of the matrix in the sorted order in an array, they will be like this- 1 2 3 4 4 5 6 7 7 8 9 9 10 11 11 14 15 17 19 20 22 24 28 99 100 So the median is 10, which is at index 12, which is midway as the total elements are 25, so the 12th index is exactly midway. Therefore, the answer will be 10. This is the question I am trying to solve using Binary Search Below is the code I have written but it is only able to pass some test cases and showing wrong answer in other cases. I am unable to find if I have made some logical error or my code doesn't work on edge cases. ``` import java.util.Arrays; public final class Solution { public static int findMedian(int matrix[][], int m, int n) { // Write your code here int[] pos= findPos(matrix,m,n); int req=(m*n)/2; while (pos[0]<=pos[1]) { int mid = (pos[0]+pos[1])/2; int smallEquals = blackbox(matrix,m,n,mid); if(smallEquals>=req){ pos[1]=mid-1; }else{ pos[0]=mid+1; } } return pos[0]; } public static int blackbox(int matrix[][], int m, int n, int mid){ int cnt=0; for (int i = 0; i < m; i++) { int low=0; int high=n-1; while(low<=high){ int mid1=(low+high)/2; if(matrix[i][mid1]<mid){ low=mid1+1; }else{ high=mid1-1; } } cnt+=low; } return cnt; } public static int[] findPos(int matrix[][], int m, int n){ int min=matrix[m-1][n-1]; int max=matrix[0][0]; for(int i=0; i<m; i++){ if(matrix[i][0]<min){ min=matrix[i][0]; } if(matrix[i][n-1]>max){ max=matrix[i][n-1]; } } return new int[]{min,max}; } } ``` I have used the optimal solution to solve this problem using Binary Search and Upper Bound. Finding the range of the search space then appying Binary Search on it. However, I am not able to pass all the test cases. The difference is only of 1 between my answer and the correct answer.
The problem is that you are setting `head.next.next = head` and then calling `__repr__` with `print("3 HEAD", head)` or `print("4 NEW_HEAD", new_head)`. In `__repr__`the loop iteratively finds the `.next` attribute, but this causes an infinite loop as after two iterations the node being processed is `head.next.next`, which you have set to be `head` itself! The value of `next` in the loop goes: `head` -> `head.next` -> `head.next.next` (=`head`) -> `head.next` -> `head.next.next` (=`head`) As you can see this causes a loop, so removing the print statements fixes the problem. You can actually prevent a loop being formed entirely by 'breaking the chain' of `.next` earlier in the function. One way to do this is to get a reference to `head.next` at the start of the function, then we can safely set `head.next = None` and not risk causing a infinite loop; if you run this function you will see we can safely call `__repr__` anywhere: ``` def reverse(head): if not head or not head.next: return head print(f"1 {head = }") head_next = head.next print(f"2 {head = }") head.next = None print(f"3 {head = }") new_head = reverse(head_next) print(f"4 {head = }\n{new_head = }") head_next.next = head print(f"5 {head = }\n{new_head = }") return new_head ``` Also, you can simplify your `__repr__` function by making it recursive: ``` def __repr__(self): return f"ListNode({self.val}, {self.next})" ```
In case it is relevant, I am observing this behavior in Tcl 8.6.13. Normally, errors in Tcl include line numbers and filenames when applicable. However, I'm finding that when errors occur in scripts executed with ```interp eval```, I do not get this information. The two examples below are exactly the same, except that Example 1 evaluates the code in the main/parent interpreter, while Example 2 evaluates it in the child interpreter. Example 1 ``` #!/bin/sh # This line continues for Tcl, but is a single line for 'sh' \ exec tclsh "$0" ${1+"$@"} ::safe::interpCreate i eval expr {"a" + 1} ``` Output ``` ./example.tcl invalid bareword "a" in expression "a + 1"; should be "$a" or "{a}" or "a(...)" or ... (parsing expression "a + 1") invoked from within "expr "a" + 1" ("eval" body line 1) invoked from within "eval expr {"a" + 1}" (file "./example.tcl" line 6) ``` Example 2 ``` #!/bin/sh # This line continues for Tcl, but is a single line for 'sh' \ exec tclsh "$0" ${1+"$@"} ::safe::interpCreate i i eval expr {"a" + 1} ``` Output ``` ./example.tcl invalid bareword "a" in expression "a + 1"; should be "$a" or "{a}" or "a(...)" or ... (parsing expression "a + 1") invoked from within "expr "a" + 1" invoked from within "i eval expr {"a" + 1}" (file "./example.tcl" line 6) ``` The error messages are nearly the same, except one line is missing in Example 2's output: ``` ("eval" body line 1)``` In this example, missing that part of the error message is not a problem, since there is only one line of code being evaluated; if it were a large script, or if the error occurred when ```source```'ing a file, that might be a different story. This behavior seems weird; partially because because it is inconsistent, but also because the child interpreter must know which code it is executing, so it should be able to report the line numbers of errors in that code; also, when ```source```ing a file, it should know the file it is reading the code from, since the source command was invoked from the child. So is there any way to get line and file information when using ```interp eval```? Alternatively, is there a way to write this code differently that could provide better error messages in scripts run in child interpreters? Some additional examples (their output still misses the same line): Example 3 (passing code to child interpreter as a single argument). ``` #!/bin/sh # This line continues for Tcl, but is a single line for 'sh' \ exec tclsh "$0" ${1+"$@"} ::safe::interpCreate i i eval {expr {"a" + 1}} ``` Output ``` ./example.tcl can't use non-numeric string as operand of "+" invoked from within "expr {"a" + 1}" invoked from within "i eval {expr {"a" + 1}}" (file "./example.tcl" line 6) ``` Example 4 (passing code to child interpreter as a single argument in a list). ``` #!/bin/sh # This line continues for Tcl, but is a single line for 'sh' \ exec tclsh "$0" ${1+"$@"} ::safe::interpCreate i i eval [list expr {"a" + 1}] ``` Output ``` ./example.tcl can't use non-numeric string as operand of "+" while executing "expr {"a" + 1}" invoked from within "i eval [list expr {"a" + 1}]" (file "./example.tcl" line 6) ``` Example 5 (passing code to child interpreter as a single argument built from lists). ``` #!/bin/sh # This line continues for Tcl, but is a single line for 'sh' \ exec tclsh "$0" ${1+"$@"} ::safe::interpCreate i i eval [list expr [list "a" + 1]] ``` Output ``` ./example.tcl invalid bareword "a" in expression "a + 1"; should be "$a" or "{a}" or "a(...)" or ... (parsing expression "a + 1") invoked from within "expr {a + 1}" invoked from within "i eval [list expr [list "a" + 1]]" (file "./example.tcl" line 6) ``` I also tried Examples 3, 4 and 5 with normal ```eval```, i.e. in the main/parent interpreter. In those cases, they produced the same output as when run with the child interpreter, except they included the missing line.
I have a Gradle Kotlin project where I define dependencies using an object for versioning, like so: ``` object Versions { const val MICROMETER = "1.11.5" } dependencies { implementation("io.micrometer:micrometer-core:${Versions.MICROMETER}")} ``` I've noticed that the dependent bot doesn't automatically upgrade or raise a pull request to update to the new version when a new version of the dependency is available. Interestingly, when I simplify the setup without using the object for versioning, as shown below: ``` dependencies { implementation("io.micrometer:micrometer-core:1.11.5")} ``` The dependent bot does raise a pull request for upgrading to the new version. Is there a specific configuration or setting I'm missing in my Gradle Kotlin project that would enable the dependentbot to automatically upgrade dependencies when using an object for versioning?
Gradle Kotlin project dependentbot not upgrading or raising PR for new versions
|kotlin|gradle|dependabot|
Cause : When you do write program, you make miss Clock setting. How to slove it : 1. Run STM32CubeProgrammer. 2. Change "Mode" into "Power down" 3. Connect 4. Erase full chip flash memory. Before you make programing in to you board, Please Check Clock setting again. If you won't change, it will happen again. Happy programming.
Is it possible to dynamically add images to React-SigmaJS, for example, through hover or when working on a zoom-in Graph? I am working on a large graph where which node has its images generated and stored in blob, instead of download, thus, I was trying to avoid generating 3000 images or more in one go. So far I have tried hovering on nodes to dynamically add the URL and change the type: if (hoveredNode) { if (node === hoveredNode || graph.neighbors(hoveredNode).includes(node)) { newData.highlighted = true; newData.size = 40 newData.type = 'image', newData.image = '/logo.svg' } else { newData.color = "#E2E2E2"; newData.highlighted = false; } } <SigmaContainer style={{ height: "600px", width: "100%" }} graph={graph} settings={{ nodeProgramClasses: { image: getNodeProgramImage() }, defaultNodeType : 'image', }}> <GraphEvents /> </SigmaContainer> But this does not show any image. Do I need to be precise with my image style? Or am I doing it wrong? Thanks for any help, and creating this beautiful library!
Getting wrong answer in Binary Search solution
|java|arrays|data-structures|binary-search|median|
{"Voters":[{"Id":4518341,"DisplayName":"wjandrea"},{"Id":1235698,"DisplayName":"Marcin Orlowski"},{"Id":2530121,"DisplayName":"L Tyrone"}]}
It's possible that the part you're missing is how to use an actual word from the macro in the regular expression. You can do that by using the `new RegExp` constructor. For example: ```new RegExp(`{${obj.subject}}`, 'g')``` which I've elaborated on below. Note: I've used an array of objects to define the subjects/replacements instead of a macro. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> // The text const text = '{HOST} blah blah blah {CONTENT} blah blah {PAGE}' // An array of objects containing the subject and replacement values const mapping = [ { subject: 'HOST', replacement: '10.4.1.13' }, { subject: 'CONTENT', replacement: 'This is content' }, { subject: 'PAGE', replacement: 'Page 1' }, ]; // A function that accepts the text and the mapping object function doReplace(text, mapping) { let updated = text; // Loop over the mapping object and for each object... for (const obj of mapping) { // ...take the subject value and add it to a template string // in a regex constructor - "g" sets the global for the constructor const regex = new RegExp(`{${obj.subject}}`, 'g'); // Use that regex in your replace/replaceAll method, using // the replacement value from the object updated = updated.replaceAll(regex, obj.replacement); } return updated; } console.log(doReplace(text, mapping)); <!-- end snippet --> Additional documentation - [Template/string literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) - [RegExp contructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) - [`replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll)
If you are using Livewire 3, you must apply some changes because your code is made for Livewire 2. In Livewire 3 *wire:model* is deferred by default, so you must add the *live* modifier to it. Also instead of *emit()* you must use *dispatch()*. In *country-dropdown.blade.php* apply this change: ```html <select id="wilaya" wire:model.live="selectedCountry" .... ``` and I suppose that you will also add a *wire:model* to the *capital-dropdown*. <br> *CountryDropdown.php* ```php class CountryDropdown extends Component { public $selectedCountry; public function updatedSelectedCountry($id) { $this->dispatch('countrySelected', countryId: $this->selectedCountry); } public function render() { $countries = Wilaya::all(); return view('livewire.country-dropdown', compact('countries')); } } ``` <br> *CapitalDropdown.php* ```php class CapitalDropdown extends Component { protected $selectedCountry = null; public $capitals; protected $listeners = ['countrySelected' => 'setCountry']; public function setCountry($countryId) { $this->selectedCountry = $countryId; } public function render() { $this->capitals = Commune::where('wilaya_id', $this->selectedCountry)->get(); return view('livewire.capital-dropdown'); } } ``` Instead of $listeners you can also use the [#[On]](https://livewire.laravel.com/docs/events#listening-for-events) php attribute: ```php ..... use Livewire\Attributes\On; class CapitalDropdown extends Component { ..... #[On('countrySelected')] public function setCountry($countryId) { $this->selectedCountry = $countryId; } ..... ```
i am using sox for creating synth with 100ms, this is my command: ``` /usr/bin/sox -V -r 44100 -n -b 64 -c 1 file.wav synth 0.1 sine 200 vol -2.0dB ``` now when i create 3 sine wave files and i combine all with ``` /usr/bin/sox file1.wav file2.wav file3.wav final.wav ``` then i get gaps between the files. i dont know why. but when i open for example file1.wav then i also see a short gap in front and at the end of the file. how can i create a sine with exact 100ms without gaps in front and end? and my 2nd question: is there also a possibility to create e.g. 10 sine wave synths with one command in sox? like sox f1 200 0.1, f2 210 01, f3 220 01, ... first 200hz 10ms, 210hz 10ms, 220hz 10ms thank you so much many greets i have tried some different options in sox but always each single sine file looks like that: ![WAV GAP][1] [1]: https://i.stack.imgur.com/12EUp.jpg
|iis|networking|iis-10|f5|
SUGGESTION ========== You could try filtering your data set using [filter][1] in your `isDuplicateStatus` function like this: /** * If 'isDuplicateStatus' returns 'true' based on parcel and status, SKIP the appending of the submitted data; otherwise, proceed in appending the data into the sheet. * * If the entries exist in the sheet, the length of the filtered data will be greater than zero. */ function isDuplicateStatus(parcel, status) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var statusSheet = ss.getSheetByName("Statuses"); var dataRange = statusSheet.getRange(3, 1, statusSheet.getLastRow() - 2, statusSheet.getLastColumn()); var data = dataRange.getValues(); //Return 'true' if a duplicate was found, 'false' otherwise return data.filter(cellData => cellData.flat()[0] == parcel && cellData.flat()[1] == status).length > 0; } So, the whole structure of your sample script would look like this: function doPost(e) { var parcel = e.parameter.parcel.toString(); var substation = e.parameter.substation.toString(); var comment = e.parameter.comment.toString(); var status = e.parameter.status.toString(); var date = new Date(); // If 'isDuplicateStatus' returns 'true' based on parcel and status, SKIP the appending of the submitted data; otherwise, proceed in appending the data into the sheet. if (isDuplicateStatus(parcel, status)) { return ContentService.createTextOutput("Duplicate status submission found. Record not added."); } else { addRecord(comment, parcel, date); addToStatuses(parcel, status, date); var htmlOutput = HtmlService.createTemplateFromFile('DependentSelect'); var subs = getDistinctSubstations(); htmlOutput.message = 'Record Added'; htmlOutput.subs = subs; return htmlOutput.evaluate(); } } function isDuplicateStatus(parcel, status) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var statusSheet = ss.getSheetByName("Statuses"); var dataRange = statusSheet.getRange(3, 1, statusSheet.getLastRow() - 2, statusSheet.getLastColumn()); var data = dataRange.getValues(); //Return 'true' if a duplicate was found, 'false' otherwise return data.filter(cellData => cellData.flat()[0] == parcel && cellData.flat()[1] == status).length > 0; } Demo ==== Sample 'Statuses' sheet: > [![enter image description here][2]][2] In this test, I will log the result if duplicate data is found: > [![enter image description here][3]][3] A sample form *(a duplicate attempt will be made to submit)*. > [![enter image description here][4]][4] Log result. *(The sheet will not be appended with data)*. > [![enter image description here][5]][5] [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter [2]: https://i.stack.imgur.com/5O6ba.png [3]: https://i.stack.imgur.com/UqQKt.png [4]: https://i.stack.imgur.com/3VNDx.png [5]: https://i.stack.imgur.com/dZ5kv.png
I can't ssh to my oracle instance I get `Connection refused` although the instance status is "running". So I scanned it with nmap and I found out that the port 22 is closed, to find out later that all 65535 ports are closed.So I go to what they call Ingress Rules to find that 22 tcp port is open with many others so I don't know what happen. I tried to connect it with rustdesk and it tell that the machine is offline, keep in mind that in the oracle cloud dashboard shows that the instance is running. Did the reboot button to many times and still nothing, the little troubleshoot button that they have shows that the machine is fine. [![](https://i.stack.imgur.com/kMJUF.png)](https://i.stack.imgur.com/kMJUF.png) all of this started after installing some tools and `sudo reboot`. before you suggest any thing remember, I can't ssh to it.
Adding on Daniel`s answer. For people using Typescript remember to remove ```@types/connect-redis```. > If you were using @types/connect-redis, remove that package as types are now included in this package. ``` npm remove @types/connect-redis ``` Keeping @types/connect-redis will have you keep the old type specifications giving you a typescript error. Also change the code like so ``` // until v6 import connectRedis from "connect-redis" import session from "express-session" const RedisStore = connectRedis(session) // after v7 import RedisStore from "connect-redis" ``` You no longer need to pass the session to redis ```connectRedis(session)```. Logs: https://github.com/tj/connect-redis/releases/tag/v7.0.0
I am working on a Sails.js application where I need to dynamically set the database URL for my Mongodb database in the datastore configuration at runtime. The idea is to get the database URL with username and password from a common service. The database URL is fetched from an external service (Infisical) during the application's bootstrap phase. However, despite successfully fetching and setting the database URL in the `sails.config.datastores.default.url` , it seems like Sails does not recognize or apply this dynamic configuration, and my application fails to connect to the database with the dynamically set URL. Here's the relevant part of my bootstrap configuration in `config/bootstrap.js`: ```javascript module.exports.bootstrap = async function (done) { console.log('Fetching database URL from Infisical'); try { const dbConfig = await InfisicalService.fetchDatabaseUrl(); console.log('Fetched database URL from Infisical', dbConfig.secret.secretValue); // Update the Sails datastore configuration with the fetched URL sails.config.datastores.default.url = dbConfig.secret.secretValue; // Assumes matching response structure from Infisical return done(); } catch (error) { console.error('Failed to fetch database URL from Infisical', error); return done(error); } }; ``` And my `config/datastores.js` initially looks like this, prepared for dynamic updates: ```javascript module.exports.datastores = { default: { adapter: 'sails-mongo', // url: `mongodb://localhost:27017/mydatabase`, // This is supposed to be set dynamically in bootstrap }, }; ``` **Issue:** When I lift the Sails application,and the URL is datastore.js is wrong or commented, it fails to connect to the database and doesn't recognize the newly set database URL at all, acting as if no URL was set. I have confirmed through logs that the URL is being fetched correctly and that the code to set the `url` in `sails.config.datastores.default.url` is executed. **Questions:** 1. Is there a specific reason why Sails.js might not recognize or apply a dynamically set database URL in the datastore configuration? 2. Are there any known workarounds or correct approaches to dynamically setting the database URL in Sails.js after fetching it at runtime? Any insights or guidance on how to correctly implement this functionality in Sails.js would be greatly appreciated.
If you're hosting an app on localhost and you want a quick way to make your browser *think* you're hosting with a domain, you can edit `/etc/hosts` in linux/mac or `C:\Windows\System32\drivers\etc\hosts` on windows and add a line: `127.0.0.1 dev.local` to the end of your /etc/hosts file. Then, if you were accessing your app on `127.0.0.1:3000`, instead use `dev.local:3000`. That way you don't have to pay for a whole server!
Who even writes code like that? Regardless, int **ppq = &pq ppq + sizeof(ppq) ppq is a pointer to a pointer. Pointer arithmetic works like it does for arrays -- if "x" is a pointer to int, and you have 4 byte ints, then x+1 advances the pointer by 4 so it points to the next int, not just to the next memory address. After all, you'd expect x[1] to give you the next integer as well, not just some random garbage made from 3 bytes of the first integer and 1 byte from the second integer on the data chunk. C-style arrays and pointers are pretty much the same thing, so this applies to pointers as well. A pointer generally has 8 bytes on a 64 bit platform, so your ppq+sizeof() actually advances the pointer "8 pointers ahead", or 8*8 bytes. Then your -1 takes it 1 pointer (aka 8 bytes) back -- so you're advancing by 56 bytes, or 0x38 bytes.
You may find this useful: https://bugs.ruby-lang.org/issues/19403 In my case, I just decided to use ruby 3.2.3
We have to compute percentiles for 100 columns in an data frame. In the example below, the column names that need percentiles are `pctile_columns`. The criteria for receiving percentiles is (1) the column is not `NA`, and (1) the `min_pg` column is `>= 12`. We are struggling to obtain the correct set of percentiles: ## Data + Attempt ``` temp_df = structure(list(group_var = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), min_pg = c(11, 15, 19, 7, 5, 34, 32, 27, 24, 18, 13, 10), stat1 = c(0.35, 0.32, 0.27, NA, NA, 0.42, 0.45, 0.47, 0.33, NA, 0.24, 0.39)), row.names = c(NA, -12L), class = "data.frame") pctile_columns <- c('stat1') library(dplyr) temp_output <- temp_df %>% group_by(group_var) %>% mutate(across(.cols = all_of(pctile_columns), .fns = ~ if_else(is.na(.) | min_pg < 12, as.numeric(NA), rank(., ties.method = "max")), .names = "{.col}__rank")) %>% mutate(across(.cols = all_of(pctile_columns), .fns = ~ if_else(is.na(.) | min_pg < 12, as.numeric(NA), round((rank(., ties.method = "max") - 1) / (n() - 1) * 100, 0)), .names = "{.col}__pctile")) ``` ## Output ``` # Groups: group_var [1] group_var min_pg stat1 stat1__rank stat1__pctile <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 11 0.35 NA NA 2 1 15 0.32 3 18 3 1 19 0.27 2 9 4 1 7 NA NA NA 5 1 5 NA NA NA 6 1 34 0.42 7 55 7 1 32 0.45 8 64 8 1 27 0.47 9 73 9 1 24 0.33 4 27 10 1 18 NA NA NA 11 1 13 0.24 1 0 12 1 10 0.39 NA NA ``` The problem with this output is that the ranks go from 1-9, whereas they should go from 1-7. Even though the `stat1` values with `min_pg < 12` are correctly being assigned an `NA` value, these `stat1` values are still being factored into the `rank` equation when computing the ranks for all of the other rows. The correct set of ranks should be 1-7 in this instance, as there are 7 metrics that meet the criteria for `stat1` to receive a rank/percentile. How can we revise our code to compute ranks/percentiles properly per our criteria?
Unable to set database url dynamically is Sails.js
|javascript|node.js|mongodb|sails.js|sails-mongo|
Check your realtime socket server if it deployed or not. Seems your socket server is not running or your socket path from client is wrong. Then you can config your client for example: const realtimeServerAddress = 'https://gamefront.onrender.com' const opts = { forceNew: true, reconnection: true, path: '/socket.io' //Make sure you config this path correct with your socket server }; const socket = io(realtimeServerAddress, opts); You may need to re-check the server installation by following the doc: https://socket.io/docs/v4/server-installation/