id stringlengths 25 25 | kind stringclasses 1
value | title stringlengths 17 17 | provisional bool 1
class | output_code stringlengths 60 4.12k | input_data_sample stringlengths 3 637 | output_data_sample unknown | transformation_instruction stringlengths 54 1.91k |
|---|---|---|---|---|---|---|---|
cmsvnvuek023ag4p2x1i01551 | contributor_item | Submission I01551 | false | def transform(text):
nums = [int(x) for x in text.split(',')]
evens = [n for n in nums if n % 2 == 0]
return ','.join(str(n) for n in evens) | 1,2,3,4,5,6,7,8,9,10 | "2,4,6,8,10" | Parse a comma-separated list of integers and return only the even ones, comma-separated. |
cmsvnvuek0239g4p2kqkf0co2 | contributor_item | Submission KF0CO2 | false | def transform(text):
n = int(text)
ones = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', ... | 342 | "three hundred forty two" | Convert an integer (0-999) into its English words representation, space-separated, lowercase. |
cmsvnvuek023bg4p28o76f0gs | contributor_item | Submission 76F0GS | false | def transform(text):
names = text.split(',')
sorted_names = sorted(names, key=lambda n: n.split()[-1])
return ','.join(sorted_names) | John Smith,Alice Adams,Bob Zephyr,Carol Brown | "Alice Adams,Carol Brown,John Smith,Bob Zephyr" | Parse a comma-separated list of 'First Last' names and sort them by last name, returning the sorted 'First Last' list comma-separated. |
cmsvnvuek023cg4p2s28m38wx | contributor_item | Submission 8M38WX | false | def transform(text):
colors = text.split(',')
sums = []
for c in colors:
c = c.lstrip('#')
r, g, b = int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16)
sums.append(str(r + g + b))
return ','.join(sums) | #FF0000,#00FF00,#0000FF | "255,255,255" | Parse a comma-separated list of 6-digit hex color codes and return the sum of R+G+B components for each, comma-separated. |
cmsvnvuek023eg4p2v11kcieq | contributor_item | Submission 1KCIEQ | false | def transform(text):
seen = set()
result = []
for w in text.split():
if w not in seen:
seen.add(w)
result.append(w)
return ' '.join(result) | the cat sat on the mat and the cat slept | "the cat sat on mat and slept" | Remove duplicate words from the text, keeping only the first occurrence of each, preserving order, space-separated. |
cmsvnvuek023fg4p20aq1qeon | contributor_item | Submission Q1QEON | false | def transform(text):
return sum(ord(ch) for ch in text) % 256 | Hello | 244 | Compute a simple checksum by summing the ASCII codes of all characters in the text, modulo 256. |
cmsvoc5f8027ig4p2pyrs66go | contributor_item | Submission RS66GO | false | def transform(text):
lines = [l for l in text.strip().split('\n') if l]
result = []
for line in lines:
last, first = line.split(', ')
result.append(f'{first} {last}')
return '\n'.join(result)
| Smith, John
Doe, Jane
| "John Smith\nJane Doe" | Given lines in 'Last, First' format, convert each to 'First Last' format, one name per line. |
cmsvoc5f8027fg4p2l3wbz2xf | contributor_item | Submission WBZ2XF | false | import json
def transform(text):
data = json.loads(text)
values = data['values']
result = {
'min': min(values),
'max': max(values),
'avg': round(sum(values) / len(values), 2)
}
return json.dumps(result)
| {"values": [4, 8, 15, 16, 23, 42]} | {
"min": 4,
"max": 42,
"avg": 18
} | Given a JSON object with a 'values' array of numbers, compute the min, max, and average, returning a JSON object with keys min, max, avg (avg rounded to 2 decimals). |
cmsvoc5f8027hg4p2n01k0azg | contributor_item | Submission 1K0AZG | false | import re
def transform(text):
return re.sub(r'\d+', lambda m: 'X' * len(m.group()), text)
| Card ending in 1234, order #56789 confirmed. | "Card ending in XXXX, order #XXXXX confirmed." | Replace every run of digits in the text with the same number of 'X' characters, keeping everything else unchanged. |
cmsvoc5f8027gg4p2pxleyz56 | contributor_item | Submission LEYZ56 | false | import csv, json, io
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()), delimiter='\t')
return json.dumps(list(reader))
| name age
Alice 30
Bob 25
| [
{
"name": "Alice",
"age": "30"
},
{
"name": "Bob",
"age": "25"
}
] | Parse a TSV (tab-separated) file with a header row into a JSON array of objects. |
cmsvoc5f8027jg4p2ajfvccbn | contributor_item | Submission FVCCBN | false | import json
def transform(text):
lines = [l for l in text.strip().split('\n') if l]
counts = [len(l.split()) for l in lines]
return json.dumps(counts)
| the quick brown fox
jumped over
the lazy dog here
| [
4,
2,
4
] | For each line in the input, count the number of words, and return a JSON array of the counts in order. |
cmsvoc5f8027lg4p2qwflqcob | contributor_item | Submission FLQCOB | false | import re
def transform(text):
return re.sub(r'\s+', ' ', text).strip()
| This is a test.
| "This is a test." | Collapse all runs of whitespace into a single space and strip leading/trailing whitespace. |
cmsvoc5f8027eg4p2yebjwalj | contributor_item | Submission BJWALJ | false | import re, json
def transform(text):
tags = re.findall(r'#(\w+)', text)
return json.dumps(sorted(set(tags)))
| Loving the #sunset and #beach vibes today! #sunset again. | [
"beach",
"sunset"
] | Extract all unique hashtags from the text, sort them alphabetically, and return as a JSON array of strings (without the # symbol). |
cmsvoc5f8027cg4p28bk1fe15 | contributor_item | Submission K1FE15 | false | import json
def transform(text):
result = {}
section = None
for line in text.strip().split('\n'):
line = line.strip()
if not line:
continue
if line.startswith('[') and line.endswith(']'):
section = line[1:-1]
result[section] = {}
elif '=' ... | [server]
host=localhost
port=8080
[client]
timeout=30
| {
"server": {
"host": "localhost",
"port": "8080"
},
"client": {
"timeout": "30"
}
} | Parse a simple INI-style config (with [section] headers and key=value lines) into a JSON object mapping section names to their key-value pairs. |
cmsvoqatw02agg4p2srqh28yt | contributor_item | Submission QH28YT | false | import re
def transform(input):
parts = [p.strip() for p in input.split(',')]
out = []
for p in parts:
h_match = re.search(r'(\d+)h', p)
m_match = re.search(r'(\d+)m', p)
h = int(h_match.group(1)) if h_match else 0
m = int(m_match.group(1)) if m_match else 0
out.appen... | 2h 30m, 45m, 1h, 3h 15m | [
150,
45,
60,
195
] | Convert a comma-separated list of duration strings (format '<H>h <M>m', either part optional) into a JSON array of total minutes. |
cmsvoqatx02b0g4p215hmsiyj | contributor_item | Submission HMSIYJ | false | def transform(text):
words = text.split()
return max(words, key=len) | the quick brown fox jumps over extraordinarily | "extraordinarily" | Find and return the longest word in the text (first one if there is a tie). |
cmsvoqatx02ajg4p2hfm5r4x7 | contributor_item | Submission M5R4X7 | false | def transform(text):
words = text.split()
def pig(w):
return w[1:] + w[0] + 'ay'
return ' '.join(pig(w) for w in words) | hello world pig latin | "ellohay orldway igpay atinlay" | Translate each word of the text to Pig Latin: move the first consonant cluster (or just first letter here, simplified to first letter) to the end and append 'ay'. |
cmsvoqatx02avg4p2zkuukbwo | contributor_item | Submission UUKBWO | false | import json
from collections import Counter
def transform(text):
counts = Counter(text.split())
return json.dumps(dict(counts)) | the cat sat on the mat the cat ran | {
"the": 3,
"cat": 2,
"sat": 1,
"on": 1,
"mat": 1,
"ran": 1
} | Return a JSON object mapping each distinct word to its frequency count in the text. |
cmsvoqatx02aig4p2mefp0s5s | contributor_item | Submission FP0S5S | false | import json
def transform(text):
lines = text.split(chr(10))
headers = lines[0].split(',')
values = lines[1].split(',')
return json.dumps(dict(zip(headers, values))) | name,age,city
Alice,30,Boston | {
"name": "Alice",
"age": "30",
"city": "Boston"
} | Parse a two-line CSV (header + one data row) and return a JSON object mapping header to value. |
cmsvoqatw02afg4p2w7zxog7h | contributor_item | Submission ZXOG7H | false | def transform(text):
fs = [float(x) for x in text.split(',')]
cs = [round((f - 32) * 5 / 9, 2) for f in fs]
return ','.join(str(c) for c in cs) | 32,98.6,212,0 | "0.0,37.0,100.0,-17.78" | Parse a comma-separated list of Fahrenheit temperatures and return Celsius equivalents, comma-separated, rounded to 2 decimals. |
cmsvoqatx02akg4p2q4df02l0 | contributor_item | Submission DF02L0 | false | def transform(text):
return ' '.join(w.capitalize() for w in text.split()) | the quick brown fox jumps | "The Quick Brown Fox Jumps" | Convert text to title case, capitalizing the first letter of every word. |
cmsvoqatx02amg4p283ho2n4u | contributor_item | Submission HO2N4U | false | import json
def transform(text):
vowels = sum(1 for ch in text if ch.lower() in 'aeiou')
consonants = sum(1 for ch in text if ch.isalpha() and ch.lower() not in 'aeiou')
return json.dumps({"vowels": vowels, "consonants": consonants}) | Hello World | {
"vowels": 3,
"consonants": 7
} | Count the number of vowels and consonants (letters only) in the text and return as a JSON object. |
cmsvoqatx02alg4p2hksif19m | contributor_item | Submission SIF19M | false | def transform(text):
return ''.join(ch for ch in text if ch.lower() not in 'aeiou') | Hello World Programming | "Hll Wrld Prgrmmng" | Remove all vowels (a, e, i, o, u, both cases) from the text. |
cmsvoqatx02apg4p2fv3vha9p | contributor_item | Submission 3VHA9P | false | import re
def transform(text):
nums = [int(n) for n in re.findall(r'\d+', text)]
return sum(nums) | I have 3 apples, 15 oranges, and 7 bananas, total 25 fruits | 50 | Extract all integers from the text and return their sum. |
cmsvoqatx02aog4p2d9uejova | contributor_item | Submission UEJOVA | false | import json
def transform(text):
pairs = text.split(';')
result = {}
for p in pairs:
k, v = p.split('=')
result[k] = v
return json.dumps(result) | name=Alice;age=30;city=Boston | {
"name": "Alice",
"age": "30",
"city": "Boston"
} | Parse a semicolon-separated list of key=value pairs into a JSON object. |
cmsvoqatx02ang4p2f9i1dovy | contributor_item | Submission I1DOVY | false | def transform(text):
return ' '.join(reversed(text.split())) | the quick brown fox jumps over | "over jumps fox brown quick the" | Reverse the order of words in the sentence, keeping each word's spelling unchanged, space-separated. |
cmsvoqatx02asg4p2bbxgymz8 | contributor_item | Submission XGYMZ8 | false | def transform(text):
if not text:
return ''
result = []
prev = text[0]
count = 1
for ch in text[1:]:
if ch == prev:
count += 1
else:
result.append(f'{count}{prev}')
prev = ch
count = 1
result.append(f'{count}{prev}')
ret... | aaabbbccccd | "3a3b4c1d" | Compress a string using run-length encoding, representing each run as <count><char>. |
cmsvoqatx02aqg4p24uqix6g5 | contributor_item | Submission QIX6G5 | false | def transform(text):
bins = text.split()
return ','.join(str(int(b, 2)) for b in bins) | 1010 1111 0011 0001 | "10,15,3,1" | Parse a space-separated list of binary strings and return their decimal equivalents, comma-separated. |
cmsvoqatx02arg4p2txcmfpwx | contributor_item | Submission CMFPWX | false | def transform(text):
nums = [int(x) for x in text.split(',')]
return ','.join(format(n, 'X') for n in nums) | 255,16,4096,10 | "FF,10,1000,A" | Parse a comma-separated list of decimal integers and return their uppercase hexadecimal equivalents (no 0x prefix), comma-separated. |
cmsvoqatx02atg4p2zk6f3kyz | contributor_item | Submission 6F3KYZ | false | import re
def transform(text):
pairs = re.findall(r'(\d+)(\D)', text)
return ''.join(ch * int(count) for count, ch in pairs) | 3a3b4c1d | "aaabbbccccd" | Decompress a run-length-encoded string of the form <count><char> repeated. |
cmsvoqatx02aug4p2vfby6pf2 | contributor_item | Submission BY6PF2 | false | def transform(text):
emails = text.split(',')
domains = [e.split('@')[1] for e in emails]
return ','.join(domains) | alice@example.com,bob@test.org,carol@sub.domain.io | "example.com,test.org,sub.domain.io" | Parse a comma-separated list of email addresses and return their domain portions (after the @), comma-separated. |
cmsvoqatx02awg4p2jsrk3i96 | contributor_item | Submission RK3I96 | false | def transform(text):
sentences = [s.strip() for s in text.split('.') if s.strip()]
capitalized = [s[0].upper() + s[1:] for s in sentences]
return '. '.join(capitalized) + '.' | hello there. how are you. i am fine. | "Hello there. How are you. I am fine." | Split the text into sentences on periods and capitalize the first letter of each, rejoining with '. '. |
cmsvoqatx02ayg4p2gg60bryn | contributor_item | Submission 60BRYN | false | def transform(text):
cs = [float(x) for x in text.split(',')]
fs = [round(c * 9 / 5 + 32, 2) for c in cs]
return ','.join(str(f) for f in fs) | 0,37,100,-17.78 | "32.0,98.6,212.0,-0.0" | Parse a comma-separated list of Celsius temperatures and return Fahrenheit equivalents, comma-separated, rounded to 2 decimals. |
cmsvoqatx02axg4p2tx8oozjg | contributor_item | Submission 8OOZJG | false | def transform(text):
return '*' * (len(text) - 4) + text[-4:] | 4111111111111111 | "************1111" | Mask a credit card number, replacing all but the last 4 digits with asterisks. |
cmsvoqatx02azg4p2050f0oyb | contributor_item | Submission 0F0OYB | false | def transform(text):
pairs = text.split(',')
total = sum(int(p.split(':')[1]) for p in pairs)
return total | a:1,b:2,c:3,d:4 | 10 | Parse a comma-separated list of key:value numeric pairs and return the sum of all the values. |
cmsvoqatx02b3g4p2alzw9d4l | contributor_item | Submission ZW9D4L | false | import json
def transform(text):
pairs = text.split(',')
people = []
for p in pairs:
name, age = p.split(':')
people.append({"name": name, "age": int(age)})
people.sort(key=lambda p: p["age"])
return json.dumps(people) | Alice:30,Bob:25,Carol:35 | [
{
"name": "Bob",
"age": 25
},
{
"name": "Alice",
"age": 30
},
{
"name": "Carol",
"age": 35
}
] | Parse a comma-separated list of name:age pairs and return a JSON list of objects sorted by age ascending. |
cmsvoqatx02b2g4p21y2mt0j7 | contributor_item | Submission 2MT0J7 | false | import re
def transform(text):
return re.sub(r'<[^>]+>', '', text) | <p>Hello <b>World</b>! <i>Welcome</i></p> | "Hello World! Welcome" | Remove all HTML tags from the text, keeping only the visible text content. |
cmsvoqatx02b1g4p2ndgkzbnf | contributor_item | Submission GKZBNF | false | def transform(text):
dates = text.split(',')
converted = []
for d in dates:
day, month, year = d.split('/')
converted.append(f'{year}-{month}-{day}')
return ','.join(converted) | 25/12/2026,01/01/2027,15/06/2026 | "2026-12-25,2027-01-01,2026-06-15" | Parse a comma-separated list of dates in DD/MM/YYYY format and return them in YYYY-MM-DD format, comma-separated. |
cmsvoqatx02b5g4p2lg1ame0v | contributor_item | Submission 1AME0V | false | def transform(text):
words = text.split()
return sum(1 for w in words if w == w[::-1]) | level noon hello world madam racecar test | 4 | Count how many words in the text are palindromes (read the same forwards and backwards). |
cmsvoqatx02b4g4p2cocgmsf6 | contributor_item | Submission CGMSF6 | false | def transform(text):
words = text.split()
return ' '.join(w[:5] for w in words) | internationalization programming excellent | "inter progr excel" | Truncate each word in the text to a maximum of 5 characters, space-separated. |
cmsvoqatx02b6g4p2vpr35hbu | contributor_item | Submission R35HBU | false | import math
def transform(text):
points = []
for p in text.split(';'):
x, y = p.split(',')
points.append((float(x), float(y)))
total = 0.0
for i in range(1, len(points)):
x1, y1 = points[i - 1]
x2, y2 = points[i]
total += math.hypot(x2 - x1, y2 - y1)
return r... | 0,0;3,4;3,0;0,0 | 12 | Parse a semicolon-separated list of x,y coordinate pairs and return the total Euclidean distance traveled across consecutive points, rounded to 2 decimals. |
cmsvoqatx02b7g4p22w5mq1bt | contributor_item | Submission 5MQ1BT | false | import json
def transform(text):
result = {}
current_section = None
for raw_line in text.split("\n"):
line = raw_line.strip()
if not line or line.startswith("#") or line.startswith(";"):
continue
if line.startswith("[") and line.endswith("]"):
current_section... | ; global settings
timeout = 30
[database]
host = localhost
port = 5432
name = "my app db"
# logging section
[logging]
level = DEBUG
path = /var/log/app.log
| {
"_global": {
"timeout": "30"
},
"database": {
"host": "localhost",
"port": "5432",
"name": "my app db"
},
"logging": {
"level": "DEBUG",
"path": "/var/log/app.log"
}
} | Parse an INI-style config text (with `[section]` headers, `key = value` lines, and `#`/`;` comment lines) into a nested JSON object mapping each section name to its own key/value object; keys found before any section header go under a `_global` section. Quoted values have their surrounding double quotes stripped. |
cmsvoqatw02aeg4p2y3qax2tr | contributor_item | Submission QAX2TR | false | def transform(input):
parts = [p.strip() for p in input.split(',')]
celsius = sorted(round((float(p) - 32) * 5/9, 1) for p in parts)
return celsius | 98.6, 32, 212, 77, -40 | [
-40,
0,
25,
37,
100
] | Convert a comma-separated list of Fahrenheit temperatures into a JSON array of Celsius temperatures, each rounded to 1 decimal place, sorted in ascending numeric order. |
cmsvoqatw02ahg4p2vxaal15v | contributor_item | Submission AAL15V | false | import re
def transform(input):
tuples = re.findall(r'\(([^)]+)\)', input)
hexes = []
for t in tuples:
r, g, b = [int(x.strip()) for x in t.split(',')]
hexes.append('#{:02X}{:02X}{:02X}'.format(r, g, b))
return ', '.join(hexes) | (255, 87, 51), (0, 128, 255), (34, 139, 34) | "#FF5733, #0080FF, #228B22" | Parse a comma-separated list of RGB tuples written as '(R, G, B)' and convert each to its uppercase 6-digit hex color code, joined by ', '. |
cmsvqtlqp02sfg4p2f2uiu3y4 | contributor_item | Submission UIU3Y4 | false | import json
import re
def transform(text):
result = {}
for line in text.strip().split("\n"):
line = line.strip()
if not line.startswith("export "):
continue
rest = line[len("export "):]
key, _, value = rest.partition("=")
value = value.strip()
if valu... | export DB_HOST=localhost
export DB_PORT=5432
export APP_NAME="My Service"
export DEBUG=true
| {
"DB_HOST": "localhost",
"DB_PORT": "5432",
"APP_NAME": "My Service",
"DEBUG": "true"
} | Parse a shell script of `export KEY=value` lines (values optionally single- or double-quoted) into a JSON object mapping each key to its unquoted string value. |
cmsvtf5al000xuvp2bcoxpmyl | contributor_item | Submission OXPMYL | false | import json
def transform(text):
text = text.lower()
counts = {v: text.count(v) for v in 'aeiou'}
return json.dumps(counts)
| The rain in Spain falls mainly on the plain | {
"a": 5,
"e": 2,
"i": 5,
"o": 1,
"u": 0
} | Count vowels (a,e,i,o,u case-insensitive) in the text and return a JSON object mapping each vowel to its count, including zero counts. |
cmsvtf5al000ruvp2nh0kintl | contributor_item | Submission 0KINTL | false | import json
def transform(text):
lines = [l for l in text.strip().split('\n') if l]
balance = 0.0
out = []
for line in lines:
date, amt = line.split(',')
balance += float(amt)
out.append({"date": date, "balance": round(balance, 2)})
return json.dumps(out)
| 2026-01-15,150.50
2026-01-16,200.00
2026-01-17,-50.25
2026-01-18,75.00 | [
{
"date": "2026-01-15",
"balance": 150.5
},
{
"date": "2026-01-16",
"balance": 350.5
},
{
"date": "2026-01-17",
"balance": 300.25
},
{
"date": "2026-01-18",
"balance": 375.25
}
] | Given daily transaction amounts as date,amount CSV lines, compute the running balance after each day and return as a JSON array of {date, balance}. |
cmsvtf5al000muvp21v2gjpe8 | contributor_item | Submission 2GJPE8 | false | def transform(text):
lines = text.strip().split('\n')
result = []
for line in lines:
snake = '_'.join(line.lower().split())
result.append(snake)
return ';'.join(result)
| The Quick Brown Fox
Jumps Over The Lazy Dog | "the_quick_brown_fox;jumps_over_the_lazy_dog" | Convert each line from Title Case to snake_case, joining lines with a semicolon. |
cmsvtf5al000tuvp2190yka6l | contributor_item | Submission 0YKA6L | false | import csv, io
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
rows = list(reader)
rows.sort(key=lambda r: r['last_name'])
return '\n'.join(f"{r['first_name']} {r['last_name']}" for r in rows)
| first_name,last_name
John,Doe
Jane,Smith | "John Doe\nJane Smith" | Convert CSV rows with first_name,last_name headers into a list of full names joined by ' ', one per line, sorted alphabetically by last name. |
cmsvtf5al000quvp2bhdyy5n3 | contributor_item | Submission DYY5N3 | false | import json
def transform(text):
result = {}
for pair in text.strip().split(';'):
if '=' in pair:
k, v = pair.split('=', 1)
result[k.strip()] = v.strip()
return json.dumps(result)
| key1=value1;key2=value2 with spaces;key3=another value | {
"key1": "value1",
"key2": "value2 with spaces",
"key3": "another value"
} | Parse a semicolon-separated list of key=value pairs (values may contain spaces) into a JSON object. |
cmsvtf5al000luvp27qgxnt5f | contributor_item | Submission GXNT5F | false | import json
from collections import defaultdict
def transform(text):
totals = defaultdict(int)
for pair in text.strip().split(','):
name, count = pair.split(':')
totals[name.strip()] += int(count)
return json.dumps(dict(sorted(totals.items())))
| apple:3,banana:5,apple:2,cherry:1,banana:1 | {
"apple": 5,
"banana": 6,
"cherry": 1
} | Parse a comma-separated list of item:count pairs and sum counts per item, returning a JSON object sorted by item name. |
cmsvtf5al000kuvp27k603zsi | contributor_item | Submission 603ZSI | false | import csv, io, json
def transform(text):
reader = csv.DictReader(io.StringIO(text.strip()))
rows = []
for row in reader:
out = {}
for k, v in row.items():
try:
out[k] = int(v)
except ValueError:
out[k] = v
rows.append(out)
... | Name,Age,City
Alice,30,NYC
Bob,25,LA
Carol,35,SF | [
{
"Name": "Alice",
"Age": 30,
"City": "NYC"
},
{
"Name": "Bob",
"Age": 25,
"City": "LA"
},
{
"Name": "Carol",
"Age": 35,
"City": "SF"
}
] | Convert a CSV string with a header row into a JSON array of objects, keeping numeric-looking fields as integers. |
cmsvtf5al000uuvp2l4gnn331 | contributor_item | Submission GNN331 | false | import json, re
def transform(text):
matches = re.findall(r'<item id="(\d+)">(.*?)</item>', text)
result = {int(k): v for k, v in matches}
return json.dumps(result)
| <root><item id="1">Apple</item><item id="2">Banana</item></root> | {
"1": "Apple",
"2": "Banana"
} | Parse simple XML with <item id="N">text</item> children and return a JSON object mapping id to text. |
cmsvtf5al000suvp2tv9zdl9y | contributor_item | Submission 9ZDL9Y | false | import json, re
def transform(text):
text = text.strip()
letters = ''.join(re.findall(r'[a-zA-Z]', text))
digits = ''.join(re.findall(r'\d', text))
return json.dumps({"letters": letters, "digits": digits})
| a1b2c3d4e5 | {
"letters": "abcde",
"digits": "12345"
} | Extract all letters and all digits from an alphanumeric string separately, returning them as JSON with keys 'letters' and 'digits'. |
cmsvtf5al0011uvp26a6kwkf6 | contributor_item | Submission 6KWKF6 | false | import json
import operator
def transform(text):
ops = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
lines = [l for l in text.strip().split('\n') if l]
results = []
for line in lines:
parts = line.split()
a, op, b = int(parts[0]), parts[1], int(parts[2... | 3 + 4
10 - 2
6 * 7
20 / 4 | [
7,
8,
42,
5
] | Evaluate each simple arithmetic expression line (operators + - * /, two integer operands) and return a JSON array of results (as numbers, division results as floats). |
cmsvtf5al0012uvp294wg6i0r | contributor_item | Submission WG6I0R | false | import json
def transform(text):
lines = [l for l in text.strip().split('\n') if l]
best = None
for line in lines:
item, price, qty = line.split(',')
total = float(price) * int(qty)
if best is None or total > best['total']:
best = {"item": item, "total": total}
retur... | apple,10,3
banana,5,7
cherry,20,1 | {
"item": "banana",
"total": 35
} | Given lines of item,price,quantity, compute total cost per item (price*quantity) and return the item with the highest total cost as a JSON object {item, total}. |
cmsvtf5al0013uvp2x42336sg | contributor_item | Submission 2336SG | false | import json
from collections import defaultdict
def transform(text):
lines = [l for l in text.strip().split('\n') if l]
fails = defaultdict(int)
for line in lines:
tokens = dict(tok.split(':') for tok in line.split())
if tokens.get('action') == 'login' and tokens.get('status') == 'fail':
... | user_id:1001 action:login status:success
user_id:1002 action:login status:fail
user_id:1001 action:logout status:success
user_id:1003 action:login status:fail | {
"1002": 1,
"1003": 1
} | Parse space-separated key:value tokens per line and count how many 'login' actions had status 'fail' per user_id, returning a JSON object mapping user_id to fail count (only users with at least one fail). |
cmsvtf5al0010uvp2aq6dj21r | contributor_item | Submission 6DJ21R | false | import json
from datetime import datetime
def transform(text):
lines = [l for l in text.strip().split('\n') if l]
durations = []
start_time = None
for line in lines:
ts, event = line.split(',')
t = datetime.fromisoformat(ts)
if event == 'START':
start_time = t
... | 2026-08-01T10:00:00,START
2026-08-01T10:05:00,STOP
2026-08-01T10:10:00,START
2026-08-01T10:25:00,STOP | [
5,
15
] | Given alternating START/STOP timestamp events, compute the duration in minutes of each START-STOP pair and return a JSON array of durations. |
cmsvtf5al000nuvp2v434fbpx | contributor_item | Submission 34FBPX | false | import json
def transform(text):
data = json.loads(text)
lines = []
for user in data['users']:
for role in user['roles']:
lines.append(f"{user['id']}:{role}")
return '\n'.join(lines)
| {"users": [{"id": 1, "roles": ["admin", "editor"]}, {"id": 2, "roles": ["viewer"]}]} | "1:admin\n1:editor\n2:viewer" | Flatten a JSON object with a users list of {id, roles} into a list of 'id:role' strings, one per role, newline separated. |
cmsvtf5al000ouvp2ca1u460c | contributor_item | Submission 1U460C | false | import re, json
def transform(text):
lines = [l for l in text.strip().split('\n') if l]
result = []
for line in lines:
m = re.match(r'^(\S+).*"\s*(\d{3})$', line)
if m:
result.append([m.group(1), m.group(2)])
return json.dumps(result)
| 192.168.1.10 - - [10/Aug/2026:13:55:36] "GET /index.html HTTP/1.1" 200
10.0.0.5 - - [10/Aug/2026:13:56:01] "POST /api/login HTTP/1.1" 401 | [
[
"192.168.1.10",
"200"
],
[
"10.0.0.5",
"401"
]
] | Extract just the IP address and HTTP status code from each Apache-style log line, returning a JSON array of [ip, status] pairs. |
cmsvtf5al000puvp2fb7tdur3 | contributor_item | Submission 7TDUR3 | false | import json
from collections import Counter
def transform(text):
nums = [int(x.strip()) for x in text.strip().split(',')]
counts = Counter(nums)
max_count = max(counts.values())
mode = min(n for n, c in counts.items() if c == max_count)
result = {
"min": min(nums),
"max": max(nums),... | 3,1,4,1,5,9,2,6,5,3,5 | {
"min": 1,
"max": 9,
"mean": 4,
"mode": 5
} | Given a comma-separated list of integers, return a JSON object with min, max, mean (rounded to 2 decimals), and the mode (most frequent value; if tie, smallest). |
cmsvtf5al000vuvp2csjauat9 | contributor_item | Submission JAUAT9 | false | import json
def transform(text):
grid = [[int(x) for x in line.split()] for line in text.strip().split('\n')]
row_sums = [sum(row) for row in grid]
col_sums = [sum(col) for col in zip(*grid)]
return json.dumps({"row_sums": row_sums, "col_sums": col_sums})
| 10 20 30
40 50 60
70 80 90 | {
"row_sums": [
60,
150,
240
],
"col_sums": [
120,
150,
180
]
} | Given a whitespace-separated grid of integers (rows on separate lines), return the sum of each row and the sum of each column as JSON with keys 'row_sums' and 'col_sums'. |
cmsvtf5al000wuvp2n368y9cf | contributor_item | Submission 68Y9CF | false | import json
def transform(text):
lines = [l for l in text.strip().split('\n') if l]
result = []
for line in lines:
uid, status = line.split(',')
if status.strip() == 'active':
result.append(uid.strip())
return json.dumps(result)
| 550e8400-e29b-41d4-a716-446655440000,active
f47ac10b-58cc-4372-a567-0e02b2c3d479,inactive | [
"550e8400-e29b-41d4-a716-446655440000"
] | Parse lines of uuid,status and return only the active UUIDs as a JSON array, preserving order. |
cmsvtf5al000zuvp2l5ky4o9z | contributor_item | Submission KY4O9Z | false | import re
def transform(text):
lines = text.strip().split('\n')
out = []
for line in lines:
line = re.sub(r'^#+\s*', '', line)
line = re.sub(r'\*\*(.*?)\*\*', r'\1', line)
line = re.sub(r'\*(.*?)\*', r'\1', line)
line = re.sub(r'`(.*?)`', r'\1', line)
out.append(line... | # Header
Some **bold** text and *italic* text here.
Another line with `code`. | "Header\nSome bold text and italic text here.\nAnother line with code." | Strip common Markdown formatting (headers, bold **, italic *, inline code backticks) leaving plain text, preserving line breaks. |
cmsvtf5al000yuvp2lb78071n | contributor_item | Submission 78071N | false | import json
from urllib.parse import parse_qsl
def transform(text):
pairs = parse_qsl(text.strip(), keep_blank_values=True)
items = []
current = {}
for k, v in pairs:
if k in current:
items.append(current)
current = {}
current[k] = v
if current:
items... | product=Widget&qty=5&price=9.99&product=Gadget&qty=2&price=19.99 | [
{
"product": "Widget",
"qty": 5,
"price": 9.99
},
{
"product": "Gadget",
"qty": 2,
"price": 19.99
}
] | Parse a query string where product/qty/price fields repeat in groups of 3 in order, grouping them into a JSON array of objects. |
cmsw380wz004luvp2pvp03sza | contributor_item | Submission P03SZA | false | from decimal import Decimal, ROUND_HALF_UP
def transform(text):
groups = []
current = {"name": "(root)", "verts": 0, "faces": 0, "tri": 0, "quad": 0, "ngon": 0}
groups.append(current)
xs, ys, zs = [], [], []
refs = 0
maxindex = 0
for raw in text.split("\n"):
line = raw.strip()
... | # exported by handmade tool
mtllib panels.mtl
v -1.0 0.0 0.0
o LeftPanel
v 0.0 0.0 0.0
v 1.0 0.0 0.0
v 1.0 2.5 0.0
vn 0.0 0.0 1.0
vt 0.0 0.0
usemtl steel
f 2/1/1 3/1/1 4/1/1
o RightPanel
v -1.5 0.0 3.25
v -1.5 1.0 3.25
f 5//1 6//1 2//1 3//1
f 5 6 2 3 4
s off
o LeftPanel
v 4.5 -2.0 1.0
f 7 5 6
| "name=(root) verts=1 faces=0 tri=0 quad=0 ngon=0\nname=LeftPanel verts=3 faces=1 tri=1 quad=0 ngon=0\nname=RightPanel verts=2 faces=2 tri=0 quad=1 ngon=1\nname=LeftPanel verts=1 faces=1 tri=1 quad=0 ngon=0\nmin=-1.500/-2.000/0.000\nmax=4.500/2.500/3.250\nrefs=15 maxindex=7" | Summarize a Wavefront OBJ mesh. Rules:
1. Ignore blank lines and lines whose first non-space character is '#'.
2. Split each remaining line on whitespace; the first token is the keyword.
3. 'o NAME' opens a new object group. Any geometry appearing before the first 'o' belongs to a group named '(root)'; if no vertex and... |
cmsw380wz004nuvp20dq5cbba | contributor_item | Submission Q5CBBA | false | def transform(text):
disc_title = None
disc_performer = None
tracks = []
current = None
def quoted(line):
first = line.find('"')
last = line.rfind('"')
if first == -1 or last <= first:
return line.split(None, 1)[1].strip() if " " in line else ""
return li... | REM GENRE Ambient
REM DATE 2019
PERFORMER "Marsh Collective"
TITLE "Tidal Fields"
FILE "album.wav" WAVE
TRACK 01 AUDIO
TITLE "Opening Silt"
INDEX 01 00:00:00
TRACK 02 AUDIO
TITLE "Second Light"
PERFORMER "Marsh Collective feat. Ilse"
INDEX 00 03:12:30
INDEX 01 03:14:00
TRACK 03 MODE1/2352
... | "01|00:00:00|03:14:00|Marsh Collective - Opening Silt\n02|03:14:00|02:46:00|Marsh Collective feat. Ilse - Second Light\n04|07:00:74|04:44:38|Marsh Collective - Tidal Fields\n05|11:45:37|--:--:--|Marsh Collective - Closing Silt\ntracks=4 playable=10:44:38" | Turn a CD cue sheet into a track listing. Rules:
1. Consider only lines whose stripped form starts with 'TRACK ', 'TITLE ', 'PERFORMER ', 'INDEX ' or 'FILE '. Ignore every other line, including REM lines.
2. A 'TRACK NN AUDIO' line opens a new track; NN is a two-digit number. Only tracks with type 'AUDIO' are listed; a... |
cmsw380wz004ruvp2i92cxhbk | contributor_item | Submission 2CXHBK | false | from decimal import Decimal, ROUND_HALF_UP, InvalidOperation
UNITS = {"K": 1024, "M": 1024 ** 2, "G": 1024 ** 3, "T": 1024 ** 4}
def transform(text):
skipped = []
rows = []
for raw in text.split("\n"):
if not raw.strip():
continue
if "\t" not in raw:
skipped.append... | 4.0K ./src/utils
12M ./src
1.5G ./data/raw
900 ./data/tmp
2.3G ./data
128K ./docs
0 ./empty
17X ./weird
nosizehere ./broken
1.0T ./
| "SKIP 17X\t./weird\nSKIP nosizehere ./broken\n1099511627776|./|1.00 TiB\n2469606195|./data|2.30 GiB\n1610612736|./data/raw|1.50 GiB\n12582912|./src|12.00 MiB\n131072|./docs|128.00 KiB\n4096|./src/utils|4.00 KiB\n900|./data/tmp|900 B\n0|./empty|0 B\nentries=8 total=1103604565687" | Convert 'du -h' style output into exact byte counts.
1. Each non-blank line holds a size, then a TAB, then a path. Strip trailing whitespace from the path.
2. A size is a decimal number optionally followed by one unit letter: K, M, G or T, case-insensitive, meaning multiplication by 1024, 1024**2, 1024**3 and 1024**4. ... |
cmsw380wz004ouvp2niczerno | contributor_item | Submission CZERNO | false | def transform(text):
invalid = []
rows = []
for raw in text.split("\n"):
line = raw.strip()
if not line or line.startswith("#"):
continue
fields = line.split()
if len(fields) < 4:
invalid.append("INVALID " + line)
continue
source, m... | # /etc/fstab: static file system information
UUID=7c2f-9a11 / ext4 defaults,noatime,errors=remount-ro 0 1
/dev/sdb1 /data xfs rw,relatime,nofail 0 2
tmpfs /tmp tmpfs defaults 0 0
LABEL=archive /mnt/arch ext4 noauto,user,ro,... | "INVALID /dev/sdd1 swap\n/|ext4|uuid|errors=remount-ro,noatime|01\n/data|xfs|device|nofail,relatime,rw|02\n/mnt/arch|ext4|label|noatime,noauto,ro,user|00\n/mnt/spare|auto|device|defaults|00\n/proc|proc|pseudo|defaults|00\n/sys/fs/cgroup|cgroup2|pseudo|memory_recursiveprot,nsdelegate|00\n/tmp|tmpfs|pseudo|defaults|00\n... | Normalize a Unix fstab file into a mount table.
1. Strip each line; drop lines that are empty or start with '#'.
2. Split the remaining lines on runs of whitespace. A valid entry has at least 4 fields: source, mount point, filesystem type, options. Fields 5 (dump) and 6 (pass) default to '0' when absent. An entry with ... |
cmsw380wz004quvp27yhc8hh0 | contributor_item | Submission HC8HH0 | false | from decimal import Decimal, ROUND_HALF_UP
def transform(text):
lines = text.split("\n")
while lines and lines[-1] == "":
lines.pop()
usable = len(lines) - (len(lines) % 4)
out = []
reads = 0
bases = 0
q30 = 0
for start in range(0, usable, 4):
header, seq, sep, qual = ... | @read_0001 lane=3 tile=1101
ACGTACGTNNGGCC
+
IIIIIIII##IIII
@read_0002
GGGCCCATTA
+read_0002
!!!!IIIIII
@read_0003 short
ACGT
+
III
@read_0004
atgcatgcatgc
+
5555IIII::::
| "read_0001 len=14 gc=57.1 meanq=34.57 n=2\nread_0002 len=10 gc=60.0 meanq=24.00 n=0\nread_0003 MALFORMED\nread_0004 len=12 gc=50.0 meanq=28.33 n=0\nreads=3 bases=36 q30=22" | Compute per-read statistics for a FASTQ file.
1. Split the input into lines and drop trailing empty lines. The remaining lines are grouped into records of exactly four lines: header, sequence, separator, quality. If the number of lines is not a multiple of four, ignore the leftover lines at the end.
2. The read id is t... |
cmsw380wz004muvp2lsjo5x4h | contributor_item | Submission JO5X4H | false | from decimal import Decimal, ROUND_HALF_UP
def transform(text):
out = []
n = 0
for raw in text.split("\n"):
line = raw.strip()
if not line:
continue
n += 1
if not line.startswith("$") or line.count("*") != 1:
out.append("%d: BADSUM" % n)
... | $GPGGA,123519.00,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*69
$GPGGA,001043.00,4404.14036,N,12118.85961,W,1,12,0.98,1113.0,M,-21.3,M,,*59
$GPGGA,092751.00,3723.2475,S,14507.36,E,0,04,2.5,19.7,M,,M,,*59
$GPGGA,123519.00,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*6A
$GPRMC,081836,A,3751.65,S,14507.36,E,000.0... | "1: 12:35:19 48.117300 11.516667 sats=8 alt=545.4m\n2: 00:10:43 44.069006 -121.314327 sats=12 alt=1113.0m\n3: NOFIX\n4: BADSUM\n5: SKIP GPRMC\n6: 18:13:05 51.557020 -0.118533 sats=6 alt=12.5m" | Decode NMEA 0183 GGA fix sentences. Process every non-blank line in input order, numbering them from 1 counting only non-blank lines.
1. A sentence must start with '$' and contain exactly one '*'. The two characters after '*' are the checksum in hexadecimal. Compute the checksum as the XOR of every character strictly b... |
cmsw380wz004puvp24a7pzsiu | contributor_item | Submission 7PZSIU | false | def transform(text):
origin = "."
default_ttl = "3600"
last_owner = None
records = []
for raw in text.split("\n"):
line = raw.split(";")[0].rstrip()
if not line.strip():
continue
if line.lstrip().startswith("$"):
parts = line.split()
if pa... | $ORIGIN example.net.
$TTL 3600
@ IN NS ns1 ; primary
IN NS ns2.example.net.
@ IN MX 10 mail
@ IN MX 20 backup.mx.example.org.
ns1 IN A 192.0.2.53
ns2 600 IN A 192.0.2.54
www IN CNAME @
mail IN A 192.0.2.25
; a stray comment line
sho... | "api.dev.example.net. 3600 A 198.51.100.7\ndev.example.net. 3600 NS ns1.example.net.\nexample.net. 3600 MX 10 mail.example.net.\nexample.net. 3600 MX 20 backup.mx.example.org.\nexample.net. 3600 NS ns1.example.net.\nexample.net. 3600 NS ns2.example.net.\nexample.net. 3600 TXT \"v=spf1 mx -all\"\nmail.example.net. 3600 ... | Expand a BIND-style DNS zone fragment into fully qualified records.
1. Remove a ';' comment from each line: everything from the first ';' to the end of the line is dropped. Then drop lines that are empty after stripping trailing whitespace.
2. '$ORIGIN name' and '$TTL seconds' are directives that set the current origin... |
cmsw3b1lf005duvp2rboah3jz | contributor_item | Submission OAH3JZ | false | def transform(text):
raw_lines = text.split("\n")
unfolded = []
for line in raw_lines:
if line[:1] in (" ", "\t") and unfolded:
unfolded[-1] += line[1:]
else:
unfolded.append(line)
def unescape(value):
out = []
i = 0
while i < len(value):
... | BEGIN:VCARD
VERSION:3.0
N:Okonkwo;Adaeze;Q;Dr.;
FN:Dr. Adaeze Okonkwo
ORG:Longname Research Institute for Applied
Cartography;Mapping Division
TEL;TYPE=WORK,VOICE:+44 20 7946-0958
TEL;TYPE=CELL:+44 (7700) 900.123
EMAIL;TYPE=INTERNET;TYPE=PREF:adaeze@example.org
NOTE:Field survey lead\nAvailable Tuesdays
END:VCARD
BEG... | "Dr. Adaeze Okonkwo|Longname Research Institute for Applied Cartography / Mapping Division|adaeze@example.org|+442079460958,+447700900123\nBo Zhang|Solo Practice|bo@example.net,bo.zhang@work.example.net|-\nKiosk Support Desk|-|-|08005550199\ncontacts=3 withemail=2" | Flatten a stream of vCard 3.0 records into one line per contact.
1. First unfold the input: a line beginning with a space or a horizontal tab is a continuation of the previous line; remove exactly one leading whitespace character and append the rest to the previous line. Do this before any other parsing.
2. A contact r... |
cmsw3b1lf005cuvp2rgrl0pcn | contributor_item | Submission RL0PCN | false | def transform(text):
name = "Untitled"
entries = []
pending = None
for raw in text.split("\n"):
line = raw.strip()
if not line:
continue
if line.startswith("#"):
if line.startswith("#PLAYLIST:"):
name = line[len("#PLAYLIST:"):].strip()
... | #EXTM3U
#PLAYLIST:Night Drive
#EXTINF:213,Kessler Trio - Amber Underpass
tracks/amber_underpass.mp3
#EXTINF:-1,Harbour Radio Live
https://stream.example.org/harbour
# a stray comment that should be ignored
#EXTINF:95,Interlude
tracks/interlude.flac
#EXTINF:3067,Kessler Trio - The Long Way Back
/media/library/long way b... | "1. Kessler Trio | Amber Underpass | 3:33 | mp3\n2. <unknown> | Harbour Radio Live | --:-- | stream\n3. <unknown> | Interlude | 1:35 | flac\n4. Kessler Trio | The Long Way Back | 51:07 | none\n5. Nuria Vidal | Coda | 0:47 | ogg\nplaylist=Night Drive entries=5 known=4 total=0:57:02" | Turn an extended M3U playlist into a numbered track listing.
1. Ignore the '#EXTM3U' header and any blank line. A '#PLAYLIST:<name>' line sets the playlist name; if it never appears use 'Untitled'.
2. A '#EXTINF:<seconds>,<title>' line describes the next entry; seconds is an integer that may be -1 for unknown. The entr... |
cmsw3b1lf005iuvp2ea76qrub | contributor_item | Submission 76QRUB | false | import re
from decimal import Decimal, ROUND_HALF_UP
WIND = re.compile(r"^(\d{3}|VRB)(\d{2,3})(?:G(\d{2,3}))?KT$")
TEMP = re.compile(r"^(M?\d{1,2})/(M?\d{1,2})$")
def transform(text):
out = []
good = 0
bad = 0
for raw in text.split("\n"):
line = raw.strip()
if not line:
co... | EGLL 121350Z 24015G27KT 9999 -RA SCT012 BKN020 12/09 Q1008
KJFK 121351Z 00000KT 1/2SM FG VV002 M02/M03 A2992
LFPG 121400Z VRB03KT CAVOK 25/12 Q1015
YSSY 121430Z 09018KT 8000 SHRA FEW015 SCT030 19/14 Q1012
NZAA 121500Z 36004KT 3000 BR OVC004 07/07 Q0998
BROKEN 12Z
CYYZ 121530Z 31012KT 2SM -SN BKN008 M08/M11 A2975
| "EGLL 12/13:50Z wind=240@15ktg27 vis=10+km t=12C dp=9C qnh=1008hPa\nKJFK 12/13:51Z wind=calm vis=0.8km t=-2C dp=-3C qnh=1013.2hPa\nLFPG 12/14:00Z wind=VRB@03kt vis=CAVOK t=25C dp=12C qnh=1015hPa\nYSSY 12/14:30Z wind=090@18kt vis=8.0km t=19C dp=14C qnh=1012hPa\nNZAA 12/15:00Z wind=360@04kt vis=3.0km t=7C dp=7C qnh=998hP... | Decode METAR aviation weather reports. Process every non-blank line, stripped, in order.
1. Split on whitespace. The first token is the station identifier; the second must be a 7-character day-time group 'DDHHMMZ'. If it is missing or malformed, emit '<station> INVALID' and continue.
2. Scan the remaining tokens:
- ... |
cmsw3b1lf005fuvp26d6ggmal | contributor_item | Submission 6GGMAL | false | import hashlib
def transform(text):
gaps = []
data = bytearray()
marker = None
for raw in text.split("\n"):
line = raw.strip()
if not line:
continue
head = line.split("|", 1)[0].strip()
tokens = head.split()
if len(tokens) == 1 and all(c in "01234567... | 00000000 50 4b 03 04 14 00 00 00 08 00 21 00 4d 61 6b 65 |PK........!.Make|
00000010 66 69 6c 65 55 54 09 00 03 9c 2f 0a 65 9c 2f 0a |fileUT..../.e../|
00000020 65 75 78 0b 00 01 04 e8 03 00 00 04 e8 03 00 00 |eux.............|
00000040 0a 63 6c 65 61 6e 3a 0a |.clean:.|
00000038
| "GAP at 00000040\nlength=56\nmarker=ok\nsha256=8b1b7aa022519daaada9494262ad2a8e3a8204b9649b37a98818a0231da379e9\nprintable=25\ntext=PK........!.MakefileUT..../.e./.eux..............clean:." | Reconstruct the bytes described by a 'hexdump -C' listing.
1. Ignore blank lines. A line consisting only of hexadecimal digits is the trailing length marker; remember the last one seen.
2. Every other line starts with an 8-digit hexadecimal offset, then whitespace, then up to 16 two-digit hexadecimal byte values, then ... |
cmsw3b1lf005euvp2vy6vwbyk | contributor_item | Submission 6VWBYK | false | import json
def transform(text):
physical = text.split("\n")
logical = []
buffer = ""
continuing = False
for line in physical:
current = line.lstrip() if continuing else line
trailing = len(current) - len(current.rstrip("\\"))
if trailing % 2 == 1:
buffer += cur... | # database settings
! legacy comment style
db.host = localhost
db.port:5432
db.name postgres
db.host = 127.0.0.1
long.description = first fragment \
second fragment \
third fragment
path.windows = C\:\\logs\\app
empty.value =
key\ with\ space = present
greeting = café – ready
tabbed.value = left\tright
| {
"db.host": "127.0.0.1",
"db.name": "postgres",
"db.port": "5432",
"empty.value": "",
"greeting": "café – ready",
"key with space": "present",
"long.description": "first fragment second fragment third fragment",
"path.windows": "C:\\logs\\app",
"tabbed.value": "left\tright"
} | Parse a Java .properties file into JSON.
1. A logical line ends where a physical line does NOT end with an odd number of backslashes. When a line ends with a single backslash, that backslash and the newline are removed and the leading whitespace of the next physical line is stripped before joining.
2. Leading whitespac... |
cmsw3b1lf005huvp2bvhnee8v | contributor_item | Submission HNEE8V | false | def transform(text):
physical = text.split("\n")
logical = []
buffer = None
for line in physical:
piece = line
if buffer is not None:
piece = piece.lstrip()
piece = buffer + " " + piece
buffer = None
if piece.endswith("\\"):
buffer ... | CC = gcc
CFLAGS = -O2 -Wall
OBJ = main.o util.o
# default goal
all: build test
build: $(OBJ) banner.h
$(CC) $(CFLAGS) -o app $(OBJ)
@echo built
main.o: main.c util.h \
banner.h
$(CC) -c main.c
util.o: util.c util.h
$(CC) -c util.c
test: build ; ./app --selftest
.PHONY: all test clean
clean:
rm -f *.o... | "all: build,test recipes=0 phony=yes\nbuild: $(OBJ),banner.h,extra.h recipes=3 phony=no\nclean: - recipes=1 phony=yes\nmain.o: main.c,util.h,banner.h recipes=1 phony=no\ntest: build recipes=1 phony=yes\nutil.o: util.c,util.h recipes=1 phony=no\nmissing=$(OBJ),banner.h,extra.h,main.c,util.c,util.h" | Build a target report from a Makefile.
1. A physical line ending with a backslash continues onto the next line: remove the backslash and the newline and join with a single space, stripping the leading whitespace of the continuation.
2. A logical line starting with a TAB character is a recipe line belonging to the most ... |
cmsw3b1lf005guvp2yezr4zr3 | contributor_item | Submission ZR4ZR3 | false | import re
PATTERN = re.compile(r"^P(?:(\d+)W|(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?)$")
def transform(text):
out = []
ok = 0
total_sum = 0
for raw in text.split("\n"):
line = raw.strip()
if not line:
continue
negative = line.startswith("-")
body... | PT1H30M
P3DT4H15M30S
PT0S
P1W
PT90M
-PT45S
P2DT
PT1.5H
P1Y2M
P10D
P2WT3H
PT36H
banana
| "PT1H30M -> 5400 -> PT1H30M\nP3DT4H15M30S -> 274530 -> P3DT4H15M30S\nPT0S -> 0 -> PT0S\nP1W -> 604800 -> P7D\nPT90M -> 5400 -> PT1H30M\n-PT45S -> -45 -> -PT45S\nP2DT -> INVALID\nPT1.5H -> UNSUPPORTED\nP1Y2M -> UNSUPPORTED\nP10D -> 864000 -> P10D\nP2WT3H -> INVALID\nPT36H -> 129600 -> P1DT12H\nbanana -> INVALID\nok=8 su... | Normalize a list of ISO 8601 durations. Process every non-blank line in order after stripping it.
1. A duration may start with '-' meaning a negative value. After that it must start with 'P'.
2. Supported forms are 'PnW' (weeks, 7 days each) and 'P[nD][T[nH][nM][nS]]'. All component values are non-negative integers.
3.... |
cmsw3dojj0066uvp2sac5iwwh | contributor_item | Submission C5IWWH | false | import re
def transform(text):
entries = []
i = 0
while True:
at = text.find("@", i)
if at == -1:
break
brace = text.find("{", at)
if brace == -1:
break
etype = text[at + 1:brace].strip().lower()
depth = 0
end = brace
... | @article{knuth1984lp,
author = {Donald E. Knuth},
title = {Literate Programming},
journal = {The Computer Journal},
year = 1984,
volume = {27},
number = {2},
pages = {97--111}
}
@book{lamport1994latex, author={Leslie Lamport}, title={{LaTeX}: A Document
Preparation System}, publisher={Addison... | "anon2020notes: Anonymous (2020). Field Notes on Peat Bog Drainage.\nknuth1984lp: Knuth, D. E. (1984). Literate Programming. The Computer Journal, 27(2), 97-111.\nlamport1994latex: Lamport, L. (1994). LaTeX: A Document Preparation System. Addison-Wesley.\nostrom1990cpr: Ostrom, E. & Gardner, R. & Walker, J. M. (1990). ... | Format BibTeX entries as plain-text citations.
1. An entry starts at '@<type>{<key>,' and ends at the matching closing brace, counting brace nesting. The type is lower-cased; the key is the text up to the first comma.
2. Inside an entry, fields are 'name = value' separated by commas that are not inside braces. The name... |
cmsw3dojj0067uvp236vxv422 | contributor_item | Submission VXV422 | false | def transform(text):
def unescape(value):
replacements = [("\\F\\", "|"), ("\\S\\", "^"), ("\\T\\", "&"),
("\\R\\", "~"), ("\\E\\", "\\")]
for token, replacement in replacements:
value = value.replace(token, replacement)
return value
segments = []
... | MSH|^~\&|LIS|RiverLab|EHR|Clinic|20240117093000||ORU^R01|MSG00023|P|2.5
PID|1||A12345^^^MRN||Ramirez^Elena^Quiteria||19870204|F
OBR|1||LAB998|CBC^Complete Blood Count
OBX|1|NM|WBC^White Blood Cells||6.2|10*3/uL|4.0-11.0|N|||F
OBX|2|NM|HGB^Hemoglobin||10.1|g/dL|12.0-16.0|L|||F
OBX|3|NM|PLT^Platelets||702|10*3/uL|150-400... | "patient=Ramirez, Elena Quiteria (A12345) dob=1987-02-04 sex=F\nWhite Blood Cells: 6.2 10*3/uL\nHemoglobin: 10.1 g/dL [LOW]\nPlatelets: 702 10*3/uL [CRITICAL-HIGH]\nTechnologist note: Sample hemolyzed & slightly clotted\nresults=4 abnormal=2 notes=2" | Extract a lab report from an HL7 v2 message.
1. Segments are the non-blank lines, stripped. Fields within a segment are separated by '|', components within a field by '^'.
2. Split into fields and components first, and only then decode these escape sequences inside each component: '\\F\\' -> '|', '\\S\\' -> '^', '\\T\\... |
cmsw3dojj0064uvp23wudbmk5 | contributor_item | Submission UDBMK5 | false | import re
ENCODED_WORD = re.compile(r"^=\?utf-8\?Q\?(.*)\?=$", re.IGNORECASE)
def transform(text):
lines = text.split("\n")
if lines and lines[-1] == "":
lines.pop()
stats = {"escapes": 0}
def decode(payload, underscore_is_space=False):
data = bytearray()
i = 0
while... | =?utf-8?Q?Caf=C3=A9_planning_meeting?=
Hello team,
This paragraph was wrapped by the mail=
er and must be rejoined without a space.
Budget: 1=2C500=E2=82=AC plus 5=25 handling.
Tabs=09and=20spaces survive the round trip.
Na=C3=AFve r=C3=A9sum=C3=A9 attached.
-- =
Signature block
| "Café planning meeting\nHello team,\nThis paragraph was wrapped by the mailer and must be rejoined without a space.\nBudget: 1,500€ plus 5% handling.\nTabs\tand spaces survive the round trip.\nNaïve résumé attached.\n-- Signature block\nlines=7 soft=2 escapes=15 nonascii=5" | Decode a quoted-printable message body.
1. Work line by line over the input, dropping a single trailing empty line if the text ends with a newline.
2. A line ending with '=' has a soft line break: remove that '=' and join the line with the next one before decoding. Count how many soft breaks were removed.
3. In the joi... |
cmsw3dojj0063uvp2md41v1ug | contributor_item | Submission 41V1UG | false | import re
from fractions import Fraction
MIXED = re.compile(r"^(\d+)\s+(\d+)/(\d+)\s+(.*)$")
FRACTION = re.compile(r"^(\d+)/(\d+)\s+(.*)$")
DECIMAL = re.compile(r"^(\d+\.\d+|\d+)\s+(.*)$")
def transform(text):
lines = [ln for ln in text.split("\n") if ln.strip()]
factor = Fraction(1)
body = []
for in... | scale: 3/2
2 1/4 cups flour
1/2 tsp fine salt
3 large eggs
0.75 cup whole milk
1 pinch grated nutmeg
2/3 cup caster sugar
a splash of vanilla
12 blanched almonds
1 1/3 tbsp cold butter
| "3 3/8 cups flour\n3/4 tsp fine salt\n4 1/2 large eggs\n1 1/8 cup whole milk\n1 1/2 pinch grated nutmeg\n1 cup caster sugar\na splash of vanilla\n18 blanched almonds\n2 tbsp cold butter\nscaled=8 passthrough=1" | Scale a recipe's ingredient quantities.
1. The first non-blank line must be 'scale: <factor>' where the factor is an integer, a decimal number or a fraction like '3/2'. Parse it as an exact rational number.
2. Every following non-blank line is an ingredient line. Strip it, then try to read a leading quantity, which is ... |
cmsw3dojj0068uvp2hn23pot7 | contributor_item | Submission 23POT7 | false | from decimal import Decimal, ROUND_HALF_UP
DIGITS = {"black": 0, "brown": 1, "red": 2, "orange": 3, "yellow": 4,
"green": 5, "blue": 6, "violet": 7, "gray": 8, "white": 9}
MULTIPLIERS = dict((name, Decimal(10) ** value) for name, value in DIGITS.items())
MULTIPLIERS["gold"] = Decimal("0.1")
MULTIPLIERS["silv... | brown black red gold
yellow violet orange
green blue black brown
red red red red
orange white brown silver
blue gray gold gold
black brown red
brown grey red gold
brown black black red brown
purple haze orange
red red
| "brown black red gold -> 1 kohm +/-5%\nyellow violet orange -> 47 kohm +/-20%\ngreen blue black brown -> 56 ohm +/-1%\nred red red red -> 2.2 kohm +/-2%\norange white brown silver -> 390 ohm +/-10%\nblue gray gold gold -> 6.8 ohm +/-5%\nblack brown red -> 100 ohm +/-20%\nbrown grey red gold -> 1.8 kohm +/-5%\nbrown bla... | Decode resistor colour bands into resistance values.
1. Each non-blank line is one resistor: whitespace-separated colour names, lower-cased before lookup. Accept 'grey' as a spelling of 'gray'.
2. Digit colours are black 0, brown 1, red 2, orange 3, yellow 4, green 5, blue 6, violet 7, gray 8, white 9.
3. Multiplier co... |
cmsw3dojj0065uvp2qukf4cq8 | contributor_item | Submission KF4CQ8 | false | import re
PLAN = re.compile(r"^1\.\.(\d+)$")
TEST = re.compile(r"^(not ok|ok)\b\s*(\d+)?\s*(.*)$")
def transform(text):
plan = None
tests = []
for raw in text.split("\n"):
if not raw.strip():
continue
if raw[0].isspace():
continue
line = raw.strip()
... | TAP version 13
1..8
ok 1 - loads configuration
not ok 2 - parses response header
---
message: expected 200 but got 500
...
ok 3 - retries transient errors # SKIP network disabled in CI
ok 4 - writes cache entry
not ok 5 - flushes the queue # TODO known flake, see #421
# a bare comment line
ok 6 - closes the socke... | "FAIL 2 parses response header\nFAIL 7 reports metrics\nSKIP 3 retries transient errors (network disabled in CI)\nSKIP 8 shuts down cleanly (requires root)\nplan=8 ran=8 pass=3 fail=2 skip=2 todo=1\nresult=FAIL" | Summarize a TAP version 13 test stream.
1. Ignore a leading 'TAP version <n>' line. A line matching '1..<n>' is the plan; remember n. Ignore indented lines (they are YAML diagnostics) and lines starting with '#'.
2. Every other non-blank line must start with 'ok' or 'not ok', optionally followed by a test number and th... |
cmswrwxvz0087uvp26rye53qo | contributor_item | Submission YE53QO | false | import json
def transform(text):
counts = {}
for line in text.strip().split('\n'):
record = json.loads(line)
if record.get('action') == 'login':
user = record['user']
counts[user] = counts.get(user, 0) + 1
return json.dumps(counts) | {"user":"alice","action":"login"}
{"user":"bob","action":"login"}
{"user":"alice","action":"logout"}
{"user":"carol","action":"login"} | {
"alice": 1,
"bob": 1,
"carol": 1
} | Parse newline-delimited JSON (NDJSON) records and count how many records have action 'login', grouped by user, returning a JSON object. |
cmswrwxvz0089uvp2o2k6l6zc | contributor_item | Submission K6L6ZC | false | import json
from urllib.parse import quote
def transform(text):
params = json.loads(text)
parts = []
for key in sorted(params.keys()):
parts.append(f"{quote(str(key))}={quote(str(params[key]))}")
return '&'.join(parts) | {"q": "python tutorial", "page": "2", "sort": "relevance"} | "page=2&q=python%20tutorial&sort=relevance" | Convert a JSON object of query parameters into a URL query string, with keys sorted alphabetically and values percent-escaped for spaces. |
cmswrwxvz008buvp2q2wzdf7l | contributor_item | Submission WZDF7L | false | import re
import json
def transform(text):
pattern = r'\(?(\d{3})\)?[.\-\s]?(\d{3})[.\-](\d{4})'
matches = re.findall(pattern, text)
normalized = [f"{a}-{b}-{c}" for a, b, c in matches]
return json.dumps(normalized) | Call me at 555.123.4567 or my office line (555) 987-6543. Backup: 555-111-2222 | [
"555-123-4567",
"555-987-6543",
"555-111-2222"
] | Extract all US-style phone numbers from text (formats with dots, dashes, or parentheses) and normalize each to XXX-XXX-XXXX, returning a JSON array in order found. |
cmswrwxvz008auvp216w6gc1o | contributor_item | Submission W6GC1O | false | import json
def transform(text):
result = {}
for line in text.strip().split('\n'):
key_part, _, value = line.partition('=')
keys = [k.strip() for k in key_part.strip().split('.')]
value = value.strip()
node = result
for k in keys[:-1]:
node = node.setdefault(... | app.debug = true
app.port = 8080
db.host = localhost
db.port = 5432 | {
"app": {
"debug": "true",
"port": "8080"
},
"db": {
"host": "localhost",
"port": "5432"
}
} | Parse dotted-key = value config lines into a nested JSON object, splitting each key on '.' to build nested levels. |
cmsws8ydl008euvp2f2shkpqe | contributor_item | Submission SHKPQE | false | def transform(text):
vowels = "aeiou"
words = text.strip().split()
result = []
for word in words:
if word[0] in vowels:
result.append(word + "way")
else:
i = 0
while i < len(word) and word[i] not in vowels:
i += 1
result.app... | hello world this is fun | "ellohay orldway isthay isway unfay" | Translate each space-separated word into Pig Latin: move the leading consonant cluster to the end and append 'ay'; words starting with a vowel just get 'way' appended. Return the words space-joined. |
cmsws9cdz008kuvp2u4rs9t2e | contributor_item | Submission RS9T2E | false | import json
from collections import Counter
def transform(text):
words = text.strip().split()
counts = Counter(words)
ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
return json.dumps(ranked[:2]) | the cat sat on the mat the cat ran | [
[
"the",
3
],
[
"cat",
2
]
] | Find the 2 most frequent words. Break ties by choosing the alphabetically earlier word first. Return a JSON array of [word, count] pairs. |
cmsws9nle008puvp2v32gmixh | contributor_item | Submission 2GMIXH | false | import json
def is_balanced(line):
depth = 0
for ch in line:
if ch == '(':
depth += 1
elif ch == ')':
depth -= 1
if depth < 0:
return False
return depth == 0
def transform(text):
lines = text.split('\n')
return json.dumps([is_bala... | (a(b)c)
(a(b)
()()
)( | [
true,
false,
true,
false
] | For each line, determine whether its parentheses are balanced (every '(' has a matching later ')' and never goes negative). Return a JSON array of booleans, one per line. |
cmswsarct008uuvp2e9xfgpk3 | contributor_item | Submission XFGPK3 | false | import json
import statistics
def transform(text):
nums = [int(line) for line in text.strip().split('\n')]
stats = {
"min": min(nums),
"max": max(nums),
"mean": round(statistics.mean(nums), 2),
"stdev": round(statistics.pstdev(nums), 2)
}
return json.dumps(stats) | 4
8
15
16
23
42 | {
"min": 4,
"max": 42,
"mean": 18,
"stdev": 12.32
} | Compute basic statistics (min, max, mean, and population standard deviation, each rounded to 2 decimals) over the list of integers (one per line), returning a JSON object with keys min, max, mean, stdev. |
cmswsarcs008ruvp27oaxx5o6 | contributor_item | Submission AXX5O6 | false | def transform(text):
if not text:
return ""
result = []
prev = text[0]
count = 1
for ch in text[1:]:
if ch == prev:
count += 1
else:
result.append(f"{prev}{count}")
prev = ch
count = 1
result.append(f"{prev}{count}")
ret... | aaabbbcccd | "a3b3c3d1" | Apply run-length encoding to the text: each maximal run of a repeated character becomes '<char><count>'; a run of length 1 still gets a count of 1. |
cmswsarct008suvp23pws2752 | contributor_item | Submission WS2752 | false | import ipaddress
import json
def transform(text):
network = ipaddress.ip_network('192.168.1.0/24')
result = []
for line in text.strip().split('\n'):
ip = ipaddress.ip_address(line.strip())
if ip in network:
result.append(line.strip())
return json.dumps(result) | 192.168.1.5
192.168.2.10
192.168.1.200
10.0.0.1 | [
"192.168.1.5",
"192.168.1.200"
] | Given a fixed CIDR block of 192.168.1.0/24, determine which of the listed IPv4 addresses (one per line) fall inside it, returning a JSON array of the matching addresses in order. |
cmsx3d5d5002jx3p2oi4ce8jq | contributor_item | Submission 4CE8JQ | false |
import re
import json
def transform(text):
pattern = re.compile(r'^([A-Za-z_][\w.]*(?:Error|Exception|Warning)): (.+)$', re.MULTILINE)
counts = {}
examples = {}
for m in pattern.finditer(text):
exc_type, msg = m.group(1), m.group(2).strip()
counts[exc_type] = counts.get(exc_type, 0) + ... | 2026-08-10 10:22:01 ERROR Processing failed
Traceback (most recent call last):
File "app.py", line 10, in <module>
main()
File "app.py", line 5, in main
raise ValueError("bad input")
ValueError: bad input
2026-08-10 10:22:05 ERROR Processing failed
Traceback (most recent call last):
File "app.py", line 22... | [
{
"type": "ValueError",
"count": 2,
"example_message": "bad input"
},
{
"type": "KeyError",
"count": 1,
"example_message": "'missing_field'"
}
] | This is an application log containing multiple Python tracebacks. Find every unindented line matching the pattern '<ExceptionType>: <message>' (where ExceptionType ends in Error, Exception, or Warning), and count how many times each exception type occurs, keeping the first message seen for each type as its example_mess... |
cmsx3d5d5002sx3p2ksmlh1e4 | contributor_item | Submission MLH1E4 | false |
import json
import re
def transform(text):
blocks = [b for b in text.strip('\n').split('\n\n') if b.strip()]
records = []
for block in blocks:
lines = [l.strip() for l in block.strip('\n').split('\n')]
recipient = lines[0]
street = lines[1]
city_line = lines[2]
m = ... | John Carter
482 Elm Street
Springfield, IL 62704
Maria Gomez
19 Rue de Paris
Paris, TX 75460
Wei Zhang
1200 5th Ave Apt 3B
New York, NY 1001
Tom Baker
77 Ocean Drive
Miami, FL 33139 | [
{
"recipient": "John Carter",
"street": "482 Elm Street",
"city": "Springfield",
"state": "IL",
"zip": "62704",
"zip_valid": true
},
{
"recipient": "Maria Gomez",
"street": "19 Rue de Paris",
"city": "Paris",
"state": "TX",
"zip": "75460",
"zip_valid": true
},
... | This text contains shipping address blocks separated by blank lines. Each block has exactly 3 lines: recipient name, street address, and 'City, ST ZIP'. Parse each block into a record with keys recipient, street, city, state, zip, and zip_valid (true only if the zip is exactly 5 digits). Return a JSON array of these re... |
cmsx3d5d5002tx3p22po3070b | contributor_item | Submission O3070B | false |
def roman_to_int(s):
vals = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
prev = 0
for ch in reversed(s):
v = vals[ch]
if v < prev:
total -= v
else:
total += v
prev = v
return total
def transform(text):
l... | item,quantity_roman
Widget,XIV
Gadget,IX
Gizmo,XL
Sprocket,IV
Doohickey,MCMXCIX | "item,quantity_roman,quantity\nWidget,XIV,14\nGadget,IX,9\nGizmo,XL,40\nSprocket,IV,4\nDoohickey,MCMXCIX,1999" | This CSV has an 'item' column and a 'quantity_roman' column containing Roman numerals. Convert each Roman numeral to its integer value and append it as a new 'quantity' column. Return the result as CSV text (comma-separated, newline-joined, no trailing newline), keeping the original columns and appending the new one. |
cmsx3d5d50034x3p24xuj7sdu | contributor_item | Submission UJ7SDU | false |
import json
def transform(text):
data = json.loads(text)
lines = []
def walk(node, depth):
lines.append(' ' * depth + f"[{node['score']}] {node['author']}: {node['text']}")
children = sorted(node.get('replies', []), key=lambda c: -c['score'])
for child in children:
wa... | {
"id": "c1",
"author": "alice",
"score": 15,
"text": "Great post!",
"replies": [
{
"id": "c2",
"author": "bob",
"score": 42,
"text": "I agree completely.",
"replies": [
{
"id": "c4",
"author": "carol",
"score": 3,
"text": "Same... | "[15] alice: Great post!\n [42] bob: I agree completely.\n [3] carol: Same here.\n [7] dave: Not sure about this." | This is a JSON comment tree where each node has id, author, score, text, and a 'replies' list of child nodes. Flatten the tree into indented text lines: at every level, sort sibling nodes by score descending, and render each node as '<indent>[score] author: text' where indent is two spaces per depth level (root is dept... |
cmsx3d5d50038x3p2zqni7i5l | contributor_item | Submission NI7I5L | false |
import json
def parse_value(v):
v = v.strip()
if v.lower() == 'true':
return True
if v.lower() == 'false':
return False
try:
return int(v)
except ValueError:
pass
try:
return float(v)
except ValueError:
pass
return v
def transform(text):... | [base]
timeout = 30
retries = 3
env = production
[service_a]
extends = base
timeout = 10
[service_b]
extends = service_a
retries = 5
debug = true | {
"base": {
"timeout": 30,
"retries": 3,
"env": "production"
},
"service_a": {
"timeout": 10,
"retries": 3,
"env": "production"
},
"service_b": {
"timeout": 10,
"retries": 5,
"env": "production",
"debug": true
}
} | This is an INI-like config with sections that may declare 'extends = <parent_section>' to inherit key/value pairs from another section, with the child's own keys overriding the parent's (recursively resolved, since a parent may itself extend another section). The 'extends' key must not appear in the final output. Conve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.