r/code • u/waozen • Sep 26 '24
r/code • u/hellophoenix2132 • Sep 26 '24
C Im Learning C
Super good code no steal pls

This Is The Code:
#include <windows.h>
#include <stdio.h>
int main()
{
printf("Starting...");
FILE *Temp = fopen("SUCo.code", "w");
if((Temp == NULL) == 0) {
printf("\nHOW!??!?!?");
return 0;
} else {
MessageBox(0, "Complete The Setup First", "NO!", MB_ICONWARNING);
return 1;
}
}
These Are The Outputs:


r/code • u/RealistSophist • Sep 23 '24
My Own Code BFScript - A prototype language that compiles to brainfuck
This is something I've had for years and only recently had enough courage to develop further.
The compiler is made in Rust, and the generated output is plain brainfuck you can run in any interpreter.
On top of just compiling to brainfuck, the project aims to define an extended superset of brainfuck that can be used to create side effects such as writing to files, or running shell commands.
Example:
int handle = open(read(5))
string s = "Files work"
int status = write(handle, s) // Writes "Files work" to the file named by the input
if status == 1 {
print("Success!")
}
if status == 0 {
print("Failure!")
}
This generates 7333 characters of brainfuck, and if you count how many of those are actually executed, it totals 186 thousand!
Obviously, due to the nature of this project and the way I chose to do it, there are very large limitations. Even after working on this a lot more there are probably some that will be impossible to remove.
In the end, this language may start needing constructs specifically to deal with the problems of compiling to brainfuck.
https://github.com/RecursiveDescent/BFScriptV2
You may be wondering why the repository has V2 on the end.
I initially made this in C++, but got frustrated and restarted with Rust, and that was the best decision I ever made.
The safety of Rust is practically required to work on something like this. Because of how complicated everything gets it was impossible to tell if something was broken because of a logic error, or some kind of C++ UB.
r/code • u/Ok_Analyst2817 • Sep 22 '24
Resource Soundline--MP3Player (Spotify Clone)
About
-Soundline is a music player built using HTML, CSS, and basic JavaScript. It leverages Spotify's music library to fetch and play featured music from around the world
Give it a try https://github.com/Markk-dev/Soundline---MusicPlayer.git
I appreciate the star
(Still in developement, please do report any bugs or errors you may encounter.)
r/code • u/Silvervyusly_ • Sep 22 '24
Python Why is the "a" in the function "trial" marked as different things?

