_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q256300
checksum
validation
def checksum(file_path, hash_type='md5', block_size=65536): """Returns either the md5 or sha256 hash of a file at `file_path`. md5 is the default hash_type as it is faster than sha256 The default block size is 64 kb, which appears to be one of a few command choices according to https://stackoverflow.com/a/44873382/2680. The code below is an extension of the example presented in that post. """ if hash_type == 'md5': hash_ = hashlib.md5() elif hash_type == 'sha256': hash_ = hashlib.sha256() else:
python
{ "resource": "" }
q256301
Project.storage
validation
def storage(self, provider='osfstorage'): """Return storage `provider`.""" stores = self._json(self._get(self._storages_url), 200) stores = stores['data'] for store in stores: provides = self._get_attribute(store, 'attributes', 'provider') if provides == provider:
python
{ "resource": "" }
q256302
Project.storages
validation
def storages(self): """Iterate over all storages for this projects.""" stores = self._json(self._get(self._storages_url), 200)
python
{ "resource": "" }
q256303
Storage.create_file
validation
def create_file(self, path, fp, force=False, update=False): """Store a new file at `path` in this storage. The contents of the file descriptor `fp` (opened in 'rb' mode) will be uploaded to `path` which is the full path at which to store the file. To force overwrite of an existing file, set `force=True`. To overwrite an existing file only if the files differ, set `update=True` """ if 'b' not in fp.mode: raise ValueError("File has to be opened in binary mode.") # all paths are assumed to be absolute path = norm_remote_path(path) directory, fname = os.path.split(path) directories = directory.split(os.path.sep) # navigate to the right parent object for our file parent = self for directory in directories: # skip empty directory names if directory: parent = parent.create_folder(directory, exist_ok=True) url = parent._new_file_url # When uploading a large file (>a few MB) that already exists # we sometimes get a ConnectionError instead of a status == 409. connection_error = False # peek at the file to check if it is an empty file which needs special # handling in requests. If we pass a file like object to data that # turns out to be of length zero then no file is created on the OSF. # See: https://github.com/osfclient/osfclient/pull/135 if file_empty(fp): response = self._put(url, params={'name': fname}, data=b'') else: try: response = self._put(url, params={'name': fname}, data=fp) except ConnectionError: connection_error = True if connection_error or response.status_code == 409: if not force and not update: # one-liner to get file size from file pointer from # https://stackoverflow.com/a/283719/2680824 file_size_bytes = get_local_file_size(fp) large_file_cutoff = 2**20 # 1 MB in bytes if connection_error and file_size_bytes < large_file_cutoff: msg = (
python
{ "resource": "" }
q256304
copyfileobj
validation
def copyfileobj(fsrc, fdst, total, length=16*1024): """Copy data from file-like object fsrc to file-like object fdst This is like shutil.copyfileobj but with a progressbar. """ with tqdm(unit='bytes', total=total, unit_scale=True) as pbar: while 1:
python
{ "resource": "" }
q256305
File.write_to
validation
def write_to(self, fp): """Write contents of this file to a local file. Pass in a filepointer `fp` that has been opened for writing in binary mode. """ if 'b' not in fp.mode: raise ValueError("File has to be opened in binary mode.") response = self._get(self._download_url, stream=True) if response.status_code == 200:
python
{ "resource": "" }
q256306
File.remove
validation
def remove(self): """Remove this file from the remote storage.""" response = self._delete(self._delete_url) if
python
{ "resource": "" }
q256307
File.update
validation
def update(self, fp): """Update the remote file from a local file. Pass in a filepointer `fp` that has been opened for writing in binary mode. """ if 'b' not in fp.mode: raise ValueError("File has to be opened in binary mode.") url = self._upload_url # peek at the file to check if it is an ampty file which needs special # handling in requests. If we pass a file like object to data that # turns out to be of length zero then no file is created on the OSF if fp.peek(1):
python
{ "resource": "" }
q256308
ContainerMixin._iter_children
validation
def _iter_children(self, url, kind, klass, recurse=None): """Iterate over all children of `kind` Yield an instance of `klass` when a child is of type `kind`. Uses `recurse` as the path of attributes in the JSON returned from `url` to find more children. """ children = self._follow_next(url) while children: child = children.pop() kind_ = child['attributes']['kind'] if kind_ == kind:
python
{ "resource": "" }
q256309
might_need_auth
validation
def might_need_auth(f): """Decorate a CLI function that might require authentication. Catches any UnauthorizedException raised, prints a helpful message and then exits. """ @wraps(f) def wrapper(cli_args): try: return_value = f(cli_args)
python
{ "resource": "" }
q256310
init
validation
def init(args): """Initialize or edit an existing .osfcli.config file.""" # reading existing config file, convert to configparser object config = config_from_file() config_ = configparser.ConfigParser() config_.add_section('osf') if 'username' not in config.keys(): config_.set('osf', 'username', '') else: config_.set('osf', 'username', config['username']) if 'project' not in config.keys(): config_.set('osf', 'project', '') else: config_.set('osf', 'project', config['project']) # now we can start asking for new values print('Provide a username for the config file [current username: {}]:'.format( config_.get('osf', 'username'))) username = input()
python
{ "resource": "" }
q256311
clone
validation
def clone(args): """Copy all files from all storages of a project. The output directory defaults to the current directory. If the project is private you need to specify a username. If args.update is True, overwrite any existing local files only if local and remote files differ. """ osf = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output with tqdm(unit='files') as pbar: for store in project.storages: prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path)
python
{ "resource": "" }
q256312
fetch
validation
def fetch(args): """Fetch an individual file from a project. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. The local path defaults to the name of the remote file. If the project is private you need to specify a username. If args.force is True, write local file even if that file already exists. If args.force is False but args.update is True, overwrite an existing local file only if local and remote files differ. """ storage, remote_path = split_storage(args.remote) local_path = args.local if local_path is None: _, local_path = os.path.split(remote_path) local_path_exists = os.path.exists(local_path) if local_path_exists and not args.force and not args.update: sys.exit("Local file %s already exists, not overwriting." % local_path) directory, _ = os.path.split(local_path) if directory:
python
{ "resource": "" }
q256313
list_
validation
def list_(args): """List all files from all storages for project. If the project is private you need to specify a username. """ osf = _setup_osf(args) project = osf.project(args.project) for store in project.storages: prefix = store.name for file_ in store.files:
python
{ "resource": "" }
q256314
upload
validation
def upload(args): """Upload a new file to an existing project. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. If the project is private you need to specify a username. To upload a whole directory (and all its sub-directories) use the `-r` command-line option. If your source directory name ends in a / then files will be created directly in the remote directory. If it does not end in a slash an extra sub-directory with the name of the local directory will be created. To place contents of local directory `foo` in remote directory `bar/foo`: $ osf upload -r foo bar To place contents of local directory `foo` in remote directory `bar`: $ osf upload -r foo/ bar """ osf = _setup_osf(args) if osf.username is None or osf.password is None: sys.exit('To upload a file you need to provide a username and' ' password.') project = osf.project(args.project) storage, remote_path = split_storage(args.destination) store = project.storage(storage) if args.recursive: if not os.path.isdir(args.source): raise RuntimeError("Expected source ({}) to be a directory when " "using recursive mode.".format(args.source))
python
{ "resource": "" }
q256315
remove
validation
def remove(args): """Remove a file from the project's storage. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. """ osf = _setup_osf(args) if osf.username is None or osf.password is None: sys.exit('To remove a file you need to provide a username and'
python
{ "resource": "" }
q256316
OSF.login
validation
def login(self, username, password=None, token=None): """Login user for protected API calls."""
python
{ "resource": "" }
q256317
OSF.project
validation
def project(self, project_id): """Fetch project `project_id`.""" type_ = self.guid(project_id) url = self._build_url(type_, project_id)
python
{ "resource": "" }
q256318
OSF.guid
validation
def guid(self, guid): """Determines JSONAPI type for provided GUID"""
python
{ "resource": "" }
q256319
OSFCore._json
validation
def _json(self, response, status_code): """Extract JSON from response if `status_code` matches.""" if isinstance(status_code, numbers.Integral): status_code = (status_code,) if response.status_code in status_code: return response.json() else:
python
{ "resource": "" }
q256320
OSFCore._follow_next
validation
def _follow_next(self, url): """Follow the 'next' link on paginated results.""" response = self._json(self._get(url), 200) data = response['data'] next_url = self._get_attribute(response,
python
{ "resource": "" }
q256321
project
validation
def project(*descs, root_file=None): """ Make a new project, using recursion and alias resolution. Use this function in preference to calling Project() directly. """ load.ROOT_FILE = root_file desc = merge.merge(merge.DEFAULT_PROJECT, *descs) path = desc.get('path', '') if root_file: project_path = os.path.dirname(root_file) if
python
{ "resource": "" }
q256322
Description.clear
validation
def clear(self): """Clear description to default values""" self._desc = {} for key, value in merge.DEFAULT_PROJECT.items():
python
{ "resource": "" }
q256323
SPI
validation
def SPI(ledtype=None, num=0, **kwargs): """Wrapper function for using SPI device drivers on systems like the Raspberry Pi and BeagleBone. This allows using any of the SPI drivers from a single entry point instead importing the driver for a specific LED type. Provides the same parameters of :py:class:`bibliopixel.drivers.SPI.SPIBase` as well as those below: :param ledtype: One of: LPD8806, WS2801, WS281X, or APA102 """ from ...project.types.ledtype import
python
{ "resource": "" }
q256324
EditQueue.put_edit
validation
def put_edit(self, f, *args, **kwds): """ Defer an edit to run on the EditQueue. :param callable f: The function to be called :param tuple args: Positional arguments to the function :param tuple
python
{ "resource": "" }
q256325
EditQueue.get_and_run_edits
validation
def get_and_run_edits(self): """ Get all the edits in the queue, then execute them. The algorithm gets all edits, and then executes all of them. It does *not* pull off one edit, execute, repeat until the queue is empty, and that means that the queue might not be empty at the end of ``run_edits``, because new edits might have entered the queue while the previous edits are being executed. This has the advantage that if edits enter the queue faster than they can be processed, ``get_and_run_edits`` won't go into an infinite loop, but rather the queue will grow unboundedly, which that can be detected, and mitigated and reported on - or if Queue.maxsize is set, ``bp`` will
python
{ "resource": "" }
q256326
DevicesImpl.find_serial_devices
validation
def find_serial_devices(self): """Scan and report all compatible serial devices on system. :returns: List of discovered devices """ if self.devices is not None: return self.devices self.devices = {} hardware_id = "(?i)" + self.hardware_id # forces case insensitive for ports in serial.tools.list_ports.grep(hardware_id): port = ports[0] try: id = self.get_device_id(port) ver = self._get_device_version(port) except: log.debug('Error getting device_id for %s, %s', port, self.baudrate) if True: raise continue
python
{ "resource": "" }
q256327
DevicesImpl.get_device
validation
def get_device(self, id=None): """Returns details of either the first or specified device :param int id: Identifier of desired device. If not given, first device found will be returned :returns tuple: Device ID, Device Address, Firmware Version """ if id is None: if not self.devices: raise ValueError('No default device for %s' % self.hardware_id) id, (device, version) = sorted(self.devices.items())[0] elif id in self.devices: device, version = self.devices[id]
python
{ "resource": "" }
q256328
DevicesImpl.error
validation
def error(self, fail=True, action=''): """ SHOULD BE PRIVATE METHOD """ e = 'There was an unknown error communicating with the device.' if action:
python
{ "resource": "" }
q256329
DevicesImpl.set_device_id
validation
def set_device_id(self, dev, id): """Set device ID to new value. :param str dev: Serial device address/path :param id: Device ID to set """ if id < 0 or id > 255: raise ValueError("ID must
python
{ "resource": "" }
q256330
get
validation
def get(name=None): """ Return a named Palette, or None if no such name exists. If ``name`` is omitted, the default value is used.
python
{ "resource": "" }
q256331
crop
validation
def crop(image, top_offset=0, left_offset=0, bottom_offset=0, right_offset=0): """Return an image cropped on top, bottom, left or right.""" if bottom_offset or top_offset or left_offset or right_offset: width, height = image.size
python
{ "resource": "" }
q256332
resize
validation
def resize(image, x, y, stretch=False, top=None, left=None, mode='RGB', resample=None): """Return an image resized.""" if x <= 0: raise ValueError('x must be greater than zero') if y <= 0: raise ValueError('y must be greater than zero') from PIL import Image resample = Image.ANTIALIAS if resample is None else resample if not isinstance(resample, numbers.Number): try: resample = getattr(Image, resample.upper()) except: raise ValueError("(1) Didn't understand resample=%s" % resample) if not isinstance(resample, numbers.Number): raise ValueError("(2) Didn't understand resample=%s" % resample) size = x, y if stretch: return image.resize(size, resample=resample) result = Image.new(mode, size) ratios = [d1
python
{ "resource": "" }
q256333
Matrix.drawCircle
validation
def drawCircle(self, x0, y0, r, color=None): """ Draw a circle in
python
{ "resource": "" }
q256334
Matrix.fillCircle
validation
def fillCircle(self, x0, y0, r, color=None): """ Draw a filled circle in an RGB color, with center x0, y0 and
python
{ "resource": "" }
q256335
Matrix.drawLine
validation
def drawLine(self, x0, y0, x1, y1, color=None, colorFunc=None, aa=False): """ Draw a between x0, y0 and x1, y1 in an RGB color. :param colorFunc: a function that takes an integer from x0 to x1 and returns a color corresponding to that point :param aa:
python
{ "resource": "" }
q256336
Matrix.bresenham_line
validation
def bresenham_line(self, x0, y0, x1, y1, color=None, colorFunc=None): """ Draw line from point x0, y0 to x1, y1 using Bresenham's algorithm. Will draw
python
{ "resource": "" }
q256337
Matrix.fillScreen
validation
def fillScreen(self, color=None): """Fill the matrix with the given RGB color"""
python
{ "resource": "" }
q256338
Matrix.fillTriangle
validation
def fillTriangle(self, x0, y0, x1, y1, x2, y2, color=None, aa=False): """ Draw filled triangle with points x0,y0 - x1,y1 - x2,y2
python
{ "resource": "" }
q256339
Routing.set_project
validation
def set_project(self, project): """Set the base project for routing.""" def visit(x): # Try to set_project, then recurse through any values() set_project = getattr(x, 'set_project', None) if set_project:
python
{ "resource": "" }
q256340
Circle.set
validation
def set(self, ring, angle, color): """Set pixel to RGB color tuple"""
python
{ "resource": "" }
q256341
Circle.get
validation
def get(self, ring, angle): """Get RGB color tuple of color at index pixel"""
python
{ "resource": "" }
q256342
run
validation
def run(function, *args, use_subprocess=False, daemon=True, **kwds): """ Create input, output queues, call `function` in a subprocess or a thread. ``function`` is called like this: ``function(input, output, *args, **kwds)`` :param use_subprocess: if true, create a new multiprocess; if false, create a new thread :param function: the function to call :param daemon: is the thread or subprocess run as a daemon or not? :param args: positional arguments to the function :param kwds: keyword arguments to the function :returns: a tuple with three elements: the subprocess or thread, an input queue, and an output queue. """
python
{ "resource": "" }
q256343
color_scale
validation
def color_scale(color, level): """ Scale RGB tuple by
python
{ "resource": "" }
q256344
SavedDescription.save
validation
def save(self, project_file=''): """Save the description as a YML file. Prompt if no file given."""
python
{ "resource": "" }
q256345
Palette.get
validation
def get(self, position=0): """ Return a color interpolated from the Palette. In the case where continuous=False, serpentine=False, scale=1, autoscale=False, and offset=0, this is exactly the same as plain old [] indexing, but with a wrap-around. The constructor parameters affect this result as documented in the constructor. Arguments: ``position``: May be any integer or floating point number """ n = len(self) if n == 1: return self[0] pos = position if self.length and self.autoscale: pos *= len(self) pos /= self.length pos *= self.scale pos += self.offset if not self.continuous: if not self.serpentine: return self[int(pos % n)] # We want a color sequence of length 2n-2 # e.g. for n=5: a b c d | e d c b | a b c d ... m = (2 * n) - 2
python
{ "resource": "" }
q256346
Task.run
validation
def run(self, next_task): """Wait for the event, run the task, trigger the next task.""" self.event.wait()
python
{ "resource": "" }
q256347
report
validation
def report(function, *args, **kwds): """Run a function, catch, report and discard
python
{ "resource": "" }
q256348
Control._receive
validation
def _receive(self, msg): """ Receive a message from the input source and perhaps raise an Exception. """ msg = self._convert(msg) if msg is None: return str_msg = self.verbose and self._msg_to_str(msg) if self.verbose and log.is_debug(): log.debug('Message %s', str_msg) if self.pre_routing:
python
{ "resource": "" }
q256349
APA102.set_device_brightness
validation
def set_device_brightness(self, val): """ APA102 & SK9822 support on-chip brightness control, allowing greater color depth. APA102 superimposes a 440Hz PWM on the 19kHz base PWM to control brightness. SK9822 uses a base 4.7kHz PWM but controls brightness with a variable current source. Because of this SK9822 will have much less flicker at lower levels. Either way, this option is better and faster than scaling in BiblioPixel. """ # bitshift to scale from
python
{ "resource": "" }
q256350
_addLoggingLevel
validation
def _addLoggingLevel(levelName, levelNum, methodName=None): """ Comprehensively adds a new logging level to the `logging` module and the currently configured logging class. `levelName` becomes an attribute of the `logging` module with the value `levelNum`. `methodName` becomes a convenience method for both `logging` itself and the class returned by `logging.getLoggerClass()` (usually just `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is used. To avoid accidental clobberings of existing attributes, this method will raise an `AttributeError` if the level name is already an attribute of the `logging` module or if the method name is already present Example ------- >>> addLoggingLevel('TRACE', logging.DEBUG - 5) >>> logging.getLogger(__name__).setLevel("TRACE") >>> logging.getLogger(__name__).trace('that worked') >>> logging.trace('so did this') >>> logging.TRACE 5 """ if not methodName: methodName = levelName.lower() if hasattr(logging, levelName): raise AttributeError( '{} already defined in logging module'.format(levelName)) if hasattr(logging, methodName): raise AttributeError( '{} already defined in logging module'.format(methodName)) if hasattr(logging.getLoggerClass(), methodName): raise AttributeError(
python
{ "resource": "" }
q256351
Layout.construct
validation
def construct(cls, project, **desc): """Construct a layout. SHOULD BE PRIVATE
python
{ "resource": "" }
q256352
Layout.clone
validation
def clone(self): """ Return an independent copy of this layout with a completely separate color_list and no drivers.
python
{ "resource": "" }
q256353
Layout.set_color_list
validation
def set_color_list(self, color_list, offset=0): """ Set the internal colors starting at an optional offset. If `color_list` is a list or other 1-dimensional array, it is reshaped into an N x 3 list. If `color_list` too long it is truncated;
python
{ "resource": "" }
q256354
Layout.fill
validation
def fill(self, color, start=0, end=-1): """Fill the entire strip with RGB color tuple""" start = max(start, 0) if end < 0 or end >= self.numLEDs: end = self.numLEDs - 1
python
{ "resource": "" }
q256355
Layout.fillRGB
validation
def fillRGB(self, r, g, b, start=0, end=-1): """Fill entire
python
{ "resource": "" }
q256356
Layout.fillHSV
validation
def fillHSV(self, hsv, start=0, end=-1): """Fill the entire strip with HSV color tuple"""
python
{ "resource": "" }
q256357
wheel_helper
validation
def wheel_helper(pos, length, cycle_step): """Helper for wheel_color that distributes colors over length and allows
python
{ "resource": "" }
q256358
single
validation
def single(method): """Decorator for RestServer methods that take a single address""" @functools.wraps(method) def single(self, address, value=None): address = urllib.parse.unquote_plus(address) try: error = NO_PROJECT_ERROR if not self.project: raise ValueError error = BAD_ADDRESS_ERROR ed = editor.Editor(address, self.project) if value is None: error = BAD_GETTER_ERROR result = method(self, ed)
python
{ "resource": "" }
q256359
multi
validation
def multi(method): """Decorator for RestServer methods that take multiple addresses""" @functools.wraps(method) def multi(self, address=''): values = flask.request.values address = urllib.parse.unquote_plus(address) if address and values and not address.endswith('.'): address += '.' result = {} for a in values or '': try: if not self.project: raise ValueError('No Project is currently loaded')
python
{ "resource": "" }
q256360
advance_permutation
validation
def advance_permutation(a, increasing=True, forward=True): """ Advance a list of unique, ordered elements in-place, lexicographically increasing or backward, by rightmost or leftmost digit. Returns False if the permutation wrapped around - i.e. went from lexicographically greatest to least, and True in all other cases. If the length of the list is N, then this function will repeat values after N! steps, and will return False exactly once. See also https://stackoverflow.com/a/34325140/43839 """ if not forward: a.reverse() cmp = operator.lt if increasing else operator.gt try: i = next(i for i in reversed(range(len(a) - 1)) if cmp(a[i],
python
{ "resource": "" }
q256361
Indexed._on_index
validation
def _on_index(self, old_index): """ Override this method to get called right after ``self.index`` is set. :param int old_index: the previous index, before it was changed. """ if self.animation:
python
{ "resource": "" }
q256362
Cutter.apply
validation
def apply(self, function): """ For each row or column in cuts, read a list of its colors, apply the function to that list of colors, then write it back to the layout. """
python
{ "resource": "" }
q256363
compose_events
validation
def compose_events(events, condition=all): """ Compose a sequence of events into one event. Arguments: events: a sequence of objects looking like threading.Event condition: a function taking a sequence of bools and returning a bool. """ events = list(events) master_event = threading.Event() def changed(): if condition(e.is_set() for e in events): master_event.set() else: master_event.clear() def add_changed(f):
python
{ "resource": "" }
q256364
_add_redundant_arguments
validation
def _add_redundant_arguments(parser): """ These arguments are redundant with just using a project, and we should encouraging that as you don't have to learn any dumb flags! For example, instead of bp foo.yml --animation=wombat --numbers=float use bp foo.yml + '{animation: wombat, numbers: float}' """ parser.add_argument( '-a', '--animation', default=None, help='Default animation type if no animation is specified') if deprecated.allowed(): # pragma: no cover parser.add_argument( '--dimensions', '--dim', default=None, help='DEPRECATED: x, (x, y) or (x, y, z) dimensions for project') parser.add_argument(
python
{ "resource": "" }
q256365
draw_circle
validation
def draw_circle(setter, x0, y0, r, color=None): """ Draws a circle at point x0, y0 with radius r of the specified RGB color """ f = 1 - r ddF_x = 1 ddF_y = -2 * r x = 0 y = r setter(x0, y0 + r, color) setter(x0, y0 - r, color) setter(x0 + r, y0, color) setter(x0 - r, y0, color) while
python
{ "resource": "" }
q256366
fill_circle
validation
def fill_circle(setter, x0, y0, r, color=None): """Draws a filled circle at point x0,y0 with radius r and specified color""" _draw_fast_vline(setter,
python
{ "resource": "" }
q256367
bresenham_line
validation
def bresenham_line(setter, x0, y0, x1, y1, color=None, colorFunc=None): """Draw line from point x0,y0 to x,1,y1. Will draw beyond matrix bounds.""" steep = abs(y1 - y0) > abs(x1 - x0) if steep: x0, y0 = y0, x0 x1, y1 = y1, x1 if x0 > x1: x0, x1 = x1, x0 y0, y1 = y1, y0 dx = x1 - x0 dy = abs(y1 - y0) err = dx / 2 if y0 < y1: ystep = 1 else: ystep = -1
python
{ "resource": "" }
q256368
fill_rect
validation
def fill_rect(setter, x, y, w, h, color=None, aa=False): """Draw solid rectangle with top-left
python
{ "resource": "" }
q256369
draw_round_rect
validation
def draw_round_rect(setter, x, y, w, h, r, color=None, aa=False): """Draw rectangle with top-left corner at x,y, width w, height h, and corner radius r. """ _draw_fast_hline(setter, x + r, y, w - 2 * r, color, aa) # Top _draw_fast_hline(setter, x + r, y + h - 1, w - 2 * r, color, aa) # Bottom
python
{ "resource": "" }
q256370
fill_round_rect
validation
def fill_round_rect(setter, x, y, w, h, r, color=None, aa=False): """Draw solid rectangle with top-left corner at x,y, width w, height h, and corner radius r""" fill_rect(setter, x + r, y, w - 2 * r, h, color, aa) _fill_circle_helper(setter, x + w - r - 1, y + r, r,
python
{ "resource": "" }
q256371
draw_triangle
validation
def draw_triangle(setter, x0, y0, x1, y1, x2, y2, color=None, aa=False): """Draw triangle with points x0,y0 - x1,y1 - x2,y2""" draw_line(setter, x0, y0, x1, y1, color, aa)
python
{ "resource": "" }
q256372
fill_triangle
validation
def fill_triangle(setter, x0, y0, x1, y1, x2, y2, color=None, aa=False): """Draw solid triangle with points x0,y0 - x1,y1 - x2,y2""" a = b = y = last = 0 if y0 > y1: y0, y1 = y1, y0 x0, x1 = x1, x0 if y1 > y2: y2, y1 = y1, y2 x2, x1 = x1, x2 if y0 > y1: y0, y1 = y1, y0 x0, x1 = x1, x0 if y0 == y2: # Handle awkward all-on-same-line case as its own thing a = b = x0 if x1 < a: a = x1 elif x1 > b: b = x1 if x2 < a: a = x2 elif x2 > b: b = x2 _draw_fast_hline(setter, a, y0, b - a + 1, color, aa) dx01 = x1 - x0 dy01 = y1 - y0 dx02 = x2 - x0 dy02 = y2 - y0 dx12 = x2 - x1 dy12 = y2 - y1 sa = 0 sb = 0 # For upper part of triangle, find scanline crossings for segments # 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 # is included here (and second loop will be skipped, avoiding a /0 # error there), otherwise scanline y1 is skipped here and handled # in the second loop...which also avoids a /0 error here if y0=y1 # (flat-topped triangle). if y1 == y2: last = y1 # include y1 scanline else: last =
python
{ "resource": "" }
q256373
DriverBase.set_colors
validation
def set_colors(self, colors, pos): """ Use with caution! Directly set the pixel buffers. :param colors: A list of color tuples :param int pos: Position in color list to begin set operation. """ self._colors = colors self._pos
python
{ "resource": "" }
q256374
pointOnCircle
validation
def pointOnCircle(cx, cy, radius, angle): """ Calculates the coordinates of a point on a circle given the center point, radius, and angle. """ angle = math.radians(angle) - (math.pi / 2) x = cx + radius * math.cos(angle) if x < cx: x = math.ceil(x)
python
{ "resource": "" }
q256375
genVector
validation
def genVector(width, height, x_mult=1, y_mult=1): """ Generates a map of vector lengths from the center point to each coordinate. width - width of matrix to generate height - height of matrix to generate x_mult - value to scale x-axis by y_mult - value to scale y-axis by """ center_x = (width - 1) / 2 center_y
python
{ "resource": "" }
q256376
all_named_colors
validation
def all_named_colors(): """Return an iteration over all name, color pairs in tables""" yield from _TO_COLOR_USER.items() for name, color
python
{ "resource": "" }
q256377
contains
validation
def contains(x): """Return true if this string or integer tuple appears in tables""" if isinstance(x, str): x = canonical_name(x)
python
{ "resource": "" }
q256378
make_segments
validation
def make_segments(strip, length): """Return a list of Segments that evenly split the strip.""" if len(strip) % length: raise ValueError('The length of strip must be a multiple of length') s = [] try: while True:
python
{ "resource": "" }
q256379
Segment.next
validation
def next(self, length): """Return a new segment starting right after
python
{ "resource": "" }
q256380
Builder.stop
validation
def stop(self=None): """Stop the builder if it's running.""" if not self: instance = getattr(Runner.instance(), 'builder', None) self = instance and instance() if not self:
python
{ "resource": "" }
q256381
Builder.simpixel
validation
def simpixel(new=0, autoraise=True): """Open an instance of simpixel in the browser"""
python
{ "resource": "" }
q256382
recurse
validation
def recurse(desc, pre='pre_recursion', post=None, python_path=None): """ Depth first recursion through a dictionary containing type constructors The arguments pre, post and children are independently either: * None, which means to do nothing * a string, which means to use the static class method of that name on the class being constructed, or * a callable, to be called at each recursion Arguments: dictionary -- a project dictionary or one of its subdictionaries pre -- called before children are visited node in the recursion post -- called after children are visited in the recursion python_path -- relative path to start resolving typenames """ def call(f, desc): if isinstance(f, str): # f is the name of a static class method on the datatype. f = getattr(datatype, f, None) return f and f(desc) # Automatically load strings that look like JSON or Yaml filenames. desc = load.load_if_filename(desc) or desc desc = construct.to_type_constructor(desc, python_path) datatype = desc.get('datatype') desc = call(pre, desc) or desc for child_name in getattr(datatype, 'CHILDREN', []): child = desc.get(child_name) if child: is_plural = child_name.endswith('s') remove_s = is_plural and child_name != 'drivers' #
python
{ "resource": "" }
q256383
to_type_constructor
validation
def to_type_constructor(value, python_path=None): """" Tries to convert a value to a type constructor. If value is a string, then it used as the "typename" field. If the "typename" field exists, the symbol for that name is imported and added to the type constructor as a field "datatype". Throws: ImportError -- if "typename" is set but cannot be imported ValueError -- if "typename" is malformed """ if not value: return value if callable(value): return {'datatype': value} value = to_type(value)
python
{ "resource": "" }
q256384
fill
validation
def fill(strip, item, start=0, stop=None, step=1): """Fill a portion of a strip from start to stop by step with a given item. If stop is not given, it defaults to the length of the strip.
python
{ "resource": "" }
q256385
pop_legacy_palette
validation
def pop_legacy_palette(kwds, *color_defaults): """ Older animations in BPA and other areas use all sorts of different names for what we are now representing with palettes. This function mutates a kwds dictionary to remove these legacy fields and extract a palette from it, which it returns. """
python
{ "resource": "" }
q256386
euclidean
validation
def euclidean(c1, c2): """Square of the euclidean distance""" diffs = ((i - j)
python
{ "resource": "" }
q256387
Writer._write
validation
def _write(self, filename, frames, fps, loop=0, palette=256): """ Write a series of frames as a single animated GIF. :param str filename: the name of the GIF file to write :param list frames: a list of filenames, each of which represents a single frame of the animation. Each frame must have exactly the same dimensions, and the code has only been tested with .gif files. :param float fps: The number of frames per second. :param int
python
{ "resource": "" }
q256388
dumps
validation
def dumps(data, use_yaml=None, safe=True, **kwds): """ Dumps data into a nicely formatted JSON string. :param dict data: a dictionary to dump :param kwds: keywords to pass to json.dumps :returns: a string with formatted data :rtype: str """ if use_yaml is None: use_yaml = ALWAYS_DUMP_YAML
python
{ "resource": "" }
q256389
dump
validation
def dump(data, file=sys.stdout, use_yaml=None, **kwds): """ Dumps data as nicely formatted JSON string to a file or file handle :param dict data: a dictionary to dump :param file: a filename or file handle to write to :param kwds: keywords to pass to json.dump """ if use_yaml is None: use_yaml = ALWAYS_DUMP_YAML def dump(fp): if use_yaml: yaml.safe_dump(data, stream=fp, **kwds) else: json.dump(data, fp, indent=4, sort_keys=True, **kwds) if not
python
{ "resource": "" }
q256390
load
validation
def load(file, use_yaml=None): """ Loads not only JSON files but also YAML files ending in .yml. :param file: a filename or file handle to read from :returns: the data loaded from the JSON or YAML file :rtype: dict
python
{ "resource": "" }
q256391
adapt_animation_layout
validation
def adapt_animation_layout(animation): """ Adapt the setter in an animation's layout so that Strip animations can run on on Matrix, Cube, or Circle layout, and Matrix or Cube animations can run on a Strip layout. """ layout = animation.layout required = getattr(animation, 'LAYOUT_CLASS', None) if not required or isinstance(layout, required): return msg = LAYOUT_WARNING % ( type(animation).__name__, required.__name__, type(layout).__name__) setter = layout.set adaptor = None if required is strip.Strip: if isinstance(layout, matrix.Matrix): width = layout.width def adaptor(pixel, color=None): y, x = divmod(pixel, width) setter(x, y, color or BLACK) elif isinstance(layout, cube.Cube): lx, ly = layout.x, layout.y def adaptor(pixel, color=None): yz, x = divmod(pixel, lx)
python
{ "resource": "" }
q256392
hsv2rgb_raw
validation
def hsv2rgb_raw(hsv): """ Converts an HSV tuple to RGB. Intended for internal use. You should use hsv2rgb_spectrum or hsv2rgb_rainbow instead. """ HSV_SECTION_3 = 0x40 h, s, v = hsv # The brightness floor is minimum number that all of # R, G, and B will be set to. invsat = 255 - s brightness_floor = (v * invsat) // 256 # The color amplitude is the maximum amount of R, G, and B # that will be added on top of the brightness_floor to # create the specific hue desired. color_amplitude = v - brightness_floor # figure out which section of the hue wheel we're in, # and how far offset we are within that section section = h // HSV_SECTION_3 # 0..2 offset = h % HSV_SECTION_3 # 0..63 rampup = offset rampdown = (HSV_SECTION_3 - 1) - offset # compute color-amplitude-scaled-down versions of rampup and rampdown rampup_amp_adj = (rampup * color_amplitude) // (256 // 4) rampdown_amp_adj = (rampdown * color_amplitude) // (256 //
python
{ "resource": "" }
q256393
hsv2rgb_spectrum
validation
def hsv2rgb_spectrum(hsv): """Generates RGB values from HSV values in line
python
{ "resource": "" }
q256394
hsv2rgb_rainbow
validation
def hsv2rgb_rainbow(hsv): """Generates RGB values from HSV that have an even visual distribution. Be careful as this method is only have as fast as hsv2rgb_spectrum.""" def nscale8x3_video(r, g, b, scale): nonzeroscale = 0 if scale != 0: nonzeroscale = 1 if r != 0: r = ((r * scale) >> 8) + nonzeroscale if g != 0: g = ((g * scale) >> 8) + nonzeroscale if b != 0: b = ((b * scale) >> 8) + nonzeroscale return (r, g, b) def scale8_video_LEAVING_R1_DIRTY(i, scale): nonzeroscale = 0 if scale != 0: nonzeroscale = 1 if i != 0: i = ((i * scale) >> 8) + nonzeroscale return i h, s, v = hsv offset = h & 0x1F # 0..31 offset8 = offset * 8 third = (offset8 * (256 // 3)) >> 8 r, g, b = (0, 0, 0) if not (h & 0x80): if not (h & 0x40): if not (h & 0x20): r = 255 - third g = third b = 0 else: r = 171 g = 85 + third b = 0x00 else: if not (h & 0x20): twothirds = (third << 1) r = 171 - twothirds g = 171 + third b = 0 else: r = 0
python
{ "resource": "" }
q256395
hsv2rgb_360
validation
def hsv2rgb_360(hsv): """Python default hsv to rgb conversion for when hue values in the range 0-359 are preferred. Due to requiring float math, this method is slower than hsv2rgb_rainbow and hsv2rgb_spectrum."""
python
{ "resource": "" }
q256396
color_cmp
validation
def color_cmp(a, b): """Order colors by hue, saturation and value, in that order. Returns -1 if a < b, 0 if a == b and 1 if a < b. """ if a == b:
python
{ "resource": "" }
q256397
ServerCache.get_server
validation
def get_server(self, key, **kwds): """ Get a new or existing server for this key. :param int key: key for the server to use """ kwds = dict(self.kwds, **kwds) server = self.servers.get(key) if server: # Make sure it's the right server.
python
{ "resource": "" }
q256398
set_one
validation
def set_one(desc, name, value): """Set one section in a Project description""" old_value = desc.get(name) if old_value is None: raise KeyError('No section "%s"' % name) if value is None: value = type(old_value)() elif name in CLASS_SECTIONS: if isinstance(value, str): value = {'typename': aliases.resolve(value)} elif isinstance(value, type): value = {'typename': class_name.class_name(value)} elif not isinstance(value, dict): raise TypeError('Expected dict, str or type, got "%s"' % value) typename = value.get('typename') if typename: s = 's' if name
python
{ "resource": "" }
q256399
update
validation
def update(desc, other=None, **kwds): """Update sections in a Project description""" other = other and _as_dict(other) or {} for i in other, kwds: for k, v in i.items(): if isinstance(v, dict): # Only for dicts, merge instead of overwriting old_v = desc[k] for k2, v2 in v.items():
python
{ "resource": "" }