code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def log_error(self, text: str) -> None: ''' Given some error text it will log the text if self.log_errors is True :param text: Error text to log ''' if self.log_errors: with self._log_fp.open('a+') as log_file: log_file.write(f'{text}\n')
Given some error text it will log the text if self.log_errors is True :param text: Error text to log
Below is the the instruction that describes the task: ### Input: Given some error text it will log the text if self.log_errors is True :param text: Error text to log ### Response: def log_error(self, text: str) -> None: ''' Given some error text it will log the text if self.log_errors is T...
def explore(node): """ Given a node, explores on relatives, siblings and children :param node: GraphNode from which to explore :return: set of explored GraphNodes """ explored = set() explored.add(node) dfs(node, callback=lambda n: explored.add(n)) return explored
Given a node, explores on relatives, siblings and children :param node: GraphNode from which to explore :return: set of explored GraphNodes
Below is the the instruction that describes the task: ### Input: Given a node, explores on relatives, siblings and children :param node: GraphNode from which to explore :return: set of explored GraphNodes ### Response: def explore(node): """ Given a node, explores on relatives, siblings and children ...
def search_template_present(name, definition): ''' Ensure that the named search template is present. name Name of the search template to add definition Required dict for creation parameters as per http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html *...
Ensure that the named search template is present. name Name of the search template to add definition Required dict for creation parameters as per http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html **Example:** .. code-block:: yaml test_pipelin...
Below is the the instruction that describes the task: ### Input: Ensure that the named search template is present. name Name of the search template to add definition Required dict for creation parameters as per http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.h...
def install(pkg=None, pkgs=None, dir=None, runas=None, registry=None, env=None, dry_run=False, silent=True): ''' Install an NPM package. If no directory is specified, the package will be installed globally. If no packag...
Install an NPM package. If no directory is specified, the package will be installed globally. If no package is specified, the dependencies (from package.json) of the package in the given directory will be installed. pkg A package name in any format accepted by NPM, including a version ...
Below is the the instruction that describes the task: ### Input: Install an NPM package. If no directory is specified, the package will be installed globally. If no package is specified, the dependencies (from package.json) of the package in the given directory will be installed. pkg A pac...
def delete_object(self, object): """ Delete object specified by ``object``. """ #pdb.set_trace() self.db.engine.delete_key(object)#, userid='abc123', id='1') print('dynamo.delete_object(%s)' % object)
Delete object specified by ``object``.
Below is the the instruction that describes the task: ### Input: Delete object specified by ``object``. ### Response: def delete_object(self, object): """ Delete object specified by ``object``. """ #pdb.set_trace() self.db.engine.delete_key(object)#, userid='abc123', id='1') print('...
def min_depth_img(self, num_img=1): """Collect a series of depth images and return the min of the set. Parameters ---------- num_img : int The number of consecutive frames to process. Returns ------- :obj:`DepthImage` The min DepthImage c...
Collect a series of depth images and return the min of the set. Parameters ---------- num_img : int The number of consecutive frames to process. Returns ------- :obj:`DepthImage` The min DepthImage collected from the frames.
Below is the the instruction that describes the task: ### Input: Collect a series of depth images and return the min of the set. Parameters ---------- num_img : int The number of consecutive frames to process. Returns ------- :obj:`DepthImage` ...
def _required_args(fn): """Returns arguments of fn with default=REQUIRED_ARG.""" spec = getargspec(fn) if not spec.defaults: return [] arg_names = spec.args[-len(spec.defaults):] return [name for name, val in zip(arg_names, spec.defaults) if val is REQUIRED_ARG]
Returns arguments of fn with default=REQUIRED_ARG.
Below is the the instruction that describes the task: ### Input: Returns arguments of fn with default=REQUIRED_ARG. ### Response: def _required_args(fn): """Returns arguments of fn with default=REQUIRED_ARG.""" spec = getargspec(fn) if not spec.defaults: return [] arg_names = spec.args[-len(spec.defau...
def find(self, uid): """Find and load the user from database by uid(user id)""" data = (db.select(self.table).select('username', 'email', 'real_name', 'password', 'bio', 'status', 'role', 'uid'). condition('uid', uid).execute() ...
Find and load the user from database by uid(user id)
Below is the the instruction that describes the task: ### Input: Find and load the user from database by uid(user id) ### Response: def find(self, uid): """Find and load the user from database by uid(user id)""" data = (db.select(self.table).select('username', 'email', 'real_name', ...
def custom_action(sender, action, instance, user=None, **kwargs): """ Manually trigger a custom action (or even a standard action). """ opts = get_opts(instance) model = '.'.join([opts.app_label, opts.object_name]) dis...
Manually trigger a custom action (or even a standard action).
Below is the the instruction that describes the task: ### Input: Manually trigger a custom action (or even a standard action). ### Response: def custom_action(sender, action, instance, user=None, **kwargs): """ Manually trigger a...
def inn(self) -> str: """Generate random, but valid ``INN``. :return: INN. """ def control_sum(nums: list, t: str) -> int: digits = { 'n2': [7, 2, 4, 10, 3, 5, 9, 4, 6, 8], 'n1': [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8], } nu...
Generate random, but valid ``INN``. :return: INN.
Below is the the instruction that describes the task: ### Input: Generate random, but valid ``INN``. :return: INN. ### Response: def inn(self) -> str: """Generate random, but valid ``INN``. :return: INN. """ def control_sum(nums: list, t: str) -> int: digits = ...
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Write the ValidationInformation structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode ValidationInformation structure data, supporting a write...
Write the ValidationInformation structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode ValidationInformation structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining ...
Below is the the instruction that describes the task: ### Input: Write the ValidationInformation structure encoding to the data stream. Args: output_buffer (stream): A data stream in which to encode ValidationInformation structure data, supporting a write method....
def _parseSimpleSelector(self, src): """simple_selector : [ namespace_selector ]? element_name? [ HASH | class | attrib | pseudo ]* S* ; """ ctxsrc = src.lstrip() nsPrefix, src = self._getMatchResult(self.re_namespace_selector, src) name, src = self._getMatchResul...
simple_selector : [ namespace_selector ]? element_name? [ HASH | class | attrib | pseudo ]* S* ;
Below is the the instruction that describes the task: ### Input: simple_selector : [ namespace_selector ]? element_name? [ HASH | class | attrib | pseudo ]* S* ; ### Response: def _parseSimpleSelector(self, src): """simple_selector : [ namespace_selector ]? element_name? [ HASH | cl...
def execute(self): """ Execute the actions necessary to perform a `molecule init scenario` and returns None. :return: None """ scenario_name = self._command_args['scenario_name'] role_name = os.getcwd().split(os.sep)[-1] role_directory = util.abs_path(os....
Execute the actions necessary to perform a `molecule init scenario` and returns None. :return: None
Below is the the instruction that describes the task: ### Input: Execute the actions necessary to perform a `molecule init scenario` and returns None. :return: None ### Response: def execute(self): """ Execute the actions necessary to perform a `molecule init scenario` and ...
def export_results(job, fsid, file_name, univ_options, subfolder=None): """ Write out a file to a given location. The location can be either a directory on the local machine, or a folder with a bucket on AWS. :param str fsid: The file store id for the file to be exported :param str file_name: The n...
Write out a file to a given location. The location can be either a directory on the local machine, or a folder with a bucket on AWS. :param str fsid: The file store id for the file to be exported :param str file_name: The name of the file that neeeds to be exported (path to file is also acceptab...
Below is the the instruction that describes the task: ### Input: Write out a file to a given location. The location can be either a directory on the local machine, or a folder with a bucket on AWS. :param str fsid: The file store id for the file to be exported :param str file_name: The name of the file...
def _get_or_create_user(self, force_populate=False): """ Loads the User model object from the database or creates it if it doesn't exist. Also populates the fields, subject to AUTH_LDAP_ALWAYS_UPDATE_USER. """ save_user = False username = self.backend.ldap_to_dja...
Loads the User model object from the database or creates it if it doesn't exist. Also populates the fields, subject to AUTH_LDAP_ALWAYS_UPDATE_USER.
Below is the the instruction that describes the task: ### Input: Loads the User model object from the database or creates it if it doesn't exist. Also populates the fields, subject to AUTH_LDAP_ALWAYS_UPDATE_USER. ### Response: def _get_or_create_user(self, force_populate=False): """ ...
def get_instance(self, payload): """ Build an instance of NotificationInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.notification.NotificationInstance :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance ...
Build an instance of NotificationInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.notification.NotificationInstance :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance
Below is the the instruction that describes the task: ### Input: Build an instance of NotificationInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.notification.NotificationInstance :rtype: twilio.rest.api.v2010.account.notification.Notific...
def getrruleset(self, addRDate=False): """ Get an rruleset created from self. If addRDate is True, add an RDATE for dtstart if it's not included in an RRULE, and count is decremented if it exists. Note that for rules which don't match DTSTART, DTSTART may not appear in ...
Get an rruleset created from self. If addRDate is True, add an RDATE for dtstart if it's not included in an RRULE, and count is decremented if it exists. Note that for rules which don't match DTSTART, DTSTART may not appear in list(rruleset), although it should. By default, an RDATE i...
Below is the the instruction that describes the task: ### Input: Get an rruleset created from self. If addRDate is True, add an RDATE for dtstart if it's not included in an RRULE, and count is decremented if it exists. Note that for rules which don't match DTSTART, DTSTART may not appear ...
def stop(self): """Close websocket connection.""" self.state = STATE_STOPPED if self.transport: self.transport.close()
Close websocket connection.
Below is the the instruction that describes the task: ### Input: Close websocket connection. ### Response: def stop(self): """Close websocket connection.""" self.state = STATE_STOPPED if self.transport: self.transport.close()
def custom_getter_router(custom_getter_map, name_fn): """Creates a custom getter than matches requests to dict of custom getters. Custom getters are callables which implement the [custom getter API] (https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable). The returned custom getter dispat...
Creates a custom getter than matches requests to dict of custom getters. Custom getters are callables which implement the [custom getter API] (https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable). The returned custom getter dispatches calls based on pattern matching the name of the requ...
Below is the the instruction that describes the task: ### Input: Creates a custom getter than matches requests to dict of custom getters. Custom getters are callables which implement the [custom getter API] (https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable). The returned custom get...
def coordinates(self, reference=None): """ Returns the coordinates of a :Placeable: relative to :reference: """ coordinates = [i._coordinates for i in self.get_trace(reference)] return functools.reduce(lambda a, b: a + b, coordinates)
Returns the coordinates of a :Placeable: relative to :reference:
Below is the the instruction that describes the task: ### Input: Returns the coordinates of a :Placeable: relative to :reference: ### Response: def coordinates(self, reference=None): """ Returns the coordinates of a :Placeable: relative to :reference: """ coordinates = [i._coordinat...
async def _send_recipients( self, recipients: List[str], options: List[str] = None, timeout: DefaultNumType = _default, ) -> RecipientErrorsType: """ Send the recipients given to the server. Used as part of :meth:`.sendmail`. """ recipient_erro...
Send the recipients given to the server. Used as part of :meth:`.sendmail`.
Below is the the instruction that describes the task: ### Input: Send the recipients given to the server. Used as part of :meth:`.sendmail`. ### Response: async def _send_recipients( self, recipients: List[str], options: List[str] = None, timeout: DefaultNumType = _default, ...
def setStopAction(self, action, *args, **kwargs): """ Set a function to call when run() is stopping, after the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. ...
Set a function to call when run() is stopping, after the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action.
Below is the the instruction that describes the task: ### Input: Set a function to call when run() is stopping, after the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass ...
def crab_request(client, action, *args): ''' Utility function that helps making requests to the CRAB service. :param client: A :class:`suds.client.Client` for the CRAB service. :param string action: Which method to call, eg. `ListGewesten` :returns: Result of the SOAP call. .. versionadded:: 0...
Utility function that helps making requests to the CRAB service. :param client: A :class:`suds.client.Client` for the CRAB service. :param string action: Which method to call, eg. `ListGewesten` :returns: Result of the SOAP call. .. versionadded:: 0.3.0
Below is the the instruction that describes the task: ### Input: Utility function that helps making requests to the CRAB service. :param client: A :class:`suds.client.Client` for the CRAB service. :param string action: Which method to call, eg. `ListGewesten` :returns: Result of the SOAP call. .. ...
def wide_to_long(df, stubnames, i, j, sep="", suffix=r'\d+'): r""" Wide panel to long format. Less flexible but more user-friendly than melt. With stubnames ['A', 'B'], this function expects to find one or more group of columns with format A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,... You ...
r""" Wide panel to long format. Less flexible but more user-friendly than melt. With stubnames ['A', 'B'], this function expects to find one or more group of columns with format A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,... You specify what you want to call this suffix in the resulting long fo...
Below is the the instruction that describes the task: ### Input: r""" Wide panel to long format. Less flexible but more user-friendly than melt. With stubnames ['A', 'B'], this function expects to find one or more group of columns with format A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,... Y...
def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger...
Get raw predicate information for given request class, and cache for subsequent calls.
Below is the the instruction that describes the task: ### Input: Get raw predicate information for given request class, and cache for subsequent calls. ### Response: def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for ...
def _split_compound_string_(compound_string): """ Split a compound's combined formula and phase into separate strings for the formula and phase. :param compound_string: Formula and phase of a chemical compound, e.g. 'SiO2[S1]'. :returns: Formula of chemical compound. :returns: Phase of c...
Split a compound's combined formula and phase into separate strings for the formula and phase. :param compound_string: Formula and phase of a chemical compound, e.g. 'SiO2[S1]'. :returns: Formula of chemical compound. :returns: Phase of chemical compound.
Below is the the instruction that describes the task: ### Input: Split a compound's combined formula and phase into separate strings for the formula and phase. :param compound_string: Formula and phase of a chemical compound, e.g. 'SiO2[S1]'. :returns: Formula of chemical compound. :returns:...
def write_color_old( text, attr=None): u'''write text at current cursor position and interpret color escapes. return the number of characters written. ''' res = [] chunks = terminal_escape.split(text) n = 0 # count the characters we actually write, omitting the escapes if attr is No...
u'''write text at current cursor position and interpret color escapes. return the number of characters written.
Below is the the instruction that describes the task: ### Input: u'''write text at current cursor position and interpret color escapes. return the number of characters written. ### Response: def write_color_old( text, attr=None): u'''write text at current cursor position and interpret color escapes. ...
def get_usb_controller_by_name(self, name): """Returns a USB controller with the given type. in name of type str return controller of type :class:`IUSBController` raises :class:`VBoxErrorObjectNotFound` A USB controller with given name doesn't exist. """ ...
Returns a USB controller with the given type. in name of type str return controller of type :class:`IUSBController` raises :class:`VBoxErrorObjectNotFound` A USB controller with given name doesn't exist.
Below is the the instruction that describes the task: ### Input: Returns a USB controller with the given type. in name of type str return controller of type :class:`IUSBController` raises :class:`VBoxErrorObjectNotFound` A USB controller with given name doesn't exist. ### Resp...
def get_json(self): """Serialize ratings object as JSON-formatted string""" ratings_dict = { 'category': self.category, 'date': self.date, 'day': self.weekday, 'next week': self.next_week, 'last week': self.last_week, 'entries': sel...
Serialize ratings object as JSON-formatted string
Below is the the instruction that describes the task: ### Input: Serialize ratings object as JSON-formatted string ### Response: def get_json(self): """Serialize ratings object as JSON-formatted string""" ratings_dict = { 'category': self.category, 'date': self.date, ...
def configure(self, organization, base_url='', ttl='', max_ttl='', mount_point=DEFAULT_MOUNT_POINT): """Configure the connection parameters for GitHub. This path honors the distinction between the create and update capabilities inside ACL policies. Supported methods: POST: /auth/{m...
Configure the connection parameters for GitHub. This path honors the distinction between the create and update capabilities inside ACL policies. Supported methods: POST: /auth/{mount_point}/config. Produces: 204 (empty body) :param organization: The organization users must be par...
Below is the the instruction that describes the task: ### Input: Configure the connection parameters for GitHub. This path honors the distinction between the create and update capabilities inside ACL policies. Supported methods: POST: /auth/{mount_point}/config. Produces: 204 (empty bo...
def startDrag(self, dropActions): """Reimplement Qt Method - handle drag event""" data = QMimeData() data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()]) drag = QDrag(self) drag.setMimeData(data) drag.exec_()
Reimplement Qt Method - handle drag event
Below is the the instruction that describes the task: ### Input: Reimplement Qt Method - handle drag event ### Response: def startDrag(self, dropActions): """Reimplement Qt Method - handle drag event""" data = QMimeData() data.setUrls([QUrl(fname) for fname in self.get_selected_filenames...
def mft_record_size(self): """ Returns: int: MFT record size in bytes """ if self.extended_bpb.clusters_per_mft < 0: return 2 ** abs(self.extended_bpb.clusters_per_mft) else: return self.clusters_per_mft * self.sectors_per_cluster * \ ...
Returns: int: MFT record size in bytes
Below is the the instruction that describes the task: ### Input: Returns: int: MFT record size in bytes ### Response: def mft_record_size(self): """ Returns: int: MFT record size in bytes """ if self.extended_bpb.clusters_per_mft < 0: return 2 ** ...
def activate_hopscotch(driver): """ Allows you to use Hopscotch Tours with SeleniumBase http://linkedin.github.io/hopscotch/ """ hopscotch_css = constants.Hopscotch.MIN_CSS hopscotch_js = constants.Hopscotch.MIN_JS backdrop_style = style_sheet.hops_backdrop_style verify_script = ("""// ...
Allows you to use Hopscotch Tours with SeleniumBase http://linkedin.github.io/hopscotch/
Below is the the instruction that describes the task: ### Input: Allows you to use Hopscotch Tours with SeleniumBase http://linkedin.github.io/hopscotch/ ### Response: def activate_hopscotch(driver): """ Allows you to use Hopscotch Tours with SeleniumBase http://linkedin.github.io/hopscotch/ ...
def select_mastery_path(self, id, course_id, module_id, assignment_set_id=None, student_id=None): """ Select a mastery path. Select a mastery path when module item includes several possible paths. Requires Mastery Paths feature to be enabled. Returns a compound document w...
Select a mastery path. Select a mastery path when module item includes several possible paths. Requires Mastery Paths feature to be enabled. Returns a compound document with the assignments included in the given path and any module items related to those assignments
Below is the the instruction that describes the task: ### Input: Select a mastery path. Select a mastery path when module item includes several possible paths. Requires Mastery Paths feature to be enabled. Returns a compound document with the assignments included in the given path and ...
def _list_records(self, rtype=None, name=None, content=None): """List all records for the hosted zone.""" records = [] paginator = RecordSetPaginator(self.r53_client, self.domain_id) for record in paginator.all_record_sets(): if rtype is not None and record['Type'] != rtype: ...
List all records for the hosted zone.
Below is the the instruction that describes the task: ### Input: List all records for the hosted zone. ### Response: def _list_records(self, rtype=None, name=None, content=None): """List all records for the hosted zone.""" records = [] paginator = RecordSetPaginator(self.r53_client, self.do...
def plot(self, plot_cmd=None, tf=lambda y: y): """plot the data we have, return ``self``""" if not plot_cmd: plot_cmd = self.plot_cmd colors = 'bgrcmyk' pyplot.hold(False) res = self.res flatx, flatf = self.flattened() minf = np.inf for i in f...
plot the data we have, return ``self``
Below is the the instruction that describes the task: ### Input: plot the data we have, return ``self`` ### Response: def plot(self, plot_cmd=None, tf=lambda y: y): """plot the data we have, return ``self``""" if not plot_cmd: plot_cmd = self.plot_cmd colors = 'bgrcmyk' ...
def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name i...
Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600
Below is the the instruction that describes the task: ### Input: Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ### Response: def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Ex...
def perform_action( self, action, machines, params, progress_title, success_title): """Perform the action on the set of machines.""" if len(machines) == 0: return 0 with utils.Spinner() as context: return self._async_perform_action( context, ac...
Perform the action on the set of machines.
Below is the the instruction that describes the task: ### Input: Perform the action on the set of machines. ### Response: def perform_action( self, action, machines, params, progress_title, success_title): """Perform the action on the set of machines.""" if len(machines) == 0: ...
def render(template='', data={}, partials_path='.', partials_ext='mustache', partials_dict={}, padding='', def_ldel='{{', def_rdel='}}', scopes=None): """Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷...
Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷ ├─╼ main.py ├─╼ main.ms └─┮ partials └── part.ms then main.py would make the following call: render(open('main.ms', 'r'), {...}, 'partials', 'ms') ...
Below is the the instruction that describes the task: ### Input: Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷ ├─╼ main.py ├─╼ main.ms └─┮ partials └── part.ms then main.py would make the following ...
def get_rps_list(self): """ get list of each second's rps :returns: list of tuples (rps, duration of corresponding rps in seconds) :rtype: list """ seconds = range(0, int(self.duration) + 1) rps_groups = groupby([proper_round(self.rps_at(t)) for t in seconds], ...
get list of each second's rps :returns: list of tuples (rps, duration of corresponding rps in seconds) :rtype: list
Below is the the instruction that describes the task: ### Input: get list of each second's rps :returns: list of tuples (rps, duration of corresponding rps in seconds) :rtype: list ### Response: def get_rps_list(self): """ get list of each second's rps :returns: list of tupl...
def root_sections(h): """ Returns a list of all sections that have no parent. """ roots = [] for section in h.allsec(): sref = h.SectionRef(sec=section) # has_parent returns a float... cast to bool if sref.has_parent() < 0.9: roots.append(section) return roots
Returns a list of all sections that have no parent.
Below is the the instruction that describes the task: ### Input: Returns a list of all sections that have no parent. ### Response: def root_sections(h): """ Returns a list of all sections that have no parent. """ roots = [] for section in h.allsec(): sref = h.SectionRef(sec=section) ...
def set_footer(self, text: str, icon_url: str = None) -> None: """ Sets the footer of the embed. Parameters ---------- text: str The footer text. icon_url: str, optional URL for the icon in the footer. """ self.footer = { ...
Sets the footer of the embed. Parameters ---------- text: str The footer text. icon_url: str, optional URL for the icon in the footer.
Below is the the instruction that describes the task: ### Input: Sets the footer of the embed. Parameters ---------- text: str The footer text. icon_url: str, optional URL for the icon in the footer. ### Response: def set_footer(self, text: str, icon_url: s...
def get_children(self): """Get the child nodes below this node. :returns: The children. :rtype: iterable(NodeNG) """ for field in self._astroid_fields: attr = getattr(self, field) if attr is None: continue if isinstance(attr, (...
Get the child nodes below this node. :returns: The children. :rtype: iterable(NodeNG)
Below is the the instruction that describes the task: ### Input: Get the child nodes below this node. :returns: The children. :rtype: iterable(NodeNG) ### Response: def get_children(self): """Get the child nodes below this node. :returns: The children. :rtype: iterable(Nod...
def citation(self): """ Returns the contents of the citation.bib file that describes the source and provenance of the dataset or to cite for academic work. """ path = find_dataset_path( self.name, data_home=self.data_home, fname="meta.json", raises=False ) ...
Returns the contents of the citation.bib file that describes the source and provenance of the dataset or to cite for academic work.
Below is the the instruction that describes the task: ### Input: Returns the contents of the citation.bib file that describes the source and provenance of the dataset or to cite for academic work. ### Response: def citation(self): """ Returns the contents of the citation.bib file that descr...
def run(bam, chrom, pos1, pos2, reffa, chr_reffa, parameters): """Run mpileup on given chrom and pos""" # check for chr ref is_chr_query = chrom.startswith('chr') if is_chr_query and chr_reffa is None: chr_reffa = reffa # check bam ref type bam_header = subprocess.check_output("samtool...
Run mpileup on given chrom and pos
Below is the the instruction that describes the task: ### Input: Run mpileup on given chrom and pos ### Response: def run(bam, chrom, pos1, pos2, reffa, chr_reffa, parameters): """Run mpileup on given chrom and pos""" # check for chr ref is_chr_query = chrom.startswith('chr') if is_chr_query and c...
def modify_process_summary(self, pid=None, text='', append=False): ''' modify_process_summary(self, pid=None, text='') Modifies the summary text of the process execution :Parameters: * *key* (`pid`) -- Identifier of an existing process * *key* (`text`) -- summary text ...
modify_process_summary(self, pid=None, text='') Modifies the summary text of the process execution :Parameters: * *key* (`pid`) -- Identifier of an existing process * *key* (`text`) -- summary text * *append* (`boolean`) -- True to append to summary. False to override it.
Below is the the instruction that describes the task: ### Input: modify_process_summary(self, pid=None, text='') Modifies the summary text of the process execution :Parameters: * *key* (`pid`) -- Identifier of an existing process * *key* (`text`) -- summary text * *append* ...
def apply_T7(word): '''If a VVV-sequence does not contain a potential /i/-final diphthong, there is a syllable boundary between the second and third vowels, e.g. [kau.an], [leu.an], [kiu.as].''' T7 = '' WORD = word.split('.') for i, v in enumerate(WORD): if contains_VVV(v): ...
If a VVV-sequence does not contain a potential /i/-final diphthong, there is a syllable boundary between the second and third vowels, e.g. [kau.an], [leu.an], [kiu.as].
Below is the the instruction that describes the task: ### Input: If a VVV-sequence does not contain a potential /i/-final diphthong, there is a syllable boundary between the second and third vowels, e.g. [kau.an], [leu.an], [kiu.as]. ### Response: def apply_T7(word): '''If a VVV-sequence does not conta...
def add_compression(self, compression=True): """ Add an instruction enabling or disabling compression for the transmitted raster image lines. Not all models support compression. If the specific model doesn't support it but this method is called trying to enable it, either a warning is se...
Add an instruction enabling or disabling compression for the transmitted raster image lines. Not all models support compression. If the specific model doesn't support it but this method is called trying to enable it, either a warning is set or an exception is raised depending on the value of :py...
Below is the the instruction that describes the task: ### Input: Add an instruction enabling or disabling compression for the transmitted raster image lines. Not all models support compression. If the specific model doesn't support it but this method is called trying to enable it, either a warning i...
def min_cost_flow(self, display = None, **args): ''' API: min_cost_flow(self, display='off', **args) Description: Solves minimum cost flow problem using node/edge attributes with the algorithm specified. Pre: (1) Assumes a directed graph in...
API: min_cost_flow(self, display='off', **args) Description: Solves minimum cost flow problem using node/edge attributes with the algorithm specified. Pre: (1) Assumes a directed graph in which each arc has 'capacity' and 'cost' attributes. ...
Below is the the instruction that describes the task: ### Input: API: min_cost_flow(self, display='off', **args) Description: Solves minimum cost flow problem using node/edge attributes with the algorithm specified. Pre: (1) Assumes a directed graph in...
def composition(self): """ (Composition) Returns the composition """ elmap = collections.defaultdict(float) for site in self: for species, occu in site.species.items(): elmap[species] += occu return Composition(elmap)
(Composition) Returns the composition
Below is the the instruction that describes the task: ### Input: (Composition) Returns the composition ### Response: def composition(self): """ (Composition) Returns the composition """ elmap = collections.defaultdict(float) for site in self: for species, occu in...
def inverse(self): """Returns a new instance of MarginalRateTaxScale Invert a taxscale: Assume tax_scale composed of bracket which thresholds are expressed in term of brut revenue. The inverse is another MarginalTaxSclae which thresholds are expressed in terms of net revenue. ...
Returns a new instance of MarginalRateTaxScale Invert a taxscale: Assume tax_scale composed of bracket which thresholds are expressed in term of brut revenue. The inverse is another MarginalTaxSclae which thresholds are expressed in terms of net revenue. If net = revbrut - ...
Below is the the instruction that describes the task: ### Input: Returns a new instance of MarginalRateTaxScale Invert a taxscale: Assume tax_scale composed of bracket which thresholds are expressed in term of brut revenue. The inverse is another MarginalTaxSclae which thresholds ar...
def get_unconnected_nodes(sentence_graph): """ Takes a TigerSentenceGraph and returns a list of node IDs of unconnected nodes. A node is unconnected, if it doesn't have any in- or outgoing edges. A node is NOT considered unconnected, if the graph only consists of that particular node. Para...
Takes a TigerSentenceGraph and returns a list of node IDs of unconnected nodes. A node is unconnected, if it doesn't have any in- or outgoing edges. A node is NOT considered unconnected, if the graph only consists of that particular node. Parameters ---------- sentence_graph : TigerSentenc...
Below is the the instruction that describes the task: ### Input: Takes a TigerSentenceGraph and returns a list of node IDs of unconnected nodes. A node is unconnected, if it doesn't have any in- or outgoing edges. A node is NOT considered unconnected, if the graph only consists of that particular n...
def drawBezier(self, p1, p2, p3, p4): """Draw a standard cubic Bezier curve. """ p1 = Point(p1) p2 = Point(p2) p3 = Point(p3) p4 = Point(p4) if not (self.lastPoint == p1): self.draw_cont += "%g %g m\n" % JM_TUPLE(p1 * self.ipctm) self.draw_cont...
Draw a standard cubic Bezier curve.
Below is the the instruction that describes the task: ### Input: Draw a standard cubic Bezier curve. ### Response: def drawBezier(self, p1, p2, p3, p4): """Draw a standard cubic Bezier curve. """ p1 = Point(p1) p2 = Point(p2) p3 = Point(p3) p4 = Point(p4) if ...
def parse_lrvalue_string(search_string, delimiter=":"): ''' The function takes a multi-line output/string with the format "name/descr : value", and converts it to a dictionary object with key value pairs, where key is built from the name/desc part and value as the value. ...
The function takes a multi-line output/string with the format "name/descr : value", and converts it to a dictionary object with key value pairs, where key is built from the name/desc part and value as the value. eg: "Serial Number: FCH1724V1GT" will be translated to dict['serial_number'] = "FCH1...
Below is the the instruction that describes the task: ### Input: The function takes a multi-line output/string with the format "name/descr : value", and converts it to a dictionary object with key value pairs, where key is built from the name/desc part and value as the value. eg: "Serial Number:...
def calculate_ef_var(tpf, fpf): """ determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the fpf @ which the enrichment factor was calculated :param tpf: float tpf @ which the enrichment factor was calculated :param fpf: float fpf @ which the enr...
determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the fpf @ which the enrichment factor was calculated :param tpf: float tpf @ which the enrichment factor was calculated :param fpf: float fpf @ which the enrichment factor was calculated :return ef...
Below is the the instruction that describes the task: ### Input: determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the fpf @ which the enrichment factor was calculated :param tpf: float tpf @ which the enrichment factor was calculated :param fpf: ...
def video_load_time(self): """ Returns aggregate video load time for all pages. """ load_times = self.get_load_times('video') return round(mean(load_times), self.decimal_precision)
Returns aggregate video load time for all pages.
Below is the the instruction that describes the task: ### Input: Returns aggregate video load time for all pages. ### Response: def video_load_time(self): """ Returns aggregate video load time for all pages. """ load_times = self.get_load_times('video') return round(mean(loa...
def create_event(self, register=False): """Create an asyncio.Event inside the emulation loop. This method exists as a convenience to create an Event object that is associated with the correct EventLoop(). If you pass register=True, then the event will be registered as an event that mus...
Create an asyncio.Event inside the emulation loop. This method exists as a convenience to create an Event object that is associated with the correct EventLoop(). If you pass register=True, then the event will be registered as an event that must be set for the EmulationLoop to be consid...
Below is the the instruction that describes the task: ### Input: Create an asyncio.Event inside the emulation loop. This method exists as a convenience to create an Event object that is associated with the correct EventLoop(). If you pass register=True, then the event will be registered as...
def venv_pth(self, dirs): ''' Add the directories in `dirs` to the `sys.path`. A venv.pth file will be written in the site-packages dir of this virtualenv to add dirs to sys.path. dirs: a list of directories. ''' # Create venv.pth to add dirs to sys.path when us...
Add the directories in `dirs` to the `sys.path`. A venv.pth file will be written in the site-packages dir of this virtualenv to add dirs to sys.path. dirs: a list of directories.
Below is the the instruction that describes the task: ### Input: Add the directories in `dirs` to the `sys.path`. A venv.pth file will be written in the site-packages dir of this virtualenv to add dirs to sys.path. dirs: a list of directories. ### Response: def venv_pth(self, dirs): ...
def named_crumb(context, name, *args, **kwargs): """ Resolves given named URL and returns the relevant breadcrumb label (if available). Usage:: <a href="{% url project-detail project.slug %}"> {% named_crumb project-detail project.slug %} </a> """ url = reverse(name, args=a...
Resolves given named URL and returns the relevant breadcrumb label (if available). Usage:: <a href="{% url project-detail project.slug %}"> {% named_crumb project-detail project.slug %} </a>
Below is the the instruction that describes the task: ### Input: Resolves given named URL and returns the relevant breadcrumb label (if available). Usage:: <a href="{% url project-detail project.slug %}"> {% named_crumb project-detail project.slug %} </a> ### Response: def named_cr...
def is_businessperiod(cls, in_period): """ :param in_period: object to be checked :type in_period: object, str, timedelta :return: True if cast works :rtype: Boolean checks is argument con becasted to BusinessPeriod """ try: # to be removed i...
:param in_period: object to be checked :type in_period: object, str, timedelta :return: True if cast works :rtype: Boolean checks is argument con becasted to BusinessPeriod
Below is the the instruction that describes the task: ### Input: :param in_period: object to be checked :type in_period: object, str, timedelta :return: True if cast works :rtype: Boolean checks is argument con becasted to BusinessPeriod ### Response: def is_businessperiod(cls, in_...
def UpsertUser(self, database_link, user, options=None): """Upserts a user. :param str database_link: The link to the database. :param dict user: The Azure Cosmos user to upsert. :param dict options: The request options for the request. :retu...
Upserts a user. :param str database_link: The link to the database. :param dict user: The Azure Cosmos user to upsert. :param dict options: The request options for the request. :return: The upserted User. :rtype: dict
Below is the the instruction that describes the task: ### Input: Upserts a user. :param str database_link: The link to the database. :param dict user: The Azure Cosmos user to upsert. :param dict options: The request options for the request. :ret...
def set_from_file(file_name): """ Merge configuration from a file with JSON data :param file_name: name of the file to be read :raises TypeError: if file_name is not str """ if type(file_name) != str: raise TypeError('file_name must be str') global _config_file_name _config_file...
Merge configuration from a file with JSON data :param file_name: name of the file to be read :raises TypeError: if file_name is not str
Below is the the instruction that describes the task: ### Input: Merge configuration from a file with JSON data :param file_name: name of the file to be read :raises TypeError: if file_name is not str ### Response: def set_from_file(file_name): """ Merge configuration from a file with JSON data ...
def optical_flow_rad_send(self, time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance, force_mavlink1=False): ''' Optical flow from an angular rate flow sensor (e...
Optical flow from an angular rate flow sensor (e.g. PX4FLOW or mouse sensor) time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) sensor_id : Sensor ID (uint8_t) integration_time_us ...
Below is the the instruction that describes the task: ### Input: Optical flow from an angular rate flow sensor (e.g. PX4FLOW or mouse sensor) time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) sensor_id ...
def run(self): """Starts the receiver.""" executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) loop = asyncio.get_event_loop() loop.run_until_complete(self._run_loop(executor)) self._log.info('Shutting down...') executor.shutdown()
Starts the receiver.
Below is the the instruction that describes the task: ### Input: Starts the receiver. ### Response: def run(self): """Starts the receiver.""" executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) loop = asyncio.get_event_loop() loop.run_until_complete(self._run_loop(execut...
def import_by_path(path): """Append the path to sys.path, then attempt to import module with path's basename, finally making certain to remove appended path. http://stackoverflow.com/questions/1096216/override-namespace-in-python""" sys.path.append(os.path.dirname(path)) try: return __imp...
Append the path to sys.path, then attempt to import module with path's basename, finally making certain to remove appended path. http://stackoverflow.com/questions/1096216/override-namespace-in-python
Below is the the instruction that describes the task: ### Input: Append the path to sys.path, then attempt to import module with path's basename, finally making certain to remove appended path. http://stackoverflow.com/questions/1096216/override-namespace-in-python ### Response: def import_by_path(path): ...
def tunnel(container, local_port, remote_port=None, gateway_port=None): ''' Set up an SSH tunnel into the container, using the host as a gateway host. Args: * container: Container name or ID * local_port: Local port * remote_port=None: Port on the Docker container (defaults to local...
Set up an SSH tunnel into the container, using the host as a gateway host. Args: * container: Container name or ID * local_port: Local port * remote_port=None: Port on the Docker container (defaults to local_port) * gateway_port=None: Port on the gateway host (defaults to remote_por...
Below is the the instruction that describes the task: ### Input: Set up an SSH tunnel into the container, using the host as a gateway host. Args: * container: Container name or ID * local_port: Local port * remote_port=None: Port on the Docker container (defaults to local_port) ...
def mime_type(self, path): """Get mime-type from filename""" name, ext = os.path.splitext(path) return MIME_TYPES[ext]
Get mime-type from filename
Below is the the instruction that describes the task: ### Input: Get mime-type from filename ### Response: def mime_type(self, path): """Get mime-type from filename""" name, ext = os.path.splitext(path) return MIME_TYPES[ext]
def hash_length(instance): """Ensure keys in 'hashes'-type properties are no more than 30 characters long. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] == 'file': try: hashes = obj['hashes'] ...
Ensure keys in 'hashes'-type properties are no more than 30 characters long.
Below is the the instruction that describes the task: ### Input: Ensure keys in 'hashes'-type properties are no more than 30 characters long. ### Response: def hash_length(instance): """Ensure keys in 'hashes'-type properties are no more than 30 characters long. """ for key, obj in instance['objects']....
def parse_log_path(args, trial_content): '''parse log path''' path_list = [] host_list = [] for trial in trial_content: if args.trial_id and args.trial_id != 'all' and trial.get('id') != args.trial_id: continue pattern = r'(?P<head>.+)://(?P<host>.+):(?P<path>.*)' mat...
parse log path
Below is the the instruction that describes the task: ### Input: parse log path ### Response: def parse_log_path(args, trial_content): '''parse log path''' path_list = [] host_list = [] for trial in trial_content: if args.trial_id and args.trial_id != 'all' and trial.get('id') != args.trial...
def _get_health_status(self, url, ssl_params, timeout): """ Don't send the "can connect" service check if we have troubles getting the health status """ try: r = self._perform_request(url, "/health", ssl_params, timeout) # we don't use get() here so we can...
Don't send the "can connect" service check if we have troubles getting the health status
Below is the the instruction that describes the task: ### Input: Don't send the "can connect" service check if we have troubles getting the health status ### Response: def _get_health_status(self, url, ssl_params, timeout): """ Don't send the "can connect" service check if we have troubles ...
def add(places, name, cmd, args, env=None, uid=None, gid=None, extras=None, env_inherit=None): """Add a process. :param places: a Places instance :param name: string, the logical name of the process :param cmd: string, executable :param args: list of strings, command-line arguments :par...
Add a process. :param places: a Places instance :param name: string, the logical name of the process :param cmd: string, executable :param args: list of strings, command-line arguments :param env: dictionary mapping strings to strings (will be environment in subprocess) :param uid: int...
Below is the the instruction that describes the task: ### Input: Add a process. :param places: a Places instance :param name: string, the logical name of the process :param cmd: string, executable :param args: list of strings, command-line arguments :param env: dictionary mapping strings to str...
def pool_revert(self, pool_id, version_id): """Function to revert a specific pool (Requires login) (UNTESTED). Parameters: pool_id (int): Where pool_id is the pool id. version_id (int): """ return self._get('pools/{0}/revert.json'.format(pool_id), ...
Function to revert a specific pool (Requires login) (UNTESTED). Parameters: pool_id (int): Where pool_id is the pool id. version_id (int):
Below is the the instruction that describes the task: ### Input: Function to revert a specific pool (Requires login) (UNTESTED). Parameters: pool_id (int): Where pool_id is the pool id. version_id (int): ### Response: def pool_revert(self, pool_id, version_id): """Function ...
def date_time_this_century( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the current century. :param before_now: include days in current century before today :param after_now: include days in current...
Gets a DateTime object for the current century. :param before_now: include days in current century before today :param after_now: include days in current century after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :r...
Below is the the instruction that describes the task: ### Input: Gets a DateTime object for the current century. :param before_now: include days in current century before today :param after_now: include days in current century after today :param tzinfo: timezone, instance of datetime.tzinfo...
def get_tags_of_offer_per_page(self, offer_id, per_page=1000, page=1): """ Get tags of offer per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param offer_id: the offer id :return: list """ return self...
Get tags of offer per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param offer_id: the offer id :return: list
Below is the the instruction that describes the task: ### Input: Get tags of offer per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param offer_id: the offer id :return: list ### Response: def get_tags_of_offer_per_page(self, o...
def factory(cfg, login, pswd, request_type): """ Instantiate ExportRequest :param cfg: request configuration, should consist of request description (url and optional parameters) :param login: :param pswd: :param request_type: TYPE_SET_FIELD_VALUE || TYPE_CREATE_ENTITY || ...
Instantiate ExportRequest :param cfg: request configuration, should consist of request description (url and optional parameters) :param login: :param pswd: :param request_type: TYPE_SET_FIELD_VALUE || TYPE_CREATE_ENTITY || TYPE_DELETE_ENTITY || TYPE_CREATE_RELATION :return: Expor...
Below is the the instruction that describes the task: ### Input: Instantiate ExportRequest :param cfg: request configuration, should consist of request description (url and optional parameters) :param login: :param pswd: :param request_type: TYPE_SET_FIELD_VALUE || TYPE_CREATE_ENTITY...
def convert_md_to_rst(source, destination=None, backup_dir=None): """Try to convert the source, an .md (markdown) file, to an .rst (reStructuredText) file at the destination. If the destination isn't provided, it defaults to be the same as the source path except for the filename extension. If the destin...
Try to convert the source, an .md (markdown) file, to an .rst (reStructuredText) file at the destination. If the destination isn't provided, it defaults to be the same as the source path except for the filename extension. If the destination file already exists, it will be overwritten. In the event of an...
Below is the the instruction that describes the task: ### Input: Try to convert the source, an .md (markdown) file, to an .rst (reStructuredText) file at the destination. If the destination isn't provided, it defaults to be the same as the source path except for the filename extension. If the destinatio...
def total_variation(arr): ''' If arr is a 2D array (N X M), assumes that arr is a spectrogram with time along axis=0. Calculates the 1D total variation in time for each frequency and returns an array of size M. If arr is a 1D array, calculates total variation and returns a scalar. Sum ( Abs(arr_i+1,j - ...
If arr is a 2D array (N X M), assumes that arr is a spectrogram with time along axis=0. Calculates the 1D total variation in time for each frequency and returns an array of size M. If arr is a 1D array, calculates total variation and returns a scalar. Sum ( Abs(arr_i+1,j - arr_ij) ) If arr is a 2D array,...
Below is the the instruction that describes the task: ### Input: If arr is a 2D array (N X M), assumes that arr is a spectrogram with time along axis=0. Calculates the 1D total variation in time for each frequency and returns an array of size M. If arr is a 1D array, calculates total variation and returns a...
def passes(self): """ Returns a list structure of the appended passes and its options. Returns (list): The appended passes. """ ret = [] for pass_ in self.working_list: ret.append(pass_.dump_passes()) return ret
Returns a list structure of the appended passes and its options. Returns (list): The appended passes.
Below is the the instruction that describes the task: ### Input: Returns a list structure of the appended passes and its options. Returns (list): The appended passes. ### Response: def passes(self): """ Returns a list structure of the appended passes and its options. Returns (list...
def jd_to_datetime(jd, returniso=False): '''This converts a UTC JD to a Python `datetime` object or ISO date string. Parameters ---------- jd : float The Julian date measured at UTC. returniso : bool If False, returns a naive Python `datetime` object corresponding to `jd`....
This converts a UTC JD to a Python `datetime` object or ISO date string. Parameters ---------- jd : float The Julian date measured at UTC. returniso : bool If False, returns a naive Python `datetime` object corresponding to `jd`. If True, returns the ISO format string correspo...
Below is the the instruction that describes the task: ### Input: This converts a UTC JD to a Python `datetime` object or ISO date string. Parameters ---------- jd : float The Julian date measured at UTC. returniso : bool If False, returns a naive Python `datetime` object correspon...
def class_dict_to_specs(mcs, class_dict): """Takes a class `__dict__` and returns `HeronComponentSpec` entries""" specs = {} for name, spec in class_dict.items(): if isinstance(spec, HeronComponentSpec): # Use the variable name as the specification name. if spec.name is None: ...
Takes a class `__dict__` and returns `HeronComponentSpec` entries
Below is the the instruction that describes the task: ### Input: Takes a class `__dict__` and returns `HeronComponentSpec` entries ### Response: def class_dict_to_specs(mcs, class_dict): """Takes a class `__dict__` and returns `HeronComponentSpec` entries""" specs = {} for name, spec in class_dict.ite...
def _release(level): """TODO: we should make sure that we are on master release""" version, comment = _new_version(level) if version is not None: run(['git', 'commit', str(VER_PATH.relative_to(BASE_PATH)), str(CHANGES_PATH.relative_to(BASE_PATH)), ...
TODO: we should make sure that we are on master release
Below is the the instruction that describes the task: ### Input: TODO: we should make sure that we are on master release ### Response: def _release(level): """TODO: we should make sure that we are on master release""" version, comment = _new_version(level) if version is not None: run(['git', ...
def pad(data, padwidth, value=0.0): """ Pad an array with a specific value. Parameters ---------- data : ndarray Numpy array of any dimension and type. padwidth : int or tuple If int, it will pad using this amount at the beginning and end of all dimensions. If it is a tu...
Pad an array with a specific value. Parameters ---------- data : ndarray Numpy array of any dimension and type. padwidth : int or tuple If int, it will pad using this amount at the beginning and end of all dimensions. If it is a tuple (of same length as `ndim`), then the ...
Below is the the instruction that describes the task: ### Input: Pad an array with a specific value. Parameters ---------- data : ndarray Numpy array of any dimension and type. padwidth : int or tuple If int, it will pad using this amount at the beginning and end of all dime...
def describe_events(SourceIdentifier=None, SourceType=None, StartTime=None, EndTime=None, Duration=None, EventCategories=None, Filters=None, MaxRecords=None, Marker=None): """ Lists events for a given source identifier and source type. You can also specify a start and end time. For more information on AWS DMS e...
Lists events for a given source identifier and source type. You can also specify a start and end time. For more information on AWS DMS events, see Working with Events and Notifications . See also: AWS API Documentation :example: response = client.describe_events( SourceIdentifier='string', ...
Below is the the instruction that describes the task: ### Input: Lists events for a given source identifier and source type. You can also specify a start and end time. For more information on AWS DMS events, see Working with Events and Notifications . See also: AWS API Documentation :example: resp...
def __connect(host, port, username, password, private_key): """ Establish remote connection :param host: Hostname or IP address to connect to :param port: Port number to use for SSH :param username: Username credentials for SSH access :param password: Password credential...
Establish remote connection :param host: Hostname or IP address to connect to :param port: Port number to use for SSH :param username: Username credentials for SSH access :param password: Password credentials for SSH access (or private key passphrase) :param private_key: Private...
Below is the the instruction that describes the task: ### Input: Establish remote connection :param host: Hostname or IP address to connect to :param port: Port number to use for SSH :param username: Username credentials for SSH access :param password: Password credentials for SSH a...
def add_parent_commands(self, cmd_path, help=None): """ Create parent command object in cmd tree then return the last parent command object. :rtype: dict """ existed_cmd_end_index = self.index_in_tree(cmd_path) new_path, existed_path = self._get_paths( ...
Create parent command object in cmd tree then return the last parent command object. :rtype: dict
Below is the the instruction that describes the task: ### Input: Create parent command object in cmd tree then return the last parent command object. :rtype: dict ### Response: def add_parent_commands(self, cmd_path, help=None): """ Create parent command object in cmd tree then retu...
def stash_calibration(self, attenuations, freqs, frange, calname): """Save it for later""" self.calibration_vector = attenuations self.calibration_freqs = freqs self.calibration_frange = frange self.calname = calname
Save it for later
Below is the the instruction that describes the task: ### Input: Save it for later ### Response: def stash_calibration(self, attenuations, freqs, frange, calname): """Save it for later""" self.calibration_vector = attenuations self.calibration_freqs = freqs self.calibration_frange =...
def stats(self, key=None): """ Return server stats. :param key: Optional if you want status from a key. :type key: six.string_types :return: A dict with server stats :rtype: dict """ # TODO: Stats with key is not working. returns = {} for...
Return server stats. :param key: Optional if you want status from a key. :type key: six.string_types :return: A dict with server stats :rtype: dict
Below is the the instruction that describes the task: ### Input: Return server stats. :param key: Optional if you want status from a key. :type key: six.string_types :return: A dict with server stats :rtype: dict ### Response: def stats(self, key=None): """ Return s...
def viterbi_decoder(self,x,metric_type='soft',quant_level=3): """ A method which performs Viterbi decoding of noisy bit stream, taking as input soft bit values centered on +/-1 and returning hard decision 0/1 bits. Parameters ---------- x: Received noisy...
A method which performs Viterbi decoding of noisy bit stream, taking as input soft bit values centered on +/-1 and returning hard decision 0/1 bits. Parameters ---------- x: Received noisy bit values centered on +/-1 at one sample per bit metric_type: ...
Below is the the instruction that describes the task: ### Input: A method which performs Viterbi decoding of noisy bit stream, taking as input soft bit values centered on +/-1 and returning hard decision 0/1 bits. Parameters ---------- x: Received noisy bit values cen...
def assertDutTraceDoesNotContain(dut, message, bench): """ Raise TestStepFail if bench.verify_trace does not find message from dut traces. :param dut: Dut object. :param message: Message to look for. :param: Bench, must contain verify_trace method. :raises: AttributeError if bench does not cont...
Raise TestStepFail if bench.verify_trace does not find message from dut traces. :param dut: Dut object. :param message: Message to look for. :param: Bench, must contain verify_trace method. :raises: AttributeError if bench does not contain verify_trace method. TestStepFail if verify_trace returns T...
Below is the the instruction that describes the task: ### Input: Raise TestStepFail if bench.verify_trace does not find message from dut traces. :param dut: Dut object. :param message: Message to look for. :param: Bench, must contain verify_trace method. :raises: AttributeError if bench does not co...
def merge_graphs(main_graph, addition_graph): """Merges an ''addition_graph'' into the ''main_graph''. Returns a tuple of dictionaries, mapping old node ids and edge ids to new ids. """ node_mapping = {} edge_mapping = {} for node in addition_graph.get_all_node_objects(): node_id = nod...
Merges an ''addition_graph'' into the ''main_graph''. Returns a tuple of dictionaries, mapping old node ids and edge ids to new ids.
Below is the the instruction that describes the task: ### Input: Merges an ''addition_graph'' into the ''main_graph''. Returns a tuple of dictionaries, mapping old node ids and edge ids to new ids. ### Response: def merge_graphs(main_graph, addition_graph): """Merges an ''addition_graph'' into the ''main_g...
def _terminate(self): '''Shutdown agent gently removing the descriptor and notifying partners.''' def generate_body(): d = defer.succeed(None) d.addBoth(defer.drop_param, self.agent.shutdown_agent) # Delete the descriptor d.addBoth(lambda _: self....
Shutdown agent gently removing the descriptor and notifying partners.
Below is the the instruction that describes the task: ### Input: Shutdown agent gently removing the descriptor and notifying partners. ### Response: def _terminate(self): '''Shutdown agent gently removing the descriptor and notifying partners.''' def generate_body(): d ...
def _load_templates(workflow: dict, templates_root: str): """Load templates keys.""" workflow_template_path = join(templates_root, workflow['id'], workflow['version']) for i, stage_config in enumerate(workflow['stages']): stage_template_path = join(workflow_template...
Load templates keys.
Below is the the instruction that describes the task: ### Input: Load templates keys. ### Response: def _load_templates(workflow: dict, templates_root: str): """Load templates keys.""" workflow_template_path = join(templates_root, workflow['id'], workflow['version']) f...
def make_op_return_tx(data, private_key, blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE, change_address=None, format='bin'): """ Builds and signs an OP_RETURN transaction. """ # get out the private key object, sending address, and inputs private_key_obj, from_address, inputs...
Builds and signs an OP_RETURN transaction.
Below is the the instruction that describes the task: ### Input: Builds and signs an OP_RETURN transaction. ### Response: def make_op_return_tx(data, private_key, blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE, change_address=None, format='bin'): """ Builds and signs an OP_RETURN t...
def table(T_table_world=RigidTransform(from_frame='table', to_frame='world'), dim=0.16, color=(0,0,0)): """Plot a table mesh in 3D. Parameters ---------- T_table_world : autolab_core.RigidTransform Pose of table relative to world. dim : float The side-len...
Plot a table mesh in 3D. Parameters ---------- T_table_world : autolab_core.RigidTransform Pose of table relative to world. dim : float The side-length for the table. color : 3-tuple Color tuple.
Below is the the instruction that describes the task: ### Input: Plot a table mesh in 3D. Parameters ---------- T_table_world : autolab_core.RigidTransform Pose of table relative to world. dim : float The side-length for the table. color : 3-tuple ...
def get_string_polyglot_attack(self, obj): """ Return a polyglot attack containing the original object """ return self.polyglot_attacks[random.choice(self.config.techniques)] % obj
Return a polyglot attack containing the original object
Below is the the instruction that describes the task: ### Input: Return a polyglot attack containing the original object ### Response: def get_string_polyglot_attack(self, obj): """ Return a polyglot attack containing the original object """ return self.polyglot_attacks[random.choic...
def get_depth_term(self, C, rup): """ Returns depth term (dependent on top of rupture depth) as given in equations 1 Note that there is a ztor cap of 100 km that is introduced in the Fortran code but not mentioned in the original paper! """ if rup.ztor > 100.0: ...
Returns depth term (dependent on top of rupture depth) as given in equations 1 Note that there is a ztor cap of 100 km that is introduced in the Fortran code but not mentioned in the original paper!
Below is the the instruction that describes the task: ### Input: Returns depth term (dependent on top of rupture depth) as given in equations 1 Note that there is a ztor cap of 100 km that is introduced in the Fortran code but not mentioned in the original paper! ### Response: def get_dept...
def reply(self, timeout=None): """ Returns the initial reply. This is emitted before any subscription data is emitted. This function raises an exception if the subscription attempt failed. """ self._wait_on_signal(self._response_received) if self._response_excepti...
Returns the initial reply. This is emitted before any subscription data is emitted. This function raises an exception if the subscription attempt failed.
Below is the the instruction that describes the task: ### Input: Returns the initial reply. This is emitted before any subscription data is emitted. This function raises an exception if the subscription attempt failed. ### Response: def reply(self, timeout=None): """ Returns the ini...
def create_full_tear_sheet(factor_data, long_short=True, group_neutral=False, by_group=False): """ Creates a full tear sheet for analysis and evaluating single return predicting (alpha) factor. Parameters ---------- ...
Creates a full tear sheet for analysis and evaluating single return predicting (alpha) factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward ret...
Below is the the instruction that describes the task: ### Input: Creates a full tear sheet for analysis and evaluating single return predicting (alpha) factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1),...
def execute(self, conn, app, release_version, pset_hash, output_label, global_tag, transaction = False): """ returns id for a given application This always requires all four variables to be set, because you better have them in blockInsert """ binds = {} binds["ap...
returns id for a given application This always requires all four variables to be set, because you better have them in blockInsert
Below is the the instruction that describes the task: ### Input: returns id for a given application This always requires all four variables to be set, because you better have them in blockInsert ### Response: def execute(self, conn, app, release_version, pset_hash, output_label, global_tag, transa...
def write(self): """ Writes the ``.sln`` file to disk. """ filters = { 'MSGUID': lambda x: ('{%s}' % x).upper(), 'relslnfile': lambda x: os.path.relpath(x, os.path.dirname(self.FileName)) } context = { 'sln': self } retu...
Writes the ``.sln`` file to disk.
Below is the the instruction that describes the task: ### Input: Writes the ``.sln`` file to disk. ### Response: def write(self): """ Writes the ``.sln`` file to disk. """ filters = { 'MSGUID': lambda x: ('{%s}' % x).upper(), 'relslnfile': lambda x: os.path.r...