r/StackoverReddit • u/ByrdieRose • Jun 20 '24
r/StackoverReddit • u/Mighty555 • Jun 19 '24
C++ Error: a non static member reference must be relative to a specific object
In C++, how to you avoid "a non static member reference must be relative to a specific object" error when calling a function from a derived class in a base class without creating an instance of the derived class or make the function in the derived class static?
Basically, I'm asking if there are ways around this. I'm thinking of creating a copy constructor in base where I can pass the instance of derived class by reference but I'm not sure if this is possible.
I've the instance of the derived class in my int man function and I don't want to create another derived class instance in my class header file.
Can I use a base class pointer to the address of the derived object?
r/StackoverReddit • u/LemonLord7 • Jun 17 '24
C++ Kattis safe secret problem: Handling very large sets of possible input combinations
Here is my current solution: https://www.online-cpp.com/brSt5zxDqT
Here is the kattis problem: https://www.online-cpp.com/brSt5zxDqT
I've sped up my solution and I think it seems to be fast enough, but it is sometimes giving the wrong answer. If you could help me out in solving this coding problem I would really appreciate it. Maybe you notice me making some silly mistake or you notice some bad coding practice, or maybe you find my bug! But any help would be appreciated.
Thanks!
r/StackoverReddit • u/RandomHuman1002 • Jun 16 '24
Question Need some help with debugging
import cupy as cp
distance_kernel_code = '''
extern "C" __global__
void calculate_distances(const int* matrix1, const int* path, int* distances, int* city1_vals, int* city2_vals, int* indices, int* ID, int n) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n - 1) {
int city1 = path[idx];
int city2 = path[idx + 1];
ID[idx] = idx;
city1_vals[idx] = city1;
city2_vals[idx] = city2;
int matrix_index = city1 * n + city2;
indices[idx] = matrix_index;
distances[idx] = matrix1[matrix_index];
}
}
'''
distance_module = cp.RawModule(code=distance_kernel_code)
calculate_distances_kernel = distance_module.get_function('calculate_distances')
def randomMatrix(size, maxDistance):
matrix = cp.triu(cp.random.randint(1, maxDistance + 1, size=(size, size)), k=1)
matrix = matrix + matrix.T
return matrix
def calculate_distance(route, distance_matrix, n):
route = cp.asarray(route, dtype=cp.int32)
distances = cp.empty(route.size - 1, dtype=cp.int32)
city1_vals = cp.empty(route.size - 1, dtype=cp.int32)
city2_vals = cp.empty(route.size - 1, dtype=cp.int32)
indices = cp.empty(route.size - 1, dtype=cp.int32)
ID = cp.empty(route.size - 1, dtype=cp.int32)
block_size = 256
grid_size = (route.size - 1 + block_size - 1) // block_size
stream = cp.cuda.Stream()
with stream:
calculate_distances_kernel((grid_size,), (block_size,), (distance_matrix, route, distances, city1_vals, city2_vals, indices,ID, n))
stream.synchronize()
print("Route:", route)
print("City1 Values:", city1_vals.get())
print("City2 Values:", city2_vals.get())
print("Indices:", indices.get())
print("Intermediate Distances:", distances.get())
print("ID",ID)
total_distance = cp.sum(distances).get()
return total_distance
n = 4
Separation = 100
matrix = randomMatrix(n, Separation)
flattened_matrix = matrix.flatten()
print("Matrix:\n", matrix)
print("Flattened Matrix:\n", flattened_matrix)
initial_temp = 10000
cooling_rate = 0.95
iterations = 9000
current_route = cp.asarray([0, 1, 2, 3], dtype=cp.int32)
total_distance = calculate_distance(current_route, flattened_matrix, n)
print("Total Distance:", total_distance)
print("Current Route:", current_route)Output
Matrix:
[[ 0 4 57 84]
[ 4 0 89 30]
[57 89 0 80]
[84 30 80 0]]
Flattened Matrix:
[ 0 4 57 84 4 0 89 30 57 89 0 80 84 30 80 0]
Route: [0 1 2 3]
City1 Values: [0 1 2]
City2 Values: [1 2 3]
Indices: [ 1 6 11]
Intermediate Distances: [ 0 84 0]
ID [0 1 2]
Total Distance: 84
Current Route: [0 1 2 3]Intermediate Distances are wrong and I can't figure out why
r/StackoverReddit • u/infectedUser68 • Jun 16 '24
I got banned, what do now?
Apparently many people disliked my post to which i took it down. Now im banned from posting but SO is telling me to rephrase it in order to get unbanned. What do now? The post is gone...
r/StackoverReddit • u/Fearless-Armadillo57 • Jun 13 '24
Help building and running an extension for Azure DevOps
Hey, there!
I'm interested in make some modifications to an open-source extension for Azure DevOps (gherkin-renderer-extension). I don't have any experience on developing extensions for Azure DevOps and I'm trying to gain that knowledge. However, I urgently need to implement a feature in this project, but I can't even get it to run.
Please, don't curse at me. Developing Azure DevOps Extensions isn't my main role.
r/StackoverReddit • u/Low_Huckleberry1632 • Jun 13 '24
Python Help with code part 2!
This is one of my codes I need help with:
import sys
import sequenceAnalysis as sa
def main(filename=None):
"""
Main function to read sequences from a FASTA file or stdin,
calculate nucleotide, codon, and amino acid compositions,
and print the results in the specified format.
Parameters:
filename (str): The name of the FASTA file to read from.
If None, read from stdin.
"""
Create a NucParams instance
nuc_params = sa.NucParams()
Create a FastAreader instance
reader = sa.FastAreader(filename)
Read and process each sequence from the FASTA file or stdin
for header, sequence in reader.readFasta():
nuc_params.addSequence(sequence)
Calculate total sequence length in megabases
total_length = nuc_params.nucCount() / 1_000_000
Calculate GC content as a percentage
gc_content = ((nuc_params.nucComposition().get('G', 0) + nuc_params.nucComposition().get('C', 0)) /
nuc_params.nucCount()) * 100
Print the sequence length and GC content
print(f"sequence length = {total_length:.2f} Mb")
print("")
print(f"GC content = {gc_content:.1f}%")
print("")
Get the amino acid and codon compositions
aa_comp = nuc_params.aaComposition()
codon_comp = nuc_params.codonComposition()
Print the relative codon usage
for aa in sorted(sa.NucParams.rnaCodonTable.values()):
codons = [codon for codon, aa_code in sa.NucParams.rnaCodonTable.items() if aa_code == aa]
total_aa_count = sum(codon_comp[codon] for codon in codons)
for codon in sorted(codons):
if total_aa_count > 0:
frequency = (codon_comp[codon] / total_aa_count) * 100
else:
frequency = 0.0
print(f"{codon} : {aa} {frequency:5.1f} ({codon_comp[codon]:6d})")
if __name__ == '__main__':
main()
the error is the following:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 53
50 print(f"{codon} : {aa} {frequency:5.1f} ({codon_comp[codon]:6d})")
52 if __name__ == '__main__':
---> 53 main()
Cell In[1], line 15, in main(filename)
5 """
6 Main function to read sequences from a FASTA file or stdin,
7 calculate nucleotide, codon, and amino acid compositions,
(...)
12 If None, read from stdin.
13 """
14 # Create a NucParams instance
---> 15 nuc_params = sa.NucParams()
17 # Create a FastAreader instance
18 reader = sa.FastAreader(filename)
NameError: name 'sa' is not definedr/StackoverReddit • u/Low_Huckleberry1632 • Jun 13 '24
Python Help with Python coding assignment? I have multiple but I can’t figure out how to fix it.
Hello,
Please help me figure out what is wrong with my codes.
I keep getting errors when I run them and I’m not sure on how to fix them.
r/StackoverReddit • u/Livid-Salamander-949 • Jun 13 '24
C Helpful language agnostic insight when learning underlying programming fundamentals.
When pondering a project thinking about the structure of a core Linux utility like script (utility that records the output of the terminal to a file) it occurred to me , after some digging , what is actually going on when you write code that emulates or copies these core Linux utilities .
It just gave me a kinda of aha! Moment and ohhh okay response . Maybe it will help someone else as well so Here is a summary of the insight :
——————————————————
Understanding System Calls with Code Snippets
System calls are the way user-space programs request services from the operating system kernel. They simplify the interaction between higher-level languages (like C and Python) and the low-level operations of the OS.
What is a System Call?
A system call allows a user program to ask the operating system to perform a task that requires kernel-level privileges, such as reading a file or creating a process.
Example in C: read() System Call
Here's a simple C program that uses the read() system call:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
int fd;
char buffer[128];
ssize_t bytesRead;
fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
bytesRead = read(fd, buffer, sizeof(buffer) - 1);
if (bytesRead == -1) {
perror("read");
close(fd);
return 1;
}
buffer[bytesRead] = '\0';
printf("Read %zd bytes: %s\n", bytesRead, buffer);
close(fd);
return 0;
}Example in Python: Using os Module
Python simplifies system calls further with the os module:
import os
fd = os.open("example.txt", os.O_RDONLY)
buffer = os.read(fd, 128)
print(f"Read {len(buffer)} bytes: {buffer.decode()}")
os.close(fd)How System Calls Work Under the Hood
User Space Invocation:
The program calls a function (
read()in C oros.read()in Python).
Transition to Kernel Space:
The function uses a special CPU instruction to switch to kernel mode.
Kernel Mode Execution:
The kernel performs the requested operation, like reading data from a file.
Return to User Space:
The kernel returns the result to the user program.
Simplifying Interactions
System calls make it easier to perform complex operations by:
Abstracting hardware interactions.
Controlling access to resources.
Standardizing operations across different systems.
Conclusion
System calls provide a secure, standardized way for higher-level languages to interact with the kernel, making complex tasks like file I/O straightforward and safe. They bridge the gap between user-friendly programming languages and the critical, low-level functions of the operating system.
r/StackoverReddit • u/Livid-Salamander-949 • Jun 13 '24
What language now ?
I find myself using a lot of python and bash , not out of preference but out of need and practicality of solving challenges and augmenting my computer usage and workflow to be more efficient with various tasks. Often I make scripts and apps revolving around ai, automation , data collection / analysis for finance and business context, I use the terminal a lot. And I dabble in embedded systems(raspberry pi/arduino etc)but I’d like to learn those things slowly with the aforementioned being my main interests . With all this in mind I’m curious about what types of languages should I try to learn for practical reasons chiefly and for educational reasons secondly . Any insights or comments are welcome 🤗
r/StackoverReddit • u/[deleted] • Jun 12 '24
Do you guys know sites like LeetCode with slightly more C-friendly problems?
So I'm using LeetCode to prepare for an exams on Algorithms and Datastructures. The course was based on CLRS and the problems from previous exams are in fact problems that I found also on LeetCode, such as EditDistance or Merging two Binary Search Trees.
The main difference is that the problems they give us are slightly more focused on implementing the algorithm and less on dealing with C. Don't get me wrong, I don't mind quickly coding up a little HashTable so I can solve a problem that takes O(n^2) time complexity in O(n) time by sacrificing O(n) spae but it gets annoying when I feel like some problems are clearly easier to solve in another language than C...
So yeah, I was wondering if there is a site that features a lot of problems, has tests to verify your solution and gives you template, i.e., the function you have to provide, which is slightly more C-friendly and doesn't force you figure out more C-related stuff, forcing you more to think about the algorithm and less about the specific implementation.
EDIT:
I ended up sticking with LeetCode because I realized implementing my own stack/queues/heaps helped me to review pointers and algorithm parts such as heapify from heapSort which I can implement from my head although I never actively tried to learn it by heart, I just kind had to get used to it since I needed heaps for some problems and had to make my own quickly. I also made my own hashMap which was a massive pain to do but it was satisfying to see it work and pass all the LeetCode tests like on first try.
r/StackoverReddit • u/Swimming_Tangelo8423 • Jun 11 '24
Javascript Developing a function that downloads a Pupeeter PDF to the user's device when clicking a button
Context for my app: I am creating an app that allows suers to tailor their resumes, they send their resume via text and a job description and an AI model will send back the tailored version as HTML code which then gets made into a pdf by pupeeteer, the user ```resume as text```, the ```job description``` and the ```ai_output``` are all saved as a row in. a database and this is called a 'scan', visiting each scan page will give information about that certain scan, e.g the ```resume as text```, the ```job description``` and so on . The user may come back and find the scans that he done.
I have managed to create a function that converts HTML into PDF by using Pupeteer, i followed the docs and it creates a whole new file in my directory with the result pdf but i do not want that, i need to make it so that the file is downloadable when clicked 'Download', i also need to upload this file to my db so that it can be retrieved after from a database and pressing the same download (in that scan page) button will download the same file. (What is your go to solution when handling file uploads into db and retrieving it?)
My current tech stack: Next.js, Supabase, Clerk, TypeScript
here is the function that generate html code into a pdf, how can i make this file downloadable too before uploading it to a database
const scan = await findScanById(params.scanId);
const generatePDF = async ({ htmlContent }: { htmlContent: string }) => {const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(htmlContent, { waitUntil: "domcontentloaded" });
await page.emulateMediaType("screen");
const pdfBuffer = await page.pdf({margin: { top: 0, right: 0, bottom: 0, left: 0 }, // Set all margins to 0printBackground: true,format: "A4",});
await browser.close();
return pdfBuffer;};
generatePDF({ htmlContent: scan[0].ai_output });
r/StackoverReddit • u/Ok-Weather1767 • Jun 11 '24
Has anyone worked with Janus Automation Integrators?
I am currently an aspiring level 2 software engineer helping commission a new line. I am curious if anyone has had experience working with Janus Automation. I want to prep myself so I am ready to work with and maintain/improve the level 2 system once it is up and running the process. The problem I am running into is getting information on their proprietary real-time database software. It is called “Rodeo Automation Suite”. In addition I am curious what programming languages I should be learning to be prepped for working with this kind of system. I know there will be more than one sql database, but not exactly sure what kind of SQL database it will be. Any pointers or advice/follow-up questions are appreciated. I am here to learn whatever I can to learn and improve.
r/StackoverReddit • u/Mysterious-Stock5125 • Jun 11 '24
Question How do I interpret GitHub CodeQL CLI results?
It's my first time trying out CodeQL. I've setup a few Python scripts for analysis via the CLI. I ran the create database command and analyze command with a queries that look for the top 25 CWEs by MITRE, and specified that the results should be a CSV file. My issue is interpreting the results. The severity levels I got are only {'error', 'warning'}. I expected {'critical', 'high', 'medium', 'low'}. I read https://github.blog/changelog/2021-07-19-codeql-code-scanning-new-severity-levels-for-security-alerts/ and https://docs.github.com/en/code-security/code-scanning/managing-code-scanning-alerts/about-code-scanning-alerts but I'm still not clear on what these results mean. Are 'error' and 'warning' necessarily about security here? I am only interested in security vulnerabilities and I only used queries that look specifically for CWEs. My assumption based on what I read is that error = {critical and high} and warning = {medium and low} and note = none.
r/StackoverReddit • u/ContestExtra7998 • Jun 11 '24
Does anybody know of a method to extract SpeechT5-TTS compatible X-Vector's from a GMM?
TTS - Pastebin.com it works perfectly until it tries to pass the X-vectors to the SpeechT5 model. I wanted to use a GMM because you can blend multiple speaker embeddings into one GMM but I am open to any ideas you guys have if that is just not possible.
r/StackoverReddit • u/shhh-5977 • May 12 '25
Question How do we define a list of lists in protobuf of grpc
Example: [[1,2 ,[3,4]] , I tried this https://codingtechroom.com/question/how-to-define-a-list-of-lists-in-google-protocol-buffers-protobuf- But i didn't work for me I also tried using the listvalues that also didn't work. I tried like 20 times but nothing worked. Please help me with this.
r/StackoverReddit • u/hi_i_m_here • Apr 15 '25
C C threading
Hi I am learning networking and I am getting pretty cofterbole but I don't fully good at this yet but to my understanding when I am learning networking I sould learn how to use different therdes to make the server faster and handle connections better but I don't know therding should I learn them both at the same time or should I get better at networking and then learn therding
r/StackoverReddit • u/[deleted] • Jan 03 '25
CSS Can anyone teach me how to use css selectors
I am very confused
r/StackoverReddit • u/cluxes • Dec 07 '24
C Question: strace & ltrace
Hi, I've been working on a file daemond for a while now, git_link. The daemond runs smoothly understand normal circumstances. However, if its ran with strace, it runs into a segfault and the segfault is even more frequent when ran with ltrace.
QUESTION: Could this segmentation fault be as a result of the interruptions performed by strace and ltrace while running the application?
NB: Documentation of this project is really old and needs updating.
r/StackoverReddit • u/FickleSwordfish8689 • Sep 18 '24
Question Having issues with Prism js Autoloader
so i'm basically trying to use prism js for syntax highlighting of my code blocks in my vscode extension webview but it's not working,the question with all the code snippets are documented in details in this stackoverflow question :
r/StackoverReddit • u/ENSainETY • Aug 07 '24
C# Let's Learn It!: Video 2 of Akka.Net
Hail and well met! I'm doing another stream this Thursday (8/8) starting at 7pm CST. I'll be walking through Akka .Net again with the Akka.Restaurant project. We'll need to finish the overall walkthrough and do some cleanup.
Youtube: https://youtube.com/live/s2F5XBAuQm4?feature=share
Twitch: https://www.twitch.tv/sir_codesalot/schedule?seriesID=2af7f593-6ebb-45d5-a114-d2c271911a8d
Repository: https://github.com/briansain/Akka.Restaurant
r/StackoverReddit • u/SnooGoats1303 • Aug 06 '24
Question Facebook Graph API 20.x (x, the unknown quantity)
So I create an App. I get an access_token, specifying "pages_read_engagement". For good measure, using my app-id and app-secret, I get a long term token. I then make a simple request
curl -i -X GET "https://graph.facebook.com/v20.0/100057751132253?access_token=REDACTED"and I get the response
{"error":{"message":"Unsupported get request. Object with ID '100057751132253' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api","type":"GraphMethodException","code":100,"error_subcode":33,"fbtrace_id":"AGSkkLP2xPncRE9SS4nAMZT"}}Now I happen to know that 100057751132253 resolves to KevinMichelMLA, a state-level politician in the Australian state of Western Australia. As far as I can tell, his profile is public. And I have at least one of the required permissions. What else am I missing?
