instruction
stringlengths
0
30k
I try to use play feature delivery for an android app for splitting an app with more than 400 Mo size. I didn't manage to link the file "videonamexyz.mp4" from the module "feature_video" The absolute path in the module "C:\Users\xxxxxx\AndroidStudioProjects\namexyz\feature_videos\src\main\res\raw\videonamexyz.mp4" The absolute path in the base "C:\Users\xxxxxx\AndroidStudioProjects\namexyz\app\src\main\res\raw" the problematic part is I want to use the following code propose by "https://developer.android.com/guide/playcore/feature-delivery" ``` val uri = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(context.getPackageName()) // Look up the resources in the application with its splits loaded .appendPath(resources.getResourceTypeName(resId)) .appendPath(String.format("%s:%s", resources.getResourcePackageName(resId), // Look up the dynamic resource in the split namespace. resources.getResourceEntryName(resId) )) .build() ``` but I didn't manage to initialize "ResId" but the code wait for an int not to stringname of the file I try that code " val resId = resources.getIdentifier("videonamexyz", "raw", packageName)" but it doesn't seem to work. the complete kotlin code of the activity is: ``` package com.namexyz.namexyz import android.content.ContentResolver import android.net.Uri import android.os.Build import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.media3.common.MediaItem import androidx.media3.exoplayer.ExoPlayer import androidx.media3.ui.PlayerView import com.google.android.play.core.splitinstall.SplitInstallManager import com.google.android.play.core.splitinstall.SplitInstallManagerFactory import com.google.android.play.core.splitinstall.SplitInstallRequest class videonamexyz2 : AppCompatActivity() { private var player: ExoPlayer? = null private lateinit var splitInstallManager: SplitInstallManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.videonamexyz) splitInstallManager = SplitInstallManagerFactory.create(this) val moduleName = "feature_videos" // Le nom de votre module de fonctionnalités dynamiques if (splitInstallManager.installedModules.contains(moduleName)) { // Le module est déjà installé, initialiser le lecteur directement initializePlayer() } else { // Le module n'est pas installé, demander son installation val request = SplitInstallRequest.newBuilder() .addModule(moduleName) .build() splitInstallManager.startInstall(request) .addOnSuccessListener { // Le module a été installé avec succès, initialiser le lecteur initializePlayer() } .addOnFailureListener { // Échec de l'installation du module, gérer l'erreur } } } private fun initializePlayer() { player = ExoPlayer.Builder(this).build().also { exoPlayer -> val playerView: PlayerView = findViewById(R.id.player_view) playerView.player = exoPlayer val videoResId = resources.getIdentifier("videonamexyz", "raw", packageName) // val uri = if (videoResId != 0) Uri.parse("android.resource://$packageName/$videoResId") else Uri.EMPTY // val uri = if (videoResId != 0) Uri.parse("android.resource://${this.packageName}/${R.raw.videonamexyz}" else Uri.EMPTY // val videoFileName = "videonamexyz.mp4" // val uri = Uri.parse("android.resource://$packageName/") // val filePath = "C:/Users/gilou/AndroidStudioProjects/namexyz/feature_videos/src/main/res/raw/videonamexyz.mp4" // val file = File(filePath) // val uri = Uri.fromFile(file) // val videoFileName = "videonamexyz.mp4" // val uri = Uri.parse("android.resource://$packageName/feature_videos/$videoFileName") //val videoFileName = "videonamexyz.mp4" //val resourceId = resources.getIdentifier(videoFileName, "raw", packageName) //val resourceId = feature_video.R.raw.videonamexyz //val featurePackageName = "votre.package.nom.feature_video" // Remplacez par le nom du package de votre module de fonctionnalité // val resourceId = featurePackageName.R.raw.videonamexyz // val resId = "videonamexyz.mp4" // val uri = Uri.parse("android.resource://$featurePackageName/$resourceId") //val uri = Uri.Builder() // .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) // .authority(this.packageName) // Utilisez packageName pour obtenir le nom du package de l'application // .appendPath("raw") // Spécifiez le dossier des ressources brutes // .appendPath("videonamexyz") // Nom du fichier sans extension // .build() val resId = resources.getIdentifier("videonamexyz", "raw", packageName) val uri = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(this.getPackageName()) // Look up the resources in the application with its splits loaded .appendPath(resources.getResourceTypeName(resId)) .appendPath(String.format("%s:%s", resources.getResourcePackageName(resId), // Look up the dynamic resource in the split namespace. resources.getResourceEntryName(resId) )) .build() val mediaItem = MediaItem.fromUri(uri) exoPlayer.setMediaItem(mediaItem) exoPlayer.prepare() exoPlayer.playWhenReady = true } } override fun onStart() { super.onStart() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { initializePlayer() } } override fun onResume() { super.onResume() if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.N || player == null)) { initializePlayer() } } override fun onPause() { super.onPause() if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { releasePlayer() } } override fun onStop() { super.onStop() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { releasePlayer() } } private fun releasePlayer() { player?.let { it.release() player = null } } } ``` the linking doesn't work, I want the linking works with play feature delivery module Thanks a lot in advance for your answers
problem with linking ressources with play feature delivery android app
|android|kotlin|
null
Image: https://i.stack.imgur.com/3dIm0.png I have a method called Background Blur, but it completely blurs the background of the window, and even if the window is transparent, the corners of the window look bad. How can I ensure that this is applied only to the background of the border? Blur.cs: ``` namespace TestApp { internal enum AccentState { ACCENT_DISABLED = 1, ACCENT_ENABLE_GRADIENT = 0, ACCENT_ENABLE_TRANSPARENTGRADIENT = 2, ACCENT_ENABLE_BLURBEHIND = 3, ACCENT_INVALID_STATE = 4 } [StructLayout(LayoutKind.Sequential)] internal struct AccentPolicy { public AccentState AccentState; public int AccentFlags; public int GradientColor; public int AnimationId; } [StructLayout(LayoutKind.Sequential)] internal struct WindowCompositionAttributeData { public WindowCompositionAttribute Attribute; public IntPtr Data; public int SizeOfData; } internal enum WindowCompositionAttribute { // ... WCA_ACCENT_POLICY = 19 // ... } /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> /// public partial class Blurx { [DllImport("user32.dll")] internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data); internal void EnableBlur(dynamic Element) { IntPtr hwnd; PresentationSource source = PresentationSource.FromVisual(Element); hwnd = source != null ? ((HwndSource)source).Handle : IntPtr.Zero; AccentPolicy accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND }; int accentStructSize = Marshal.SizeOf(accent); var accentPtr = Marshal.AllocHGlobal(accentStructSize); Marshal.StructureToPtr(accent, accentPtr, false); WindowCompositionAttributeData data = new WindowCompositionAttributeData { Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY, SizeOfData = accentStructSize, Data = accentPtr }; SetWindowCompositionAttribute(hwnd, ref data); Marshal.FreeHGlobal(accentPtr); } public void Show(dynamic Element) { EnableBlur(Element); } } } ``` MainWindow.Xaml.cs: ``` namespace TestApp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private Blurx Blur; public MainWindow() { InitializeComponent(); Blur = new Blurx(); } private void Window_Loaded(object sender, RoutedEventArgs e) { Blur.Show(Main); } private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DragMove(); } } } ``` MainWindow.Xaml: ``` <Window x:Class="TestApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Telegram_Group_Media_Scraper" mc:Ignorable="d" WindowStyle="None" Background="Transparent" AllowsTransparency="True" Title="MainWindow" Loaded="Window_Loaded" MouseLeftButtonDown="Window_MouseLeftButtonDown" Height="500" Width="500"> <Border CornerRadius="50" x:Name="Main" Background="#7FDE7AFF"> </Border> </Window> ``` [1]: https://i.stack.imgur.com/QSSft.png
Thats my first post on stackoverflow so i hope i'm doing this properly. if not let me know. i have a problem with the code, but i cant see were. The CS50 check gives me un output error: ** *":( encrypts "This is CS50" as "Cbah ah KH50" using yukfrnlbavmwzteogxhcipjsqd as key Cause output not valid ASCII text"*** ``` Thats the code: #include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]) { if (argc != 2) { printf("Usage: ./substitution\n"); return 1; } string key = argv[1]; if (strlen(key) != 26) { printf("The key must contain 26 characters\n"); return 1; } for(int i = 0; i < strlen(key); i++) { if (!isalpha(key[i])) { printf("Usage: ./substitution\n"); return 1; } } for (int i = 0; i < strlen(key); i++) { for(int j = i + 1; j < strlen(key); j++) { if (toupper(key[i]) == toupper(key[j])) { printf("Usage: substitution key\n"); return 1; } } } string plaintext = get_string("Plaintext: "); printf("ciphertext: "); for(int i = 0; i < strlen(plaintext); i++) { if(isupper(plaintext[i])) { int letter = plaintext[i] - 'A'; printf("%c", key[letter]); } else if(islower(plaintext[i])) { int letter = plaintext[i] - 'a'; printf("%c", tolower(key[letter])); } else if (plaintext[i] == ' ') // Handle spaces { printf(" "); } else { printf("%c",plaintext[i]); } } printf("\n"); return 0; } ```
What's the difference between the Microsoft.ApiManagement/service/portalsettings and Microsoft.ApiManagement/service/portalconfigs
|azure-api-management|azure-bicep|
null
I have a list component to display data fetched from a REST API. I do the fetching in a `useEffect` hook with no dependency array, and set the result into my state. This is my code: ``` import { useEffect, useState } from 'react'; import { fetchAllMedias } from '../service'; import { MediaResponse } from '../types'; import { MediaType } from '../enums'; export default function MediaList() { const [medias, setMedias] = useState<MediaResponse[]>([]); useEffect(() => { const setMediasOnLoad = async () => { try { const fetchedMedias = await fetchAllMedias(); setMedias(fetchedMedias); } catch (error) { console.error('error fetching medias:', error); } }; void setMediasOnLoad(); }, []); const getMediaTypeIcon = (mediaType: MediaType) => { /* returns an Icon component */ }; return ( <div id='media-list'> {medias.map((media) => ( <div key={media.mediaId} className='grid grid-cols-12 border-b-2 first:border-t-2 py-2 gap-4'> <div className='col-span-6 pl-4 flex gap-2'> <div className='flex items-center'>{getMediaTypeIcon(media.mediaType)}</div> <span>{media.title}</span> </div> <div className='border border-violet-200 bg-violet-200 rounded-md font-semibold text-violet-700 px-2'> {media.mediaLanguage.mediaLanguageName} </div> <div className='border border-emerald-200 bg-emerald-200 rounded-md font-semibold text-emerald-700 px-2'> {media.country.countryName} </div> </div> ))} </div> ); } ``` I would like to write a unit test to make sure that the list can be rendered properly, e.g. checking that the title of a movie can be shown. I have provided a mock implementation for the `fetchAllMedias` function, and I have asserted that the function was called. However, the list does not render in the test. This is how I have written the test: ``` import { render, screen, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import * as service from '../service'; import MediaList from '.'; const mockMedias = [ /* mock data */ ]; test('Can render media list', async () => { const mockFetchMedias = vi.spyOn(service, 'fetchAllMedias'); mockFetchMedias.mockReturnValue(new Promise(() => mockMedias)); render(<MediaList />); expect(mockFetchMedias).toHaveBeenCalled(); expect(mockFetchMedias).toReturnWith(new Promise(() => mockMedias)); await waitFor(() => { expect(screen.getByText(/Avengers/)).toBeInTheDocument(); }); }); ``` When running vitest, I get the following error: ``` TestingLibraryElementError: Unable to find an element with the text: /Avengers/. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. Ignored nodes: comments, script, style <body> <div> <div id="media-list" /> </div> </body> ``` I am new to vitest (and frontend testing in general). I have searched for a long time how to fix this issue, but I haven't been able to find others with the same problem. Any help with this will be greatly appreciated.
Undefined reference in MinGW after moving from VC++
|c++|compilation|linker|g++|mingw|
|visual-studio-code|jupyter-notebook|vscode-debugger|debuggervisualizer|
Your sample code shows that you are using the [deprecated](https://developers.google.com/identity/sign-in/web/deprecation-and-sunset) Google Sign-in JavaScript library. You should [migrate](https://developers.google.com/identity/gsi/web/guides/migration) to the new Sign in with Google library. FedCM is only applicable for the new library. Thanks, Herman
I was facing the same issue and this has solved my problem: import daisyui from 'daisyui'; /** @type {import('tailwindcss').Config} */ export default { content: [ "./index.html", "./src/**/*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [daisyui], }
You have some data model like this: public class Model { public string? RootEntity { get; set; } public int Count { get; set; } public List<Item> Results { get; set; } = new(); } public record Item(string Name, string Email, string Function); And you would like to deserialize JSON to this model that has been "compressed" by converting the `"results"` array of objects to an array of array of values, and moving the property names of each `"results"` object to a separate array of strings called `"headers"`. You can do this with a generic converter such as the following: public class ObjectWithResultArrayConverter<TModel> : JsonConverter<TModel> where TModel : class, new() { protected virtual string HeadersName => "header"; protected virtual string ResultsName => "results"; public override TModel? ReadJson(JsonReader reader, Type objectType, TModel? existingValue, bool hasExistingValue, JsonSerializer serializer) { if (!(serializer.ContractResolver.ResolveContract(objectType) is JsonObjectContract contract)) throw new NotImplementedException("Contract is not a JsonObjectContract"); var resultsProperty = contract.Properties.GetClosestMatchProperty(ResultsName); if (resultsProperty == null) throw new NotImplementedException($"No results property {ResultsName} found."); if (reader.MoveToContentAndAssert().TokenType == JsonToken.Null) return null; var jObj = JObject.Load(reader); var headers = jObj.GetValue(HeadersName, StringComparison.OrdinalIgnoreCase).RemoveFromLowestPossibleParent() as JArray; var results = jObj.GetValue(ResultsName, StringComparison.OrdinalIgnoreCase).RemoveFromLowestPossibleParent() as JArray; var value = existingValue ?? (TModel?)contract.DefaultCreator?.Invoke() ?? new TModel(); // Populate TModel properties other than the results serializer.Populate(jObj.CreateReader(), value); // Populate TModel results. if (headers != null && results != null) { var resultsJArray = new JArray(results.Children<JArray>().Select(innerArray => new JObject(headers.Zip(innerArray, (h, i) => new JProperty((string)h!, i))))); var resultsValue = serializer.Deserialize(resultsJArray.CreateReader(), resultsProperty.PropertyType); resultsProperty.ValueProvider!.SetValue(value, resultsValue); } return value; } public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, TModel? value, JsonSerializer serializer) => throw new NotImplementedException(); } public static partial class JsonExtensions { public static JsonReader MoveToContentAndAssert(this JsonReader reader) { ArgumentNullException.ThrowIfNull(reader); if (reader.TokenType == JsonToken.None) // Skip past beginning of stream. reader.ReadAndAssert(); while (reader.TokenType == JsonToken.Comment) // Skip past comments. reader.ReadAndAssert(); return reader; } public static JsonReader ReadAndAssert(this JsonReader reader) { ArgumentNullException.ThrowIfNull(reader); if (!reader.Read()) throw new JsonReaderException("Unexpected end of JSON stream."); return reader; } public static TJToken? RemoveFromLowestPossibleParent<TJToken>(this TJToken? node) where TJToken : JToken { if (node == null) return null; JToken toRemove; var property = node.Parent as JProperty; if (property != null) { // Also detach the node from its immediate containing property -- Remove() does not do this even though it seems like it should toRemove = property; property.Value = null!; } else { toRemove = node; } if (toRemove.Parent != null) toRemove.Remove(); return node; } } And then deserialize by adding the converter to `JsonSerializerSettings.Converters` e.g. as follows: var settings = new JsonSerializerSettings { Converters = { new ObjectWithResultArrayConverter<Model>() }, // Add other settings as required, e.g. ContractResolver = new CamelCasePropertyNamesContractResolver(), }; var model = JsonConvert.DeserializeObject<Model>(jsonString, settings); Notes: - The converter assumes that the object has a `Results` property. This assumption can be changed by overriding `ResultsName`. - Serialization in the same format is not implemented. Your model will be re-serialized using default serialization as follows: ```json { "rootEntity": "function", "count": 2, "results": [ { "name": "12 HOURS", "email": "test@test.com", "function": "testing" }, { "name": "Example", "email": "example@test.com", "function": "second" } ] } ``` Demo fiddle [here](https://dotnetfiddle.net/gpIQMm).
The comment posted by jasonharper is "on point." Unless the work done by `function` is sufficiently CPU-intensive, the time saved by running it in parallel will not make up for the additional overhead incurred by creating child processes. If you are to use multiprocessing, I would simply break up the half-open interval [0, 100_000) into N smaller, non-overlapping half-open intervals where N is the number of CPU processors you have. I have chosen the `f(x)` function (`x ** 2`) such that the value of `x` that satisfies a specific value of `f(x)` (`9801198001`) is skewed so that a serial solution will not find a result (`99001`) until it has checked almost all possible values of `x`. Even so, for such a simple function a multiprocessing solution runs 10 times more slowly than the serial solution. If the `f(x)` function is monotonically increasing or decreasing, then the serial solution can be further sped up using a binary search, which I have also included: ```python from multiprocessing import Pool, cpu_count def f(x): return x ** 2 def search(r): for x in r: if f(x) == 9801198001: return x return None def main(): import time # Parallel processing: pool_size = cpu_count() interval_size = 100_000 // pool_size lower_bound = 0 args = [] for _ in range(pool_size - 1): args.append(range(lower_bound, lower_bound + interval_size)) lower_bound += interval_size # Final interval: args.append(range(lower_bound, 100_000)) t = time.time() with Pool(pool_size) as pool: for result in pool.imap_unordered(search, args): if result is not None: break # An implicit call to pool.terminate() will be called # to terminate any remaining submitted tasks elapsed = time.time() - t print(f'result = {result}, parallel elapsed time = {elapsed}') # Serial processing: t = time.time() result = search(range(100_000)) elapsed = time.time() - t print(f'result = {result}, serial elapsed time = {elapsed}') # Serial processing using a binary search # for monotonically increasing function: t = time.time() lower = 0 upper = 100_000 result = None while lower < upper: x = lower + (upper - lower) // 2 sq = f(x) if sq == 9801198001: result = x break if sq < 9801198001: lower = x + 1 else: upper = x elapsed = time.time() - t print(f'result = {result}, serial binary search elapsed time = {elapsed}') if __name__ == '__main__': main() ``` Prints: ```lang-None result = 99001, parallel elapsed time = 0.24248361587524414 result = 99001, serial elapsed time = 0.029256343841552734 result = 99001, serial binary search elapsed time = 0.0 ```
In React.js with Vitest, how can I test a list that displays data from an API is rendered properly?
|reactjs|typescript|unit-testing|vite|vitest|
Such as is reported in docs: > Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save(). Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on your models, nor does it emit the pre_save or post_save signals (which are a consequence of calling Model.save()). If you want to update a bunch of records for a model that has a custom save() method, loop over them and call save(), like this: for e in Entry.objects.filter(pub_date__year=2010): e.comments_on = False e.save()
EDIT: Made some changes to the code which answered some of my previously asked questions, but now I have new questions I am very new to threads and parallel programming so forgive me if I did things unconventionally. I have two threads, and I am trying to get them to communicate to one another. One of them runs shorter than the other so what I am trying to have is that when the shorter one ends, the longer one will also end. I had partial success with this by passing and scanning a certain object (here I use `sentinel`) to mark the completion of either of the threads, but I have several questions regarding this. Here is the sample code I am running: from threading import Thread import time from queue import Queue sentinel = object() q = Queue() q.put(0) def say_hello(subject, q): print("starting hello") for i in range(5): time.sleep(2) print(f"\nhello {subject}! iter:{i}") data = q.get() if data is sentinel: break else: q.put(data) print(f"from hello: {q.queue}") if i == 4: print("hello finished because of iter") q.put(sentinel) else: print("hello finished because of sentinel from foo") q.put(sentinel) def foo(q): print("starting foo") for j in range(2): time.sleep(1) print(f"\nfoo iter:{j}") data = q.get() if data is sentinel: break else: q.put(data) print(f"from foo: {q.queue}") if j == 1: print("foo finished because of iter") q.put(sentinel) else: print("foo finished because of sentinel from hello") q.put(sentinel) def t(): print("t:0\n") for k in range(1,6): time.sleep(1) print(f"\nt:{k}") def run(): time_thread = Thread(target = t) time_thread.start() hello_thread = Thread(target = say_hello, args = ["lem", q]) hello_thread.start() foo_thread = Thread(target = foo, args = [q]) foo_thread.start() time_thread.join() hello_thread.join() foo_thread.join() print("Done") run() In this case, `foo` should end first and `say_hello` will end following that, and that is what is seen from the output. here is the output: t:0 starting hello starting foo t:1 foo iter:0 from foo: deque([0]) hello lem! iter:0 t:2 foo iter:1 from foo: deque([0]) foo finished because of iter from hello: deque([<object object at 0x000001B9CF908EA0>, 0]) t:3 t:4 hello lem! iter:1 hello finished because of sentinel from foo t:5 Done Now my question is: 1. Is this the right way of doing this? Is there perhaps an easier, cleaner, more conventional way of performing the same thing? 2. The output seems a little erratic such that they change ever so slightly every time I rerun it 3. Are local variables of identical names shared between threads? I was running all my loops with `i` before and it almost seems like it affects all the threads 4. It seems like `say_hello` doesn't quite run at the timestamps I want it to be. At `t:1` there shouldn't be any output from `say_hello` but there is. This is even more peculiar seeing that `from hello: deque...` is only printed after `foo`'s part did. I always suspected that they should print in pairs Any and all input is greatly appreciated. Thanks!
FB API parameter error: The parameter ad_reached_countries is required
|php|laravel|facebook-graph-api|facebook-php-sdk|facebook-ads-api|
Even in 2024 in Angular Material v.17, there is still no ability to get the selected option in `mat-select-trigger`. Also if you use `someMethodWithArrayFindInside()` in your HTML template, you will get in trouble with performance leaks, because you can use methods in the template only under `onPush` strategy. Otherwise, your method will fire whenever CD fires. That's why I suggest using a simple pipe to get current selected option from formControl: ``` <mat-select [formControl]="myFormControl" > <mat-select-trigger> <span>Your customized trigger value</span> {{ (myFormControl.value | selectedOptionPipe: options)?.viewValue || '' }} </mat-select-trigger> ... </mat-select> ``` pipe: ``` @Pipe({ name: 'selectedOptionPipe', }) export class SelectedOptionPipe implements PipeTransform { public transform(value: any, options: CustomOption[]): CustomOption| null { return options.find((v) => v.value === value) || null; } } ```
I'm developing a personal project using Ionic Framework, React, and Supabase DB. I was trying to get my clothing categories from the DB and was using showLoading() and hideLoading() during query execution. The problem is that while fetching Menu the ```hideLoading()``` is not working, and the spinner spins forever. Another thing I noticed is that while using ```useEffect()``` hook to make the fetch function work it activates two times while loading the page, but the second useEffect executes perfectly, and so does the Loading event. The main objective is to build the menu, add an ```OnClick()``` function that changes the father variable to the id of the menu page, and then fetch the categories associated with that page. Here is my code: ``` const fetchMenu = async () => { try { const { data: menuData, error } = await supabase.from('categoria').select('*').eq('pai', 0); if (error) throw error; setMenu(menuData); console.log(menuData); } catch (error: any) { await showToast({ message: error.message || error.error_description, duration: 5000 }); } } const fetchCategories = async (father: number) => { showLoading(); try { const { data: categoriesData, error } = await supabase.from('categoria').select('*').eq('pai', father); if (error) throw error; setCategories(categoriesData); console.log(categoriesData); } catch (error: any) { await showToast({ message: error.message || error.error_description, duration: 5000 }); } hideLoading(); } useEffect(() => { fetchMenu(); }, []); useEffect(() => { if (father != null){ fetchCategories(father); } }, [father]); return ( <IonPage> {/*CABEÇALHO*/} <IonHeader> <IonToolbar> <IonTitle>Fossil Fashion</IonTitle> </IonToolbar> <IonSegment> {menu?.map((menuPage: any) => ( <IonSegmentButton key={menuPage.id} value={Number(menuPage.id)} onClick={(e) => setFather(Number(e.currentTarget.value))}> <IonLabel>{menuPage.nome}</IonLabel> </IonSegmentButton> ))} </IonSegment> </IonHeader> {/*CORPO*/} <IonContent> <IonSearchbar placeholder="Pesquisa"></IonSearchbar> <IonGrid> {categories?.map((category: any) => ( <IonRow key={category.id}> <IonItemGroup> <IonItemDivider> <IonLabel>{category.nome}</IonLabel> </IonItemDivider> </IonItemGroup> </IonRow> ))} </IonGrid> ``` I tried using finally statment, setTimeOut function, but nothing worked.
Discord.js not playing sound
|javascript|discord|discord.js|
Make sure you are using the right project name. The error can be misleading if there is any typo there. It will not tell you "You have no access to this Project ID" but instead show you the same error message as you got. Browsing the resource on the GCloud Console helps to identify the right Project ID.
The binding between the incoming request and method is not working as you expect. Change your method to be more explicit about the incoming parameters. Note that I have defined a `record` to encapsulate the your request parameters. ``` [HttpPost] public IActionResult NextTextFromChoice([FromBody] NextChoiceRequest request) { var nextText = _dataBaseController.UpdateAllInfoWithChoice(request.Id); return Json(nextText); } ``` ``` public record NextChoiceRequest(int Id); ``` The `[FromBody]` isn't entirely necessary here as there is no other binding going on and .NET is smart enough to work out the binding. However, it can be benificial to be explicit regardless.
{"Voters":[{"Id":10008173,"DisplayName":"David Maze"},{"Id":7508700,"DisplayName":"David Buck"},{"Id":9214357,"DisplayName":"Zephyr"}],"SiteSpecificCloseReasonIds":[18]}
Requirements (reverse engineered from the question): - the body of the loop knows which iteration it is for self and all parents - the number of loops is between 0 and at least hundreds - memory allocation isn't a problem, i.e., no attempt at limiting it via compartmentalization is required - manual termination of the current (but not parent) loop is available - loop counters are integers and count upwards from zero - no code is executed, except in the leaf loop - recursion is not compulsory Here's a stab to try to get the idea across, and I will try compiling it upon interest. Again: **it does not work as currently is**. using Counter = int; using State = std::vector<Counter>; using Condition = std::function<bool(const State &)>; using Action = std::function<void(const State &)>; void run(const std::vector<Condition> & conditions, Action action) { std::vector<Counter> state(conditions.size(), 0); unsigned depth{}; while(depth < conditions.size() && ! conditions[conditions.size()-1-depth]) { if(conditions[conditions.size()-1-depth](state)) { action(state); } else { // Go up the stack of loops. while(depth++ < state.size()) { state[state.size()-1-depth] = 0 ++state[state.size()-2-depth]; } } } }
This is the expected behaviour. If you look at `Surface`'s source code below, you can see that it leverages `CompositionLocalProvider` with `LocalContentColor` set to `contentColor` (content color derives from color parameter). This propagates color changes to the composable function proved through the `content` parameter. fun Surface( modifier: Modifier = Modifier, shape: Shape = RectangleShape, color: Color = MaterialTheme.colorScheme.surface, contentColor: Color = contentColorFor(color), tonalElevation: Dp = 0.dp, shadowElevation: Dp = 0.dp, border: BorderStroke? = null, content: @Composable () -> Unit ) { val absoluteElevation = LocalAbsoluteTonalElevation.current + tonalElevation CompositionLocalProvider( LocalContentColor provides contentColor, LocalAbsoluteTonalElevation provides absoluteElevation ) { Box(
|c#|json|list|json.net|
What is happening here? ` case '/front': return MaterialPageRoute(builder: (_) => FrontPage()); ` What does the (_) mean? It should be a build context parameter value? I have searched for Flutter, Dart explanation of the '(_)' usage but cannot find any.
Flutter Dart Syntax
|flutter|dart|syntax|
null
In Visual Studio, if I create a new project using the "Azure Functions" template, the JSON serialization used by that function will be different depending on which version of the template I use. I'm wondering how can I tell which JSON serialization will be used, solely from looking at the code/project. **Minimal complete and viable example** (you need to have the Visual Studio "Azure" workload installed to do this) 1. Create a new project using the "Azure Functions" template, choose ".NET 6.0 (Long term support)" and use the default options for everything else. 2. Replace the `string responseMessage` and `return` lines with this code: ``` csharp var content = new ResponseContent(); return new OkObjectResult(content); ``` 3. Add this class to the project: ``` csharp public class ResponseContent { [Newtonsoft.Json.JsonProperty("CouldBeThis")] public string Example { get; set; } = "MyValue"; } ``` 4. Create a new project using the "Azure Functions" template, choose ".NET 6.0 Isolated (Long Term Support)" and use the default options for everything else. 5. Replace the `return` line with the same code as shown in 2. 6. Add this class to the project: ``` csharp public class ResponseContent { [System.Text.Json.Serialization.JsonPropertyName("ButMaybeThis")] public string Example { get; set; } = "MyValue"; } ``` 7. Run both projects, and use a browser to visit the URL shown for each project. The outputs are, respectively: ``` json { "CouldBeThis": "MyValue" } ``` and ``` json { "ButMaybeThis": "MyValue" } ``` The above is demonstrating that one project is using `Newtonsoft.Json` for Json serialization, but the other is using `System.Text.Json`. But if I had not yet put any attributes on that object, then how could I have determined which JSON serialization will be used, solely from looking at the code/project? **EDIT after request to add the complete function code** Here's the complete in-process function (steps 1-3 above): ``` csharp using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace FunctionAppA { public static class Function1 { [FunctionName("Function1")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string name = req.Query["name"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(requestBody); name = name ?? data?.name; ResponseContent content = new ResponseContent(); return new OkObjectResult(content); } } public class ResponseContent { [Newtonsoft.Json.JsonProperty("CouldBeThis")] public string Example { get; set; } = "MyValue"; } } ``` and here's the complete isolated version ``` csharp using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.Functions.Worker; using Microsoft.Extensions.Logging; namespace FunctionAppI { public class Function1 { private readonly ILogger<Function1> _logger; public Function1(ILogger<Function1> logger) { _logger = logger; } [Function("Function1")] public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req) { _logger.LogInformation("C# HTTP trigger function processed a request."); ResponseContent content = new ResponseContent(); return new OkObjectResult(content); } public class ResponseContent { [System.Text.Json.Serialization.JsonPropertyName("ButMaybeThis")] public string Example { get; set; } = "MyValue"; } } } ```
null
One possible option to *simulate a bit* what you're looking for is to use the [Cartodb Position][1] as a primary basemap, then add a [`WmsTileLayer`][2] (*like the topo layer provided by [NGI][3] service*) : ```py m = folium.Map( location=[51.026, 4.476] zoom_start=9, tiles="cartodb positron", ) folium.WmsTileLayer( url="https://cartoweb.wms.ngi.be/service", fmt="image/png", layers="topo", transparent=True, ).add_to(m) ``` [![enter image description here][4]][4] Alternatively, you can use a localized base layer, i.e a tile from [`openstreetmap-carto-be`][5] that excludes areas outside Belgium: ```py m = folium.Map( location=[51.026, 4.476], zoom_start=9, tiles="https://tile.openstreetmap.be/osmbe/{z}/{x}/{y}.png", attr='&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, Tiles courtesy of <a href="https://geo6.be/">GEO-6</a>', ) ``` [![enter image description here][6]][6] ***NB** : Both approaches are indepenent of the extent/bounds of your data (polygons, points, ..)*. Used input : [BELGIUM_-_Municipalities.geojson][7] ```py import json import folium def style_function(x): return { "fillColor": "cyan", "fillOpacity": 0.3, "color": "black", "opacity": 0.7, "weight": 1, } with open("BELGIUM_-_Municipalities.geojson", "r") as f: data = json.load(f) folium.GeoJson( data, name="Municipalities", style_function=style_function, ).add_to(m) ``` [1]: https://carto.com/blog/getting-to-know-positron-and-dark-matter [2]: https://python-visualization.github.io/folium/latest/reference.html#folium.raster_layers.WmsTileLayer [3]: https://www.ngi.be/website/fr/ [4]: https://i.stack.imgur.com/Ypkns.jpg [5]: https://github.com/osmbe/openstreetmap-carto-be [6]: https://i.stack.imgur.com/uqXrt.png [7]: https://hub.arcgis.com/datasets/9589d9e5e5904f1ea8d245b54f51b4fd/explore?location=50.483908%2C4.476903%2C7.73
Im making a simple plant growing game in the CMU CS acedemy thing and I can't figure out how to make this work. If I click up it makes it work as usual one time but does nothing whenever i click up again. Code: ``` app.background = 'skyBlue' import time def increaseHeight(height): Rect(225, 0, 120, 250, fill='skyBlue') planta = Rect(250, 150, 10, 100, fill='forestGreen') planta.height += height planta.centerY -= height plantb = Rect(270, 150 - height, 10, 100 + height, fill='forestGreen'), plantc = Rect(290, 150 - height, 10, 100 + height, fill='forestGreen'), plantd = Rect(310, 150 - height, 10, 100 + height, fill='forestGreen'), plante = Rect(330, 150 - height, 10, 100 + height, fill='forestGreen') def Reset(): Rect(225, 0, 120, 250, fill='skyBlue') planta = Rect(250, 240, 10, 10, fill='forestGreen'), plantb = Rect(270, 240, 10, 10, fill='forestGreen'), plantc = Rect(290, 240, 10, 10, fill='forestGreen'), plantd = Rect(310, 240, 10, 10, fill='forestGreen'), plante = Rect(330, 240, 10, 10, fill='forestGreen') def decreaseWater(height): Rect(0, 145, 80, 105, fill=gradient('dimGrey', 'silver', start = 'bottom-left')) Rect(5, 150, 70, 95, fill='grey') Rect(5, 150 + height, 70, 95 - height, fill=gradient('lightBlue', 'teal', start = 'top-right')) def Start(): planta = Rect(250, 150, 10, 100, fill='forestGreen') plantb = Rect(270, 150, 10, 100, fill='forestGreen') plantc = Rect(290, 150, 10, 100, fill='forestGreen') plantd = Rect(310, 150, 10, 100, fill='forestGreen') plante = Rect(330, 150, 10, 100, fill='forestGreen') def onKeyPress(key): print(key) if key == 'up': increaseHeight(5) decreaseWater(2) Rect(0, 250, 400, 150, fill = 'saddleBrown') Circle(100, 60, 30, fill='yellow') Circle(100, 60, 40, fill='yellow', opacity = 50) Circle(100, 60, 50, fill='yellow', opacity = 25) Circle(100, 60, 75, fill='yellow', opacity = 10) waterTank = Rect(0, 145, 80, 105, fill=gradient('dimGrey', 'silver', start = 'bottom-left')) Rect(5, 150, 70, 95, fill='grey') Rect(5, 150, 70, 95, fill=gradient('lightBlue', 'teal', start = 'top-right')) Label('Press UpArrow to grow', 200, 375, fill='white', font='cinzel', size = 15) Start() ``` Rescources - https://academy.cs.cmu.edu/docs I tried using global variables but I couldn't edit them
I have written this code to fine-tune gpt2 on a dataset imported from HuggingFace: from transformers import Trainer, TrainingArguments, GPT2LMHeadModel, GPT2Tokenizer model_name = "gpt2" tokenizer = GPT2Tokenizer.from_pretrained(model_name) model = GPT2LMHeadModel.from_pretrained(model_name) training_args = TrainingArguments( output_dir="./output", num_train_epochs=3, per_device_train_batch_size=8, logging_dir="./logs", ) trainer = Trainer( model=model, args=training_args, train_dataset=train, tokenizer=tokenizer, ) trainer.train()` When I run this, I am getting KeyError:9198 though 9198 is included in dataframe of my dataset (I checked it twice) This is the error I have encountered: KeyError Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3801 try: -> 3802 return self._engine.get_loc(casted_key) 3803 except KeyError as err: 11 frames pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 9198 The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3802 return self._engine.get_loc(casted_key) 3803 except KeyError as err: -> 3804 raise KeyError(key) from err 3805 except TypeError: 3806 # If we have a listlike key, _check_indexing_error will raise KeyError: 9198
Can't resolve KeyError in Pandas
|machine-learning|gpt-2|fine-tuning|
null
I'm experimenting with running Gradient Descent (GD) on polynomials of some low degree - say 3 - with *n* variables, on a domain constrained by a hypercube [-1,1]^*n*. I want to compare the termination point of GD with the actual KKT point calculated with Sympy. For example, I have a Sympy expression with 3 variables a, b and c (that is *n*=3) like this: 0.2*a**3 - 0.1*a**2*b - 0.9*a**2*c + 0.5*a**2 - 0.1*a*b**2 - 0.4*a*b*c + 0.5*a*b - 0.6*a*c**2 - 0.5*a*c - 0.6*a - 0.1*b**3 + 0.4*b**2*c - 0.4*b**2 + 0.7*b*c**2 - 0.4*b*c + 0.9*b + 0.09*c**3 - 0.6*c**2 + 0.4*c + 0.22 What is the best, quickest way of finding all KKT points for this expressions with the constraints: -1 <= a <= 1 -1 <= b <= 1 -1 <= c <= 1 (ideally the search would be limited only to the vicinity of the GD termination point to save computation time but I'm not sure how to do that rigorously)
Best way of finding KKT points for a Sympy polynomial
|python|sympy|mathematical-optimization|symbolic-math|gradient-descent|
Your main method looks fine. 1) Probably your .class file does not correspond to your .java file. I would try to clean up my project (if I was using an IDE and getting this). That is: delete the .class file, regenerate it from the .java file. 2) It seems you're not running ImageFile but some other class, even though you think you're running ImageFile. Check what your IDE is running behind the scenes.
null
I have an HTML table with the following structure: ``` <table> <thead>..</thead> <tbody> <tr> <td>some</td> <td>content</td> <td>etc</td> </tr> <tr class="certain"> <td><div class="that-one"></div>some</td> <td>content</td> <td>etc</td> </tr> several other rows... <tbody> </table> ``` And I am trying to figure out what to do with the `<div class="that-one">` (or any other element, if needed) inside the table so it can be painted outside the table. I have tried the negative left property, ```transform: translateX(-20px)```, and ```overflow: visible```. I know that there is something different with rendering HTML tables. I cannot change the structure of the table just can add whatever element inside. Finding: both negative left property and ```transform: translateX(-20px)``` work in Firefox but don't work in Chrome (behaves like ```overflow: hidden``). Have some Javascript workaround on my mind, but would rather stay without it. Also, I don't want it as CSS pseudoelement, because there will be some click event binded.
null
> My problem is that when it launches the first new terminal that new terminal becomes the "active" terminal and it does not come back to the original script to finish the loop and launch the other terminals. Is there a way to release the new terminal and finish working through the loop to launch the other terminals? Sure, just background the process in your loop by adding a `&` after the command: ```sh gnome-terminal -q \ --geometry="105x8" \ --window \ --title "Title 1" \ --command="command_to_run_in_new_terminal" \ --tab \ --title "Tab 2" \ --command="command_to_run_in_second_tab" & ``` *(Note that on Unity in Ubuntu 23.04, this isn't necessary, as the `gnome-terminal` command launches a new terminal window via a `gnome-terminal-server` daemon process and exits.)* ## Window Managers ... how do they work? Becoming the "active terminal" is actually just an illusion created by your window manager. The terminal window pops over the window you have selected. There's probably a setting in your window manager to NOT focus new windows. Therefore, fixing this user experience involves either a) configuring your window manager to not let new window steal focus, or b) start `gnome-terminal` minimized. Any solution I found to the problem of "Start `gnome-terminal` minimized" seems to depend on a given window manager having support for this. The [solution for X11 is convoluted enough, involving `xdotool`](https://askubuntu.com/questions/488356/how-can-i-start-a-script-in-a-minimised-gnome-terminal). No Wayland solution presents itself. ## Fixing the `for` loop Okay, let's go back to the original question where your script wasn't starting more than one process. It *sounds* like `gnome-terminal` is hanging open after the command finishes. That's not good. If you use the syntax `gnome-terminal -- sh -c 'MYCOMMAND'` it will close the terminal after the command finishes. For example: ```sh COMMANDS=( 'ls; sleep 5' 'ls; sleep 5' 'ls; sleep 5' 'ls; sleep 5' 'echo "hello world"; sleep 5' 'ls; sleep 5' 'echo "hello world"; sleep 5' ) for cmd in "${COMMANDS[@]}"; do gnome-terminal -q --geometry="105x8" -- sh -c "$cmd" & done ``` But that's no good, it launches everything at once! What if there are hundreds of jobs, that'll max out your CPU and more likely your RAM. ## Not overloading your computer: Re-writing the `for` loop using GNU Parallel For your main loop, you can leverage GNU Parallel to spawn multiple terminals as well. With `-j3` it'll only launch 3 the terminals at once and wait for one to exit before starting another one. ```sh COMMANDS=( 'ls; sleep 5' 'ls; sleep 5' 'ls; sleep 5' 'ls; sleep 5' 'echo "hello world"; sleep 5' 'ls; sleep 5' 'echo "hello world"; sleep 5' ) parallel -j3 gnome-terminal -q --geometry="105x8" --wait -- sh -c ::: "${COMMANDS[@]}" # -j3 = launch 3 jobs at once ``` Adding `--wait` causes the terminal process to NOT fork to the background. If it forked, it would just launch everything at the same time, negating our attempt at job control.
{"Voters":[{"Id":3074564,"DisplayName":"Mofi"},{"Id":6464308,"DisplayName":"Laurenz Albe"},{"Id":9214357,"DisplayName":"Zephyr"}],"SiteSpecificCloseReasonIds":[18]}
*Linux 6.1. PHP 8.2.7. KDE Plasma 5.x. X11.* I've long had a very annoying issue with my PHP CLI scripts which keeps coming up and causing problems. I've now finally made a minimal test case and hope that this can be solved once and for all. If you do these three things: 1. Register a handler function for the `SIGHUP` signal (which is left empty/does nothing)... 2. Check for input from the user (`fgets(STDIN);`)... 3. Run the PHP CLI script like `xterm -e php test.php` (which is how I have to call it, for complex reasons unrelated to this problem)... ... then *the resulting XTerm terminal emulator window will not be possible to close by clicking the "X" in the top-right corner*! Nothing will happen if you click it. As soon as you comment or remove the line which registers the signal handler, it will let you close the window when run like above. Test case ========= * `xterm -e php 1.php` = the "X" **CANNOT** be clicked to make the XTerm window close. * `xterm -e php 2.php` = the "X" **CAN** be clicked to make the XTerm window close. `1.php`: ``` <?php function dummy_handler() { /* deliberately left empty */ } pcntl_signal(SIGHUP, 'dummy_handler'); $input = fgets(STDIN); ``` `2.php`: ``` <?php function dummy_handler() { /* deliberately left empty */ } $input = fgets(STDIN); ``` What can I do to bypass this? To make it clear, I need to register the handler function, I need to call `xterm` with `-e`, and I need to "wait for input". I should also point out that I've tried those classic `setsid` and `nohup` Linux tricks without any luck. I don't understand what exactly causes this. Please don't tell me to "just remember to use Ctrl + C" or something; I need to be able to close certain PHP CLI scripts before their natural life is over, by clicking the "X", and I need to be able to have some cleanup routines called before it closes. (The handler function is empty in this minimal example just to demonstrate that it still happens without me doing anything weird/complex.) It probably happens regardless of the desktop environment and terminal emulator, but I'm stuck with KDE Plasma and XTerm on Linux and that's what I need this to work on. Update: Using `exit(1);` in the handler function doesn't make a difference.
I am trying to write a small jit compiler. For that, I need to somehow load new code into memory and then execute it. Given the output of the compiler for a function that simply adds the 2nd and 3rd argument ```{asm} push %rbp mov %rsp, %rbp sub $44, %rsp movl %esi, -4(%rbp) movl %edx, -8(%rbp) # return a+b movl -4(%rbp), %esi movl -8(%rbp), %r11d addl %r11d, %esi movl %esi, %eax leave ret ``` I save my compiler output to a file, called `subfunction.S` and translate it via `as -o subfunction.o subfunction.S`. I then try to load it into memory and execute it as follows: ```{c} #include <stdio.h> #include <sys/mman.h> typedef int (*fun_pointer)(int, int, int); int main(){ FILE *f = fopen("subfunction.o", "r"); if (f) { fseek(f, 0, SEEK_END); int length = ftell(f); fseek(f, 0, SEEK_SET); char *memory = mmap(NULL, // address length+10, // size PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, // fd (not used here) 0); // offset (not used here) if (memory) { fread(memory, 1, length, f); fclose(f); fun_pointer function = memory; int res = function(0,1,2); printf("RESULT: %d", res); fflush(stdout); } } } ``` Note that my assembly code contains no external references (with regard to linking). This unfortunately does not work (=> Segfault)(*). My guess is, that my compilation step using `as` is not appropriate to create binary data that can be executed from memory. I also tried using `ld` (with tmp.o as input) and load the output of it into memory. Again with no success. (*) Actually changing `sub $44, %rsp` to `sub 44, %rsp`, which makes no sense, as 44 is interpreted as memory location causes no segfault (but also no return value). This leads me to think that it might be some kind of alignment issue?
CS50 - C -problemset 2 - substitution - output not valid ASCII text
|cs50|substitution|
null
I using the following Antlr4 PLSQL grammar files: https://github.com/antlr/grammars-v4/tree/master/sql/plsql. From here I downloaded as follows: ``` wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/Python3/PlSqlLexerBase.py wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/Python3/PlSqlParserBase.py wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/PlSqlLexer.g4 wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/PlSqlParser.g4 mv PlSql*g4 grammars wget https://www.antlr.org/download/antlr-4.13.1-complete.jar mv antlr-4.13.1-complete.jar lib ``` Giving me : ``` ├── lib │   ├── antlr-4.13.1-complete.jar ├── grammars1 │   ├── PlSqlLexer.g4 │   └── PlSqlParser.g4 ├── PlSqlLexer.g4 ├── PlSqlParser.py ``` When I then run: ``` java -jar ./lib/antlr-4.9.3-complete.jar -Dlanguage=Python3 grammars/*g4 ``` I get the following generated in `grammars`: ``` grammars-v4-master PlSqlLexer.interp PlSqlParserBase.py PlSqlParserListener.py __pycache__ master.zip PlSqlLexer.py PlSqlParser.g4 PlSqlParser.py runPLSQL.py PlSqlLexer.g4 PlSqlLexer.tokens PlSqlParser.interp PlSqlParser.tokens ``` I then create the runPLSQL.py Python script : ``` cd grammars python3 runPLSQL.py ../../plsql/test.sql ``` But this errored with: ``` import pandas Traceback (most recent call last): File "/home/me/try2/grammars/runPLSQL.py", line 11, in <module> from PlSqlParserListener import PlSqlParserListener File "/home/me/try2/grammars/PlSqlParserListener.py", line 6, in <module> from PlSqlParser import PlSqlParser File "/home/me/try2/grammars/PlSqlParser.py", line 14, in <module> from PlSqlParserBase import PlSqlParserBase File "/home/me/try2/grammars/PlSqlParserBase.py", line 1, in <module> {"payload":{"allShortcutsEnabled":false,"fileTree":{"sql/plsql/Python3":{"items":[{"name":"PlSqlLexerBase.py","path":"sql/plsql/Python3/PlSqlLexerBase.py","contentType":"file"} NameError: name 'false' is not defined. Did you mean: 'False'? ``` I had to edit the `PlSqlLexerBase.py` file as below to overcome this and similar errors: 1. Replace `:false` with `:False` 2. Replace `:true` with `:True` 3. Replace `:null` with `:None` But now I get this: ``` import pandas Traceback (most recent call last): File "/home/me/try2/grammars/runPLSQL.py", line 11, in <module> from PlSqlParserListener import PlSqlParserListener File "/home/me/try2/grammars/PlSqlParserListener.py", line 6, in <module> from PlSqlParser import PlSqlParser File "/home/me/try2/grammars/PlSqlParser.py", line 14, in <module> from PlSqlParserBase import PlSqlParserBase ImportError: cannot import name 'PlSqlParserBase' from 'PlSqlParserBase' (/home/me/try2/grammars/PlSqlParserBase.py) ``` The top of the `runPLSQL.py` script is: ``` import os import pandas from antlr4 import InputStream, ParseTreeWalker from antlr4.CommonTokenStream import CommonTokenStream from pandas import DataFrame #from PlSql.grammar.PlSqlListener import PlSqlListener #from PlSql.grammar.PlSqlLexer import PlSqlLexer #from PlSql.grammar.PlSqlParser import PlSqlParser from PlSqlParserListener import PlSqlParserListener from PlSqlLexer import PlSqlLexer from PlSqlParser import PlSqlParser from tabulate import tabulate class SQLParser(PlSqlListener): ```
Load function written in amd64 assembly into memory and call it
|c|assembly|compiler-construction|jit|
{"Voters":[{"Id":6243352,"DisplayName":"ggorlen"},{"Id":20292589,"DisplayName":"Yaroslavm"},{"Id":9214357,"DisplayName":"Zephyr"}],"SiteSpecificCloseReasonIds":[13]}
This is one application to this question. For example, find the bar cutting combinations of 3 bar lengths. So that the waste should not be longer than 1' (2.5 cm) after cutting in the 20' (50 cm) length rebar. So, I used three nested loops, because there are three bar cuts. If I have 50 bar cuts, then I will use 50 nested loops. So, this is how can we rewrite it using recursion. [Relative question in c++][1] [![Code and correct answer for the given data][2]][2] [1]: https://stackoverflow.com/questions/69089153/something-better-than-many-nested-for-loops [2]: https://i.stack.imgur.com/7uwtO.png
With one Subscriber, an async list showing all items from Observable, what is the most efficient way to temporarily filter results based on user provided search criteria as a `string`? The component imports `TokenService` and the template subscribes to `tokens`: `tokenService.tokens | async` ```javascript // ./token.service.ts @Injectable({ providedIn: 'root' }) export class TokenService { private tokens$ = new BehaviorSubject<Token[]>([]); readonly tokens = this.tokens$.asObservable(); constructor() { this.getTokens(); } filterTokens(q?: string) { ... } ... } ``` The output should display a list of items with names loosely matching the provided search criteria. Provided the letter `w` (lower case) as input "Work" and "New" would display from a set of `['Work', 'Test', 'New']`. Passing the newly filtered values to the `BehaviorSubject` obviously makes the values unrecoverable unless cached elsewhere. ```javascript filterTokens(q?: string): void { this.tokens$.next( this.tokens$.getValue().filter(t => t.issuer.toLowerCase().includes(q.toLowerCase())) ); } ``` The following method returns "Work" and "New" when passed `tokenService.filterTokens('r') | async`: ```javascript filterTokens(q?: string): Observable<Token[]> { return this.tokens.pipe( map(tt => tt.filter(t => t.issuer.toLowerCase().includes(q.toLowerCase()))) ); } ``` This however, is not dynamic based on user input.
How should I filter Observables the "Right Way" with RxJs in Angular 17?
|javascript|angular|ionic-framework|
null
I am using django framework and i will get the value error while i use razorpay payment gateway [enter image description here](https://i.stack.imgur.com/OOUbg.png) **This iS models ** ``` class Payment(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) amount = models.FloatField() razorpay_order_id = models.CharField(max_length=100,blank = True , null = True) razorpay_payment_status = models.CharField(max_length=100,blank = True , null = True) razorpay_payment_id = models.CharField(max_length=100,blank = True , null = True) paid = models.BooleanField(default = False) class OrderPlaced(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) #cid = models.ForeignKey(Payment,on_delete=models.CASCADE) customer = models.ForeignKey(Customer,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) ordered_date = models.DateField(auto_now_add = True) status = models.CharField(max_length = 50,choices = STATUS_CHOICES,default = 'Pending') payment = models.ForeignKey(Payment, on_delete=models.CASCADE,default ="") @property def total_cost(self): return self.quantity*self.product.discounted_price ``` **This is html code** ``` {% extends 'app/base.html' %} {% load static %} {% block title %} Buy Now {% endblock %} {% block main-content %} <div class="container"> {% if messages %} {% for msg in messages %} <div class="alert alert-denger" role="alert"> {{msg}} </div> {% endfor %} {% endif %} <div class="row mt-5"> <div class="col-sm-6"> <h4> Order Summery </h4> <hr> {% for item in cart_items %} <div class="card mb-2"> <div class="card-body"> <h5> Product: {{item.product.title}}</h5> <p>Quantity: {{item.quantity}} </p> <p class="fw-bold">Price: {{item.product.discounted_price}}</p> </div> </div> {% endfor %} <p class="fw-bold"> Total Cost + Rs. 40 = {{totalamount}}</p> <small>Term and Conditions: Lorem ipsum dolor sit amet consectetur.</small> </div> <div class="col-sm-4 offset-sm-1"> <h4>Select Shipping Address </h4> <hr> <form method="post" id="myform"> {% csrf_token %} {% for ad in add %} <div class="card"> <div class="card-body"> <h5>{{ad.name}}</h5> <p> Mobile No.: {{ad.mobile}}</p> <p>{{ad.locality}} {{ad.city}} {{ad.state}} - {{ad.zipcode}}</p> </div> </div> <div class="form-check mt-2 mb-5"> <input class="form-check-input" type="radio" name="custid" id="custadd{{forloop.counter}}" value="{{ad.id}}"> <label class="form-check-label fw-bold" for="custadd{{forloop.counter}}"> Address:{{forloop.counter}}</label> </div> {% endfor %} <div class="form-check mb-3"> <label for="totanount" class="form-label"> Total Amount</label> <input type="number" class="form-control" name="totamount" value={{totalamount}} readonly> </div> <div class="text-end"> {% comment "" %} <button type="submit" class="btn btn-warning mt-3 px-5 fw-bold"> Continue </button>{% endcomment %} <!--<div id="paypal-button-container"> </div>--> <button id="rzp-button1" type="submit" class="btn btn-warning mt-3 ox-5 fw-bold" > Payment </button> <br> <br> <br> </div> </form> </div> </div> </div> {% endblock main-content %} {% block payment-gateway %} <script> var options = { "key": "rzp_test_Xjdfwh2QHqbpcz", "amount": "50000", "currency": "INR", "name": "Raju General Shop", "description": "Get Best And Fresh Products", "order_id": "{{order_id}}", "handler": function (response){ console.log("Success") var form = document.getElementById("myform"); alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature); window.location.href = ' http://127.0.0.1:8000/paymentdone?order_id=${response.razorpay_order_id}&payment_id=${response.razorpay_payment_id}&cust_id=${form.elements["custid"].value}' }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed', function (response){ alert(response.error.code); alert(response.error.description); alert(response.error.source); alert(response.error.step); alert(response.error.reason); alert(response.error.metadata.order_id); alert(response.error.metadata.payment_id); }); document.getElementById('rzp-button1').onclick = function(e){ rzp1.open(); e.preventDefault(); } </script> {% endblock payment-gateway %} ``` **This is view functions** ``` class checkout(View): def get(self,request): user = request.user add = Customer.objects.filter(user=user) cart_items = Cart.objects.filter(user=user) amount=0 for p in cart_items: value = p.quantity*p.product.discounted_price amount = amount + value totalamount = amount + 40 razoramount = int(totalamount * 100) client = razorpay.Client(auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) data = { "amount": razoramount, "currency": "INR", "receipt": "order_rcptid_12", 'payment_capture': 1 } payment_response = client.order.create(data=data) print(payment_response) order_id = payment_response['id'] order_status = payment_response['status'] print(order_id) if order_status == 'created': payment = Payment( user=user, amount=totalamount, razorpay_order_id=order_id, razorpay_payment_status=order_status ) payment.save() return render(request,'app/checkout.html',locals()) def payment_done(request): order_id = request.GET.get('order_id') payment_id = request.GET.get('payment_id') cust_id = str(request.GET.get('cust_id')) user = request.user print("pid=",payment_id,"oid=",order_id) #Payment.objects.create(razorpay_order_id=order_id, razorpay_payment_id=payment_id, cust_id=cust_id) customer = Customer.objects.get(id=cust_id) payment = Payment.objects.get(razorpay_order_id=order_id) payment.paid = True payment.razorpay_payment_id = payment_id cart = Cart.objects.filter(user=user) payment.save() for c in cart: OrderPlaced(user=user,customer=customer,product=c.product,quantity=c.quantity,payment=payment).save() c.delete() return redirect('orders') ``` i want to gwt order id cust_id payment id etc from get methode and store in database after complete payment Please help me solve this error
i am geting value error while get cust id value from passing query in link which is in checkout file . I am using razorpay payment-gateway
|python|django|payment-gateway|
null
for me my docer server was running on 0.0.0.0 so used that instead of the localhost.
Your output: ```lang-none this is thread 1 this is thread 2 main exists thread 2 exists thread 1 exists thread 1 exists ``` Before I see that *"it prints "thread 1 exists" twice."*, I see that it prints after "main exists": This behavior can lead to unpredictable results. -- First, you should array your code: ```cpp #include <thread> #include <iostream> #include <future> #include <syncstream> void log(const char* str) { std::osyncstream ss(std::cout); ss << str << std::endl; } void worker1(std::future<int> fut) { log("this is thread 1"); fut.get(); log("thread 1 exists"); } void worker2(std::promise<int> prom) { log("this is thread 2"); prom.set_value(10); log("thread 2 exits"); } int main() { std::promise<int> prom; std::future<int> fut = prom.get_future(); // Fire the 2 threads: std::thread t1(worker1, std::move(fut)); std::thread t2(worker2, std::move(prom)); t1.join(); t2.join(); log("main exits"); } ``` Key points: * CRITICAL: Replace the `while` loop and `detach()` with `join()` in the `main()` to ensure that the main thread waits for all child threads to finish before exiting. * Dilute the `#include` lines to include only what's necessary - For better practice. * Remove unused variables - For better practice. * Remove the unused `using namespace` directive - For better practice. * In addition, I would also replace the `printf()` calls with `std::osyncstream`. [Demo][1] Now, the output is: ```lang-none this is thread 1 this is thread 2 thread 2 exits thread 1 exits main exits ``` -- *"The detach used but not join here is the requirements from test. I cannot change that."* - In that case: ```cpp #include <thread> #include <iostream> #include <future> #include <syncstream> #include <mutex> #include <condition_variable> std::mutex mtx{}; std::condition_variable cv{}; uint8_t workers_finished{ 0 }; // Counter for finished workers void log(const char* str) { std::osyncstream ss(std::cout); ss << str << std::endl; } void worker1(std::future<int> fut) { log("this is thread 1"); fut.get(); log("thread 1 exits"); std::lock_guard lock(mtx); ++workers_finished; cv.notify_one(); // Signal main thread } void worker2(std::promise<int> prom) { log("this is thread 2"); prom.set_value(10); log("thread 2 exits"); std::lock_guard lock(mtx); ++workers_finished; cv.notify_one(); // Signal main thread } int main() { std::promise<int> prom; std::future<int> fut = prom.get_future(); // Fire the 2 threads: std::thread t1(worker1, std::move(fut)); std::thread t2(worker2, std::move(prom)); t1.detach(); t2.detach(); { std::unique_lock lock(mtx); while (workers_finished < 2) { cv.wait(lock); // Wait until notified (or spurious wakeup) } } log("main exits"); } ``` [Demo][1] Now, the output is: (The same) ```lang-none this is thread 1 this is thread 2 thread 2 exits thread 1 exits main exits ``` [1]: https://onlinegdb.com/UboKp_Bpf
I have a elastic search query that looks like this: _search{ "aggs": { "bodyTypeMinPrice": { "terms": { "field": "specification.bodyType" }, "aggs": { "highest_price": { "max": { "field": "specification.price.dealerGrossPrice" } } } } } } Where I want the minimum price (specification.price.dealerGrossPrice) per bodytype (specification.bodyType). How can i convert this query to a AggregationDictionary? I am using nest 7.17. This is what I have so far, but I have no idea how to put them together: var aggregationDictionary = new AggregationDictionary(); var aggregationContainer= new AggregationContainer(); var term = new Term() { Field = new Field("specification.bodyType") }; var minAgg = new MinAggregation("minDealerGrossPrice", "specification.price.dealerGrossPrice");
Convert elastic search query to nest AggregationDictionary
|c#|elasticsearch|nest|
null
[MacVim](https://macvim.org/) is a macOS application with a file open dialog that calls [NSOpenPanel](https://developer.apple.com/documentation/appkit/nsopenpanel) with a simple view to show hidden files (see [MMAppController.m's fileOpen method](https://github.com/macvim-dev/macvim/blob/master/src/MacVim/MMAppController.m) and [Miscellaneous.m's showHiddenFilesView method](https://github.com/macvim-dev/macvim/blob/master/src/MacVim/Miscellaneous.m). When I open files with MacVim, I can use ⌘A to select all files. But I don't see what it's doing that's any different than what I do below, which does *not* allow me to use ⌘A to select all files. NSOpenPanel *panel = [NSOpenPanel openPanel]; [panel setCanChooseFiles:YES]; [panel setCanChooseDirectories:YES]; [panel setAllowsMultipleSelection:YES]; if ([panel runModal] == NSModalResponseOK) { for ( NSURL* URL in [panel URLs] ) { NSLog( @"%@", [URL path] ); } } else { NSLog( @"ok button not pressed"); } The docs for `NSOpenPanel` and [NSSavePanel](https://developer.apple.com/documentation/appkit/nssavepanel), which `NSOpenPanel` inherits don't make any mention of key bindings or other booleans that I might set. The only thing that I saw that might be useful is a custom view but MacVim doesn't appear to be doing anything with `NSView` that relates.
How can I tell NSOpenPanel to respect the ⌘A (select all items) key binding?
|objective-c|cocoa|macvim|
I have the following table that has 8 columns of IDs that I will be joining to my DIM table. The table has 100K+ rows of IDs. Is there a more efficient way to join the IDs to my DIM table rather than using my code provided? | ID1 | ID2 | ID3 | ID4 | ... | ID8 | |----: |------:| -----:|-----:|-----:| -----:| | 123 | 456 | 789 | 658 | ... | 987 | SELECT F.ID1, D1.NAME, F.ID2, D2.NAME, F.ID3, D3.NAME, etc. FROM FACT_TABLE AS F LEFT JOIN DIM AS D1 ON D1.ID = F.ID1 LEFT JOIN DIM AS D2 ON D2.ID = F.ID2 LEFT JOIN DIM AS D3 ON D3.ID = F.ID3 LEFT JOIN DIM AS D4 ON D4.ID = F.ID4 ... LEFT JOIN DIM AS D8 ON D8.ID = F.ID8
Antlr4 python runtime error after generating from grammar
|python|antlr4|
What you are looking for is some global state, that is maintained across multiple pages. For this example I will use react's context API, if this does not fit your use-case you can find some other state management libraries. First you would need to crate a global context, with one global state in your form provider ```javascript // FormProvider.tsx import { createContext, useContext, useState } from 'react'; const FormContext = createContext(); // Exported to be used in other components export const useFormContext = () => useContext(FormContext); export const FormProvider = ({ children }) => { const [formData, setFormData] = useState({}); return ( <FormContext.Provider value={{ formData, setFormData }}> {children} </FormContext.Provider> ); }; ``` Now you need to wrap your app with the `FormProvider` ```javascript // You are already doing this part //_app.tsx return ( <div> <FormProvider> <Component {...pageProps} /> </FormProvider> </div> ) ``` Now you can use it like this. Keep in mind you will be updating the global state of the form which will change on all of your pages. ```javascript // In your form component import { useForm } from 'react-hook-form'; import { useFormContext } from '../path/to/formContext'; const MyFormComponent = () => { const { formData, setFormData } = useFormContext(); const { register, handleSubmit } = useForm({ defaultValues: formData, resolver: zodResolver(MyFormSchema), }); const onSubmit = (data) => { setFormData(data); // Handle form submission }; return ( <form onSubmit={handleSubmit(onSubmit)}> {/* Form fields */} </form> ); }; ``` Example where you can access the data from another page ```javascript // In another page or component import { useFormContext } from '../path/to/formContext'; const AnotherPage = () => { const { formData } = useFormContext(); // Use formData as needed }; ```
Try to set `NO` for `pushViewController:animated:`, in another word, use `pushViewController:vc animated:NO` instead. I Guess if we set YES for `animated:`, in order to show the animation of current VC dismissing, RandomView will be added again. And after the animation ends,RandomView will be removed. That could explain the log that willMoveToWindow: is called another twice
I am using Apps Script to run multiple find and replace functions but it doesn't seem very efficient to do it this way: First Function looks like this: function findAndReplace1() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YouTube'); var range = sheet.getRange('A2:D'); var textFinder = sheet.createTextFinder('&#39;'); textFinder.replaceAllWith(""); } Second function looks like this: function findAndReplace2() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YouTube'); var range = sheet.getRange('A2:D'); var textFinder = sheet.createTextFinder('|'); textFinder.replaceAllWith(" "); } And so on. It works OK but I would like to have just one function that performs multiple find & replace 'functions'. How would I achieve this?
Can't change a variable in CMU CS academy
|variables|new-operator|
null
How to change the link structure of any blog post that is shared on any social media platform. This is a News website designed on WordPress Platform. The problem specifically arises when any blogpost written in telugu is shared on Whatsapp. The link structure after sharing is showing up something similar to "%0%0%0%0%8%8 [![enter image description here][1]][1] I want the shared link to have the title of the blog post and the featured image of the post [1]: https://i.stack.imgur.com/XHORg.png
You can add on top of the CMakeLists: macro(set name) message(STATUS "defining ${name}") _set(${name} ${ARGV}) endmacro() set(a b) and print `CMAKE_CURRENT_LIST_*` variables.
Check the [source][1]: ```python try: makedirs(head, exist_ok=exist_ok) except FileExistsError: # Defeats race condition when another thread created the path pass ``` So no exception in case of someone else creating the same path. [1]: https://github.com/python/cpython/blob/8da83f3386da603605358dc9ec68796daa5ef455/Lib/os.py#L202
I experience the same on Jenkins v2.425 with email extension v2.105. Not a solution but maybe a temporary fix is to deactivate the authentication of your SMTP server and then remove the credentials.
I am trying to get messages from a thread using the chat_gpt_sdk flutter package. I am failing at a seemingly very simple step. I must be missing something fundamental and it's driving me nuts. Here is a piece of my code: ``` final runRequest = CreateRun(assistantId: assistantID); runResult = await globals.chatAI.threads.runs .createRun(threadId: threadID, request: runRequest); var runID = runResult.id.toString(); print('runID: $runID'); // this is giving me the output 'runID: run_abc123'. final mRunSteps = await globals.chatAI.threads.runs.listRunSteps( threadId: threadID, runId: runID, //this is where I get an error! ); print('runID after: ${runResult.id}'); ``` If I run the code above, I get a runtime error saying ``` [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Null' is not a subtype of type 'String' #0 new ListRun.fromJson (package:chat_gpt_sdk/src/model/run/response/list_run.dart:19:22) #1 OpenAIClient.get (package:chat_gpt_sdk/src/client/openai_client.dart:59:25) <asynchronous suspension> #2 ChatBotBrain.getChatAnswer (package:germaniac01/controlers/chatbot_brain.dart:84:23) <asynchronous suspension> #3 _ChatBotScreenState.build.<anonymous closure>.<anonymous closure> (package:germaniac01/screens/chatbot_screen.dart:52:35) <asynchronous suspension> ``` The error is pointing to the position before the "await globals.chatAI.threads....". I assume it's related to the runID, because if I exchange the definition of runID with `runID = 'run_abc123'` instead, it works just fine. In that case the print below gives me the same output as the one above, so it seems that runID is a String all the time. If I wrap it with `if(runID is String)` it says that's unnecessary bc always true. Why does it say it is null then? What am I missing?
I have an esp32 and i wish to use it to drive a HC-SR04 sonar module. I use interrupts to get information from sensors,then I use a queue to pass the data to a freertos task to output it. At first, it work and output the correct data, but after few second, it report an error and reboot. Here is the error: Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled. Core 1 register dump: PC : 0x40084c90 PS : 0x00050631 A0 : 0x800d31c4 A1 : 0x3ffbf53c A2 : 0x00000040 A3 : 0x00018040 A4 : 0x000637ff A5 : 0x3ffbf50c A6 : 0x00000008 A7 : 0x00000000 A8 : 0x00000001 A9 : 0x4008bf6e A10 : 0x00060b23 A11 : 0x3ffc4a14 A12 : 0x3ff44000 A13 : 0xffffff00 A14 : 0x00000000 A15 : 0x00000020 SAR : 0x0000001d EXCCAUSE: 0x0000001c EXCVADDR: 0x800d31d0 LBEG : 0x400899a4 LEND : 0x400899ba LCOUNT : 0xffffffff Backtrace: 0x40084c8d:0x3ffbf53c |<-CORRUPTED Then I found that if I delete the code that were used to push the data to the queue, it will work normally. So I guass that is the problem,but I don't Know how to fix it. Here is main: ``` radar radar0(25,35); void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.setDebugOutput(true); radar0.start(); } ``` Here is how radar class define: ``` class radar { private: uint8_t txPin,rxPin; Ticker loopTrigger; //ticker that use to trigger loop Ticker singalEnder; //ticker that use to generate a 1ms pulse QueueHandle_t dstQueue; //queue that use to pass dst to coroutine float previousDst; bool enable; unsigned long echoStartTime; //The time the echo start received void loop(); void echoStartHandler(); //callback when the echo start void echoEndHandler(); //callback when the echo end void queueListener(); public: radar(uint8_t txPin,uint8_t rxPin); void start(); }; radar::radar(uint8_t txPin,uint8_t rxPin){ this->txPin=txPin; this->rxPin=rxPin; this->enable=true; this->dstQueue = xQueueCreate(4,sizeof(float)); } void radar::start(){ //set pin mode pinMode(this->txPin,OUTPUT); pinMode(this->rxPin,INPUT); //low down the txPin digitalWrite(this->txPin,LOW); //Create a coroutine for listening to the dstQueue auto fn = [](void *arg){static_cast<radar*>(arg)->queueListener();}; xTaskCreate(fn,"dstListener",1024,this,0,NULL); //enable the radar this->enable=true; this->loop(); } void radar::queueListener(){ float dst; while (this->enable) { if (xQueueReceive(this->dstQueue,&dst,0)==pdFALSE){ //sleep 10ms if the queue is empty vTaskDelay(10/portTICK_PERIOD_MS); continue; } if (abs(dst-this->previousDst)>5){ Serial.println(dst); this->previousDst=dst; } } vTaskDelete(NULL); } void radar::echoStartHandler(){ this->echoStartTime = micros(); //Set rxPin pull-down interrupt attachInterruptArg(rxPin,[](void* r){static_cast<radar*>(r)->echoEndHandler();},this,FALLING); } void radar::echoEndHandler(){ detachInterrupt(this->rxPin); unsigned long echoEndTime = micros(); float pluseTime; if (echoEndTime > this->echoStartTime){ //If the variable does not overflow pluseTime = echoEndTime - this->echoStartTime; }else{ pluseTime = echoEndTime + (LONG_MAX - this->echoStartTime); } float dst = pluseTime * 0.0173; //push the dst to queue BaseType_t xHigherPriorityTaskWoken; xQueueSendFromISR(this->dstQueue,&dst,&xHigherPriorityTaskWoken); if (xHigherPriorityTaskWoken==pdTRUE){ portYIELD_FROM_ISR(); } } void radar::loop(){ if (!this->enable){ return; } //Set loop() to be triggered after 100ms this->loopTrigger.once_ms<radar*>(100,[](radar* r){r->loop();},this); //Generate a 1ms pulse at txPin digitalWrite(this->txPin,HIGH); this->singalEnder.once_ms<uint8_t>(1,[](uint8_t pin){digitalWrite(pin,LOW);},this->txPin); //Set rxPin pull-up callback attachInterruptArg(rxPin,[](void* r){static_cast<radar*>(r)->echoStartHandler();},this,RISING); } ``` Thank for your help! ps: Please forgive my poor English.I'm not a native speaker.
Encountering Core panic'ed when trying to use FreeRTOS queue in esp32
|c++|esp32|freertos|
null
So I'm trying to deploy an application to Google App Engine from Github actions and I'm getting this error message: ```Failed to create cloud build: invalid bucket "<PROJECT_NUMBER>.cloudbuild-logs.googleusercontent.com"; default Cloud Build service account or user-specified service account does not have access to the bucket``` I have tried to specify a different bucket for logging other than the default, using the flag: `--bucket gs://generic-app`. I've also tried to specify a different service account that has owner role (overkill, I know), exported it's key and passed it into the `credentials_json` prop. But I get the same error message. Why would this be happening? Full workflow file ```yaml name: Deploy to Goggle App Engine on: push: branches: - main - staging jobs: build-and-deploy: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Setup Node.js and yarn uses: actions/setup-node@v2 with: node-version: '18' - name: Install dependencies run: yarn - name: Build Node Project run: yarn build # Production - name: Google Cloud Auth Production if: github.event_name == 'push' && github.ref == 'refs/heads/main' uses: 'google-github-actions/auth@v2' with: credentials_json: '${{ secrets.GCP_SA_KEY_PRODUCTION }}' project_id: ${{ secrets.GCP_PROJECT_ID_PRODUCTION }} # Staging - name: Google Cloud Auth Staging if: github.event_name == 'push' && github.ref == 'refs/heads/staging' uses: 'google-github-actions/auth@v2' with: credentials_json: '${{ secrets.GCP_SA_KEY_STAGING }}' project_id: ${{ secrets.GCP_PROJECT_ID_STAGING }} - name: Set up Cloud SDK uses: 'google-github-actions/setup-gcloud@v2' - name: Deploy to Google App Engine run: | gcloud app deploy app.yaml --quiet --version service-default --no-promote --bucket gs://generic-app ```