code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def listMethods(self, pid, sdefpid=None): '''List available service methods. :param pid: object pid :param sDefPid: service definition pid :rtype: :class:`requests.models.Response` ''' # /objects/{pid}/methods ? [format, datetime] # /objects/{pid}/methods/{sdefpi...
List available service methods. :param pid: object pid :param sDefPid: service definition pid :rtype: :class:`requests.models.Response`
Below is the the instruction that describes the task: ### Input: List available service methods. :param pid: object pid :param sDefPid: service definition pid :rtype: :class:`requests.models.Response` ### Response: def listMethods(self, pid, sdefpid=None): '''List available service...
def permission_required(perms, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME): """ this is analog to django's builtin ``permission_required`` decorator, but improved to check per slug ACLRules and default permissions for anonymous and logged in users if there is a r...
this is analog to django's builtin ``permission_required`` decorator, but improved to check per slug ACLRules and default permissions for anonymous and logged in users if there is a rule affecting a slug, the user needs to be part of the rule's allowed users. If there isn't a matching rule, defaults pe...
Below is the the instruction that describes the task: ### Input: this is analog to django's builtin ``permission_required`` decorator, but improved to check per slug ACLRules and default permissions for anonymous and logged in users if there is a rule affecting a slug, the user needs to be part of the ...
def str2listtuple(self, string_message): "Covert a string that is ready to be sent to graphite into a tuple" if type(string_message).__name__ not in ('str', 'unicode'): raise TypeError("Must provide a string or unicode") if not string_message.endswith('\n'): string_mess...
Covert a string that is ready to be sent to graphite into a tuple
Below is the the instruction that describes the task: ### Input: Covert a string that is ready to be sent to graphite into a tuple ### Response: def str2listtuple(self, string_message): "Covert a string that is ready to be sent to graphite into a tuple" if type(string_message).__name__ not in ('st...
def calculate_heartbeats(shb, chb): """ Given a heartbeat string from the server, and a heartbeat tuple from the client, calculate what the actual heartbeat settings should be. :param (str,str) shb: server heartbeat numbers :param (int,int) chb: client heartbeat numbers :rtype: (int,int) "...
Given a heartbeat string from the server, and a heartbeat tuple from the client, calculate what the actual heartbeat settings should be. :param (str,str) shb: server heartbeat numbers :param (int,int) chb: client heartbeat numbers :rtype: (int,int)
Below is the the instruction that describes the task: ### Input: Given a heartbeat string from the server, and a heartbeat tuple from the client, calculate what the actual heartbeat settings should be. :param (str,str) shb: server heartbeat numbers :param (int,int) chb: client heartbeat numbers :r...
def get_unique_figname(dirname, root, ext): """ Append a number to "root" to form a filename that does not already exist in "dirname". """ i = 1 figname = root + '_%d' % i + ext while True: if osp.exists(osp.join(dirname, figname)): i += 1 figname = root + '_%...
Append a number to "root" to form a filename that does not already exist in "dirname".
Below is the the instruction that describes the task: ### Input: Append a number to "root" to form a filename that does not already exist in "dirname". ### Response: def get_unique_figname(dirname, root, ext): """ Append a number to "root" to form a filename that does not already exist in "dirname"...
def virtualchain_set_opfields( op, **fields ): """ Pass along virtualchain-reserved fields to a virtualchain operation. This layer of indirection is meant to help with future compatibility, so virtualchain implementations do not try to set operation fields directly. """ # warn about unsuppo...
Pass along virtualchain-reserved fields to a virtualchain operation. This layer of indirection is meant to help with future compatibility, so virtualchain implementations do not try to set operation fields directly.
Below is the the instruction that describes the task: ### Input: Pass along virtualchain-reserved fields to a virtualchain operation. This layer of indirection is meant to help with future compatibility, so virtualchain implementations do not try to set operation fields directly. ### Response: def virt...
def file(cls, uri_or_path): """ Given either a URI like s3://bucket/path.txt or a path like /path.txt, return a file object for it. """ uri = urlparse(uri_or_path) if not uri.scheme: # Just a normal path return open(uri_or_path, 'rb') else:...
Given either a URI like s3://bucket/path.txt or a path like /path.txt, return a file object for it.
Below is the the instruction that describes the task: ### Input: Given either a URI like s3://bucket/path.txt or a path like /path.txt, return a file object for it. ### Response: def file(cls, uri_or_path): """ Given either a URI like s3://bucket/path.txt or a path like /path.txt, r...
def start(self, rootJob): """ Invoke a Toil workflow with the given job as the root for an initial run. This method must be called in the body of a ``with Toil(...) as toil:`` statement. This method should not be called more than once for a workflow that has not finished. :param...
Invoke a Toil workflow with the given job as the root for an initial run. This method must be called in the body of a ``with Toil(...) as toil:`` statement. This method should not be called more than once for a workflow that has not finished. :param toil.job.Job rootJob: The root job of the wor...
Below is the the instruction that describes the task: ### Input: Invoke a Toil workflow with the given job as the root for an initial run. This method must be called in the body of a ``with Toil(...) as toil:`` statement. This method should not be called more than once for a workflow that has not fi...
def get_last_version(skip_tags=None) -> Optional[str]: """ Return last version from repo tags. :return: A string contains version number. """ debug('get_last_version skip_tags=', skip_tags) check_repo() skip_tags = skip_tags or [] def version_finder(tag): if isinstance(tag.com...
Return last version from repo tags. :return: A string contains version number.
Below is the the instruction that describes the task: ### Input: Return last version from repo tags. :return: A string contains version number. ### Response: def get_last_version(skip_tags=None) -> Optional[str]: """ Return last version from repo tags. :return: A string contains version number. ...
def t_escaped_CARRIAGE_RETURN_CHAR(self, t): r'\x72' # 'r' t.lexer.pop_state() t.value = unichr(0x000d) return t
r'\x72
Below is the the instruction that describes the task: ### Input: r'\x72 ### Response: def t_escaped_CARRIAGE_RETURN_CHAR(self, t): r'\x72' # 'r' t.lexer.pop_state() t.value = unichr(0x000d) return t
def call(self, request=None, *args, **kwargs): """ Calls multiple time - with retry. :param request: :return: response """ if request is not None: self.request = request retry = self.request.configuration.retry if not isinstance(retry, Simple...
Calls multiple time - with retry. :param request: :return: response
Below is the the instruction that describes the task: ### Input: Calls multiple time - with retry. :param request: :return: response ### Response: def call(self, request=None, *args, **kwargs): """ Calls multiple time - with retry. :param request: :return: response...
def read(self, domain, type_name, search_command, body=None): """Read entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use thi...
Read entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command ...
Below is the the instruction that describes the task: ### Input: Read entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this re...
def validate_complex_list(prop, value, xpath_map=None): """ Default validation for Attribute Details data structure """ if value is not None: validate_type(prop, value, (dict, list)) if prop in _complex_definitions: complex_keys = _complex_definitions[prop] else: ...
Default validation for Attribute Details data structure
Below is the the instruction that describes the task: ### Input: Default validation for Attribute Details data structure ### Response: def validate_complex_list(prop, value, xpath_map=None): """ Default validation for Attribute Details data structure """ if value is not None: validate_type(prop, v...
def add_predicate(self, predicate): """ Add a new predicate callback to this handler. """ _predicate = predicate if isinstance(predicate, partial): _predicate = 'partial(%s, %s, %s)' % (predicate.func, predicate.args, predicate.keywords) if LOG_OPTS['register'...
Add a new predicate callback to this handler.
Below is the the instruction that describes the task: ### Input: Add a new predicate callback to this handler. ### Response: def add_predicate(self, predicate): """ Add a new predicate callback to this handler. """ _predicate = predicate if isinstance(predicate, partial): ...
def ping(daemon, channel, data=None): """ Process the 'ping' control message. :param daemon: The control daemon; used to get at the configuration and the database. :param channel: The publish channel to which to send the response. :param data: Optional extra d...
Process the 'ping' control message. :param daemon: The control daemon; used to get at the configuration and the database. :param channel: The publish channel to which to send the response. :param data: Optional extra data. Will be returned as the sec...
Below is the the instruction that describes the task: ### Input: Process the 'ping' control message. :param daemon: The control daemon; used to get at the configuration and the database. :param channel: The publish channel to which to send the response. :param dat...
def _dump_date(d, delim): """Used for `http_date` and `cookie_date`.""" if d is None: d = gmtime() elif isinstance(d, datetime): d = d.utctimetuple() elif isinstance(d, (integer_types, float)): d = gmtime(d) return "%s, %02d%s%s%s%s %02d:%02d:%02d GMT" % ( ("Mon", "Tu...
Used for `http_date` and `cookie_date`.
Below is the the instruction that describes the task: ### Input: Used for `http_date` and `cookie_date`. ### Response: def _dump_date(d, delim): """Used for `http_date` and `cookie_date`.""" if d is None: d = gmtime() elif isinstance(d, datetime): d = d.utctimetuple() elif isinstanc...
def index_to_time_seg(time_seg_idx, slide_step): """ 将时间片索引值转换为时间片字符串 :param time_seg_idx: :param slide_step: :return: """ assert (time_seg_idx * slide_step < const.MINUTES_IN_A_DAY) return time_util.minutes_to_time_str(time_seg_idx * slide_step)
将时间片索引值转换为时间片字符串 :param time_seg_idx: :param slide_step: :return:
Below is the the instruction that describes the task: ### Input: 将时间片索引值转换为时间片字符串 :param time_seg_idx: :param slide_step: :return: ### Response: def index_to_time_seg(time_seg_idx, slide_step): """ 将时间片索引值转换为时间片字符串 :param time_seg_idx: :param slide_step: :return: """ assert ...
def process(self): """! @brief Performs cluster analysis in line with rules of CLARANS algorithm. @see get_clusters() @see get_medoids() """ random.seed() for _ in range(0, self.__numlocal): # set (curren...
! @brief Performs cluster analysis in line with rules of CLARANS algorithm. @see get_clusters() @see get_medoids()
Below is the the instruction that describes the task: ### Input: ! @brief Performs cluster analysis in line with rules of CLARANS algorithm. @see get_clusters() @see get_medoids() ### Response: def process(self): """! @brief Performs cluster analysis in line w...
def ebic_select(self, gamma=0): """Uses Extended Bayesian Information Criteria for model selection. Can only be used in path mode (doesn't really make sense otherwise). See: Extended Bayesian Information Criteria for Gaussian Graphical Models R. Foygel and M. Drton NIPS...
Uses Extended Bayesian Information Criteria for model selection. Can only be used in path mode (doesn't really make sense otherwise). See: Extended Bayesian Information Criteria for Gaussian Graphical Models R. Foygel and M. Drton NIPS 2010 Parameters ---------...
Below is the the instruction that describes the task: ### Input: Uses Extended Bayesian Information Criteria for model selection. Can only be used in path mode (doesn't really make sense otherwise). See: Extended Bayesian Information Criteria for Gaussian Graphical Models R. Foygel...
def all_distinct(l, idx): """ Returns the list [l[i] for i in idx]  When needed, objects l[i] are replaced by a copy, to make sure that the elements of the list are all distinct Parameters --------- l: iterable idx: iterable that generates ints (e.g. ndarray of ints) Returns --...
Returns the list [l[i] for i in idx]  When needed, objects l[i] are replaced by a copy, to make sure that the elements of the list are all distinct Parameters --------- l: iterable idx: iterable that generates ints (e.g. ndarray of ints) Returns ------- a list
Below is the the instruction that describes the task: ### Input: Returns the list [l[i] for i in idx]  When needed, objects l[i] are replaced by a copy, to make sure that the elements of the list are all distinct Parameters --------- l: iterable idx: iterable that generates ints (e.g. ndarr...
def _decode_alt_names(self, alt_names): """Load SubjectAltName from a ASN.1 GeneralNames value. :Values: - `alt_names`: the SubjectAltNama extension value :Types: - `alt_name`: `GeneralNames` """ for alt_name in alt_names: tname = alt_name.get...
Load SubjectAltName from a ASN.1 GeneralNames value. :Values: - `alt_names`: the SubjectAltNama extension value :Types: - `alt_name`: `GeneralNames`
Below is the the instruction that describes the task: ### Input: Load SubjectAltName from a ASN.1 GeneralNames value. :Values: - `alt_names`: the SubjectAltNama extension value :Types: - `alt_name`: `GeneralNames` ### Response: def _decode_alt_names(self, alt_names): ...
def delete(self, record): """Delete a record. :param record: Record instance. """ index, doc_type = self.record_to_index(record) return self.client.delete( id=str(record.id), index=index, doc_type=doc_type, )
Delete a record. :param record: Record instance.
Below is the the instruction that describes the task: ### Input: Delete a record. :param record: Record instance. ### Response: def delete(self, record): """Delete a record. :param record: Record instance. """ index, doc_type = self.record_to_index(record) return ...
def types(self, *args): """Used for debugging, returns type of each arg. TYPES,ARG_1,...,ARG_N %{TYPES:A,...,10} -> 'str(A) str(B) ... int(10)' """ return ', '.join(['{0}({1})'.format(type(arg).__name__, arg) for arg in args])
Used for debugging, returns type of each arg. TYPES,ARG_1,...,ARG_N %{TYPES:A,...,10} -> 'str(A) str(B) ... int(10)'
Below is the the instruction that describes the task: ### Input: Used for debugging, returns type of each arg. TYPES,ARG_1,...,ARG_N %{TYPES:A,...,10} -> 'str(A) str(B) ... int(10)' ### Response: def types(self, *args): """Used for debugging, returns type of each arg. TYPES...
def _build_provider_list(): """ Construct the provider registry, using the app settings. """ registry = None if appsettings.FLUENT_OEMBED_SOURCE == 'basic': registry = bootstrap_basic() elif appsettings.FLUENT_OEMBED_SOURCE == 'embedly': params = {} if appsettings.MICAWBE...
Construct the provider registry, using the app settings.
Below is the the instruction that describes the task: ### Input: Construct the provider registry, using the app settings. ### Response: def _build_provider_list(): """ Construct the provider registry, using the app settings. """ registry = None if appsettings.FLUENT_OEMBED_SOURCE == 'basic': ...
def system_config_files(self): """Get a list of absolute paths to the system config files.""" return [os.path.join(f, self.filename) for f in get_system_config_dirs( self.app_name, self.app_author)]
Get a list of absolute paths to the system config files.
Below is the the instruction that describes the task: ### Input: Get a list of absolute paths to the system config files. ### Response: def system_config_files(self): """Get a list of absolute paths to the system config files.""" return [os.path.join(f, self.filename) for f in get_system_config_dir...
def dew_point(self, db): """Get the dew point (C), which is constant throughout the day (except at saturation). args: db: The maximum dry bulb temperature over the day. """ if self._hum_type == 'Dewpoint': return self._hum_value elif self._hum_type == 'We...
Get the dew point (C), which is constant throughout the day (except at saturation). args: db: The maximum dry bulb temperature over the day.
Below is the the instruction that describes the task: ### Input: Get the dew point (C), which is constant throughout the day (except at saturation). args: db: The maximum dry bulb temperature over the day. ### Response: def dew_point(self, db): """Get the dew point (C), which is consta...
def update(self, of): """Update a file from another file, for copying""" # The other values should be set when the file object is created with dataset.bsfile() for p in ('mime_type', 'preference', 'state', 'hash', 'modified', 'size', 'contents', 'source_hash', 'data'): setattr(self,...
Update a file from another file, for copying
Below is the the instruction that describes the task: ### Input: Update a file from another file, for copying ### Response: def update(self, of): """Update a file from another file, for copying""" # The other values should be set when the file object is created with dataset.bsfile() for p ...
def aggregations(self): """ Override parent method. Obtain list of the terms and their corresponding values using "terms" aggregations for the previous time period. :returns: a data frame containing terms and their corresponding values """ prev_month_start = get_prev_mo...
Override parent method. Obtain list of the terms and their corresponding values using "terms" aggregations for the previous time period. :returns: a data frame containing terms and their corresponding values
Below is the the instruction that describes the task: ### Input: Override parent method. Obtain list of the terms and their corresponding values using "terms" aggregations for the previous time period. :returns: a data frame containing terms and their corresponding values ### Response: def aggrega...
def TryLink( self, text, extension ): """Compiles the program given in text to an executable env.Program, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing). """ ...
Compiles the program given in text to an executable env.Program, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing).
Below is the the instruction that describes the task: ### Input: Compiles the program given in text to an executable env.Program, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processi...
def forms_valid(self, inlines): """ If the form and formsets are valid, save the associated models. """ for formset in inlines: formset.save() return HttpResponseRedirect(self.get_success_url())
If the form and formsets are valid, save the associated models.
Below is the the instruction that describes the task: ### Input: If the form and formsets are valid, save the associated models. ### Response: def forms_valid(self, inlines): """ If the form and formsets are valid, save the associated models. """ for formset in inlines: ...
def _build_url(self, endpoint): """ Build complete URL """ if not issubclass(type(self), ChatApiBase) and not self.subdomain: raise ZenpyException("subdomain is required when accessing the Zendesk API!") if self.subdomain: endpoint.netloc = '{}.{}'.format(self.subdomain,...
Build complete URL
Below is the the instruction that describes the task: ### Input: Build complete URL ### Response: def _build_url(self, endpoint): """ Build complete URL """ if not issubclass(type(self), ChatApiBase) and not self.subdomain: raise ZenpyException("subdomain is required when accessing the ...
def parse_args(): ''' Parse the arguments ''' parser = argparse.ArgumentParser(prog='setup_tree_modules', usage='%(prog)s [opts]') parser.add_argument('-v', '--verbose', action='store_true', dest='verbose', help='Print extra information.', default=False) parser.add_argument('-r'...
Parse the arguments
Below is the the instruction that describes the task: ### Input: Parse the arguments ### Response: def parse_args(): ''' Parse the arguments ''' parser = argparse.ArgumentParser(prog='setup_tree_modules', usage='%(prog)s [opts]') parser.add_argument('-v', '--verbose', action='store_true', dest='verbos...
def strptime_fuzzy(s): """Fuzzy date string parsing Note: this returns current date if not found. If only year is provided, will return current month, day """ import dateutil.parser dt = dateutil.parser.parse(str(s), fuzzy=True) return dt
Fuzzy date string parsing Note: this returns current date if not found. If only year is provided, will return current month, day
Below is the the instruction that describes the task: ### Input: Fuzzy date string parsing Note: this returns current date if not found. If only year is provided, will return current month, day ### Response: def strptime_fuzzy(s): """Fuzzy date string parsing Note: this returns current date if not fo...
def compress_and_sort_index(self): """Sort index, add header, and compress. :rtype: bool :returns: True """ idx_fname = '{name}.{date}.mbox.csv'.format(**self.__dict__) try: reader = csv.reader(open(idx_fname), dialect='excel-tab') except IOError: ...
Sort index, add header, and compress. :rtype: bool :returns: True
Below is the the instruction that describes the task: ### Input: Sort index, add header, and compress. :rtype: bool :returns: True ### Response: def compress_and_sort_index(self): """Sort index, add header, and compress. :rtype: bool :returns: True """ idx...
def _parse(self, stream, context, path): """Parse until the end of objects data.""" num_players = context._._._.replay.num_players start = stream.tell() # Have to read everything to be able to use find() read_bytes = stream.read() # Try to find the first marker, a portion...
Parse until the end of objects data.
Below is the the instruction that describes the task: ### Input: Parse until the end of objects data. ### Response: def _parse(self, stream, context, path): """Parse until the end of objects data.""" num_players = context._._._.replay.num_players start = stream.tell() # Have to read...
def a_torispherical(D, f, k): r'''Calculates depth of a torispherical head according to [1]_. .. math:: a = a_1 + a_2 .. math:: \alpha = \sin^{-1}\frac{1-2k}{2(f-k)} .. math:: a_1 = fD(1-\cos\alpha) .. math:: a_2 = kD\cos\alpha Parameters ---------- D...
r'''Calculates depth of a torispherical head according to [1]_. .. math:: a = a_1 + a_2 .. math:: \alpha = \sin^{-1}\frac{1-2k}{2(f-k)} .. math:: a_1 = fD(1-\cos\alpha) .. math:: a_2 = kD\cos\alpha Parameters ---------- D : float Diameter of the m...
Below is the the instruction that describes the task: ### Input: r'''Calculates depth of a torispherical head according to [1]_. .. math:: a = a_1 + a_2 .. math:: \alpha = \sin^{-1}\frac{1-2k}{2(f-k)} .. math:: a_1 = fD(1-\cos\alpha) .. math:: a_2 = kD\cos\alpha ...
def _update_object_map(self, obj_map): """loop through all the keys in self.my_osid_object._my_map, and see if any of them contain text like "AssetContent:<label>" If so, assume it is markup (?), replace the string with asset_content.get_url()""" # TODO: Look for <img> tags to add in alt...
loop through all the keys in self.my_osid_object._my_map, and see if any of them contain text like "AssetContent:<label>" If so, assume it is markup (?), replace the string with asset_content.get_url()
Below is the the instruction that describes the task: ### Input: loop through all the keys in self.my_osid_object._my_map, and see if any of them contain text like "AssetContent:<label>" If so, assume it is markup (?), replace the string with asset_content.get_url() ### Response: def _update_object...
def AppConfigFlagHandler(feature=None): """ This is the default handler. It checks for feature flags in the current app's configuration. For example, to have 'unfinished_feature' hidden in production but active in development: config.py class ProductionConfig(Config): FEATURE_FLAGS = { 'unfinished...
This is the default handler. It checks for feature flags in the current app's configuration. For example, to have 'unfinished_feature' hidden in production but active in development: config.py class ProductionConfig(Config): FEATURE_FLAGS = { 'unfinished_feature' : False, } class Development...
Below is the the instruction that describes the task: ### Input: This is the default handler. It checks for feature flags in the current app's configuration. For example, to have 'unfinished_feature' hidden in production but active in development: config.py class ProductionConfig(Config): FEATURE_FLAG...
def _read_mode_ts(self, size, kind): """Read Time Stamp option. Positional arguments: * size - int, length of option * kind - int, 68 (TS) Returns: * dict -- extracted Time Stamp (TS) option Structure of Timestamp (TS) option [RFC 791]: ...
Read Time Stamp option. Positional arguments: * size - int, length of option * kind - int, 68 (TS) Returns: * dict -- extracted Time Stamp (TS) option Structure of Timestamp (TS) option [RFC 791]: +--------+--------+--------+--------+ ...
Below is the the instruction that describes the task: ### Input: Read Time Stamp option. Positional arguments: * size - int, length of option * kind - int, 68 (TS) Returns: * dict -- extracted Time Stamp (TS) option Structure of Timestamp (TS) option [R...
def _infer_shape(self, dimensions): """Replaces the -1 wildcard in the output shape vector. This function infers the correct output shape given the input dimensions. Args: dimensions: List of input non-batch dimensions. Returns: Tuple of non-batch output dimensions. """ # Size of ...
Replaces the -1 wildcard in the output shape vector. This function infers the correct output shape given the input dimensions. Args: dimensions: List of input non-batch dimensions. Returns: Tuple of non-batch output dimensions.
Below is the the instruction that describes the task: ### Input: Replaces the -1 wildcard in the output shape vector. This function infers the correct output shape given the input dimensions. Args: dimensions: List of input non-batch dimensions. Returns: Tuple of non-batch output dimensio...
def _show_annotation_box(self, event): """Update an existing box or create an annotation box for an event.""" ax = event.artist.axes # Get the pre-created annotation box for the axes or create a new one. if self.display != 'multiple': annotation = self.annotations[ax] ...
Update an existing box or create an annotation box for an event.
Below is the the instruction that describes the task: ### Input: Update an existing box or create an annotation box for an event. ### Response: def _show_annotation_box(self, event): """Update an existing box or create an annotation box for an event.""" ax = event.artist.axes # Get the pre-...
def post_freeze_hook(self): """Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions. This method is called at the end of the :meth:`dtoolcore.ProtoDataSet.freeze` method. In the :class:`dtoolcore.storage_broker.DiskStorageBroker` it removes the temporary directory for sto...
Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions. This method is called at the end of the :meth:`dtoolcore.ProtoDataSet.freeze` method. In the :class:`dtoolcore.storage_broker.DiskStorageBroker` it removes the temporary directory for storing item metadata fragment files.
Below is the the instruction that describes the task: ### Input: Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions. This method is called at the end of the :meth:`dtoolcore.ProtoDataSet.freeze` method. In the :class:`dtoolcore.storage_broker.DiskStorageBroker` it removes t...
def com_google_fonts_check_whitespace_ink(ttFont): """Whitespace glyphs have ink?""" from fontbakery.utils import get_glyph_name, glyph_has_ink # code-points for all "whitespace" chars: WHITESPACE_CHARACTERS = [ 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x0020, 0x0085, 0x00A0, 0x1680, 0x2000, 0x2001,...
Whitespace glyphs have ink?
Below is the the instruction that describes the task: ### Input: Whitespace glyphs have ink? ### Response: def com_google_fonts_check_whitespace_ink(ttFont): """Whitespace glyphs have ink?""" from fontbakery.utils import get_glyph_name, glyph_has_ink # code-points for all "whitespace" chars: WHITESPACE_CH...
def get_html_attrs(kwargs=None): """Generate HTML attributes from the provided keyword arguments. The output value is sorted by the passed keys, to provide consistent output. Because of the frequent use of the normally reserved keyword `class`, `classes` is used instead. Also, all underscores are tran...
Generate HTML attributes from the provided keyword arguments. The output value is sorted by the passed keys, to provide consistent output. Because of the frequent use of the normally reserved keyword `class`, `classes` is used instead. Also, all underscores are translated to regular dashes. Set a...
Below is the the instruction that describes the task: ### Input: Generate HTML attributes from the provided keyword arguments. The output value is sorted by the passed keys, to provide consistent output. Because of the frequent use of the normally reserved keyword `class`, `classes` is used instead. A...
def get_dataset(): """Create a dataset for machine learning of segmentations. Returns ------- tuple : (X, y) where X is a list of tuples. Each tuple is a feature. y is a list of labels (0 for 'not in one symbol' and 1 for 'in symbol') """ seg_data = "segmentation-X.npy" seg_...
Create a dataset for machine learning of segmentations. Returns ------- tuple : (X, y) where X is a list of tuples. Each tuple is a feature. y is a list of labels (0 for 'not in one symbol' and 1 for 'in symbol')
Below is the the instruction that describes the task: ### Input: Create a dataset for machine learning of segmentations. Returns ------- tuple : (X, y) where X is a list of tuples. Each tuple is a feature. y is a list of labels (0 for 'not in one symbol' and 1 for 'in symbol') ### Respo...
def enable_support_autoupload(self, **kwargs): """Set Spanning Tree state. Args: enabled (bool): Is Autoupload enabled? (True, False). callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ...
Set Spanning Tree state. Args: enabled (bool): Is Autoupload enabled? (True, False). callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: ...
Below is the the instruction that describes the task: ### Input: Set Spanning Tree state. Args: enabled (bool): Is Autoupload enabled? (True, False). callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will...
def retryable_http_error( e ): """ Determine if an error encountered during an HTTP download is likely to go away if we try again. """ if isinstance( e, urllib.error.HTTPError ) and e.code in ('503', '408', '500'): # The server returned one of: # 503 Service Unavailable # 408 Req...
Determine if an error encountered during an HTTP download is likely to go away if we try again.
Below is the the instruction that describes the task: ### Input: Determine if an error encountered during an HTTP download is likely to go away if we try again. ### Response: def retryable_http_error( e ): """ Determine if an error encountered during an HTTP download is likely to go away if we try again. ...
def insert(self, name, index, value): """Insert a value at the passed index in the named header.""" return self._sequence[name].insert(index, value)
Insert a value at the passed index in the named header.
Below is the the instruction that describes the task: ### Input: Insert a value at the passed index in the named header. ### Response: def insert(self, name, index, value): """Insert a value at the passed index in the named header.""" return self._sequence[name].insert(index, value)
def close(self): """ Stop the client. """ self.stopped.set() for event in self.to_be_stopped: event.set() if self._receiver_thread is not None: self._receiver_thread.join() self._socket.close()
Stop the client.
Below is the the instruction that describes the task: ### Input: Stop the client. ### Response: def close(self): """ Stop the client. """ self.stopped.set() for event in self.to_be_stopped: event.set() if self._receiver_thread is not None: se...
def merge(s, t): """Merge dictionary t into s.""" for k, v in t.items(): if isinstance(v, dict): if k not in s: s[k] = v continue s[k] = merge(s[k], v) continue s[k] = v return s
Merge dictionary t into s.
Below is the the instruction that describes the task: ### Input: Merge dictionary t into s. ### Response: def merge(s, t): """Merge dictionary t into s.""" for k, v in t.items(): if isinstance(v, dict): if k not in s: s[k] = v continue s[k] ...
def create_node(args): ''' Create a node. ''' node = query(method='servers', args=args, http_method='POST') action = query( method='servers', server_id=node['server']['id'], command='action', args={'action': 'poweron'}, http_method='POST' ) return node
Create a node.
Below is the the instruction that describes the task: ### Input: Create a node. ### Response: def create_node(args): ''' Create a node. ''' node = query(method='servers', args=args, http_method='POST') action = query( method='servers', server_id=node['server']['id'], comman...
def _validate_image_orientation(image_orientation): ''' Ensure that the image orientation is supported - The direction cosines have magnitudes of 1 (just in case) - The direction cosines are perpendicular ''' row_cosine, column_cosine, slice_cosine = _extract_cosines(image_orientation) if n...
Ensure that the image orientation is supported - The direction cosines have magnitudes of 1 (just in case) - The direction cosines are perpendicular
Below is the the instruction that describes the task: ### Input: Ensure that the image orientation is supported - The direction cosines have magnitudes of 1 (just in case) - The direction cosines are perpendicular ### Response: def _validate_image_orientation(image_orientation): ''' Ensure that the...
def register_filter(self, filter_name, filter_ref, force=False): """ Add/register one filter. Args: filter_name (str): Filter name used inside :program:`Jinja2` tags. filter_ref: Reference to the filter itself, i.e. the corresponding :program:`Python` function. ...
Add/register one filter. Args: filter_name (str): Filter name used inside :program:`Jinja2` tags. filter_ref: Reference to the filter itself, i.e. the corresponding :program:`Python` function. force (bool): If set to ``True``, forces the registration of a filter no matter if...
Below is the the instruction that describes the task: ### Input: Add/register one filter. Args: filter_name (str): Filter name used inside :program:`Jinja2` tags. filter_ref: Reference to the filter itself, i.e. the corresponding :program:`Python` function. force (bool):...
def append_overhead_costs(costs, new_id, overhead_percentage=0.15): """ Adds 15% overhead costs to the list of costs. Usage:: from rapid_prototyping.context.utils import append_overhead_costs costs = [ .... ] costs = append_overhead_costs(costs, MAIN_ID + get_co...
Adds 15% overhead costs to the list of costs. Usage:: from rapid_prototyping.context.utils import append_overhead_costs costs = [ .... ] costs = append_overhead_costs(costs, MAIN_ID + get_counter(counter)[0]) :param costs: Your final list of costs. :param new_i...
Below is the the instruction that describes the task: ### Input: Adds 15% overhead costs to the list of costs. Usage:: from rapid_prototyping.context.utils import append_overhead_costs costs = [ .... ] costs = append_overhead_costs(costs, MAIN_ID + get_counter(count...
def tournament_name2number(self, name): """Translate tournament name to tournament number. Args: name (str): tournament name to translate Returns: number (int): number of the tournament or `None` if unknown. Examples: >>> NumerAPI().tournament_name2...
Translate tournament name to tournament number. Args: name (str): tournament name to translate Returns: number (int): number of the tournament or `None` if unknown. Examples: >>> NumerAPI().tournament_name2number('delta') 4 >>> Numer...
Below is the the instruction that describes the task: ### Input: Translate tournament name to tournament number. Args: name (str): tournament name to translate Returns: number (int): number of the tournament or `None` if unknown. Examples: >>> NumerAPI(...
def _find_package(self, root_package): """Finds package name of file :param root_package: root package :return: package name """ package = self.path.replace(root_package, "") if package.endswith(".py"): package = package[:-3] package = package.repla...
Finds package name of file :param root_package: root package :return: package name
Below is the the instruction that describes the task: ### Input: Finds package name of file :param root_package: root package :return: package name ### Response: def _find_package(self, root_package): """Finds package name of file :param root_package: root package :return:...
def stem(self): """ Stem tokens with Porter Stemmer. """ def s(tokens): return [PorterStemmer().stem(t) for t in tokens] self.stems = list(map(s, self.tokens))
Stem tokens with Porter Stemmer.
Below is the the instruction that describes the task: ### Input: Stem tokens with Porter Stemmer. ### Response: def stem(self): """ Stem tokens with Porter Stemmer. """ def s(tokens): return [PorterStemmer().stem(t) for t in tokens] self.stems = list(map(s, sel...
def rank(self, dte): '''The rank of a given *dte* in the timeseries''' timestamp = self.pickler.dumps(dte) return self.backend_structure().rank(timestamp)
The rank of a given *dte* in the timeseries
Below is the the instruction that describes the task: ### Input: The rank of a given *dte* in the timeseries ### Response: def rank(self, dte): '''The rank of a given *dte* in the timeseries''' timestamp = self.pickler.dumps(dte) return self.backend_structure().rank(timestamp)
def pre_save_title(instance, **kwargs): ''' Update article.languages ''' if instance.article.languages: languages = instance.article.languages.split(',') else: languages = [] if instance.language not in languages: languages.append(instance.language) instance.article.l...
Update article.languages
Below is the the instruction that describes the task: ### Input: Update article.languages ### Response: def pre_save_title(instance, **kwargs): ''' Update article.languages ''' if instance.article.languages: languages = instance.article.languages.split(',') else: languages = [] ...
def set_window_user_pointer(window, pointer): """ Sets the user pointer of the specified window. You may pass a normal python object into this function and it will be wrapped automatically. The object will be kept in existence until the pointer is set to something else or until the window is destroyed. ...
Sets the user pointer of the specified window. You may pass a normal python object into this function and it will be wrapped automatically. The object will be kept in existence until the pointer is set to something else or until the window is destroyed. Wrapper for: void glfwSetWindowUserPointer(GL...
Below is the the instruction that describes the task: ### Input: Sets the user pointer of the specified window. You may pass a normal python object into this function and it will be wrapped automatically. The object will be kept in existence until the pointer is set to something else or until the window is ...
def has_causal_out_edges(graph: BELGraph, node: BaseEntity) -> bool: """Return true if the node contains any out_edges that are causal.""" return any( data[RELATION] in CAUSAL_RELATIONS for _, _, data in graph.out_edges(node, data=True) )
Return true if the node contains any out_edges that are causal.
Below is the the instruction that describes the task: ### Input: Return true if the node contains any out_edges that are causal. ### Response: def has_causal_out_edges(graph: BELGraph, node: BaseEntity) -> bool: """Return true if the node contains any out_edges that are causal.""" return any( data[...
def create_observations(params: Dict[str, Dict[str, Any]], access_token: str) -> List[Dict[str, Any]]: """Create a single or several (if passed an array) observations). :param params: :param access_token: the access token, as returned by :func:`get_access_token()` :return: iNaturalist's JSON response,...
Create a single or several (if passed an array) observations). :param params: :param access_token: the access token, as returned by :func:`get_access_token()` :return: iNaturalist's JSON response, as a Python object :raise: requests.HTTPError, if the call is not successful. iNaturalist returns an erro...
Below is the the instruction that describes the task: ### Input: Create a single or several (if passed an array) observations). :param params: :param access_token: the access token, as returned by :func:`get_access_token()` :return: iNaturalist's JSON response, as a Python object :raise: requests....
def create_repo(self, repo_name=None, feed=None, envs=[], checksum_type="sha256", query='/repositories/'): """ `repo_name` - Name of repository to create `feed` - Repo URL to feed from `checksum_type` - Used for generating meta-data Create repository in specified environments, a...
`repo_name` - Name of repository to create `feed` - Repo URL to feed from `checksum_type` - Used for generating meta-data Create repository in specified environments, associate the yum_distributor with it and publish the repo
Below is the the instruction that describes the task: ### Input: `repo_name` - Name of repository to create `feed` - Repo URL to feed from `checksum_type` - Used for generating meta-data Create repository in specified environments, associate the yum_distributor with it and publish t...
def start(self, container, **kwargs): """ Identical to :meth:`docker.api.container.ContainerApiMixin.start` with additional logging. """ self.push_log("Starting container '{0}'.".format(container)) super(DockerFabricClient, self).start(container, **kwargs)
Identical to :meth:`docker.api.container.ContainerApiMixin.start` with additional logging.
Below is the the instruction that describes the task: ### Input: Identical to :meth:`docker.api.container.ContainerApiMixin.start` with additional logging. ### Response: def start(self, container, **kwargs): """ Identical to :meth:`docker.api.container.ContainerApiMixin.start` with additional loggi...
def new(): """Create a new community.""" form = CommunityForm(formdata=request.values) ctx = mycommunities_ctx() ctx.update({ 'form': form, 'is_new': True, 'community': None, }) if form.validate_on_submit(): data = copy.deepcopy(form.data) community_id ...
Create a new community.
Below is the the instruction that describes the task: ### Input: Create a new community. ### Response: def new(): """Create a new community.""" form = CommunityForm(formdata=request.values) ctx = mycommunities_ctx() ctx.update({ 'form': form, 'is_new': True, 'community': No...
def write(self): """Write the configuration to :attr:`path`""" with open(self.path, 'w') as f: self.config.write(f)
Write the configuration to :attr:`path`
Below is the the instruction that describes the task: ### Input: Write the configuration to :attr:`path` ### Response: def write(self): """Write the configuration to :attr:`path`""" with open(self.path, 'w') as f: self.config.write(f)
def _RegisterProcess(self, process): """Registers a process with the engine. Args: process (MultiProcessBaseProcess): process. Raises: KeyError: if the process is already registered with the engine. ValueError: if the process is missing. """ if process is None: raise ValueE...
Registers a process with the engine. Args: process (MultiProcessBaseProcess): process. Raises: KeyError: if the process is already registered with the engine. ValueError: if the process is missing.
Below is the the instruction that describes the task: ### Input: Registers a process with the engine. Args: process (MultiProcessBaseProcess): process. Raises: KeyError: if the process is already registered with the engine. ValueError: if the process is missing. ### Response: def _Regis...
def legacy_events_view(request): """ View to see legacy events. """ events = TeacherEvent.objects.all() event_count = events.count() paginator = Paginator(events, 100) page = request.GET.get('page') try: events = paginator.page(page) except PageNotAnInteger: events =...
View to see legacy events.
Below is the the instruction that describes the task: ### Input: View to see legacy events. ### Response: def legacy_events_view(request): """ View to see legacy events. """ events = TeacherEvent.objects.all() event_count = events.count() paginator = Paginator(events, 100) page = reque...
def _uses_db(func, self, *args, **kwargs): """ Use as a decorator for operations on the database, to ensure connection setup and teardown. Can only be used on methods on objects with a `self.session` attribute. """ if not self.session: _logger.debug('Creating new db session') self._init_...
Use as a decorator for operations on the database, to ensure connection setup and teardown. Can only be used on methods on objects with a `self.session` attribute.
Below is the the instruction that describes the task: ### Input: Use as a decorator for operations on the database, to ensure connection setup and teardown. Can only be used on methods on objects with a `self.session` attribute. ### Response: def _uses_db(func, self, *args, **kwargs): """ Use as a decorato...
def orient_undirected_graph(self, data, umg, alg='HC'): """Orient the undirected graph using GNN and apply CGNN to improve the graph. Args: data (pandas.DataFrame): Observational data on which causal discovery has to be performed. umg (nx.Graph): Graph that provid...
Orient the undirected graph using GNN and apply CGNN to improve the graph. Args: data (pandas.DataFrame): Observational data on which causal discovery has to be performed. umg (nx.Graph): Graph that provides the skeleton, on which the GNN then the CGNN algo...
Below is the the instruction that describes the task: ### Input: Orient the undirected graph using GNN and apply CGNN to improve the graph. Args: data (pandas.DataFrame): Observational data on which causal discovery has to be performed. umg (nx.Graph): Graph that prov...
def gradient(self, P, Q, Y, i): """Computes the gradient of KL divergence with respect to the i'th example of Y""" return 4 * sum([ (P[i, j] - Q[i, j]) * (Y[i] - Y[j]) * (1 + np.linalg.norm(Y[i] - Y[j]) ** 2) ** -1 \ for j in range(Y.shape[0]) ])
Computes the gradient of KL divergence with respect to the i'th example of Y
Below is the the instruction that describes the task: ### Input: Computes the gradient of KL divergence with respect to the i'th example of Y ### Response: def gradient(self, P, Q, Y, i): """Computes the gradient of KL divergence with respect to the i'th example of Y""" return 4 * sum([ ...
def read_file(input_filename): '''Like read() except uses a file rather than an IO stream, for convenience''' with open(input_filename) as f: g = GreenGenesTaxonomy.read(f) return g
Like read() except uses a file rather than an IO stream, for convenience
Below is the the instruction that describes the task: ### Input: Like read() except uses a file rather than an IO stream, for convenience ### Response: def read_file(input_filename): '''Like read() except uses a file rather than an IO stream, for convenience''' with open(input_filename) as f: ...
def _color_attr(self, ground, attr): """ Given a color attribute, set the current cursor appropriately. """ attr = colors[ground][attr] attrs = self.cursor_attributes if ground == "foreground": self.cursor_attributes = (attrs[0], attr, attrs[2]) elif ...
Given a color attribute, set the current cursor appropriately.
Below is the the instruction that describes the task: ### Input: Given a color attribute, set the current cursor appropriately. ### Response: def _color_attr(self, ground, attr): """ Given a color attribute, set the current cursor appropriately. """ attr = colors[ground][attr] ...
def query(self, msg_type, query, *parameters, **options): '''Performs a query against a q service. In typical use case, `query` is the name of the function to call and `parameters` are its parameters. When `parameters` list is empty, the query can be an arbitrary q expression ...
Performs a query against a q service. In typical use case, `query` is the name of the function to call and `parameters` are its parameters. When `parameters` list is empty, the query can be an arbitrary q expression (e.g. ``0 +/ til 100``). Calls a anonymous function ...
Below is the the instruction that describes the task: ### Input: Performs a query against a q service. In typical use case, `query` is the name of the function to call and `parameters` are its parameters. When `parameters` list is empty, the query can be an arbitrary q expression ...
def _add_getter(self): """ Add a read-only ``{prop_name}`` property to the element class for this child element. """ property_ = property(self._getter, None, None) # assign unconditionally to overwrite element name definition setattr(self._element_cls, self._prop_...
Add a read-only ``{prop_name}`` property to the element class for this child element.
Below is the the instruction that describes the task: ### Input: Add a read-only ``{prop_name}`` property to the element class for this child element. ### Response: def _add_getter(self): """ Add a read-only ``{prop_name}`` property to the element class for this child element. ...
def decorate(self, function_or_name): '''Decorate a function to time the execution The method can be called with or without a name. If no name is given the function defaults to the name of the function. :keyword function_or_name: The name to post to or the function to wrap >>>...
Decorate a function to time the execution The method can be called with or without a name. If no name is given the function defaults to the name of the function. :keyword function_or_name: The name to post to or the function to wrap >>> from statsd import Timer >>> timer = Tim...
Below is the the instruction that describes the task: ### Input: Decorate a function to time the execution The method can be called with or without a name. If no name is given the function defaults to the name of the function. :keyword function_or_name: The name to post to or the function ...
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment o...
Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to existing component or to N+1 component. In the latter case ...
Below is the the instruction that describes the task: ### Input: Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to ex...
def update_user(self, user_id, **kwargs): """Update user properties of specified user. :param str user_id: The ID of the user to update (Required) :param str username: The unique username of the user :param str email: The unique email of the user :param str full_name: The full n...
Update user properties of specified user. :param str user_id: The ID of the user to update (Required) :param str username: The unique username of the user :param str email: The unique email of the user :param str full_name: The full name of the user :param str password: The pass...
Below is the the instruction that describes the task: ### Input: Update user properties of specified user. :param str user_id: The ID of the user to update (Required) :param str username: The unique username of the user :param str email: The unique email of the user :param str full_...
def write_file_chunk( file_path: str, packed_chunk: str, append: bool = True, offset: int = -1 ): """ Write or append the specified chunk data to the given file path, unpacking the chunk before writing. If the file does not yet exist, it will be created. Set the append ar...
Write or append the specified chunk data to the given file path, unpacking the chunk before writing. If the file does not yet exist, it will be created. Set the append argument to False if you do not want the chunk to be appended to an existing file. :param file_path: The file where the chunk w...
Below is the the instruction that describes the task: ### Input: Write or append the specified chunk data to the given file path, unpacking the chunk before writing. If the file does not yet exist, it will be created. Set the append argument to False if you do not want the chunk to be appended to an exi...
def update_region_to_controller(self, region): """ Update the controller string with dynamic region info. Controller string should end up as `<name[-env]>.<region>.cloudgenix.com` **Parameters:** - **region:** region string. **Returns:** No return value, mutates the ...
Update the controller string with dynamic region info. Controller string should end up as `<name[-env]>.<region>.cloudgenix.com` **Parameters:** - **region:** region string. **Returns:** No return value, mutates the controller in the class namespace
Below is the the instruction that describes the task: ### Input: Update the controller string with dynamic region info. Controller string should end up as `<name[-env]>.<region>.cloudgenix.com` **Parameters:** - **region:** region string. **Returns:** No return value, mutates th...
def clone(srcpath, destpath, vcs=None): """Clone an existing repository. :param str srcpath: Path to an existing repository :param str destpath: Desired path of new repository :param str vcs: Either ``git``, ``hg``, or ``svn`` :returns VCSRepo: The newly cloned repository If ``vcs`` is not giv...
Clone an existing repository. :param str srcpath: Path to an existing repository :param str destpath: Desired path of new repository :param str vcs: Either ``git``, ``hg``, or ``svn`` :returns VCSRepo: The newly cloned repository If ``vcs`` is not given, then the repository type is discovered from...
Below is the the instruction that describes the task: ### Input: Clone an existing repository. :param str srcpath: Path to an existing repository :param str destpath: Desired path of new repository :param str vcs: Either ``git``, ``hg``, or ``svn`` :returns VCSRepo: The newly cloned repository ...
def select(self): """ Select the current item and run it """ self.selected_option = self.current_option self.selected_item.set_up() self.selected_item.action() self.selected_item.clean_up() self.returned_value = self.selected_item.get_return() self...
Select the current item and run it
Below is the the instruction that describes the task: ### Input: Select the current item and run it ### Response: def select(self): """ Select the current item and run it """ self.selected_option = self.current_option self.selected_item.set_up() self.selected_item.ac...
def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without...
.. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_t...
Below is the the instruction that describes the task: ### Input: .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param...
def smart_truncate(string, max_length=0, word_boundary=False, separator=' ', save_order=False): """ Truncate a string. :param string (str): string for modification :param max_length (int): output string length :param word_boundary (bool): :param save_order (bool): if True then word order of outp...
Truncate a string. :param string (str): string for modification :param max_length (int): output string length :param word_boundary (bool): :param save_order (bool): if True then word order of output string is like input string :param separator (str): separator between words :return:
Below is the the instruction that describes the task: ### Input: Truncate a string. :param string (str): string for modification :param max_length (int): output string length :param word_boundary (bool): :param save_order (bool): if True then word order of output string is like input string :par...
def grant_winsta_and_desktop(th): ''' Grant the token's user access to the current process's window station and desktop. ''' current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0] # Add permissions for the sid to the current windows station and thread id. # This prev...
Grant the token's user access to the current process's window station and desktop.
Below is the the instruction that describes the task: ### Input: Grant the token's user access to the current process's window station and desktop. ### Response: def grant_winsta_and_desktop(th): ''' Grant the token's user access to the current process's window station and desktop. ''' curr...
def _load(formula): ''' Generates a list of salt://<formula>/defaults.(json|yaml) files and fetches them from the Salt master. Returns first defaults file as python dict. ''' # Compute possibilities _mk_client() paths = [] for ext in ('yaml', 'json'): source_url = salt.util...
Generates a list of salt://<formula>/defaults.(json|yaml) files and fetches them from the Salt master. Returns first defaults file as python dict.
Below is the the instruction that describes the task: ### Input: Generates a list of salt://<formula>/defaults.(json|yaml) files and fetches them from the Salt master. Returns first defaults file as python dict. ### Response: def _load(formula): ''' Generates a list of salt://<formula>/defaults.(j...
def grab_filt(self, filt, analyte=None): """ Flexible access to specific filter using any key format. Parameters ---------- f : str, dict or bool either logical filter expression, dict of expressions, or a boolean analyte : str name of...
Flexible access to specific filter using any key format. Parameters ---------- f : str, dict or bool either logical filter expression, dict of expressions, or a boolean analyte : str name of analyte the filter is for. Returns ------- ...
Below is the the instruction that describes the task: ### Input: Flexible access to specific filter using any key format. Parameters ---------- f : str, dict or bool either logical filter expression, dict of expressions, or a boolean analyte : str ...
def parse_deltat_data(fileobj): """Parse the United States Naval Observatory ``deltat.data`` file. Each line file gives the date and the value of Delta T:: 2016 2 1 68.1577 This function returns a 2xN array of raw Julian dates and matching Delta T values. """ array = np.loadtxt(fileob...
Parse the United States Naval Observatory ``deltat.data`` file. Each line file gives the date and the value of Delta T:: 2016 2 1 68.1577 This function returns a 2xN array of raw Julian dates and matching Delta T values.
Below is the the instruction that describes the task: ### Input: Parse the United States Naval Observatory ``deltat.data`` file. Each line file gives the date and the value of Delta T:: 2016 2 1 68.1577 This function returns a 2xN array of raw Julian dates and matching Delta T values. ### Resp...
def lu_solve_ATAI(A, rho, b, lu, piv, check_finite=True): r""" Solve the linear system :math:`(A^T A + \rho I)\mathbf{x} = \mathbf{b}` or :math:`(A^T A + \rho I)X = B` using :func:`scipy.linalg.lu_solve`. Parameters ---------- A : array_like Matrix :math:`A` rho : float Scalar :...
r""" Solve the linear system :math:`(A^T A + \rho I)\mathbf{x} = \mathbf{b}` or :math:`(A^T A + \rho I)X = B` using :func:`scipy.linalg.lu_solve`. Parameters ---------- A : array_like Matrix :math:`A` rho : float Scalar :math:`\rho` b : array_like Vector :math:`\mathbf{b}`...
Below is the the instruction that describes the task: ### Input: r""" Solve the linear system :math:`(A^T A + \rho I)\mathbf{x} = \mathbf{b}` or :math:`(A^T A + \rho I)X = B` using :func:`scipy.linalg.lu_solve`. Parameters ---------- A : array_like Matrix :math:`A` rho : float S...
def remove(self, item, count=0): """ Removes @item from the list for @count number of occurences """ self._client.lrem(self.key_prefix, count, self._dumps(item))
Removes @item from the list for @count number of occurences
Below is the the instruction that describes the task: ### Input: Removes @item from the list for @count number of occurences ### Response: def remove(self, item, count=0): """ Removes @item from the list for @count number of occurences """ self._client.lrem(self.key_prefix, count, self._dumps(item)...
def expandf(m, format): # noqa A002 """Expand the string using the format replace pattern or function.""" _assert_expandable(format, True) return _apply_replace_backrefs(m, format, flags=FORMAT)
Expand the string using the format replace pattern or function.
Below is the the instruction that describes the task: ### Input: Expand the string using the format replace pattern or function. ### Response: def expandf(m, format): # noqa A002 """Expand the string using the format replace pattern or function.""" _assert_expandable(format, True) return _apply_repla...
def smart_insert(cls, engine_or_session, data, minimal_size=5, op_counter=0): """ An optimized Insert strategy. :return: number of insertion operation been executed. Usually it is greatly smaller than ``len(data)``. **中文文档** 在Insert中, 如果已经预知不会出现IntegrityError, 那么使用...
An optimized Insert strategy. :return: number of insertion operation been executed. Usually it is greatly smaller than ``len(data)``. **中文文档** 在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要 远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略: 1. 尝试Bulk Insert, Bulk Insert由于...
Below is the the instruction that describes the task: ### Input: An optimized Insert strategy. :return: number of insertion operation been executed. Usually it is greatly smaller than ``len(data)``. **中文文档** 在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要 远远快于逐...
def get_documents(self, doc_format='dict'): """ Get the documents returned from Storege in this response. Keyword args: doc_format -- Specifies the doc_format for the returned documents. Can be 'dict', 'etree' or 'string'. Default is 'dict'. Returns:...
Get the documents returned from Storege in this response. Keyword args: doc_format -- Specifies the doc_format for the returned documents. Can be 'dict', 'etree' or 'string'. Default is 'dict'. Returns: A dict where keys are document ids and ...
Below is the the instruction that describes the task: ### Input: Get the documents returned from Storege in this response. Keyword args: doc_format -- Specifies the doc_format for the returned documents. Can be 'dict', 'etree' or 'string'. Default is 'dict'. ...
def dist_string(self, val_meters): '''return a distance as a string''' if self.settings.dist_unit == 'nm': return "%.1fnm" % (val_meters * 0.000539957) if self.settings.dist_unit == 'miles': return "%.1fmiles" % (val_meters * 0.000621371) return "%um" % val_meters
return a distance as a string
Below is the the instruction that describes the task: ### Input: return a distance as a string ### Response: def dist_string(self, val_meters): '''return a distance as a string''' if self.settings.dist_unit == 'nm': return "%.1fnm" % (val_meters * 0.000539957) if self.settings.d...
def branches(self): # type: () -> List[str] """ List of all branches this commit is a part of. """ if self._branches is None: cmd = 'git branch --contains {}'.format(self.sha1) out = shell.run( cmd, capture=True, never_prete...
List of all branches this commit is a part of.
Below is the the instruction that describes the task: ### Input: List of all branches this commit is a part of. ### Response: def branches(self): # type: () -> List[str] """ List of all branches this commit is a part of. """ if self._branches is None: cmd = 'git branch --contain...
def _vax_to_ieee_single_float(data): """Converts a float in Vax format to IEEE format. data should be a single string of chars that have been read in from a binary file. These will be processed 4 at a time into float values. Thus the total number of byte/chars in the string should be divisible by 4...
Converts a float in Vax format to IEEE format. data should be a single string of chars that have been read in from a binary file. These will be processed 4 at a time into float values. Thus the total number of byte/chars in the string should be divisible by 4. Based on VAX data organization in a b...
Below is the the instruction that describes the task: ### Input: Converts a float in Vax format to IEEE format. data should be a single string of chars that have been read in from a binary file. These will be processed 4 at a time into float values. Thus the total number of byte/chars in the string sho...
def process_full_position(data, header, var_only=False): """ Return genetic data when all alleles called on same line. Returns an array containing one item, a tuple of five items: (string) chromosome (string) start position (1-based) (array of strings) matching dbSNP entries ...
Return genetic data when all alleles called on same line. Returns an array containing one item, a tuple of five items: (string) chromosome (string) start position (1-based) (array of strings) matching dbSNP entries (string) reference allele sequence (array of strings) the ge...
Below is the the instruction that describes the task: ### Input: Return genetic data when all alleles called on same line. Returns an array containing one item, a tuple of five items: (string) chromosome (string) start position (1-based) (array of strings) matching dbSNP entries ...
def get_rotation_and_scale(header, skew_threshold=0.001): """Calculate rotation and CDELT.""" ((xrot, yrot), (cdelt1, cdelt2)) = get_xy_rotation_and_scale(header) if math.fabs(xrot) - math.fabs(yrot) > skew_threshold: raise ValueError("Skew detected: xrot=%.4f yrot=%.4f" % ( xrot, ...
Calculate rotation and CDELT.
Below is the the instruction that describes the task: ### Input: Calculate rotation and CDELT. ### Response: def get_rotation_and_scale(header, skew_threshold=0.001): """Calculate rotation and CDELT.""" ((xrot, yrot), (cdelt1, cdelt2)) = get_xy_rotation_and_scale(header) if math.fabs(xrot) - math...
def read_network_file(self, path_to_network_file): """ Parameters ----------- path_to_network_file : str Expects a network file with columns "pw0" and "pw1." A "features" column that specifies the features where the (pw0, pw1) edge is present will assign a w...
Parameters ----------- path_to_network_file : str Expects a network file with columns "pw0" and "pw1." A "features" column that specifies the features where the (pw0, pw1) edge is present will assign a weight to the edge, though it is not required (edge will have ...
Below is the the instruction that describes the task: ### Input: Parameters ----------- path_to_network_file : str Expects a network file with columns "pw0" and "pw1." A "features" column that specifies the features where the (pw0, pw1) edge is present will assign a wei...
def sample_from_largest_budget(self, info_dict): """We opted for a single multidimensional KDE compared to the hierarchy of one-dimensional KDEs used in TPE. The dimensional is seperated by budget. This function sample a configuration from largest budget. Firstly we sample "num_samples" ...
We opted for a single multidimensional KDE compared to the hierarchy of one-dimensional KDEs used in TPE. The dimensional is seperated by budget. This function sample a configuration from largest budget. Firstly we sample "num_samples" configurations, then prefer one with the largest l(x...
Below is the the instruction that describes the task: ### Input: We opted for a single multidimensional KDE compared to the hierarchy of one-dimensional KDEs used in TPE. The dimensional is seperated by budget. This function sample a configuration from largest budget. Firstly we sample "num_...