code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def same_log10_order_of_magnitude(x, delta=0.1): """ Return true if range is approximately in same order of magnitude For example these sequences are in the same order of magnitude: - [1, 8, 5] # [1, 10) - [35, 20, 80] # [10 100) - [232, 730] # [100, 1000) Parameters ...
Return true if range is approximately in same order of magnitude For example these sequences are in the same order of magnitude: - [1, 8, 5] # [1, 10) - [35, 20, 80] # [10 100) - [232, 730] # [100, 1000) Parameters ---------- x : array-like Values in base 10. ...
Below is the the instruction that describes the task: ### Input: Return true if range is approximately in same order of magnitude For example these sequences are in the same order of magnitude: - [1, 8, 5] # [1, 10) - [35, 20, 80] # [10 100) - [232, 730] # [100, 1000) Para...
def surrogateescape_handler(exc): """ Pure Python implementation of the PEP 383: the "surrogateescape" error handler of Python 3. Undecodable bytes will be replaced by a Unicode character U+DCxx on decoding, and these are translated into the original bytes on encoding. """ mystring = exc.obj...
Pure Python implementation of the PEP 383: the "surrogateescape" error handler of Python 3. Undecodable bytes will be replaced by a Unicode character U+DCxx on decoding, and these are translated into the original bytes on encoding.
Below is the the instruction that describes the task: ### Input: Pure Python implementation of the PEP 383: the "surrogateescape" error handler of Python 3. Undecodable bytes will be replaced by a Unicode character U+DCxx on decoding, and these are translated into the original bytes on encoding. ### Res...
def index(self, key, default=UNSET): """Find the first key-value pair with key *key* and return its position. If the key is not found, return *default*. If default was not provided, raise a ``KeyError`` """ self._find_lt(key) node = self._path[0][2] if node is se...
Find the first key-value pair with key *key* and return its position. If the key is not found, return *default*. If default was not provided, raise a ``KeyError``
Below is the the instruction that describes the task: ### Input: Find the first key-value pair with key *key* and return its position. If the key is not found, return *default*. If default was not provided, raise a ``KeyError`` ### Response: def index(self, key, default=UNSET): """Find the...
def eval(self, code, mode="single"): """Evaluate code in the context of the frame.""" if isinstance(code, string_types): if PY2 and isinstance(code, text_type): # noqa code = UTF8_COOKIE + code.encode("utf-8") code = compile(code, "<interactive>", mode) r...
Evaluate code in the context of the frame.
Below is the the instruction that describes the task: ### Input: Evaluate code in the context of the frame. ### Response: def eval(self, code, mode="single"): """Evaluate code in the context of the frame.""" if isinstance(code, string_types): if PY2 and isinstance(code, text_type): # n...
def to_set_field(cls): """ Returns a callable instance that will convert a value to a Sequence. :param cls: Valid class type of the items in the Sequence. :return: instance of the SequenceConverter. """ class SetConverter(object): def __init__(self, cls): self._cls = cls ...
Returns a callable instance that will convert a value to a Sequence. :param cls: Valid class type of the items in the Sequence. :return: instance of the SequenceConverter.
Below is the the instruction that describes the task: ### Input: Returns a callable instance that will convert a value to a Sequence. :param cls: Valid class type of the items in the Sequence. :return: instance of the SequenceConverter. ### Response: def to_set_field(cls): """ Returns a callable i...
def _close_cursor_now(self, cursor_id, address=None): """Send a kill cursors message with the given id. What closing the cursor actually means depends on this client's cursor manager. If there is none, the cursor is closed synchronously on the current thread. """ if not ...
Send a kill cursors message with the given id. What closing the cursor actually means depends on this client's cursor manager. If there is none, the cursor is closed synchronously on the current thread.
Below is the the instruction that describes the task: ### Input: Send a kill cursors message with the given id. What closing the cursor actually means depends on this client's cursor manager. If there is none, the cursor is closed synchronously on the current thread. ### Response: def _clo...
def request_verification(self, user, identity): """ Sends the user a verification email with a link to verify ownership of the email address. :param user: User id or object :param identity: Identity id or object :return: requests Response object """ return UserId...
Sends the user a verification email with a link to verify ownership of the email address. :param user: User id or object :param identity: Identity id or object :return: requests Response object
Below is the the instruction that describes the task: ### Input: Sends the user a verification email with a link to verify ownership of the email address. :param user: User id or object :param identity: Identity id or object :return: requests Response object ### Response: def request_verif...
def free_params(self, value): """Set the free parameters. Note that this bypasses enforce_bounds. """ value = scipy.asarray(value, dtype=float) self.K_up_to_date = False self.k.free_params = value[:self.k.num_free_params] self.noise_k.free_params = value[self.k.num_free_p...
Set the free parameters. Note that this bypasses enforce_bounds.
Below is the the instruction that describes the task: ### Input: Set the free parameters. Note that this bypasses enforce_bounds. ### Response: def free_params(self, value): """Set the free parameters. Note that this bypasses enforce_bounds. """ value = scipy.asarray(value, dtype=float) ...
def _local_pauli_eig_meas(op, idx): """ Generate gate sequence to measure in the eigenbasis of a Pauli operator, assuming we are only able to measure in the Z eigenbasis. (Note: The unitary operations of this Program are essentially the Hermitian conjugates of those in :py:func:`_one_q_pauli_prep`) ...
Generate gate sequence to measure in the eigenbasis of a Pauli operator, assuming we are only able to measure in the Z eigenbasis. (Note: The unitary operations of this Program are essentially the Hermitian conjugates of those in :py:func:`_one_q_pauli_prep`)
Below is the the instruction that describes the task: ### Input: Generate gate sequence to measure in the eigenbasis of a Pauli operator, assuming we are only able to measure in the Z eigenbasis. (Note: The unitary operations of this Program are essentially the Hermitian conjugates of those in :py:func:`_on...
def emit(self, record): """Write record as journal event. MESSAGE is taken from the message provided by the user, and PRIORITY, LOGGER, THREAD_NAME, CODE_{FILE,LINE,FUNC} fields are appended automatically. In addition, record.MESSAGE_ID will be used if present. "...
Write record as journal event. MESSAGE is taken from the message provided by the user, and PRIORITY, LOGGER, THREAD_NAME, CODE_{FILE,LINE,FUNC} fields are appended automatically. In addition, record.MESSAGE_ID will be used if present.
Below is the the instruction that describes the task: ### Input: Write record as journal event. MESSAGE is taken from the message provided by the user, and PRIORITY, LOGGER, THREAD_NAME, CODE_{FILE,LINE,FUNC} fields are appended automatically. In addition, record.MESSAGE_ID will be ...
def periodic_distance(a, b, periodic): ''' Periodic distance between two arrays. Periodic is a 3 dimensional array containing the 3 box sizes. ''' a = np.array(a) b = np.array(b) periodic = np.array(periodic) delta = np.abs(a - b) delta = np.where(delta > 0.5 * periodic, periodic -...
Periodic distance between two arrays. Periodic is a 3 dimensional array containing the 3 box sizes.
Below is the the instruction that describes the task: ### Input: Periodic distance between two arrays. Periodic is a 3 dimensional array containing the 3 box sizes. ### Response: def periodic_distance(a, b, periodic): ''' Periodic distance between two arrays. Periodic is a 3 dimensional array conta...
def unpack_from_dict(fmt, names, data, offset=0): """Same as :func:`~bitstruct.unpack_from_dict()`, but returns a dictionary. See :func:`~bitstruct.pack_dict()` for details on `names`. """ return CompiledFormatDict(fmt, names).unpack_from(data, offset)
Same as :func:`~bitstruct.unpack_from_dict()`, but returns a dictionary. See :func:`~bitstruct.pack_dict()` for details on `names`.
Below is the the instruction that describes the task: ### Input: Same as :func:`~bitstruct.unpack_from_dict()`, but returns a dictionary. See :func:`~bitstruct.pack_dict()` for details on `names`. ### Response: def unpack_from_dict(fmt, names, data, offset=0): """Same as :func:`~bitstruct.unpack_from_...
def is_valid_country_abbrev(abbrev, case_sensitive=False): """ Given a country code abbreviation, check to see if it matches the country table. abbrev: (str) Country code to evaluate. case_sensitive: (bool) When True, enforce case sensitivity. Returns True if valid, False if not. """ i...
Given a country code abbreviation, check to see if it matches the country table. abbrev: (str) Country code to evaluate. case_sensitive: (bool) When True, enforce case sensitivity. Returns True if valid, False if not.
Below is the the instruction that describes the task: ### Input: Given a country code abbreviation, check to see if it matches the country table. abbrev: (str) Country code to evaluate. case_sensitive: (bool) When True, enforce case sensitivity. Returns True if valid, False if not. ### Response: ...
def mline_point_(self, col, x=None, y=None, rsum=None, rmean=None): """ Splits a column into multiple series based on the column's unique values. Then visualize theses series in a chart. Parameters: column to split, x axis column, y axis column Optional: rsum="1D" to resample and sum data an rmean="1D" to m...
Splits a column into multiple series based on the column's unique values. Then visualize theses series in a chart. Parameters: column to split, x axis column, y axis column Optional: rsum="1D" to resample and sum data an rmean="1D" to mean the data
Below is the the instruction that describes the task: ### Input: Splits a column into multiple series based on the column's unique values. Then visualize theses series in a chart. Parameters: column to split, x axis column, y axis column Optional: rsum="1D" to resample and sum data an rmean="1D" to mean the...
def processStream(self): """Process a brotli stream. """ print('addr hex{:{}s}binary context explanation'.format( '', self.width-10)) print('Stream header'.center(60, '-')) self.windowSize = self.verboseRead(WindowSizeAlphabet()) print('Metablock header'.cent...
Process a brotli stream.
Below is the the instruction that describes the task: ### Input: Process a brotli stream. ### Response: def processStream(self): """Process a brotli stream. """ print('addr hex{:{}s}binary context explanation'.format( '', self.width-10)) print('Stream header'.center(60,...
def build_recursive_delocalize_command(source, outputs, file_provider): """Return a multi-line string with a shell script to copy recursively. Arguments: source: Folder with the data. For example /mnt/data outputs: a list of OutputFileParam. file_provider: file provider string used to filte...
Return a multi-line string with a shell script to copy recursively. Arguments: source: Folder with the data. For example /mnt/data outputs: a list of OutputFileParam. file_provider: file provider string used to filter the output params; the returned command will only apply ou...
Below is the the instruction that describes the task: ### Input: Return a multi-line string with a shell script to copy recursively. Arguments: source: Folder with the data. For example /mnt/data outputs: a list of OutputFileParam. file_provider: file provider string used to filter the ou...
def get_end_balance(self, after: date) -> Decimal: """ Calculates account balance """ # create a new date without hours #date_corrected = datetimeutils.end_of_day(after) datum = Datum() datum.from_date(after) datum.end_of_day() #log(DEBUG, "getting balance on %s",...
Calculates account balance
Below is the the instruction that describes the task: ### Input: Calculates account balance ### Response: def get_end_balance(self, after: date) -> Decimal: """ Calculates account balance """ # create a new date without hours #date_corrected = datetimeutils.end_of_day(after) datum =...
def jenks_breaks(values, nb_class): """ Compute jenks natural breaks on a sequence of `values`, given `nb_class`, the number of desired class. Parameters ---------- values : array-like The Iterable sequence of numbers (integer/float) to be used. nb_class : int The desired nu...
Compute jenks natural breaks on a sequence of `values`, given `nb_class`, the number of desired class. Parameters ---------- values : array-like The Iterable sequence of numbers (integer/float) to be used. nb_class : int The desired number of class (as some other functions requests ...
Below is the the instruction that describes the task: ### Input: Compute jenks natural breaks on a sequence of `values`, given `nb_class`, the number of desired class. Parameters ---------- values : array-like The Iterable sequence of numbers (integer/float) to be used. nb_class : int ...
def fields(self): """Filter fields based on request query parameters.""" fields = super().fields return apply_subfield_projection(self, copy.copy(fields))
Filter fields based on request query parameters.
Below is the the instruction that describes the task: ### Input: Filter fields based on request query parameters. ### Response: def fields(self): """Filter fields based on request query parameters.""" fields = super().fields return apply_subfield_projection(self, copy.copy(fields))
def _get_apphook_field_names(model): """ Return all foreign key field names for a AppHookConfig based model """ from .models import AppHookConfig # avoid circular dependencies fields = [] for field in model._meta.fields: if isinstance(field, ForeignKey) and issubclass(field.remote_field...
Return all foreign key field names for a AppHookConfig based model
Below is the the instruction that describes the task: ### Input: Return all foreign key field names for a AppHookConfig based model ### Response: def _get_apphook_field_names(model): """ Return all foreign key field names for a AppHookConfig based model """ from .models import AppHookConfig # avoi...
def build_includes(include_packages, freezer=None, optional=None): """ Iterate the list of packages to build a complete list of those packages as well as all subpackages. :param include_packages: list of package names :type: include_pacakges: list of basestr :param freezer: The freezer to use (See ...
Iterate the list of packages to build a complete list of those packages as well as all subpackages. :param include_packages: list of package names :type: include_pacakges: list of basestr :param freezer: The freezer to use (See FREEZER constants) :param optional: Optional pacakge names to include (will...
Below is the the instruction that describes the task: ### Input: Iterate the list of packages to build a complete list of those packages as well as all subpackages. :param include_packages: list of package names :type: include_pacakges: list of basestr :param freezer: The freezer to use (See FREEZER co...
def addchild(self, startip, endip, name, description): """ Method takes inpur of str startip, str endip, name, and description and adds a child scope. The startip and endip MUST be in the IP address range of the parent scope. :param startip: str of ipv4 address of the first address in th...
Method takes inpur of str startip, str endip, name, and description and adds a child scope. The startip and endip MUST be in the IP address range of the parent scope. :param startip: str of ipv4 address of the first address in the child scope :param endip: str of ipv4 address of the last address...
Below is the the instruction that describes the task: ### Input: Method takes inpur of str startip, str endip, name, and description and adds a child scope. The startip and endip MUST be in the IP address range of the parent scope. :param startip: str of ipv4 address of the first address in the chil...
def add_external_reference(self,term_id, external_ref): """ Adds an external reference for the given term @type term_id: string @param term_id: the term identifier @type external_ref: L{CexternalReference} @param external_ref: the external reference object """ ...
Adds an external reference for the given term @type term_id: string @param term_id: the term identifier @type external_ref: L{CexternalReference} @param external_ref: the external reference object
Below is the the instruction that describes the task: ### Input: Adds an external reference for the given term @type term_id: string @param term_id: the term identifier @type external_ref: L{CexternalReference} @param external_ref: the external reference object ### Response: def add...
def ndarray_to_imagedatadict(nparr): """ Convert the numpy array nparr into a suitable ImageList entry dictionary. Returns a dictionary with the appropriate Data, DataType, PixelDepth to be inserted into a dm3 tag dictionary and written to a file. """ ret = {} dm_type = None for k, v in ...
Convert the numpy array nparr into a suitable ImageList entry dictionary. Returns a dictionary with the appropriate Data, DataType, PixelDepth to be inserted into a dm3 tag dictionary and written to a file.
Below is the the instruction that describes the task: ### Input: Convert the numpy array nparr into a suitable ImageList entry dictionary. Returns a dictionary with the appropriate Data, DataType, PixelDepth to be inserted into a dm3 tag dictionary and written to a file. ### Response: def ndarray_to_imaged...
def get(self, name): """ Return a value from this evaluator. Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times with and without no_grad() context. It is advised in such cases to not use no_grad and stick to .detach() ...
Return a value from this evaluator. Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times with and without no_grad() context. It is advised in such cases to not use no_grad and stick to .detach()
Below is the the instruction that describes the task: ### Input: Return a value from this evaluator. Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times with and without no_grad() context. It is advised in such cases to not use no_grad an...
def fault_barrier(fn): """Method decorator to catch and log errors, then send fail message.""" @functools.wraps(fn) def process(self, tup): try: return fn(self, tup) except Exception as e: if isinstance(e, KeyboardInterrupt): return print(s...
Method decorator to catch and log errors, then send fail message.
Below is the the instruction that describes the task: ### Input: Method decorator to catch and log errors, then send fail message. ### Response: def fault_barrier(fn): """Method decorator to catch and log errors, then send fail message.""" @functools.wraps(fn) def process(self, tup): try: ...
def dst(self, dt): """Calculate delta for daylight saving.""" # Daylight saving starts on the second Sunday of March at 2AM standard dst_start_date = self.first_sunday(dt.year, 3) + timedelta(days=7) \ + timedelta(hours=2) # Daylight...
Calculate delta for daylight saving.
Below is the the instruction that describes the task: ### Input: Calculate delta for daylight saving. ### Response: def dst(self, dt): """Calculate delta for daylight saving.""" # Daylight saving starts on the second Sunday of March at 2AM standard dst_start_date = self.first_sunday(dt.year...
def main(): """pyprf_sim entry point.""" # Get list of input arguments (without first one, which is the path to the # function that is called): --NOTE: This is another way of accessing # input arguments, but since we use 'argparse' it is redundant. # lstArgs = sys.argv[1:] strWelcome = 'pyprf_s...
pyprf_sim entry point.
Below is the the instruction that describes the task: ### Input: pyprf_sim entry point. ### Response: def main(): """pyprf_sim entry point.""" # Get list of input arguments (without first one, which is the path to the # function that is called): --NOTE: This is another way of accessing # input arg...
def from_quad_tree(cls, quad_tree): """Creates a tile from a Microsoft QuadTree""" assert bool(re.match('^[0-3]*$', quad_tree)), 'QuadTree value can only consists of the digits 0, 1, 2 and 3.' zoom = len(str(quad_tree)) offset = int(math.pow(2, zoom)) - 1 google_x, google_y = [re...
Creates a tile from a Microsoft QuadTree
Below is the the instruction that describes the task: ### Input: Creates a tile from a Microsoft QuadTree ### Response: def from_quad_tree(cls, quad_tree): """Creates a tile from a Microsoft QuadTree""" assert bool(re.match('^[0-3]*$', quad_tree)), 'QuadTree value can only consists of the digits 0,...
def _infer_spaces(s): """ Uses dynamic programming to infer the location of spaces in a string without spaces. """ s = s.lower() # Find the best match for the i first characters, assuming cost has # been built for the i-1 first characters. # Returns a pair (match_cost, match_length). ...
Uses dynamic programming to infer the location of spaces in a string without spaces.
Below is the the instruction that describes the task: ### Input: Uses dynamic programming to infer the location of spaces in a string without spaces. ### Response: def _infer_spaces(s): """ Uses dynamic programming to infer the location of spaces in a string without spaces. """ s = s.lower(...
def from_const(cls, value, size, dtype=type(None)): """ Constructs an SArray of size with a const value. Parameters ---------- value : [int | float | str | array.array | list | dict | datetime] The value to fill the SArray size : int The size of the S...
Constructs an SArray of size with a const value. Parameters ---------- value : [int | float | str | array.array | list | dict | datetime] The value to fill the SArray size : int The size of the SArray dtype : type The type of the SArray. If not spec...
Below is the the instruction that describes the task: ### Input: Constructs an SArray of size with a const value. Parameters ---------- value : [int | float | str | array.array | list | dict | datetime] The value to fill the SArray size : int The size of the SArr...
def show_support_save_status_output_show_support_save_status_percentage_of_completion(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_support_save_status = ET.Element("show_support_save_status") config = show_support_save_status output = ET....
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def show_support_save_status_output_show_support_save_status_percentage_of_completion(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_support_save_status...
def to_csv(self, encoding=export.ENCODING, dialect=export.DIALECT, make_filename=export.MAKE_FILENAME): """Dump all worksheets of the spreadsheet to individual CSV files. Args: encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object...
Dump all worksheets of the spreadsheet to individual CSV files. Args: encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument callable returning the filename If ``make_filename`` is a str...
Below is the the instruction that describes the task: ### Input: Dump all worksheets of the spreadsheet to individual CSV files. Args: encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument c...
def sanitize_turbo(html, allowed_tags=TURBO_ALLOWED_TAGS, allowed_attrs=TURBO_ALLOWED_ATTRS): """Sanitizes HTML, removing not allowed tags and attributes. :param str|unicode html: :param list allowed_tags: List of allowed tags. :param dict allowed_attrs: Dictionary with attributes allowed for tags. ...
Sanitizes HTML, removing not allowed tags and attributes. :param str|unicode html: :param list allowed_tags: List of allowed tags. :param dict allowed_attrs: Dictionary with attributes allowed for tags. :rtype: unicode
Below is the the instruction that describes the task: ### Input: Sanitizes HTML, removing not allowed tags and attributes. :param str|unicode html: :param list allowed_tags: List of allowed tags. :param dict allowed_attrs: Dictionary with attributes allowed for tags. :rtype: unicode ### Response:...
def patch_runtime_class(self, name, body, **kwargs): """ partially update the specified RuntimeClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_runtime_class(name, body, async_re...
partially update the specified RuntimeClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_runtime_class(name, body, async_req=True) >>> result = thread.get() :param async_req bool ...
Below is the the instruction that describes the task: ### Input: partially update the specified RuntimeClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_runtime_class(name, body, async_req=Tr...
def star_stats_table(self): """ Take the parsed stats from the STAR report and add them to the basic stats table at the top of the report """ headers = OrderedDict() headers['uniquely_mapped_percent'] = { 'title': '% Aligned', 'description': '% Uniquely mapped re...
Take the parsed stats from the STAR report and add them to the basic stats table at the top of the report
Below is the the instruction that describes the task: ### Input: Take the parsed stats from the STAR report and add them to the basic stats table at the top of the report ### Response: def star_stats_table(self): """ Take the parsed stats from the STAR report and add them to the basic stats...
def get_capabilities_by_ext(self, strict_type_matching: bool = False) -> Dict[str, Dict[Type, Dict[str, Parser]]]: """ For all extensions that are supported, lists all types that can be parsed from this extension. For each type, provide the list of parsers supported. The order is "most p...
For all extensions that are supported, lists all types that can be parsed from this extension. For each type, provide the list of parsers supported. The order is "most pertinent first" This method is for monitoring and debug, so we prefer to not rely on the cache, but rather on the query engine...
Below is the the instruction that describes the task: ### Input: For all extensions that are supported, lists all types that can be parsed from this extension. For each type, provide the list of parsers supported. The order is "most pertinent first" This method is for monitoring and debug, ...
def expand_url(url, protocol): """ Expands the given URL to a full URL by adding the magento soap/wsdl parts :param url: URL to be expanded :param service: 'xmlrpc' or 'soap' """ if protocol == 'soap': ws_part = 'api/?wsdl' elif protocol == 'xmlrpc': ws_part = 'index.php...
Expands the given URL to a full URL by adding the magento soap/wsdl parts :param url: URL to be expanded :param service: 'xmlrpc' or 'soap'
Below is the the instruction that describes the task: ### Input: Expands the given URL to a full URL by adding the magento soap/wsdl parts :param url: URL to be expanded :param service: 'xmlrpc' or 'soap' ### Response: def expand_url(url, protocol): """ Expands the given URL to a full URL by a...
def impute_dataframe_range(df_impute, col_to_max, col_to_min, col_to_median): """ Columnwise replaces all ``NaNs``, ``-inf`` and ``+inf`` from the DataFrame `df_impute` with average/extreme values from the provided dictionaries. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` ...
Columnwise replaces all ``NaNs``, ``-inf`` and ``+inf`` from the DataFrame `df_impute` with average/extreme values from the provided dictionaries. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` is replaced by * ``-inf`` -> by value in col_to_min * ``+inf`` -> by valu...
Below is the the instruction that describes the task: ### Input: Columnwise replaces all ``NaNs``, ``-inf`` and ``+inf`` from the DataFrame `df_impute` with average/extreme values from the provided dictionaries. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` is replaced by ...
def multiple_choice_field_data(field, **kwargs): """ Return random value for MultipleChoiceField >>> CHOICES = [('YNG', 'Child'), ('MIDDLE', 'Parent') ,('OLD', 'GrandParent')] >>> result = any_form_field(forms.MultipleChoiceField(choices=CHOICES)) >>> type(result) <type 'str'> """ if fi...
Return random value for MultipleChoiceField >>> CHOICES = [('YNG', 'Child'), ('MIDDLE', 'Parent') ,('OLD', 'GrandParent')] >>> result = any_form_field(forms.MultipleChoiceField(choices=CHOICES)) >>> type(result) <type 'str'>
Below is the the instruction that describes the task: ### Input: Return random value for MultipleChoiceField >>> CHOICES = [('YNG', 'Child'), ('MIDDLE', 'Parent') ,('OLD', 'GrandParent')] >>> result = any_form_field(forms.MultipleChoiceField(choices=CHOICES)) >>> type(result) <type 'str'> ### Respo...
def get_properties(elt, keys=None, ctx=None): """Get elt properties. :param elt: properties elt. Not None methods or unhashable types. :param keys: key(s) of properties to get from elt. If None, get all properties. :type keys: list or str :param ctx: elt ctx from where get properties. Equal...
Get elt properties. :param elt: properties elt. Not None methods or unhashable types. :param keys: key(s) of properties to get from elt. If None, get all properties. :type keys: list or str :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function prop...
Below is the the instruction that describes the task: ### Input: Get elt properties. :param elt: properties elt. Not None methods or unhashable types. :param keys: key(s) of properties to get from elt. If None, get all properties. :type keys: list or str :param ctx: elt ctx from where get p...
def perform_experiment(self, engine_list): """ Performs nearest neighbour recall experiments with custom vector data for all engines in the specified list. Returns self.result contains list of (recall, precision, search_time) tuple. All are the averaged values over all request v...
Performs nearest neighbour recall experiments with custom vector data for all engines in the specified list. Returns self.result contains list of (recall, precision, search_time) tuple. All are the averaged values over all request vectors. search_time is the average retrieval/search tim...
Below is the the instruction that describes the task: ### Input: Performs nearest neighbour recall experiments with custom vector data for all engines in the specified list. Returns self.result contains list of (recall, precision, search_time) tuple. All are the averaged values over all req...
def build_model_classes(metadata): """Generate a model class for any models contained in the specified spec file.""" i = importlib.import_module(metadata) env = get_jinja_env() model_template = env.get_template('model.py.jinja2') for model in i.models: with open(model_path(model.name.l...
Generate a model class for any models contained in the specified spec file.
Below is the the instruction that describes the task: ### Input: Generate a model class for any models contained in the specified spec file. ### Response: def build_model_classes(metadata): """Generate a model class for any models contained in the specified spec file.""" i = importlib.import_module(metad...
def dispatch(splits, *funcs, **kwargs): """takes multiple iterables (returned by dispatch or broadcast) and delivers the items to multiple functions /-----> _INPUT1 --> double(_INPUT1) --> \ / \ splits ------> _INPUT2 --> triple(_INPUT2) ---> _OU...
takes multiple iterables (returned by dispatch or broadcast) and delivers the items to multiple functions /-----> _INPUT1 --> double(_INPUT1) --> \ / \ splits ------> _INPUT2 --> triple(_INPUT2) ---> _OUTPUT \ ...
Below is the the instruction that describes the task: ### Input: takes multiple iterables (returned by dispatch or broadcast) and delivers the items to multiple functions /-----> _INPUT1 --> double(_INPUT1) --> \ / \ splits ------> _INPUT2 --> tr...
def create_prediction_estimator(hyper_params, model, checkpoint_path=None): """ Create an estimator for prediction purpose only. :param hyper_params: The hyper params file. :param model: The keras model. :param checkpoint_path: (Optional) Path to the specific checkpoint to use. :return: """ ...
Create an estimator for prediction purpose only. :param hyper_params: The hyper params file. :param model: The keras model. :param checkpoint_path: (Optional) Path to the specific checkpoint to use. :return:
Below is the the instruction that describes the task: ### Input: Create an estimator for prediction purpose only. :param hyper_params: The hyper params file. :param model: The keras model. :param checkpoint_path: (Optional) Path to the specific checkpoint to use. :return: ### Response: def create_p...
def course_or_program_exist(self, course_id, program_uuid): """ Return whether the input course or program exist. """ course_exists = course_id and CourseApiClient().get_course_details(course_id) program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(pro...
Return whether the input course or program exist.
Below is the the instruction that describes the task: ### Input: Return whether the input course or program exist. ### Response: def course_or_program_exist(self, course_id, program_uuid): """ Return whether the input course or program exist. """ course_exists = course_id and Course...
def get_item(self, address, state = 'fresh'): """Get an item from the cache. :Parameters: - `address`: its address. - `state`: the worst state that is acceptable. :Types: - `address`: any hashable - `state`: `str` :return: the item or `No...
Get an item from the cache. :Parameters: - `address`: its address. - `state`: the worst state that is acceptable. :Types: - `address`: any hashable - `state`: `str` :return: the item or `None` if it was not found. :returntype: `CacheItem`
Below is the the instruction that describes the task: ### Input: Get an item from the cache. :Parameters: - `address`: its address. - `state`: the worst state that is acceptable. :Types: - `address`: any hashable - `state`: `str` :return: the...
def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. Raises TypeError if text is not a Unicode string. Raises requests.HTTPError if the request fails. """ # Ensure text is Unicode expected = str if sys.version_info[0]...
Renders the specified markdown content and embedded styles. Raises TypeError if text is not a Unicode string. Raises requests.HTTPError if the request fails.
Below is the the instruction that describes the task: ### Input: Renders the specified markdown content and embedded styles. Raises TypeError if text is not a Unicode string. Raises requests.HTTPError if the request fails. ### Response: def render(self, text, auth=None): """ Render...
def __parse_json_file(self, file_path): """Process Json file data :@param file_path :@type file_path: string :@throws IOError """ if file_path == '' or os.path.splitext(file_path)[1] != '.json': raise IOError('Invalid Json file') with open(file_path...
Process Json file data :@param file_path :@type file_path: string :@throws IOError
Below is the the instruction that describes the task: ### Input: Process Json file data :@param file_path :@type file_path: string :@throws IOError ### Response: def __parse_json_file(self, file_path): """Process Json file data :@param file_path :@type file_path: ...
def next(self): '''next It generates tuple of data. For example, if :py:meth:`self._variables == ('x', 'y')` This method returns :py:meth:` ( [[X] * batch_size], [[Y] * batch_size] )` Returns: tuple: tuple of data for mini-batch in numpy.ndarray. ''...
next It generates tuple of data. For example, if :py:meth:`self._variables == ('x', 'y')` This method returns :py:meth:` ( [[X] * batch_size], [[Y] * batch_size] )` Returns: tuple: tuple of data for mini-batch in numpy.ndarray.
Below is the the instruction that describes the task: ### Input: next It generates tuple of data. For example, if :py:meth:`self._variables == ('x', 'y')` This method returns :py:meth:` ( [[X] * batch_size], [[Y] * batch_size] )` Returns: tuple: tuple of data f...
def command(self, *cmd): """ Sends a command or sequence of commands through to the I²C address - maximum allowed is 32 bytes in one go. :param cmd: A spread of commands. :type cmd: int :raises luma.core.error.DeviceNotFoundError: I2C device could not be found. "...
Sends a command or sequence of commands through to the I²C address - maximum allowed is 32 bytes in one go. :param cmd: A spread of commands. :type cmd: int :raises luma.core.error.DeviceNotFoundError: I2C device could not be found.
Below is the the instruction that describes the task: ### Input: Sends a command or sequence of commands through to the I²C address - maximum allowed is 32 bytes in one go. :param cmd: A spread of commands. :type cmd: int :raises luma.core.error.DeviceNotFoundError: I2C device could...
def markov_network(potentials): """Creates a Markov Network from potentials. A Markov Network is also knows as a `Markov Random Field`_ Parameters ---------- potentials : dict[tuple, dict] A dict where the keys are either nodes or edges and the values are a dictionary of potentials...
Creates a Markov Network from potentials. A Markov Network is also knows as a `Markov Random Field`_ Parameters ---------- potentials : dict[tuple, dict] A dict where the keys are either nodes or edges and the values are a dictionary of potentials. The potential dict should map each po...
Below is the the instruction that describes the task: ### Input: Creates a Markov Network from potentials. A Markov Network is also knows as a `Markov Random Field`_ Parameters ---------- potentials : dict[tuple, dict] A dict where the keys are either nodes or edges and the values are a ...
def _connect_mv_node(network, node, target_obj): """Connects MV node to target object in MV grid If the target object is a node, a new line is created to it. If the target object is a line, the node is connected to a newly created branch tee (using perpendicular projection) on this line. New lines ...
Connects MV node to target object in MV grid If the target object is a node, a new line is created to it. If the target object is a line, the node is connected to a newly created branch tee (using perpendicular projection) on this line. New lines are created using standard equipment. Parameters ...
Below is the the instruction that describes the task: ### Input: Connects MV node to target object in MV grid If the target object is a node, a new line is created to it. If the target object is a line, the node is connected to a newly created branch tee (using perpendicular projection) on this line. ...
def default(self): """Default for enum field. Will cause resolution of Enum type and unresolved default value. """ try: return self.__resolved_default except AttributeError: resolved_default = super(EnumField, self).default if isinstance(resol...
Default for enum field. Will cause resolution of Enum type and unresolved default value.
Below is the the instruction that describes the task: ### Input: Default for enum field. Will cause resolution of Enum type and unresolved default value. ### Response: def default(self): """Default for enum field. Will cause resolution of Enum type and unresolved default value. ""...
def resolve_inputs(self, layers): '''Resolve the names of inputs for this layer into shape tuples. Parameters ---------- layers : list of :class:`Layer` A list of the layers that are available for resolving inputs. Raises ------ theanets.util.Configu...
Resolve the names of inputs for this layer into shape tuples. Parameters ---------- layers : list of :class:`Layer` A list of the layers that are available for resolving inputs. Raises ------ theanets.util.ConfigurationError : If an input cannot ...
Below is the the instruction that describes the task: ### Input: Resolve the names of inputs for this layer into shape tuples. Parameters ---------- layers : list of :class:`Layer` A list of the layers that are available for resolving inputs. Raises ------ ...
def refresh(self): """Remove editors that are not longer open.""" self._update_id_list() for _id in self.history[:]: if _id not in self.id_list: self.history.remove(_id)
Remove editors that are not longer open.
Below is the the instruction that describes the task: ### Input: Remove editors that are not longer open. ### Response: def refresh(self): """Remove editors that are not longer open.""" self._update_id_list() for _id in self.history[:]: if _id not in self.id_list: ...
def get_spark_session(enable_hive=False, app_name='marvin-engine', configs=[]): """Return a Spark Session object""" # Prepare spark context to be used import findspark findspark.init() from pyspark.sql import SparkSession # prepare spark sesseion to be returned spark = SparkSession.builder...
Return a Spark Session object
Below is the the instruction that describes the task: ### Input: Return a Spark Session object ### Response: def get_spark_session(enable_hive=False, app_name='marvin-engine', configs=[]): """Return a Spark Session object""" # Prepare spark context to be used import findspark findspark.init() ...
def find_name(self, template_name, search_dirs): """ Return the path to a template with the given name. Arguments: template_name: the name of the template. search_dirs: the list of directories in which to search. """ file_name = self.make_file_name(templat...
Return the path to a template with the given name. Arguments: template_name: the name of the template. search_dirs: the list of directories in which to search.
Below is the the instruction that describes the task: ### Input: Return the path to a template with the given name. Arguments: template_name: the name of the template. search_dirs: the list of directories in which to search. ### Response: def find_name(self, template_name, search_dir...
def run(self, conn, tmp, module_name, module_args, inject): ''' handler for file transfer operations ''' tokens = shlex.split(module_args) source = tokens[0] # FIXME: error handling args = " ".join(tokens[1:]) source = utils.template(self.runner.basedir, source, in...
handler for file transfer operations
Below is the the instruction that describes the task: ### Input: handler for file transfer operations ### Response: def run(self, conn, tmp, module_name, module_args, inject): ''' handler for file transfer operations ''' tokens = shlex.split(module_args) source = tokens[0] # FIXM...
def expand_details(df, detailCol='detail'): """Expands the details column of the given dataframe and returns the resulting DataFrame. :df: The input DataFrame. :detailCol: The detail column name. :returns: Returns DataFrame with new columns from pbp parsing. """ df = copy.deepcopy(df) d...
Expands the details column of the given dataframe and returns the resulting DataFrame. :df: The input DataFrame. :detailCol: The detail column name. :returns: Returns DataFrame with new columns from pbp parsing.
Below is the the instruction that describes the task: ### Input: Expands the details column of the given dataframe and returns the resulting DataFrame. :df: The input DataFrame. :detailCol: The detail column name. :returns: Returns DataFrame with new columns from pbp parsing. ### Response: def exp...
def subtract( self, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0, ): """ Remove duration from the instance. :param years: The number of years :type years: int :param...
Remove duration from the instance. :param years: The number of years :type years: int :param months: The number of months :type months: int :param weeks: The number of weeks :type weeks: int :param days: The number of days :type days: int :par...
Below is the the instruction that describes the task: ### Input: Remove duration from the instance. :param years: The number of years :type years: int :param months: The number of months :type months: int :param weeks: The number of weeks :type weeks: int ...
def get_float(self, key, optional=False): """ Tries to fetch a variable from the config and expects it to be strictly a float :param key: Variable to look for :param optional: Whether to raise ConfigKeyNotFoundError if key was not found :return: float """ return s...
Tries to fetch a variable from the config and expects it to be strictly a float :param key: Variable to look for :param optional: Whether to raise ConfigKeyNotFoundError if key was not found :return: float
Below is the the instruction that describes the task: ### Input: Tries to fetch a variable from the config and expects it to be strictly a float :param key: Variable to look for :param optional: Whether to raise ConfigKeyNotFoundError if key was not found :return: float ### Response: def ge...
def save_package_contents(self, root, team, owner, pkgname): """ Saves the in-memory contents to a file in the local package repository. """ assert isinstance(root, RootNode) instance_hash = hash_contents(root) pkg_path = self.package_path(team, owner, pkgname) ...
Saves the in-memory contents to a file in the local package repository.
Below is the the instruction that describes the task: ### Input: Saves the in-memory contents to a file in the local package repository. ### Response: def save_package_contents(self, root, team, owner, pkgname): """ Saves the in-memory contents to a file in the local package reposit...
def _gitignore(root): """ Parses a .gitignore file and returns patterns to match dirs and files. Only basic gitignore patterns are supported. Pattern negation, ** wildcards and anchored patterns are not currently implemented. :param root: A unicode string of the path to the git repository ...
Parses a .gitignore file and returns patterns to match dirs and files. Only basic gitignore patterns are supported. Pattern negation, ** wildcards and anchored patterns are not currently implemented. :param root: A unicode string of the path to the git repository :return: A 2-element t...
Below is the the instruction that describes the task: ### Input: Parses a .gitignore file and returns patterns to match dirs and files. Only basic gitignore patterns are supported. Pattern negation, ** wildcards and anchored patterns are not currently implemented. :param root: A unicode string ...
def _get_default_locs(self, vmin, vmax): "Returns the default locations of ticks." if self.plot_obj.date_axis_info is None: self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq) locator = self.plot_obj.date_axis_info if self.isminor: return np.compr...
Returns the default locations of ticks.
Below is the the instruction that describes the task: ### Input: Returns the default locations of ticks. ### Response: def _get_default_locs(self, vmin, vmax): "Returns the default locations of ticks." if self.plot_obj.date_axis_info is None: self.plot_obj.date_axis_info = self.finder(...
def decode(encoded_histogram, b64_wrap=True): '''Decode an encoded histogram and return a new histogram instance that has been initialized with the decoded content Return: a new histogram instance representing the decoded content Exception: TypeError in case of ba...
Decode an encoded histogram and return a new histogram instance that has been initialized with the decoded content Return: a new histogram instance representing the decoded content Exception: TypeError in case of base64 decode error HdrCookieException: ...
Below is the the instruction that describes the task: ### Input: Decode an encoded histogram and return a new histogram instance that has been initialized with the decoded content Return: a new histogram instance representing the decoded content Exception: TypeError i...
def from_shapefile(output, input_shp_files, validate): """ Convert multiple ESRI Shapefile(s) into a single NRML source model file. """ input_parser = shapefileparser.ShapefileParser() source_model = input_parser.read(input_shp_files[0], validate) for f in input_shp_files[1:]: source_mod...
Convert multiple ESRI Shapefile(s) into a single NRML source model file.
Below is the the instruction that describes the task: ### Input: Convert multiple ESRI Shapefile(s) into a single NRML source model file. ### Response: def from_shapefile(output, input_shp_files, validate): """ Convert multiple ESRI Shapefile(s) into a single NRML source model file. """ input_parse...
def p_InSwitchDefList(p): ''' InSwitchDefList : InSwitchDef | InSwitchDefList InSwitchDef ''' if len(p) <= 2: p[0] = InSwitchDefList(None, p[1]) else: p[0] = InSwitchDefList(p[1], p[2])
InSwitchDefList : InSwitchDef | InSwitchDefList InSwitchDef
Below is the the instruction that describes the task: ### Input: InSwitchDefList : InSwitchDef | InSwitchDefList InSwitchDef ### Response: def p_InSwitchDefList(p): ''' InSwitchDefList : InSwitchDef | InSwitchDefList InSwitchDef ''' if len(p) <= 2: p[0...
def reminders_list(self, **kwargs) -> SlackResponse: """Lists all reminders created by or for a given user.""" self._validate_xoxp_token() return self.api_call("reminders.list", http_verb="GET", params=kwargs)
Lists all reminders created by or for a given user.
Below is the the instruction that describes the task: ### Input: Lists all reminders created by or for a given user. ### Response: def reminders_list(self, **kwargs) -> SlackResponse: """Lists all reminders created by or for a given user.""" self._validate_xoxp_token() return self.api_call(...
def _init_externals(): """Initialize external projects by putting them into the path""" if __version__ == 'git': sys.path.insert(0, osp.join(osp.dirname(__file__), 'ext', 'gitdb')) try: import gitdb except ImportError: raise ImportError("'gitdb' could not be found in your PYTHON...
Initialize external projects by putting them into the path
Below is the the instruction that describes the task: ### Input: Initialize external projects by putting them into the path ### Response: def _init_externals(): """Initialize external projects by putting them into the path""" if __version__ == 'git': sys.path.insert(0, osp.join(osp.dirname(__file__...
def start(docker_url='unix://var/run/docker.sock', timeout=CLIENT_TIMEOUT, tag='salt/engines/docker_events', filters=None): ''' Scan for Docker events and fire events Example Config .. code-block:: yaml engines: - docker_events: docker_url...
Scan for Docker events and fire events Example Config .. code-block:: yaml engines: - docker_events: docker_url: unix://var/run/docker.sock filters: event: - start - stop - die - oom ...
Below is the the instruction that describes the task: ### Input: Scan for Docker events and fire events Example Config .. code-block:: yaml engines: - docker_events: docker_url: unix://var/run/docker.sock filters: event: - star...
def favorite_remove(self, post_id): """Remove a post from favorites (Requires login). Parameters: post_id (int): Where post_id is the post id. """ return self._get('favorites/{0}.json'.format(post_id), method='DELETE', auth=True)
Remove a post from favorites (Requires login). Parameters: post_id (int): Where post_id is the post id.
Below is the the instruction that describes the task: ### Input: Remove a post from favorites (Requires login). Parameters: post_id (int): Where post_id is the post id. ### Response: def favorite_remove(self, post_id): """Remove a post from favorites (Requires login). Paramete...
def find_class(self): """Return a class related with this type.""" if self.value <= 1: return InstructionsProperty elif self.value <= 3: return NextTablesProperty elif self.value <= 7: return ActionsProperty return OxmProperty
Return a class related with this type.
Below is the the instruction that describes the task: ### Input: Return a class related with this type. ### Response: def find_class(self): """Return a class related with this type.""" if self.value <= 1: return InstructionsProperty elif self.value <= 3: return NextT...
def _ReadFloatingPointDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a floating-point data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_valu...
Reads a floating-point data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the d...
Below is the the instruction that describes the task: ### Input: Reads a floating-point data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): na...
def set_rendering_intent(self, rendering_intent): """Set rendering intent variant for sRGB chunk""" if rendering_intent not in (None, PERCEPTUAL, RELATIVE_COLORIMETRIC, SATURATION, ...
Set rendering intent variant for sRGB chunk
Below is the the instruction that describes the task: ### Input: Set rendering intent variant for sRGB chunk ### Response: def set_rendering_intent(self, rendering_intent): """Set rendering intent variant for sRGB chunk""" if rendering_intent not in (None, PERCEP...
def load(self, name): """ If not yet in the cache, load the named template and compiles it, placing it into the cache. If in cache, return the cached template. """ if self.reload: self._maybe_purge_cache() template = self.cache.get(name) if ...
If not yet in the cache, load the named template and compiles it, placing it into the cache. If in cache, return the cached template.
Below is the the instruction that describes the task: ### Input: If not yet in the cache, load the named template and compiles it, placing it into the cache. If in cache, return the cached template. ### Response: def load(self, name): """ If not yet in the cache, load the named tem...
def _handle_comparison(self, truism): """ Handles all comparisons. """ # print("COMP:", truism) is_lt, is_equal, is_unsigned = self.comparison_info[truism.op] size = len(truism.args[0]) int_max = 2**size-1 if is_unsigned else 2**(size-1)-1 int_min = -2*...
Handles all comparisons.
Below is the the instruction that describes the task: ### Input: Handles all comparisons. ### Response: def _handle_comparison(self, truism): """ Handles all comparisons. """ # print("COMP:", truism) is_lt, is_equal, is_unsigned = self.comparison_info[truism.op] s...
def list(self): """ Get all current hooks :return: All hooks :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ return self._post( ...
Get all current hooks :return: All hooks :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries
Below is the the instruction that describes the task: ### Input: Get all current hooks :return: All hooks :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries ### Res...
def publish_server_closed(self, server_address, topology_id): """Publish a ServerClosedEvent to all server listeners. :Parameters: - `server_address`: The address (host/port pair) of the server. - `topology_id`: A unique identifier for the topology this server is a part of....
Publish a ServerClosedEvent to all server listeners. :Parameters: - `server_address`: The address (host/port pair) of the server. - `topology_id`: A unique identifier for the topology this server is a part of.
Below is the the instruction that describes the task: ### Input: Publish a ServerClosedEvent to all server listeners. :Parameters: - `server_address`: The address (host/port pair) of the server. - `topology_id`: A unique identifier for the topology this server is a part of. ###...
def load(self, read_tuple_name): """Load RNF values from a read tuple name. Args: read_tuple_name (str): Read tuple name which the values are taken from. """ self.prefix_width = 0 self.read_tuple_id_width = 0 self.genome_id_width = 0 self.chr_id_width = 0 self.coo...
Load RNF values from a read tuple name. Args: read_tuple_name (str): Read tuple name which the values are taken from.
Below is the the instruction that describes the task: ### Input: Load RNF values from a read tuple name. Args: read_tuple_name (str): Read tuple name which the values are taken from. ### Response: def load(self, read_tuple_name): """Load RNF values from a read tuple name. Args: read_tuple_name ...
def sid(tnet, communities, axis=0, calc='global', decay=0): r""" Segregation integration difference (SID). An estimation of each community or global difference of within versus between community strength.[sid-1]_ Parameters ---------- tnet: array, dict Temporal network input (graphlet or ...
r""" Segregation integration difference (SID). An estimation of each community or global difference of within versus between community strength.[sid-1]_ Parameters ---------- tnet: array, dict Temporal network input (graphlet or contact). Allowerd nettype: 'bu', 'bd', 'wu', 'wd' communit...
Below is the the instruction that describes the task: ### Input: r""" Segregation integration difference (SID). An estimation of each community or global difference of within versus between community strength.[sid-1]_ Parameters ---------- tnet: array, dict Temporal network input (graphle...
def config_dir_setup(filename): """ sets the config file and makes sure the directory exists if it has not yet been created. :param filename: :return: """ path = os.path.dirname(filename) if not os.path.isdir(path): Shell.mkdir(path)
sets the config file and makes sure the directory exists if it has not yet been created. :param filename: :return:
Below is the the instruction that describes the task: ### Input: sets the config file and makes sure the directory exists if it has not yet been created. :param filename: :return: ### Response: def config_dir_setup(filename): """ sets the config file and makes sure the directory exists if it has n...
def _get_default(self, obj): ''' Internal implementation of instance attribute access for default values. Handles bookeeping around |PropertyContainer| value, etc. ''' if self.name in obj._property_values: # this shouldn't happen because we should have checked befor...
Internal implementation of instance attribute access for default values. Handles bookeeping around |PropertyContainer| value, etc.
Below is the the instruction that describes the task: ### Input: Internal implementation of instance attribute access for default values. Handles bookeeping around |PropertyContainer| value, etc. ### Response: def _get_default(self, obj): ''' Internal implementation of instance attribute a...
def remove_labels(self, labels, relabel=False): """ Remove one or more labels. Removed labels are assigned a value of zero (i.e., background). Parameters ---------- labels : int, array-like (1D, int) The label number(s) to remove. relabel : bool, op...
Remove one or more labels. Removed labels are assigned a value of zero (i.e., background). Parameters ---------- labels : int, array-like (1D, int) The label number(s) to remove. relabel : bool, optional If `True`, then the segmentation image will be re...
Below is the the instruction that describes the task: ### Input: Remove one or more labels. Removed labels are assigned a value of zero (i.e., background). Parameters ---------- labels : int, array-like (1D, int) The label number(s) to remove. relabel : bool, o...
def full_data(self): """ Returns all the info available for the chat in the following format: title [username] (type) <id> If any data is not available, it is not added. """ data = [ self.chat.title, self._username(), self._type(), ...
Returns all the info available for the chat in the following format: title [username] (type) <id> If any data is not available, it is not added.
Below is the the instruction that describes the task: ### Input: Returns all the info available for the chat in the following format: title [username] (type) <id> If any data is not available, it is not added. ### Response: def full_data(self): """ Returns all the info available...
def _validate_backend(self): """ ensure backend string representation is correct """ try: self.backend_class # if we get an import error the specified path is wrong except (ImportError, AttributeError) as e: raise ValidationError(_('No valid backend found, got the...
ensure backend string representation is correct
Below is the the instruction that describes the task: ### Input: ensure backend string representation is correct ### Response: def _validate_backend(self): """ ensure backend string representation is correct """ try: self.backend_class # if we get an import error the specified p...
def project_move(object_id, input_params={}, always_retry=False, **kwargs): """ Invokes the /project-xxxx/move API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2Fmove """ return DXHTTPRequest('/%s/move' % object_id, ...
Invokes the /project-xxxx/move API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2Fmove
Below is the the instruction that describes the task: ### Input: Invokes the /project-xxxx/move API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2Fmove ### Response: def project_move(object_id, input_params={}, always_retry=Fal...
def Execute(self, message): """This function parses the RDFValue from the server. The Run method will be called with the specified RDFValue. Args: message: The GrrMessage that we are called to process. Returns: Upon return a callback will be called on the server to register th...
This function parses the RDFValue from the server. The Run method will be called with the specified RDFValue. Args: message: The GrrMessage that we are called to process. Returns: Upon return a callback will be called on the server to register the end of the function and pass back...
Below is the the instruction that describes the task: ### Input: This function parses the RDFValue from the server. The Run method will be called with the specified RDFValue. Args: message: The GrrMessage that we are called to process. Returns: Upon return a callback will be called o...
def _shuffle_items(items, bucket_key=None, disable=None, seed=None, session=None): """ Shuffles a list of `items` in place. If `bucket_key` is None, items are shuffled across the entire list. `bucket_key` is an optional function called for each item in `items` to calculate the key of bucket in whi...
Shuffles a list of `items` in place. If `bucket_key` is None, items are shuffled across the entire list. `bucket_key` is an optional function called for each item in `items` to calculate the key of bucket in which the item falls. Bucket defines the boundaries across which items will not be shuffl...
Below is the the instruction that describes the task: ### Input: Shuffles a list of `items` in place. If `bucket_key` is None, items are shuffled across the entire list. `bucket_key` is an optional function called for each item in `items` to calculate the key of bucket in which the item falls. Bu...
def MCMC_pdf_samples(self, fNew, num_samples=1000, starting_loc=None, stepsize=0.1, burn_in=1000, Y_metadata=None): """ Simple implementation of Metropolis sampling algorithm Will run a parallel chain for each input dimension (treats each f independently) Thus assumes f*_1 independant o...
Simple implementation of Metropolis sampling algorithm Will run a parallel chain for each input dimension (treats each f independently) Thus assumes f*_1 independant of f*_2 etc. :param num_samples: Number of samples to take :param fNew: f at which to sample around :param start...
Below is the the instruction that describes the task: ### Input: Simple implementation of Metropolis sampling algorithm Will run a parallel chain for each input dimension (treats each f independently) Thus assumes f*_1 independant of f*_2 etc. :param num_samples: Number of samples to take ...
def HumanReadableStartType(self): """Return a human readable string describing the start type value. Returns: str: human readable description of the start type value. """ if isinstance(self.start_type, py2to3.STRING_TYPES): return self.start_type return human_readable_service_enums.SERV...
Return a human readable string describing the start type value. Returns: str: human readable description of the start type value.
Below is the the instruction that describes the task: ### Input: Return a human readable string describing the start type value. Returns: str: human readable description of the start type value. ### Response: def HumanReadableStartType(self): """Return a human readable string describing the start ty...
def get_subgraph_peripheral_nodes(graph: BELGraph, subgraph: Iterable[BaseEntity], node_predicates: NodePredicates = None, edge_predicates: EdgePredicates = None, ): """Get a summa...
Get a summary dictionary of all peripheral nodes to a given sub-graph. :return: A dictionary of {external node: {'successor': {internal node: list of (key, dict)}, 'predecessor': {internal node: list of (key, dict)}}} :rtype: dict For example, it might be useful...
Below is the the instruction that describes the task: ### Input: Get a summary dictionary of all peripheral nodes to a given sub-graph. :return: A dictionary of {external node: {'successor': {internal node: list of (key, dict)}, 'predecessor': {internal node: list of...
def dot_v2(vec1, vec2): """Return the dot product of two vectors""" return vec1.x * vec2.x + vec1.y * vec2.y
Return the dot product of two vectors
Below is the the instruction that describes the task: ### Input: Return the dot product of two vectors ### Response: def dot_v2(vec1, vec2): """Return the dot product of two vectors""" return vec1.x * vec2.x + vec1.y * vec2.y
def fieldvalue_pairs(self, exclude_cache=False): '''Generator of fields,values pairs. Fields correspond to the ones which have been loaded (usually all of them) or not loaded but modified. Check the :ref:`load_only <performance-loadonly>` query function for more details. If *exclude_cache* evaluates to ``True`...
Generator of fields,values pairs. Fields correspond to the ones which have been loaded (usually all of them) or not loaded but modified. Check the :ref:`load_only <performance-loadonly>` query function for more details. If *exclude_cache* evaluates to ``True``, fields with :attr:`Field.as_cache` attribute set to ``Tru...
Below is the the instruction that describes the task: ### Input: Generator of fields,values pairs. Fields correspond to the ones which have been loaded (usually all of them) or not loaded but modified. Check the :ref:`load_only <performance-loadonly>` query function for more details. If *exclude_cache* evaluates t...
def process_directory_statements_sorted_by_pmid(directory_name): """Processes a directory filled with CSXML files, first normalizing the character encoding to utf-8, and then processing into INDRA statements sorted by pmid. Parameters ---------- directory_name : str The name of a direct...
Processes a directory filled with CSXML files, first normalizing the character encoding to utf-8, and then processing into INDRA statements sorted by pmid. Parameters ---------- directory_name : str The name of a directory filled with csxml files to process Returns ------- pmid...
Below is the the instruction that describes the task: ### Input: Processes a directory filled with CSXML files, first normalizing the character encoding to utf-8, and then processing into INDRA statements sorted by pmid. Parameters ---------- directory_name : str The name of a directory...
def delete(cls, resources, background=False, force=False): """Delete an ip by deleting the iface""" if not isinstance(resources, (list, tuple)): resources = [resources] ifaces = [] for item in resources: try: ip_ = cls.info(item) excep...
Delete an ip by deleting the iface
Below is the the instruction that describes the task: ### Input: Delete an ip by deleting the iface ### Response: def delete(cls, resources, background=False, force=False): """Delete an ip by deleting the iface""" if not isinstance(resources, (list, tuple)): resources = [resources] ...
def resume(self, vehID): """resume(string) -> None Resumes the vehicle from the current stop (throws an error if the vehicle is not stopped). """ self._connection._beginMessage( tc.CMD_SET_VEHICLE_VARIABLE, tc.CMD_RESUME, vehID, 1 + 4) self._connection._string += str...
resume(string) -> None Resumes the vehicle from the current stop (throws an error if the vehicle is not stopped).
Below is the the instruction that describes the task: ### Input: resume(string) -> None Resumes the vehicle from the current stop (throws an error if the vehicle is not stopped). ### Response: def resume(self, vehID): """resume(string) -> None Resumes the vehicle from the current stop (th...
def columns_used(self): """ Columns from any table used in the model. May come from either the choosers or alternatives tables. """ return list(tz.unique(tz.concatv( self.choosers_columns_used(), self.alts_columns_used(), self.interaction_colu...
Columns from any table used in the model. May come from either the choosers or alternatives tables.
Below is the the instruction that describes the task: ### Input: Columns from any table used in the model. May come from either the choosers or alternatives tables. ### Response: def columns_used(self): """ Columns from any table used in the model. May come from either the choosers ...
def Delete(self): """Delete public IP. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComplete() 0 """ public_ip_set = [{'public_ipId': o.id} for o in self.parent.public_ips if o!=self] self.parent.public_ips = [o for o in self.parent.public_ips if o!=self] return(clc.v2.Re...
Delete public IP. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComplete() 0
Below is the the instruction that describes the task: ### Input: Delete public IP. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComplete() 0 ### Response: def Delete(self): """Delete public IP. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComp...
def can_use_c_for(self, node): """ Check if a for loop can use classic C syntax. To use C syntax: - target should not be assign in the loop - xrange should be use as iterator - order have to be known at compile time """ assert isinstance(node....
Check if a for loop can use classic C syntax. To use C syntax: - target should not be assign in the loop - xrange should be use as iterator - order have to be known at compile time
Below is the the instruction that describes the task: ### Input: Check if a for loop can use classic C syntax. To use C syntax: - target should not be assign in the loop - xrange should be use as iterator - order have to be known at compile time ### Response: def can_us...