code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def depth(self, value): """ Update ourself and any of our subcommands. """ for command in self.subcommands.values(): command.depth = value + 1 del command.argparser._defaults[self.arg_label_fmt % self._depth] command.argparser._defaults[self.arg_label_fmt % value] = c...
Update ourself and any of our subcommands.
Below is the the instruction that describes the task: ### Input: Update ourself and any of our subcommands. ### Response: def depth(self, value): """ Update ourself and any of our subcommands. """ for command in self.subcommands.values(): command.depth = value + 1 del comman...
def load(self, filepath): # type: (str) -> None """Load configuration from existing file. :param str filepath: Path to existing config file. :raises: ValueError if supplied config file is invalid. """ try: self._config.read(filepath) import ast ...
Load configuration from existing file. :param str filepath: Path to existing config file. :raises: ValueError if supplied config file is invalid.
Below is the the instruction that describes the task: ### Input: Load configuration from existing file. :param str filepath: Path to existing config file. :raises: ValueError if supplied config file is invalid. ### Response: def load(self, filepath): # type: (str) -> None """Load c...
def queryModelIDs(self): """Queuries DB for model IDs of all currently instantiated models associated with this HyperSearch job. See also: _iterModels() Parameters: ---------------------------------------------------------------------- retval: A sequence of Nupic modelIDs """ j...
Queuries DB for model IDs of all currently instantiated models associated with this HyperSearch job. See also: _iterModels() Parameters: ---------------------------------------------------------------------- retval: A sequence of Nupic modelIDs
Below is the the instruction that describes the task: ### Input: Queuries DB for model IDs of all currently instantiated models associated with this HyperSearch job. See also: _iterModels() Parameters: ---------------------------------------------------------------------- retval: A seq...
def checkppolicy(self, **params): """ search user page """ self._check_auth(must_admin=False, redir_login=False) keys = list(params.keys()) if len(keys) != 1: cherrypy.response.status = 400 return "bad argument" password = params[keys[0]] is_admin ...
search user page
Below is the the instruction that describes the task: ### Input: search user page ### Response: def checkppolicy(self, **params): """ search user page """ self._check_auth(must_admin=False, redir_login=False) keys = list(params.keys()) if len(keys) != 1: cherrypy.respons...
def metrics(self, *metrics): """ Add a list of Metric ingredients to the query. These can either be Metric objects or strings representing metrics on the shelf. The Metric expression will be added to the query's select statement. The metric value is a property of each row of the result....
Add a list of Metric ingredients to the query. These can either be Metric objects or strings representing metrics on the shelf. The Metric expression will be added to the query's select statement. The metric value is a property of each row of the result. :param metrics: Metrics to add ...
Below is the the instruction that describes the task: ### Input: Add a list of Metric ingredients to the query. These can either be Metric objects or strings representing metrics on the shelf. The Metric expression will be added to the query's select statement. The metric value is a propert...
def get_restore_path(self, status=None): """ get_restore_path: get path to restoration file Args: status (str): step to get restore file (optional) Returns: string path to restoration file """ status = self.get_status() if status is None else status ...
get_restore_path: get path to restoration file Args: status (str): step to get restore file (optional) Returns: string path to restoration file
Below is the the instruction that describes the task: ### Input: get_restore_path: get path to restoration file Args: status (str): step to get restore file (optional) Returns: string path to restoration file ### Response: def get_restore_path(self, status=None): """...
def patch_cluster_custom_object_status(self, group, version, plural, name, body, **kwargs): # noqa: E501 """patch_cluster_custom_object_status # noqa: E501 partially update status of the specified cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by defau...
patch_cluster_custom_object_status # noqa: E501 partially update status of the specified cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_cluster_c...
Below is the the instruction that describes the task: ### Input: patch_cluster_custom_object_status # noqa: E501 partially update status of the specified cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request...
def persistent_attributes(self, persistent_attributes): # type: (Dict[str, object]) -> None """Overwrites and caches the persistent attributes value. Note that the persistent attributes will not be saved to persistence layer until the save_persistent_attributes method is called....
Overwrites and caches the persistent attributes value. Note that the persistent attributes will not be saved to persistence layer until the save_persistent_attributes method is called. :param persistent_attributes: attributes in persistence layer :type persistent_attributes: Di...
Below is the the instruction that describes the task: ### Input: Overwrites and caches the persistent attributes value. Note that the persistent attributes will not be saved to persistence layer until the save_persistent_attributes method is called. :param persistent_attributes: at...
def parsed_aggregate_reports_to_csv(reports): """ Converts one or more parsed aggregate reports to flat CSV format, including headers Args: reports: A parsed aggregate report or list of parsed aggregate reports Returns: str: Parsed aggregate report data in flat CSV format, includin...
Converts one or more parsed aggregate reports to flat CSV format, including headers Args: reports: A parsed aggregate report or list of parsed aggregate reports Returns: str: Parsed aggregate report data in flat CSV format, including headers
Below is the the instruction that describes the task: ### Input: Converts one or more parsed aggregate reports to flat CSV format, including headers Args: reports: A parsed aggregate report or list of parsed aggregate reports Returns: str: Parsed aggregate report data in flat CSV forma...
def get_vboxes(self): """ Get the maximum ID of the VBoxes :return: Maximum VBox ID :rtype: int """ vbox_list = [] vbox_max = None for node in self.nodes: if node['type'] == 'VirtualBoxVM': vbox_list.append(node['vbox_id']) ...
Get the maximum ID of the VBoxes :return: Maximum VBox ID :rtype: int
Below is the the instruction that describes the task: ### Input: Get the maximum ID of the VBoxes :return: Maximum VBox ID :rtype: int ### Response: def get_vboxes(self): """ Get the maximum ID of the VBoxes :return: Maximum VBox ID :rtype: int """ ...
def verify_light_chains(self, threshold=0.9): ''' Clusters the light chains to identify potentially spurious (non-lineage) pairings. Following clustering, all pairs in the largest light chain cluster are assumed to be correctly paired. For each of those pairs, the <verified> attr...
Clusters the light chains to identify potentially spurious (non-lineage) pairings. Following clustering, all pairs in the largest light chain cluster are assumed to be correctly paired. For each of those pairs, the <verified> attribute is set to True. For pairs not in the largest light c...
Below is the the instruction that describes the task: ### Input: Clusters the light chains to identify potentially spurious (non-lineage) pairings. Following clustering, all pairs in the largest light chain cluster are assumed to be correctly paired. For each of those pairs, the <verified> a...
def AddDischargingBattery(self, device_name, model_name, percentage, seconds_to_empty): '''Convenience method to add a discharging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seco...
Convenience method to add a discharging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seconds until the battery is empty. Please note that this does not set any global properties s...
Below is the the instruction that describes the task: ### Input: Convenience method to add a discharging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seconds until the battery is e...
def appendBPoint(self, type=None, anchor=None, bcpIn=None, bcpOut=None, bPoint=None): """ Append a bPoint to the contour. """ if bPoint is not None: if type is None: type = bPoint.type if anchor is None: anchor = bPoint.anchor ...
Append a bPoint to the contour.
Below is the the instruction that describes the task: ### Input: Append a bPoint to the contour. ### Response: def appendBPoint(self, type=None, anchor=None, bcpIn=None, bcpOut=None, bPoint=None): """ Append a bPoint to the contour. """ if bPoint is not None: if type is ...
def dump2json(self, obj, filepath, override=False, **kwargs): """ Dump a dictionary into a JSON dictionary. Uses the json.dump() function. Parameters ---------- obj : :class:`dict` A dictionary to be dumpped as JSON file. filepath : :class:`str` ...
Dump a dictionary into a JSON dictionary. Uses the json.dump() function. Parameters ---------- obj : :class:`dict` A dictionary to be dumpped as JSON file. filepath : :class:`str` The filepath for the dumped file. override : :class:`bool` ...
Below is the the instruction that describes the task: ### Input: Dump a dictionary into a JSON dictionary. Uses the json.dump() function. Parameters ---------- obj : :class:`dict` A dictionary to be dumpped as JSON file. filepath : :class:`str` The f...
def create_pg_notify_event(notif): """A factory for creating a Postgres Notification Event (an object inheriting from `cnxpublishing.events.PGNotifyEvent`) given `notif`, a `psycopg2.extensions.Notify` object. """ # TODO Lookup registered events via getAllUtilitiesRegisteredFor # for class...
A factory for creating a Postgres Notification Event (an object inheriting from `cnxpublishing.events.PGNotifyEvent`) given `notif`, a `psycopg2.extensions.Notify` object.
Below is the the instruction that describes the task: ### Input: A factory for creating a Postgres Notification Event (an object inheriting from `cnxpublishing.events.PGNotifyEvent`) given `notif`, a `psycopg2.extensions.Notify` object. ### Response: def create_pg_notify_event(notif): """A factory for ...
def int_attribute(element, attribute, default=0): """ Returns the int value of an attribute, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param attribute: The name of the attribute to evaluate :type attribute: basestring :param de...
Returns the int value of an attribute, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param attribute: The name of the attribute to evaluate :type attribute: basestring :param default: The default value to return if the attribute is not def...
Below is the the instruction that describes the task: ### Input: Returns the int value of an attribute, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param attribute: The name of the attribute to evaluate :type attribute: basestring :p...
def extract_time(match): """extract time from a time_re match.""" hour = int(match.group('hour')) minute = int(match.group('minute')) return dt.time(hour, minute)
extract time from a time_re match.
Below is the the instruction that describes the task: ### Input: extract time from a time_re match. ### Response: def extract_time(match): """extract time from a time_re match.""" hour = int(match.group('hour')) minute = int(match.group('minute')) return dt.time(hour, minute)
def RecordEvent(self, metric_name, value, fields=None): """See base class.""" self._event_metrics[metric_name].Record(value, fields)
See base class.
Below is the the instruction that describes the task: ### Input: See base class. ### Response: def RecordEvent(self, metric_name, value, fields=None): """See base class.""" self._event_metrics[metric_name].Record(value, fields)
async def put(self, path=''): """Publish a notebook on a given path. The payload directly matches the contents API for PUT. """ self.log.info("Attempt publishing to %s", path) if path == '' or path == '/': raise web.HTTPError(400, "Must provide a path for publishing...
Publish a notebook on a given path. The payload directly matches the contents API for PUT.
Below is the the instruction that describes the task: ### Input: Publish a notebook on a given path. The payload directly matches the contents API for PUT. ### Response: async def put(self, path=''): """Publish a notebook on a given path. The payload directly matches the contents API for ...
def find_any_reports(self, usage_page = 0, usage_id = 0): """Find any report type referencing HID usage control/data item. Results are returned in a dictionary mapping report_type to usage lists. """ items = [ (HidP_Input, self.find_input_reports(usage_page, ...
Find any report type referencing HID usage control/data item. Results are returned in a dictionary mapping report_type to usage lists.
Below is the the instruction that describes the task: ### Input: Find any report type referencing HID usage control/data item. Results are returned in a dictionary mapping report_type to usage lists. ### Response: def find_any_reports(self, usage_page = 0, usage_id = 0): """Find any repo...
def project_usls_on_dictionary(usls, allowed_terms=None): """`usls` is an iterable of usl. return a mapping term -> usl list """ cells_to_usls = defaultdict(set) tables = set() for u in usls: for t in u.objects(Term): for c in t.singular_sequences: # This i...
`usls` is an iterable of usl. return a mapping term -> usl list
Below is the the instruction that describes the task: ### Input: `usls` is an iterable of usl. return a mapping term -> usl list ### Response: def project_usls_on_dictionary(usls, allowed_terms=None): """`usls` is an iterable of usl. return a mapping term -> usl list """ cells_to_usls = defa...
def count(self, flag_message, padding=None, force=False): """ Log Level: :attr:COUNT @flag_message: time-like #float @padding: #str 'top', 'bottom' or 'all', adds a new line to the specified area with :func:padd @force: #bool whether or not to force the messa...
Log Level: :attr:COUNT @flag_message: time-like #float @padding: #str 'top', 'bottom' or 'all', adds a new line to the specified area with :func:padd @force: #bool whether or not to force the message to log in spite of the assigned log level ...
Below is the the instruction that describes the task: ### Input: Log Level: :attr:COUNT @flag_message: time-like #float @padding: #str 'top', 'bottom' or 'all', adds a new line to the specified area with :func:padd @force: #bool whether or not to force the messag...
def add_texts(self, reference_id, texts): """\ Adds the words from the provided iterable `texts` to the corpus. The strings will be tokenized. `reference_id` The reference identifier of the cable. `texts` An iterable of strings. """ self....
\ Adds the words from the provided iterable `texts` to the corpus. The strings will be tokenized. `reference_id` The reference identifier of the cable. `texts` An iterable of strings.
Below is the the instruction that describes the task: ### Input: \ Adds the words from the provided iterable `texts` to the corpus. The strings will be tokenized. `reference_id` The reference identifier of the cable. `texts` An iterable of strings. ### Respo...
def _eq(self, T, P): """Procedure for calculate the composition in saturation state Parameters ---------- T : float Temperature [K] P : float Pressure [MPa] Returns ------- Asat : float Saturation mass fraction of dry ...
Procedure for calculate the composition in saturation state Parameters ---------- T : float Temperature [K] P : float Pressure [MPa] Returns ------- Asat : float Saturation mass fraction of dry air in humid air [kg/kg]
Below is the the instruction that describes the task: ### Input: Procedure for calculate the composition in saturation state Parameters ---------- T : float Temperature [K] P : float Pressure [MPa] Returns ------- Asat : float ...
def get(self, sid): """ Constructs a CredentialContext :param sid: The unique id that identifies the resource to fetch. :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential....
Constructs a CredentialContext :param sid: The unique id that identifies the resource to fetch. :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext
Below is the the instruction that describes the task: ### Input: Constructs a CredentialContext :param sid: The unique id that identifies the resource to fetch. :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialContext :rtype: twilio.rest.api.v2010.account.si...
def __last_commit(self): """ Retrieve the most recent commit message (with ``svn info``) Returns: tuple: (datestr, (revno, user, None, desc)) $ svn info Path: . URL: http://python-dlp.googlecode.com/svn/trunk/layercake-python Repository Root: http://...
Retrieve the most recent commit message (with ``svn info``) Returns: tuple: (datestr, (revno, user, None, desc)) $ svn info Path: . URL: http://python-dlp.googlecode.com/svn/trunk/layercake-python Repository Root: http://python-dlp.googlecode.com/svn Reposit...
Below is the the instruction that describes the task: ### Input: Retrieve the most recent commit message (with ``svn info``) Returns: tuple: (datestr, (revno, user, None, desc)) $ svn info Path: . URL: http://python-dlp.googlecode.com/svn/trunk/layercake-python ...
def translate_output_properties(res: 'Resource', output: Any) -> Any: """ Recursively rewrite keys of objects returned by the engine to conform with a naming convention specified by the resource's implementation of `translate_output_property`. If output is a `dict`, every key is translated using `trans...
Recursively rewrite keys of objects returned by the engine to conform with a naming convention specified by the resource's implementation of `translate_output_property`. If output is a `dict`, every key is translated using `translate_output_property` while every value is transformed by recursing. If o...
Below is the the instruction that describes the task: ### Input: Recursively rewrite keys of objects returned by the engine to conform with a naming convention specified by the resource's implementation of `translate_output_property`. If output is a `dict`, every key is translated using `translate_output_p...
def retrieve(self, *args, **kwargs): """Retrieve the permsission function for the provided things. """ lookup, key = self._lookup(*args, **kwargs) return lookup[key]
Retrieve the permsission function for the provided things.
Below is the the instruction that describes the task: ### Input: Retrieve the permsission function for the provided things. ### Response: def retrieve(self, *args, **kwargs): """Retrieve the permsission function for the provided things. """ lookup, key = self._lookup(*args, **kwargs) ...
def elog(exc, func, args=None, kwargs=None, str=str, pretty=True, name=''): '''For logging exception-raising function invocations during randomized unit tests. ''' from .str import safe_str args = args if args else () kwargs = kwargs if kwargs else {} name = '{}.{}'.format(get_mod(func), name) ...
For logging exception-raising function invocations during randomized unit tests.
Below is the the instruction that describes the task: ### Input: For logging exception-raising function invocations during randomized unit tests. ### Response: def elog(exc, func, args=None, kwargs=None, str=str, pretty=True, name=''): '''For logging exception-raising function invocations during randomized uni...
def process_api_config_response(self, config_json): """Parses a JSON API config and registers methods for dispatch. Side effects: Parses method name, etc. for all methods and updates the indexing data structures with the information. Args: config_json: A dict, the JSON body of the getApi...
Parses a JSON API config and registers methods for dispatch. Side effects: Parses method name, etc. for all methods and updates the indexing data structures with the information. Args: config_json: A dict, the JSON body of the getApiConfigs response.
Below is the the instruction that describes the task: ### Input: Parses a JSON API config and registers methods for dispatch. Side effects: Parses method name, etc. for all methods and updates the indexing data structures with the information. Args: config_json: A dict, the JSON body of ...
def load_class_by_name(name: str): """Given a dotted path, returns the class""" mod_path, _, cls_name = name.rpartition('.') mod = importlib.import_module(mod_path) cls = getattr(mod, cls_name) return cls
Given a dotted path, returns the class
Below is the the instruction that describes the task: ### Input: Given a dotted path, returns the class ### Response: def load_class_by_name(name: str): """Given a dotted path, returns the class""" mod_path, _, cls_name = name.rpartition('.') mod = importlib.import_module(mod_path) cls = getattr(mo...
def export(self, filename='element.zip'): """ Export this element. Usage:: engine = Engine('myfirewall') extask = engine.export(filename='fooexport.zip') while not extask.done(): extask.wait(3) print("Finished download task: %s" %...
Export this element. Usage:: engine = Engine('myfirewall') extask = engine.export(filename='fooexport.zip') while not extask.done(): extask.wait(3) print("Finished download task: %s" % extask.message()) print("File downloaded to: %s" ...
Below is the the instruction that describes the task: ### Input: Export this element. Usage:: engine = Engine('myfirewall') extask = engine.export(filename='fooexport.zip') while not extask.done(): extask.wait(3) print("Finished download task...
def order_limit_buy(self, timeInForce=TIME_IN_FORCE_GTC, **params): """Send in a new limit buy order Any order with an icebergQty MUST have timeInForce set to GTC. :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param...
Send in a new limit buy order Any order with an icebergQty MUST have timeInForce set to GTC. :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param price: required :type price: str :param timeInForce: default G...
Below is the the instruction that describes the task: ### Input: Send in a new limit buy order Any order with an icebergQty MUST have timeInForce set to GTC. :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param price: re...
def get_process(cmd): """Get a command process.""" if sys.platform.startswith('win'): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen( cmd, startupinfo=startupinfo, stdout=subpro...
Get a command process.
Below is the the instruction that describes the task: ### Input: Get a command process. ### Response: def get_process(cmd): """Get a command process.""" if sys.platform.startswith('win'): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW ...
def bovy_print(fig_width=5,fig_height=5,axes_labelsize=16, text_fontsize=11,legend_fontsize=12, xtick_labelsize=10,ytick_labelsize=10, xtick_minor_size=2,ytick_minor_size=2, xtick_major_size=4,ytick_major_size=4): """ NAME: bovy_print PURP...
NAME: bovy_print PURPOSE: setup a figure for plotting INPUT: fig_width - width in inches fig_height - height in inches axes_labelsize - size of the axis-labels text_fontsize - font-size of the text (if any) legend_fontsize - font-size of the legend (if a...
Below is the the instruction that describes the task: ### Input: NAME: bovy_print PURPOSE: setup a figure for plotting INPUT: fig_width - width in inches fig_height - height in inches axes_labelsize - size of the axis-labels text_fontsize - font-size of the ...
def save_base_map(filename, grouped_by_text): """Dump a list of agents along with groundings and counts into a csv file Parameters ---------- filename : str Filepath for output file grouped_by_text : list of tuple List of tuples of the form output by agent_texts_with_grounding "...
Dump a list of agents along with groundings and counts into a csv file Parameters ---------- filename : str Filepath for output file grouped_by_text : list of tuple List of tuples of the form output by agent_texts_with_grounding
Below is the the instruction that describes the task: ### Input: Dump a list of agents along with groundings and counts into a csv file Parameters ---------- filename : str Filepath for output file grouped_by_text : list of tuple List of tuples of the form output by agent_texts_with...
def cudaMemcpy_dtoh(dst, src, count): """ Copy memory from device to host. Copy data from device memory to host memory. Parameters ---------- dst : ctypes pointer Host memory pointer. src : ctypes pointer Device memory pointer. count : int Number of bytes to cop...
Copy memory from device to host. Copy data from device memory to host memory. Parameters ---------- dst : ctypes pointer Host memory pointer. src : ctypes pointer Device memory pointer. count : int Number of bytes to copy.
Below is the the instruction that describes the task: ### Input: Copy memory from device to host. Copy data from device memory to host memory. Parameters ---------- dst : ctypes pointer Host memory pointer. src : ctypes pointer Device memory pointer. count : int Num...
def run(self, func=None): """ Evaluates the packaged function as func(*self.args,**self.kwargs) If func is a method of an object, it's accessed as getattr(self.obj,__name__). If it's a user-defined function, it needs to be passed in here because it can't be serialized. R...
Evaluates the packaged function as func(*self.args,**self.kwargs) If func is a method of an object, it's accessed as getattr(self.obj,__name__). If it's a user-defined function, it needs to be passed in here because it can't be serialized. Returns: object: function's return ...
Below is the the instruction that describes the task: ### Input: Evaluates the packaged function as func(*self.args,**self.kwargs) If func is a method of an object, it's accessed as getattr(self.obj,__name__). If it's a user-defined function, it needs to be passed in here because it can't be...
def add_ref(self, name, ref): """ Add a reference for the backend object that gives access to the low level context. Used in vispy.app.canvas.backends. The given name must match with that of previously added references. """ if self._name is None: self._name = ...
Add a reference for the backend object that gives access to the low level context. Used in vispy.app.canvas.backends. The given name must match with that of previously added references.
Below is the the instruction that describes the task: ### Input: Add a reference for the backend object that gives access to the low level context. Used in vispy.app.canvas.backends. The given name must match with that of previously added references. ### Response: def add_ref(self, name, re...
def _updateTransitionMatrix(self): """ Updates the hidden-state transition matrix and the initial distribution """ # TRANSITION MATRIX C = self.model.count_matrix() + self.prior_C # posterior count matrix # check if we work with these options if self.reversible...
Updates the hidden-state transition matrix and the initial distribution
Below is the the instruction that describes the task: ### Input: Updates the hidden-state transition matrix and the initial distribution ### Response: def _updateTransitionMatrix(self): """ Updates the hidden-state transition matrix and the initial distribution """ # TRANSITION MAT...
def convertAsOpenMath(term, converter): """ Converts a term into OpenMath, using either a converter or the interpretAsOpenMath method """ # if we already have openmath, or have some of our magic helpers, use interpretAsOpenMath if hasattr(term, "_ishelper") and term._ishelper or isinstance(term, om.OMA...
Converts a term into OpenMath, using either a converter or the interpretAsOpenMath method
Below is the the instruction that describes the task: ### Input: Converts a term into OpenMath, using either a converter or the interpretAsOpenMath method ### Response: def convertAsOpenMath(term, converter): """ Converts a term into OpenMath, using either a converter or the interpretAsOpenMath method """ ...
def fromdict(dict): """Takes a dictionary as an argument and returns a new Challenge object from the dictionary. :param dict: the dictionary to convert """ seed = hb_decode(dict['seed']) index = dict['index'] return Challenge(seed, index)
Takes a dictionary as an argument and returns a new Challenge object from the dictionary. :param dict: the dictionary to convert
Below is the the instruction that describes the task: ### Input: Takes a dictionary as an argument and returns a new Challenge object from the dictionary. :param dict: the dictionary to convert ### Response: def fromdict(dict): """Takes a dictionary as an argument and returns a new Challen...
def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json()
Returns a client.
Below is the the instruction that describes the task: ### Input: Returns a client. ### Response: def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json()
def add_entry(self, length): # type: (int) -> int ''' Add a new entry to this Rock Ridge Continuation Block. This method attempts to find a gap that fits the new length anywhere within this Continuation Block. If successful, it returns the offset at which it placed this...
Add a new entry to this Rock Ridge Continuation Block. This method attempts to find a gap that fits the new length anywhere within this Continuation Block. If successful, it returns the offset at which it placed this entry. If unsuccessful, it returns None. Parameters: lengt...
Below is the the instruction that describes the task: ### Input: Add a new entry to this Rock Ridge Continuation Block. This method attempts to find a gap that fits the new length anywhere within this Continuation Block. If successful, it returns the offset at which it placed this entry. ...
def db_putHex(self, db_name, key, value): """https://github.com/ethereum/wiki/wiki/JSON-RPC#db_puthex DEPRECATED """ warnings.warn('deprecated', DeprecationWarning) if not value.startswith('0x'): value = add_0x(value) return (yield from self.rpc_call('db_putH...
https://github.com/ethereum/wiki/wiki/JSON-RPC#db_puthex DEPRECATED
Below is the the instruction that describes the task: ### Input: https://github.com/ethereum/wiki/wiki/JSON-RPC#db_puthex DEPRECATED ### Response: def db_putHex(self, db_name, key, value): """https://github.com/ethereum/wiki/wiki/JSON-RPC#db_puthex DEPRECATED """ warnings....
def visit_comprehension(self, node, parent): """visit a Comprehension node by returning a fresh instance of it""" newnode = nodes.Comprehension(parent) newnode.postinit( self.visit(node.target, newnode), self.visit(node.iter, newnode), [self.visit(child, newno...
visit a Comprehension node by returning a fresh instance of it
Below is the the instruction that describes the task: ### Input: visit a Comprehension node by returning a fresh instance of it ### Response: def visit_comprehension(self, node, parent): """visit a Comprehension node by returning a fresh instance of it""" newnode = nodes.Comprehension(parent) ...
def check_undelivered(to=None): """Sends a notification email if any undelivered dispatches. Returns undelivered (failed) dispatches count. :param str|unicode to: Recipient address. If not set Django ADMINS setting is used. :rtype: int """ failed_count = Dispatch.objects.filter(dispatch_statu...
Sends a notification email if any undelivered dispatches. Returns undelivered (failed) dispatches count. :param str|unicode to: Recipient address. If not set Django ADMINS setting is used. :rtype: int
Below is the the instruction that describes the task: ### Input: Sends a notification email if any undelivered dispatches. Returns undelivered (failed) dispatches count. :param str|unicode to: Recipient address. If not set Django ADMINS setting is used. :rtype: int ### Response: def check_undelivered...
def runSearchReads(self, request): """ Runs the specified SearchReadsRequest. """ return self.runSearchRequest( request, protocol.SearchReadsRequest, protocol.SearchReadsResponse, self.readsGenerator)
Runs the specified SearchReadsRequest.
Below is the the instruction that describes the task: ### Input: Runs the specified SearchReadsRequest. ### Response: def runSearchReads(self, request): """ Runs the specified SearchReadsRequest. """ return self.runSearchRequest( request, protocol.SearchReadsRequest, ...
def g_voigt(self): """ returns the G_v shear modulus """ return (2. * self.voigt[:3, :3].trace() - np.triu(self.voigt[:3, :3]).sum() + 3 * self.voigt[3:, 3:].trace()) / 15.
returns the G_v shear modulus
Below is the the instruction that describes the task: ### Input: returns the G_v shear modulus ### Response: def g_voigt(self): """ returns the G_v shear modulus """ return (2. * self.voigt[:3, :3].trace() - np.triu(self.voigt[:3, :3]).sum() + 3 * sel...
def cnst_A1(self, X, Xf=None): r"""Compute :math:`A_1 \mathbf{x}` component of ADMM problem constraint. In this case :math:`A_1 \mathbf{x} = (\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots )^T \mathbf{x}`. """ if Xf is None: Xf = sl.rfftn(X, axes=self.cri.axisN) retu...
r"""Compute :math:`A_1 \mathbf{x}` component of ADMM problem constraint. In this case :math:`A_1 \mathbf{x} = (\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots )^T \mathbf{x}`.
Below is the the instruction that describes the task: ### Input: r"""Compute :math:`A_1 \mathbf{x}` component of ADMM problem constraint. In this case :math:`A_1 \mathbf{x} = (\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots )^T \mathbf{x}`. ### Response: def cnst_A1(self, X, Xf=None): r"""Compute :m...
def _create_cipher(self, password, salt, IV): """ Create the cipher object to encrypt or decrypt a payload. """ from Crypto.Protocol.KDF import PBKDF2 from Crypto.Cipher import AES pw = PBKDF2(password, salt, dkLen=self.block_size) return AES.new(pw[:self.block_si...
Create the cipher object to encrypt or decrypt a payload.
Below is the the instruction that describes the task: ### Input: Create the cipher object to encrypt or decrypt a payload. ### Response: def _create_cipher(self, password, salt, IV): """ Create the cipher object to encrypt or decrypt a payload. """ from Crypto.Protocol.KDF import PB...
def find_project_by_short_name(short_name, pbclient, all=None): """Return project by short_name.""" try: response = pbclient.find_project(short_name=short_name, all=all) check_api_error(response) if (len(response) == 0): msg = '%s not found! You can use the all=1 argument to ...
Return project by short_name.
Below is the the instruction that describes the task: ### Input: Return project by short_name. ### Response: def find_project_by_short_name(short_name, pbclient, all=None): """Return project by short_name.""" try: response = pbclient.find_project(short_name=short_name, all=all) check_api_er...
def download_attachments(self): """ Downloads this message attachments into memory. Need a call to 'attachment.save' to save them on disk. :return: Success / Failure :rtype: bool """ if not self._parent.has_attachments: log.debug( 'Parent {} h...
Downloads this message attachments into memory. Need a call to 'attachment.save' to save them on disk. :return: Success / Failure :rtype: bool
Below is the the instruction that describes the task: ### Input: Downloads this message attachments into memory. Need a call to 'attachment.save' to save them on disk. :return: Success / Failure :rtype: bool ### Response: def download_attachments(self): """ Downloads this message a...
def new_ele_description(**kwargs): ''' from elist.elist import * from elist.jprint import pobj root_desc = new_ele_description(leaf=False,depth=0,breadth_path=[],path=[],parent_path=[],parent_breadth_path=[]) pobj(root_desc) #None means not handled ''' desc = { ...
from elist.elist import * from elist.jprint import pobj root_desc = new_ele_description(leaf=False,depth=0,breadth_path=[],path=[],parent_path=[],parent_breadth_path=[]) pobj(root_desc) #None means not handled
Below is the the instruction that describes the task: ### Input: from elist.elist import * from elist.jprint import pobj root_desc = new_ele_description(leaf=False,depth=0,breadth_path=[],path=[],parent_path=[],parent_breadth_path=[]) pobj(root_desc) #None means not handled ### Respo...
def delete_marked_communities(): """Delete communities after holdout time.""" # TODO: Delete the community ID from all records metadata first raise NotImplementedError() Community.query.filter_by( Community.delete_time > datetime.utcnow()).delete() db.session.commit()
Delete communities after holdout time.
Below is the the instruction that describes the task: ### Input: Delete communities after holdout time. ### Response: def delete_marked_communities(): """Delete communities after holdout time.""" # TODO: Delete the community ID from all records metadata first raise NotImplementedError() Community.q...
def error_for(response): """Return the appropriate initialized exception class for a response.""" klass = error_classes.get(response.status) if klass is None: if 400 <= response.status < 500: klass = ClientError if 500 <= response.status < 600: klass = ServerError # ...
Return the appropriate initialized exception class for a response.
Below is the the instruction that describes the task: ### Input: Return the appropriate initialized exception class for a response. ### Response: def error_for(response): """Return the appropriate initialized exception class for a response.""" klass = error_classes.get(response.status) if klass is None...
def parse(table, query=None, date=None, fields=None, distinct=False, limit=None, alias=None): ''' Given a SQLAlchemy Table() instance, generate a SQLAlchemy Query() instance with the given parameters. :param table: SQLAlchemy Table() instance :param query: MQL query :param date: metri...
Given a SQLAlchemy Table() instance, generate a SQLAlchemy Query() instance with the given parameters. :param table: SQLAlchemy Table() instance :param query: MQL query :param date: metrique date range query :param date: metrique date range query element :param fields: list of field names to re...
Below is the the instruction that describes the task: ### Input: Given a SQLAlchemy Table() instance, generate a SQLAlchemy Query() instance with the given parameters. :param table: SQLAlchemy Table() instance :param query: MQL query :param date: metrique date range query :param date: metrique ...
def ipython(args): '''give the user an ipython shell, optionally with an endpoint of choice. ''' # The client will announce itself (backend/database) unless it's get from sregistry.main import get_client client = get_client(args.endpoint) client.announce(args.command) from IPython import em...
give the user an ipython shell, optionally with an endpoint of choice.
Below is the the instruction that describes the task: ### Input: give the user an ipython shell, optionally with an endpoint of choice. ### Response: def ipython(args): '''give the user an ipython shell, optionally with an endpoint of choice. ''' # The client will announce itself (backend/database) un...
def to_json(self, filename=None, encoding="utf-8", errors="strict", multiline=False, **json_kwargs): """ Transform the BoxList object into a JSON string. :param filename: If provided will save to file :param encoding: File encoding :param errors: ...
Transform the BoxList object into a JSON string. :param filename: If provided will save to file :param encoding: File encoding :param errors: How to handle encoding errors :param multiline: Put each item in list onto it's own line :param json_kwargs: additional arguments to pass...
Below is the the instruction that describes the task: ### Input: Transform the BoxList object into a JSON string. :param filename: If provided will save to file :param encoding: File encoding :param errors: How to handle encoding errors :param multiline: Put each item in list onto i...
def beeswarm(*args, **kwargs): """ Create a R-like beeswarm plot showing the mean and datapoints. The difference from matplotlib is only the left axis line is shown, and ticklabels labeling each category of data can be added. @param ax: @param x: @param kwargs: Besides xticklabels, which i...
Create a R-like beeswarm plot showing the mean and datapoints. The difference from matplotlib is only the left axis line is shown, and ticklabels labeling each category of data can be added. @param ax: @param x: @param kwargs: Besides xticklabels, which is a prettyplotlib-specific argument whi...
Below is the the instruction that describes the task: ### Input: Create a R-like beeswarm plot showing the mean and datapoints. The difference from matplotlib is only the left axis line is shown, and ticklabels labeling each category of data can be added. @param ax: @param x: @param kwargs: Be...
def is_interesting(entry): """Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none"> <commit revisi...
Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none"> <commit revision="1"> <author>mg</...
Below is the the instruction that describes the task: ### Input: Is this entry interesting? ``entry`` is an XML node representing one entry of the svn status XML output. It looks like this:: <entry path="unchanged.txt"> <wc-status item="normal" revision="1" props="none">...
def upload(self, file, name=None, prefix=None, extensions=None, overwrite=False, public=False, random_name=False, **kwargs): """ To upload file :param file: FileStorage object ...
To upload file :param file: FileStorage object or string location :param name: The name of the object. :param prefix: A prefix for the object. Can be in the form of directory tree :param extensions: list of extensions to allow. If empty, it will use all extension. :param overwrit...
Below is the the instruction that describes the task: ### Input: To upload file :param file: FileStorage object or string location :param name: The name of the object. :param prefix: A prefix for the object. Can be in the form of directory tree :param extensions: list of extensions t...
def start_engine(self): ''' Start the child processes (one per device OS) ''' if self.disable_security is True: log.warning('***Not starting the authenticator process due to disable_security being set to True***') else: log.debug('Generating the private ke...
Start the child processes (one per device OS)
Below is the the instruction that describes the task: ### Input: Start the child processes (one per device OS) ### Response: def start_engine(self): ''' Start the child processes (one per device OS) ''' if self.disable_security is True: log.warning('***Not starting the a...
async def nodes(self, text, opts=None, user=None): ''' A simple non-streaming way to return a list of nodes. ''' return [n async for n in self.eval(text, opts=opts, user=user)]
A simple non-streaming way to return a list of nodes.
Below is the the instruction that describes the task: ### Input: A simple non-streaming way to return a list of nodes. ### Response: async def nodes(self, text, opts=None, user=None): ''' A simple non-streaming way to return a list of nodes. ''' return [n async for n in self.eval(te...
def _define(self): """ gate ch a,b { h b; sdg b; cx a,b; h b; t b; cx a,b; t b; h b; s b; x b; s a;} """ definition = [] q = QuantumRegister(2, "q") rule = [ (HGate(), [q[1...
gate ch a,b { h b; sdg b; cx a,b; h b; t b; cx a,b; t b; h b; s b; x b; s a;}
Below is the the instruction that describes the task: ### Input: gate ch a,b { h b; sdg b; cx a,b; h b; t b; cx a,b; t b; h b; s b; x b; s a;} ### Response: def _define(self): """ gate ch a,b { h b; ...
def _fill_parameters(self): """ Fill in the _parameters dict from the properties file. Args: None Returns: True Todo: Figure out what could go wrong and at least acknowledge the the fact that Murphy was an optimist. """ ...
Fill in the _parameters dict from the properties file. Args: None Returns: True Todo: Figure out what could go wrong and at least acknowledge the the fact that Murphy was an optimist.
Below is the the instruction that describes the task: ### Input: Fill in the _parameters dict from the properties file. Args: None Returns: True Todo: Figure out what could go wrong and at least acknowledge the the fact that Murphy was an op...
def change_ref(self, r0=None, lmax=None): """ Return a new SHMagCoeffs class instance with a different reference r0. Usage ----- clm = x.change_ref([r0, lmax]) Returns ------- clm : SHMagCoeffs class instance. Parameters ---------- ...
Return a new SHMagCoeffs class instance with a different reference r0. Usage ----- clm = x.change_ref([r0, lmax]) Returns ------- clm : SHMagCoeffs class instance. Parameters ---------- r0 : float, optional, default = self.r0 The ref...
Below is the the instruction that describes the task: ### Input: Return a new SHMagCoeffs class instance with a different reference r0. Usage ----- clm = x.change_ref([r0, lmax]) Returns ------- clm : SHMagCoeffs class instance. Parameters ---------...
def _parse_cli_filters(filters): """ Parse the filters from the CLI and turn them into a filter dict for boto. :param filters: :return: """ parsed_filters = [] for filter_entry in filters: filter_parts = re.match('^Name=(?P<name_value>[^,]+),Values=\[?...
Parse the filters from the CLI and turn them into a filter dict for boto. :param filters: :return:
Below is the the instruction that describes the task: ### Input: Parse the filters from the CLI and turn them into a filter dict for boto. :param filters: :return: ### Response: def _parse_cli_filters(filters): """ Parse the filters from the CLI and turn them into a filter dict for ...
def runCLI(): """ The starting point for the execution of the Scrapple command line tool. runCLI uses the docstring as the usage description for the scrapple command. \ The class for the required command is selected by a dynamic dispatch, and the \ command is executed through the execute_command() ...
The starting point for the execution of the Scrapple command line tool. runCLI uses the docstring as the usage description for the scrapple command. \ The class for the required command is selected by a dynamic dispatch, and the \ command is executed through the execute_command() method of the command clas...
Below is the the instruction that describes the task: ### Input: The starting point for the execution of the Scrapple command line tool. runCLI uses the docstring as the usage description for the scrapple command. \ The class for the required command is selected by a dynamic dispatch, and the \ command...
def get_page(pno, zoom = False, max_size = None, first = False): """Return a PNG image for a document page number. """ dlist = dlist_tab[pno] # get display list of page number if not dlist: # create if not yet there dlist_tab[pno] = doc[pno].getDisplayList() dlist = dlist_ta...
Return a PNG image for a document page number.
Below is the the instruction that describes the task: ### Input: Return a PNG image for a document page number. ### Response: def get_page(pno, zoom = False, max_size = None, first = False): """Return a PNG image for a document page number. """ dlist = dlist_tab[pno] # get display list of page number...
def get_bibtex(isbn_identifier): """ Get a BibTeX string for the given ISBN. :param isbn_identifier: ISBN to fetch BibTeX entry for. :returns: A BibTeX string or ``None`` if could not fetch it. >>> get_bibtex('9783161484100') '@book{9783161484100,\\n title = {Berkeley, Oakland: Albany, Eme...
Get a BibTeX string for the given ISBN. :param isbn_identifier: ISBN to fetch BibTeX entry for. :returns: A BibTeX string or ``None`` if could not fetch it. >>> get_bibtex('9783161484100') '@book{9783161484100,\\n title = {Berkeley, Oakland: Albany, Emeryville, Alameda, Kensington},\\n author =...
Below is the the instruction that describes the task: ### Input: Get a BibTeX string for the given ISBN. :param isbn_identifier: ISBN to fetch BibTeX entry for. :returns: A BibTeX string or ``None`` if could not fetch it. >>> get_bibtex('9783161484100') '@book{9783161484100,\\n title = {Berkel...
def put(self, name=None, user_ids=None): """ :param name: str of name for the account, defaults to the created timestamp :param user_ids: list of int of users to give access to this account defaults to current user :return: Account dict created """ return self...
:param name: str of name for the account, defaults to the created timestamp :param user_ids: list of int of users to give access to this account defaults to current user :return: Account dict created
Below is the the instruction that describes the task: ### Input: :param name: str of name for the account, defaults to the created timestamp :param user_ids: list of int of users to give access to this account defaults to current user :return: Account dict created ### Response: def put(...
def filter_belief(stmts_in, belief_cutoff, **kwargs): """Filter to statements with belief above a given cutoff. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. belief_cutoff : float Only statements with belief above the belief_cutoff...
Filter to statements with belief above a given cutoff. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. belief_cutoff : float Only statements with belief above the belief_cutoff will be returned. Here 0 < belief_cutoff < 1. sa...
Below is the the instruction that describes the task: ### Input: Filter to statements with belief above a given cutoff. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. belief_cutoff : float Only statements with belief above the belie...
def update_changes_after_row_delete(self, row_num): """ Update self.changes so that row numbers for edited rows are still correct. I.e., if row 4 was edited and then row 2 was deleted, row 4 becomes row 3. This function updates self.changes to reflect that. """ if row_num...
Update self.changes so that row numbers for edited rows are still correct. I.e., if row 4 was edited and then row 2 was deleted, row 4 becomes row 3. This function updates self.changes to reflect that.
Below is the the instruction that describes the task: ### Input: Update self.changes so that row numbers for edited rows are still correct. I.e., if row 4 was edited and then row 2 was deleted, row 4 becomes row 3. This function updates self.changes to reflect that. ### Response: def update_changes...
def get_vmss(access_token, subscription_id, resource_group, vmss_name): '''Get virtual machine scale set details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_nam...
Get virtual machine scale set details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP resp...
Below is the the instruction that describes the task: ### Input: Get virtual machine scale set details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): N...
def _init_exception_logging(self, app): """ Sets up exception logging unless ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING`` is set in the Flask config. Args: app (flask.Flask). the Flask application for which to initialize the extension. """ enabled = not app.conf...
Sets up exception logging unless ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING`` is set in the Flask config. Args: app (flask.Flask). the Flask application for which to initialize the extension.
Below is the the instruction that describes the task: ### Input: Sets up exception logging unless ``APPINSIGHTS_DISABLE_EXCEPTION_LOGGING`` is set in the Flask config. Args: app (flask.Flask). the Flask application for which to initialize the extension. ### Response: def _init_exceptio...
def connect(self, ctrl): """Connect to the device.""" if self.prompt: self.prompt_re = self.driver.make_dynamic_prompt(self.prompt) else: self.prompt_re = self.driver.prompt_re self.ctrl = ctrl if self.protocol.connect(self.driver): if self.pr...
Connect to the device.
Below is the the instruction that describes the task: ### Input: Connect to the device. ### Response: def connect(self, ctrl): """Connect to the device.""" if self.prompt: self.prompt_re = self.driver.make_dynamic_prompt(self.prompt) else: self.prompt_re = self.drive...
async def stations(self): """Retrieve stations.""" data = await self.retrieve(API_DISTRITS) Station = namedtuple('Station', ['latitude', 'longitude', 'idAreaAviso', 'idConselho', 'idDistrito', 'idRegiao', ...
Retrieve stations.
Below is the the instruction that describes the task: ### Input: Retrieve stations. ### Response: async def stations(self): """Retrieve stations.""" data = await self.retrieve(API_DISTRITS) Station = namedtuple('Station', ['latitude', 'longitude', ...
def dt_comp(self, sampled_topics): """ Compute document-topic matrix from sampled_topics. """ samples = sampled_topics.shape[0] dt = np.zeros((self.D, self.K, samples)) for s in range(samples): dt[:, :, s] = \ samplers_ld...
Compute document-topic matrix from sampled_topics.
Below is the the instruction that describes the task: ### Input: Compute document-topic matrix from sampled_topics. ### Response: def dt_comp(self, sampled_topics): """ Compute document-topic matrix from sampled_topics. """ samples = sampled_topics.shape[0] dt = np.zeros((...
def list_namespaced_resource_quota(self, namespace, **kwargs): """ list or watch objects of kind ResourceQuota This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_resource_quota...
list or watch objects of kind ResourceQuota This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_resource_quota(namespace, async_req=True) >>> result = thread.get() :param async...
Below is the the instruction that describes the task: ### Input: list or watch objects of kind ResourceQuota This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_resource_quota(namespace, as...
def solve(self, max_worlds=10000, silent=False): """ find the best world to make people happy """ self.num_worlds = 0 num_unhappy = 0 for tax_rate in range(self.tax_range[0],self.tax_range[1]): for equity in range(self.equity_range[0],self.equity_range[1]): ...
find the best world to make people happy
Below is the the instruction that describes the task: ### Input: find the best world to make people happy ### Response: def solve(self, max_worlds=10000, silent=False): """ find the best world to make people happy """ self.num_worlds = 0 num_unhappy = 0 for tax_rate ...
def construct_meta(need_data, env): """ Constructs the node-structure for the status container :param need_data: need_info container :return: node """ hide_options = env.config.needs_hide_options if not isinstance(hide_options, list): raise SphinxError('Config parameter needs_hide_o...
Constructs the node-structure for the status container :param need_data: need_info container :return: node
Below is the the instruction that describes the task: ### Input: Constructs the node-structure for the status container :param need_data: need_info container :return: node ### Response: def construct_meta(need_data, env): """ Constructs the node-structure for the status container :param need_da...
def parse_int_list(string): """ Parses a string of numbers and ranges into a list of integers. Ranges are separated by dashes and inclusive of both the start and end number. Example: parse_int_list("8 9 10,11-13") == [8,9,10,11,12,13] """ integers = [] for comma_part in string.split...
Parses a string of numbers and ranges into a list of integers. Ranges are separated by dashes and inclusive of both the start and end number. Example: parse_int_list("8 9 10,11-13") == [8,9,10,11,12,13]
Below is the the instruction that describes the task: ### Input: Parses a string of numbers and ranges into a list of integers. Ranges are separated by dashes and inclusive of both the start and end number. Example: parse_int_list("8 9 10,11-13") == [8,9,10,11,12,13] ### Response: def parse_int_li...
def to_networkx(cyjs, directed=True): """ Convert Cytoscape.js-style JSON object into NetworkX object. By default, data will be handles as a directed graph. """ if directed: g = nx.MultiDiGraph() else: g = nx.MultiGraph() network_data = cyjs[DATA] if network_data is no...
Convert Cytoscape.js-style JSON object into NetworkX object. By default, data will be handles as a directed graph.
Below is the the instruction that describes the task: ### Input: Convert Cytoscape.js-style JSON object into NetworkX object. By default, data will be handles as a directed graph. ### Response: def to_networkx(cyjs, directed=True): """ Convert Cytoscape.js-style JSON object into NetworkX object. ...
def copyglob(src: str, dest: str, allow_nothing: bool = False, allow_nonfiles: bool = False) -> None: """ Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e....
Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e.g. ``/somewhere/*.txt``) dest: destination directory allow_nothing: don't raise an exception if no files are fo...
Below is the the instruction that describes the task: ### Input: Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e.g. ``/somewhere/*.txt``) dest: destination directo...
def convert_idx_to_name(self, y, lens): """Convert label index to name. Args: y (list): label index list. lens (list): true length of y. Returns: y: label name list. Examples: >>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'} ...
Convert label index to name. Args: y (list): label index list. lens (list): true length of y. Returns: y: label name list. Examples: >>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'} >>> y = [[1, 0, 0], [1, 2, 0], [1, 1, 1]] ...
Below is the the instruction that describes the task: ### Input: Convert label index to name. Args: y (list): label index list. lens (list): true length of y. Returns: y: label name list. Examples: >>> # assumes that id2label = {1: 'B-LOC', ...
def get_or_create_group(groupname, gid_preset, system=False, id_dependent=True): """ Returns the id for the given group, and creates it first in case it does not exist. :param groupname: Group name. :type groupname: unicode :param gid_preset: Group id to set if a new group is created. :type gid...
Returns the id for the given group, and creates it first in case it does not exist. :param groupname: Group name. :type groupname: unicode :param gid_preset: Group id to set if a new group is created. :type gid_preset: int or unicode :param system: Create a system group. :type system: bool ...
Below is the the instruction that describes the task: ### Input: Returns the id for the given group, and creates it first in case it does not exist. :param groupname: Group name. :type groupname: unicode :param gid_preset: Group id to set if a new group is created. :type gid_preset: int or unicode ...
def save(filename=None, family='ipv4'): ''' Save the current in-memory rules to disk CLI Example: .. code-block:: bash salt '*' nftables.save /etc/nftables ''' if _conf() and not filename: filename = _conf() nft_families = ['ip', 'ip6', 'arp', 'bridge'] rules = "#! nf...
Save the current in-memory rules to disk CLI Example: .. code-block:: bash salt '*' nftables.save /etc/nftables
Below is the the instruction that describes the task: ### Input: Save the current in-memory rules to disk CLI Example: .. code-block:: bash salt '*' nftables.save /etc/nftables ### Response: def save(filename=None, family='ipv4'): ''' Save the current in-memory rules to disk CLI Exa...
def speech(self) -> str: """ Report summary designed to be read by a text-to-speech program """ if not self.data: self.update() return speech.metar(self.data, self.units)
Report summary designed to be read by a text-to-speech program
Below is the the instruction that describes the task: ### Input: Report summary designed to be read by a text-to-speech program ### Response: def speech(self) -> str: """ Report summary designed to be read by a text-to-speech program """ if not self.data: self.update() ...
def prepare_environment(params: Params): """ Sets random seeds for reproducible experiments. This may not work as expected if you use this from within a python project in which you have already imported Pytorch. If you use the scripts/run_model.py entry point to training models with this library, yo...
Sets random seeds for reproducible experiments. This may not work as expected if you use this from within a python project in which you have already imported Pytorch. If you use the scripts/run_model.py entry point to training models with this library, your experiments should be reasonably reproducible. If ...
Below is the the instruction that describes the task: ### Input: Sets random seeds for reproducible experiments. This may not work as expected if you use this from within a python project in which you have already imported Pytorch. If you use the scripts/run_model.py entry point to training models with this...
async def get_timezone(self) -> Optional[tzinfo]: """ We can't exactly know the time zone of the user from what Facebook gives (fucking morons) but we can still give something that'll work until next DST. """ u = await self._get_user() diff = float(u.get('timezon...
We can't exactly know the time zone of the user from what Facebook gives (fucking morons) but we can still give something that'll work until next DST.
Below is the the instruction that describes the task: ### Input: We can't exactly know the time zone of the user from what Facebook gives (fucking morons) but we can still give something that'll work until next DST. ### Response: async def get_timezone(self) -> Optional[tzinfo]: """ ...
def get_default_user_groups(self, **kwargs): # noqa: E501 """Get default user groups customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_...
Get default user groups customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_default_user_groups(async_req=True) >>> result = thread.get() ...
Below is the the instruction that describes the task: ### Input: Get default user groups customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_d...
def word_tokenize(sentence): """ A generator which yields tokens based on the given sentence without deleting anything. >>> context = "I love you. Please don't leave." >>> list(word_tokenize(context)) ['I', ' ', 'love', ' ', 'you', '.', ' ', 'Please', ' ', 'don', "'", 't', ' ', 'leave', '.'] "...
A generator which yields tokens based on the given sentence without deleting anything. >>> context = "I love you. Please don't leave." >>> list(word_tokenize(context)) ['I', ' ', 'love', ' ', 'you', '.', ' ', 'Please', ' ', 'don', "'", 't', ' ', 'leave', '.']
Below is the the instruction that describes the task: ### Input: A generator which yields tokens based on the given sentence without deleting anything. >>> context = "I love you. Please don't leave." >>> list(word_tokenize(context)) ['I', ' ', 'love', ' ', 'you', '.', ' ', 'Please', ' ', 'don', "'", 't...
def update_state(self): """ Update state with latest info from Wink API. """ response = self.api_interface.get_device_state(self, type_override="button") return self._update_state_from_response(response)
Update state with latest info from Wink API.
Below is the the instruction that describes the task: ### Input: Update state with latest info from Wink API. ### Response: def update_state(self): """ Update state with latest info from Wink API. """ response = self.api_interface.get_device_state(self, type_override="button") ...
def get_score(self, terms): """Get score for a list of terms. :type terms: list :param terms: A list of terms to be analyzed. :returns: dict """ assert isinstance(terms, list) or isinstance(terms, tuple) score_li = np.asarray([self._get_score(t) ...
Get score for a list of terms. :type terms: list :param terms: A list of terms to be analyzed. :returns: dict
Below is the the instruction that describes the task: ### Input: Get score for a list of terms. :type terms: list :param terms: A list of terms to be analyzed. :returns: dict ### Response: def get_score(self, terms): """Get score for a list of terms. ...
def find(self, item_id=None): "Recursively find a menu item by its id (useful for event handlers)" for it in self: if it.id == item_id: return it elif isinstance(it, Menu): found = it.find(item_id) if found: ...
Recursively find a menu item by its id (useful for event handlers)
Below is the the instruction that describes the task: ### Input: Recursively find a menu item by its id (useful for event handlers) ### Response: def find(self, item_id=None): "Recursively find a menu item by its id (useful for event handlers)" for it in self: if it.id == item_id: ...
def _repr_latex_(self): """ This is used in IPython notebook it allows us to render the ODEProblem object in LaTeX. How Cool is this? """ # TODO: we're mixing HTML with latex here. That is not necessarily a good idea, but works # with IPython 1.2.0. Once IPython 2.0 is re...
This is used in IPython notebook it allows us to render the ODEProblem object in LaTeX. How Cool is this?
Below is the the instruction that describes the task: ### Input: This is used in IPython notebook it allows us to render the ODEProblem object in LaTeX. How Cool is this? ### Response: def _repr_latex_(self): """ This is used in IPython notebook it allows us to render the ODEProblem object ...
def get_many(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> Iterable[T]: """Gets a query from the data source, which contains a request for multiple objects. Args: query: The query being requested (contains a request for multiple objects). con...
Gets a query from the data source, which contains a request for multiple objects. Args: query: The query being requested (contains a request for multiple objects). context: The context for the extraction (mutable). Returns: The requested objects.
Below is the the instruction that describes the task: ### Input: Gets a query from the data source, which contains a request for multiple objects. Args: query: The query being requested (contains a request for multiple objects). context: The context for the extraction (mutable). ...
def get_template_uuid(self): """ Retrieves the uuid of the given template name. """ response = requests.get(self.url + 'editor/scan/templates', headers=self.headers, verify=False) templates = json.loads(response.text) for template in templates['templates']: ...
Retrieves the uuid of the given template name.
Below is the the instruction that describes the task: ### Input: Retrieves the uuid of the given template name. ### Response: def get_template_uuid(self): """ Retrieves the uuid of the given template name. """ response = requests.get(self.url + 'editor/scan/templates', headers=s...
def get_type_description(self, _type, suffix='', *args, **kwargs): """ Get description of type :param suffix: :param str _type: :rtype: str """ if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) if schema.all_o...
Get description of type :param suffix: :param str _type: :rtype: str
Below is the the instruction that describes the task: ### Input: Get description of type :param suffix: :param str _type: :rtype: str ### Response: def get_type_description(self, _type, suffix='', *args, **kwargs): """ Get description of type :param suffix: :param st...