code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def configure(ctx, integration, args, show_args, editable): """Configure an integration with default parameters. You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required. """ home = ctx.obj["HOME"] integration_path = plugin_utils.get_plugin_path(home...
Configure an integration with default parameters. You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required.
Below is the the instruction that describes the task: ### Input: Configure an integration with default parameters. You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required. ### Response: def configure(ctx, integration, args, show_args, editable): """Configu...
def handle_single_message(self, msg): """ Handle one message and modify the job storage appropriately. :param msg: the message to handle :return: None """ job_id = msg.message['job_id'] actual_msg = msg.message if msg.type == MessageType.JOB_UPDATED: ...
Handle one message and modify the job storage appropriately. :param msg: the message to handle :return: None
Below is the the instruction that describes the task: ### Input: Handle one message and modify the job storage appropriately. :param msg: the message to handle :return: None ### Response: def handle_single_message(self, msg): """ Handle one message and modify the job storage appropr...
def RunValidationOutputToConsole(feed, options): """Validate feed, print reports and return an exit code.""" accumulator = CountingConsoleProblemAccumulator( options.error_types_ignore_list) problems = transitfeed.ProblemReporter(accumulator) _, exit_code = RunValidation(feed, options, problems) return ...
Validate feed, print reports and return an exit code.
Below is the the instruction that describes the task: ### Input: Validate feed, print reports and return an exit code. ### Response: def RunValidationOutputToConsole(feed, options): """Validate feed, print reports and return an exit code.""" accumulator = CountingConsoleProblemAccumulator( options.error_...
def search_all(self, template: str) -> _Result: """Search the :class:`Element <Element>` (multiple times) for the given parse template. :param template: The Parse template to use. """ return [r for r in findall(template, self.html)]
Search the :class:`Element <Element>` (multiple times) for the given parse template. :param template: The Parse template to use.
Below is the the instruction that describes the task: ### Input: Search the :class:`Element <Element>` (multiple times) for the given parse template. :param template: The Parse template to use. ### Response: def search_all(self, template: str) -> _Result: """Search the :class:`Element <Ele...
def _function_has_n_args(self, func, n): """ Returns true if func has n arguments. Arguments with default and self for methods are not considered. """ if inspect.ismethod(func): n += 1 argspec = inspect.getargspec(func) defaults = argspec.defaults or ...
Returns true if func has n arguments. Arguments with default and self for methods are not considered.
Below is the the instruction that describes the task: ### Input: Returns true if func has n arguments. Arguments with default and self for methods are not considered. ### Response: def _function_has_n_args(self, func, n): """ Returns true if func has n arguments. Arguments with default and ...
def _versioned_lib_suffix(env, suffix, version): """Generate versioned shared library suffix from a unversioned one. If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll'""" Verbose = False if Verbose: print("_versioned_lib_suffix: suffix= ", suffix) print("_versioned_li...
Generate versioned shared library suffix from a unversioned one. If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll
Below is the the instruction that describes the task: ### Input: Generate versioned shared library suffix from a unversioned one. If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll ### Response: def _versioned_lib_suffix(env, suffix, version): """Generate versioned shared library suffix ...
def _create_out_partition(self, tenant_id, tenant_name): """Function to create a service partition. """ vrf_prof_str = self.serv_part_vrf_prof self.dcnm_obj.create_partition(tenant_name, fw_const.SERV_PART_NAME, None, vrf_prof_str, ...
Function to create a service partition.
Below is the the instruction that describes the task: ### Input: Function to create a service partition. ### Response: def _create_out_partition(self, tenant_id, tenant_name): """Function to create a service partition. """ vrf_prof_str = self.serv_part_vrf_prof self.dcnm_obj.create_partitio...
def wrap_inference_results(inference_result_proto): """Returns packaged inference results from the provided proto. Args: inference_result_proto: The classification or regression response proto. Returns: An InferenceResult proto with the result from the response. """ inference_proto = inference_pb2.I...
Returns packaged inference results from the provided proto. Args: inference_result_proto: The classification or regression response proto. Returns: An InferenceResult proto with the result from the response.
Below is the the instruction that describes the task: ### Input: Returns packaged inference results from the provided proto. Args: inference_result_proto: The classification or regression response proto. Returns: An InferenceResult proto with the result from the response. ### Response: def wrap_infer...
def getHostCertPath(self, name): ''' Gets the path to a host certificate. Args: name (str): The name of the host keypair. Examples: Get the path to the host certificate for the host "myhost": mypath = cdir.getHostCertPath('myhost') Retu...
Gets the path to a host certificate. Args: name (str): The name of the host keypair. Examples: Get the path to the host certificate for the host "myhost": mypath = cdir.getHostCertPath('myhost') Returns: str: The path if exists.
Below is the the instruction that describes the task: ### Input: Gets the path to a host certificate. Args: name (str): The name of the host keypair. Examples: Get the path to the host certificate for the host "myhost": mypath = cdir.getHostCertPath('myhost...
def save_file(self, obj): """Save a file""" try: import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute except ImportError: import io as pystringIO if not hasattr(obj, 'name') or not hasattr(obj, 'mode'): raise pickle.Pi...
Save a file
Below is the the instruction that describes the task: ### Input: Save a file ### Response: def save_file(self, obj): """Save a file""" try: import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute except ImportError: import io as pystringI...
def ensure_matplotlib_figure(obj): """Extract the current figure from a matplotlib object or return the object if it's a figure. raises ValueError if the object can't be converted. """ import matplotlib from matplotlib.figure import Figure if obj == matplotlib.pyplot: obj = obj.gcf() ...
Extract the current figure from a matplotlib object or return the object if it's a figure. raises ValueError if the object can't be converted.
Below is the the instruction that describes the task: ### Input: Extract the current figure from a matplotlib object or return the object if it's a figure. raises ValueError if the object can't be converted. ### Response: def ensure_matplotlib_figure(obj): """Extract the current figure from a matplotlib ob...
def info(self, auth, resource, options={}, defer=False): """ Request creation and usage information of specified resource according to the specified options. Args: auth: <cik> resource: Alias or ID of resource options: Options to define what info you would li...
Request creation and usage information of specified resource according to the specified options. Args: auth: <cik> resource: Alias or ID of resource options: Options to define what info you would like returned.
Below is the the instruction that describes the task: ### Input: Request creation and usage information of specified resource according to the specified options. Args: auth: <cik> resource: Alias or ID of resource options: Options to define what info you would li...
def _containing_contigs(self, hits): '''Given a list of hits, all with same query, returns a set of the contigs containing that query''' return {hit.ref_name for hit in hits if self._contains(hit)}
Given a list of hits, all with same query, returns a set of the contigs containing that query
Below is the the instruction that describes the task: ### Input: Given a list of hits, all with same query, returns a set of the contigs containing that query ### Response: def _containing_contigs(self, hits): '''Given a list of hits, all with same query, returns a set of the contigs ...
def resolve_rva(self, rva): """ RVAs are supposed to be used with the image of the file in memory. There's no direct algorithm to calculate the offset of an RVA in the file. What we do here is to find the section that contains the RVA and then we calc...
RVAs are supposed to be used with the image of the file in memory. There's no direct algorithm to calculate the offset of an RVA in the file. What we do here is to find the section that contains the RVA and then we calculate the offset between the RVA of the section ...
Below is the the instruction that describes the task: ### Input: RVAs are supposed to be used with the image of the file in memory. There's no direct algorithm to calculate the offset of an RVA in the file. What we do here is to find the section that contains the RVA and ...
def load_general(self): """|coro| Loads the players general stats""" stats = yield from self._fetch_statistics("generalpvp_timeplayed", "generalpvp_matchplayed", "generalpvp_matchwon", "generalpvp_matchlost", "generalpvp_kills", "generalpvp_dea...
|coro| Loads the players general stats
Below is the the instruction that describes the task: ### Input: |coro| Loads the players general stats ### Response: def load_general(self): """|coro| Loads the players general stats""" stats = yield from self._fetch_statistics("generalpvp_timeplayed", "generalpvp_matchplayed", ...
def apply_stats(self, statsUpdates): """ compute stats and update/apply the new stats to the running average """ def updateAccumStats(): if self._full_stats_init: return tf.cond(tf.greater(self.sgd_step, self._cold_iter), lambda: tf.group(*self._apply_stats(statsUpda...
compute stats and update/apply the new stats to the running average
Below is the the instruction that describes the task: ### Input: compute stats and update/apply the new stats to the running average ### Response: def apply_stats(self, statsUpdates): """ compute stats and update/apply the new stats to the running average """ def updateAccumStats(): ...
def list(per_page=None, page=None): """ List of payments. You have to handle pagination manually :param page: the page number :type page: int|None :param per_page: number of payment per page. It's a good practice to increase this number if you know that you will need a l...
List of payments. You have to handle pagination manually :param page: the page number :type page: int|None :param per_page: number of payment per page. It's a good practice to increase this number if you know that you will need a lot of payments. :type per_page: int|None ...
Below is the the instruction that describes the task: ### Input: List of payments. You have to handle pagination manually :param page: the page number :type page: int|None :param per_page: number of payment per page. It's a good practice to increase this number if you know that you ...
def update(): ''' Execute an svn update on all of the repos ''' # data for the fileserver event data = {'changed': False, 'backend': 'svnfs'} # _clear_old_remotes runs init(), so use the value from there to avoid a # second init() data['changed'], repos = _clear_old_remotes()...
Execute an svn update on all of the repos
Below is the the instruction that describes the task: ### Input: Execute an svn update on all of the repos ### Response: def update(): ''' Execute an svn update on all of the repos ''' # data for the fileserver event data = {'changed': False, 'backend': 'svnfs'} # _clear_old_rem...
def next_request(self): ''' Logic to handle getting a new url request, from a bunch of different queues ''' t = time.time() # update the redis queues every so often if t - self.update_time > self.update_interval: self.update_time = t self.c...
Logic to handle getting a new url request, from a bunch of different queues
Below is the the instruction that describes the task: ### Input: Logic to handle getting a new url request, from a bunch of different queues ### Response: def next_request(self): ''' Logic to handle getting a new url request, from a bunch of different queues ''' t = ...
def main(*argv): """ main driver of program """ try: adminUsername = argv[0] adminPassword = argv[1] siteURL = argv[2] deleteUser = argv[3] # Logic # sh = arcrest.AGOLTokenSecurityHandler(adminUsername, adminPassword) admin = arcrest.manageorg.Ad...
main driver of program
Below is the the instruction that describes the task: ### Input: main driver of program ### Response: def main(*argv): """ main driver of program """ try: adminUsername = argv[0] adminPassword = argv[1] siteURL = argv[2] deleteUser = argv[3] # Logic # ...
def _strip_consts(graph_def, max_const_size=32): """Strip large constant values from graph_def. This is mostly a utility function for graph(), and also originates here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb """ strip_def = tf.Gr...
Strip large constant values from graph_def. This is mostly a utility function for graph(), and also originates here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
Below is the the instruction that describes the task: ### Input: Strip large constant values from graph_def. This is mostly a utility function for graph(), and also originates here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb ### Response: d...
def bind(self, callback): """Bind a ``callback`` to this event. """ handlers = self._handlers if self._self is None: raise RuntimeError('%s already fired, cannot add callbacks' % self) if handlers is None: handlers = [] self._handlers = handler...
Bind a ``callback`` to this event.
Below is the the instruction that describes the task: ### Input: Bind a ``callback`` to this event. ### Response: def bind(self, callback): """Bind a ``callback`` to this event. """ handlers = self._handlers if self._self is None: raise RuntimeError('%s already fired, ca...
def broadcast_tx(self, address, amount, secret, secondsecret=None, vendorfield=''): """broadcasts a transaction to the peerslist using ark-js library""" peer = random.choice(self.PEERS) park = Park( peer, 4001, constants.ARK_NETHASH, '1.1.1' ...
broadcasts a transaction to the peerslist using ark-js library
Below is the the instruction that describes the task: ### Input: broadcasts a transaction to the peerslist using ark-js library ### Response: def broadcast_tx(self, address, amount, secret, secondsecret=None, vendorfield=''): """broadcasts a transaction to the peerslist using ark-js library""" pee...
def _nanmean_ddof_object(ddof, value, axis=None, **kwargs): """ In house nanmean. ddof argument will be used in _nanvar method """ from .duck_array_ops import (count, fillna, _dask_or_eager_func, where_method) valid_count = count(value, axis=axis) value = fillna(value, ...
In house nanmean. ddof argument will be used in _nanvar method
Below is the the instruction that describes the task: ### Input: In house nanmean. ddof argument will be used in _nanvar method ### Response: def _nanmean_ddof_object(ddof, value, axis=None, **kwargs): """ In house nanmean. ddof argument will be used in _nanvar method """ from .duck_array_ops import (count...
def PermissiveDict(fields=None): '''A permissive dict will permit the user to partially specify the permitted fields. Any fields that are specified and passed in will be type checked. Other fields will be allowed, but will be ignored by the type checker. ''' if fields: check_user_facing_fie...
A permissive dict will permit the user to partially specify the permitted fields. Any fields that are specified and passed in will be type checked. Other fields will be allowed, but will be ignored by the type checker.
Below is the the instruction that describes the task: ### Input: A permissive dict will permit the user to partially specify the permitted fields. Any fields that are specified and passed in will be type checked. Other fields will be allowed, but will be ignored by the type checker. ### Response: def Permi...
def make_insert(cls, table, insert_tuple): """ [Deprecated] Make INSERT query. :param str table: Table name of executing the query. :param list/tuple insert_tuple: Insertion data. :return: Query of SQLite. :rtype: str :raises ValueError: If ``insert_tuple`` is em...
[Deprecated] Make INSERT query. :param str table: Table name of executing the query. :param list/tuple insert_tuple: Insertion data. :return: Query of SQLite. :rtype: str :raises ValueError: If ``insert_tuple`` is empty |list|/|tuple|. :raises simplesqlite.NameValidation...
Below is the the instruction that describes the task: ### Input: [Deprecated] Make INSERT query. :param str table: Table name of executing the query. :param list/tuple insert_tuple: Insertion data. :return: Query of SQLite. :rtype: str :raises ValueError: If ``insert_tuple``...
def p_Interface(p): """Interface : interface IDENTIFIER Inheritance "{" InterfaceMembers "}" ";" """ p[0] = model.Interface(name=p[2], parent=p[3], members=p[5])
Interface : interface IDENTIFIER Inheritance "{" InterfaceMembers "}" ";"
Below is the the instruction that describes the task: ### Input: Interface : interface IDENTIFIER Inheritance "{" InterfaceMembers "}" ";" ### Response: def p_Interface(p): """Interface : interface IDENTIFIER Inheritance "{" InterfaceMembers "}" ";" """ p[0] = model.Interface(name=p[2], parent=p[3], members=...
def format_numbers(data, headers, column_types=(), integer_format=None, float_format=None, **_): """Format numbers according to a format specification. This uses Python's format specification to format numbers of the following types: :class:`int`, :class:`py2:long` (Python 2), :class:`fl...
Format numbers according to a format specification. This uses Python's format specification to format numbers of the following types: :class:`int`, :class:`py2:long` (Python 2), :class:`float`, and :class:`~decimal.Decimal`. See the :ref:`python:formatspec` for more information about the format strings...
Below is the the instruction that describes the task: ### Input: Format numbers according to a format specification. This uses Python's format specification to format numbers of the following types: :class:`int`, :class:`py2:long` (Python 2), :class:`float`, and :class:`~decimal.Decimal`. See the :ref:...
def django_pre_2_0_table_context( request, table, links=None, paginate_by=None, page=None, extra_context=None, paginator=None, show_hits=False, hit_label='Items'): """ :type table: Table """ if extra_context is None: # pragma: no c...
:type table: Table
Below is the the instruction that describes the task: ### Input: :type table: Table ### Response: def django_pre_2_0_table_context( request, table, links=None, paginate_by=None, page=None, extra_context=None, paginator=None, show_hits=False, h...
def transform_y(self, tfms:TfmList=None, **kwargs): "Set `tfms` to be applied to the targets only." _check_kwargs(self.y, tfms, **kwargs) self.tfm_y=True if tfms is None: self.tfms_y = list(filter(lambda t: t.use_on_y, listify(self.tfms))) self.tfmargs_y = {**self...
Set `tfms` to be applied to the targets only.
Below is the the instruction that describes the task: ### Input: Set `tfms` to be applied to the targets only. ### Response: def transform_y(self, tfms:TfmList=None, **kwargs): "Set `tfms` to be applied to the targets only." _check_kwargs(self.y, tfms, **kwargs) self.tfm_y=True if t...
def get_block_info(self, blocktype, db_number): """Returns the block information for the specified block.""" blocktype = snap7.snap7types.block_types.get(blocktype) if not blocktype: raise Snap7Exception("The blocktype parameter was invalid") logger.debug("retrieving block...
Returns the block information for the specified block.
Below is the the instruction that describes the task: ### Input: Returns the block information for the specified block. ### Response: def get_block_info(self, blocktype, db_number): """Returns the block information for the specified block.""" blocktype = snap7.snap7types.block_types.get(blocktype)...
def CheckBlobsExist(self, blob_ids): """Check if blobs for the given digests already exist.""" res = {blob_id: False for blob_id in blob_ids} urns = {self._BlobUrn(blob_id): blob_id for blob_id in blob_ids} existing = aff4.FACTORY.MultiOpen( urns, aff4_type=aff4.AFF4MemoryStreamBase, mode="r")...
Check if blobs for the given digests already exist.
Below is the the instruction that describes the task: ### Input: Check if blobs for the given digests already exist. ### Response: def CheckBlobsExist(self, blob_ids): """Check if blobs for the given digests already exist.""" res = {blob_id: False for blob_id in blob_ids} urns = {self._BlobUrn(blob_id...
def _extractCreations(self, dataSets): """ Find the elements of C{dataSets} which represent the creation of new objects. @param dataSets: C{list} of C{dict} mapping C{unicode} form submission keys to form submission values. @return: iterator of C{tuple}s with the fi...
Find the elements of C{dataSets} which represent the creation of new objects. @param dataSets: C{list} of C{dict} mapping C{unicode} form submission keys to form submission values. @return: iterator of C{tuple}s with the first element giving the opaque identifier of an ...
Below is the the instruction that describes the task: ### Input: Find the elements of C{dataSets} which represent the creation of new objects. @param dataSets: C{list} of C{dict} mapping C{unicode} form submission keys to form submission values. @return: iterator of C{tuple}s w...
def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs
Format options
Below is the the instruction that describes the task: ### Input: Format options ### Response: def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?...
def walkable(self, x, y): """ check, if the tile is inside grid and if it is set as walkable """ return self.inside(x, y) and self.nodes[y][x].walkable
check, if the tile is inside grid and if it is set as walkable
Below is the the instruction that describes the task: ### Input: check, if the tile is inside grid and if it is set as walkable ### Response: def walkable(self, x, y): """ check, if the tile is inside grid and if it is set as walkable """ return self.inside(x, y) and self.nodes[y][x...
def process_pem(self, data, name): """ PEM processing - splitting further by the type of the records :param data: :param name: :return: """ try: ret = [] data = to_string(data) parts = re.split(r'-----BEGIN', data) i...
PEM processing - splitting further by the type of the records :param data: :param name: :return:
Below is the the instruction that describes the task: ### Input: PEM processing - splitting further by the type of the records :param data: :param name: :return: ### Response: def process_pem(self, data, name): """ PEM processing - splitting further by the type of the record...
def apply_upstring(upstring, component_list): """Update the dictionaries resulting from ``parse_array_start`` with the "up" key based on the upstring returned from ``parse_upstring``. The function assumes that the upstring and component_list parameters passed in are from the same device array stanza of...
Update the dictionaries resulting from ``parse_array_start`` with the "up" key based on the upstring returned from ``parse_upstring``. The function assumes that the upstring and component_list parameters passed in are from the same device array stanza of a ``/proc/mdstat`` file. The function modif...
Below is the the instruction that describes the task: ### Input: Update the dictionaries resulting from ``parse_array_start`` with the "up" key based on the upstring returned from ``parse_upstring``. The function assumes that the upstring and component_list parameters passed in are from the same device...
def load_bytecode_definitions(*, path=None) -> dict: """Load bytecode definitions from JSON file. If no path is provided the default bytecode.json will be loaded. :param path: Either None or a path to a JSON file to load containing bytecode definitions. """ if path is not None: ...
Load bytecode definitions from JSON file. If no path is provided the default bytecode.json will be loaded. :param path: Either None or a path to a JSON file to load containing bytecode definitions.
Below is the the instruction that describes the task: ### Input: Load bytecode definitions from JSON file. If no path is provided the default bytecode.json will be loaded. :param path: Either None or a path to a JSON file to load containing bytecode definitions. ### Response: def load_by...
def sort_by_z(self): """Return a new :class:`PseudoTable` with pseudos sorted by Z""" return self.__class__(sorted(self, key=lambda p: p.Z))
Return a new :class:`PseudoTable` with pseudos sorted by Z
Below is the the instruction that describes the task: ### Input: Return a new :class:`PseudoTable` with pseudos sorted by Z ### Response: def sort_by_z(self): """Return a new :class:`PseudoTable` with pseudos sorted by Z""" return self.__class__(sorted(self, key=lambda p: p.Z))
def scroll_to_beginning_vertically(self, steps=10, *args,**selectors): """ Scroll the object which has *selectors* attributes to *beginning* vertically. See `Scroll Forward Vertically` for more details. """ return self.device(**selectors).scroll.vert.toBeginning(steps=steps)
Scroll the object which has *selectors* attributes to *beginning* vertically. See `Scroll Forward Vertically` for more details.
Below is the the instruction that describes the task: ### Input: Scroll the object which has *selectors* attributes to *beginning* vertically. See `Scroll Forward Vertically` for more details. ### Response: def scroll_to_beginning_vertically(self, steps=10, *args,**selectors): """ Scroll t...
def listPrimaryDatasets(self, primary_ds_name="", primary_ds_type=""): """ Returns all primary dataset if primary_ds_name or primary_ds_type are not passed. """ conn = self.dbi.connection() try: result = self.primdslist.execute(conn, primary_ds_name, primary_ds_type) ...
Returns all primary dataset if primary_ds_name or primary_ds_type are not passed.
Below is the the instruction that describes the task: ### Input: Returns all primary dataset if primary_ds_name or primary_ds_type are not passed. ### Response: def listPrimaryDatasets(self, primary_ds_name="", primary_ds_type=""): """ Returns all primary dataset if primary_ds_name or primary_ds_ty...
def binom_est_error(p, N, hedge = float(0)): r""" """ # asymptotic np.sqrt(p * (1 - p) / N) return np.sqrt(p*(1-p)/(N+2*hedge+1))
r"""
Below is the the instruction that describes the task: ### Input: r""" ### Response: def binom_est_error(p, N, hedge = float(0)): r""" """ # asymptotic np.sqrt(p * (1 - p) / N) return np.sqrt(p*(1-p)/(N+2*hedge+1))
def requestPositionUpdates(self, subscribe=True): """ Request/cancel request real-time position data for all accounts. """ if self.subscribePositions != subscribe: self.subscribePositions = subscribe if subscribe == True: self.ibConn.reqPositions() els...
Request/cancel request real-time position data for all accounts.
Below is the the instruction that describes the task: ### Input: Request/cancel request real-time position data for all accounts. ### Response: def requestPositionUpdates(self, subscribe=True): """ Request/cancel request real-time position data for all accounts. """ if self.subscribePositions != su...
def transform(fields, function, *tables): "Return a new table based on other tables and a transformation function" new_table = Table(fields=fields) for table in tables: for row in filter(bool, map(lambda row: function(row, table), table)): new_table.append(row) return new_table
Return a new table based on other tables and a transformation function
Below is the the instruction that describes the task: ### Input: Return a new table based on other tables and a transformation function ### Response: def transform(fields, function, *tables): "Return a new table based on other tables and a transformation function" new_table = Table(fields=fields) for...
def hv_mv_station_load(network): """ Checks for over-loading of HV/MV station. Parameters ---------- network : :class:`~.grid.network.Network` Returns ------- :pandas:`pandas.DataFrame<dataframe>` Dataframe containing over-loaded HV/MV stations, their apparent power at ...
Checks for over-loading of HV/MV station. Parameters ---------- network : :class:`~.grid.network.Network` Returns ------- :pandas:`pandas.DataFrame<dataframe>` Dataframe containing over-loaded HV/MV stations, their apparent power at maximal over-loading and the corresponding ti...
Below is the the instruction that describes the task: ### Input: Checks for over-loading of HV/MV station. Parameters ---------- network : :class:`~.grid.network.Network` Returns ------- :pandas:`pandas.DataFrame<dataframe>` Dataframe containing over-loaded HV/MV stations, their ap...
def to_utc_datetime(self, value): """ from value to datetime with tzinfo format (datetime.datetime instance) """ value = self.to_naive_datetime(value) if timezone.is_naive(value): value = timezone.make_aware(value, timezone.utc) else: value = time...
from value to datetime with tzinfo format (datetime.datetime instance)
Below is the the instruction that describes the task: ### Input: from value to datetime with tzinfo format (datetime.datetime instance) ### Response: def to_utc_datetime(self, value): """ from value to datetime with tzinfo format (datetime.datetime instance) """ value = self.to_naiv...
def is_clockwise(vertices): """ Evaluate whether vertices are in clockwise order. Args: vertices: list of vertices (x, y) in polygon. Returns: True: clockwise, False: counter-clockwise Raises: ValueError: the polygon is complex or overlapped. """ it = iterator.consecutive(cycle...
Evaluate whether vertices are in clockwise order. Args: vertices: list of vertices (x, y) in polygon. Returns: True: clockwise, False: counter-clockwise Raises: ValueError: the polygon is complex or overlapped.
Below is the the instruction that describes the task: ### Input: Evaluate whether vertices are in clockwise order. Args: vertices: list of vertices (x, y) in polygon. Returns: True: clockwise, False: counter-clockwise Raises: ValueError: the polygon is complex or overlapped. ### Respon...
def copy(self, deep=False): """Returns a copy of the list Parameters ---------- deep: bool If False (default), only the list is copied and not the contained arrays, otherwise the contained arrays are deep copied""" if not deep: return self.__c...
Returns a copy of the list Parameters ---------- deep: bool If False (default), only the list is copied and not the contained arrays, otherwise the contained arrays are deep copied
Below is the the instruction that describes the task: ### Input: Returns a copy of the list Parameters ---------- deep: bool If False (default), only the list is copied and not the contained arrays, otherwise the contained arrays are deep copied ### Response: def co...
def request(self, cmds): """ Single Execution element is permitted. cmds can be a list or single command """ if isinstance(cmds, list): cmd = '\n'.join(cmds) elif isinstance(cmds, str) or isinstance(cmds, unicode): cmd = cmds node = etree....
Single Execution element is permitted. cmds can be a list or single command
Below is the the instruction that describes the task: ### Input: Single Execution element is permitted. cmds can be a list or single command ### Response: def request(self, cmds): """ Single Execution element is permitted. cmds can be a list or single command """ if ...
def interpolate(self, factor, minGlyph, maxGlyph, round=True, suppressError=True): """ Interpolate the contents of this glyph at location ``factor`` in a linear interpolation between ``minGlyph`` and ``maxGlyph``. >>> glyph.interpolate(0.5, otherGlyph1, otherGlyp...
Interpolate the contents of this glyph at location ``factor`` in a linear interpolation between ``minGlyph`` and ``maxGlyph``. >>> glyph.interpolate(0.5, otherGlyph1, otherGlyph2) ``factor`` may be a :ref:`type-int-float` or a tuple containing two :ref:`type-int-float` values repre...
Below is the the instruction that describes the task: ### Input: Interpolate the contents of this glyph at location ``factor`` in a linear interpolation between ``minGlyph`` and ``maxGlyph``. >>> glyph.interpolate(0.5, otherGlyph1, otherGlyph2) ``factor`` may be a :ref:`type-int-float`...
async def on_shutdown(self, app): """ Graceful shutdown handler See https://docs.aiohttp.org/en/stable/web.html#graceful-shutdown """ for ws in self.clients.copy(): await ws.close(code=WSCloseCode.GOING_AWAY, message='Server shutdown') ...
Graceful shutdown handler See https://docs.aiohttp.org/en/stable/web.html#graceful-shutdown
Below is the the instruction that describes the task: ### Input: Graceful shutdown handler See https://docs.aiohttp.org/en/stable/web.html#graceful-shutdown ### Response: async def on_shutdown(self, app): """ Graceful shutdown handler See https://docs.aiohttp.org/en/stable/web.htm...
def get_vid_from_url(url): """Extracts video ID from URL. """ return match1(url, r'youtu\.be/([^?/]+)') or \ match1(url, r'youtube\.com/embed/([^/?]+)') or \ match1(url, r'youtube\.com/v/([^/?]+)') or \ match1(url, r'youtube\.com/watch/([^/?]+)') or \ pars...
Extracts video ID from URL.
Below is the the instruction that describes the task: ### Input: Extracts video ID from URL. ### Response: def get_vid_from_url(url): """Extracts video ID from URL. """ return match1(url, r'youtu\.be/([^?/]+)') or \ match1(url, r'youtube\.com/embed/([^/?]+)') or \ match1...
def sys_names(self): """ Return a list of unique systematic names from OverallSys and HistoSys """ names = {} for osys in self.overall_sys: names[osys.name] = None for hsys in self.histo_sys: names[hsys.name] = None return names.keys()
Return a list of unique systematic names from OverallSys and HistoSys
Below is the the instruction that describes the task: ### Input: Return a list of unique systematic names from OverallSys and HistoSys ### Response: def sys_names(self): """ Return a list of unique systematic names from OverallSys and HistoSys """ names = {} for osys in self...
def get_cluster(self, name, project_id=None, retry=DEFAULT, timeout=DEFAULT): """ Gets details of specified cluster :param name: The name of the cluster to retrieve :type name: str :param project_id: Google Cloud Platform project ID :type project_id: str :param r...
Gets details of specified cluster :param name: The name of the cluster to retrieve :type name: str :param project_id: Google Cloud Platform project ID :type project_id: str :param retry: A retry object used to retry requests. If None is specified, requests will not b...
Below is the the instruction that describes the task: ### Input: Gets details of specified cluster :param name: The name of the cluster to retrieve :type name: str :param project_id: Google Cloud Platform project ID :type project_id: str :param retry: A retry object used to ...
def _shallow_clone(self, ref, git_cmd): # pragma: windows no cover """Perform a shallow clone of a repository and its submodules """ git_config = 'protocol.version=2' git_cmd('-c', git_config, 'fetch', 'origin', ref, '--depth=1') git_cmd('checkout', ref) git_cmd( '-...
Perform a shallow clone of a repository and its submodules
Below is the the instruction that describes the task: ### Input: Perform a shallow clone of a repository and its submodules ### Response: def _shallow_clone(self, ref, git_cmd): # pragma: windows no cover """Perform a shallow clone of a repository and its submodules """ git_config = 'protocol.ver...
def inject_params(self, params): """Inject params into sys.argv from secureParams API, AOT, or user provided. Args: params (dict): A dictionary containing all parameters that need to be injected as args. """ for arg, value in params.items(): cli_arg = '--{}'.for...
Inject params into sys.argv from secureParams API, AOT, or user provided. Args: params (dict): A dictionary containing all parameters that need to be injected as args.
Below is the the instruction that describes the task: ### Input: Inject params into sys.argv from secureParams API, AOT, or user provided. Args: params (dict): A dictionary containing all parameters that need to be injected as args. ### Response: def inject_params(self, params): """Inj...
def send(self, stream=False): """Send the HTTP request via Python Requests modules. This method will send the request to the remote endpoint. It will try to handle temporary communications issues by retrying the request automatically. Args: stream (bool): Boolean to enable...
Send the HTTP request via Python Requests modules. This method will send the request to the remote endpoint. It will try to handle temporary communications issues by retrying the request automatically. Args: stream (bool): Boolean to enable stream download. Returns: ...
Below is the the instruction that describes the task: ### Input: Send the HTTP request via Python Requests modules. This method will send the request to the remote endpoint. It will try to handle temporary communications issues by retrying the request automatically. Args: stre...
def distro_check(): """Return a string containing the distro package manager.""" distro_data = platform.linux_distribution() distro = [d.lower() for d in distro_data if d.isalpha()] if any(['ubuntu' in distro, 'debian' in distro]) is True: return 'apt' elif any(['centos' in distro, 'redhat'...
Return a string containing the distro package manager.
Below is the the instruction that describes the task: ### Input: Return a string containing the distro package manager. ### Response: def distro_check(): """Return a string containing the distro package manager.""" distro_data = platform.linux_distribution() distro = [d.lower() for d in distro_data if ...
def add_link_to_self(self, source, weight): """ Create and add a ``Link`` from a source node to ``self``. Args: source (Node): The node that will own the new ``Link`` pointing to ``self`` weight (int or float): The weight of the newly created ``Link`` ...
Create and add a ``Link`` from a source node to ``self``. Args: source (Node): The node that will own the new ``Link`` pointing to ``self`` weight (int or float): The weight of the newly created ``Link`` Returns: None Example: >>> node_1 = N...
Below is the the instruction that describes the task: ### Input: Create and add a ``Link`` from a source node to ``self``. Args: source (Node): The node that will own the new ``Link`` pointing to ``self`` weight (int or float): The weight of the newly created ``Link`...
def _author_uid_get(post): """Get the UID of the post author. :param Post post: The post object to determine authorship of :return: Author UID :rtype: str """ u = post.meta('author.uid') return u if u else str(current_user.uid)
Get the UID of the post author. :param Post post: The post object to determine authorship of :return: Author UID :rtype: str
Below is the the instruction that describes the task: ### Input: Get the UID of the post author. :param Post post: The post object to determine authorship of :return: Author UID :rtype: str ### Response: def _author_uid_get(post): """Get the UID of the post author. :param Post post: The post ...
def compress_css(self, paths, output_filename, variant=None, **kwargs): """Concatenate and compress CSS files""" css = self.concatenate_and_rewrite(paths, output_filename, variant) compressor = self.css_compressor if compressor: css = getattr(compressor(verbose=self.verbose),...
Concatenate and compress CSS files
Below is the the instruction that describes the task: ### Input: Concatenate and compress CSS files ### Response: def compress_css(self, paths, output_filename, variant=None, **kwargs): """Concatenate and compress CSS files""" css = self.concatenate_and_rewrite(paths, output_filename, variant) ...
def memoize(f): """Cache value returned by the function.""" @wraps(f) def w(*args, **kw): memoize.mem[f] = v = f(*args, **kw) return v return w
Cache value returned by the function.
Below is the the instruction that describes the task: ### Input: Cache value returned by the function. ### Response: def memoize(f): """Cache value returned by the function.""" @wraps(f) def w(*args, **kw): memoize.mem[f] = v = f(*args, **kw) return v return w
def _series_fluoview(self): """Return image series in FluoView file.""" pages = self.pages._getlist(validate=False) mm = self.fluoview_metadata mmhd = list(reversed(mm['Dimensions'])) axes = ''.join(TIFF.MM_DIMENSIONS.get(i[0].upper(), 'Q') for i in mmhd i...
Return image series in FluoView file.
Below is the the instruction that describes the task: ### Input: Return image series in FluoView file. ### Response: def _series_fluoview(self): """Return image series in FluoView file.""" pages = self.pages._getlist(validate=False) mm = self.fluoview_metadata mmhd = list(reversed(...
def arguments(function, extra_arguments=0): """Returns the name of all arguments a function takes""" if not hasattr(function, '__code__'): return () return function.__code__.co_varnames[:function.__code__.co_argcount + extra_arguments]
Returns the name of all arguments a function takes
Below is the the instruction that describes the task: ### Input: Returns the name of all arguments a function takes ### Response: def arguments(function, extra_arguments=0): """Returns the name of all arguments a function takes""" if not hasattr(function, '__code__'): return () return function...
def changelist_view(self, request, extra_context=None): """ Inject extra links into template context. """ links = [] for action in self.get_extra_actions(): links.append({ 'label': self._get_action_label(action), 'href': self._get_acti...
Inject extra links into template context.
Below is the the instruction that describes the task: ### Input: Inject extra links into template context. ### Response: def changelist_view(self, request, extra_context=None): """ Inject extra links into template context. """ links = [] for action in self.get_extra_actions...
def get_followers(self, first_user_id=None): """ 获取关注者列表 详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表 :param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 """ params = {"access_token": self.token} if first_user_id: ...
获取关注者列表 详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表 :param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包
Below is the the instruction that describes the task: ### Input: 获取关注者列表 详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表 :param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 ### Response: def get_followers(self, first_user_id=None): """ 获取关注者列表 ...
def refresh_rooms(self): """Calls GET /joined_rooms to refresh rooms list.""" for room_id in self.user_api.get_joined_rooms()["joined_rooms"]: self._rooms[room_id] = MatrixRoom(room_id, self.user_api)
Calls GET /joined_rooms to refresh rooms list.
Below is the the instruction that describes the task: ### Input: Calls GET /joined_rooms to refresh rooms list. ### Response: def refresh_rooms(self): """Calls GET /joined_rooms to refresh rooms list.""" for room_id in self.user_api.get_joined_rooms()["joined_rooms"]: self._rooms[room_i...
def infer(msg, mrar=False): """Estimate the most likely BDS code of an message. Args: msg (String): 28 bytes hexadecimal message string mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False. Returns: String or None: BDS version, or possible versions, or None if ...
Estimate the most likely BDS code of an message. Args: msg (String): 28 bytes hexadecimal message string mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False. Returns: String or None: BDS version, or possible versions, or None if nothing matches.
Below is the the instruction that describes the task: ### Input: Estimate the most likely BDS code of an message. Args: msg (String): 28 bytes hexadecimal message string mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False. Returns: String or None: BDS version,...
def update(vm, from_file=None, key='uuid', **kwargs): ''' Update a new vm vm : string vm to be updated from_file : string json file to update the vm with -- if present, all other options will be ignored key : string [uuid|alias|hostname] value type of 'vm' parameter kwar...
Update a new vm vm : string vm to be updated from_file : string json file to update the vm with -- if present, all other options will be ignored key : string [uuid|alias|hostname] value type of 'vm' parameter kwargs : string|int|... options to update for the vm CLI ...
Below is the the instruction that describes the task: ### Input: Update a new vm vm : string vm to be updated from_file : string json file to update the vm with -- if present, all other options will be ignored key : string [uuid|alias|hostname] value type of 'vm' parameter k...
def build_single(mode): """Build, in the single-user mode.""" if mode == 'force': amode = ['-a'] else: amode = [] if executable.endswith('uwsgi'): # hack, might fail in some environments! _executable = executable[:-5] + 'python' else: _executable = executable ...
Build, in the single-user mode.
Below is the the instruction that describes the task: ### Input: Build, in the single-user mode. ### Response: def build_single(mode): """Build, in the single-user mode.""" if mode == 'force': amode = ['-a'] else: amode = [] if executable.endswith('uwsgi'): # hack, might fai...
def extract_scopes(self, request): """ Extract scopes from a request object. """ payload = self.extract_payload(request) if not payload: return None scopes_attribute = self.config.scopes_name() return payload.get(scopes_attribute, None)
Extract scopes from a request object.
Below is the the instruction that describes the task: ### Input: Extract scopes from a request object. ### Response: def extract_scopes(self, request): """ Extract scopes from a request object. """ payload = self.extract_payload(request) if not payload: return No...
def register_auth_method(self, auth_method): """ Register a new authentication method name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded "...
Register a new authentication method name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded
Below is the the instruction that describes the task: ### Input: Register a new authentication method name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded ### Respo...
def open_dataarray(filename_or_obj, group=None, decode_cf=True, mask_and_scale=None, decode_times=True, autoclose=None, concat_characters=True, decode_coords=True, engine=None, chunks=None, lock=None, cache=None, drop_variables=None, backend_kw...
Open an DataArray from a netCDF file containing a single data variable. This is designed to read netCDF files with only one data variable. If multiple variables are present then a ValueError is raised. Parameters ---------- filename_or_obj : str, Path, file or xarray.backends.*DataStore St...
Below is the the instruction that describes the task: ### Input: Open an DataArray from a netCDF file containing a single data variable. This is designed to read netCDF files with only one data variable. If multiple variables are present then a ValueError is raised. Parameters ---------- filen...
def _bend_cos_low(a, b, deriv): """Similar to bend_cos, but with relative vectors""" a = Vector3(6, deriv, a, (0, 1, 2)) b = Vector3(6, deriv, b, (3, 4, 5)) a /= a.norm() b /= b.norm() return dot(a, b).results()
Similar to bend_cos, but with relative vectors
Below is the the instruction that describes the task: ### Input: Similar to bend_cos, but with relative vectors ### Response: def _bend_cos_low(a, b, deriv): """Similar to bend_cos, but with relative vectors""" a = Vector3(6, deriv, a, (0, 1, 2)) b = Vector3(6, deriv, b, (3, 4, 5)) a /= a.norm() ...
def get_path_to_repo(self, repo: str) -> Path: """ Returns a :class:`Path <pathlib.Path>` to the location where all the branches from this repo are stored. :param repo: Repo URL :return: Path to where branches from this repository are cloned. """ return Path(self.base_dir) / "re...
Returns a :class:`Path <pathlib.Path>` to the location where all the branches from this repo are stored. :param repo: Repo URL :return: Path to where branches from this repository are cloned.
Below is the the instruction that describes the task: ### Input: Returns a :class:`Path <pathlib.Path>` to the location where all the branches from this repo are stored. :param repo: Repo URL :return: Path to where branches from this repository are cloned. ### Response: def get_path_to_repo(self, ...
def read_hdf5_dict(h5f, names=None, group=None, **kwargs): """Read a `TimeSeriesDict` from HDF5 """ # find group from which to read if group: h5g = h5f[group] else: h5g = h5f # find list of names to read if names is None: names = [key for key in h5g if _is_timeseries...
Read a `TimeSeriesDict` from HDF5
Below is the the instruction that describes the task: ### Input: Read a `TimeSeriesDict` from HDF5 ### Response: def read_hdf5_dict(h5f, names=None, group=None, **kwargs): """Read a `TimeSeriesDict` from HDF5 """ # find group from which to read if group: h5g = h5f[group] else: h...
def _connect(dbfile: 'PathLike') -> apsw.Connection: """Connect to SQLite database file.""" conn = apsw.Connection(os.fspath(dbfile)) _set_foreign_keys(conn, 1) assert _get_foreign_keys(conn) == 1 return conn
Connect to SQLite database file.
Below is the the instruction that describes the task: ### Input: Connect to SQLite database file. ### Response: def _connect(dbfile: 'PathLike') -> apsw.Connection: """Connect to SQLite database file.""" conn = apsw.Connection(os.fspath(dbfile)) _set_foreign_keys(conn, 1) assert _get_foreign_keys(c...
def agm(x, y, context=None): """ Return the arithmetic geometric mean of x and y. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_agm, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the arithmetic geometric mean of x and y.
Below is the the instruction that describes the task: ### Input: Return the arithmetic geometric mean of x and y. ### Response: def agm(x, y, context=None): """ Return the arithmetic geometric mean of x and y. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_agm, ...
def HWProcess(cls, proc: HWProcess, ctx: ResourceContext) -> None: """ Gues resource usage by HWProcess """ seen = ctx.seen for stm in proc.statements: encl = stm._enclosed_for full_ev_dep = stm._is_completly_event_dependent now_ev_dep = stm._n...
Gues resource usage by HWProcess
Below is the the instruction that describes the task: ### Input: Gues resource usage by HWProcess ### Response: def HWProcess(cls, proc: HWProcess, ctx: ResourceContext) -> None: """ Gues resource usage by HWProcess """ seen = ctx.seen for stm in proc.statements: ...
def save_frames(obj, filename, fmt=None, backend=None, options=None): """ Utility to export object to files frame by frame, numbered individually. Will use default backend and figure format by default. """ backend = Store.current_backend if backend is None else backend renderer = Store.renderers...
Utility to export object to files frame by frame, numbered individually. Will use default backend and figure format by default.
Below is the the instruction that describes the task: ### Input: Utility to export object to files frame by frame, numbered individually. Will use default backend and figure format by default. ### Response: def save_frames(obj, filename, fmt=None, backend=None, options=None): """ Utility to export obje...
def create(self, **kwargs): '''Create the device service cluster group and add devices to it.''' self._set_attributes(**kwargs) self._check_type() pollster(self._check_all_devices_in_sync)() dg = self.devices[0].tm.cm.device_groups.device_group dg.create(name=self.name, ...
Create the device service cluster group and add devices to it.
Below is the the instruction that describes the task: ### Input: Create the device service cluster group and add devices to it. ### Response: def create(self, **kwargs): '''Create the device service cluster group and add devices to it.''' self._set_attributes(**kwargs) self._check_type() ...
def use_music_service(self, service_name, api_key): """ Sets the current music service to service_name. :param str service_name: Name of the music service :param str api_key: Optional API key if necessary """ try: self.current_music = self.music_services[ser...
Sets the current music service to service_name. :param str service_name: Name of the music service :param str api_key: Optional API key if necessary
Below is the the instruction that describes the task: ### Input: Sets the current music service to service_name. :param str service_name: Name of the music service :param str api_key: Optional API key if necessary ### Response: def use_music_service(self, service_name, api_key): """ ...
def get_environ(self, sock): """Create WSGI environ entries to be merged into each request.""" cipher = sock.cipher() ssl_environ = { "wsgi.url_scheme": "https", "HTTPS": "on", 'SSL_PROTOCOL': cipher[1], 'SSL_CIPHER': cipher[0] ## SSL_VE...
Create WSGI environ entries to be merged into each request.
Below is the the instruction that describes the task: ### Input: Create WSGI environ entries to be merged into each request. ### Response: def get_environ(self, sock): """Create WSGI environ entries to be merged into each request.""" cipher = sock.cipher() ssl_environ = { "wsgi....
def print_user(self, user): '''print a filesystem database user. A "database" folder that might end with the participant status (e.g. _finished) is extracted to print in format [folder] [identifier][studyid] /scif/data/expfactory/xxxx-xxxx xxxx-xxxx[studyid] ...
print a filesystem database user. A "database" folder that might end with the participant status (e.g. _finished) is extracted to print in format [folder] [identifier][studyid] /scif/data/expfactory/xxxx-xxxx xxxx-xxxx[studyid]
Below is the the instruction that describes the task: ### Input: print a filesystem database user. A "database" folder that might end with the participant status (e.g. _finished) is extracted to print in format [folder] [identifier][studyid] /scif/data/expfactory/xxxx-x...
def disconnect(self, callback: Callable) -> None: """ Disconnects the given callback. The callback will no longer receive events from this signal. No action is taken if the callback is not on the list of listener callbacks. :param callback: the callable to remove """ ...
Disconnects the given callback. The callback will no longer receive events from this signal. No action is taken if the callback is not on the list of listener callbacks. :param callback: the callable to remove
Below is the the instruction that describes the task: ### Input: Disconnects the given callback. The callback will no longer receive events from this signal. No action is taken if the callback is not on the list of listener callbacks. :param callback: the callable to remove ### Response: ...
def python_zip(file_list, gallery_path, extension='.py'): """Stores all files in file_list into an zip file Parameters ---------- file_list : list Holds all the file names to be included in zip file gallery_path : str path to where the zipfile is stored extension : str '...
Stores all files in file_list into an zip file Parameters ---------- file_list : list Holds all the file names to be included in zip file gallery_path : str path to where the zipfile is stored extension : str '.py' or '.ipynb' In order to deal with downloads of python ...
Below is the the instruction that describes the task: ### Input: Stores all files in file_list into an zip file Parameters ---------- file_list : list Holds all the file names to be included in zip file gallery_path : str path to where the zipfile is stored extension : str ...
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_arguments) < 2: return self.print_help() text_format = gf.safe_unicode(self.actual_arguments[0]) if text_format == u"list": ...
Perform command and return the appropriate exit code. :rtype: int
Below is the the instruction that describes the task: ### Input: Perform command and return the appropriate exit code. :rtype: int ### Response: def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_...
def get_unix_tput_terminal_size(): """ Get the terminal size of a UNIX terminal using the tput UNIX command. Ref: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window """ import subprocess try: proc = subprocess.Popen(["tput", "cols"], stdin=subpr...
Get the terminal size of a UNIX terminal using the tput UNIX command. Ref: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
Below is the the instruction that describes the task: ### Input: Get the terminal size of a UNIX terminal using the tput UNIX command. Ref: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window ### Response: def get_unix_tput_terminal_size(): """ Get the terminal...
def fetch_messages(self): """Sends FetchRequests for all topic/partitions set for consumption Returns: Generator that yields KafkaMessage structs after deserializing with the configured `deserializer_class` Note: Refreshes metadata on errors, and resets fetc...
Sends FetchRequests for all topic/partitions set for consumption Returns: Generator that yields KafkaMessage structs after deserializing with the configured `deserializer_class` Note: Refreshes metadata on errors, and resets fetch offset on OffsetOutOfRa...
Below is the the instruction that describes the task: ### Input: Sends FetchRequests for all topic/partitions set for consumption Returns: Generator that yields KafkaMessage structs after deserializing with the configured `deserializer_class` Note: Refreshes met...
def create_iam_resources(env='dev', app='', **_): """Create the IAM Resources for the application. Args: env (str): Deployment environment/account, i.e. dev, stage, prod. app (str): Spinnaker Application name. Returns: True upon successful completion. """ session = boto3.se...
Create the IAM Resources for the application. Args: env (str): Deployment environment/account, i.e. dev, stage, prod. app (str): Spinnaker Application name. Returns: True upon successful completion.
Below is the the instruction that describes the task: ### Input: Create the IAM Resources for the application. Args: env (str): Deployment environment/account, i.e. dev, stage, prod. app (str): Spinnaker Application name. Returns: True upon successful completion. ### Response: def...
def add_campaign(self, name, device_filter, **kwargs): """Add new update campaign. Add an update campaign with a name and device filtering. Example: .. code-block:: python device_api, update_api = DeviceDirectoryAPI(), UpdateAPI() # Get a filter to use for update camp...
Add new update campaign. Add an update campaign with a name and device filtering. Example: .. code-block:: python device_api, update_api = DeviceDirectoryAPI(), UpdateAPI() # Get a filter to use for update campaign query_obj = device_api.get_query(query_id="MYID")...
Below is the the instruction that describes the task: ### Input: Add new update campaign. Add an update campaign with a name and device filtering. Example: .. code-block:: python device_api, update_api = DeviceDirectoryAPI(), UpdateAPI() # Get a filter to use for update c...
def _filter_kwargs(names, dict_): """Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any] ``dict_`` where the...
Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any] ``dict_`` where the keys intersect with ``names`` and the va...
Below is the the instruction that describes the task: ### Input: Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any]...
def generate(env): """Add Builders and construction variables for lib to an Environment.""" SCons.Tool.createStaticLibBuilder(env) # Set-up ms tools paths msvc_setup_env_once(env) env['AR'] = 'lib' env['ARFLAGS'] = SCons.Util.CLVar('/nologo') env['ARCOM'] = "${TEMPFILE('...
Add Builders and construction variables for lib to an Environment.
Below is the the instruction that describes the task: ### Input: Add Builders and construction variables for lib to an Environment. ### Response: def generate(env): """Add Builders and construction variables for lib to an Environment.""" SCons.Tool.createStaticLibBuilder(env) # Set-up ms tools paths ...
def get_version(self, as_tuple=False): """Returns uWSGI version string or tuple. :param bool as_tuple: :rtype: str|tuple """ if as_tuple: return uwsgi.version_info return decode(uwsgi.version)
Returns uWSGI version string or tuple. :param bool as_tuple: :rtype: str|tuple
Below is the the instruction that describes the task: ### Input: Returns uWSGI version string or tuple. :param bool as_tuple: :rtype: str|tuple ### Response: def get_version(self, as_tuple=False): """Returns uWSGI version string or tuple. :param bool as_tuple: :rtype: st...
def names_container(self): """Returns True if this URI is not representing input/output stream and names a directory. """ if not self.stream: return os.path.isdir(self.object_name) else: return False
Returns True if this URI is not representing input/output stream and names a directory.
Below is the the instruction that describes the task: ### Input: Returns True if this URI is not representing input/output stream and names a directory. ### Response: def names_container(self): """Returns True if this URI is not representing input/output stream and names a directory. ...
def localize_date(date, city): """ Localize date into city Date: datetime City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'.. """ local = pytz.timezone(city) local_dt = local.localize(date, is_dst=None) return local_dt
Localize date into city Date: datetime City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'..
Below is the the instruction that describes the task: ### Input: Localize date into city Date: datetime City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'.. ### Response: def localize_date(date, city): """ Localize date into city Date: datetime City: timezone city defini...
def get_stp_mst_detail_output_cist_port_port_hello_time(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_stp_mst_detail_output_cist_port_port_hello_time(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") ...
def colfieldnames(self, columnname, keyword=''): """Get the names of the fields in a column keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields ...
Get the names of the fields in a column keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword ...
Below is the the instruction that describes the task: ### Input: Get the names of the fields in a column keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names o...
def _initalize_tree(self, position, momentum, slice_var, stepsize): """ Initalizes root node of the tree, i.e depth = 0 """ position_bar, momentum_bar, _ = self.simulate_dynamics(self.model, position, momentum, stepsize, sel...
Initalizes root node of the tree, i.e depth = 0
Below is the the instruction that describes the task: ### Input: Initalizes root node of the tree, i.e depth = 0 ### Response: def _initalize_tree(self, position, momentum, slice_var, stepsize): """ Initalizes root node of the tree, i.e depth = 0 """ position_bar, momentum_bar, _ =...
def add_subcommands(parser, namespace, functions, **namespace_kwargs): """ A wrapper for :func:`add_commands`. These examples are equivalent:: add_commands(parser, [get, put], namespace='db', namespace_kwargs={ 'title': 'database commands', ...
A wrapper for :func:`add_commands`. These examples are equivalent:: add_commands(parser, [get, put], namespace='db', namespace_kwargs={ 'title': 'database commands', 'help': 'CRUD for our silly database' }) ...
Below is the the instruction that describes the task: ### Input: A wrapper for :func:`add_commands`. These examples are equivalent:: add_commands(parser, [get, put], namespace='db', namespace_kwargs={ 'title': 'database commands', ...