_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q6200
BaseBaseModel.find_by_id
train
def find_by_id(self, _id, projection=None): """find record by _id """ if isinstance(_id, list) or isinstance(_id, tuple): return list(self.__collect.find( {'_id': {'$in': [self._to_primary_key(i) for i in _id]}}, projection)) document_id = self._to_primary_ke...
python
{ "resource": "" }
q6201
to_list_str
train
def to_list_str(value, encode=None): """recursively convert list content into string :arg list value: The list that need to be converted. :arg function encode: Function used to encode object. """ result = [] for index, v in enumerate(value): if isinstance(v, dict): result.ap...
python
{ "resource": "" }
q6202
to_dict_str
train
def to_dict_str(origin_value, encode=None): """recursively convert dict content into string """ value = copy.deepcopy(origin_value) for k, v in value.items(): if isinstance(v, dict): value[k] = to_dict_str(v, encode) continue if isinstance(v, list): v...
python
{ "resource": "" }
q6203
default_encode
train
def default_encode(v): """convert ObjectId, datetime, date into string """ if isinstance(v, ObjectId): return unicode_type(v) if isinstance(v, datetime): return format_time(v) if isinstance(v, date): return format_time(v) return v
python
{ "resource": "" }
q6204
to_str
train
def to_str(v, encode=None): """convert any list, dict, iterable and primitives object to string """ if isinstance(v, basestring_type): return v if isinstance(v, dict): return to_dict_str(v, encode) if isinstance(v, Iterable): return to_list_str(v, encode) if encode: ...
python
{ "resource": "" }
q6205
get_base_dir
train
def get_base_dir(currfile, dir_level_num=3): """ find certain path according to currfile """ root_path = os.path.abspath(currfile) for i in range(0, dir_level_num): root_path = os.path.dirname(root_path) return root_path
python
{ "resource": "" }
q6206
join_sys_path
train
def join_sys_path(currfile, dir_level_num=3): """ find certain path then load into sys path """ if os.path.isdir(currfile): root_path = currfile else: root_path = get_base_dir(currfile, dir_level_num) sys.path.append(root_path)
python
{ "resource": "" }
q6207
camel_to_underscore
train
def camel_to_underscore(name): """ convert CamelCase style to under_score_case """ as_list = [] length = len(name) for index, i in enumerate(name): if index != 0 and index != length - 1 and i.isupper(): as_list.append('_%s' % i.lower()) else: as_list.appen...
python
{ "resource": "" }
q6208
encode_http_params
train
def encode_http_params(**kw): ''' url paremeter encode ''' try: _fo = lambda k, v: '{name}={value}'.format( name=k, value=to_basestring(quote(v))) except: _fo = lambda k, v: '%s=%s' % (k, to_basestring(quote(v))) _en = utf8 return '&'.join([_fo(k, _en(v)) for k,...
python
{ "resource": "" }
q6209
_init_file_logger
train
def _init_file_logger(logger, level, log_path, log_size, log_count): """ one logger only have one level RotatingFileHandler """ if level not in [logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]: level = logging.DEBUG for h in logger.handlers: ...
python
{ "resource": "" }
q6210
Session._processor
train
def _processor(self): """Application processor to setup session for every request""" self.store.cleanup(self._config.timeout) self._load()
python
{ "resource": "" }
q6211
Session._load
train
def _load(self): """Load the session from the store, by the id from cookie""" self.session_id = self._session_object.get_session_id() # protection against session_id tampering if self.session_id and not self._valid_session_id(self.session_id): self.session_id = None ...
python
{ "resource": "" }
q6212
Store.encode
train
def encode(self, session_data): """encodes session dict as a string""" pickled = pickle.dumps(session_data) return to_basestring(encodebytes(pickled))
python
{ "resource": "" }
q6213
Store.decode
train
def decode(self, session_data): """decodes the data to get back the session dict """ pickled = decodebytes(utf8(session_data)) return pickle.loads(pickled)
python
{ "resource": "" }
q6214
cli
train
def cli(): """An improved shell command, based on konch.""" from flask.globals import _app_ctx_stack app = _app_ctx_stack.top.app options = {key: app.config.get(key, DEFAULTS[key]) for key in DEFAULTS.keys()} base_context = {"app": app} if options["KONCH_FLASK_IMPORTS"]: base_context.up...
python
{ "resource": "" }
q6215
LazyUUIDTask.replace
train
def replace(self): """ Performs conversion to the regular Task object, referenced by the stored UUID. """ replacement = self._tw.tasks.get(uuid=self._uuid) self.__class__ = replacement.__class__ self.__dict__ = replacement.__dict__
python
{ "resource": "" }
q6216
LazyUUIDTaskSet.replace
train
def replace(self): """ Performs conversion to the regular TaskQuerySet object, referenced by the stored UUIDs. """ replacement = self._tw.tasks.filter(' '.join(self._uuids)) self.__class__ = replacement.__class__ self.__dict__ = replacement.__dict__
python
{ "resource": "" }
q6217
TaskResource._update_data
train
def _update_data(self, data, update_original=False, remove_missing=False): """ Low level update of the internal _data dict. Data which are coming as updates should already be serialized. If update_original is True, the original_data dict is updated as well. """ self._data...
python
{ "resource": "" }
q6218
TaskResource.export_data
train
def export_data(self): """ Exports current data contained in the Task as JSON """ # We need to remove spaces for TW-1504, use custom separators data_tuples = ((key, self._serialize(key, value)) for key, value in six.iteritems(self._data)) # Empty ...
python
{ "resource": "" }
q6219
Task.from_input
train
def from_input(cls, input_file=sys.stdin, modify=None, backend=None): """ Creates a Task object, directly from the stdin, by reading one line. If modify=True, two lines are used, first line interpreted as the original state of the Task object, and second line as its new, modified...
python
{ "resource": "" }
q6220
TaskQuerySet.filter
train
def filter(self, *args, **kwargs): """ Returns a new TaskQuerySet with the given filters added. """ clone = self._clone() for f in args: clone.filter_obj.add_filter(f) for key, value in kwargs.items(): clone.filter_obj.add_filter_param(key, value) ...
python
{ "resource": "" }
q6221
CSequenceMatcher.set_seq1
train
def set_seq1(self, a): """Same as SequenceMatcher.set_seq1, but check for non-list inputs implementation.""" if a is self.a: return self.a = a if not isinstance(self.a, list): self.a = list(self.a) # Types must be hashable to work in the c layer. ...
python
{ "resource": "" }
q6222
CSequenceMatcher.set_seq2
train
def set_seq2(self, b): """Same as SequenceMatcher.set_seq2, but uses the c chainb implementation. """ if b is self.b and hasattr(self, 'isbjunk'): return self.b = b if not isinstance(self.a, list): self.a = list(self.a) if not isinstance(se...
python
{ "resource": "" }
q6223
CSequenceMatcher.get_matching_blocks
train
def get_matching_blocks(self): """Same as SequenceMatcher.get_matching_blocks, but calls through to a faster loop for find_longest_match. The rest is the same. """ if self.matching_blocks is not None: return self.matching_blocks matching_blocks = _cdifflib.matching_...
python
{ "resource": "" }
q6224
_tostream
train
def _tostream(parser, obj, stream, skipprepack = False): """ Compatible to old parsers """ if hasattr(parser, 'tostream'): return parser.tostream(obj, stream, skipprepack) else: data = parser.tobytes(obj, skipprepack) cls = type(parser) if cls not in _deprecated_parse...
python
{ "resource": "" }
q6225
_to_str
train
def _to_str(dumped_val, encoding='utf-8', ordered=True): """ Convert bytes in a dump value to str, allowing json encode """ _dict = OrderedDict if ordered else dict if isinstance(dumped_val, dict): return OrderedDict((k, _to_str(v, encoding)) for k,v in dumped_val.items()) elif isinstanc...
python
{ "resource": "" }
q6226
NamedStruct._unpack
train
def _unpack(self, data): ''' Unpack a struct from bytes. For parser internal use. ''' #self._logger.log(logging.DEBUG, 'unpacking %r', self) current = self while current is not None: data = current._parser.unpack(data, current) last = current ...
python
{ "resource": "" }
q6227
NamedStruct._prepack
train
def _prepack(self): ''' Prepack stage. For parser internal use. ''' current = self while current is not None: current._parser.prepack(current, skip_self = True) current = getattr(current, '_sub', None) current = self while current is not No...
python
{ "resource": "" }
q6228
NamedStruct._getextra
train
def _getextra(self): ''' Get the extra data of this struct. ''' current = self while hasattr(current, '_sub'): current = current._sub return getattr(current, '_extra', None)
python
{ "resource": "" }
q6229
Parser.paddingsize2
train
def paddingsize2(self, realsize): ''' Return a padded size from realsize, for NamedStruct internal use. ''' if self.base is not None: return self.base.paddingsize2(realsize) return (realsize + self.padding - 1) // self.padding * self.padding
python
{ "resource": "" }
q6230
typedef.parser
train
def parser(self): ''' Get parser for this type. Create the parser on first call. ''' if not hasattr(self, '_parser'): self._parser = self._compile() return self._parser
python
{ "resource": "" }
q6231
enum.formatter
train
def formatter(self, value): ''' Format a enumerate value to enumerate names if possible. Used to generate human readable dump result. ''' if not self._bitwise: n = self.getName(value) if n is None: return value else: ...
python
{ "resource": "" }
q6232
OptionalParser.packto
train
def packto(self, namedstruct, stream): """ Pack a struct to a stream """ if hasattr(namedstruct, self.name): return _tostream(self.basetypeparser, getattr(namedstruct, self.name), stream, True) else: return 0
python
{ "resource": "" }
q6233
Meso._get_response
train
def _get_response(self, endpoint, request_dict): """ Returns a dictionary of data requested by each function. Arguments: ---------- endpoint: string, mandatory Set in all other methods, this is the API endpoint specific to each function. request_dict: string, mandato...
python
{ "resource": "" }
q6234
BaseCollection.avg
train
def avg(self, key=None): """ Get the average value of a given key. :param key: The key to get the average for :type key: mixed :rtype: float or int """ count = self.count() if count: return self.sum(key) / count
python
{ "resource": "" }
q6235
BaseCollection.diff
train
def diff(self, items): """ Diff the collections with the given items :param items: The items to diff with :type items: mixed :return: A Collection instance :rtype: Collection """ return self.__class__([i for i in self.items if i not in items])
python
{ "resource": "" }
q6236
BaseCollection.each
train
def each(self, callback): """ Execute a callback over each item. .. code:: collection = Collection([1, 2, 3]) collection.each(lambda x: x + 3) .. warning:: It only applies the callback but does not modify the collection's items. Use the...
python
{ "resource": "" }
q6237
BaseCollection.every
train
def every(self, step, offset=0): """ Create a new collection consisting of every n-th element. :param step: The step size :type step: int :param offset: The start offset :type offset: int :rtype: Collection """ new = [] for position, it...
python
{ "resource": "" }
q6238
BaseCollection.without
train
def without(self, *keys): """ Get all items except for those with the specified keys. :param keys: The keys to remove :type keys: tuple :rtype: Collection """ items = copy(self.items) keys = reversed(sorted(keys)) for key in keys: d...
python
{ "resource": "" }
q6239
BaseCollection.only
train
def only(self, *keys): """ Get the items with the specified keys. :param keys: The keys to keep :type keys: tuple :rtype: Collection """ items = [] for key, value in enumerate(self.items): if key in keys: items.append(value) ...
python
{ "resource": "" }
q6240
BaseCollection.filter
train
def filter(self, callback=None): """ Run a filter over each of the items. :param callback: The filter callback :type callback: callable or None :rtype: Collection """ if callback: return self.__class__(list(filter(callback, self.items))) ret...
python
{ "resource": "" }
q6241
BaseCollection.where
train
def where(self, key, value): """ Filter items by the given key value pair. :param key: The key to filter by :type key: str :param value: The value to filter by :type value: mixed :rtype: Collection """ return self.filter(lambda item: data_get(it...
python
{ "resource": "" }
q6242
BaseCollection.first
train
def first(self, callback=None, default=None): """ Get the first item of the collection. :param default: The default value :type default: mixed """ if callback is not None: for val in self.items: if callback(val): return val...
python
{ "resource": "" }
q6243
BaseCollection.flatten
train
def flatten(self): """ Get a flattened list of the items in the collection. :rtype: Collection """ def _flatten(d): if isinstance(d, dict): for v in d.values(): for nested_v in _flatten(v): yield nested_v ...
python
{ "resource": "" }
q6244
BaseCollection.forget
train
def forget(self, *keys): """ Remove an item from the collection by key. :param keys: The keys to remove :type keys: tuple :rtype: Collection """ keys = reversed(sorted(keys)) for key in keys: del self[key] return self
python
{ "resource": "" }
q6245
BaseCollection.get
train
def get(self, key, default=None): """ Get an element of the collection. :param key: The index of the element :type key: mixed :param default: The default value to return :type default: mixed :rtype: mixed """ try: return self.items[k...
python
{ "resource": "" }
q6246
BaseCollection.implode
train
def implode(self, value, glue=''): """ Concatenate values of a given key as a string. :param value: The value :type value: str :param glue: The glue :type glue: str :rtype: str """ first = self.first() if not isinstance(first, (basestri...
python
{ "resource": "" }
q6247
BaseCollection.last
train
def last(self, callback=None, default=None): """ Get the last item of the collection. :param default: The default value :type default: mixed """ if callback is not None: for val in reversed(self.items): if callback(val): re...
python
{ "resource": "" }
q6248
BaseCollection.pluck
train
def pluck(self, value, key=None): """ Get a list with the values of a given key. :rtype: Collection """ if key: return dict(map(lambda x: (data_get(x, key), data_get(x, value)), self.items)) else: results = list(map(lambda x: data_get(x, value), s...
python
{ "resource": "" }
q6249
BaseCollection.max
train
def max(self, key=None): """ Get the max value of a given key. :param key: The key :type key: str or None :rtype: mixed """ def _max(result, item): val = data_get(item, key) if result is None or val > result: return valu...
python
{ "resource": "" }
q6250
BaseCollection.min
train
def min(self, key=None): """ Get the min value of a given key. :param key: The key :type key: str or None :rtype: mixed """ def _min(result, item): val = data_get(item, key) if result is None or val < result: return valu...
python
{ "resource": "" }
q6251
BaseCollection.for_page
train
def for_page(self, page, per_page): """ "Paginate" the collection by slicing it into a smaller collection. :param page: The current page :type page: int :param per_page: Number of items by slice :type per_page: int :rtype: Collection """ start =...
python
{ "resource": "" }
q6252
BaseCollection.pull
train
def pull(self, key, default=None): """ Pulls an item from the collection. :param key: The key :type key: mixed :param default: The default value :type default: mixed :rtype: mixed """ val = self.get(key, default) self.forget(key) ...
python
{ "resource": "" }
q6253
BaseCollection.reject
train
def reject(self, callback): """ Create a collection of all elements that do not pass a given truth test. :param callback: The truth test :type callback: callable :rtype: Collection """ if self._use_as_callable(callback): return self.filter(lambda ite...
python
{ "resource": "" }
q6254
BaseCollection.sort
train
def sort(self, callback=None): """ Sort through each item with a callback. :param callback: The callback :type callback: callable or None :rtype: Collection """ items = self.items if callback: return self.__class__(sorted(items, key=callback...
python
{ "resource": "" }
q6255
BaseCollection.sum
train
def sum(self, callback=None): """ Get the sum of the given values. :param callback: The callback :type callback: callable or string or None :rtype: mixed """ if callback is None: return sum(self.items) callback = self._value_retriever(callba...
python
{ "resource": "" }
q6256
BaseCollection.zip
train
def zip(self, *items): """ Zip the collection together with one or more arrays. :param items: The items to zip :type items: list :rtype: Collection """ return self.__class__(list(zip(self.items, *items)))
python
{ "resource": "" }
q6257
BaseCollection.merge
train
def merge(self, items): """ Merge the collection with the given items. :param items: The items to merge :type items: list or Collection :rtype: Collection """ if isinstance(items, BaseCollection): items = items.all() if not isinstance(items,...
python
{ "resource": "" }
q6258
BaseCollection.transform
train
def transform(self, callback): """ Transform each item in the collection using a callback. :param callback: The callback :type callback: callable :rtype: Collection """ self._items = self.map(callback).all() return self
python
{ "resource": "" }
q6259
BaseCollection._value_retriever
train
def _value_retriever(self, value): """ Get a value retrieving callback. :type value: mixed :rtype: callable """ if self._use_as_callable(value): return value return lambda item: data_get(item, value)
python
{ "resource": "" }
q6260
buildvrt
train
def buildvrt(input_file_list, output_file, relative=True, **kwargs): """Build a VRT See also: https://www.gdal.org/gdalbuildvrt.html You can find the possible BuildVRTOptions (**kwargs**) here: https://github.com/nextgis/pygdal/blob/78a793057d2162c292af4f6b240e19da5d5e52e2/2.1.0/osgeo/gda...
python
{ "resource": "" }
q6261
rasterize
train
def rasterize(src_vector: str, burn_attribute: str, src_raster_template: str, dst_rasterized: str, gdal_dtype: int = 4): """Rasterize the values of a spatial vector file. Arguments: src_vector {str}} -- A OGR vector file (e.g. GeoPackage, ESRI Sha...
python
{ "resource": "" }
q6262
convert_polygons_to_lines
train
def convert_polygons_to_lines(src_polygons, dst_lines, crs=None, add_allone_col=False): """Convert polygons to lines. Arguments: src_polygons {path to geopandas-readable file} -- Filename of the the polygon vector dataset to be converted to lines. dst_lines {[type]} -- Filename whe...
python
{ "resource": "" }
q6263
dtype_checker_df
train
def dtype_checker_df(df, dtype, return_=None): """Check if there are NaN values of values outside of a given datatype range. Arguments: df {dataframe} -- A dataframe. dtype {str} -- The datatype to check for. Keyword Arguments: return_ {str} -- Returns a boolean dataframe with the v...
python
{ "resource": "" }
q6264
EOCubeChunk._get_spatial_bounds
train
def _get_spatial_bounds(self): """Get the spatial bounds of the chunk.""" # This should be a MultiRasterIO method with rasterio.open(self._mrio._get_template_for_given_resolution(self._mrio.dst_res, "path")) as src_layer: pass # later we need src_layer for src_layer.window_transform...
python
{ "resource": "" }
q6265
EOCubeChunk.robust_data_range
train
def robust_data_range(arr, robust=False, vmin=None, vmax=None): """Get a robust data range, i.e. 2nd and 98th percentile for vmin, vmax parameters.""" # from the seaborn code # https://github.com/mwaskom/seaborn/blob/3a3ec75befab52c02650c62772a90f8c23046038/seaborn/matrix.py#L201 def _...
python
{ "resource": "" }
q6266
EOCubeChunk.from_eocube
train
def from_eocube(eocube, ji): """Create a EOCubeChunk object from an EOCube object.""" eocubewin = EOCubeChunk(ji, eocube.df_layers, eocube.chunksize, eocube.wdir) return eocubewin
python
{ "resource": "" }
q6267
EOCubeSceneCollection.get_chunk
train
def get_chunk(self, ji): """Get a EOCubeChunk""" return EOCubeSceneCollectionChunk(ji=ji, df_layers=self.df_layers, chunksize=self.chunksize, variables=self.variables, ...
python
{ "resource": "" }
q6268
get_dataset
train
def get_dataset(dataset="s2l1c"): """Get a specific sampledata to play around. So far the following sampledata exist: * 's2l1c': One Sentinel-2 Level 1C scene with a reference dataset. * 'lsts': A time series of 105 Landsat scenes each with the bands b3 (red), b4 (nir), b5 (swir1) and fmask. Keyw...
python
{ "resource": "" }
q6269
windows_from_blocksize
train
def windows_from_blocksize(blocksize_xy, width, height): """Create rasterio.windows.Window instances with given size which fully cover a raster. Arguments: blocksize_xy {int or list of two int} -- [description] width {int} -- With of the raster for which to create the windows. height {i...
python
{ "resource": "" }
q6270
MultiRasterIO._get_dst_resolution
train
def _get_dst_resolution(self, dst_res=None): """Get default resolution, i.e. the highest resolution or smallest cell size.""" if dst_res is None: dst_res = min(self._res_indices.keys()) return dst_res
python
{ "resource": "" }
q6271
MultiRasterIO.windows_from_blocksize
train
def windows_from_blocksize(self, blocksize_xy=512): """Create rasterio.windows.Window instances with given size which fully cover the raster. Arguments: blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines the width and height of th...
python
{ "resource": "" }
q6272
MultiRasterIO._resample
train
def _resample(self, arrays, ji_windows): """Resample all arrays with potentially different resolutions to a common resolution.""" # get a destination array template win_dst = ji_windows[self.dst_res] aff_dst = self._layer_meta[self._res_indices[self.dst_res][0]]["transform"] arra...
python
{ "resource": "" }
q6273
extract
train
def extract(src_vector: str, burn_attribute: str, src_raster: list, dst_names: list, dst_dir: str, src_raster_template: str = None, gdal_dtype: int = 4, n_jobs: int = 1): """Extract values from list of single band raster for pixels ...
python
{ "resource": "" }
q6274
Plane.extrema
train
def extrema(self, x0, y0, w, h): """ Returns the minimum and maximum values contained in a given area. :param x0: Starting x index. :param y0: Starting y index. :param w: Width of the area to scan. :param h: Height of the area to scan. :return: Tuple containi...
python
{ "resource": "" }
q6275
Cursebox.set_cursor
train
def set_cursor(self, x, y): """ Sets the cursor to the desired position. :param x: X position :param y: Y position """ curses.curs_set(1) self.screen.move(y, x)
python
{ "resource": "" }
q6276
Cursebox.put
train
def put(self, x, y, text, fg, bg): """ Puts a string at the desired coordinates using the provided colors. :param x: X position :param y: Y position :param text: Text to write :param fg: Foreground color number :param bg: Background color number ...
python
{ "resource": "" }
q6277
Cursebox.poll_event
train
def poll_event(self): """ Waits for an event to happen and returns a string related to the event. If the event is a normal (letter) key press, the letter is returned (case sensitive) :return: Event type """ # Flush all inputs before this one that were done since last po...
python
{ "resource": "" }
q6278
draw_panel
train
def draw_panel(cb, pool, params, plane): """ Draws the application's main panel, displaying the current Mandelbrot view. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :param plane: Plane containing the cu...
python
{ "resource": "" }
q6279
update_display
train
def update_display(cb, pool, params, plane, qwertz): """ Draws everything. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :param plane: Plane containing the current Mandelbrot values. :type plane: plan...
python
{ "resource": "" }
q6280
save
train
def save(params): """ Saves the current parameters to a file. :param params: Current application parameters. :return: """ if is_python3(): import pickle cPickle = pickle else: import cPickle ts = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d_%H-...
python
{ "resource": "" }
q6281
capture
train
def capture(cb, pool, params): """ Renders and saves a screen-sized picture of the current position. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params """ w, h = screen_resolution() # Re-adapt dimens...
python
{ "resource": "" }
q6282
cycle
train
def cycle(cb, pool, params, plane): """ Fun function to do a palette cycling animation. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :param plane: Plane containing the current Mandelbrot values. :typ...
python
{ "resource": "" }
q6283
init_coords
train
def init_coords(cb, params): """ Initializes coordinates and zoom for first use. Loads coordinates from Mandelbrot-space. :param cb: Cursebox instance. :type cb: cursebox.Cursebox :param params: Current application parameters. :type params: params.Params :return: """ w = cb.wid...
python
{ "resource": "" }
q6284
screen_resolution
train
def screen_resolution(): """ Returns the current screen's resolution. Should be multi-platform. :return: A tuple containing the width and height of the screen. """ w = 0 h = 0 try: # Windows import ctypes user32 = ctypes.windll.user32 w, h = user32.GetSy...
python
{ "resource": "" }
q6285
open_file
train
def open_file(filename): """ Multi-platform way to make the OS open a file with its default application """ if sys.platform.startswith("darwin"): subprocess.call(("open", filename)) elif sys.platform == "cygwin": subprocess.call(("cygstart", filename)) elif os.name == "nt": ...
python
{ "resource": "" }
q6286
mandelbrot_iterate
train
def mandelbrot_iterate(c, max_iterations, julia_seed=None): """ Returns the number of iterations before escaping the Mandelbrot fractal. :param c: Coordinates as a complex number :type c: complex :param max_iterations: Limit of how many tries are attempted. :return: Tuple containing the last co...
python
{ "resource": "" }
q6287
mandelbrot
train
def mandelbrot(x, y, params): """ Computes the number of iterations of the given plane-space coordinates. :param x: X coordinate on the plane. :param y: Y coordinate on the plane. :param params: Current application parameters. :type params: params.Params :return: Discrete number of iteratio...
python
{ "resource": "" }
q6288
mandelbrot_capture
train
def mandelbrot_capture(x, y, w, h, params): """ Computes the number of iterations of the given pixel-space coordinates, for high-res capture purposes. Contrary to :func:`mandelbrot`, this function returns a continuous number of iterations to avoid banding. :param x: X coordinate on the picture...
python
{ "resource": "" }
q6289
update_position
train
def update_position(params): """ Computes the center of the viewport's Mandelbrot-space coordinates. :param params: Current application parameters. :type params: params.Params """ cx = params.plane_x0 + params.plane_w / 2.0 cy = params.plane_y0 + params.plane_h / 2.0 params.mb_cx, param...
python
{ "resource": "" }
q6290
zoom
train
def zoom(params, factor): """ Applies a zoom on the current parameters. Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates. :param params: Current application parameters. :param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom) "...
python
{ "resource": "" }
q6291
Params.resize
train
def resize(self, w, h): """ Used when resizing the plane, resets the plane ratio factor. :param w: New width of the visible section of the plane. :param h: New height of the visible section of the plane. """ self.plane_w = w self.plane_h = h self.plane_ra...
python
{ "resource": "" }
q6292
check_sender_and_entity_handle_match
train
def check_sender_and_entity_handle_match(sender_handle, entity_handle): """Ensure that sender and entity handles match. Basically we've already verified the sender is who they say when receiving the payload. However, the sender might be trying to set another author in the payload itself, since Diaspora has...
python
{ "resource": "" }
q6293
transform_attributes
train
def transform_attributes(attrs, cls): """Transform some attribute keys. :param attrs: Properties from the XML :type attrs: dict :param cls: Class of the entity :type cls: class """ transformed = {} for key, value in attrs.items(): if value is None: value = "" ...
python
{ "resource": "" }
q6294
get_element_child_info
train
def get_element_child_info(doc, attr): """Get information from child elements of this elementas a list since order is important. Don't include signature tags. :param doc: XML element :param attr: Attribute to get from the elements, for example "tag" or "text". """ props = [] for child in d...
python
{ "resource": "" }
q6295
rfc7033_webfinger_view
train
def rfc7033_webfinger_view(request, *args, **kwargs): """ Django view to generate an RFC7033 webfinger. """ resource = request.GET.get("resource") if not resource: return HttpResponseBadRequest("No resource found") if not resource.startswith("acct:"): return HttpResponseBadReques...
python
{ "resource": "" }
q6296
retrieve_diaspora_hcard
train
def retrieve_diaspora_hcard(handle): """ Retrieve a remote Diaspora hCard document. :arg handle: Remote handle to retrieve :return: str (HTML document) """ webfinger = retrieve_and_parse_diaspora_webfinger(handle) document, code, exception = fetch_document(webfinger.get("hcard_url")) if...
python
{ "resource": "" }
q6297
retrieve_and_parse_diaspora_webfinger
train
def retrieve_and_parse_diaspora_webfinger(handle): """ Retrieve a and parse a remote Diaspora webfinger document. :arg handle: Remote handle to retrieve :returns: dict """ try: host = handle.split("@")[1] except AttributeError: logger.warning("retrieve_and_parse_diaspora_web...
python
{ "resource": "" }
q6298
retrieve_diaspora_host_meta
train
def retrieve_diaspora_host_meta(host): """ Retrieve a remote Diaspora host-meta document. :arg host: Host to retrieve from :returns: ``XRD`` instance """ document, code, exception = fetch_document(host=host, path="/.well-known/host-meta") if exception: return None xrd = XRD.pars...
python
{ "resource": "" }
q6299
_get_element_text_or_none
train
def _get_element_text_or_none(document, selector): """ Using a CSS selector, get the element and return the text, or None if no element. :arg document: ``HTMLElement`` document :arg selector: CSS selector :returns: str or None """ element = document.cssselect(selector) if element: ...
python
{ "resource": "" }