Tell us what works and what could be better. We read every submission.
@abehmiel·54 public vizzes
The visualization maps a personal collection of adapted resources as a node-link diagram, showing how different files, tools, and references connect through shared use. It reads data from a Markdown file containing resource links, including an external blog post on clustering section titles, and renders the network using a force-directed layout with `d3.forceSimulation`. Nodes represent individual resources, with links drawn as SVG lines, and the code also employs `d3.select` and `d3.scaleOrdinal` for styling and positioning. The graph updates dynamically as forces settle, revealing clusters of related materials.
This visualization example uses the Natural Language Toolkit’s `pos_tag` and `str2tuple` functions to map part-of-speech tags from the Penn Treebank to plain-English definitions. The `clarify_pos` function accepts a tag string and returns a human-readable description, such as “conjunction, coordinating” for “CC” or “determiner” for “DT.” The code is designed to apply directly to pandas DataFrames via a `.apply()` call, creating a new column that translates each tag for easier analysis. The mapping covers common tags including nouns, verbs, adjectives, adverbs, pronouns, and prepositions.
This example converts tabular PDF data into a clean CSV file and a pandas DataFrame. It reads a government PDF containing space-delimited user IDs and handles using `tabula.read_pdf` with `pages='all'`, then splits the single messy column into two properly named columns (`user id` and `handle`) via pandas string methods. The cleaned data is written to `exhibit_b.csv` using `df.to_csv`. The script demonstrates a practical workflow for fixing poorly formatted government tabular releases with pandas and tabula-py.
This example demonstrates how to create square matplotlib figures with large axis labels and precisely controlled tick counts. The `create_figure` function builds a figure with a fixed square size and uses `MaxNLocator` to set the number of x-axis ticks, while `format_axes` applies custom numeric formatting via `FormatStrFormatter` and independently controls tick counts and label sizes for both axes. The code relies on matplotlib’s `figure`, `add_subplot`, and `tick_params` APIs to produce clean, publication-ready plots.
This example shows how to align two Pandas DataFrames with slightly misspelled index labels, producing a joined table where each row pairs a number with its corresponding letter. The code uses `difflib.get_close_matches` within a `map` operation on the second DataFrame’s index to find the closest match in the first DataFrame’s index, then applies `df1.join(df2)` to merge them. The result corrects mismatches like "too" to "two" and "fours" to "four", demonstrating a fuzzy-join pattern with Pandas’ built-in join API.
This example scrapes a Buzzfeed article and converts its text into clean, tokenized sentences for natural language processing. It shows the pipeline from raw HTML to normalized, sentence-segmented data. The scraper uses BeautifulSoup and requests to extract paragraph elements with the class `subbuzz-text`. Text cleaning relies on the `unicodedata` module and regex via `re`, while sentence tokenization uses NLTK’s Punkt tokenizer. The final output is a single string of joined sentences, ready for further NLP analysis.
This visualization maps the conversational flow and technical stack of the NYC Botmakers meetup, derived from hand-written notes taken at Babycastles. It charts the connections between topics like chatbots, generative Twitter bots, visual recognition, and video bots, linking each to specific APIs and tools such as Dialogflow, Tracery.io, Glitch, Clarifai, and moviepy. The data source is an unstructured org-mode file, and the rendering uses a force-directed graph to show how presenters and their projects relate.
A gist transcript of the New York City Council’s hearing on algorithmic transparency bill 16-96 becomes a force-directed network graph. The visualization maps speakers, organizations, and policy topics as linked nodes, with clustering and spatial proximity conveying conversational relationships. It uses `d3.forceSimulation` and `d3.drag` to position and interact with the nodes, while a side panel displays the raw transcript text. The source data is the gist’s plain-text notes, parsed into a JSON structure of entities and their mentions.
This example presents a Keybase proof as a text-based verification document, showing how a user authenticates their GitHub identity through a signed JSON object and PGP message. The plain-text rendering displays the structured claim, including the public key fingerprint, signature block, and command-line instructions. The data originates from the Keybase proof format, with the visible code using standard cryptographic libraries for signing and verification. The visualization relies on simple typographic layout to make the proof’s components—identity, signature, and instructions—clearly readable without graphical charts.
A deliberately obfuscated Lua implementation of Roman numeral conversion hides all arithmetic and constants behind absurdly named functions and Monte Carlo simulation. The code defines numerals like Cicero() for "C" and IIIII() for "V", then derives values by random sampling. It uses the Busted testing framework to validate conversion functions sourced from Rosetta Code.
This example scrapes press releases from pressreleasepoint.com, saving each article’s text to individual files while printing both the download URL and content to the console. It demonstrates web scraping with BeautifulSoup and requests, iterating through 2,497 paginated index pages and extracting text from the `content-press_release` class. The script handles missing links with a broad exception pass, outputs verbose progress logs, and organizes saved files by page and index.
This visualization example presents a collection of Python utility functions for solving HackerRank challenges, organized in a single file. It demonstrates reusable code snippets for common algorithmic tasks, including greatest common divisor and least common multiple calculations using the `fractions.gcd` function, prime number generation with an optimized sieve, bitfield conversion through `bin(n)`, string reversal, and list sorting. The code also includes helper functions like `lcm` and `primes` with docstrings explaining their inputs and outputs. The gist serves as a reference library, showing how to implement and structure these fundamental algorithms for competitive programming problems.
This notebook introduces core NLP concepts using the spaCy library, demonstrating how to analyze text structure through part-of-speech tagging and dependency parsing. It explains grammatical abstractions like sentences and word functions while acknowledging their limitations, particularly for poetry. The code example uses spaCy’s built-in pipeline to process English sentences, showing token attributes and linguistic annotations. Written in Python 2.7, it also mentions alternatives like NLTK and resources for other languages. The notebook’s content mixes explanatory prose with executable cells, offering a beginner-friendly tour of how language can be computationally decomposed.
This tutorial demonstrates how word vectors encode semantic similarity through a progression from simple animal characteristics to high-dimensional text representations. It uses matplotlib to plot animal data points in two-dimensional space, calculating Euclidean distances between them. The notebook also employs Gensim’s Word2Vec model to create and explore word embeddings, including nearest-neighbor queries and analogical reasoning. The code is written in Python 2.7 within a Jupyter Notebook, with all examples released under CC0 and explanatory text under CC BY 4.0.
This example demonstrates how to test the `is_prime` function across multiple input-output pairs using pytest’s parameterized testing. It shows a table of seven cases, ranging from negative numbers to large primes, each paired with an expected boolean result. The code uses the `@pytest.mark.parametrize` decorator to define the `x` and `output` arguments, then asserts that `is_prime(x)` matches the expected output. The test data is written directly in the decorator’s list, sourced from James Routley’s blog, and the test runs each case as a separate pytest test.
A script downloads every CBS Corporation press release from 2009 through 2017, saving each article’s text as a separate file in a `press-releases/` directory. It uses BeautifulSoup to parse HTML from both year-index pages and individual article pages, extracting the main content from the `entry-content` class. The code iterates through paginated year listings, printing each URL and the downloaded text to the console, and writes the text to numbered files. Requests handles the HTTP fetching, while `urljoin` and glob organize the file paths.
This example scrapes Fox News press releases from the press archive for years 2011–2017, organized by month, and saves each release as a separate text file. It uses BeautifulSoup and the `requests` library to parse HTML pages, extract article text from elements with class `hentry`, and prints verbose download progress and content to the console while writing files to a `press-releases/` directory. The script iterates through URL patterns for each year and month, handling missing pages silently.
This visualization demonstrates the F1-score expectation maximization algorithm for optimizing predictions from posterior probabilities. It plots the expected F1 score against the number of positive labels (k), showing two curves for predictions with and without a "None" label, and marks the optimal k with a black dot. The code uses NumPy for dynamic programming calculations, pandas for data handling, and Matplotlib’s pyplot API with the ggplot style to render the line chart, annotations, and axis labels.
The example demonstrates how Keras’s `ImageDataGenerator` applies random geometric transformations and normalization to a single input image, producing a grid of augmented variations saved as JPEG files. It shows the effects of rotation, width and height shifts, shear, zoom, and horizontal flipping on a cat photo, with pixel fill mode set to nearest. The code loads an image via `load_img`, converts it to a NumPy array with `img_to_array`, reshapes it into a batch, and then uses the generator’s `.flow()` method to generate and save 20 preview images to a directory. The approach relies entirely on Keras’s preprocessing API, with no custom data source or rendering.
This example demonstrates a one-hot encoding function that converts an array of categorical object labels into a binary matrix format suitable for training neural networks in Keras. The code defines `one_hot_encode_object_array`, which uses NumPy’s `np.unique` with `return_inverse=True` to map each unique string to an integer ID, then passes those IDs to `np_utils.to_categorical` from Keras to produce the final encoded vectors. It applies this transformation separately to training and testing label arrays (`train_y` and `test_y`), storing the results as `train_y_ohe` and `test_y_ohe` for subsequent model building.
This example demonstrates a simple Python unit test using the Arrange-Act-Assert pattern. It shows a test function `test_reverse` that verifies the in-place reversal of a list of Greek letter names, checking both the return value and the mutated list state. The code uses Python’s built-in `list.reverse` method and `assert` statements. The test data is a hardcoded list, and the rendering approach is plain console output from a test runner, with no visualization library involved.
This visualization demonstrates a Bash script that automates SSH agent setup on first terminal use after reboot. It shows the conditional logic checking for an existing SSH authentication socket, then initializing `ssh-agent` if needed, symlinking the socket to a stable path, and verifying loaded keys with `ssh-add`. The code uses standard shell commands (`eval`, `ln -sf`, `export`) and SSH utilities (`ssh-agent`, `ssh-add`) from a Unix StackExchange answer. The rendering approach is a literal code snippet with syntax highlighting, sourced from a gist by abehmiel, displaying the `.bashrc` addition for seamless key management.
This example demonstrates a live Twitter stream filter that detects tweets containing “hello world” phrase variants and prints the matching tweet and a randomized commentary message. It uses Tweepy’s StreamListener to monitor the public stream for keywords “hello” and “world,” ignoring retweets. On a match, it constructs a reply message with the tweet’s URL and prints it, while the retweet and status-update actions remain commented out. The code relies on Tweepy’s OAuth authentication and the Twitter streaming API, with credentials loaded from a separate creds module.
This example shows a minimal Twitter bot framework that continuously scans for tweets containing variations of “Hello world” and prints each matching tweet alongside a randomly selected comment phrase. It uses the Tweepy library to authenticate with Twitter’s API via OAuth and iterates through search results with `tweepy.Cursor`. For each found tweet, the code prints the author’s screen name and text, then constructs a status message embedding the tweet’s URL; retweeting and posting are commented out, while a five-second sleep prevents rate limiting. The data source is live Twitter search results, and the rendering is plain text output to the console.
This example collects tweets for the irony-sarcasm dataset, pulling tweet text for eight labeled subtypes (regular, sarcasm, irony, and their test splits) using Tweepy’s `statuses_lookup` API. It reads tweet IDs from tab-separated CSV files provided by Roman Klinger’s dataset, batches them by 100 with sleep delays to respect rate limits, and stores the full JSON metadata for each tweet. The code then minimizes each record to its `text` field and writes both a JSON master file and a CSV version per subtype, using pandas for ID loading and Python’s `json` and `csv` modules for output.
This visualization documents a systemd service and shell script that work around a Linux kernel touchscreen bug on the Dell XPS 13 9350. The example shows how the script determines the correct GPIO pin by parsing `/sys/kernel/debug/pinctrl/INT344B:00/pins` with `awk` and reading the `gpio-ranges` file with `sed`, then exports the pin via `/sys/class/gpio/export`, sets its direction to `high`, and unexports it. It also includes a kernel-version check using `uname -r` that halts execution when the installed kernel differs from the patched version.
Pico-8 communic8 demonstrates a serialization and messaging interface between a Pico-8 cartridge and JavaScript, using a shared memory buffer at `0x5f80` with a header-based handshake protocol. The code defines custom serializers for byte, boolean, number, array, tuple, opacify, and string types, mapping Pico-8 characters to indices for efficient transmission. A coroutine-based receiver queues incoming messages, while the `_update_communic8` function reads header flags and pokes memory to coordinate reads and writes. The example shows how to structure binary data exchange with type-aware packing and unpacking between two runtimes.
This example shows two confusion matrices for evaluating a GradientBoostingClassifier’s predictions on a binary test set, using scikit-learn’s `confusion_matrix` function. The first plot displays raw counts of true versus predicted labels, while the second normalizes each row to show proportions. Both use `plt.imshow` with a blue colormap, annotated with counts or normalized values, and include axis labels for true and predicted classes. The code defines a custom `plot_confusion_matrix` function that applies `imshow`, colorbar, and text annotations, and saves each figure as a PNG.
This example demonstrates exploratory data analysis and automated model selection for a website conversion dataset, revealing patterns such as higher conversion rates among younger users, repeat customers, and those visiting more pages. It first uses pandas to group data and matplotlib to plot conversion trends by pages visited, country, and age. The workflow then applies scikit-learn’s train_test_split and TPOTClassifier to automatically optimize a machine-learning pipeline, exporting the final model to a Python file.
This example merges nine years of JSON-format Trump tweets into a single CSV file, consolidating chronological tweet data into one tabular output. It uses Python’s `json` library to load each yearly file and the `csv` module’s `csv.writer` to write rows. The script first writes a header row from the keys of the first tweet, then appends each tweet’s values for every file in sequence. The resulting `trumptweets.csv` preserves all original fields without transformation, enabling further analysis or visualization of the combined dataset.
The example demonstrates a straightforward text-transformation utility that converts any given string to Title Case, capitalizing the first letter of each word while lowercasing the remaining characters. It operates on a single string input and returns the formatted result. The code relies on the native JavaScript `String.replace()` method with a regular expression (`/\w\S*/g`) to match word boundaries, and applies a callback function that uses `charAt()`, `toUpperCase()`, and `substr()` to restructure each word. No external libraries or frameworks are involved, and the function is self-contained, making it a reusable snippet for formatting labels or headings in web applications.
This example cleans Fitbit activity and sleep data downloaded as CSV files. It loads the data with pandas, removes rows with zero activity calories or zero time in bed, and converts date strings into datetime objects using `datetime.strptime`. It then adds a weekday column via `strftime('%A')`, preparing the data for further analysis or visualization. The script outputs two data frames, one for activities and one for sleep, each with a date and weekday column.
This visualization maps a week of daily journal entries from an Org-mode file, with each weekday as a node. It uses d3.forceSimulation to position the days and d3.select with data joins to render circles and text labels. The entry content is parsed from the plain-text structure, showing which days have notes under categories like Weather, Plans, and General. A radial or linear layout is not used; instead, the force-directed graph reveals the frequency and density of logged items across the week, with no interaction or animation beyond the initial simulation tick.
This example demonstrates a basic HTTP request to a remote API, retrieving JSON data and checking the response status. It uses Python’s `requests` library to send a GET request to `https://www.something.com`, passing custom headers with a token and query parameters. The code calls `response.json()` to parse the returned payload and accesses `response.status_code` to verify the request’s success. The data source is the external endpoint, and the rendering approach is absent, as the snippet focuses solely on the request lifecycle.
This example demonstrates how to retrieve the key associated with the maximum value in a Python dictionary. It defines a dictionary with four string keys and numeric values, including a very large integer, then uses the built-in `max` function with the `key=some_dict.get` argument to find the correct key. The code shows a concise, idiomatic approach to this common data-processing task without relying on external libraries, making it a useful snippet for Python developers.
This visualization demonstrates the Bi-Term Topic Model (BTM) in action, showing how topic distributions emerge from short-text co-occurrence patterns. The code implements a pure Python Gibbs sampler that infers latent topics from observed biterms, with the model's parameters visualized as topic-term probability matrices. It uses the `BTMGibbsSampler` class to iteratively update topic assignments via multinomial sampling, relying on the `random` module for stochastic draws and custom normalization functions. The rendering shows the inferred `BTModel`'s topic proportions and per-topic word distributions, highlighting how BTM handles sparse short-text data through biterm aggregation.
This example demonstrates multiple ways to import CSV data into pandas DataFrames, highlighting how to handle missing values, specify column names, set indexes, skip rows, and interpret thousands separators. The code creates a sample dataset with mixed data types—including strings, integers, and missing values marked with periods—then saves it as a CSV file before applying various `pd.read_csv` parameters. It shows techniques like using `header=None`, the `names` parameter, `index_col` for single or multi-column indexes, `na_values` for custom missing value sentinels, `skiprows` to omit initial lines, and `thousands=','` to parse formatted numbers. The examples use pandas' built-in CSV reader, sourced from Chris Albon's original tutorial.
This example shows how a single command-line script resizes a GIF to 120 by 120 pixels using Gifsicle, a dedicated GIF manipulation tool. The visible code calls `gifsicle --resize 120x120 file.gif` and writes the output to `out-120.gif`, preserving the animation’s frame structure while scaling its dimensions. The visualization highlights the contrast between the original and resized output, demonstrating the tool’s straightforward API for batch or single-file resizing. No additional JavaScript or rendering libraries appear in the provided snippet.
This palette defines ten colorblind-differentiable RGB tuples for Matplotlib plotting, including dark blue, orange, half-gray, sky blue, burnt sienna, and peach. The code assigns each color as a tuple of RGB values scaled to 0–1, suitable for direct use in Matplotlib functions like `plot` or `scatter`. The palette draws on the Okabe-Ito scheme to maintain distinction across common color vision deficiencies, and the file lists the colors with descriptive names, though it does not include a visualization or usage example beyond the color definitions.
This example shows four distinct data series plotted together in a single three-dimensional scatterplot, with each series assigned a different color (black, red, blue, and green) and a corresponding legend label. The plot uses Matplotlib’s `add_subplot` with the `projection='3d'` option to create the axes, then calls `ax.scatter` four times for the x, y, and z coordinates of each dataset. It sets axis labels via `xlabel`, `ylabel`, and `zlabel`, adds a title, and saves the figure as a PNG using `savefig`. The code comments note that 3D plots are generally discouraged for transferability but useful for exploratory analysis.
This example creates a publication-quality figure with two stacked Matplotlib subplots, each displaying four labeled data series with distinct marker styles. The code enables TeX rendering for bold mathematical text throughout the figure, including axis labels, titles, and annotations, while a shared y-axis label spans both plots. It uses the `subplot` API to add axes, `plot` with custom markers, and `set_position` to adjust subplot extents. The script saves the result as a PNG file using `savefig` and applies a serif font family for a polished academic appearance.
This example visualizes Langton’s Ant cellular automata on a 128-by-128 finite grid, showing the emergent trail of black and white cells as one or more ants move according to a configurable turning rule. The simulation runs up to 11,000 steps, then renders the final board state and ant positions using Matplotlib’s `imshow` with a gray colormap and a red overlay via `numpy.ma` masks. The code defines `Grid` and `Ant` classes in Python, uses NumPy arrays for the board, and saves the output as a PNG image.
This example shows a script for installing a curated set of R packages essential for data science workflows. It covers data manipulation with `dplyr`, `tidyr`, and `data.table`; data presentation via `rmarkdown` and `knitr`; database connectivity through `RODBC`, `RMySQL`, `RPostgreSQL`, and `RSQLite`; and file I/O for formats like Excel (`xlsx`), SAS (`foreign`), JSON (`jsonlite`), and XML (`XML`). The code also includes packages for plotting (`ggplot2`), package development (`devtools`, `roxygen2`), and testing (`testthat`). Each package name is accompanied by a comment explaining its purpose, making the installation list self-documenting.
This example demonstrates a collection of practical data manipulation recipes for the Pandas library in Python. It shows how to perform common DataFrame operations, including filtering rows by values, renaming columns, handling missing data, sorting, grouping, pivoting, and converting data types. The snippets use Pandas APIs such as `pd.unique`, `df.isin`, `df.rename`, `df.groupby`, `pd.pivot_table`, and `df.fillna`, along with NumPy functions like `np.where`. The code also covers text processing with `.str` methods, concatenating columns, and creating DataFrames from dictionaries or Django querysets.
This example shows a minimal PICO-8 game state machine with menu, game, and end states, driven by button input. The code defines `_init`, `_update`, and `_draw` callbacks to switch between states, run a countdown timer, and render text via `print` and a black background with `rectfill`. It uses PICO-8’s built-in `btnp` for button presses and Lua’s arithmetic operators for the timer decrement. The visible rendering approach is simple immediate-mode drawing without external libraries or data sources.
This example presents a collection of code snippets from Raymond Hettinger’s PyCon 2013 talk, demonstrating how to refactor common Python patterns into more idiomatic and efficient forms. The notes show before-and-after comparisons, such as replacing `range` with `xrange`, using `enumerate` for indexed loops, and applying `iter` with a sentinel value. It covers looping over collections, dictionaries, and multiple sequences, highlighting APIs like `zip`, `izip`, `sorted`, and `iteritems`. The rendering is plain text within a markdown file, with no visual data or canvas involved.
This script reconstructs music tracks from a PICO-8 cartridge by parsing the cartridge’s `__music__` section to identify enabled sound patterns, then mixing the corresponding exported WAV files into complete songs. It reads 64 sound files using the `wave` module, unpacks their 16-bit samples with `struct.unpack`, sums the active tracks per frame, and applies a 61-sample crossfade to prevent looping pops. The code uses `argparse` for command-line arguments and writes the final mixed tracks as new WAV files via `wave.open` and `writeframes`.
This visualization presents a plain-text cheatsheet for regular expressions, organized into sections for special characters, quantifiers, special sequences, and useful examples. It uses Markdown headings and code blocks to display regex patterns and their meanings, with inline examples like `\bfoo\b` for word boundary matching. The layout relies on standard HTML rendering of the Markdown source, with no JavaScript or external libraries involved. It serves as a static reference guide, showing the syntax and semantics of regex constructs directly in the document.
This utility module processes raw tweet JSON objects for text analysis. It extracts timestamps via `datetime.strptime`, hashtags, user mentions, and cleaned text by stripping URLs, mentions, and media using entity indices. It further sanitizes punctuation with the `string` module, removes English stopwords from `nltk.corpus`, and applies Lancaster stemming via `nltk.stem.lancaster.LancasterStemmer`. The code demonstrates reusable functions for preparing Twitter data, relying solely on standard Python and NLTK libraries without any visualization or rendering components.
GistBox demonstrates how GitHub Gists can organize reusable code, documentation, and personal notes through a series of JavaScript, Ruby, and Markdown examples. The JavaScript file logs the window object, the Ruby file implements a quicksort algorithm, and the Markdown files contain keyboard shortcut documentation and a cheesecake recipe with ingredients and directions. The visualization highlights the variety of content types Gists support, from executable code snippets to formatted text, showing their utility as a versatile storage and sharing tool.
This example shows a PHP Twitter autoresponder bot that monitors the Twitter Search API for specific keywords and automatically replies to matching tweets. The code uses the PECL OAuth extension to authenticate with Twitter API 1.1, performing searches for configured terms like "over 9000" and posting responses via the statuses/update endpoint. It tracks the last replied-to tweet ID in a local file to avoid duplicates, verifies account credentials, and includes command-line OAuth authorization for initial setup.
This example shows how to decrypt a password-protected PDF file directly from the command line using the `qpdf` tool. The code first presents a one-line command that applies a known password with the `--decrypt` flag, converting `orig.pdf` into `decrypted.pdf`. It then demonstrates an interactive variant that uses the shell’s `read` built-in with the `-s` flag to silently prompt for a password, storing it in a variable and passing it to `qpdf` via command substitution. The rendering approach is purely textual, relying on standard shell syntax rather than any graphics or visualization library.
This example shows a Python implementation of Dijkstra's shortest-path algorithm operating on a graph with weighted edges. It defines a `Graph` class that stores nodes, edges, and distances, then uses the `dijsktra` function to compute the minimum distance from a starting node to all others, returning both the visited distances and the path map. The code relies on Python’s `defaultdict` for edge adjacency and a set-based node collection to iteratively select the unvisited node with the smallest known distance. The visualization itself is not rendered—only the algorithm’s logic and data structures are presented in plain code.
This example demonstrates a memoize decorator in Python that caches function results to optimize repeated calls. The code defines a `memoize` function using a dictionary as a cache, and a `wrapper` function that checks for cached results before computing new ones, handling missing keys via exception. It applies the decorator to a recursive Fibonacci function (`fib`), showing how the cache reduces redundant recursive computations. The implementation relies on Python’s built-in exception handling and dictionary API, with no external libraries.