Posts

Showing posts from November, 2023

Pagination from two tables in SQL Server

I have two tables with the following schema: Table A : ColumnA, UserId, ... - rest of the schema omitted for brevity Table B : ColumnB, UserId, ... - rest of the schema omitted for brevity The tables can have duplicate values between them. For e.g - Table A row (<some-columnA-value>, 1, ...) and Table B row (<some-columnB-value>, 1, ...) , 1 being the UserId. Now, I have an API which is used to fetch all the UserId values from both tables. With increasing data, I want to now use pagination for this API and would like to modify the queries accordingly. There should also not be any duplicates over the pages or within a page. How do I achieve this? Also a requirement is that I need to use keyset pagination rather than offset pagination since offset pagination gets slower as and when the offset increases. So far, I have thought of using indexed views since there is only 1 column that I require to fetch but since the data keeps changing quite frequently and in large ...

Null checking with primary constructor in C# 12

I using C# 12. In C# 12 I can use primary constructor: public class UserService(IUnitOfWork uow) : IUserService { } Before C# 12 I used null checking for items that I inject in constructor: public class UserService : IUserService { private readonly IUnitOfWork _uow; public UserService(IUnitOfWork uow) { ArgumentNullException.ThrowIfNull(uow); _uow = uow; } } Now how can I do null checking in C# 12 ? Is it need to use fail fast with primary constructor ?

Django with mypy: How to resolve incompatible types error due to redefined field for custom `User` model class that extends "AbstractUser"?

I have an existing Django project which uses a custom User model class that extends AbstractUser . For various important reasons, we need to redefine the email field as follows: class User(AbstractUser): ... email = models.EmailField(db_index=True, blank=True, null=True, unique=True) ... Typing checks via mypy have been recently added. However, when I perform the mypy check, I get the following error: error: Incompatible types in assignment (expression has type "EmailField[str | int | Combinable | None, str | None]", base class "AbstractUser" defined the type as "EmailField[str | int | Combinable, str]") [assignment] How can I make it so that mypy allows this type reassignment? I don't wish to just use # type: ignore because I wish to use its type protections. For context, if I do use # type: ignore , then I get dozens of instances of the following mypy error instead from all over my codebase: error: Cannot determine type of ...

Avalonia window (textboxes) embedded in Autodesk Inventor not accepting input

I'm developing an Autodesk Inventor plug-in and I've chosen to use Avalonia for the UI. Inventor exposes the ability to create a dockable window. I'm not completely sure how it works behind the scenes but you can add a winforms / WPF control to it, by adding the control's handle as child to the dockable window. After looking at some samples I figured out how to add the avalonia control to the dockable window. Everything seems to be working fine, only keypresses are not accepted. (Just backspace & delete) When I run the app from a button press in the ribbon, there are no such problems. I've found some information on StackOverflow and on the Autodesk forum. I thought the problem might be related to Avalonia so I've used the sample here to embed the avalonia app in a WPF window, thinking this would fix the problem. It didn't. This thread on the autodesk forum describes the same problem, but for a WPF window. <Grid> <!--WPF input works--...

Use a Nonlinear Poisson Regression with two independent variables?

I'm looking for a way to use Nonlinear Regression with Poisson for predictive purposes. I would need something similar to Poisson regression , but with some modifications because: I have two data sets that are made up of randomly placed numbers and have no correlation; The two variables are both independent (and not one dependent and one independent); The purpose of the regression will be to obtain a parameter that can be used in the Poisson distribution to calculate probabilities (explained better later), such as in poisson.pmf(2, regression_result) ; Is there something i could use that satisfies the three points above? Any algorithm in some library like scikit learn , scipy , etc? I can't find an algorithm that is useful for my case. I would need something similar to sklearn.linear_model.PoissonRegressor , but for nonlinear regression and for both independent variables My data are: Team_A__goal_scored = [1, 3, 1, 2, 2] (x) Team_B__goal_conceded = [3, 0, 1, 1, 2] (y) ...

Excel: Compounding matrix generation with array inputs

