Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
Recursive mathematical and list functions in Haskell
Defines various recursive functions for summation, power calculations, and list operations in Haskell, including sums over ranges, power com...
module Gyak05 where
sumTo :: Integer -> Integer
sumTo x
| x <= 0 = 0
| otherwise = x + sumTo (x-1)
sumBetweenHelper :: Integer -> Integer -> Integer
sumBetweenHelper n m
| n == m = n
| otherwise = sumBetweenHelper n (m-1) + m
Guest class managing prizes in a game
Defines a Guest class that tracks a guest's name and the prizes (gifts) they have won, allowing addition of prizes and calculating the total...
using System;
using System.Collections.Generic;
namespace HF10
{
internal class Guest
{
private string name;
private List<Gift> prizes;
public string Name
{
get { return name; }
}
Singleton Pattern in C#
Defines a singleton class with a static instance method ensuring a single object and a method returning a fixed integer.
namespace HF10
{
internal class S : ISize
{
private static S instance = null;
private S()
{
}
public static S Instance()
{
if (instance == null)
{
Egyszerű HTML oldal alapértelmezett címkékkel
Ez a HTML kód létrehoz egy alap weboldalt egy fejléccel és egy bekezdéssel.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Center.cs
using System;
using System.Collections.Generic;
namespace HF07
{
internal class Center
{
private List<Bank> bankok;
public Center(List<Bank> bankok)
{
this.bankok = bankok;
}
ATM.cs
using System;
namespace HF07
{
internal class ATM
{
private string location;
private Center center;
public ATM(string location, Center center)
{
this.location = location;
this.center = center;
Simple React Footer
A basic React functional component for a website footer.
import React from 'react';
const Footer = () => {
return (
<footer style={{
textAlign: 'center',
padding: '1rem',
backgroundColor: '#f1f1f1',
position: 'fixed',
bottom: 0,
width: '100%'
}}>
ATM class handling transaction
Models an ATM linked to a location that verifies a PIN and processes a withdrawal transaction through a central system.
using System;
namespace HF07
{
internal class ATM
{
private string location;
private Center center;
public ATM(string location, Center center)
{
this.location = location;
this.center = center;
Write binary data to a file
This snippet writes UTF-8 encoded text data with a null byte separator into a binary file using .NET file and text encoding classes.
$text = "CodShot binary rejection test" + [char]0 + "This should be rejected by the backend.";
[System.IO.File]::WriteAllBytes("codshot-import-test-binary.js", [System.Text.Encoding]::UTF8.GetBytes($text))
Bank transaction and balance handling
Manages transactions across multiple banks and retrieves account balances by card or account number.
using System;
using System.Collections.Generic;
namespace HF07
{
internal class Center
{
private List<Bank> bankok;
public Center(List<Bank> bankok)
{
this.bankok = bankok;
}
Counter generator in Python
This Python generator function yields numbers from 1 up to a given number, then prints them.
def count_up_to(n):
count = 1
while count <= n:
yield countdfrgdf
count += 1
## original
for num in count_up_to(5):
print(num)
Load PHPMailer Library Once
This function loads the three essential PHPMailer files only once to prevent multiple inclusions during execution.
<?php
function mailer_require_phpmailer(): void
{
static $loaded = false;
if ($loaded) {
return;
}
$base = APP_PATH . '/libraries/PHPMailer/src';
require_once $base . '/Exception.php';
require_once $base . '/PHPMailer.php';
Simple PHP Router with Dynamic User ID Route
This code implements a basic PHP router that directs static URLs to specific files and handles dynamic user ID routes, returning a 404 error...
<?php
$routes = [
'/' => 'home.php',
'/about' => 'about.php',
'/user' => 'user.php'
];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
function handleRoute($uri, $routes)
{
if (array_key_exists($uri, $routes)) {
Responsive Bootstrap Product Card
A modern responsive product card built with Bootstrap 5, featuring a hover animation and a call-to-action button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Card</title>
<!-- Bootstrap -->
Fetch Active Users
Fetches users from an API and returns only those who are active using async/await and ES6+ syntax.
const fetchActiveUsers = async (url) => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const users = await response.json();
Simple Login Form
A basic HTML form for user login with username and password fields.
<form action="/login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
Print numbers from 1 to 5
This Java program uses a for loop to print numbers from 1 to 5 on the console.
public class SimpleLoop {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Language Detection and Translation Loader
Manages front-end language detection, session and cookie handling, and loads language translation scopes from PHP files with fallback suppor...
<?php
declare(strict_types=1);
// ------------------------------------------------------------
// Global language code list
// ------------------------------------------------------------
if (!defined('ALLOWED_LANG_CODES')) {
Debounced Search Input Handler
Implements a debounced search input handler that delays API calls until the user stops typing for 500ms, reducing unnecessary requests.
function debounce(func, delay = 300) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
Modern JavaScript User Loader
Loads and manages users asynchronously from an API, providing methods to find users by ID and render the user list in the DOM.
let users = [];
let isLoading = false;
class User {
constructor(id, name, email) {
this.id = id;
this.name = name;
this.email = email;
}
getDisplayName() {
return `${this.name} (${this.email})`;
}
}
FAQ Section Markup
A simple FAQ section using semantic HTML and details/summary elements.
<section class="faq-section" aria-labelledby="faq-title">
<h2 id="faq-title">Frequently asked questions</h2>
<details>
<summary>Can I use CodShot for free?</summary>
<p>Yes. The free plan is a good way to try the platform.</p>
</details>
Simple React Component
A basic functional React component displaying a greeting message.
import React from 'react';
function Greeting() {
return <h1>Hello, welcome to CodShot!</h1>;
}
export default Greeting;
Cross-Tab State Sync with BroadcastChannel
Synchronize lightweight UI state between tabs from the same origin.
const channel = new BroadcastChannel('app-preferences');
const preferences = {
theme: 'dark',
compactMode: true,
};
channel.addEventListener('message', (event) => {
if (event.data?.type !== 'preferences-updated') {
return;
}
Promise-Based IndexedDB Key-Value Store
Store structured values in IndexedDB with a small promise-based wrapper.
const databaseName = 'app-cache';
const storeName = 'key-value';
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(databaseName, 1);