code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _read_range(self, start, end=0): """ Read a range of bytes in stream. Args: start (int): Start stream position. end (int): End stream position. 0 To not specify end. Returns: bytes: number of bytes read """ # Get o...
Read a range of bytes in stream. Args: start (int): Start stream position. end (int): End stream position. 0 To not specify end. Returns: bytes: number of bytes read
Below is the the instruction that describes the task: ### Input: Read a range of bytes in stream. Args: start (int): Start stream position. end (int): End stream position. 0 To not specify end. Returns: bytes: number of bytes read ### Response: ...
def get_value(data, name, field, allow_many_nested=False): """Get a value from a dictionary. Handles ``MultiDict`` types when ``multiple=True``. If the value is not found, return `missing`. :param object data: Mapping (e.g. `dict`) or list-like instance to pull the value from. :param str name: ...
Get a value from a dictionary. Handles ``MultiDict`` types when ``multiple=True``. If the value is not found, return `missing`. :param object data: Mapping (e.g. `dict`) or list-like instance to pull the value from. :param str name: Name of the key. :param bool multiple: Whether to handle multi...
Below is the the instruction that describes the task: ### Input: Get a value from a dictionary. Handles ``MultiDict`` types when ``multiple=True``. If the value is not found, return `missing`. :param object data: Mapping (e.g. `dict`) or list-like instance to pull the value from. :param str nam...
def cachedir_index_add(minion_id, profile, driver, provider, base=None): ''' Add an entry to the cachedir index. This generally only needs to happen when a new instance is created. This entry should contain: .. code-block:: yaml - minion_id - profile used to create the instance ...
Add an entry to the cachedir index. This generally only needs to happen when a new instance is created. This entry should contain: .. code-block:: yaml - minion_id - profile used to create the instance - provider and driver name The intent of this function is to speed up lookups f...
Below is the the instruction that describes the task: ### Input: Add an entry to the cachedir index. This generally only needs to happen when a new instance is created. This entry should contain: .. code-block:: yaml - minion_id - profile used to create the instance - provider and ...
def superReadFile(filepath, **kwargs): """ Uses pandas.read_excel (on excel files) and returns a dataframe of the first sheet (unless sheet is specified in kwargs) Uses superReadText (on .txt,.tsv, or .csv files) and returns a dataframe of the data. One function to read almost all types of data file...
Uses pandas.read_excel (on excel files) and returns a dataframe of the first sheet (unless sheet is specified in kwargs) Uses superReadText (on .txt,.tsv, or .csv files) and returns a dataframe of the data. One function to read almost all types of data files.
Below is the the instruction that describes the task: ### Input: Uses pandas.read_excel (on excel files) and returns a dataframe of the first sheet (unless sheet is specified in kwargs) Uses superReadText (on .txt,.tsv, or .csv files) and returns a dataframe of the data. One function to read almost all ...
def generate_hotel_price(location, nights, room_type): """ Generates a number within a reasonable range that might be expected for a hotel. The price is fixed for a pair of location and roomType. """ room_types = ['queen', 'king', 'deluxe'] cost_of_living = 0 for i in range(len(location)): ...
Generates a number within a reasonable range that might be expected for a hotel. The price is fixed for a pair of location and roomType.
Below is the the instruction that describes the task: ### Input: Generates a number within a reasonable range that might be expected for a hotel. The price is fixed for a pair of location and roomType. ### Response: def generate_hotel_price(location, nights, room_type): """ Generates a number within a ...
def _check_proper_bases(self, node): """ Detect that a class inherits something which is not a class or a type. """ for base in node.bases: ancestor = safe_infer(base) if ancestor in (astroid.Uninferable, None): continue if isin...
Detect that a class inherits something which is not a class or a type.
Below is the the instruction that describes the task: ### Input: Detect that a class inherits something which is not a class or a type. ### Response: def _check_proper_bases(self, node): """ Detect that a class inherits something which is not a class or a type. """ f...
def dispatch_result(self, raw_msg): """dispatch method for result replies""" try: idents,msg = self.session.feed_identities(raw_msg, copy=False) msg = self.session.unserialize(msg, content=False, copy=False) engine = idents[0] try: idx = se...
dispatch method for result replies
Below is the the instruction that describes the task: ### Input: dispatch method for result replies ### Response: def dispatch_result(self, raw_msg): """dispatch method for result replies""" try: idents,msg = self.session.feed_identities(raw_msg, copy=False) msg = self.sessi...
def shuffle_step(entries, step): ''' Shuffle the step ''' answer = [] for i in range(0, len(entries), step): sub = entries[i:i+step] shuffle(sub) answer += sub return answer
Shuffle the step
Below is the the instruction that describes the task: ### Input: Shuffle the step ### Response: def shuffle_step(entries, step): ''' Shuffle the step ''' answer = [] for i in range(0, len(entries), step): sub = entries[i:i+step] shuffle(sub) answer += sub return answ...
def parse_lit(self, lines): ''' Parse a string line-by-line delineating comments and code :returns: An tuple of boolean/list-of-string pairs. True designates a comment; False designates code. ''' comment_char = '#' # TODO: move this into a directive option co...
Parse a string line-by-line delineating comments and code :returns: An tuple of boolean/list-of-string pairs. True designates a comment; False designates code.
Below is the the instruction that describes the task: ### Input: Parse a string line-by-line delineating comments and code :returns: An tuple of boolean/list-of-string pairs. True designates a comment; False designates code. ### Response: def parse_lit(self, lines): ''' Parse a...
def open_tar(path_or_file, *args, **kwargs): """ A with-context for tar files. Passes through positional and kwargs to tarfile.open. If path_or_file is a file, caller must close it separately. """ (path, fileobj) = ((path_or_file, None) if isinstance(path_or_file, string_types) else...
A with-context for tar files. Passes through positional and kwargs to tarfile.open. If path_or_file is a file, caller must close it separately.
Below is the the instruction that describes the task: ### Input: A with-context for tar files. Passes through positional and kwargs to tarfile.open. If path_or_file is a file, caller must close it separately. ### Response: def open_tar(path_or_file, *args, **kwargs): """ A with-context for tar files. ...
def get_termination_stats(self, get_cos=True): """ Returns a dict of termination statistics Parameters ---------- get_cos : Bool, optional Whether or not to calcualte the cosine of the residuals with the tangent plane of the model using the cu...
Returns a dict of termination statistics Parameters ---------- get_cos : Bool, optional Whether or not to calcualte the cosine of the residuals with the tangent plane of the model using the current J. The calculation may take some time. Defaul...
Below is the the instruction that describes the task: ### Input: Returns a dict of termination statistics Parameters ---------- get_cos : Bool, optional Whether or not to calcualte the cosine of the residuals with the tangent plane of the model using the ...
def get_element_by_path(tree, path_and_name, namespace): # type: (_Element, str, str) -> typing.Union[_Element, None] """Find sub-element of given path with given short name.""" global xml_element_cache namespace_map = {'A': namespace[1:-1]} base_path, element_name = path_and_name.rsplit('/', 1) ...
Find sub-element of given path with given short name.
Below is the the instruction that describes the task: ### Input: Find sub-element of given path with given short name. ### Response: def get_element_by_path(tree, path_and_name, namespace): # type: (_Element, str, str) -> typing.Union[_Element, None] """Find sub-element of given path with given short name....
def pair_visual(original, adversarial, figure=None): """ This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plot :ret...
This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plot :return: the matplot figure to reuse for future samples
Below is the the instruction that describes the task: ### Input: This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plo...
def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|arg...
Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse grou...
Below is the the instruction that describes the task: ### Input: Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argp...
def all_good_stars(self): """ A list of all `EPSFStar` objects stored in this object that have not been excluded from fitting, including those that comprise linked stars (i.e. `LinkedEPSFStar`), as a flat list. """ stars = [] for star in self.all_stars: ...
A list of all `EPSFStar` objects stored in this object that have not been excluded from fitting, including those that comprise linked stars (i.e. `LinkedEPSFStar`), as a flat list.
Below is the the instruction that describes the task: ### Input: A list of all `EPSFStar` objects stored in this object that have not been excluded from fitting, including those that comprise linked stars (i.e. `LinkedEPSFStar`), as a flat list. ### Response: def all_good_stars(self): """ ...
def render_it(self, kind, num, with_tag=False, glyph=''): ''' render, no user logged in ''' all_cats = MPost.query_recent(num, kind=kind) kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.re...
render, no user logged in
Below is the the instruction that describes the task: ### Input: render, no user logged in ### Response: def render_it(self, kind, num, with_tag=False, glyph=''): ''' render, no user logged in ''' all_cats = MPost.query_recent(num, kind=kind) kwd = { 'with_tag': ...
def random(cls, L=1, avg_mu=1.0, alphabet='nuc', pi_dirichlet_alpha=1, W_dirichlet_alpha=3.0, mu_gamma_alpha=3.0): """ Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (s...
Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap')
Below is the the instruction that describes the task: ### Input: Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap') ### Response: def random(cl...
def _apply_bracket_layers(self): """Extract bracket layers in a GSGlyph into free-standing UFO glyphs with Designspace substitution rules. As of Glyphs.app 2.6, only single axis bracket layers are supported, we assume the axis to be the first axis in the Designspace. Bracket layer ...
Extract bracket layers in a GSGlyph into free-standing UFO glyphs with Designspace substitution rules. As of Glyphs.app 2.6, only single axis bracket layers are supported, we assume the axis to be the first axis in the Designspace. Bracket layer backgrounds are not round-tripped. ...
Below is the the instruction that describes the task: ### Input: Extract bracket layers in a GSGlyph into free-standing UFO glyphs with Designspace substitution rules. As of Glyphs.app 2.6, only single axis bracket layers are supported, we assume the axis to be the first axis in the Designs...
def download_by_id(self, vid = '', title = None, output_dir='.', merge=True, info_only=False,**kwargs): """self, str->None Keyword arguments: self: self vid: The video ID for BokeCC cloud, something like FE3BB999594978049C33DC5901307461 Calls the prepare...
self, str->None Keyword arguments: self: self vid: The video ID for BokeCC cloud, something like FE3BB999594978049C33DC5901307461 Calls the prepare() to download the video. If no title is provided, this method shall try to find a proper title ...
Below is the the instruction that describes the task: ### Input: self, str->None Keyword arguments: self: self vid: The video ID for BokeCC cloud, something like FE3BB999594978049C33DC5901307461 Calls the prepare() to download the video. If ...
def MobileDeviceApplication(self, data=None, subset=None): """{dynamic_docstring}""" return self.factory.get_object(jssobjects.MobileDeviceApplication, data, subset)
{dynamic_docstring}
Below is the the instruction that describes the task: ### Input: {dynamic_docstring} ### Response: def MobileDeviceApplication(self, data=None, subset=None): """{dynamic_docstring}""" return self.factory.get_object(jssobjects.MobileDeviceApplication, data, sub...
def get_filename_safe_string(string): """ Converts a string to a string that is safe for a filename Args: string (str): A string to make safe for a filename Returns: str: A string safe for a filename """ invalid_filename_chars = ['\\', '/', ':', '"', '*', '?', '|', '\n', ...
Converts a string to a string that is safe for a filename Args: string (str): A string to make safe for a filename Returns: str: A string safe for a filename
Below is the the instruction that describes the task: ### Input: Converts a string to a string that is safe for a filename Args: string (str): A string to make safe for a filename Returns: str: A string safe for a filename ### Response: def get_filename_safe_string(string): """ Con...
def has_valid_soma(data_wrapper): '''Check if a data block has a valid soma Returns: CheckResult with result ''' try: make_soma(data_wrapper.soma_points()) return CheckResult(True) except SomaError: return CheckResult(False)
Check if a data block has a valid soma Returns: CheckResult with result
Below is the the instruction that describes the task: ### Input: Check if a data block has a valid soma Returns: CheckResult with result ### Response: def has_valid_soma(data_wrapper): '''Check if a data block has a valid soma Returns: CheckResult with result ''' try: ...
def error(self, message, *args, **kwargs): """Log error event. Compatible with logging.error signature. """ self.system.error(message, *args, **kwargs)
Log error event. Compatible with logging.error signature.
Below is the the instruction that describes the task: ### Input: Log error event. Compatible with logging.error signature. ### Response: def error(self, message, *args, **kwargs): """Log error event. Compatible with logging.error signature. """ self.system.error(message, *...
def get_elastic_items(elastic, elastic_scroll_id=None, limit=None): """ Get the items from the index """ scroll_size = limit if not limit: scroll_size = DEFAULT_LIMIT if not elastic: return None url = elastic.index_url max_process_items_pack_time = "5m" # 10 minutes url +...
Get the items from the index
Below is the the instruction that describes the task: ### Input: Get the items from the index ### Response: def get_elastic_items(elastic, elastic_scroll_id=None, limit=None): """ Get the items from the index """ scroll_size = limit if not limit: scroll_size = DEFAULT_LIMIT if not elastic...
def find_ctrlpts(obj, u, v=None, **kwargs): """ Finds the control points involved in the evaluation of the curve/surface point defined by the input parameter(s). :param obj: curve or surface :type obj: abstract.Curve or abstract.Surface :param u: parameter (for curve), parameter on the u-direction (for...
Finds the control points involved in the evaluation of the curve/surface point defined by the input parameter(s). :param obj: curve or surface :type obj: abstract.Curve or abstract.Surface :param u: parameter (for curve), parameter on the u-direction (for surface) :type u: float :param v: parameter...
Below is the the instruction that describes the task: ### Input: Finds the control points involved in the evaluation of the curve/surface point defined by the input parameter(s). :param obj: curve or surface :type obj: abstract.Curve or abstract.Surface :param u: parameter (for curve), parameter on the...
def get_path(self, instance=True, origin='openconfig'): '''get_path High-level api: get_path returns gNMI path object of the config node. Note that gNMI Path can specify list instance but cannot specify leaf-list instance. Parameters ---------- instance : `bool...
get_path High-level api: get_path returns gNMI path object of the config node. Note that gNMI Path can specify list instance but cannot specify leaf-list instance. Parameters ---------- instance : `bool` True if the gNMI Path object refers to only one insta...
Below is the the instruction that describes the task: ### Input: get_path High-level api: get_path returns gNMI path object of the config node. Note that gNMI Path can specify list instance but cannot specify leaf-list instance. Parameters ---------- instance : `bo...
def likelihood_weighting(X, e, bn, N): """Estimate the probability distribution of variable X given evidence e in BayesNet bn. [Fig. 14.15] >>> seed(1017) >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T), ... burglary, 10000).show_approx() 'False: 0.702, True: 0.298' ""...
Estimate the probability distribution of variable X given evidence e in BayesNet bn. [Fig. 14.15] >>> seed(1017) >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T), ... burglary, 10000).show_approx() 'False: 0.702, True: 0.298'
Below is the the instruction that describes the task: ### Input: Estimate the probability distribution of variable X given evidence e in BayesNet bn. [Fig. 14.15] >>> seed(1017) >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T), ... burglary, 10000).show_approx() 'False: 0.7...
def users(self, start=1, num=10, sortField="fullName", sortOrder="asc", role=None): """ Lists all the members of the organization. The start and num paging parameters are supported. Inputs: start - The numb...
Lists all the members of the organization. The start and num paging parameters are supported. Inputs: start - The number of the first entry in the result set response. The index number is 1-based. The default value of start is 1 (that is, the first ...
Below is the the instruction that describes the task: ### Input: Lists all the members of the organization. The start and num paging parameters are supported. Inputs: start - The number of the first entry in the result set response. The index number is 1-based. ...
def _get_vcpu_field_and_address(self, field_name, x, y, p): """Get the field and address for a VCPU struct field.""" vcpu_struct = self.structs[b"vcpu"] field = vcpu_struct[six.b(field_name)] address = (self.read_struct_field("sv", "vcpu_base", x, y) + vcpu_struct.size...
Get the field and address for a VCPU struct field.
Below is the the instruction that describes the task: ### Input: Get the field and address for a VCPU struct field. ### Response: def _get_vcpu_field_and_address(self, field_name, x, y, p): """Get the field and address for a VCPU struct field.""" vcpu_struct = self.structs[b"vcpu"] field = ...
def print_to_tsplib(self, edges, tspfile, precision=0): """ See TSPlib format: <https://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/> NAME: bayg29 TYPE: TSP COMMENT: 29 Cities in Bavaria, geographical distances DIMENSION: 29 EDGE_WEIGHT_TYPE...
See TSPlib format: <https://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/> NAME: bayg29 TYPE: TSP COMMENT: 29 Cities in Bavaria, geographical distances DIMENSION: 29 EDGE_WEIGHT_TYPE: EXPLICIT EDGE_WEIGHT_FORMAT: UPPER_ROW DISPLAY_DATA_TYPE: ...
Below is the the instruction that describes the task: ### Input: See TSPlib format: <https://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/> NAME: bayg29 TYPE: TSP COMMENT: 29 Cities in Bavaria, geographical distances DIMENSION: 29 EDGE_WEIGHT_TYPE: EXPLI...
def _process_list(self, list_line): # -rw-r--r-- 1 ftp ftp 68 May 09 19:37 testftp.txt """ Processes a line of 'ls -l' output, and updates state accordingly. :param list_line: Line to process """ res = list_line.split(' ', 8) if res[0].startswith('-'): ...
Processes a line of 'ls -l' output, and updates state accordingly. :param list_line: Line to process
Below is the the instruction that describes the task: ### Input: Processes a line of 'ls -l' output, and updates state accordingly. :param list_line: Line to process ### Response: def _process_list(self, list_line): # -rw-r--r-- 1 ftp ftp 68 May 09 19:37 testftp.txt """ Proces...
def xstep(self): r"""Minimise Augmented Lagrangian with respect to block vector :math:`\mathbf{x} = \left( \begin{array}{ccc} \mathbf{x}_0^T & \mathbf{x}_1^T & \ldots \end{array} \right)^T\;`. """ # This test reflects empirical evidence that two slightly # different impl...
r"""Minimise Augmented Lagrangian with respect to block vector :math:`\mathbf{x} = \left( \begin{array}{ccc} \mathbf{x}_0^T & \mathbf{x}_1^T & \ldots \end{array} \right)^T\;`.
Below is the the instruction that describes the task: ### Input: r"""Minimise Augmented Lagrangian with respect to block vector :math:`\mathbf{x} = \left( \begin{array}{ccc} \mathbf{x}_0^T & \mathbf{x}_1^T & \ldots \end{array} \right)^T\;`. ### Response: def xstep(self): r"""Minimise Augmen...
def prepare_request(self, *args, **kw): """ creates a full featured HTTPRequest objects """ self.http_request = self.request_class(self.path, *args, **kw)
creates a full featured HTTPRequest objects
Below is the the instruction that describes the task: ### Input: creates a full featured HTTPRequest objects ### Response: def prepare_request(self, *args, **kw): """ creates a full featured HTTPRequest objects """ self.http_request = self.request_class(self.path, *args, **kw)
def rotation_from_axis_and_origin(axis, origin, angle, to_frame='world'): """ Returns a rotation matrix around some arbitrary axis, about the point origin, using Rodrigues Formula Parameters ---------- axis : :obj:`numpy.ndarray` of float 3x1 vector representing whic...
Returns a rotation matrix around some arbitrary axis, about the point origin, using Rodrigues Formula Parameters ---------- axis : :obj:`numpy.ndarray` of float 3x1 vector representing which axis we should be rotating about origin : :obj:`numpy.ndarray` of float ...
Below is the the instruction that describes the task: ### Input: Returns a rotation matrix around some arbitrary axis, about the point origin, using Rodrigues Formula Parameters ---------- axis : :obj:`numpy.ndarray` of float 3x1 vector representing which axis we should be rotat...
async def transfer(self, device: SomeDevice, ensure_playback: bool = False): """Transfer playback to a new device and determine if it should start playing. Parameters ---------- device : :obj:`SomeDevice` The device on which playback should be started/transferred. en...
Transfer playback to a new device and determine if it should start playing. Parameters ---------- device : :obj:`SomeDevice` The device on which playback should be started/transferred. ensure_playback : bool if `True` ensure playback happens on new device. ...
Below is the the instruction that describes the task: ### Input: Transfer playback to a new device and determine if it should start playing. Parameters ---------- device : :obj:`SomeDevice` The device on which playback should be started/transferred. ensure_playback : boo...
def purge_objects(self, request): """ Removes all objects in this table. This action first displays a confirmation page; next, it deletes all objects and redirects back to the change list. """ def truncate_table(model): if settings.TRUNCATE_TABLE_SQL_STATEMEN...
Removes all objects in this table. This action first displays a confirmation page; next, it deletes all objects and redirects back to the change list.
Below is the the instruction that describes the task: ### Input: Removes all objects in this table. This action first displays a confirmation page; next, it deletes all objects and redirects back to the change list. ### Response: def purge_objects(self, request): """ Removes all obj...
def get_group_member_ids(self, group_id, start=None, timeout=None): """Call get group member IDs API. https://devdocs.line.me/en/#get-group-room-member-ids Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the bot as ...
Call get group member IDs API. https://devdocs.line.me/en/#get-group-room-member-ids Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the bot as a friend or has blocked the bot. :param str group_id: Group ID...
Below is the the instruction that describes the task: ### Input: Call get group member IDs API. https://devdocs.line.me/en/#get-group-room-member-ids Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the bot as a friend ...
def wheel(self, fun, **kwargs): ''' Run :ref:`wheel modules <all-salt.wheel>` synchronously Wraps :py:meth:`salt.wheel.WheelClient.master_call`. Note that wheel functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns t...
Run :ref:`wheel modules <all-salt.wheel>` synchronously Wraps :py:meth:`salt.wheel.WheelClient.master_call`. Note that wheel functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns the result from the wheel module
Below is the the instruction that describes the task: ### Input: Run :ref:`wheel modules <all-salt.wheel>` synchronously Wraps :py:meth:`salt.wheel.WheelClient.master_call`. Note that wheel functions must be called using keyword arguments. Positional arguments are not supported. :...
def copy_node(node): """Copy a node but keep its annotations intact.""" if not isinstance(node, gast.AST): return [copy_node(n) for n in node] new_node = copy.deepcopy(node) setattr(new_node, anno.ANNOTATION_FIELD, getattr(node, anno.ANNOTATION_FIELD, {}).copy()) return new_node
Copy a node but keep its annotations intact.
Below is the the instruction that describes the task: ### Input: Copy a node but keep its annotations intact. ### Response: def copy_node(node): """Copy a node but keep its annotations intact.""" if not isinstance(node, gast.AST): return [copy_node(n) for n in node] new_node = copy.deepcopy(node) setat...
def add_arguments(self, parser): """Add command arguments""" parser.add_argument(self._source_param, **self._source_kwargs) parser.add_argument('--base', '-b', action='store', help= 'Supply the base currency as code or a settings variable name. ' 'The default is...
Add command arguments
Below is the the instruction that describes the task: ### Input: Add command arguments ### Response: def add_arguments(self, parser): """Add command arguments""" parser.add_argument(self._source_param, **self._source_kwargs) parser.add_argument('--base', '-b', action='store', he...
def _make_list_or_1d_tensor(values): """Return a list (preferred) or 1d Tensor from values, if values.ndims < 2.""" values = tf.convert_to_tensor(value=values, name='values') values_ = tf.get_static_value(values) # Static didn't work. if values_ is None: # Cheap way to bring to at least 1d. return va...
Return a list (preferred) or 1d Tensor from values, if values.ndims < 2.
Below is the the instruction that describes the task: ### Input: Return a list (preferred) or 1d Tensor from values, if values.ndims < 2. ### Response: def _make_list_or_1d_tensor(values): """Return a list (preferred) or 1d Tensor from values, if values.ndims < 2.""" values = tf.convert_to_tensor(value=values,...
def call(self, func, *args, **kwargs): """ Call a function, resolving any type-hinted arguments. """ guessed_kwargs = self._guess_kwargs(func) for key, val in guessed_kwargs.items(): kwargs.setdefault(key, val) try: return func(*args, **kwargs) ...
Call a function, resolving any type-hinted arguments.
Below is the the instruction that describes the task: ### Input: Call a function, resolving any type-hinted arguments. ### Response: def call(self, func, *args, **kwargs): """ Call a function, resolving any type-hinted arguments. """ guessed_kwargs = self._guess_kwargs(func) ...
def predict_in_frame_coding_effect( variant, transcript, trimmed_cdna_ref, trimmed_cdna_alt, sequence_from_start_codon, cds_offset): """Coding effect of an in-frame nucleotide change Parameters ---------- variant : Variant transcript : Transcript ...
Coding effect of an in-frame nucleotide change Parameters ---------- variant : Variant transcript : Transcript trimmed_cdna_ref : str Reference nucleotides from the coding sequence of the transcript trimmed_cdna_alt : str Nucleotides to insert in place of the reference nucleo...
Below is the the instruction that describes the task: ### Input: Coding effect of an in-frame nucleotide change Parameters ---------- variant : Variant transcript : Transcript trimmed_cdna_ref : str Reference nucleotides from the coding sequence of the transcript trimmed_cdna_alt...
def _prepare_input(expression_data, gene_names, tf_names): """ Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D nump...
Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list...
Below is the the instruction that describes the task: ### Input: Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * ...
def set_sid_attrs(self, sid, **kwargs): """Write all the supplied kwargs as attributes of the sid's file. """ table = self._ensure_ctable(sid) for k, v in kwargs.items(): table.attrs[k] = v
Write all the supplied kwargs as attributes of the sid's file.
Below is the the instruction that describes the task: ### Input: Write all the supplied kwargs as attributes of the sid's file. ### Response: def set_sid_attrs(self, sid, **kwargs): """Write all the supplied kwargs as attributes of the sid's file. """ table = self._ensure_ctable(sid) ...
def finish_review(self, success=True, error=False): """Mark our review as finished.""" if self.set_status: if error: self.github_repo.create_status( state="error", description="Static analysis error! inline-plz failed to run.", ...
Mark our review as finished.
Below is the the instruction that describes the task: ### Input: Mark our review as finished. ### Response: def finish_review(self, success=True, error=False): """Mark our review as finished.""" if self.set_status: if error: self.github_repo.create_status( ...
def on_message(self, ws, reply, *args): """ This method is called by the websocket connection on every message that is received. If we receive a ``notice``, we hand over post-processing and signalling of events to ``process_notice``. """ log.debug("Received me...
This method is called by the websocket connection on every message that is received. If we receive a ``notice``, we hand over post-processing and signalling of events to ``process_notice``.
Below is the the instruction that describes the task: ### Input: This method is called by the websocket connection on every message that is received. If we receive a ``notice``, we hand over post-processing and signalling of events to ``process_notice``. ### Response: def on_mes...
def get_branch(self): """ :return: """ if self.repo.head.is_detached: if os.getenv('GIT_BRANCH'): branch = os.getenv('GIT_BRANCH') elif os.getenv('BRANCH_NAME'): branch = os.getenv('BRANCH_NAME') elif os.getenv('TRAVIS_B...
:return:
Below is the the instruction that describes the task: ### Input: :return: ### Response: def get_branch(self): """ :return: """ if self.repo.head.is_detached: if os.getenv('GIT_BRANCH'): branch = os.getenv('GIT_BRANCH') elif os.getenv('BRANCH_N...
def _filter_and_bucket_subtokens(subtoken_counts, min_count): """Return a bucketed list of subtokens that are filtered by count. Args: subtoken_counts: defaultdict mapping subtokens to their counts min_count: int count used to filter subtokens Returns: List of subtoken sets, where subtokens in set i...
Return a bucketed list of subtokens that are filtered by count. Args: subtoken_counts: defaultdict mapping subtokens to their counts min_count: int count used to filter subtokens Returns: List of subtoken sets, where subtokens in set i have the same length=i.
Below is the the instruction that describes the task: ### Input: Return a bucketed list of subtokens that are filtered by count. Args: subtoken_counts: defaultdict mapping subtokens to their counts min_count: int count used to filter subtokens Returns: List of subtoken sets, where subtokens in set...
def set_random_state(state): """Force-set the state of factory.fuzzy's random generator.""" randgen.state_set = True randgen.setstate(state) faker.generator.random.setstate(state)
Force-set the state of factory.fuzzy's random generator.
Below is the the instruction that describes the task: ### Input: Force-set the state of factory.fuzzy's random generator. ### Response: def set_random_state(state): """Force-set the state of factory.fuzzy's random generator.""" randgen.state_set = True randgen.setstate(state) faker.generator.rando...
def match_exists(self, field, required=True, new_group=False): """Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules using the dot syntax. For example, ``"mdf...
Below is the the instruction that describes the task: ### Input: Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
def create_entity(self): """Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all paren...
Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all parents that are part of it (but ...
Below is the the instruction that describes the task: ### Input: Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object t...
def main(args=None): """Take folder or single file and analyze each.""" if args is None: parser = create_parser() args = parser.parse_args() if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) input_module = input_ma...
Take folder or single file and analyze each.
Below is the the instruction that describes the task: ### Input: Take folder or single file and analyze each. ### Response: def main(args=None): """Take folder or single file and analyze each.""" if args is None: parser = create_parser() args = parser.parse_args() if args.debug: ...
def selection(self, index): """Update selected row.""" self.update() self.isActiveWindow() self._parent.delete_btn.setEnabled(True)
Update selected row.
Below is the the instruction that describes the task: ### Input: Update selected row. ### Response: def selection(self, index): """Update selected row.""" self.update() self.isActiveWindow() self._parent.delete_btn.setEnabled(True)
def update(self): '''Called at regular intervals to poll the mouse position to send continuous commands.''' if self.action_space == 'continuous': # mouse movement only used for continuous action space if self.world_state and self.world_state.is_mission_running: if self.mouse_...
Called at regular intervals to poll the mouse position to send continuous commands.
Below is the the instruction that describes the task: ### Input: Called at regular intervals to poll the mouse position to send continuous commands. ### Response: def update(self): '''Called at regular intervals to poll the mouse position to send continuous commands.''' if self.action_space == 'con...
def vcdTypeInfoForHType(t) -> Tuple[str, int, Callable[[RtlSignalBase, Value], str]]: """ :return: (vcd type name, vcd width) """ if isinstance(t, (SimBitsT, Bits, HBool)): return (VCD_SIG_TYPE.WIRE, t.bit_length(), vcdBitsFormatter) elif isinstance(t, HEnum): return (VCD_SIG_TYPE.RE...
:return: (vcd type name, vcd width)
Below is the the instruction that describes the task: ### Input: :return: (vcd type name, vcd width) ### Response: def vcdTypeInfoForHType(t) -> Tuple[str, int, Callable[[RtlSignalBase, Value], str]]: """ :return: (vcd type name, vcd width) """ if isinstance(t, (SimBitsT, Bits, HBool)): ret...
def default(self, value): """Change of resolver name. :param value: new default value to use. :type value: str or callable :raises: KeyError if value is a string not already registered.""" if value is None: if self: value = list(self.keys())[0] ...
Change of resolver name. :param value: new default value to use. :type value: str or callable :raises: KeyError if value is a string not already registered.
Below is the the instruction that describes the task: ### Input: Change of resolver name. :param value: new default value to use. :type value: str or callable :raises: KeyError if value is a string not already registered. ### Response: def default(self, value): """Change of resolve...
def est_update_covariance(self, modelparams): """ Returns the covariance of the gaussian noise process for one unit step. In the case where the covariance is being learned, the expected covariance matrix is returned. :param modelparams: Shape `(n_models, n_modelparams)`...
Returns the covariance of the gaussian noise process for one unit step. In the case where the covariance is being learned, the expected covariance matrix is returned. :param modelparams: Shape `(n_models, n_modelparams)` shape array of model parameters.
Below is the the instruction that describes the task: ### Input: Returns the covariance of the gaussian noise process for one unit step. In the case where the covariance is being learned, the expected covariance matrix is returned. :param modelparams: Shape `(n_models, n_modelparam...
def _compute_distance_matrix(self): """Compute the full distance matrix on pairs of nodes. The distance map self._dist_matrix is computed from the graph using all_pairs_shortest_path_length. """ if not self.is_connected(): raise CouplingError("coupling graph not conn...
Compute the full distance matrix on pairs of nodes. The distance map self._dist_matrix is computed from the graph using all_pairs_shortest_path_length.
Below is the the instruction that describes the task: ### Input: Compute the full distance matrix on pairs of nodes. The distance map self._dist_matrix is computed from the graph using all_pairs_shortest_path_length. ### Response: def _compute_distance_matrix(self): """Compute the full dis...
def tokenize(self, sentence, normalized=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=normalize_text): # type: (text_type, bool, bool, bool, bool, Callable[[str], str])->Union[List[str], Tokenized...
* What you can do - Call mecab tokenizer, and return tokenized objects
Below is the the instruction that describes the task: ### Input: * What you can do - Call mecab tokenizer, and return tokenized objects ### Response: def tokenize(self, sentence, normalized=True, is_feature=False, is_surface=False, return_...
def posterior(self, x, sigma=1.): """Model is X_1,...,X_n ~ N(theta, sigma^2), theta~self, sigma fixed""" pr0 = 1. / self.scale**2 # prior precision prd = x.size / sigma**2 # data precision varp = 1. / (pr0 + prd) # posterior variance mu = varp * (pr0 * self.loc + prd * x.mean...
Model is X_1,...,X_n ~ N(theta, sigma^2), theta~self, sigma fixed
Below is the the instruction that describes the task: ### Input: Model is X_1,...,X_n ~ N(theta, sigma^2), theta~self, sigma fixed ### Response: def posterior(self, x, sigma=1.): """Model is X_1,...,X_n ~ N(theta, sigma^2), theta~self, sigma fixed""" pr0 = 1. / self.scale**2 # prior precision ...
def get(self, id): """Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group` """ url = utils.urljoin(self.url, id) response = self.session.get(url) return Group(self, **response.data)
Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group`
Below is the the instruction that describes the task: ### Input: Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group` ### Response: def get(self, id): """Get a single group by ID. :param str id: a group ID :...
def extract_twin_values(triples, traits, gender=None): """Calculate the heritability of certain traits in triplets. Parameters ========== triples: (a, b, "Female/Male") triples. The sample IDs are then used to query the traits dictionary. traits: sample_id => value dictionary Retu...
Calculate the heritability of certain traits in triplets. Parameters ========== triples: (a, b, "Female/Male") triples. The sample IDs are then used to query the traits dictionary. traits: sample_id => value dictionary Returns ======= tuples of size 2, that contain paired trai...
Below is the the instruction that describes the task: ### Input: Calculate the heritability of certain traits in triplets. Parameters ========== triples: (a, b, "Female/Male") triples. The sample IDs are then used to query the traits dictionary. traits: sample_id => value dictionary ...
def or_constraint(v=0, sense="maximize"): """ OR constraint""" assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__() model, x, y, z = _init() r = model.addVar("r", "B") model.addConsOr([x,y,z], r) model.addCons(x==v) model.setObjective(r, sense=sense) _optimize("OR", model)
OR constraint
Below is the the instruction that describes the task: ### Input: OR constraint ### Response: def or_constraint(v=0, sense="maximize"): """ OR constraint""" assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__() model, x, y, z = _init() r = model.addVar("r", "B") model.addConsOr([x,y...
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` and obj:`all_methods_P` as a set of...
r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` and obj:`all_methods_P` as a set of methods for which the data ...
Below is the the instruction that describes the task: ### Input: r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` an...
def merge_segments(filename, scan, cleanup=True, sizelimit=0): """ Merges cands/noise pkl files from multiple segments to single cands/noise file. Expects segment cands pkls with have (1) state dict and (2) cands dict. Writes tuple state dict and duple of numpy arrays A single pkl written per scan usin...
Merges cands/noise pkl files from multiple segments to single cands/noise file. Expects segment cands pkls with have (1) state dict and (2) cands dict. Writes tuple state dict and duple of numpy arrays A single pkl written per scan using root name fileroot. if cleanup, it will remove segments after mer...
Below is the the instruction that describes the task: ### Input: Merges cands/noise pkl files from multiple segments to single cands/noise file. Expects segment cands pkls with have (1) state dict and (2) cands dict. Writes tuple state dict and duple of numpy arrays A single pkl written per scan using ...
def call(self, **kwargs): """Call all the functions that have previously been added to the dependency graph in topological and lexicographical order, and then return variables in a ``dict``. You may provide variable values with keyword arguments. These values will be written an...
Call all the functions that have previously been added to the dependency graph in topological and lexicographical order, and then return variables in a ``dict``. You may provide variable values with keyword arguments. These values will be written and can satisfy dependencies. ...
Below is the the instruction that describes the task: ### Input: Call all the functions that have previously been added to the dependency graph in topological and lexicographical order, and then return variables in a ``dict``. You may provide variable values with keyword arguments. These ...
def do_reload(bot, target, cmdargs, server_send=None): """The reloading magic. - First, reload handler.py. - Then make copies of all the handler data we want to keep. - Create a new handler and restore all the data. """ def send(msg): if server_send is not None: server_sen...
The reloading magic. - First, reload handler.py. - Then make copies of all the handler data we want to keep. - Create a new handler and restore all the data.
Below is the the instruction that describes the task: ### Input: The reloading magic. - First, reload handler.py. - Then make copies of all the handler data we want to keep. - Create a new handler and restore all the data. ### Response: def do_reload(bot, target, cmdargs, server_send=None): """The...
def addOutHeaderInfo(self, name, type, namespace, element_type=0, mustUnderstand=0): """Add an output SOAP header description to the call info.""" headerinfo = HeaderInfo(name, type, namespace, element_type) if mustUnderstand: headerinfo.mustUnderstand = 1 ...
Add an output SOAP header description to the call info.
Below is the the instruction that describes the task: ### Input: Add an output SOAP header description to the call info. ### Response: def addOutHeaderInfo(self, name, type, namespace, element_type=0, mustUnderstand=0): """Add an output SOAP header description to the call info.""" ...
def exec_cmd(self, command, **kwargs): """Wrapper method that can be changed in the inheriting classes.""" self._is_allowed_command(command) self._check_command_parameters(**kwargs) return self._exec_cmd(command, **kwargs)
Wrapper method that can be changed in the inheriting classes.
Below is the the instruction that describes the task: ### Input: Wrapper method that can be changed in the inheriting classes. ### Response: def exec_cmd(self, command, **kwargs): """Wrapper method that can be changed in the inheriting classes.""" self._is_allowed_command(command) self._che...
def no_auth(self): """Unset authentication temporarily as a context manager.""" old_basic_auth, self.auth = self.auth, None old_token_auth = self.headers.pop('Authorization', None) yield self.auth = old_basic_auth if old_token_auth: self.headers['Authorizati...
Unset authentication temporarily as a context manager.
Below is the the instruction that describes the task: ### Input: Unset authentication temporarily as a context manager. ### Response: def no_auth(self): """Unset authentication temporarily as a context manager.""" old_basic_auth, self.auth = self.auth, None old_token_auth = self.headers.pop...
def Parse(self, parser_mediator, file_object): """Parses a single file-like object. Args: parser_mediator (ParserMediator): a parser mediator. file_object (dvfvs.FileIO): a file-like object to parse. Raises: UnableToParseFile: when the file cannot be parsed. """ if not file_objec...
Parses a single file-like object. Args: parser_mediator (ParserMediator): a parser mediator. file_object (dvfvs.FileIO): a file-like object to parse. Raises: UnableToParseFile: when the file cannot be parsed.
Below is the the instruction that describes the task: ### Input: Parses a single file-like object. Args: parser_mediator (ParserMediator): a parser mediator. file_object (dvfvs.FileIO): a file-like object to parse. Raises: UnableToParseFile: when the file cannot be parsed. ### Response: ...
def to_array(self): """ Serializes this InputTextMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputTextMessageContent, self).to_array() array['message_text'] = u(self.message_text) # py2: type ...
Serializes this InputTextMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict
Below is the the instruction that describes the task: ### Input: Serializes this InputTextMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict ### Response: def to_array(self): """ Serializes this InputTextMessageContent to a dictionary. ...
def ms_to_datetime(ms, tzinfo=None): """Convert a millisecond time value to an offset-aware Python datetime object.""" if not isinstance(ms, (int, long)): raise TypeError('expected integer, not %s' % type(ms)) if tzinfo is None: tzinfo = mktz() return datetime.datetime.fromtimestamp(ms...
Convert a millisecond time value to an offset-aware Python datetime object.
Below is the the instruction that describes the task: ### Input: Convert a millisecond time value to an offset-aware Python datetime object. ### Response: def ms_to_datetime(ms, tzinfo=None): """Convert a millisecond time value to an offset-aware Python datetime object.""" if not isinstance(ms, (int, long)...
def lmx_moe_h1k_f4k_x32(): """Transformer with mixture of experts. 890M Params.""" hparams = lmx_h1k_f4k() hparams.ffn_layer = "local_moe_tpu" hparams.moe_num_experts = 32 hparams.weight_dtype = "bfloat16" hparams.batch_size = 8192 return hparams
Transformer with mixture of experts. 890M Params.
Below is the the instruction that describes the task: ### Input: Transformer with mixture of experts. 890M Params. ### Response: def lmx_moe_h1k_f4k_x32(): """Transformer with mixture of experts. 890M Params.""" hparams = lmx_h1k_f4k() hparams.ffn_layer = "local_moe_tpu" hparams.moe_num_experts = 32 hp...
def print_log(value_color="", value_noncolor=""): """set the colors for text.""" HEADER = '\033[92m' ENDC = '\033[0m' print(HEADER + value_color + ENDC + str(value_noncolor))
set the colors for text.
Below is the the instruction that describes the task: ### Input: set the colors for text. ### Response: def print_log(value_color="", value_noncolor=""): """set the colors for text.""" HEADER = '\033[92m' ENDC = '\033[0m' print(HEADER + value_color + ENDC + str(value_noncolor))
def get_follows(self, model_or_obj_or_qs): """ Returns all the followers of a model, an object or a queryset. """ fname = self.fname(model_or_obj_or_qs) if isinstance(model_or_obj_or_qs, QuerySet): return self.filter(**{'%s__in' % fname: model_or_obj_or_qs}) ...
Returns all the followers of a model, an object or a queryset.
Below is the the instruction that describes the task: ### Input: Returns all the followers of a model, an object or a queryset. ### Response: def get_follows(self, model_or_obj_or_qs): """ Returns all the followers of a model, an object or a queryset. """ fname = self.fname(model_or...
def GetDefault(self, container=None): """Return boolean value.""" return rdfvalue.RDFBool( super(ProtoBoolean, self).GetDefault(container=container))
Return boolean value.
Below is the the instruction that describes the task: ### Input: Return boolean value. ### Response: def GetDefault(self, container=None): """Return boolean value.""" return rdfvalue.RDFBool( super(ProtoBoolean, self).GetDefault(container=container))
def color_map(cls, group): print("Group %s" % group) """ Change default color behavior. Map certain states always to the same colors (similar to MMS). """ try: state_idx = cls.states.index(group) except ValueError: # on any unexpected stat...
Change default color behavior. Map certain states always to the same colors (similar to MMS).
Below is the the instruction that describes the task: ### Input: Change default color behavior. Map certain states always to the same colors (similar to MMS). ### Response: def color_map(cls, group): print("Group %s" % group) """ Change default color behavior. Map certain ...
def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param ...
Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding ...
Below is the the instruction that describes the task: ### Input: Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overridin...
def category_count(self): """Returns the number of categories in `categories`.""" category_dict = self.categories count_dict = {category: len( category_dict[category]) for category in category_dict} return count_dict
Returns the number of categories in `categories`.
Below is the the instruction that describes the task: ### Input: Returns the number of categories in `categories`. ### Response: def category_count(self): """Returns the number of categories in `categories`.""" category_dict = self.categories count_dict = {category: len( categor...
def clear_all(self): """ Clears (resets) all counters. """ self._lock.acquire() try: self._cache = {} self._updated = False finally: self._lock.release()
Clears (resets) all counters.
Below is the the instruction that describes the task: ### Input: Clears (resets) all counters. ### Response: def clear_all(self): """ Clears (resets) all counters. """ self._lock.acquire() try: self._cache = {} self._updated = False finally: ...
def make_figure_uhs(extractors, what): """ $ oq plot 'uhs?kind=mean&site_id=0' """ import matplotlib.pyplot as plt fig = plt.figure() got = {} # (calc_id, kind) -> curves for i, ex in enumerate(extractors): uhs = ex.get(what) for kind in uhs.kind: got[ex.calc_id,...
$ oq plot 'uhs?kind=mean&site_id=0'
Below is the the instruction that describes the task: ### Input: $ oq plot 'uhs?kind=mean&site_id=0' ### Response: def make_figure_uhs(extractors, what): """ $ oq plot 'uhs?kind=mean&site_id=0' """ import matplotlib.pyplot as plt fig = plt.figure() got = {} # (calc_id, kind) -> curves ...
def vlq2int(data): """Read one VLQ-encoded integer value from an input data stream.""" # The VLQ is little-endian. byte = ord(data.read(1)) value = byte & 0x7F shift = 1 while byte & 0x80 != 0: byte = ord(data.read(1)) value = ((byte & 0x7F) << shift * 7) | value shift +...
Read one VLQ-encoded integer value from an input data stream.
Below is the the instruction that describes the task: ### Input: Read one VLQ-encoded integer value from an input data stream. ### Response: def vlq2int(data): """Read one VLQ-encoded integer value from an input data stream.""" # The VLQ is little-endian. byte = ord(data.read(1)) value = byte & 0x...
def tree2doe(str1): """tree2doe""" retstuff = makedoedict(str1) ddict = makedoetree(retstuff[0], retstuff[1]) ddict = retstuff[0] retstuff[1] = {}# don't need it anymore str1 = ''#just re-using it l1list = list(ddict.keys()) l1list.sort() for i in range(0, len(l1list)): str1...
tree2doe
Below is the the instruction that describes the task: ### Input: tree2doe ### Response: def tree2doe(str1): """tree2doe""" retstuff = makedoedict(str1) ddict = makedoetree(retstuff[0], retstuff[1]) ddict = retstuff[0] retstuff[1] = {}# don't need it anymore str1 = ''#just re-using it l...
def getEdges(self, vertex, inEdges = True, outEdges = True, rawResults = False) : """returns in, out, or both edges liked to a given document. vertex can be either a Document object or a string for an _id. If rawResults a arango results will be return as fetched, if false, will return a liste of Edge ob...
returns in, out, or both edges liked to a given document. vertex can be either a Document object or a string for an _id. If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects
Below is the the instruction that describes the task: ### Input: returns in, out, or both edges liked to a given document. vertex can be either a Document object or a string for an _id. If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects ### Response: def...
async def make_request(self, redirect=False): ''' Acts as the central hub for preparing requests to be sent, and returning them upon completion. Generally just pokes through self's attribs and makes decisions about what to do. Returns: sock: The socket to be returned...
Acts as the central hub for preparing requests to be sent, and returning them upon completion. Generally just pokes through self's attribs and makes decisions about what to do. Returns: sock: The socket to be returned to the calling session's pool. Respon...
Below is the the instruction that describes the task: ### Input: Acts as the central hub for preparing requests to be sent, and returning them upon completion. Generally just pokes through self's attribs and makes decisions about what to do. Returns: sock: The socket to be retur...
def ins2dict(ins, kind=''): """Turn a SQLAlchemy Model instance to dict. :param ins: a SQLAlchemy instance. :param kind: specify which kind of dict tranformer should be called. :return: dict, instance data. If model has defined `to_xxx_dict`, then ins2dict(ins, 'xxx') will call `model.to_xxx_d...
Turn a SQLAlchemy Model instance to dict. :param ins: a SQLAlchemy instance. :param kind: specify which kind of dict tranformer should be called. :return: dict, instance data. If model has defined `to_xxx_dict`, then ins2dict(ins, 'xxx') will call `model.to_xxx_dict()`. Default kind is ''. If...
Below is the the instruction that describes the task: ### Input: Turn a SQLAlchemy Model instance to dict. :param ins: a SQLAlchemy instance. :param kind: specify which kind of dict tranformer should be called. :return: dict, instance data. If model has defined `to_xxx_dict`, then ins2dict(ins, 'x...
def initiate_close(self): """Start closing the sender (won't complete until all data is sent).""" self._running = False self._accumulator.close() self.wakeup()
Start closing the sender (won't complete until all data is sent).
Below is the the instruction that describes the task: ### Input: Start closing the sender (won't complete until all data is sent). ### Response: def initiate_close(self): """Start closing the sender (won't complete until all data is sent).""" self._running = False self._accumulator.close() ...
def showLipds(D=None): """ Display the dataset names of a given LiPD data | Example | lipd.showLipds(D) :pararm dict D: LiPD data :return none: """ if not D: print("Error: LiPD data not provided. Pass LiPD data into the function.") else: print(json.dumps(D.keys(), ...
Display the dataset names of a given LiPD data | Example | lipd.showLipds(D) :pararm dict D: LiPD data :return none:
Below is the the instruction that describes the task: ### Input: Display the dataset names of a given LiPD data | Example | lipd.showLipds(D) :pararm dict D: LiPD data :return none: ### Response: def showLipds(D=None): """ Display the dataset names of a given LiPD data | Example ...
def get_wireframe(viewer, x, y, z, **kwargs): """Produce a compound object of paths implementing a wireframe. x, y, z are expected to be 2D arrays of points making up the mesh. """ # TODO: something like this would make a great utility function # for ginga n, m = x.shape objs = [] for i ...
Produce a compound object of paths implementing a wireframe. x, y, z are expected to be 2D arrays of points making up the mesh.
Below is the the instruction that describes the task: ### Input: Produce a compound object of paths implementing a wireframe. x, y, z are expected to be 2D arrays of points making up the mesh. ### Response: def get_wireframe(viewer, x, y, z, **kwargs): """Produce a compound object of paths implementing a w...
def save_sampleset(self, f, name): '''Serialize the sampleset to file using the HDF5 format. Name is usually in {train, test}.''' f.create_dataset(name + '_encoder_x', data=self.encoder_x) f.create_dataset(name + '_decoder_x', data=self.decoder_x) f.create_dataset(name + '_decoder_y', da...
Serialize the sampleset to file using the HDF5 format. Name is usually in {train, test}.
Below is the the instruction that describes the task: ### Input: Serialize the sampleset to file using the HDF5 format. Name is usually in {train, test}. ### Response: def save_sampleset(self, f, name): '''Serialize the sampleset to file using the HDF5 format. Name is usually in {train, test}.''' f...
def set_admin(msg, handler): """Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified. """ if handler.config['feature']['servicestype'] == "ircservices": match = re.match("STATUS (.*) ([0-3])", msg) elif handler.config['featu...
Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified.
Below is the the instruction that describes the task: ### Input: Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified. ### Response: def set_admin(msg, handler): """Handle admin verification responses from NickServ. | If NickServ tells...
def write_mhd_file(filename, data, shape=None, meta_dict=None): """ Write the `data` and `meta_dict` in two files with names that use `filename` as a prefix. Parameters ---------- filename: str Path to the output file. This is going to be used as a preffix. Two files will be...
Write the `data` and `meta_dict` in two files with names that use `filename` as a prefix. Parameters ---------- filename: str Path to the output file. This is going to be used as a preffix. Two files will be created, one with a '.mhd' extension and another with '.raw'. I...
Below is the the instruction that describes the task: ### Input: Write the `data` and `meta_dict` in two files with names that use `filename` as a prefix. Parameters ---------- filename: str Path to the output file. This is going to be used as a preffix. Two files will be cr...
def copy_dir(src, dst): """ this function will simply copy the file from the source path to the dest path given as input """ try: debug.log("copy dir from "+ src, "to "+ dst) shutil.copytree(src, dst) except Exception as e: debug.log("Error: happened while copying!\n%s\n"%e)
this function will simply copy the file from the source path to the dest path given as input
Below is the the instruction that describes the task: ### Input: this function will simply copy the file from the source path to the dest path given as input ### Response: def copy_dir(src, dst): """ this function will simply copy the file from the source path to the dest path given as input """ try...
def create_chat(self, blogname, **kwargs): """ Create a chat post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a st...
Create a chat post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a...
Below is the the instruction that describes the task: ### Input: Create a chat post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet...
def dataset_resource(self, ref_id, friendly_name=None, description=None, access=None, location=None, project_id=None): """See https://developers.google.com/bigquery/docs/reference/v2/datasets#resource Parameters ---------- ref_id : str Datase...
See https://developers.google.com/bigquery/docs/reference/v2/datasets#resource Parameters ---------- ref_id : str Dataset id (the reference id, not the integer id) friendly_name : str, optional An optional descriptive name for the dataset ...
Below is the the instruction that describes the task: ### Input: See https://developers.google.com/bigquery/docs/reference/v2/datasets#resource Parameters ---------- ref_id : str Dataset id (the reference id, not the integer id) friendly_name : str, optio...
def change_response(x, prob, index): ''' change every response in x that matches 'index' by randomly sampling from prob ''' #pdb.set_trace() N = (x==index).sum() #x[x==index]=9 x[x==index] = dist.sample(N)
change every response in x that matches 'index' by randomly sampling from prob
Below is the the instruction that describes the task: ### Input: change every response in x that matches 'index' by randomly sampling from prob ### Response: def change_response(x, prob, index): ''' change every response in x that matches 'index' by randomly sampling from prob ''' #pdb.set_trace() ...
def scalar_projection(v1, v2): '''compute the scalar projection of v1 upon v2 Args: v1, v2: iterable indices 0, 1, 2 corresponding to cartesian coordinates Returns: 3-vector of the projection of point p onto the direction of v ''' return np.dot(v1, v2) / np.linalg.norm(v2)
compute the scalar projection of v1 upon v2 Args: v1, v2: iterable indices 0, 1, 2 corresponding to cartesian coordinates Returns: 3-vector of the projection of point p onto the direction of v
Below is the the instruction that describes the task: ### Input: compute the scalar projection of v1 upon v2 Args: v1, v2: iterable indices 0, 1, 2 corresponding to cartesian coordinates Returns: 3-vector of the projection of point p onto the direction of v ### Response: def scala...
def UpdateWorkerStatus( self, identifier, status, pid, used_memory, display_name, number_of_consumed_sources, number_of_produced_sources, number_of_consumed_events, number_of_produced_events, number_of_consumed_event_tags, number_of_produced_event_tags, number_of_consumed_reports, number_o...
Updates the status of a worker. Args: identifier (str): worker identifier. status (str): human readable status of the worker e.g. 'Idle'. pid (int): process identifier (PID). used_memory (int): size of used memory in bytes. display_name (str): human readable of the file entry currentl...
Below is the the instruction that describes the task: ### Input: Updates the status of a worker. Args: identifier (str): worker identifier. status (str): human readable status of the worker e.g. 'Idle'. pid (int): process identifier (PID). used_memory (int): size of used memory in bytes...