Image
Task: To output an array of scalar products based on input array of boolean values and scalars. Requirements: The solution needs to be formulaic (i.e. contained in one cell) and done without the use of VBA -> the solution needs to be dynamic to accommodate different input arrays. Input array A (Boolean values) >= 2023 2024 2025 2026 2023 1 0 0 0 2024 1 1 0 0 2025 1 1 1 0 2026 1 1 1 1 Input array B (Scalar values) 2023 2024 2025 2026 1.25 1 1.2 1.05 1.35 1.1 1 1.2 1.25 1.15 1.05 1.05 1.3 1 1.1 1.15 1.25 1.1 1.4 1.35 Output array (Compounded scalars) 2023 2024 2025 2026 1.25 1.25 1.5 1.575 1.35 1.485 1.485 1.782 1.25 1.4375 1.509375 1.58484375 1.3 1.3 1.43 1.6445 1.25 1.375 1.925 2.59875 In practice: the columns of Output array are comprised of row-wise products of the Input array B . For example the first column is only the 2023 scalars, bu...

Local host redirecting too many times

I Keep getting this when ever I want to run localhost This page isn’t working localhost redirected you too many times. Try deleting your cookies. ERR_TOO_MANY_REDIRECTS I tried deleting third party cookies. What can I do solve this issue. I download snipe-it database but it does not seem to be working.

Regex, anonymise all matches, per line where there is 1 mandatory match with various optional matches

I've research this quite heavily now but nothing seems to be getting me close Below is an excerpt of a csv file. I need to anonymise certain lines where there is a match found for an email address. Once a match is found I need to also anonymise other certain fields that might also be present on the same line. I read about ? making preceding token's optional so though it would be relatively easy to specific an optional group and a mandatory group but I can't it to work. This is the example data: test1,rod.p@nono.com,bbb,123456789,987654321,aaa,121 test2,aaa,rod.p@yes.com,123456789,aaa,bbb,987654321,122,rod.p@yes.com,aaa,123456 test3,rod.p@yesyes.com,123456789,987654321,aaa,123 Based on the below syntax, I need the line test2 being matched only and specifically the parts aaa [optional as long as the email address has been matched on the same line] bbb [optional as long as the email address has been matched on the same line] rod.p@yes.com [mandatory] (please note the em...

OSDev -- double buffering rebooting system

Hello I'm trying to make a simple os, and I'm currently trying to do double buffering. I have two arrays in the size of the screen and a function that copy the array that currently is being used to the memory of the screen and then swap the being used array to the second one. And there is a function that clear the screen and set it to a specific color. screen.c static u8 *BUFFER = (u8*) 0xA0000; u8 buffers[2][SCREEN_SIZE]; u8 current_buffer = 0; #define CURRENT (buffers[current_buffer]) #define SWAP() (current_buffer = 1 - current_buffer) void screen_swap(){ memcpy(BUFFER, CURRENT, SCREEN_SIZE); SWAP(); } void clear_screen(u8 color){ // set all the memory of the screen to one color memset(&CURRENT, color, SCREEN_SIZE); } memory.c void memset(void* src, u8 val, u32 len){ u8* ptr = (u8*)src; while(len--){ *ptr++ = val; } } void* memcpy(void* dst, void* src, u32 len){ u8 *d = (u8*)dst; const u8 *s...

how to pass an assertion in if condition using cypress without halting the execution in case of assertion failure

I am trying to pass an assertion to if condition and execute a logic when the condition is met and another logic when condition is failed. Since the test is failing on failure of assertion i am not able to achieve the desired result. I tried the following... if(cy.get("div").length\>0) { cy.log("print this") } else { cy.log("print this") } or if(cy.get("div").should('have.length.greaterThan',0) { cy.log("print this") } else { cy.log("print this") }

Find the minimum value for each unique key without using a for loop

I have a numpy array with keys (e.g. [1, 2, 2, 3, 3, 2] ) and an array with values (e.g. [0.2, 0.6, 0.8, 0.4, 0.9, 0.3] ). I want to find the minimum value associated with each unique key without using a for loop. In this example, the answer is {1: 0.2, 2: 0.3, 3: 0.4} . I asked ChatGPT and New Bing but they keep giving me the wrong answer. So, is it really possible to do this without a for loop? Edit 1: What I'm trying to achieve is the fastest speed. Also, in my case, most keys are unique. I considered using np.unique to acquire every key and then compute the min value for every key, but clearly it requires a for loop and a quadratic time. I also considered sorting the arrays by keys and apply np.min on the values of each key, but I doubt its efficiency when most keys are unique. Additionally, according to the comments, pandas.DataFrame has a groupby method which might be helpful, but I'm not sure if it's the fastest (perhaps I'm going to try on my own). Edit 2:...

Python - extend enum fields during creation

