Friday, September 30
Shadow

Tag: function

Helper function for responsiveness in react native

gist
import { Dimensions, PixelRatio } from "react-native"; // Retrieve initial screen's width let screenWidth = Dimensions.get("window").width; // Retrieve initial screen's height let screenHeight = Dimensions.get("window").height; /** * Converts provided width percentage to independent pixel (dp). * @param {string} widthPercent The percentage of screen's width that UI element should cover * along with the percentage symbol (%). * @return {number} The calculated dp depending on current device's screen width. */ const widthPercentageToDP = (widthPercent) => { // Parse string percentage input and convert it to number. const elemWidth = typeof widthPercent === "number" ? widthPercent : parseFloat(widthPercent); // Use PixelRatio.roun...

An example of a Python decorator to simplify caching a function’s result.

gist
"""An example of a cache decorator.""" import json from functools import wraps from redis import StrictRedis redis = StrictRedis() def cached(func): """ Decorator that caches the results of the function call. We use Redis in this example, but any cache (e.g. memcached) will work. We also assume that the result of the function can be seralized as JSON, which obviously will be untrue in many situations. Tweak as needed. """ @wraps(func) def wrapper(*args, **kwargs): # Generate the cache key from the function's arguments. key_parts = [func.__name__] + list(args) key = '-'.join(key_parts) result = redis.get(key) if result is None: # Run the function and cache the result for next time. ...