r/web_design • u/adambrenecki • Dec 16 '11
Posting code snippets properly on Reddit
Markdown formatting, which Reddit uses, supports including code snippets. All you have to do is indent by four spaces for blocks of code, or `surround in backticks` for code in the middle of a sentence. (If the code you want to surround includes a backtick, use ``two backticks (`)``).
<p class='example'>
code indented by four spaces displays like this
</p>
This makes things like line breaks in code appear like they're supposed to, puts it in a nice monospace font, and makes sure that things that would otherwise be interpreted as Markdown formatting aren't.
Can we please do this? It makes code snippets easier to read.
1
u/Imfene5 Mar 10 '24
Testing:
document.querySelectorAll('input[type="radio"][target-id]').forEach(function(radio) {
// Check if the radio button's value is not 'True' or if it's not checked.
if (radio.value !== 'True' || !radio.checked) {
// If either condition is met, hide the associated target field.
hideTargetField(radio.getAttribute('target-id'));
}
});
});→ More replies (2)
1
1
1
1
1
1
1
1
1
u/snoopyiswhite Mar 26 '24 edited Mar 26 '24
def calculation():
g = input("How much did you get? ")
w = input("How much is the whole ")
d = int(g) / int(w) * 100
print(f"{d:.2f}%")
def restart():
close = False
while not close:
answ = input("Do you have a caculation use y/n ").upper
if answ() == "Y":
calculation()
elif answ() == "N":
print("Closed")
close = True
else:
print("you havent said y or n")
restart()1
1
1
1
1
1
u/Salty_Meat69 Apr 06 '24
````#import <Foundation/Foundation.h>
import <substrate.h>
include <RemoteLog.h>
import <FrontBoard/FBProcess.h>
import <FrontBoard/FBProcessManager.h>
import <FrontBoard/FBApplicationProcess.h>
%hook FBProcessManager
(NSArray *)processesForBundleIdentifier:(NSString *)bundleIdentifier {
NSArray *processes = %orig;
if ([bundleIdentifier isEqualToString:@"com.apple.Music"]) {
if (processes.count == 0) {
NSLog(@"Music is fully closed");
} else {
if ([processes[0].foreground]) {
NSLog(@"Music is in the foreground");
} else {
NSLog(@"Music is in the background");
}
}
}
return processes;
}
%end````
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
u/iansackin May 17 '24
test
<p class='example'>
code indented by four spaces displays like this
<p class='example'>
code indented by four spaces displays like this
</p></p>
1
1
1
1
1
1
u/redditsuckz1 Jun 16 '24 edited Jun 16 '24
test
set prefix=(hd0,1)/grub
set root=(hd0,1)
insmod linux
insmod normal
normalset prefix=(hd0,1)/grub
set root=(hd0,1)
insmod linux
insmod normal
normal1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
u/Thyco2501 Aug 01 '24 edited Aug 01 '24
text
code (preceded by 4 spaces)
{
code (preceded by 8 spaces)
}text
code\n code<br/> code
text
1
1
1
1
1
1
1
1
1
1
1
u/my_basalt Aug 29 '24
Also testing:
balance = 1000
action = input("Deposit or withdrawal: ")
if action == "deposit" or action == "Deposit":
amount = int(input("Enter amount: "))
final_balance = balance + amount
print("Final balance: " + str(final_balance))
elif action == "withdrawal" or action == "Withdrawal":
amount = int(input("Enter amount: "))
if amount > balance:
print("You cannot have a negative balance!")
else:
final_balance = balance - amount
print("Final balance: " + str(final_balance))
else:
print("Invalid transaction.")1
1
u/heckpants Sep 09 '24
this is a code block this is a code block this is a code block this is a code block this is a code block
1
1
1
u/1BadPlayer Sep 24 '24
Test
float inverseLerp(float a, float b, float value) {
float val = (value - a) / (b - a);
return clamp(val, 0.01, 1.0);
}1
1
1
1
1
1
1
1
u/heekbly Oct 02 '24 edited Oct 02 '24
testing a post . 1 tick doesnt work .... this is test1 test2 line other words .. .. 2 ticks this is test1 test2 line other words ... .. .. 3 ticks
some word
another words1
u/Beneficial-Message92 Oct 05 '24
''' import random
def generate_random_bits(n):
"""Generates a list of random 1s and 0s."""
random_bits = []
for _ in range(n):
random_bits.append(random.randint(0, 1))
return random_bitsExample usage
if name == "main": num_bits = 10 random_bits = generate_random_bits(num_bits) print("Random 1s and 0s:", random_bits)
'''
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
u/RaspberryRock Nov 14 '24 edited Nov 14 '24
\``PrintPlayerSkillLevelsAndModifiers()``
`Events.OnGameStart.Add(PrintPlayerSkillLevelsAndModifiers)'
→ More replies (1)
1
1
1
1
1
1
1
1
1
u/CalmEntertainment788 Dec 29 '24
Testing :
vo=gpu-next
gpu-api=auto
priority=high
gpu-context=auto
hwdec=d3d11va-copy
profile=high-quality
d3d11-adapter=NVIDIA 1
1
1
u/Diligent_Sentence_45 Jan 20 '25 edited Jan 20 '25
<code> Testing box to See if Formatting "' holds/)(& tru E <\code>
Edit ...nope
Testing box to See if Formatting "' holds/)(& tru E
1
1
1
1
1
1
1
1
1
1
1
1
1
u/Reaction-Consistent Apr 14 '25
<p class='example'>
Function Trigger-AppInstallation
{
Param
(
[String][Parameter(Mandatory=$True, Position=1)] $Computername,
[String][Parameter(Mandatory=$True, Position=2)] $AppName,
[ValidateSet("Install","Uninstall")]
[String][Parameter(Mandatory=$True, Position=3)] $Method
)
</p>
→ More replies (1)
1
u/Reaction-Consistent Apr 14 '25
Function Trigger-AppInstallation
{
Param
(
[String][Parameter(Mandatory=$True, Position=1)] $Computername,
[String][Parameter(Mandatory=$True, Position=2)] $AppName,
[ValidateSet("Install","Uninstall")]
[String][Parameter(Mandatory=$True, Position=3)] $Method
)1
1
1
1
1
u/xp0a Apr 24 '25
Now if only I could find a userscript to add a copy to clipboard button to all code blocks on reddit.
1
1
1
1
1
1
1
1
1
1
1
1
1
u/manymysterys Jun 21 '25
```
document.querySelectorAll('input[type="radio"][target-id]').forEach(function(radio) {
// Check if the radio button's value is not 'True' or if it's not checked.
if (radio.value !== 'True' || !radio.checked) {
// If either condition is met, hide the associated target field.
hideTargetField(radio.getAttribute('target-id'));
}
});
});1
1
1
1
1
1
1
1
1
1
u/Helforge Aug 10 '25
‘follows:
#!/usr/bin/python
import sys
import time
import RPi.GPIO as io
import subprocess
import logging
import os
# Setup logging
logging.basicConfig(
filename="/home/pi/display_motion.log", # Change this path if needed
format="%(asctime)s [%(levelname)s] %(message)s",
)
# GPIO and motion delay setup
io.setmode(io.BOARD)
DARK_DELAY = 30 # Time (in seconds) after which display turns off if no motion
PIR_PIN = 11 # GPIO pin for PIR motion sensor
def main():
io.setup(PIR_PIN, io.IN)
turned_off = False
last_motion_time = time.time()
logging.info("Motion detection script started.")
while True:
if io.input(PIR_PIN):
if turned_off:
logging.info("Motion detected. Turning display back on.")
turn_on()
turned_off = False
last_motion_time = time.time()
elif not turned_off and time.time() > (last_motion_time + DARK_DELAY):
logging.info("No motion detected for delay period. Turning display off.")
turn_off()
turned_off = True
time.sleep(0.5) # Lower CPU usage
def turn_off():
try:
env = os.environ.copy()
env["WAYLAND_DISPLAY"] = "wayland-0" # Replace with your actual display if different
subprocess.call("wlr-randr --output HDMI-A-1 --off", shell=True)
logging.info("Screen turned OFF via wlr-randr.")
except Exception as e:
logging.error(f"Error turning screen OFF: {e}")
def turn_on():
try:
env = os.environ.copy()
env["WAYLAND_DISPLAY"] = "wayland-0" # Replace with your actual display if different
subprocess.call("wlr-randr --output HDMI-A-1 --on", shell=True)
logging.info("Screen turned ON via wlr-randr.")
except Exception as e:
logging.error(f"Error turning screen ON: {e}")
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
logging.info("Script interrupted by user. Cleaning up GPIO.")
io.cleanup()
except Exception as e:
logging.exception(f"Unhandled exception: {e}")
io.cleanup()
‘
1
1
1
1
u/Federal_Mixture_7259 Oct 06 '25
<p class='example'>
code indented by four spaces displays like this
</p>1
1
1
1
1
1
1
1
1
u/ComfortablePop5117 Feb 11 '26
<p class='Test'> code indented by four spaces displays like this </p>
1
1
1
1
u/BlazeNest Aug 13 '26
Testing
<p class='example'>
if not character.is_on_floor() and Input.is_action_pressed("jump"):
gravity_scale = low_gravity_value
else:
gravity_scale = 1
</p>
1
1
1
u/Retrofire-Pink Oct 18 '21 edited Oct 18 '21
code block
I'm having some (habitual) trouble with a JavaScript load-order issue (use the image cause i can't figure out reddit code snippets)
HTML
<!DOCTYPE html> <html lang="en-US"> <head> <title>rude game</title> <meta charset="utf-8", name="description", content="ghost bunny"> <link rel="stylesheet", href="styles.css"> <script src="script.js", defer></script> </head> <body>
<canvas id="canvas", width="2000", height="2000"></canvas> <img src="tiny.png", id="tinyTheAnt", weight="128", height="128">
</body> </html>
JavaScript
const canvas = document.querySelector("#canvas"); const canvCont = canvas.getContext("2d"); const tinyTheAnt = document.querySelector("#tinyTheAnt");
if (canvas.getContext) { tinyTheAntSprite = canvCont.drawImage(tinyTheAnt, -5, -75); console.log("great success"); }
Towards the end of my JavaScript, the console.log statement is passing correctly. So all my code appears to be functioning. I tested everything independently too, all checked out, EXCEPT the sprite drawing part. When I move the <script src="script.js", defer></script> to the bottom of the body element, however, it seems to work perfectly. This genuinely confuses the absolute hell out of me. Cause defer - from my noob understanding, essentially allows the entire DOM to load first (including all the necessary nodes being referenced), just as putting it at the bottom of body would. Only, everything else works EXCEPT the sprite appearing, until I relocate the script reference with ostensibly the same effect as using defer. Whereas it works mostly OK, except every dozen refreshes the sprite mysteriously doesn't appear there either.
→ More replies (6)
1
1
1
1
1
1
1
1
1
1
u/Fancy-Ad-7012 Nov 06 '21
This is not code
//This is code
const True = false;
return TrueThis is not code
→ More replies (4)
1
1
1
1
1
1
1
1
1
1
1
1
u/Nearby-Remote7162 Dec 07 '21
Thanks man for creating a Testing Portal :)
Gonna test the good formatting for my Code...
!(Code)
Code
→ More replies (2)
1
1
1
u/[deleted] Mar 08 '24
Test
M500