Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/?q=function&page=1374&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 18363 results for "function"(2508ms)

falDemoAppmain.tsx3 matches

@daisuke•Updated 6 months ago
5import { falProxyRequest } from "https://esm.town/v/stevekrouse/falProxyRequest";
6
7function App() {
8 const [prompt, setPrompt] = useState("");
9 const [imageUrl, setImageUrl] = useState("");
103}
104
105function client() {
106 createRoot(document.getElementById("root")).render(<App />);
107}
108if (typeof document !== "undefined") { client(); }
109
110export default async function server(req: Request): Promise<Response> {
111 const url = new URL(req.url);
112 if (url.pathname === "/") {

geminiBboxmain.tsx39 matches

@yawnxyz•Updated 6 months ago
49 import { marked } from "https://esm.run/marked";
50
51 // Add debounce function
52 function debounce(func, wait) {
53 let timeout;
54 return function executedFunction(...args) {
55 const later = () => {
56 clearTimeout(timeout);
62 }
63
64 // Combined function to fetch and handle images
65 async function fetchImage(url, options = {}) {
66 const { returnType = 'blob' } = options;
67
102 }
103
104 // Update the image preview function to use the combined fetchImage
105 async function updateImagePreview(url) {
106 const imageContainer = document.getElementById('imageContainer');
107 const canvas = document.getElementById('canvas');
118
119 const img = new Image();
120 img.onload = function() {
121 // Remove spinner and restore container
122 imageContainer.innerHTML = '<canvas id="canvas"></canvas>';
140 }
141
142 // Helper function to show error state
143 function showErrorState(canvas, ctx, message) {
144 canvas.style.display = 'block';
145 canvas.width = 400;
164 });
165
166 function handleImageUrlClick(event) {
167 console.log("IMAGE CLICK")
168 event.preventDefault();
175
176 // Retrieves the API key from local storage or prompts the user to enter it
177 function getApiKey() {
178 let apiKey = localStorage.getItem("GEMINI_API_KEY");
179 if (!apiKey) {
187
188 // Initializes and returns a Google Generative AI model instance
189 async function getGenerativeModel(params) {
190 const API_KEY = getApiKey();
191 const genAI = new GoogleGenerativeAI(API_KEY);
194
195 // Converts a file to a GenerativePart object for use with the AI model
196 async function fileToGenerativePart(file) {
197 return new Promise((resolve) => {
198 const reader = new FileReader();
208
209 // Applies a high contrast filter to the image on a canvas
210 function applyHighContrast(canvas) {
211 const ctx = canvas.getContext('2d');
212 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
233
234 // Resizes and compresses an image file, optionally applying high contrast
235 function resizeAndCompressImage(file, maxWidth = 1000) {
236 return new Promise((resolve) => {
237 const reader = new FileReader();
238 reader.onload = function(event) {
239 const img = new Image();
240 img.onload = function() {
241 const canvas = document.createElement('canvas');
242 const ctx = canvas.getContext('2d');
271
272 // Splits an image into a grid of smaller tiles
273 function splitImage(file, rows, cols) {
274 return new Promise((resolve) => {
275 const reader = new FileReader();
276 reader.onload = function(event) {
277 const img = new Image();
278 img.onload = function() {
279 const tileWidth = Math.floor(img.width / cols);
280 const tileHeight = Math.floor(img.height / rows);
314 }
315
316 // Creates a delay promise for use in async functions
317 function delay(ms) {
318 return new Promise(resolve => setTimeout(resolve, ms));
319 }
320
321 // Processes a single tile with the AI model, with retry logic
322 async function processTileWithRetry(model, tile, prompt, delayMs, maxRetries = 3) {
323 for (let attempt = 1; attempt <= maxRetries; attempt++) {
324 try {
344 }
345
346 // Main function to process the image and prompt, coordinating the entire detection process
347 async function processImageAndPrompt() {
348 const fileInput = document.getElementById('imageInput');
349 const urlInput = document.getElementById('imageUrlInput');
437
438 // Extracts coordinate data from the AI model's response text
439 function extractCoordinates(text) {
440 console.log("Raw AI response text:", text); // Log raw AI response
441
442 const cleanedText = text.replace(${markdownJsonRegex}, function(match, p1) {
443 return p1.trim();
444 });
459
460 // Displays the full image with bounding boxes drawn on a canvas
461 function displayImageWithBoundingBoxes(file, coordinates, rows, cols) {
462 const reader = new FileReader();
463 reader.onload = function(event) {
464 const image = new Image();
465 image.onload = function() {
466 const canvas = document.getElementById('canvas');
467 const ctx = canvas.getContext('2d');
515
516 // Displays a single tile with its bounding boxes and grid
517 function displayTileWithBoundingBoxes(tile, { coordinates }) {
518 const reader = new FileReader();
519 reader.onload = function(event) {
520 const image = new Image();
521 image.onload = function() {
522 const padding = 80;
523 const labelPadding = 40;
663
664 // Generates a description of the image using the AI model
665 async function getImageDescription() {
666 const fileInput = document.getElementById('imageInput');
667 const urlInput = document.getElementById('imageUrlInput');
878 </div>
879 <script>
880 function loadImage(event) {
881 const file = event.target.files[0];
882 const reader = new FileReader();
883 reader.onload = function(e) {
884 const canvas = document.getElementById('canvas');
885 canvas.style.display = 'block';
886 const ctx = canvas.getContext('2d');
887 const img = new Image();
888 img.onload = function() {
889 canvas.width = img.width;
890 canvas.height = img.height;
932 </div>
933 <script>
934 function toggleThresholdInputs() {
935 const checkbox = document.getElementById('highContrastCheckbox');
936 const thresholdInputs = document.getElementById('thresholdInputs');

countermain.tsx8 matches

@yawnxyz•Updated 6 months ago
200 let lastSavedText = ''; // Track the last saved text
201
202 function populateTextAreaFromHash() {
203 const hash = window.location.hash.slice(1); // Remove the '#' character
204 if (hash) {
209 }
210
211 async function updateCounts() {
212 const encoder = new TextEncoder();
213 const utf8 = new Uint8Array(inputText.value.length * 3);
287 }
288
289 async function tokenize() {
290 const response = await fetch('/tokenize', {
291 method: 'POST',
322 }
323
324 function adjustTextareaHeight() {
325 inputText.style.height = 'auto';
326 inputText.style.height = inputText.scrollHeight + 10 + 'px';
341 window.addEventListener('hashchange', populateTextAreaFromHash);
342
343 // Add the history functions:
344 async function updateHistoryList() {
345 const history = await db.history.reverse().limit(50).toArray();
346 historyList.innerHTML = history.map(item =>
428});
429
430function replaceEmojisWithCodePoints(text) {
431 console.log("Replacing emojis with code points:", text);
432
442}
443
444function getTiktokenSegments(encoder, inputText) {
445 try {
446 const tokens = encoder.encode(inputText);

fullWebsiteVersionmain.tsx7 matches

@willthereader•Updated 6 months ago
1async function findBrokenLinks(websiteUrl) {
2 console.log("Version: " + import.meta.url.match(/[?&]v=([^&]*)/)?.at(1));
3 console.log(`Starting findBrokenLinks for website: ${websiteUrl}`);
7 const allCheckedLinks = new Set();
8 const allBrokenLinks = [];
9 // Function to check if a URL is valid and accessible
10 async function checkUrl(url) {
11 console.log(`Checking URL: ${url}`);
12 try {
26 }
27
28 // Function to ensure URL is absolute and classify link type
29 function processUrl(baseUrl, href) {
30 try {
31 if (
191}
192
193export default async function(interval) {
194 console.log(`Starting broken link check at ${new Date().toISOString()}`);
195 const url = "https://dateme.directory/browse";
202 console.log("External broken links:", JSON.stringify(results.brokenLinks.external, null, 2));
203 } catch (error) {
204 console.error(`Error in main function: ${error.message}`);
205 }
206}

BBslackScoutmain.tsx10 matches

@alexdphan•Updated 6 months ago
15}
16
17export default async function(interval: Interval): Promise<void> {
18 try {
19 await createTable();
38
39// Create an SQLite table
40async function createTable(): Promise<void> {
41 await sqlite.execute(`
42 CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (
50
51// Fetch Hacker news, Twitter, and Reddit results
52async function fetchHackerNewsResults(topic: string): Promise<Website[]> {
53 return hackerNewsSearch({
54 query: topic,
58}
59
60async function fetchTwitterResults(topic: string): Promise<Website[]> {
61 return twitterSearch({
62 query: topic,
67}
68
69async function fetchRedditResults(topic: string): Promise<Website[]> {
70 return redditSearch({ query: topic });
71}
72
73function formatSlackMessage(website: Website): string {
74 const displayTitle = website.title || website.url;
75 return `*<${website.url}|${displayTitle}>*
78}
79
80async function sendSlackMessage(message: string): Promise<Response> {
81 const slackWebhookUrl = Deno.env.get("SLACK_WEBHOOK_URL");
82 if (!slackWebhookUrl) {
104}
105
106async function isURLInTable(url: string): Promise<boolean> {
107 const result = await sqlite.execute({
108 sql: `SELECT 1 FROM ${TABLE_NAME} WHERE url = :url LIMIT 1`,
112}
113
114async function addWebsiteToTable(website: Website): Promise<void> {
115 await sqlite.execute({
116 sql: `INSERT INTO ${TABLE_NAME} (source, url, title, date_published)
120}
121
122async function processResults(results: Website[]): Promise<void> {
123 for (const website of results) {
124 if (!(await isURLInTable(website.url))) {

falProxyRequestmain.tsx1 match

@stevekrouse•Updated 6 months ago
1export async function falProxyRequest(req: Request) {
2 const method = req.method;
3 const body = method === "GET" || method === "HEAD" ? undefined : await req.text();

cerebras_codermain.tsx5 matches

@kate•Updated 6 months ago
6import { tomorrow } from "https://esm.sh/react-syntax-highlighter/dist/esm/styles/prism";
7
8function App() {
9 const [prompt, setPrompt] = useState("hello llamapalooza");
10 const [code, setCode] = useState("");
18 >(null);
19
20 async function handleSubmit(e: React.FormEvent) {
21 e.preventDefault();
22 setLoading(true);
92}
93
94function client() {
95 createRoot(document.getElementById("root")!).render(<App />);
96}
100}
101
102function extractCodeFromFence(text: string): string {
103 const htmlMatch = text.match(/```html\n([\s\S]*?)\n```/);
104 return htmlMatch ? htmlMatch[1].trim() : text;
105}
106
107export default async function server(req: Request): Promise<Response> {
108 if (req.method === "POST") {
109 const client = new Cerebras();

reqEvaltownmain.tsx4 matches

@maxm•Updated 6 months ago
1import net, { AddressInfo } from "node:net";
2
3export default async function(req: Request): Promise<Response> {
4 return serveRequest(
5 req,
6 `data:text/tsx,${
7 encodeURIComponent(`
8export default async function(req: Request): Promise<Response> {
9 return Response.json("I am within a worker!")
10}
14}
15
16export async function serveRequest(req: Request, importUrl: string): Promise<Response> {
17 let port = await getFreePort();
18 const worker = new Worker(`https://esm.town/v/maxm/evaltownWorker?cachebust=${crypto.randomUUID()}`, {
55 });
56
57export async function isPortListening(port: number): Promise<boolean> {
58 let isListening = false;
59 const maxWaitTime = 2000; // ms

valtowntownmain.tsx5 matches

@maxm•Updated 6 months ago
48await contentStore.init();
49
50function Town() {
51 return (
52 <div
69}
70
71function HomePage() {
72 return (
73 <html>
82 <form method="POST" action="/submit">
83 <textarea name="handler" rows={10} cols={50} autoFocus>
84 {`export default async function(req: Request) {
85 return Response.json("Hello, world!");
86}`}
95}
96
97function ContentPage({ handler, id }: { handler: string; id: string }) {
98 return (
99 <html>
122 let originalContent = textarea.value;
123
124 textarea.addEventListener('input', function() {
125 if (textarea.value !== originalContent) {
126 submitButton.style.display = 'inline-block';

ethereumAddressGeneratormain.tsx4 matches

@alfongj•Updated 6 months ago
4import { ethers } from "https://esm.sh/ethers@5.7.2";
5
6function CopyableField({ label, value }) {
7 const copyToClipboard = () => {
8 navigator.clipboard.writeText(value).then(() => {
22}
23
24function App() {
25 const [wallet, setWallet] = useState(null);
26
51}
52
53function client() {
54 createRoot(document.getElementById("root")).render(<App />);
55}
57if (typeof document !== "undefined") { client(); }
58
59export default async function server(request: Request): Promise<Response> {
60 return new Response(`
61 <html>

getFileEmail4 file matches

@shouser•Updated 1 week ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblk•Updated 2 weeks ago
Simple functional CSS library for Val Town
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.