text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation. <END_TASK> <USER_TASK:> Description: def fit_transform(self, X, y, step_size=0.1, init_weights=None, warm_start=False): """Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation."""
self.fit(X=X, y=y, step_size=step_size, init_weights=init_weights, warm_start=warm_start) return self.transform(X=X)
<SYSTEM_TASK:> Strips text from the given html string, leaving only tags. <END_TASK> <USER_TASK:> Description: def escape_tags(value, valid_tags): """ Strips text from the given html string, leaving only tags. This functionality requires BeautifulSoup, nothing will be done otherwise. This isn't perfect. Someone could put javascript in here: <a onClick="alert('hi');">test</a> So if you use valid_tags, you still need to trust your data entry. Or we could try: - only escape the non matching bits - use BeautifulSoup to understand the elements, escape everything else and remove potentially harmful attributes (onClick). - Remove this feature entirely. Half-escaping things securely is very difficult, developers should not be lured into a false sense of security. """
# 1. escape everything value = conditional_escape(value) # 2. Reenable certain tags if valid_tags: # TODO: precompile somewhere once? tag_re = re.compile(r'&lt;(\s*/?\s*(%s))(.*?\s*)&gt;' % '|'.join(re.escape(tag) for tag in valid_tags)) value = tag_re.sub(_replace_quot, value) # Allow comments to be hidden value = value.replace("&lt;!--", "<!--").replace("--&gt;", "-->") return mark_safe(value)
<SYSTEM_TASK:> Returns a list of content types from the models defined in settings. <END_TASK> <USER_TASK:> Description: def _get_seo_content_types(seo_models): """Returns a list of content types from the models defined in settings."""
try: return [ContentType.objects.get_for_model(m).id for m in seo_models] except Exception: # previously caught DatabaseError # Return an empty list if this is called too early return []
<SYSTEM_TASK:> Register the backends specified in Meta.backends with the admin. <END_TASK> <USER_TASK:> Description: def register_seo_admin(admin_site, metadata_class): """Register the backends specified in Meta.backends with the admin."""
if metadata_class._meta.use_sites: path_admin = SitePathMetadataAdmin model_instance_admin = SiteModelInstanceMetadataAdmin model_admin = SiteModelMetadataAdmin view_admin = SiteViewMetadataAdmin else: path_admin = PathMetadataAdmin model_instance_admin = ModelInstanceMetadataAdmin model_admin = ModelMetadataAdmin view_admin = ViewMetadataAdmin def get_list_display(): return tuple( name for name, obj in metadata_class._meta.elements.items() if obj.editable) backends = metadata_class._meta.backends if 'model' in backends: class ModelAdmin(model_admin): form = get_model_form(metadata_class) list_display = model_admin.list_display + get_list_display() _register_admin(admin_site, metadata_class._meta.get_model('model'), ModelAdmin) if 'view' in backends: class ViewAdmin(view_admin): form = get_view_form(metadata_class) list_display = view_admin.list_display + get_list_display() _register_admin(admin_site, metadata_class._meta.get_model('view'), ViewAdmin) if 'path' in backends: class PathAdmin(path_admin): form = get_path_form(metadata_class) list_display = path_admin.list_display + get_list_display() _register_admin(admin_site, metadata_class._meta.get_model('path'), PathAdmin) if 'modelinstance' in backends: class ModelInstanceAdmin(model_instance_admin): form = get_modelinstance_form(metadata_class) list_display = (model_instance_admin.list_display + get_list_display()) _register_admin(admin_site, metadata_class._meta.get_model('modelinstance'), ModelInstanceAdmin)
<SYSTEM_TASK:> Override the method to change the form attribute empty_permitted. <END_TASK> <USER_TASK:> Description: def _construct_form(self, i, **kwargs): """Override the method to change the form attribute empty_permitted."""
form = super(MetadataFormset, self)._construct_form(i, **kwargs) # Monkey patch the form to always force a save. # It's unfortunate, but necessary because we always want an instance # Affect on performance shouldn't be too great, because ther is only # ever one metadata attached form.empty_permitted = False form.has_changed = lambda: True # Set a marker on this object to prevent automatic metadata creation # This is seen by the post_save handler, which then skips this # instance. if self.instance: self.instance.__seo_metadata_handled = True return form
<SYSTEM_TASK:> Returns an appropriate value for the given name. <END_TASK> <USER_TASK:> Description: def _resolve_value(self, name): """ Returns an appropriate value for the given name. """
name = str(name) if name in self._metadata._meta.elements: element = self._metadata._meta.elements[name] # Look in instances for an explicit value if element.editable: value = getattr(self, name) if value: return value # Otherwise, return an appropriate default value (populate_from) populate_from = element.populate_from if isinstance(populate_from, collections.Callable): return populate_from(self, **self._populate_from_kwargs()) elif isinstance(populate_from, Literal): return populate_from.value elif populate_from is not NotSet: return self._resolve_value(populate_from) # If this is not an element, look for an attribute on metadata try: value = getattr(self._metadata, name) except AttributeError: pass else: if isinstance(value, collections.Callable): if getattr(value, '__self__', None): return value(self) else: return value(self._metadata, obj=self) return value
<SYSTEM_TASK:> Utility function to decorate a group of url in urls.py <END_TASK> <USER_TASK:> Description: def decorated_patterns(func, *urls): """ Utility function to decorate a group of url in urls.py Taken from http://djangosnippets.org/snippets/532/ + comments See also http://friendpaste.com/6afByRiBB9CMwPft3a6lym Example: urlpatterns = [ url(r'^language/(?P<lang_code>[a-z]+)$', views.MyView, name='name'), ] + decorated_patterns(login_required, url(r'^', include('cms.urls')), """
def decorate(urls, func): for url in urls: if isinstance(url, RegexURLPattern): url.__class__ = DecoratedURLPattern if not hasattr(url, "_decorate_with"): setattr(url, "_decorate_with", []) url._decorate_with.append(func) elif isinstance(url, RegexURLResolver): for pp in url.url_patterns: if isinstance(pp, RegexURLPattern): pp.__class__ = DecoratedURLPattern if not hasattr(pp, "_decorate_with"): setattr(pp, "_decorate_with", []) pp._decorate_with.append(func) if func: if not isinstance(func, (list, tuple)): func = [func] for f in func: decorate(urls, f) return urls
<SYSTEM_TASK:> Return a list of custom fields for this model <END_TASK> <USER_TASK:> Description: def get_custom_fields(self): """ Return a list of custom fields for this model """
return CustomField.objects.filter( content_type=ContentType.objects.get_for_model(self))
<SYSTEM_TASK:> Get a custom field object for this model <END_TASK> <USER_TASK:> Description: def get_custom_field(self, field_name): """ Get a custom field object for this model field_name - Name of the custom field you want. """
content_type = ContentType.objects.get_for_model(self) return CustomField.objects.get( content_type=content_type, name=field_name)
<SYSTEM_TASK:> Get a value for a specified custom field <END_TASK> <USER_TASK:> Description: def get_custom_value(self, field_name): """ Get a value for a specified custom field field_name - Name of the custom field you want. """
custom_field = self.get_custom_field(field_name) return CustomFieldValue.objects.get_or_create( field=custom_field, object_id=self.id)[0].value
<SYSTEM_TASK:> Set a value for a specified custom field <END_TASK> <USER_TASK:> Description: def set_custom_value(self, field_name, value): """ Set a value for a specified custom field field_name - Name of the custom field you want. value - Value to set it to """
custom_field = self.get_custom_field(field_name) custom_value = CustomFieldValue.objects.get_or_create( field=custom_field, object_id=self.id)[0] custom_value.value = value custom_value.save()
<SYSTEM_TASK:> Assigns an item from a given cluster to the closest located cluster. <END_TASK> <USER_TASK:> Description: def assign_item(self, item, origin): """ Assigns an item from a given cluster to the closest located cluster. :param item: the item to be moved. :param origin: the originating cluster. """
closest_cluster = origin for cluster in self.__clusters: if self.distance(item, centroid(cluster)) < self.distance( item, centroid(closest_cluster)): closest_cluster = cluster if id(closest_cluster) != id(origin): self.move_item(item, origin, closest_cluster) return True else: return False
<SYSTEM_TASK:> Moves an item from one cluster to anoter cluster. <END_TASK> <USER_TASK:> Description: def move_item(self, item, origin, destination): """ Moves an item from one cluster to anoter cluster. :param item: the item to be moved. :param origin: the originating cluster. :param destination: the target cluster. """
if self.equality: item_index = 0 for i, element in enumerate(origin): if self.equality(element, item): item_index = i break else: item_index = origin.index(item) destination.append(origin.pop(item_index))
<SYSTEM_TASK:> Initialises the clusters by distributing the items from the data. <END_TASK> <USER_TASK:> Description: def initialise_clusters(self, input_, clustercount): """ Initialises the clusters by distributing the items from the data. evenly across n clusters :param input_: the data set (a list of tuples). :param clustercount: the amount of clusters (n). """
# initialise the clusters with empty lists self.__clusters = [] for _ in range(clustercount): self.__clusters.append([]) # distribute the items into the clusters count = 0 for item in input_: self.__clusters[count % clustercount].append(item) count += 1
<SYSTEM_TASK:> If a progress function was supplied, this will call that function with <END_TASK> <USER_TASK:> Description: def publish_progress(self, total, current): """ If a progress function was supplied, this will call that function with the total number of elements, and the remaining number of elements. :param total: The total number of elements. :param remaining: The remaining number of elements. """
if self.progress_callback: self.progress_callback(total, current)
<SYSTEM_TASK:> Sets the method to determine the distance between two clusters. <END_TASK> <USER_TASK:> Description: def set_linkage_method(self, method): """ Sets the method to determine the distance between two clusters. :param method: The method to use. It can be one of ``'single'``, ``'complete'``, ``'average'`` or ``'uclus'``, or a callable. The callable should take two collections as parameters and return a distance value between both collections. """
if method == 'single': self.linkage = single elif method == 'complete': self.linkage = complete elif method == 'average': self.linkage = average elif method == 'uclus': self.linkage = uclus elif hasattr(method, '__call__'): self.linkage = method else: raise ValueError('distance method must be one of single, ' 'complete, average of uclus')
<SYSTEM_TASK:> Perform hierarchical clustering. <END_TASK> <USER_TASK:> Description: def cluster(self, matrix=None, level=None, sequence=None): """ Perform hierarchical clustering. :param matrix: The 2D list that is currently under processing. The matrix contains the distances of each item with each other :param level: The current level of clustering :param sequence: The sequence number of the clustering """
logger.info("Performing cluster()") if matrix is None: # create level 0, first iteration (sequence) level = 0 sequence = 0 matrix = [] # if the matrix only has two rows left, we are done linkage = partial(self.linkage, distance_function=self.distance) initial_element_count = len(self._data) while len(matrix) > 2 or matrix == []: item_item_matrix = Matrix(self._data, linkage, True, 0) item_item_matrix.genmatrix(self.num_processes) matrix = item_item_matrix.matrix smallestpair = None mindistance = None rowindex = 0 # keep track of where we are in the matrix # find the minimum distance for row in matrix: cellindex = 0 # keep track of where we are in the matrix for cell in row: # if we are not on the diagonal (which is always 0) # and if this cell represents a new minimum... cell_lt_mdist = cell < mindistance if mindistance else False if ((rowindex != cellindex) and (cell_lt_mdist or smallestpair is None)): smallestpair = (rowindex, cellindex) mindistance = cell cellindex += 1 rowindex += 1 sequence += 1 level = matrix[smallestpair[1]][smallestpair[0]] cluster = Cluster(level, self._data[smallestpair[0]], self._data[smallestpair[1]]) # maintain the data, by combining the the two most similar items # in the list we use the min and max functions to ensure the # integrity of the data. imagine: if we first remove the item # with the smaller index, all the rest of the items shift down by # one. So the next index will be wrong. We could simply adjust the # value of the second "remove" call, but we don't know the order # in which they come. The max and min approach clarifies that self._data.remove(self._data[max(smallestpair[0], smallestpair[1])]) # remove item 1 self._data.remove(self._data[min(smallestpair[0], smallestpair[1])]) # remove item 2 self._data.append(cluster) # append item 1 and 2 combined self.publish_progress(initial_element_count, len(self._data)) # all the data is in one single cluster. We return that and stop self.__cluster_created = True logger.info("Call to cluster() is complete") return
<SYSTEM_TASK:> Flattens a list. <END_TASK> <USER_TASK:> Description: def flatten(L): """ Flattens a list. Example: >>> flatten([a,b,[c,d,[e,f]]]) [a,b,c,d,e,f] """
if not isinstance(L, list): return [L] if L == []: return L return flatten(L[0]) + flatten(L[1:])
<SYSTEM_TASK:> Completely flattens out a cluster and returns a one-dimensional set <END_TASK> <USER_TASK:> Description: def fullyflatten(container): """ Completely flattens out a cluster and returns a one-dimensional set containing the cluster's items. This is useful in cases where some items of the cluster are clusters in their own right and you only want the items. :param container: the container to flatten. """
flattened_items = [] for item in container: if hasattr(item, 'items'): flattened_items = flattened_items + fullyflatten(item.items) else: flattened_items.append(item) return flattened_items
<SYSTEM_TASK:> Calculates the minkowski distance between two points. <END_TASK> <USER_TASK:> Description: def minkowski_distance(x, y, p=2): """ Calculates the minkowski distance between two points. :param x: the first point :param y: the second point :param p: the order of the minkowski algorithm. If *p=1* it is equal to the manhatten distance, if *p=2* it is equal to the euclidian distance. The higher the order, the closer it converges to the Chebyshev distance, which has *p=infinity*. """
from math import pow assert len(y) == len(x) assert len(x) >= 1 sum = 0 for i in range(len(x)): sum += abs(x[i] - y[i]) ** p return pow(sum, 1.0 / float(p))
<SYSTEM_TASK:> Pretty-prints this cluster. Useful for debuging. <END_TASK> <USER_TASK:> Description: def display(self, depth=0): """ Pretty-prints this cluster. Useful for debuging. """
print(depth * " " + "[level %s]" % self.level) for item in self.items: if isinstance(item, Cluster): item.display(depth + 1) else: print(depth * " " + "%s" % item)
<SYSTEM_TASK:> Retrieve all clusters up to a specific level threshold. This <END_TASK> <USER_TASK:> Description: def getlevel(self, threshold): """ Retrieve all clusters up to a specific level threshold. This level-threshold represents the maximum distance between two clusters. So the lower you set this threshold, the more clusters you will receive and the higher you set it, you will receive less but bigger clusters. :param threshold: The level threshold: .. note:: It is debatable whether the value passed into this method should really be as strongly linked to the real cluster-levels as it is right now. The end-user will not know the range of this value unless s/he first inspects the top-level cluster. So instead you might argue that a value ranging from 0 to 1 might be a more useful approach. """
left = self.items[0] right = self.items[1] # if this object itself is below the threshold value we only need to # return it's contents as a list if self.level <= threshold: return [fullyflatten(self.items)] # if this cluster's level is higher than the threshold we will # investgate it's left and right part. Their level could be below the # threshold if isinstance(left, Cluster) and left.level <= threshold: if isinstance(right, Cluster): return [fullyflatten(left.items)] + right.getlevel(threshold) else: return [fullyflatten(left.items)] + [[right]] elif isinstance(right, Cluster) and right.level <= threshold: if isinstance(left, Cluster): return left.getlevel(threshold) + [fullyflatten(right.items)] else: return [[left]] + [fullyflatten(right.items)] # Alright. We covered the cases where one of the clusters was below # the threshold value. Now we'll deal with the clusters that are above # by recursively applying the previous cases. if isinstance(left, Cluster) and isinstance(right, Cluster): return left.getlevel(threshold) + right.getlevel(threshold) elif isinstance(left, Cluster): return left.getlevel(threshold) + [[right]] elif isinstance(right, Cluster): return [[left]] + right.getlevel(threshold) else: return [[left], [right]]
<SYSTEM_TASK:> returns a minified version of the javascript string <END_TASK> <USER_TASK:> Description: def jsmin(js, **kwargs): """ returns a minified version of the javascript string """
if not is_3: if cStringIO and not isinstance(js, unicode): # strings can use cStringIO for a 3x performance # improvement, but unicode (in python2) cannot klass = cStringIO.StringIO else: klass = StringIO.StringIO else: klass = io.StringIO ins = klass(js) outs = klass() JavascriptMinify(ins, outs, **kwargs).minify() return outs.getvalue()
<SYSTEM_TASK:> memoizing decorator for linkage functions. <END_TASK> <USER_TASK:> Description: def cached(fun): """ memoizing decorator for linkage functions. Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because, the way this is coded (interchangingly using sets and frozensets) is true for this specific case. For other cases that is not necessarily guaranteed. """
_cache = {} @wraps(fun) def newfun(a, b, distance_function): frozen_a = frozenset(a) frozen_b = frozenset(b) if (frozen_a, frozen_b) not in _cache: result = fun(a, b, distance_function) _cache[(frozen_a, frozen_b)] = result return _cache[(frozen_a, frozen_b)] return newfun
<SYSTEM_TASK:> Given two collections ``a`` and ``b``, this will return the distance of the <END_TASK> <USER_TASK:> Description: def single(a, b, distance_function): """ Given two collections ``a`` and ``b``, this will return the distance of the points which are closest together. ``distance_function`` is used to determine the distance between two elements. Example:: >>> single([1, 2], [3, 4], lambda x, y: abs(x-y)) 1 # (distance between 2 and 3) """
left_a, right_a = min(a), max(a) left_b, right_b = min(b), max(b) result = min(distance_function(left_a, right_b), distance_function(left_b, right_a)) return result
<SYSTEM_TASK:> Given two collections ``a`` and ``b``, this will return the mean of all <END_TASK> <USER_TASK:> Description: def average(a, b, distance_function): """ Given two collections ``a`` and ``b``, this will return the mean of all distances. ``distance_function`` is used to determine the distance between two elements. Example:: >>> single([1, 2], [3, 100], lambda x, y: abs(x-y)) 26 """
distances = [distance_function(x, y) for x in a for y in b] return sum(distances) / len(distances)
<SYSTEM_TASK:> Multiprocessing task function run by worker processes <END_TASK> <USER_TASK:> Description: def worker(self): """ Multiprocessing task function run by worker processes """
tasks_completed = 0 for task in iter(self.task_queue.get, 'STOP'): col_index, item, item2 = task if not hasattr(item, '__iter__') or isinstance(item, tuple): item = [item] if not hasattr(item2, '__iter__') or isinstance(item2, tuple): item2 = [item2] result = (col_index, self.combinfunc(item, item2)) self.done_queue.put(result) tasks_completed += 1 logger.info("Worker %s performed %s tasks", current_process().name, tasks_completed)
<SYSTEM_TASK:> Actually generate the matrix <END_TASK> <USER_TASK:> Description: def genmatrix(self, num_processes=1): """ Actually generate the matrix :param num_processes: If you want to use multiprocessing to split up the work and run ``combinfunc()`` in parallel, specify ``num_processes > 1`` and this number of workers will be spun up, the work is split up amongst them evenly. """
use_multiprocessing = num_processes > 1 if use_multiprocessing: self.task_queue = Queue() self.done_queue = Queue() self.matrix = [] logger.info("Generating matrix for %s items - O(n^2)", len(self.data)) if use_multiprocessing: logger.info("Using multiprocessing on %s processes!", num_processes) if use_multiprocessing: logger.info("Spinning up %s workers", num_processes) processes = [Process(target=self.worker) for i in range(num_processes)] [process.start() for process in processes] for row_index, item in enumerate(self.data): logger.debug("Generating row %s/%s (%0.2f%%)", row_index, len(self.data), 100.0 * row_index / len(self.data)) row = {} if use_multiprocessing: num_tasks_queued = num_tasks_completed = 0 for col_index, item2 in enumerate(self.data): if self.diagonal is not None and col_index == row_index: # This is a cell on the diagonal row[col_index] = self.diagonal elif self.symmetric and col_index < row_index: # The matrix is symmetric and we are "in the lower left # triangle" - fill this in after (in case of multiprocessing) pass # Otherwise, this cell is not on the diagonal and we do indeed # need to call combinfunc() elif use_multiprocessing: # Add that thing to the task queue! self.task_queue.put((col_index, item, item2)) num_tasks_queued += 1 # Start grabbing the results as we go, so as not to stuff all of # the worker args into memory at once (as Queue.get() is a # blocking operation) if num_tasks_queued > num_processes: col_index, result = self.done_queue.get() row[col_index] = result num_tasks_completed += 1 else: # Otherwise do it here, in line """ if not hasattr(item, '__iter__') or isinstance(item, tuple): item = [item] if not hasattr(item2, '__iter__') or isinstance(item2, tuple): item2 = [item2] """ # See the comment in function _encapsulate_item_for_combinfunc # for details of why the lines above have been replaced # by function invocations item = _encapsulate_item_for_combinfunc(item) item2 = _encapsulate_item_for_combinfunc(item2) row[col_index] = self.combinfunc(item, item2) if self.symmetric: # One more iteration to get symmetric lower left triangle for col_index, item2 in enumerate(self.data): if col_index >= row_index: break # post-process symmetric "lower left triangle" row[col_index] = self.matrix[col_index][row_index] if use_multiprocessing: # Grab the remaining worker task results while num_tasks_completed < num_tasks_queued: col_index, result = self.done_queue.get() row[col_index] = result num_tasks_completed += 1 row_indexed = [row[index] for index in range(len(self.data))] self.matrix.append(row_indexed) if use_multiprocessing: logger.info("Stopping/joining %s workers", num_processes) [self.task_queue.put('STOP') for i in range(num_processes)] [process.join() for process in processes] logger.info("Matrix generated")
<SYSTEM_TASK:> This function uses dciodvfy to generate <END_TASK> <USER_TASK:> Description: def validate(fname): """ This function uses dciodvfy to generate a list of warnings and errors discovered within the DICOM file. :param fname: Location and filename of DICOM file. """
validation = { "errors": [], "warnings": [] } for line in _process(fname): kind, message = _determine(line) if kind in validation: validation[kind].append(message) return validation
<SYSTEM_TASK:> Grabs image data and converts it to a numpy array <END_TASK> <USER_TASK:> Description: def numpy(self): """ Grabs image data and converts it to a numpy array """
# load GDCM's image reading functionality image_reader = gdcm.ImageReader() image_reader.SetFileName(self.fname) if not image_reader.Read(): raise IOError("Could not read DICOM image") pixel_array = self._gdcm_to_numpy(image_reader.GetImage()) return pixel_array
<SYSTEM_TASK:> This method saves the image from a numpy array using matplotlib <END_TASK> <USER_TASK:> Description: def save_as_plt(self, fname, pixel_array=None, vmin=None, vmax=None, cmap=None, format=None, origin=None): """ This method saves the image from a numpy array using matplotlib :param fname: Location and name of the image file to be saved. :param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value :param vmin: matplotlib vmin :param vmax: matplotlib vmax :param cmap: matplotlib color map :param format: matplotlib format :param origin: matplotlib origin This method will return True if successful """
from matplotlib.backends.backend_agg \ import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from pylab import cm if pixel_array is None: pixel_array = self.numpy if cmap is None: cmap = cm.bone fig = Figure(figsize=pixel_array.shape[::-1], dpi=1, frameon=False) canvas = FigureCanvas(fig) fig.figimage(pixel_array, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin) fig.savefig(fname, dpi=1, format=format) return True
<SYSTEM_TASK:> Returns array of dictionaries containing all the data elements in <END_TASK> <USER_TASK:> Description: def read(self): """ Returns array of dictionaries containing all the data elements in the DICOM file. """
def ds(data_element): value = self._str_filter.ToStringPair(data_element.GetTag()) if value[1]: return DataElement(data_element, value[0].strip(), value[1].strip()) results = [data for data in self.walk(ds) if data is not None] return results
<SYSTEM_TASK:> Loops through all data elements and allows a function to interact <END_TASK> <USER_TASK:> Description: def walk(self, fn): """ Loops through all data elements and allows a function to interact with each data element. Uses a generator to improve iteration. :param fn: Function that interacts with each DICOM element """
if not hasattr(fn, "__call__"): raise TypeError("""walk_dataset requires a function as its parameter""") dataset = self._dataset iterator = dataset.GetDES().begin() while (not iterator.equal(dataset.GetDES().end())): data_element = iterator.next() yield fn(data_element) header = self._header iterator = header.GetDES().begin() while (not iterator.equal(header.GetDES().end())): data_element = iterator.next() yield fn(data_element)
<SYSTEM_TASK:> Searches for data elements in the DICOM file given the filters <END_TASK> <USER_TASK:> Description: def find(self, group=None, element=None, name=None, VR=None): """ Searches for data elements in the DICOM file given the filters supplied to this method. :param group: Hex decimal for the group of a DICOM element e.g. 0x002 :param element: Hex decimal for the element value of a DICOM element e.g. 0x0010 :param name: Name of the DICOM element, e.g. "Modality" :param VR: Value Representation of the DICOM element, e.g. "PN" """
results = self.read() if name is not None: def find_name(data_element): return data_element.name.lower() == name.lower() return filter(find_name, results) if group is not None: def find_group(data_element): return (data_element.tag['group'] == group or int(data_element.tag['group'], 16) == group) results = filter(find_group, results) if element is not None: def find_element(data_element): return (data_element.tag['element'] == element or int(data_element.tag['element'], 16) == element) results = filter(find_element, results) if VR is not None: def find_VR(data_element): return data_element.VR.lower() == VR.lower() results = filter(find_VR, results) return results
<SYSTEM_TASK:> According to PS 3.15-2008, basic application level <END_TASK> <USER_TASK:> Description: def anonymize(self): """ According to PS 3.15-2008, basic application level De-Indentification of a DICOM file requires replacing the values of a set of data elements"""
self._anon_obj = gdcm.Anonymizer() self._anon_obj.SetFile(self._file) self._anon_obj.RemoveGroupLength() if self._anon_tags is None: self._anon_tags = get_anon_tags() for tag in self._anon_tags: cur_tag = tag['Tag'].replace("(", "") cur_tag = cur_tag.replace(")", "") name = tag["Attribute Name"].replace(" ", "").encode("utf8") group, element = cur_tag.split(",", 1) # TODO expand this 50xx, 60xx, gggg, eeee if ("xx" not in group and "gggg" not in group and "eeee" not in group): group = int(group, 16) element = int(element, 16) if self.find(group=group, element=element): self._anon_obj.Replace( gdcm.Tag(group, element), "Anon" + name) return self._anon_obj
<SYSTEM_TASK:> Returns a DataFrame of the repo names present in this project directory <END_TASK> <USER_TASK:> Description: def repo_name(self): """ Returns a DataFrame of the repo names present in this project directory :return: DataFrame """
ds = [[x.repo_name] for x in self.repos] df = pd.DataFrame(ds, columns=['repository']) return df
<SYSTEM_TASK:> Manually import a CSV into a nYNAB budget <END_TASK> <USER_TASK:> Description: def command(self): """Manually import a CSV into a nYNAB budget"""
print('pynYNAB CSV import') args = self.parser.parse_args() verify_common_args(args) verify_csvimport(args.schema, args.accountname) client = clientfromkwargs(**args) delta = do_csvimport(args, client) client.push(expected_delta=delta)
<SYSTEM_TASK:> Manually import an OFX into a nYNAB budget <END_TASK> <USER_TASK:> Description: def command(self): """Manually import an OFX into a nYNAB budget"""
print('pynYNAB OFX import') args = self.parser.parse_args() verify_common_args(args) client = clientfromkwargs(**args) delta = do_ofximport(args.file, client) client.push(expected_delta=delta)
<SYSTEM_TASK:> Establish a default-setting listener. <END_TASK> <USER_TASK:> Description: def default_listener(col_attr, default): """Establish a default-setting listener."""
@event.listens_for(col_attr, "init_scalar", retval=True, propagate=True) def init_scalar(target, value, dict_): if default.is_callable: # the callable of ColumnDefault always accepts a context argument value = default.arg(None) elif default.is_scalar: value = default.arg else: raise NotImplementedError( "Can't invoke pre-default for a SQL-level column default") dict_[col_attr.key] = value return value
<SYSTEM_TASK:> Returns a boolean for is a parseable .coverage file can be found in the repository <END_TASK> <USER_TASK:> Description: def has_coverage(self): """ Returns a boolean for is a parseable .coverage file can be found in the repository :return: bool """
if os.path.exists(self.git_dir + os.sep + '.coverage'): try: with open(self.git_dir + os.sep + '.coverage', 'r') as f: blob = f.read() blob = blob.split('!')[2] json.loads(blob) return True except Exception: return False else: return False
<SYSTEM_TASK:> Internal method to filter a list of file changes by extension and ignore_dirs. <END_TASK> <USER_TASK:> Description: def __check_extension(files, ignore_globs=None, include_globs=None): """ Internal method to filter a list of file changes by extension and ignore_dirs. :param files: :param ignore_globs: a list of globs to ignore (if none falls back to extensions and ignore_dir) :param include_globs: a list of globs to include (if none, includes all). :return: dict """
if include_globs is None or include_globs == []: include_globs = ['*'] out = {} for key in files.keys(): # count up the number of patterns in the ignore globs list that match if ignore_globs is not None: count_exclude = sum([1 if fnmatch.fnmatch(key, g) else 0 for g in ignore_globs]) else: count_exclude = 0 # count up the number of patterns in the include globs list that match count_include = sum([1 if fnmatch.fnmatch(key, g) else 0 for g in include_globs]) # if we have one vote or more to include and none to exclude, then we use the file. if count_include > 0 and count_exclude == 0: out[key] = files[key] return out
<SYSTEM_TASK:> Returns the name of the repository, using the local directory name. <END_TASK> <USER_TASK:> Description: def _repo_name(self): """ Returns the name of the repository, using the local directory name. :returns: str """
if self._git_repo_name is not None: return self._git_repo_name else: reponame = self.repo.git_dir.split(os.sep)[-2] if reponame.strip() == '': return 'unknown_repo' return reponame
<SYSTEM_TASK:> Get the python representation of the obj <END_TASK> <USER_TASK:> Description: def _decode(self, obj, context): """ Get the python representation of the obj """
return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode("utf8")
<SYSTEM_TASK:> temporarily remove hstore virtual fields otherwise DRF considers them many2many <END_TASK> <USER_TASK:> Description: def update(self, instance, validated_data): """ temporarily remove hstore virtual fields otherwise DRF considers them many2many """
model = self.Meta.model meta = self.Meta.model._meta original_virtual_fields = list(meta.virtual_fields) # copy if hasattr(model, '_hstore_virtual_fields'): # remove hstore virtual fields from meta for field in model._hstore_virtual_fields.values(): meta.virtual_fields.remove(field) instance = super(HStoreSerializer, self).update(instance, validated_data) if hasattr(model, '_hstore_virtual_fields'): # restore original virtual fields meta.virtual_fields = original_virtual_fields return instance
<SYSTEM_TASK:> update image on panel, as quickly as possible <END_TASK> <USER_TASK:> Description: def update_image(self, data): """ update image on panel, as quickly as possible """
if 1 in data.shape: data = data.squeeze() if self.conf.contrast_level is not None: clevels = [self.conf.contrast_level, 100.0-self.conf.contrast_level] imin, imax = np.percentile(data, clevels) data = np.clip((data - imin)/(imax - imin + 1.e-8), 0, 1) self.axes.images[0].set_data(data) self.canvas.draw()
<SYSTEM_TASK:> leftup event handler for zoom mode in images <END_TASK> <USER_TASK:> Description: def zoom_leftup(self, event=None): """leftup event handler for zoom mode in images"""
if self.zoom_ini is None: return ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini try: dx = abs(ini_x - event.x) dy = abs(ini_y - event.y) except: dx, dy = 0, 0 t0 = time.time() self.rbbox = None self.zoom_ini = None if (dx > 3) and (dy > 3) and (t0-self.mouse_uptime)>0.1: self.mouse_uptime = t0 zlims, tlims = {}, {} ax = self.axes xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() zlims[ax] = [xmin, xmax, ymin, ymax] if len(self.conf.zoom_lims) == 0: self.conf.zoom_lims.append(zlims) ax_inv = ax.transData.inverted try: x1, y1 = ax_inv().transform((event.x, event.y)) except: x1, y1 = self.x_lastmove, self.y_lastmove try: x0, y0 = ax_inv().transform((ini_x, ini_y)) except: x0, y0 = ini_xd, ini_yd tlims[ax] = [int(round(min(x0, x1))), int(round(max(x0, x1))), int(round(min(y0, y1))), int(round(max(y0, y1)))] self.conf.zoom_lims.append(tlims) # now apply limits: self.set_viewlimits() if callable(self.zoom_callback): self.zoom_callback(wid=self.GetId(), limits=tlims[ax])
<SYSTEM_TASK:> Collects all the directories into a `set` object. <END_TASK> <USER_TASK:> Description: def collect_directories(self, directories): """ Collects all the directories into a `set` object. If `self.recursive` is set to `True` this method will iterate through and return all of the directories and the subdirectories found from `directories` that are not blacklisted. if `self.recursive` is set to `False` this will return all the directories that are not balcklisted. `directories` may be either a single object or an iterable. Recommend passing in absolute paths instead of relative. `collect_directories` will attempt to convert `directories` to absolute paths if they are not already. """
directories = util.to_absolute_paths(directories) if not self.recursive: return self._remove_blacklisted(directories) recursive_dirs = set() for dir_ in directories: walk_iter = os.walk(dir_, followlinks=True) walk_iter = [w[0] for w in walk_iter] walk_iter = util.to_absolute_paths(walk_iter) walk_iter = self._remove_blacklisted(walk_iter) recursive_dirs.update(walk_iter) return recursive_dirs
<SYSTEM_TASK:> Removes any `directories` from the set of plugin directories. <END_TASK> <USER_TASK:> Description: def remove_directories(self, directories): """ Removes any `directories` from the set of plugin directories. `directories` may be a single object or an iterable. Recommend passing in all paths as absolute, but the method will attemmpt to convert all paths to absolute if they are not already based on the current working directory. """
directories = util.to_absolute_paths(directories) self.plugin_directories = util.remove_from_set(self.plugin_directories, directories)
<SYSTEM_TASK:> Attempts to remove the `directories` from the set of blacklisted <END_TASK> <USER_TASK:> Description: def remove_blacklisted_directories(self, directories): """ Attempts to remove the `directories` from the set of blacklisted directories. If a particular directory is not found in the set of blacklisted, method will continue on silently. `directories` may be a single instance or an iterable. Recommend passing in absolute paths. Method will try to convert to an absolute path if it is not already using the current working directory. """
directories = util.to_absolute_paths(directories) black_dirs = self.blacklisted_directories black_dirs = util.remove_from_set(black_dirs, directories)
<SYSTEM_TASK:> Attempts to remove the blacklisted directories from `directories` <END_TASK> <USER_TASK:> Description: def _remove_blacklisted(self, directories): """ Attempts to remove the blacklisted directories from `directories` and then returns whatever is left in the set. Called from the `collect_directories` method. """
directories = util.to_absolute_paths(directories) directories = util.remove_from_set(directories, self.blacklisted_directories) return directories
<SYSTEM_TASK:> Return image data from TIFF file as numpy array. <END_TASK> <USER_TASK:> Description: def imread(filename, *args, **kwargs): """Return image data from TIFF file as numpy array. The first image series is returned if no arguments are provided. Parameters ---------- key : int, slice, or sequence of page indices Defines which pages to return as array. series : int Defines which series of pages to return as array. Examples -------- >>> image = imread('test.tif', 0) """
with TIFFfile(filename) as tif: return tif.asarray(*args, **kwargs)
<SYSTEM_TASK:> Read MM_HEADER tag from file and return as numpy.rec.array. <END_TASK> <USER_TASK:> Description: def read_mm_header(fd, byte_order, dtype, count): """Read MM_HEADER tag from file and return as numpy.rec.array."""
return numpy.rec.fromfile(fd, MM_HEADER, 1, byteorder=byte_order)[0]
<SYSTEM_TASK:> Read MM_UIC1 tag from file and return as dictionary. <END_TASK> <USER_TASK:> Description: def read_mm_uic1(fd, byte_order, dtype, count): """Read MM_UIC1 tag from file and return as dictionary."""
t = fd.read(8*count) t = struct.unpack('%s%iI' % (byte_order, 2*count), t) return dict((MM_TAG_IDS[k], v) for k, v in zip(t[::2], t[1::2]) if k in MM_TAG_IDS)
<SYSTEM_TASK:> Read MM_UIC2 tag from file and return as dictionary. <END_TASK> <USER_TASK:> Description: def read_mm_uic2(fd, byte_order, dtype, count): """Read MM_UIC2 tag from file and return as dictionary."""
result = {'number_planes': count} values = numpy.fromfile(fd, byte_order+'I', 6*count) result['z_distance'] = values[0::6] // values[1::6] #result['date_created'] = tuple(values[2::6]) #result['time_created'] = tuple(values[3::6]) #result['date_modified'] = tuple(values[4::6]) #result['time_modified'] = tuple(values[5::6]) return result
<SYSTEM_TASK:> Read MM_UIC3 tag from file and return as dictionary. <END_TASK> <USER_TASK:> Description: def read_mm_uic3(fd, byte_order, dtype, count): """Read MM_UIC3 tag from file and return as dictionary."""
t = numpy.fromfile(fd, byte_order+'I', 2*count) return {'wavelengths': t[0::2] // t[1::2]}
<SYSTEM_TASK:> Read CS_LSM_INFO tag from file and return as numpy.rec.array. <END_TASK> <USER_TASK:> Description: def read_cz_lsm_info(fd, byte_order, dtype, count): """Read CS_LSM_INFO tag from file and return as numpy.rec.array."""
result = numpy.rec.fromfile(fd, CZ_LSM_INFO, 1, byteorder=byte_order)[0] {50350412: '1.3', 67127628: '2.0'}[result.magic_number] # validation return result
<SYSTEM_TASK:> Read LSM scan information from file and return as Record. <END_TASK> <USER_TASK:> Description: def read_cz_lsm_scan_info(fd, byte_order): """Read LSM scan information from file and return as Record."""
block = Record() blocks = [block] unpack = struct.unpack if 0x10000000 != struct.unpack(byte_order+"I", fd.read(4))[0]: raise ValueError("not a lsm_scan_info structure") fd.read(8) while True: entry, dtype, size = unpack(byte_order+"III", fd.read(12)) if dtype == 2: value = stripnull(fd.read(size)) elif dtype == 4: value = unpack(byte_order+"i", fd.read(4))[0] elif dtype == 5: value = unpack(byte_order+"d", fd.read(8))[0] else: value = 0 if entry in CZ_LSM_SCAN_INFO_ARRAYS: blocks.append(block) name = CZ_LSM_SCAN_INFO_ARRAYS[entry] newobj = [] setattr(block, name, newobj) block = newobj elif entry in CZ_LSM_SCAN_INFO_STRUCTS: blocks.append(block) newobj = Record() block.append(newobj) block = newobj elif entry in CZ_LSM_SCAN_INFO_ATTRIBUTES: name = CZ_LSM_SCAN_INFO_ATTRIBUTES[entry] setattr(block, name, value) elif entry == 0xffffffff: block = blocks.pop() else: setattr(block, "unknown_%x" % entry, value) if not blocks: break return block
<SYSTEM_TASK:> Decompress PackBits encoded byte string. <END_TASK> <USER_TASK:> Description: def decodepackbits(encoded): """Decompress PackBits encoded byte string. PackBits is a simple byte-oriented run-length compression scheme. """
func = ord if sys.version[0] == '2' else lambda x: x result = [] i = 0 try: while True: n = func(encoded[i]) + 1 i += 1 if n < 129: result.extend(encoded[i:i+n]) i += n elif n > 129: result.extend(encoded[i:i+1] * (258-n)) i += 1 except IndexError: pass return b''.join(result) if sys.version[0] == '2' else bytes(result)
<SYSTEM_TASK:> Decompress byte string to array of integers of any bit size <= 32. <END_TASK> <USER_TASK:> Description: def unpackints(data, dtype, itemsize, runlen=0): """Decompress byte string to array of integers of any bit size <= 32. Parameters ---------- data : byte str Data to decompress. dtype : numpy.dtype or str A numpy boolean or integer type. itemsize : int Number of bits per integer. runlen : int Number of consecutive integers, after which to start at next byte. """
if itemsize == 1: # bitarray data = numpy.fromstring(data, '|B') data = numpy.unpackbits(data) if runlen % 8: data = data.reshape(-1, runlen+(8-runlen%8)) data = data[:, :runlen].reshape(-1) return data.astype(dtype) dtype = numpy.dtype(dtype) if itemsize in (8, 16, 32, 64): return numpy.fromstring(data, dtype) if itemsize < 1 or itemsize > 32: raise ValueError("itemsize out of range: %i" % itemsize) if dtype.kind not in "biu": raise ValueError("invalid dtype") itembytes = next(i for i in (1, 2, 4, 8) if 8 * i >= itemsize) if itembytes != dtype.itemsize: raise ValueError("dtype.itemsize too small") if runlen == 0: runlen = len(data) // itembytes skipbits = runlen*itemsize % 8 if skipbits: skipbits = 8 - skipbits shrbits = itembytes*8 - itemsize bitmask = int(itemsize*'1'+'0'*shrbits, 2) dtypestr = '>' + dtype.char # dtype always big endian? unpack = struct.unpack l = runlen * (len(data)*8 // (runlen*itemsize + skipbits)) result = numpy.empty((l, ), dtype) bitcount = 0 for i in range(len(result)): start = bitcount // 8 s = data[start:start+itembytes] try: code = unpack(dtypestr, s)[0] except Exception: code = unpack(dtypestr, s + b'\x00'*(itembytes-len(s)))[0] code = code << (bitcount % 8) code = code & bitmask result[i] = code >> shrbits bitcount += itemsize if (i+1) % runlen == 0: bitcount += skipbits return result
<SYSTEM_TASK:> Read TIFF header and all page records from file. <END_TASK> <USER_TASK:> Description: def _fromfile(self): """Read TIFF header and all page records from file."""
self._fd.seek(0) try: self.byte_order = {b'II': '<', b'MM': '>'}[self._fd.read(2)] except KeyError: raise ValueError("not a valid TIFF file") version = struct.unpack(self.byte_order+'H', self._fd.read(2))[0] if version == 43: # BigTiff self.offset_size, zero = struct.unpack(self.byte_order+'HH', self._fd.read(4)) if zero or self.offset_size != 8: raise ValueError("not a valid BigTIFF file") elif version == 42: self.offset_size = 4 else: raise ValueError("not a TIFF file") self.pages = [] while True: try: page = TIFFpage(self) self.pages.append(page) except StopIteration: break if not self.pages: raise ValueError("empty TIFF file")
<SYSTEM_TASK:> Return image data of multiple TIFF pages as numpy array. <END_TASK> <USER_TASK:> Description: def asarray(self, key=None, series=None): """Return image data of multiple TIFF pages as numpy array. By default the first image series is returned. Parameters ---------- key : int, slice, or sequence of page indices Defines which pages to return as array. series : int Defines which series of pages to return as array. """
if key is None and series is None: series = 0 if series is not None: pages = self.series[series].pages else: pages = self.pages if key is None: pass elif isinstance(key, int): pages = [pages[key]] elif isinstance(key, slice): pages = pages[key] elif isinstance(key, collections.Iterable): pages = [pages[k] for k in key] else: raise TypeError('key must be an int, slice, or sequence') if len(pages) == 1: return pages[0].asarray() elif self.is_nih: result = numpy.vstack(p.asarray(colormapped=False, squeeze=False) for p in pages) if pages[0].is_palette: result = numpy.take(pages[0].color_map, result, axis=1) result = numpy.swapaxes(result, 0, 1) else: if self.is_ome and any(p is None for p in pages): firstpage = next(p for p in pages if p) nopage = numpy.zeros_like( firstpage.asarray()) result = numpy.vstack((p.asarray() if p else nopage) for p in pages) if key is None: try: result.shape = self.series[series].shape except ValueError: warnings.warn("failed to reshape %s to %s" % ( result.shape, self.series[series].shape)) result.shape = (-1,) + pages[0].shape else: result.shape = (-1,) + pages[0].shape return result
<SYSTEM_TASK:> Read TIFF IFD structure and its tags from file. <END_TASK> <USER_TASK:> Description: def _fromfile(self): """Read TIFF IFD structure and its tags from file. File cursor must be at storage position of IFD offset and is left at offset to next IFD. Raises StopIteration if offset (first bytes read) is 0. """
fd = self.parent._fd byte_order = self.parent.byte_order offset_size = self.parent.offset_size fmt = {4: 'I', 8: 'Q'}[offset_size] offset = struct.unpack(byte_order + fmt, fd.read(offset_size))[0] if not offset: raise StopIteration() # read standard tags tags = self.tags fd.seek(offset) fmt, size = {4: ('H', 2), 8: ('Q', 8)}[offset_size] try: numtags = struct.unpack(byte_order + fmt, fd.read(size))[0] except Exception: warnings.warn("corrupted page list") raise StopIteration() for _ in range(numtags): tag = TIFFtag(self.parent) tags[tag.name] = tag # read LSM info subrecords if self.is_lsm: pos = fd.tell() for name, reader in CZ_LSM_INFO_READERS.items(): try: offset = self.cz_lsm_info["offset_"+name] except KeyError: continue if not offset: continue fd.seek(offset) try: setattr(self, "cz_lsm_"+name, reader(fd, byte_order)) except ValueError: pass fd.seek(pos)
<SYSTEM_TASK:> Initialize instance from arguments. <END_TASK> <USER_TASK:> Description: def _fromdata(self, code, dtype, count, value, name=None): """Initialize instance from arguments."""
self.code = int(code) self.name = name if name else str(code) self.dtype = TIFF_DATA_TYPES[dtype] self.count = int(count) self.value = value
<SYSTEM_TASK:> pass theme colors to bottom panel <END_TASK> <USER_TASK:> Description: def onThemeColor(self, color, item): """pass theme colors to bottom panel"""
bconf = self.panel_bot.conf if item == 'grid': bconf.set_gridcolor(color) elif item == 'bg': bconf.set_bgcolor(color) elif item == 'frame': bconf.set_framecolor(color) elif item == 'text': bconf.set_textcolor(color) bconf.canvas.draw()
<SYSTEM_TASK:> adds `names` to the internal collection of entry points to track <END_TASK> <USER_TASK:> Description: def add_entry_points(self, names): """ adds `names` to the internal collection of entry points to track `names` can be a single object or an iterable but must be a string or iterable of strings. """
names = util.return_set(names) self.entry_point_names.update(names)
<SYSTEM_TASK:> sets the internal collection of entry points to be <END_TASK> <USER_TASK:> Description: def set_entry_points(self, names): """ sets the internal collection of entry points to be equal to `names` `names` can be a single object or an iterable but must be a string or iterable of strings. """
names = util.return_set(names) self.entry_point_names = names
<SYSTEM_TASK:> removes `names` from the set of entry points to track. <END_TASK> <USER_TASK:> Description: def remove_entry_points(self, names): """ removes `names` from the set of entry points to track. `names` can be a single object or an iterable. """
names = util.return_set(names) util.remove_from_set(self.entry_point_names, names)
<SYSTEM_TASK:> helper method to change `paths` to absolute paths. <END_TASK> <USER_TASK:> Description: def to_absolute_paths(paths): """ helper method to change `paths` to absolute paths. Returns a `set` object `paths` can be either a single object or iterable """
abspath = os.path.abspath paths = return_set(paths) absolute_paths = {abspath(x) for x in paths} return absolute_paths
<SYSTEM_TASK:> set a matplotlib Line2D to have the current properties <END_TASK> <USER_TASK:> Description: def update(self, line=None): """ set a matplotlib Line2D to have the current properties"""
if line: markercolor = self.markercolor if markercolor is None: markercolor=self.color # self.set_markeredgecolor(markercolor, line=line) # self.set_markerfacecolor(markercolor, line=line) self.set_label(self.label, line=line) self.set_color(self.color, line=line) self.set_style(self.style, line=line) self.set_drawstyle(self.drawstyle, line=line) self.set_marker(self.marker,line=line) self.set_markersize(self.markersize, line=line) self.set_linewidth(self.linewidth, line=line)
<SYSTEM_TASK:> used for building set of traces <END_TASK> <USER_TASK:> Description: def _init_trace(self, n, color, style, linewidth=2.5, zorder=None, marker=None, markersize=6): """ used for building set of traces"""
while n >= len(self.traces): self.traces.append(LineProperties()) line = self.traces[n] label = "trace %i" % (n+1) line.label = label line.drawstyle = 'default' if zorder is None: zorder = 5 * (n+1) line.zorder = zorder if color is not None: line.color = color if style is not None: line.style = style if linewidth is not None: line.linewidth = linewidth if marker is not None: line.marker = marker if markersize is not None: line.markersize = markersize self.traces[n] = line
<SYSTEM_TASK:> set color for background of plot <END_TASK> <USER_TASK:> Description: def set_bgcolor(self, color): """set color for background of plot"""
self.bgcolor = color for ax in self.canvas.figure.get_axes(): if matplotlib.__version__ < '2.0': ax.set_axis_bgcolor(color) else: ax.set_facecolor(color) if callable(self.theme_color_callback): self.theme_color_callback(color, 'bg')
<SYSTEM_TASK:> set color for labels and axis text <END_TASK> <USER_TASK:> Description: def set_textcolor(self, color): """set color for labels and axis text"""
self.textcolor = color self.relabel() if callable(self.theme_color_callback): self.theme_color_callback(color, 'text')
<SYSTEM_TASK:> unzoom display 1 level or all the way <END_TASK> <USER_TASK:> Description: def unzoom(self, full=False, delay_draw=False): """unzoom display 1 level or all the way"""
if full: self.zoom_lims = self.zoom_lims[:1] self.zoom_lims = [] elif len(self.zoom_lims) > 0: self.zoom_lims.pop() self.set_viewlimits() if not delay_draw: self.canvas.draw()
<SYSTEM_TASK:> add arrow to plot <END_TASK> <USER_TASK:> Description: def add_arrow(self, x1, y1, x2, y2, **kws): """add arrow to plot"""
self.panel.add_arrow(x1, y1, x2, y2, **kws)
<SYSTEM_TASK:> Adds `filepaths` to internal state. Recommend passing <END_TASK> <USER_TASK:> Description: def add_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Adds `filepaths` to internal state. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be added. """
self.file_manager.add_plugin_filepaths(filepaths, except_blacklisted)
<SYSTEM_TASK:> Sets internal state to `filepaths`. Recommend passing <END_TASK> <USER_TASK:> Description: def set_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Sets internal state to `filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable. If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be set. """
self.file_manager.set_plugin_filepaths(filepaths, except_blacklisted)
<SYSTEM_TASK:> Add `filepaths` to blacklisted filepaths. <END_TASK> <USER_TASK:> Description: def add_blacklisted_filepaths(self, filepaths, remove_from_stored=True): """ Add `filepaths` to blacklisted filepaths. If `remove_from_stored` is `True`, any `filepaths` in internal state will be automatically removed. """
self.file_manager.add_blacklisted_filepaths(filepaths, remove_from_stored)
<SYSTEM_TASK:> Collects and returns every filepath from each directory in <END_TASK> <USER_TASK:> Description: def collect_filepaths(self, directories): """ Collects and returns every filepath from each directory in `directories` that is filtered through the `file_filters`. If no `file_filters` are present, passes every file in directory as a result. Always returns a `set` object `directories` can be a object or an iterable. Recommend using absolute paths. """
plugin_filepaths = set() directories = util.to_absolute_paths(directories) for directory in directories: filepaths = util.get_filepaths_from_dir(directory) filepaths = self._filter_filepaths(filepaths) plugin_filepaths.update(set(filepaths)) plugin_filepaths = self._remove_blacklisted(plugin_filepaths) return plugin_filepaths
<SYSTEM_TASK:> Adds `filepaths` to the `self.plugin_filepaths`. Recommend passing <END_TASK> <USER_TASK:> Description: def add_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Adds `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be added. """
filepaths = util.to_absolute_paths(filepaths) if except_blacklisted: filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths) self.plugin_filepaths.update(filepaths)
<SYSTEM_TASK:> Sets `filepaths` to the `self.plugin_filepaths`. Recommend passing <END_TASK> <USER_TASK:> Description: def set_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Sets `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable. If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be set. """
filepaths = util.to_absolute_paths(filepaths) if except_blacklisted: filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths) self.plugin_filepaths = filepaths
<SYSTEM_TASK:> Removes `filepaths` from `self.plugin_filepaths`. <END_TASK> <USER_TASK:> Description: def remove_plugin_filepaths(self, filepaths): """ Removes `filepaths` from `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if not passed in. `filepaths` can be a single object or an iterable. """
filepaths = util.to_absolute_paths(filepaths) self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths, filepaths)
<SYSTEM_TASK:> Sets internal file filters to `file_filters` by tossing old state. <END_TASK> <USER_TASK:> Description: def set_file_filters(self, file_filters): """ Sets internal file filters to `file_filters` by tossing old state. `file_filters` can be single object or iterable. """
file_filters = util.return_list(file_filters) self.file_filters = file_filters
<SYSTEM_TASK:> Adds `file_filters` to the internal file filters. <END_TASK> <USER_TASK:> Description: def add_file_filters(self, file_filters): """ Adds `file_filters` to the internal file filters. `file_filters` can be single object or iterable. """
file_filters = util.return_list(file_filters) self.file_filters.extend(file_filters)
<SYSTEM_TASK:> Removes the `file_filters` from the internal state. <END_TASK> <USER_TASK:> Description: def remove_file_filters(self, file_filters): """ Removes the `file_filters` from the internal state. `file_filters` can be a single object or an iterable. """
self.file_filters = util.remove_from_list(self.file_filters, file_filters)
<SYSTEM_TASK:> Add `filepaths` to blacklisted filepaths. <END_TASK> <USER_TASK:> Description: def add_blacklisted_filepaths(self, filepaths, remove_from_stored=True): """ Add `filepaths` to blacklisted filepaths. If `remove_from_stored` is `True`, any `filepaths` in `plugin_filepaths` will be automatically removed. Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory. """
filepaths = util.to_absolute_paths(filepaths) self.blacklisted_filepaths.update(filepaths) if remove_from_stored: self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths, filepaths)
<SYSTEM_TASK:> Sets internal blacklisted filepaths to filepaths. <END_TASK> <USER_TASK:> Description: def set_blacklisted_filepaths(self, filepaths, remove_from_stored=True): """ Sets internal blacklisted filepaths to filepaths. If `remove_from_stored` is `True`, any `filepaths` in `self.plugin_filepaths` will be automatically removed. Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory. """
filepaths = util.to_absolute_paths(filepaths) self.blacklisted_filepaths = filepaths if remove_from_stored: self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths, filepaths)
<SYSTEM_TASK:> Removes `filepaths` from blacklisted filepaths <END_TASK> <USER_TASK:> Description: def remove_blacklisted_filepaths(self, filepaths): """ Removes `filepaths` from blacklisted filepaths Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory. """
filepaths = util.to_absolute_paths(filepaths) black_paths = self.blacklisted_filepaths black_paths = util.remove_from_set(black_paths, filepaths)
<SYSTEM_TASK:> internal helper method to remove the blacklisted filepaths <END_TASK> <USER_TASK:> Description: def _remove_blacklisted(self, filepaths): """ internal helper method to remove the blacklisted filepaths from `filepaths`. """
filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths) return filepaths
<SYSTEM_TASK:> helps iterate through all the file parsers <END_TASK> <USER_TASK:> Description: def _filter_filepaths(self, filepaths): """ helps iterate through all the file parsers each filter is applied individually to the same set of `filepaths` """
if self.file_filters: plugin_filepaths = set() for file_filter in self.file_filters: plugin_paths = file_filter(filepaths) plugin_filepaths.update(plugin_paths) else: plugin_filepaths = filepaths return plugin_filepaths
<SYSTEM_TASK:> return rgb tuple for named color in rgb.txt or a hex color <END_TASK> <USER_TASK:> Description: def rgb(color,default=(0,0,0)): """ return rgb tuple for named color in rgb.txt or a hex color """
c = color.lower() if c[0:1] == '#' and len(c)==7: r,g,b = c[1:3], c[3:5], c[5:] r,g,b = [int(n, 16) for n in (r, g, b)] return (r,g,b) if c.find(' ')>-1: c = c.replace(' ','') if c.find('gray')>-1: c = c.replace('gray','grey') if c in x11_colors.keys(): return x11_colors[c] return default
<SYSTEM_TASK:> Checks if the given filename is a valid plugin for this Strategy <END_TASK> <USER_TASK:> Description: def plugin_valid(self, filename): """ Checks if the given filename is a valid plugin for this Strategy """
filename = os.path.basename(filename) for regex in self.regex_expressions: if regex.match(filename): return True return False
<SYSTEM_TASK:> Gets message matching provided id. <END_TASK> <USER_TASK:> Description: def get_message(self, message_id): """Gets message matching provided id. the Outlook email matching the provided message_id. Args: message_id: A string for the intended message, provided by Outlook Returns: :class:`Message <pyOutlook.core.message.Message>` """
r = requests.get('https://outlook.office.com/api/v2.0/me/messages/' + message_id, headers=self._headers) check_response(r) return Message._json_to_message(self, r.json())
<SYSTEM_TASK:> Get first 10 messages in account, across all folders. <END_TASK> <USER_TASK:> Description: def get_messages(self, page=0): """Get first 10 messages in account, across all folders. Keyword Args: page (int): Integer representing the 'page' of results to fetch Returns: List[:class:`Message <pyOutlook.core.message.Message>`] """
endpoint = 'https://outlook.office.com/api/v2.0/me/messages' if page > 0: endpoint = endpoint + '/?%24skip=' + str(page) + '0' log.debug('Getting messages from endpoint: {} with Headers: {}'.format(endpoint, self._headers)) r = requests.get(endpoint, headers=self._headers) check_response(r) return Message._json_to_messages(self, r.json())
<SYSTEM_TASK:> Returns a list of all folders for this account <END_TASK> <USER_TASK:> Description: def get_folders(self): """ Returns a list of all folders for this account Returns: List[:class:`Folder <pyOutlook.core.folder.Folder>`] """
endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' r = requests.get(endpoint, headers=self._headers) if check_response(r): return Folder._json_to_folders(self, r.json())
<SYSTEM_TASK:> Retrieves all messages from a folder, specified by its name. This only works with "Well Known" folders, <END_TASK> <USER_TASK:> Description: def _get_messages_from_folder_name(self, folder_name): """ Retrieves all messages from a folder, specified by its name. This only works with "Well Known" folders, such as 'Inbox' or 'Drafts'. Args: folder_name (str): The name of the folder to retrieve Returns: List[:class:`Message <pyOutlook.core.message.Message>` ] """
r = requests.get('https://outlook.office.com/api/v2.0/me/MailFolders/' + folder_name + '/messages', headers=self._headers) check_response(r) return Message._json_to_messages(self, r.json())
<SYSTEM_TASK:> Returns the JSON representation of this message required for making requests to the API. <END_TASK> <USER_TASK:> Description: def api_representation(self, content_type): """ Returns the JSON representation of this message required for making requests to the API. Args: content_type (str): Either 'HTML' or 'Text' """
payload = dict(Subject=self.subject, Body=dict(ContentType=content_type, Content=self.body)) if self.sender is not None: payload.update(From=self.sender.api_representation()) # A list of strings can also be provided for convenience. If provided, convert them into Contacts if any(isinstance(item, str) for item in self.to): self.to = [Contact(email=email) for email in self.to] # Turn each contact into the JSON needed for the Outlook API recipients = [contact.api_representation() for contact in self.to] payload.update(ToRecipients=recipients) # Conduct the same process for CC and BCC if needed if self.cc: if any(isinstance(email, str) for email in self.cc): self.cc = [Contact(email) for email in self.cc] cc_recipients = [contact.api_representation() for contact in self.cc] payload.update(CcRecipients=cc_recipients) if self.bcc: if any(isinstance(email, str) for email in self.bcc): self.bcc = [Contact(email) for email in self.bcc] bcc_recipients = [contact.api_representation() for contact in self.bcc] payload.update(BccRecipients=bcc_recipients) if self._attachments: payload.update(Attachments=[attachment.api_representation() for attachment in self._attachments]) payload.update(Importance=str(self.importance)) return dict(Message=payload)
<SYSTEM_TASK:> Takes the recipients, body, and attachments of the Message and sends. <END_TASK> <USER_TASK:> Description: def send(self, content_type='HTML'): """ Takes the recipients, body, and attachments of the Message and sends. Args: content_type: Can either be 'HTML' or 'Text', defaults to HTML. """
payload = self.api_representation(content_type) endpoint = 'https://outlook.office.com/api/v1.0/me/sendmail' self._make_api_call('post', endpoint=endpoint, data=json.dumps(payload))
<SYSTEM_TASK:> Forward Message to recipients with an optional comment. <END_TASK> <USER_TASK:> Description: def forward(self, to_recipients, forward_comment=None): # type: (Union[List[Contact], List[str]], str) -> None """Forward Message to recipients with an optional comment. Args: to_recipients: A list of :class:`Contacts <pyOutlook.core.contact.Contact>` to send the email to. forward_comment: String comment to append to forwarded email. Examples: >>> john = Contact('[email protected]') >>> betsy = Contact('[email protected]') >>> email = Message() >>> email.forward([john, betsy]) >>> email.forward([john], 'Hey John') """
payload = dict() if forward_comment is not None: payload.update(Comment=forward_comment) # A list of strings can also be provided for convenience. If provided, convert them into Contacts if any(isinstance(recipient, str) for recipient in to_recipients): to_recipients = [Contact(email=email) for email in to_recipients] # Contact() will handle turning itself into the proper JSON format for the API to_recipients = [contact.api_representation() for contact in to_recipients] payload.update(ToRecipients=to_recipients) endpoint = 'https://outlook.office.com/api/v2.0/me/messages/{}/forward'.format(self.message_id) self._make_api_call('post', endpoint=endpoint, data=json.dumps(payload))
<SYSTEM_TASK:> Reply to the Message. <END_TASK> <USER_TASK:> Description: def reply(self, reply_comment): """Reply to the Message. Notes: HTML can be inserted in the string and will be interpreted properly by Outlook. Args: reply_comment: String message to send with email. """
payload = '{ "Comment": "' + reply_comment + '"}' endpoint = 'https://outlook.office.com/api/v2.0/me/messages/' + self.message_id + '/reply' self._make_api_call('post', endpoint, data=payload)
<SYSTEM_TASK:> Replies to everyone on the email, including those on the CC line. <END_TASK> <USER_TASK:> Description: def reply_all(self, reply_comment): """Replies to everyone on the email, including those on the CC line. With great power, comes great responsibility. Args: reply_comment: The string comment to send to everyone on the email. """
payload = '{ "Comment": "' + reply_comment + '"}' endpoint = 'https://outlook.office.com/api/v2.0/me/messages/{}/replyall'.format(self.message_id) self._make_api_call('post', endpoint, data=payload)