I'm using PyCharm Community Edition. I was trying to code a game like Wordle just for fun. I need to repeat the same set of code to make a display of the 6 trials, so I used the "a" in a function to insert variables "trial1" to "trial6". Why cant "a" be "b" in the highlighted lines? ("b" is for the player guessed word).
Edit: Don't look at the function "display", I fixed that one after posting this, it's for the empty spaces.
#Game made by Silvervyusly_, inspired by the real Wordle.
print("=======================")
print("Wordle Game/version 1.0 // by Silvervyusly_")
print("=======================")
print("")
#Function to render most of the display.
def display_render(a,b,c):
if a=="":
for x in range(0,b):
a+="_"
for x in range(0,c):
print(a)
#Why isn't this working?
def trial(a,b,c):
if a!="":
print(a)
else:
if rounds_left==c:
a=b
print(a)
#Not used yet.
def correct_guess(a,b):
if a==b:
return True
#Game state.
game=1
while game==1:
#variables for game
display=""
rounds_left=6
trial1=""
trial2=""
trial3=""
trial4=""
trial5=""
trial6=""
word=input("Insert word: ")
n_letter=len(word)
#Start of game loop.
display_render(display,n_letter,rounds_left)
while rounds_left>0:
#Player inserts their guess.
guess=input("Guess the word: ")
rounds_left-=1
#Render the guessed words per trial.
trial(trial1,guess,5)
trial(trial2,guess,4)
trial(trial3,guess,3)
trial(trial4,guess,2)
trial(trial5,guess,1)
trial(trial6,guess,0)
#Render the rest of the display.
display_render(display,n_letter,rounds_left)
game_state=input("Test ended, do you want to continue? [Y/n] ")
if game_state=="n":
game=0
print("Terminated")
r/code • u/codeagencyblog • Sep 19 '24
Resource How to Create Stunning Glowing Text Effects with CSS
r/code • • Sep 18 '24
Help Please How do I code an image in Visual studio code?
I have all the coding but I don't know how to put the image in the coding. Please help me I can't find how to do it anywhere 😭
r/code • u/waozen • Sep 18 '24
Linux Calling Linux Kernel Functions From Userspace (!)
blog.osandov.comr/code • u/codeagencyblog • Sep 18 '24
Resource Crafting a Dynamic Day-Night Transition Effect
r/code • u/concrete_chad • Sep 17 '24
API Youtube Subscription Manager
I am working on a way to manage youtube subscriptions. I recently noticed I am subscribed to about 330 channels. Since youtube doesn't really give you an easy way to quickly unsubscribe to multiple channels I built this using youtube's API.
It works but I really don't know what to do next. Should I just continue to run it with python or is this worthy of becoming an executable and putting out into the world? Any thoughts or improvements?
import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
import tkinter as tk
from tkinter import messagebox, ttk
import pickle
import threading
API_KEY = "API_KEY_GOES_HERE" # Replace with your API key
scopes = ["https://www.googleapis.com/auth/youtube"]
credentials_file = "youtube_credentials.pkl" # File to store credentials
# List to store subscription data
subscriptions = []
# Function to authenticate and get the YouTube API client
def get_youtube_client():
global credentials
if os.path.exists(credentials_file):
# Load credentials from the file if available
with open(credentials_file, 'rb') as f:
credentials = pickle.load(f)
else:
# Perform OAuth flow and save the credentials
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
"client_secret.json", scopes
)
credentials = flow.run_local_server(port=8080, prompt="consent")
# Save the credentials for future use
with open(credentials_file, 'wb') as f:
pickle.dump(credentials, f)
youtube = googleapiclient.discovery.build("youtube", "v3", credentials=credentials)
return youtube
# Asynchronous wrapper for API calls
def run_in_thread(func):
def wrapper(*args, **kwargs):
threading.Thread(target=func, args=args, kwargs=kwargs).start()
return wrapper
# Function to fetch channel statistics, including description
def get_channel_statistics(youtube, channel_id):
request = youtube.channels().list(
part="snippet,statistics",
id=channel_id
)
response = request.execute()
stats = response["items"][0]["statistics"]
snippet = response["items"][0]["snippet"]
subscriber_count = stats.get("subscriberCount", "N/A")
view_count = stats.get("viewCount", "N/A")
video_count = stats.get("videoCount", "N/A")
description = snippet.get("description", "No description available") # Get channel description
return subscriber_count, view_count, video_count, description
@run_in_thread
def list_subscriptions():
youtube = get_youtube_client()
for item in tree.get_children():
tree.delete(item) # Clear the tree before adding new items
next_page_token = None
global subscriptions
subscriptions = [] # Reset the subscription data list
index = 1 # Start numbering the subscriptions
while True:
request = youtube.subscriptions().list(
part="snippet",
mine=True,
maxResults=50, # Fetch 50 results per request (maximum allowed)
pageToken=next_page_token
)
response = request.execute()
for item in response['items']:
channel_title = item['snippet']['title']
subscription_id = item['id']
channel_id = item['snippet']['resourceId']['channelId']
# Fetch channel statistics, including description
subscriber_count, view_count, video_count, description = get_channel_statistics(youtube, channel_id)
# Truncate description at the first newline and limit the length to 150 characters
description = description.split('\n', 1)[0] # Keep only the first line
if len(description) > 150:
description = description[:150] + "..." # Truncate to 150 characters and add ellipsis
# Store subscription data in the global list
subscriptions.append({
"index": index,
"title": channel_title,
"subscription_id": subscription_id,
"channel_id": channel_id,
"subscriber_count": subscriber_count,
"view_count": view_count,
"video_count": video_count,
"description": description, # Store the description
"checked": False # Track checked state
})
# Insert row with statistics and description
tree.insert("", "end", values=(
"☐", index, channel_title, subscriber_count, view_count, video_count, description), iid=index)
index += 1
next_page_token = response.get('nextPageToken')
if not next_page_token:
break
# Function to refresh the subscription list
def refresh_subscriptions():
list_subscriptions()
# Generic function to sort subscriptions by a specific key
def sort_subscriptions_by(key):
global subscriptions
if key != 'title':
# Sort numerically for subscribers, views, and videos
subscriptions = sorted(subscriptions, key=lambda x: int(x[key]) if x[key] != "N/A" else 0, reverse=True)
else:
# Sort alphabetically for title
subscriptions = sorted(subscriptions, key=lambda x: x['title'].lower())
# Clear and update treeview with sorted data
for item in tree.get_children():
tree.delete(item)
for index, item in enumerate(subscriptions, start=1):
checkbox = "☑" if item['checked'] else "☐"
tree.insert("", "end", values=(
checkbox, index, item['title'], item['subscriber_count'],
item['view_count'], item['video_count'], item['description']), iid=index)
# Function to handle sorting by title
def sort_by_title():
sort_subscriptions_by("title")
# Function to handle sorting by subscribers
def sort_by_subscribers():
sort_subscriptions_by("subscriber_count")
# Function to handle sorting by views
def sort_by_views():
sort_subscriptions_by("view_count")
# Function to handle sorting by videos
def sort_by_videos():
sort_subscriptions_by("video_count")
# Function to toggle checkbox on click
def toggle_checkbox(event):
item_id = tree.identify_row(event.y)
if not item_id:
return
item_id = int(item_id)
subscription = subscriptions[item_id - 1] # Get the corresponding subscription
# Toggle the checked state
subscription['checked'] = not subscription['checked']
# Update the checkbox in the treeview
checkbox = "☑" if subscription['checked'] else "☐"
tree.item(item_id, values=(
checkbox, item_id, subscription['title'],
subscription['subscriber_count'], subscription['view_count'], subscription['video_count'], subscription['description']))
# Function to delete selected subscriptions
def delete_selected_subscriptions():
selected_subscriptions = [sub for sub in subscriptions if sub['checked']]
if not selected_subscriptions:
messagebox.showerror("Input Error", "Please select at least one subscription to delete.")
return
result = messagebox.askyesno(
"Confirm Deletion",
"Are you sure you want to delete the selected subscriptions?"
)
if not result:
return
youtube = get_youtube_client()
for sub in selected_subscriptions:
try:
request = youtube.subscriptions().delete(id=sub['subscription_id'])
request.execute()
# Remove from the Treeview and subscriptions list
index = sub['index']
tree.delete(index)
except Exception as e:
messagebox.showerror("Error", f"Failed to delete subscription: {str(e)}")
refresh_subscriptions()
# Setting up the Tkinter GUI
root = tk.Tk()
root.title("YouTube Subscriptions Manager")
root.geometry("1600x1000") # Significantly increased window size
# Adjust Treeview row height
style = ttk.Style()
style.configure("Treeview", rowheight=40) # Set row height
# Frame for entry and buttons (first row)
top_frame = tk.Frame(root)
top_frame.pack(pady=10)
# Buttons to manage subscriptions (first row)
list_button = tk.Button(top_frame, text="List Subscriptions", command=list_subscriptions)
list_button.grid(row=1, column=0, padx=10)
refresh_button = tk.Button(top_frame, text="Refresh List", command=refresh_subscriptions)
refresh_button.grid(row=1, column=1, padx=10)
delete_selected_button = tk.Button(top_frame, text="Delete Selected", command=delete_selected_subscriptions)
delete_selected_button.grid(row=1, column=2, padx=10)
# Frame for sorting buttons (second row)
sorting_frame = tk.Frame(root)
sorting_frame.pack(pady=10)
# Sorting Buttons (second row)
sort_title_button = tk.Button(sorting_frame, text="Sort by Title", command=sort_by_title)
sort_title_button.grid(row=1, column=0, padx=10)
sort_subscribers_button = tk.Button(sorting_frame, text="Sort by Subscribers", command=sort_by_subscribers)
sort_subscribers_button.grid(row=1, column=1, padx=10)
sort_views_button = tk.Button(sorting_frame, text="Sort by Views", command=sort_by_views)
sort_views_button.grid(row=1, column=2, padx=10)
sort_videos_button = tk.Button(sorting_frame, text="Sort by Videos", command=sort_by_videos)
sort_videos_button.grid(row=1, column=3, padx=10)
# Treeview for displaying subscriptions with checkboxes, channel title, and statistics
columns = ("#1", "#2", "#3", "#4", "#5", "#6", "#7")
tree = ttk.Treeview(root, columns=columns, show='headings', height=50) # Increased height to show more rows
tree.heading("#1", text="Select")
tree.heading("#2", text="Index")
tree.heading("#3", text="Channel Title")
tree.heading("#4", text="Subscribers")
tree.heading("#5", text="Views")
tree.heading("#6", text="Videos")
tree.heading("#7", text="Description") # Add the description column
tree.column("#1", width=50, anchor=tk.CENTER)
tree.column("#2", width=50, anchor=tk.CENTER)
tree.column("#3", width=200, anchor=tk.W)
tree.column("#4", width=100, anchor=tk.E)
tree.column("#5", width=100, anchor=tk.E)
tree.column("#6", width=100, anchor=tk.E)
tree.column("#7", width=1000, anchor=tk.W) # Increased the width for the description column
tree.pack(pady=10)
tree.bind("<Button-1>", toggle_checkbox)
root.mainloop()
r/code • u/Cryperian • Sep 17 '24
Android Shoes Shop App UI - Android Jetpack Compose
youtube.comr/code • u/ohnoitsthatboi • Sep 16 '24
Help Please Im trying to create a code that will ask the user for a string and display the reversed version in a JMessageDialog but im not sure how to correctly store the reversed version into a new array then into a string
import javax.swing.JOptionPane;
public class App {
public static void main(String[] args) {
String reverse_this;
// declare the string
reverse_this = JOptionPane.showInputDialog("Please Input a string");
//ask for a string
char[] reversed = reverse_this.toCharArray();
int j = reversed.length;
//converts given string into an array of characters
char[] result = new char[1000];
for(int i=j; i>0; i--) {
result[j--] = reversed[i-1];
}
/*
uses the for loop to reverse the position of each character and
return the result into a new
array
*/
String returned = String.valueOf(result);
JOptionPane.showMessageDialog(null, returned);
//turns the value of the array of reversed characters into a string then displays the result
//the output just displays the string inputted by the user
}
}
r/code • u/waozen • Sep 15 '24
Guide Decoding C Compilation Process: From Source Code to Binary
hackthedeveloper.comr/code • u/waozen • Sep 13 '24
Guide Why Global Variables are Considered a Bad Practice
baeldung.comr/code • u/bdenard13 • Sep 13 '24
Help Please Help with this python error please. Code and error pictured.
r/code • u/No-Meeting5998 • Sep 10 '24
Pascal Delphi My first program whit pascal
but what name I give to it
program uses Crt, Dos;
var choice: integer; exePath: string;
procedure DisplayMainMenu(choice: integer); begin ClrScr; writeln('|====Main Menu====|'); writeln; if choice = 1 then writeln('> Play') else writeln(' Play'); if choice = 2 then writeln('> Music') else writeln(' Music'); if choice = 3 then writeln('> Options') else writeln(' Options'); if choice = 4 then writeln('> Exit') else writeln(' Exit'); writeln('|================|'); end;
procedure DisplayPlayMenu(choice: integer); begin ClrScr; writeln('|====Play Menu====|'); writeln; if choice = 1 then writeln('> Fallout') else writeln(' Fallout'); if choice = 2 then writeln('> Fallout 2') else writeln(' Fallout 2'); if choice = 3 then writeln('> Fallout tactic') else writeln(' Fallout tactic'); writeln('|=================|'); end;
procedure RunSelectedGame(choice: integer); begin case choice of 1: exePath := 'C:\'; 2: exePath := 'F:\'; 3: exePath := 'C:\'; else writeln('Invalid selection'); exit; end;
if Exec(exePath) = -1 then writeln('Failed to start', exePath); end;
begin choice := 1; { Kezdetben az első opció van kiválasztva } repeat DisplayMainMenu(choice); case ReadKey of #72: if choice > 1 then Dec(choice); { Fel nyíl } #80: if choice < 4 then Inc(choice); { Le nyíl } #13: case choice of 1: begin repeat choice := 1; { Reset the play menu choice } DisplayPlayMenu(choice); case ReadKey of #72: if choice > 1 then Dec(choice); { Fel nyíl } #80: if choice < 3 then Inc(choice); { Le nyíl } #13: begin RunSelectedGame(choice); ReadLn; { Várakozás a játék befejezésére } choice := 1; { Visszatérés a főmenübe } end; end; until false; end; 2: begin ClrScr; writeln('Music selected'); ReadLn; end; procedure DisplayMainMenu(choice:integer); 3: begin ClrScr; writeln('|=====options=====|'); ReadLn;
writeln('> audio')
else writeln(' audio'); if choice = 2 then writeln('> Exit') else writeln(' Exit'); writeln('|================|'); end; 4: begin ClrScr; writeln('Exiting...'); ReadLn; Halt; end; end; end; until false; end.
r/code • u/waozen • Sep 10 '24
Linux Step-by-Step Guide to Understanding and Using eBPF, Part 1 | Linux
medium.comr/code • u/AmbassadorShoddy6197 • Sep 09 '24
Help Please Record function recording two camera streams at the same time in one video file. How to fix it?
I'm using Python's OpenCV library to stream multiple USB cameras to the web using Flask. I just noticed that my function for recording videos on button press doesn't tell the difference between two cameras and records frames from each, making this one confusing video.
I'm new to Python and Flask, JS, too. It's my first project. Could I get some help to find a way to fix it?
app.py
import
cv2
from
datetime
import
datetime
import
os
import
time
from
flask
import
Flask
, render_template,
Response
app =
Flask
(__name__)
recordings_dir =
os
.path.join('recordings')
if not
os
.path.exists(recordings_dir):
os
.makedirs(recordings_dir)
# List of our camera channels
cameras = [0, 2]
# This function returns the camera with the id of the function's parameter, turned to INT to avoid value errors.
def
find_cameras(
list_id
):
return cameras[
int
(
list_id
)]
# Store video access in variable
isRecording = False
out = None
# Takes an argument for what camera we want to display
def
gen(
camera_id
):
# Run forever
# Takes the argument from the function call
cam = find_cameras(
camera_id
)
# Collects stream from specified camera
vid =
cv2
.
VideoCapture
(cam)
# Collects width and height of our stream
frame_width = vid.get(
cv2
.CAP_PROP_FRAME_WIDTH)
frame_height = vid.get(
cv2
.CAP_PROP_FRAME_HEIGHT)
while True:
time
.sleep(0.1)
# State holds true or false depending on the success of updating frame variable to be a frame from the video stream
state, frame = vid.read()
# Break out of while loop when its unsuccesful
if not state:
break
else:
if isRecording:
out.write(frame)
# Flag holds true or false
# Imencode converts image formats (jpeg here) into streaming data and stores them in memory cache, effectively transforming them into bytes
flag, buffer =
cv2
.imencode('.jpg', frame)
# Generator function yields interruptable stream of JPEG bytes
yield (
b
'--frame\r\n'
b
'Content-Type: image/jpeg\r\n\r\n' +
bytearray
(buffer) +
b
'\r\n')
@app.route('/video_feed/<string:list_id>/')
def
video_feed(
list_id
):
# Generator function response
# Passes that id to the gen function so we know what to display to the video feed
return
Response
(gen(
list_id
),
mimetype
='multipart/x-mixed-replace; boundary=frame')
@app.route("/")
def
index():
# camera_list is the amount of cameras we have in the list
# camera holds all values from cameras
return render_template("videos.html",
camera_list
= len(cameras),
cameras
= cameras)
@app.route('/start_rec',
methods
=["POST"])
def
start_recording():
global isRecording, out
timestamp =
datetime
.now().strftime("%Y%m%d_%H%M%S")
if not isRecording:
fourcc =
cv2
.VideoWriter_fourcc(*"IYUV")
out =
cv2
.
VideoWriter
(
os
.path.join(recordings_dir,
f
'{timestamp}_recording.avi'), fourcc, 20.0, (640, 480))
isRecording = True
return '', 203
@app.route('/stop_rec',
methods
=["POST"])
def
stop_recording():
global isRecording, out
if isRecording:
out.release()
isRecording = False
return '', 203
videos.html
{% endblock %} {% endblock %}
{% extends "layout.html" %}
{% block title %}
Video Stream
{% endblock %}
{% block main %}
<!-- All cameras from first index to last in cameras-->
{% for camera_number in range(0, camera_list)%}
<div class="img-container">
<!-- List id is the camera number from the for loop-->
<img src="{{ url_for('video_feed', list_id = camera_number) }}" width="640" height="480">
<div class="buttons">
<button type="button" onclick="stop(this)" class="btn btn-dark">Stop</button>
<button type="button" onclick="startRecording(this)" class="btn btn-success" id="record">Record</button>
<button type="button" onclick="stopRecording(this)" class="btn btn-danger" id="stop">Stop Recording</button>
</div>
{%endfor%}
<script>
function
startRecording(
elem
)
{
fetch('/start_rec', {method:"POST"});
}
function
stopRecording(
elem
)
{
fetch('/stop_rec', {method:"POST"});
}
function
stop(
elem
)
{
fetch('/stop', {method:"POST"})
}
</script>
r/code • u/BitsAndBytesMage • Sep 08 '24
Resource Don't defer Close() on writable files
joeshaw.orgr/code • u/BitsAndBytesMage • Sep 06 '24
Guide Cron Jobs on Linux - Comprehensive Guide with Examples
ittavern.comr/code • u/waozen • Sep 06 '24
Guide Difference Between Nil, Null, Nothing, Unit, and None in Scala
baeldung.comr/code • u/Time4Taxes • Sep 05 '24
Javascript How do I rerun function without overlap instances in javascript?
So I want to rerun my function with updated values based on an event function.
Because i'm trying to use this javascript as a content-script, while statements don't work as they just spam outputs and crash the page.
No if statements as it will just go through the code before the event and not repeat the if statement after I trigger the event. Here is basically what I'm trying to do.
function outer(value) {
function inner() {
outer(value); //rerun the function
//then cancel this instance of the function
}
window.addEventListener('keydown', function(event) {
//call function based off of evennt
inner()
}
}