Is it possible extend enum during creation? Example: class MyEnum(enum.StrEnum): ID = "id" NAME = "NAME And I need that after creating this enum contains the next fields: ID = "id" NAME = "name" ID_DESC = "-id" NAME_DESC = "-name" I need this to create custom ordering enum for FastAPI project Now I have the next way to create new enum NewEnum = enum.StrEnum( f"{name.title()}OrderingEnum", [ ( f"{ordering_field.upper()}_DESC" if ordering_field.startswith("-") else ordering_field.upper(), ordering_field, ) for ordering_field in itertools.chain( values, [f"-{field}" for field in values], ) ], ) But I need do this automatically, because each module with model have similar enum. Maybe this is possible to solve my problem using MetaClass for my enum class, or override ...

How to format bar chart yearly x-axis to not contain floats

Image
What causes the x-axis to have Year numbers in between the bars and the 0.5 attached to the Population Year ru = px.bar(wakel, x = "Population Year", y = "Population", color = "City") ru.show()

Custom hook with clear and update time not works as per expected

When update the default time with setInterval , it's not working as expected. Instead it's added as a new instance. How to clear the setInterval in the custom hook and update new value? app.jsx import React from 'react'; import './style.css'; import CustomTimer from './Custom'; import { useState, useEffect } from 'react'; export default function App() { const [intervalTime, setIntervalTime] = useState(200); const time = CustomTimer(intervalTime); useEffect(() => { setTimeout(() => { console.log('Hi'); setIntervalTime(500); }, 5000); }); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some happen! {time} </h2> </div> ); } Custom.js import { useEffect, useState } from 'react'; function CustomTimer(startTime) { const [timer, setTimer] = useState(startTime); useEffect(() => { c...

Mediation analysis with a tobit regression is failing to find the outcome variable

I am trying to run a mediation analysis with the mediation package in R. My outcome variable needs to be modeled with a tobit model (censored data). When I try to run it, it claims that the outcome variable cannot be found, although it is in the dataframe. See reproducable example: library(mediation) test <- data.frame(mediator = c(0.333,0.201,0.343,0.133,0.240), DV = c(0.152,2.318,0.899,0.327,1.117), outcome=c(1.715,1.716,0.544,3.284,3.599)) mediator_model <- lm(mediator ~ DV, data = test) outcome_model <- vglm(outcome ~ mediator + DV, tobit(Upper = 4, Lower = -4), link = "identity",data = test) med <- mediate(mediator_model, outcome_model, treat = "DV", mediator = "mediator") When I run this, I get the error Error in eval(predvars, data, env) : object 'outcome' not found , even though the outcome model runs without a problem.

Extract string from image using pytesseract

Image
I am a newbie on OCR manipulation and extraction data from images. After searching for solution I did find some code but it didn't work for my use case, it didn't extract correctly all characters, at most 2 of them. I want to get the characters on this image: I tried this solution: image = cv2.imread('./images/screenshot_2023_11_16_15_41_24.png') # Assuming 4 characters in a 36x9 image char_width = image.shape[1] // 4 char_height = image.shape[0] characters = [] characters_slices = [(0, 9), (9, 18), (18, 27), (27, 36)] # Adjust based on your image for start, end in characters_slices: char = image[0:char_height, start:end] characters.append(char) # Perform OCR on each character extracted_text = "" for char in characters: char_text = pytesseract.image_to_string(char, config='--psm 10 --oem 3 -c char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') extracted_text += char_text.strip() + " " print("Extracted Text:...

Makefile won't find *.lib but path is declared

I am trying to compile a plugin example for a software from autodesk. here is the Makefile ############################################################################## # Makefile for use by API developers # # # # NOTE: "vcvarsall amd64" must be run before attempting to compile the API # # examples. Please see the API documentation for information. # # # ############################################################################## # # If the location of the Alias libraries and header files are # different from $ALIAS_LOCATION, set it here. # ALIAS_LOCATION=C:\Program Files\Autodesk\AliasSurface2023.0 CPPEXAMPLES = cppCube.exe EXAMPLES = $(CPPEXAMPLES) CC = cl.exe CPLUSPLUS = cl.exe LINK = link.exe INCLUDES = /I. /I"$(ALIAS_LOCATION)\ODS\Common\include" ...

Building correct API query URL to filter data from clinicaltrials.gov by multiple keywords

Image
I am trying to get some data from a public API and need some help figuring out the correct query syntax for the request URL. Below is my script. (Never mind fixing or improving the function, it is working well enough so far.) What I need is the correct query URL. I would like to get a list of clinical studies from clinicaltrials.gov for search term "EGFR", but narrow the search down so that only results are returned that have "Recruiting" OR "Active, not recruiting" in the "OverallStatus" field. Here are the possible values for the "OverallStatus" field. I am having a hard time figuring out the API docs. There is a page with Search Expressions and Syntax , but they don't explain how to search for multiple values. How do I build the query string to search for multiple possible values in a field? I appreciate any insights! library(tidyverse) library(httr) library(jsonlite) library(glue) get_studies_df <- function(query_url...

NextJS 13 in Azure: process.env.{SETTING_NAME} in server components is undefined

I upgraded to NextJS v13 from v12. I thought components inside the src/app folder are server components by default but when I try to use the values from process.env after deploying with Azure, its returning undefined for those configuration settings. It works when I run it locally maybe because those settings are in a .env file but after deployment it should get it from the Azure configuration settings. Here is the sample page: src/app/page.tsx import SampleClientView from '@components/components/client/SampleClientView'; // This has 'use client'; const SamplePage = () => { const configOne = process.env.CONFIG_ONE; const configTwo = process.env.CONFIG_TWO; return ( <SampleClientView configOne={configOne} configTwo={configTwo} /> ); }; export default SamplePage;

LINQ Exception when Lists of Documents containing Lists - Querying MongoDB Entity Framework Core

We are doing some development on the EF Core Library for MongoDB. It's in preview, so I'm trying to work out if this is a bug or a feature (or lack of a feature). We are not doing any queries on these elements yet, but when the problematic collection is queried, if the problematic element is defined, we're running into problems. public class Template { public ObjectId _id { get; set; } public string name { get; set; } public bool inheritFrom { get; set; } public List<CallRound> callRounds { get; set; } //this is a list of sub documents with a list, it complains public Qualifier qualifiers { get; set; } // this is a sub document with a list, it doesn't complain } public class CallRound { public List<CollectionReference>? jobQualifiers { get; set; } //this is the offender, if we comment out this code, the query functions public bool isOvertime { get; set; } public bool offerOrientedOnly { get; set; } public string gend...

Deploy Container App from Bitbucket to Azure

Image
I have a Bitbucket repository which builds my code with a pipeline and pushes a docker image to Docker Hub . So far, so good. Now I want to continues deploy the latest image to my Container App on Azure. My options seems to be: Setup Continuous Deployment in Azure Create a pipeline step in bitbucket to push the new image created to Azure with Azure CLI My problem with 1. is that it seems to be only support for GitHub with it required. And my problem with 2. is that it doesnt look like Atlassian has this supported Which leaves me with some costum created pipeline where Im suppose to do this with Azure CLI where Im way out of my depth. Does anyone have a suggestion to how I can automaticly update my Container App?

Error saying "git is not installed" but it actually is [closed]

This error appears in the cmd window Image of error when I try to run "gradlew.bat" from the baritone repository "https://ift.tt/Qq6blna". Also it is definitely not the file's fault because other people don't have this issue. I tried running the gradlew.bat file and expected it to create/build a "dist" folder which is supposed to contain artifacts aka .jar files of the MC mod baritone, result is it didn't get created. File of gradlew.bat https://pastebin.com/FEzqR9FR code ` @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, ...

Keycloak oidc authentication issue on K8s having replica of application server

I am facing an issue with authorization_code grant type on a replica set up in a K8s cluster and seeking for advice and help. My set up is as follows: 1 instance of Keycloak server running on 1 pod on 1 node. 2 instances of backend server running on 2 pods on 2 different nodes. (say api1 and api2 ) Basically, the problem here is, suppose if the api1 initiates a code verification challenge to the Keycloak during the authentication workflow, and the user after successfully authenticating with Keycloak with a valid username and password, the Keycloak would then invoke the redirectURI of the backend server. However, the redirectURI instead of hitting api1 , hits the other instance of backend server api2 . And due to this the session state of the Request object for api2 would not have the code_verifier property because of which we are unable to call the /protocol/openid-connect/token api to get the access token. What I am trying to achieve is either have the redirectURI always h...

Iterate over list of YouTube/RTSP streams, add text overlays, and expose as a fixed RTSP endpoint

My goal is a shell script or Python utility that cycles through list (.csv, .yaml, or .json) of YouTube/RSTP source streams in a format similar to the following (.csv) example below: url,overlay_text,delay_ms rtsp://admin:12345@192.168.1.210:554/Streaming/Channels/101,THIS IS OVERLAY TEXT,5000 https://www.youtube.com/watch?v=dQw4w9WgXcQ,THIS IS MORE OVERLAY TEXT,5000 . . . rtsp://admin:12345@192.168.1.210:554/Streaming/Channels/101,THIS IS OVERLAY TEXT,5000 https://www.youtube.com/watch?v=dQw4w9WgXcQ,THIS IS MORE OVERLAY TEXT,5000 For each record in the text file, the utility will: Capture the stream from the specified source URL Add the overlay_text for that record to the stream Proxy or otherwise expose it as a fixed/unchanging RTSP endpoint Wait delay_ms for that record Kill that stream, go on to the next one, and repeat...exposing the next stream using the same RTSP endpoint. So, to a consumer of that RTSP stream, it just seems like a stream that switched to a different ...

how to get rid of peter panning completely using cascaded shadow maps?

I am making a voxel open world game with C and opengl 4.0. I implemented cascaded shadow maps using this tutorial: https://learnopengl.com/Guest-Articles/2021/CSM I cant get rid of peter panning no matter how I set the bias variable. My shadows looks like this: current shadows As you can see there are thin gaps between cubes and their shadows. I dont want that. This is how I set bias variable: float bias = max(0.005f * (1.0f - dot(normal, lightDirection)), 0.00028f); const float biasModifier = 0.2f; if(layer==0){ bias *= 1 / (cascade0range * biasModifier); } else if(layer==1){ bias *= 1 / (cascade1range * biasModifier); } else if(layer==2){ bias *= 1 / (cascade2range * biasModifier); } else if(layer==3){ bias *= 1 / (cascade3range * biasModifier); } If you want to see all of the code, this is the repository of the project: https://github.com/SUKRUCIRIS/OPENGL_VOXEL_GSU I tried to decrease bias variable more but it caused shadow acne and even then the gap was still there: shadow a...

Recursively adding columns to pyspark dataframe nested arrays

I'm working with a pyspark DataFrame that contains multiple levels of nested arrays of structs. My goal is to add an array's hash column + record's top level hash column to each nested array. To achieve that for all nested arrays I need to use recursion since I do not know how nested the array can be. So for this example schema schema = StructType([ StructField("name", StringType()), StructField("experience", ArrayType(StructType([ StructField("role", StringType()), StructField("duration", StringType()), StructField("company", ArrayType(StructType([ StructField("company_name", StringType()), StructField("location", StringType()) ]))) ]))) ]) The desired output schema would look like this: hashed_schema = StructType([ StructField("name", StringType()), StructField("experience", ArrayType(StructType([ ...

getting error when uploading SignUpOrSignIn custom policy file, I want to include user identities with id token

I want to fetch the sign-in user's identities array from the tenant and include it in the id token (add in the RelyingParty outputclaim),Would like to know how to add user's properties mainly identities with id token. <ClaimType Id="identities"> <DisplayName>Identities</DisplayName> <DataType>stringCollection</DataType> </ClaimType> <ClaimsProvider> <DisplayName>Azure Active Directory</DisplayName> <TechnicalProfiles> <TechnicalProfile Id="AAD-UserReadUsingObjectId"> <DisplayName>Azure Active Directory</DisplayName> <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> <CryptographicKeys> <Key Id="issuer_secret" StorageReferenceId="B2C_1A_TokenSignin...

Next.js instrumentation behaves differently with conditional extracted to variable

This issue came from an earlier issue I created , which was resolved, but the underlying behaviour is so baffling I'm desparate to know what is going on. Next.js has an experimental feature called Instrumentation that allows code to be run on boot-up. It seems to run both server-side and client-side, so a special check is necessary if nodejs-dependent imports are to be used. I have working code that uses this functionality: export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { const os = await require('os'); console.log(os.hostname()); } } However, the following code does not work: export async function register() { const isServer = process.env.NEXT_RUNTIME === 'nodejs' if (isServer) { const os = await require('os'); console.log(os.hostname()); } } The error is: - error ./instrumentation.ts:12:21 Module not found: Can't resolve 'os' 10 | const isServer = process.env.NEXT_RUNTI...

CUDA issue with NER (Named Entity Recognition) for ML predictions

I'm attempting to use NamedEntityRecognition (NER) ( https://github.com/dotnet/machinelearning/issues/630 ) to predict categories for words/phrases within a large body of text. Currently using 3 Nuget packages to try get this working: Microsoft.ML (3.0.0-preview.23511.1) Microsoft.ML.TorchSharp (0.21.0-preview.23511.1) Torchsharp-cpu (0.101.1) At the point of training the model [estimator.Fit(dataView)], I get the following error: Field not found: 'TorchSharp.torch.CUDA'. I may have misunderstood something here, but I should be processing with CPU from the Torchsharp-cpu package and I'm not sure where the CUDA reference is coming from. This also appears to be a package reference rather than a field? using Microsoft.ML; using Microsoft.ML.Data; using Microsoft.ML.TorchSharp; using System; using System.Collections.Generic; using System.Windows.Forms; namespace NerTester { public partial class Form1 : Form { public Form1() { Ini...

Understanding QuickGrid internals: "Defer hack"

I am studying the source code of the QuickGrid from Blazor (ASP.NET Core 8). The implementation leverages some internal knowledge on how Blazor handles the actual rendering in order to collect all ColumnBase child components. It does so by initiating and ending a "collecting session" and during this session all ColumnBase child components attach themselves to the cascaded grid context. <CascadingValue TValue="InternalGridContext<TGridItem>" IsFixed="true" Value="@_internalGridContext"> @{ StartCollectingColumns(); } @ChildContent <Defer> @{ FinishCollectingColumns(); } <ColumnsCollectedNotifier TGridItem="TGridItem" /> @* HTML table... *@ </Defer> </CascadingValue> The ColumnBase components inside the ChildContent execute the following code in their BuildRenderTree method: InternalGridContext.Grid.AddColumn(this, InitialSortDirection, IsDefaultSortColumn);...

Can I connect to cloud sql postgres using Private IP from my computer (locally) using Python?

I'm trying to connect to a cloud sql postgreSQL instance using Python code from my local machine (locally) and using the Private IP of my cloud sql instance. from google.cloud.sql.connector import Connector, IPTypes import pg8000 import sqlalchemy from sqlalchemy import text def connect_with_connector_auto_iam_authn(): instance_connection_name = "connection name" db_user = "SA name" # e.g. 'my-db-user' db_name = "postgres" # e.g. 'my-database' ip_type = IPTypes.PRIVATE # initialize Cloud SQL Python Connector object connector = Connector() def getconn() -> pg8000.dbapi.Connection: conn: pg8000.dbapi.Connection = connector.connect( instance_connection_name, "pg8000", user=db_user, password="", db=db_name, enable_iam_auth=True, ip_type=ip_type ) return conn # The Cloud SQL Python Connector can be used with SQLAlchemy # using the 'creator...

Join statements with multiple filters in Spring Data JPA

I am using Spring Data JPA to query records from a database. This is my SQL query SELECT t1.id FROM test1 t1 LEFT OUTER JOIN test2 t2 ON t1.id = t2.id WHERE t2.key = 'keyNames' and t2.value IN 'a,b,c' and to_timestamp(t1.createdtime,'YYYY-MM-DD"T"HH24:MI:SSxff3"Z"') >= (SYSDATE - INTERVAL '12' HOUR); I have created test1 and test2 entities with @OnetoMany association and the repositories. public interface Test1Repository extends JpaRepository<Test1, Long>, JpaSpecificationExecutor<Test1> { } public interface Test2Repository extends JpaRepository<Test2, Long>, JpaSpecificationExecutor<Test2> { } public class Test1 { @Id @Column(name = "ID", nullable = false) private Long Id; @Column(name = "CREATED_DATE", nullable = false) @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'") @CreationTimestamp private LocalDateTime createdDate; @OneToMany(mappedBy ...

Qt Context Menu for each item in ListView [duplicate]

I use PyQt5 + Qt Designer 5. Is it possible to show Context Menu when I rightclick on item in ListView area? The best I've got to is context menu opening when I click anywhere inside of ListView area but not the one item.

Ado.net connection to mysql in ssis

I have 60 table in my sql in 60 different servers from 192.168.69.1 to 192.168.69.60 When I create a single mysql connection and read data from first table its worked. But when I create a parameterized connection with expression, it's not working and I see this error : [ADO NET Source [2]] Error: An error occurred executing the provided SQL command: "select * from mdl_adobeconnect". SELECT command denied to user 'biteam'@'192.168.12.20' for table 'mdl_adobeconnect' But I have full permission on all tables.

Missing gems when running bundler exec fastlane

I'm trying to run fastlane locally on a M1 MacBook. After running bundler exec fastlane deploy I get the following exception: Could not find json-2.6.3, digest-crc-0.6.5, unf_ext-0.0.8.2 in locally installed gems Run `bundle install` to install missing gems. No exception is thrown on running bundle install and it seems like the missing gems are installed, but if I run bundler exec fastlane deploy again, I get the same exception as before. Any tips on how I can fix this ?

How to dynamically/programmatically subscribe to a datasource from a ThingsBoard widget?

I'm working with a ThingsBoard widget and I'm looking for a way to programmatically subscribe to a data source where the field/attribute or timeseries key is not predetermined. Currently, I can utilize the dashboard state to subscribe to entities (assets, devices) or clients dynamically. However, this approach requires prior knowledge of the attribute name, which in my case is dynamic. Is there a method or API within ThingsBoard that allows for such dynamic attribute subscriptions within a widget? Any examples or documentation pointers would be highly appreciated.

How can I obtain an image's PPI in JavaScript if it's unavailable in EXIF Data?

I have a tool in frappe-framework that permits image uploads by checking, the width[=1050px], height[=1500px] and filesize [between 300KB to 3000KB] of an image. Along with the existing requirements I need to add an additional check to permit image upload if PPI = 300. I am able to get the PPI using the EXIF metadata in javascript. Is there an alternative approach or library I can use to get an image's PPI when it's not present in the EXIF data?

Spring Boot application OracleDriver claims to not accept jdbcUrl

When launching a Spring Boot application in IntelliJ using the Spring Boot Application run configuration, running with Java 1.8, I am receiving the following message (only one listed for brevity's sake - but the same exception for each of the attempted URLs): Driver oracle.jdbc.OracleDriver claims to not accept jdbcUrl, "jdbc:oracle:thin:@redacted.redacted.us-east-1.rds.amazonaws.com:1234/abcd" I have seen the recommendations on this answer and this answer but I have been unsuccessful in determining the root of the problem. My configurations are as follows - I am using EnvFile locally to provide for values that are normally handled by Vault in our deployed environments. application.properties spring.datasource.url="${DATASOURCE_URL}" spring.datasource.driver-class-name="${SPRING_DATASOURCE_DRIVER-CLASS-NAME}" environment value DATASOURCE_URL=jdbc:oracle:thin:@redacted.redacted.us-east-1.rds.amazonaws.com:1521/abcd # I have tried the followin...

create map with types that implement interface

How to create a map with struct types that implements interface I'm trying to create a map that stores the type for each column (database) There is a few things wrong with the code. I don't really know how to solve it Type_string and Type_int implements sql.Scanner with method Scan I want to be able to fetch a non-predefined set of fields from a database. I don't know if this is the right approach? Want a less strict version than just passing a predifined struct to rows.Scan() Prefer a solution without reflect if possible Types type Type_string string func (t *Type_string) Scan(value any) error { switch value := value.(type) { case []uint8: *t = Type_string(value) default: return fmt.Errorf("Invalid database type: %T %v", value, value) } return nil } type Type_int int func (t *Type_int) Scan(value any) error { switch value := value.(type) { case int64: *t = Type_int(value) default: re...

ansible xml module - set namespace & namespaced elements

I need to change the following xml <network> <name>docker-machines</name> <uuid>ea91ff7c-aa2b-4fa9-b59d-d1fae70285ad</uuid> ... </network> to <network xmlns:dnsmasq='http://libvirt.org/schemas/network/dnsmasq/1.0'> <name>docker-machines</name> <uuid>ea91ff7c-aa2b-4fa9-b59d-d1fae70285ad</uuid> ... <dns> <forwarder addr='5.1.66.255'/> </dns> <dnsmasq:options> <dnsmasq:option value='dhcp-option=option:ntp-server,10.10.14.1'/> </dnsmasq:options> </network> I have successfully managed to set the <dns><forwarder> elemnent using this: - name: Set resolver for docker-machines network xml: path: /etc/libvirt/qemu/networks/docker-machines.xml xpath: /network/dns set_children: - forwarder: addr: 8.8.8.8 Unfortunately, creating the namespaced elements does not seem to be that easy. For exampl...

How do we create siblings composition column out of gender and family id and individual id columns in R

I applied the suggested code to the original dataset. But it didn't produced the desired result in the siblings_composition column such that 1 for at least 1 male sibling, 2 for at least 1 female sibling, 3 for both male and female siblings and 0 for no siblings. In the original dataset BIRIMNO is for family_id, CINSIYET is for gender and id is for individual_id. As an illustration I provide the result which is produced by the code below: head(data) # A tibble: 6 × 4 # Groups: BIRIMNO [5] BIRIMNO CINSIYET id siblings_composition <dbl> <fct> <dbl> <int> 1 144003 F 14400307 3 2 144003 M 14400306 3 3 144009 F 14400903 3 4 144014 M 14401409 3 5 144015 M 14401501 2 6 144016 M 14401603 3 For reproducability on the original dataset, the result of: dput(head(data, 1...

Can I create a map of key-value pairs by deserializing from JSON?

I'm trying to create a Map<TKey, TValue> instance by deserializing a JSON document, but what I'm actually getting seems to be a different type of object, with none of the methods that Map<TKey, TValue> has. I'm quite new to TypeScript (I work mostly with C#) so I created a little unit test using Jest to check whether Map<TKey, TValue> does what I want, specifically whether I can use the forEach method to iterate through each of the key-value pairs. function createMap(): Map<number, string> { const map = new Map<number, string>(); map.set(1, 'foo'); map.set(2, 'bar'); console.log(map); // Console output: Map(2) { 1 => 'foo', 2 => 'bar' } return map; } function iterateUsingForEach(map: Map<number, string>): number { let counter = 0; map.forEach((value: string, key: number, map: Map<number, string>) => { // Normally I'd do something more exciting he...

Swift code suspension point in asynchronous & synchronous code [closed]

I keep reading that synchronous function code runs to completion without interruption but asynchronous functions can define potential suspension points via async/await . But my question is why can't synchronous function code be interrupted at any point, can't the OS scheduler suspend the thread/process at any point and give CPU to a higher priority thread/process (just like it happens in any OS)? What am I understanding wrong here?

Bazel unable to build go targets (version 1.21) due to new workspace mode

Image
What version of rules_go are you using? 0.42.0 What version of gazelle are you using? 0.33.0 What version of Bazel are you using? 6.4.0 Does this issue reproduce with the latest releases of all the above? yes What operating system and processor architecture are you using? MacOS Sonoma / Apple M2 Pro What did you do? upgraded to go 1.21, now when I run bazel build //... , all of the external go modules my program utilizes throws errors related to the new workspace mode introduced in 1.18 https://go.dev/doc/tutorial/workspaces : How do i resolve this? there is no feasible way to add all the modules used in that directory to a go.work file. Is there a way to turn this new workspace mode off?

How to add a reference in a Sphinx custom directive?

I'm creating a custom directive to display the list of all the available components in pydata-sphinx theme. I try to avoid using the raw directive so I'm building a custom one to remain compatible with the other builders. Here is the important part of the code: """A directive to generate the list of all the built-in components. Read the content of the component folder and generate a list of all the components. This list will display some information about the component and a link to the GitHub file. """ from docutils import nodes from sphinx.application import Sphinx from sphinx.util.docutils import SphinxDirective class ComponentListDirective(SphinxDirective): """A directive to generate the list of all the built-in components.""" # ... def run(self) -> List[nodes.Node]: """Create the list.""" # ... # `component` is a list of pathlib ...

Python: urllib3 Library, unable to make requests. Error: urllib3.exceptions.MaxRetryError:

I am new to Python and experiencing issues with the urllib3 library when running on a linux environment. The problem is that the library is unable to make GET requests to any URL's and the requests were tested with other libraries that do similar stuff. The error that I am getting is urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='google.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(\<urllib3.connection.HTTPSConnection object at 0x7f43c27f6cd0\>, 'Connection to google.com timed out. (connect timeout=3)')) As mentioned before, using any other package such as requests or wget performs the request well. Using a PoolManager instead or changing the retry configs will just keep the script running indefinitely. The code: import urllib3 try: response = urllib3.request('GET', 'https://google.com') if response.status == 200: print(response.data) else: print(response.status) ...

how keep the hover enabled while the submenu is open

I have a simple table on my website listing devices and their characteristics (in the example at the link below there will be a shortened version of the table). import "./styles.css"; import { SubMenu } from "./SubMenu"; const subMenuSlice = <SubMenu />; const nodes = [ { id: "0", name: "Samsung Galaxy", subMenu: subMenuSlice }, { id: "0", name: "Iphone", subMenu: subMenuSlice } ]; export default function App() { return ( <table> <tbody> {nodes.map((val, key) => ( <tr key={key}> <td>{val.name}</td> <td>{val.subMenu}</td> </tr> ))} </tbody> </table> ); } https://codesandbox.io/s/romantic-rgb-5t7xkq As you can see, when you hover over any of the lines, the entire line turns gray and an additional button appears. By clicking on this button t...