code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def normalize(self, body): """ Invoke the JSON API normalizer Perform the following: * add the type as a rtype property * flatten the payload * add the id as a rid property ONLY if present We don't need to vet the inputs much because the Parser has ...
Invoke the JSON API normalizer Perform the following: * add the type as a rtype property * flatten the payload * add the id as a rid property ONLY if present We don't need to vet the inputs much because the Parser has already done all the work. :pa...
Below is the the instruction that describes the task: ### Input: Invoke the JSON API normalizer Perform the following: * add the type as a rtype property * flatten the payload * add the id as a rid property ONLY if present We don't need to vet the inputs much b...
def load_rules(self, force_reload=False, overwrite=True): """Load rules from policy file or cache.""" # double-checked locking if self.load_once and self._policy_loaded: return with self._load_lock: if self.load_once and self._policy_loaded: retur...
Load rules from policy file or cache.
Below is the the instruction that describes the task: ### Input: Load rules from policy file or cache. ### Response: def load_rules(self, force_reload=False, overwrite=True): """Load rules from policy file or cache.""" # double-checked locking if self.load_once and self._policy_loaded: ...
def getComboValue(combo): """ Checks to see if there is a dataType custom property set to determine whether to return an integer or a string. :param combo | <QComboBox> :return <int> || <str> """ dataType = unwrapVariant(combo.property('dataType')) if ...
Checks to see if there is a dataType custom property set to determine whether to return an integer or a string. :param combo | <QComboBox> :return <int> || <str>
Below is the the instruction that describes the task: ### Input: Checks to see if there is a dataType custom property set to determine whether to return an integer or a string. :param combo | <QComboBox> :return <int> || <str> ### Response: def getComboValue(combo): """ ...
def predict(abg,date,obs=568): """Run GB's predict using an ABG file as input.""" import orbfit import RO.StringUtil (ra,dec,a,b,ang) = orbfit.predict(abg,date,obs) obj['RA']=ra obj['DEC']=dec obj['dRA']=a obj['dDEC']=b obj['dANG']=ang return obj
Run GB's predict using an ABG file as input.
Below is the the instruction that describes the task: ### Input: Run GB's predict using an ABG file as input. ### Response: def predict(abg,date,obs=568): """Run GB's predict using an ABG file as input.""" import orbfit import RO.StringUtil (ra,dec,a,b,ang) = orbfit.predict(abg,date,obs) obj['R...
def get_objectlist(description, config_key, module): """ Take a description and return a list of classes. Parameters ---------- description : list of dictionaries Each dictionary has only one entry. The key is the name of a class. The value of that entry is a list of dictionaries ag...
Take a description and return a list of classes. Parameters ---------- description : list of dictionaries Each dictionary has only one entry. The key is the name of a class. The value of that entry is a list of dictionaries again. Those dictionaries are paramters. Returns -...
Below is the the instruction that describes the task: ### Input: Take a description and return a list of classes. Parameters ---------- description : list of dictionaries Each dictionary has only one entry. The key is the name of a class. The value of that entry is a list of dictionarie...
def get_datatypes(self): """ Returns a set of datatypes in this cell. Returns ------- out : set Set of the datatypes used in this cell. """ datatypes = set() for element in self.elements: if isinstance(element, PolygonSet): ...
Returns a set of datatypes in this cell. Returns ------- out : set Set of the datatypes used in this cell.
Below is the the instruction that describes the task: ### Input: Returns a set of datatypes in this cell. Returns ------- out : set Set of the datatypes used in this cell. ### Response: def get_datatypes(self): """ Returns a set of datatypes in this cell. ...
def check_port(self, port): """ Attempts to bind to the requested communicator port, checking if it is already in use. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind(("localhost", port)) except socket.error: raise UnityWorker...
Attempts to bind to the requested communicator port, checking if it is already in use.
Below is the the instruction that describes the task: ### Input: Attempts to bind to the requested communicator port, checking if it is already in use. ### Response: def check_port(self, port): """ Attempts to bind to the requested communicator port, checking if it is already in use. """ ...
def roughness_Farshad(ID=None, D=None, coeffs=None): r'''Calculates of retrieves the roughness of a pipe based on the work of [1]_. This function will return an average value for pipes of a given material, or if diameter is provided, will calculate one specifically for the pipe inner diameter according ...
r'''Calculates of retrieves the roughness of a pipe based on the work of [1]_. This function will return an average value for pipes of a given material, or if diameter is provided, will calculate one specifically for the pipe inner diameter according to the following expression with constants `A` and `...
Below is the the instruction that describes the task: ### Input: r'''Calculates of retrieves the roughness of a pipe based on the work of [1]_. This function will return an average value for pipes of a given material, or if diameter is provided, will calculate one specifically for the pipe inner diamete...
def all_docs_with_tag(self, doc_tag): """ Returns all the documents with the specified tag. """ docs = [] while True: try: doc = self.next_doc_with(doc_tag) docs.append(doc) except StopIteration: break ...
Returns all the documents with the specified tag.
Below is the the instruction that describes the task: ### Input: Returns all the documents with the specified tag. ### Response: def all_docs_with_tag(self, doc_tag): """ Returns all the documents with the specified tag. """ docs = [] while True: try: ...
def group_by(self, to_key): """ :param to_key: :type to_key: T -> unicode :rtype: TDict[TList[T]] Usage: >>> TList([1, 2, 3, 4, 5]).group_by(lambda x: x % 2).to_json() '{"0": [2,4],"1": [1,3,5]}' """ ret = TDict() for v in self: ...
:param to_key: :type to_key: T -> unicode :rtype: TDict[TList[T]] Usage: >>> TList([1, 2, 3, 4, 5]).group_by(lambda x: x % 2).to_json() '{"0": [2,4],"1": [1,3,5]}'
Below is the the instruction that describes the task: ### Input: :param to_key: :type to_key: T -> unicode :rtype: TDict[TList[T]] Usage: >>> TList([1, 2, 3, 4, 5]).group_by(lambda x: x % 2).to_json() '{"0": [2,4],"1": [1,3,5]}' ### Response: def group_by(self, to_...
def posthoc_tukey_hsd(x, g, alpha=0.05): '''Pairwise comparisons with TukeyHSD confidence intervals. This is a convenience function to make statsmodels `pairwise_tukeyhsd` method more applicable for further use. Parameters ---------- x : array_like or pandas Series object, 1d An array,...
Pairwise comparisons with TukeyHSD confidence intervals. This is a convenience function to make statsmodels `pairwise_tukeyhsd` method more applicable for further use. Parameters ---------- x : array_like or pandas Series object, 1d An array, any object exposing the array interface, contain...
Below is the the instruction that describes the task: ### Input: Pairwise comparisons with TukeyHSD confidence intervals. This is a convenience function to make statsmodels `pairwise_tukeyhsd` method more applicable for further use. Parameters ---------- x : array_like or pandas Series object, ...
def predict_y(self, Xnew): """ Compute the mean and variance of held-out data at the points Xnew """ pred_f_mean, pred_f_var = self._build_predict(Xnew) return self.likelihood.predict_mean_and_var(pred_f_mean, pred_f_var)
Compute the mean and variance of held-out data at the points Xnew
Below is the the instruction that describes the task: ### Input: Compute the mean and variance of held-out data at the points Xnew ### Response: def predict_y(self, Xnew): """ Compute the mean and variance of held-out data at the points Xnew """ pred_f_mean, pred_f_var = self._build...
def __publish(topic, message, subject=None): """ Publish a message to a SNS topic :type topic: str :param topic: SNS topic to publish the message to :type message: str :param message: Message to send via SNS :type subject: str :param subject: Subject to use for e-mail notifications :ret...
Publish a message to a SNS topic :type topic: str :param topic: SNS topic to publish the message to :type message: str :param message: Message to send via SNS :type subject: str :param subject: Subject to use for e-mail notifications :returns: None
Below is the the instruction that describes the task: ### Input: Publish a message to a SNS topic :type topic: str :param topic: SNS topic to publish the message to :type message: str :param message: Message to send via SNS :type subject: str :param subject: Subject to use for e-mail notifi...
def watchpoint_set(self, addr, addr_mask=0x0, data=0x0, data_mask=0x0, access_size=None, read=False, write=False, privileged=False): ...
Sets a watchpoint at the given address. This method allows for a watchpoint to be set on an given address or range of addresses. The watchpoint can then be triggered if the data at the given address matches the specified ``data`` or range of data as determined by ``data_mask``, on spec...
Below is the the instruction that describes the task: ### Input: Sets a watchpoint at the given address. This method allows for a watchpoint to be set on an given address or range of addresses. The watchpoint can then be triggered if the data at the given address matches the specified ``da...
def fhp_from_json_dict( json_dict # type: Dict[str, Any] ): # type: (...) -> FieldHashingProperties """ Make a :class:`FieldHashingProperties` object from a dictionary. :param dict json_dict: The dictionary must have have an 'ngram' key and one of k or num_bits....
Make a :class:`FieldHashingProperties` object from a dictionary. :param dict json_dict: The dictionary must have have an 'ngram' key and one of k or num_bits. It may have 'positional' key; if missing a default is used. The encoding is always set to th...
Below is the the instruction that describes the task: ### Input: Make a :class:`FieldHashingProperties` object from a dictionary. :param dict json_dict: The dictionary must have have an 'ngram' key and one of k or num_bits. It may have 'positional' key; if missing a defa...
def express_route_ports(self): """Instance depends on the API version: * 2018-08-01: :class:`ExpressRoutePortsOperations<azure.mgmt.network.v2018_08_01.operations.ExpressRoutePortsOperations>` """ api_version = self._get_api_version('express_route_ports') if api_version == '2...
Instance depends on the API version: * 2018-08-01: :class:`ExpressRoutePortsOperations<azure.mgmt.network.v2018_08_01.operations.ExpressRoutePortsOperations>`
Below is the the instruction that describes the task: ### Input: Instance depends on the API version: * 2018-08-01: :class:`ExpressRoutePortsOperations<azure.mgmt.network.v2018_08_01.operations.ExpressRoutePortsOperations>` ### Response: def express_route_ports(self): """Instance depends on the...
def get_host(environ): # type: (Dict[str, str]) -> str """Return the host for the given WSGI environment. Yanked from Werkzeug.""" if environ.get("HTTP_HOST"): rv = environ["HTTP_HOST"] if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"): rv = rv[:-3] elif envi...
Return the host for the given WSGI environment. Yanked from Werkzeug.
Below is the the instruction that describes the task: ### Input: Return the host for the given WSGI environment. Yanked from Werkzeug. ### Response: def get_host(environ): # type: (Dict[str, str]) -> str """Return the host for the given WSGI environment. Yanked from Werkzeug.""" if environ.get("HTTP_HO...
def multi_load_data(Channel, RunNos, RepeatNos, directoryPath='.', calcPSD=True, NPerSegmentPSD=1000000): """ Lets you load multiple datasets at once assuming they have a filename which contains a pattern of the form: CH<ChannelNo>_RUN00...<RunNo>_REPEAT00...<RepeatNo> Parameters ---------...
Lets you load multiple datasets at once assuming they have a filename which contains a pattern of the form: CH<ChannelNo>_RUN00...<RunNo>_REPEAT00...<RepeatNo> Parameters ---------- Channel : int The channel you want to load RunNos : sequence Sequence of run numbers you wan...
Below is the the instruction that describes the task: ### Input: Lets you load multiple datasets at once assuming they have a filename which contains a pattern of the form: CH<ChannelNo>_RUN00...<RunNo>_REPEAT00...<RepeatNo> Parameters ---------- Channel : int The channel you want ...
def specific_gains(string): """Convert string with gains of individual amplification elements to dict""" if not string: return {} gains = {} for gain in string.split(','): amp_name, value = gain.split('=') gains[amp_name.strip()] = float(value.strip()) return gains
Convert string with gains of individual amplification elements to dict
Below is the the instruction that describes the task: ### Input: Convert string with gains of individual amplification elements to dict ### Response: def specific_gains(string): """Convert string with gains of individual amplification elements to dict""" if not string: return {} gains = {} ...
def run(app: web.Application, **kwargs): """Run an `aiohttp.web.Application` using gunicorn. :param app: The app to run. :param str app_uri: Import path to `app`. Takes the form ``$(MODULE_NAME):$(VARIABLE_NAME)``. The module name can be a full dotted path. The variable name refers ...
Run an `aiohttp.web.Application` using gunicorn. :param app: The app to run. :param str app_uri: Import path to `app`. Takes the form ``$(MODULE_NAME):$(VARIABLE_NAME)``. The module name can be a full dotted path. The variable name refers to the `aiohttp.web.Application` instance. ...
Below is the the instruction that describes the task: ### Input: Run an `aiohttp.web.Application` using gunicorn. :param app: The app to run. :param str app_uri: Import path to `app`. Takes the form ``$(MODULE_NAME):$(VARIABLE_NAME)``. The module name can be a full dotted path. The ...
def list_keyvaults(access_token, subscription_id, rgname): '''Lists key vaults in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP res...
Lists key vaults in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. 200 OK.
Below is the the instruction that describes the task: ### Input: Lists key vaults in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP ...
def setup(self): """ Abinit has the very *bad* habit of changing the file extension by appending the characters in [A,B ..., Z] to the output file, and this breaks a lot of code that relies of the use of a unique file extension. Here we fix this issue by renaming run.abo to run.abo_[numb...
Abinit has the very *bad* habit of changing the file extension by appending the characters in [A,B ..., Z] to the output file, and this breaks a lot of code that relies of the use of a unique file extension. Here we fix this issue by renaming run.abo to run.abo_[number] if the output file "run.abo" alre...
Below is the the instruction that describes the task: ### Input: Abinit has the very *bad* habit of changing the file extension by appending the characters in [A,B ..., Z] to the output file, and this breaks a lot of code that relies of the use of a unique file extension. Here we fix this issue by r...
def _product(k, v): """ Perform the product between two objects even if they don't support iteration """ if not _can_iterate(k): k = [k] if not _can_iterate(v): v = [v] return list(product(k, v))
Perform the product between two objects even if they don't support iteration
Below is the the instruction that describes the task: ### Input: Perform the product between two objects even if they don't support iteration ### Response: def _product(k, v): """ Perform the product between two objects even if they don't support iteration """ if not _can_iterat...
def gen_repr(cls, template, *args, **kwargs): """Generates a string for :func:`repr`.""" buf = io.StringIO() buf.write(u'<') buf.write(cls.__module__.decode() if kwargs.pop('full', False) else u'etc') buf.write(u'.') buf.write(cls.__name__.decode()) if not kwargs.pop('dense', False): ...
Generates a string for :func:`repr`.
Below is the the instruction that describes the task: ### Input: Generates a string for :func:`repr`. ### Response: def gen_repr(cls, template, *args, **kwargs): """Generates a string for :func:`repr`.""" buf = io.StringIO() buf.write(u'<') buf.write(cls.__module__.decode() if kwargs.pop('full', Fa...
def list_all_discount_promotions(cls, **kwargs): """List DiscountPromotions Return a list of DiscountPromotions This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_discount_promotions(asy...
List DiscountPromotions Return a list of DiscountPromotions This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_discount_promotions(async=True) >>> result = thread.get() :param a...
Below is the the instruction that describes the task: ### Input: List DiscountPromotions Return a list of DiscountPromotions This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_discount_promo...
def get_memory_banks_per_run(coreAssignment, cgroups): """Get an assignment of memory banks to runs that fits to the given coreAssignment, i.e., no run is allowed to use memory that is not local (on the same NUMA node) to one of its CPU cores.""" try: # read list of available memory banks ...
Get an assignment of memory banks to runs that fits to the given coreAssignment, i.e., no run is allowed to use memory that is not local (on the same NUMA node) to one of its CPU cores.
Below is the the instruction that describes the task: ### Input: Get an assignment of memory banks to runs that fits to the given coreAssignment, i.e., no run is allowed to use memory that is not local (on the same NUMA node) to one of its CPU cores. ### Response: def get_memory_banks_per_run(coreAssignmen...
def from_env(cls, prefix, kms_decrypt=False, aws_profile=None): """ Load database credential from env variable. - host: ENV.{PREFIX}_HOST - port: ENV.{PREFIX}_PORT - database: ENV.{PREFIX}_DATABASE - username: ENV.{PREFIX}_USERNAME - password: ENV.{PREFIX}_PASSWO...
Load database credential from env variable. - host: ENV.{PREFIX}_HOST - port: ENV.{PREFIX}_PORT - database: ENV.{PREFIX}_DATABASE - username: ENV.{PREFIX}_USERNAME - password: ENV.{PREFIX}_PASSWORD :param prefix: str :param kms_decrypt: bool :param aws_p...
Below is the the instruction that describes the task: ### Input: Load database credential from env variable. - host: ENV.{PREFIX}_HOST - port: ENV.{PREFIX}_PORT - database: ENV.{PREFIX}_DATABASE - username: ENV.{PREFIX}_USERNAME - password: ENV.{PREFIX}_PASSWORD :pa...
def discover_yaml(bank=None, **meta): """Discovers the YAML format and registers it if available. Install YAML support via PIP:: pip install PyYAML :param bank: The format bank to register the format in :param meta: Extra information associated with the format """ try: import ...
Discovers the YAML format and registers it if available. Install YAML support via PIP:: pip install PyYAML :param bank: The format bank to register the format in :param meta: Extra information associated with the format
Below is the the instruction that describes the task: ### Input: Discovers the YAML format and registers it if available. Install YAML support via PIP:: pip install PyYAML :param bank: The format bank to register the format in :param meta: Extra information associated with the format ### Resp...
def _parse_planar_geometry_surface(self, node): """ Parses a planar geometry surface """ nodes = [] for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"]: nodes.append(geo.Point(getattr(node, key)["lon"], getattr(node, key)...
Parses a planar geometry surface
Below is the the instruction that describes the task: ### Input: Parses a planar geometry surface ### Response: def _parse_planar_geometry_surface(self, node): """ Parses a planar geometry surface """ nodes = [] for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"]...
def create(self, repo_user, repo_name, issue_number, body): """ PATCH /repos/:owner/:repo/issues/:number/comments :param issue_number: The issue's (or pull request's) number :param body: The body of this comment """ return self.api.makeRequest( ['repos', repo...
PATCH /repos/:owner/:repo/issues/:number/comments :param issue_number: The issue's (or pull request's) number :param body: The body of this comment
Below is the the instruction that describes the task: ### Input: PATCH /repos/:owner/:repo/issues/:number/comments :param issue_number: The issue's (or pull request's) number :param body: The body of this comment ### Response: def create(self, repo_user, repo_name, issue_number, body): """...
def cancel(self,order_id): ''' cancel the specified order :param order_id: order_id to be canceled ''' url= 'https://coincheck.com/api/exchange/orders/' + order_id headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.delete(url,hea...
cancel the specified order :param order_id: order_id to be canceled
Below is the the instruction that describes the task: ### Input: cancel the specified order :param order_id: order_id to be canceled ### Response: def cancel(self,order_id): ''' cancel the specified order :param order_id: order_id to be canceled ''' url= 'https://coincheck.c...
def delete(self, resource_group, name): """ Delete a container group :param resource_group: the name of the resource group :type resource_group: str :param name: the name of the container group :type name: str """ self.connection.container_groups.delete(r...
Delete a container group :param resource_group: the name of the resource group :type resource_group: str :param name: the name of the container group :type name: str
Below is the the instruction that describes the task: ### Input: Delete a container group :param resource_group: the name of the resource group :type resource_group: str :param name: the name of the container group :type name: str ### Response: def delete(self, resource_group, name...
def extract_filestem(data): """Extract filestem from Entrez eSummary data. Function expects esummary['DocumentSummarySet']['DocumentSummary'][0] Some illegal characters may occur in AssemblyName - for these, a more robust regex replace/escape may be required. Sadly, NCBI don't just use standard pe...
Extract filestem from Entrez eSummary data. Function expects esummary['DocumentSummarySet']['DocumentSummary'][0] Some illegal characters may occur in AssemblyName - for these, a more robust regex replace/escape may be required. Sadly, NCBI don't just use standard percent escapes, but instead replace ...
Below is the the instruction that describes the task: ### Input: Extract filestem from Entrez eSummary data. Function expects esummary['DocumentSummarySet']['DocumentSummary'][0] Some illegal characters may occur in AssemblyName - for these, a more robust regex replace/escape may be required. Sadly, N...
def _date_val(self, dt: datetime) -> None: """ Add a date value :param dt: datetime to add """ self._tval_char = dt.strftime('%Y-%m-%d %H:%M') self._nval_num = (dt.year * 10000) + (dt.month * 100) + dt.day + \ (((dt.hour / 100.0) + (dt.minute / 10...
Add a date value :param dt: datetime to add
Below is the the instruction that describes the task: ### Input: Add a date value :param dt: datetime to add ### Response: def _date_val(self, dt: datetime) -> None: """ Add a date value :param dt: datetime to add """ self._tval_char = dt.strftime('%Y-%m-%d %H:%M') ...
def num(value): """Convert a value from one of several bases to an int.""" if re_hex_num.match(value): return int(value, base=16) else: return int(value)
Convert a value from one of several bases to an int.
Below is the the instruction that describes the task: ### Input: Convert a value from one of several bases to an int. ### Response: def num(value): """Convert a value from one of several bases to an int.""" if re_hex_num.match(value): return int(value, base=16) else: return int(value)
def remove_response_property(xml_root): """Removes response properties if exist.""" if xml_root.tag == "testsuites": properties = xml_root.find("properties") resp_properties = [] for prop in properties: prop_name = prop.get("name", "") if "polarion-response-" in p...
Removes response properties if exist.
Below is the the instruction that describes the task: ### Input: Removes response properties if exist. ### Response: def remove_response_property(xml_root): """Removes response properties if exist.""" if xml_root.tag == "testsuites": properties = xml_root.find("properties") resp_properties ...
def _create_tautological_expression_for_location(query_metadata_table, location): """For a given location, create a BinaryComposition that always evaluates to 'true'.""" location_type = query_metadata_table.get_location_info(location).type location_exists = BinaryComposition( u'!=', ContextField(lo...
For a given location, create a BinaryComposition that always evaluates to 'true'.
Below is the the instruction that describes the task: ### Input: For a given location, create a BinaryComposition that always evaluates to 'true'. ### Response: def _create_tautological_expression_for_location(query_metadata_table, location): """For a given location, create a BinaryComposition that always eval...
def _get_firewall_rules(firewall_rules): ''' Construct a list of optional firewall rules from the cloud profile. ''' ret = [] for key, value in six.iteritems(firewall_rules): # Verify the required 'protocol' property is present in the cloud # profile config if 'protocol' not ...
Construct a list of optional firewall rules from the cloud profile.
Below is the the instruction that describes the task: ### Input: Construct a list of optional firewall rules from the cloud profile. ### Response: def _get_firewall_rules(firewall_rules): ''' Construct a list of optional firewall rules from the cloud profile. ''' ret = [] for key, value in six....
def _succeed(self, request_id, reply, duration): """Publish a CommandSucceededEvent.""" self.listeners.publish_command_success( duration, reply, self.name, request_id, self.sock_info.address, self.op_id)
Publish a CommandSucceededEvent.
Below is the the instruction that describes the task: ### Input: Publish a CommandSucceededEvent. ### Response: def _succeed(self, request_id, reply, duration): """Publish a CommandSucceededEvent.""" self.listeners.publish_command_success( duration, reply, self.name, request...
def _fix_example_namespace(self): """Attempts to resolve issues where our samples use 'http://example.com/' for our example namespace but python-stix uses 'http://example.com' by removing the former. """ example_prefix = 'example' # Example ns prefix idgen_prefix = idgen...
Attempts to resolve issues where our samples use 'http://example.com/' for our example namespace but python-stix uses 'http://example.com' by removing the former.
Below is the the instruction that describes the task: ### Input: Attempts to resolve issues where our samples use 'http://example.com/' for our example namespace but python-stix uses 'http://example.com' by removing the former. ### Response: def _fix_example_namespace(self): """Attempts to ...
def GetHashCode(self): """uint32 identifier""" slice_length = 4 if len(self.Data) >= 4 else len(self.Data) return int.from_bytes(self.Data[:slice_length], 'little')
uint32 identifier
Below is the the instruction that describes the task: ### Input: uint32 identifier ### Response: def GetHashCode(self): """uint32 identifier""" slice_length = 4 if len(self.Data) >= 4 else len(self.Data) return int.from_bytes(self.Data[:slice_length], 'little')
def spur(image, mask=None, iterations=1): '''Remove spur pixels from an image 0 0 0 0 0 0 0 1 0 -> 0 0 0 0 0 1 0 0 ? ''' global spur_table_1,spur_table_2 if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~...
Remove spur pixels from an image 0 0 0 0 0 0 0 1 0 -> 0 0 0 0 0 1 0 0 ?
Below is the the instruction that describes the task: ### Input: Remove spur pixels from an image 0 0 0 0 0 0 0 1 0 -> 0 0 0 0 0 1 0 0 ? ### Response: def spur(image, mask=None, iterations=1): '''Remove spur pixels from an image 0 0 0 0 0 0 0 1 0 -> 0 0 0 0 0 1 0 0...
def _wrap_results(result, dtype, fill_value=None): """ wrap our results if needed """ if is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype): if fill_value is None: # GH#24293 fill_value = iNaT if not isinstance(result, np.ndarray): tz = getattr(dtype,...
wrap our results if needed
Below is the the instruction that describes the task: ### Input: wrap our results if needed ### Response: def _wrap_results(result, dtype, fill_value=None): """ wrap our results if needed """ if is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype): if fill_value is None: # GH#242...
def set_velocities(self, velocities): """ :param velocities (au): list of list of atom velocities :return: """ assert len(velocities) == len(self.mol) self.params["velocity"] = velocities
:param velocities (au): list of list of atom velocities :return:
Below is the the instruction that describes the task: ### Input: :param velocities (au): list of list of atom velocities :return: ### Response: def set_velocities(self, velocities): """ :param velocities (au): list of list of atom velocities :return: """ ...
def process_tokens(self, tokens): u""" Iterate other tokens to find strings and ensure that they are prefixed. :param tokens: :return: """ for (tok_type, token, (start_row, _), _, _) in tokens: if tok_type == tokenize.STRING: self._check_string...
u""" Iterate other tokens to find strings and ensure that they are prefixed. :param tokens: :return:
Below is the the instruction that describes the task: ### Input: u""" Iterate other tokens to find strings and ensure that they are prefixed. :param tokens: :return: ### Response: def process_tokens(self, tokens): u""" Iterate other tokens to find strings and ensure that the...
def get_summaries_log_dir(decode_hp, output_dir, dataset_split): """Get nested summaries_log_dir based on decode_hp.""" child_dir = decode_hp.summaries_log_dir level_dir = "".join([str(level) for level in decode_hp.level_interp]) if decode_hp.channel_interp == "all": rank_dir = "all" else: rank_dir = ...
Get nested summaries_log_dir based on decode_hp.
Below is the the instruction that describes the task: ### Input: Get nested summaries_log_dir based on decode_hp. ### Response: def get_summaries_log_dir(decode_hp, output_dir, dataset_split): """Get nested summaries_log_dir based on decode_hp.""" child_dir = decode_hp.summaries_log_dir level_dir = "".join([...
def connect_proxy(self, proxy_host='localhost', proxy_port=0, proxy_type=socks.HTTP, host='localhost', port=0): """Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix w...
Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. Note: This method is automatically invoked by __init__...
Below is the the instruction that describes the task: ### Input: Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to...
def delete(config, group, force): """Delete an LDAP group.""" if not force: if not click.confirm( 'Confirm that you want to delete group {}'.format(group)): sys.exit("Deletion of {} aborted".format(group)) client = Client() client.prepare_...
Delete an LDAP group.
Below is the the instruction that describes the task: ### Input: Delete an LDAP group. ### Response: def delete(config, group, force): """Delete an LDAP group.""" if not force: if not click.confirm( 'Confirm that you want to delete group {}'.format(group)): ...
def to_pandas(self): """Return a pandas dataframe representation of the condensed tree. Each row of the dataframe corresponds to an edge in the tree. The columns of the dataframe are `parent`, `child`, `lambda_val` and `child_size`. The `parent` and `child` are the ids of the ...
Return a pandas dataframe representation of the condensed tree. Each row of the dataframe corresponds to an edge in the tree. The columns of the dataframe are `parent`, `child`, `lambda_val` and `child_size`. The `parent` and `child` are the ids of the parent and child nodes in...
Below is the the instruction that describes the task: ### Input: Return a pandas dataframe representation of the condensed tree. Each row of the dataframe corresponds to an edge in the tree. The columns of the dataframe are `parent`, `child`, `lambda_val` and `child_size`. The `par...
def fill_subparser(subparser): """Sets up a subparser to download audio of YouTube videos. Adds the compulsory `--youtube-id` flag. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `youtube_audio` command. """ subparser.add_argument( ...
Sets up a subparser to download audio of YouTube videos. Adds the compulsory `--youtube-id` flag. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `youtube_audio` command.
Below is the the instruction that describes the task: ### Input: Sets up a subparser to download audio of YouTube videos. Adds the compulsory `--youtube-id` flag. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `youtube_audio` command. ### Response...
def generate_graphs(data, name, results_dir): """Generate all reports from original dataframe :param dic data: dict containing raw and compiled results dataframes :param str name: name for prefixing graphs output :param str results_dir: results output directory """ graphs.resp_graph_raw(data['r...
Generate all reports from original dataframe :param dic data: dict containing raw and compiled results dataframes :param str name: name for prefixing graphs output :param str results_dir: results output directory
Below is the the instruction that describes the task: ### Input: Generate all reports from original dataframe :param dic data: dict containing raw and compiled results dataframes :param str name: name for prefixing graphs output :param str results_dir: results output directory ### Response: def genera...
def search(self, term: str, case_sensitive: bool = False) -> 'PrettyDir': """Searches for names that match some pattern. Args: term: String used to match names. A name is returned if it matches the whole search term. case_sensitive: Boolean to match case or not, de...
Searches for names that match some pattern. Args: term: String used to match names. A name is returned if it matches the whole search term. case_sensitive: Boolean to match case or not, default is False (case insensitive). Return: A Prett...
Below is the the instruction that describes the task: ### Input: Searches for names that match some pattern. Args: term: String used to match names. A name is returned if it matches the whole search term. case_sensitive: Boolean to match case or not, default is False ...
def _merge_patches(self): """Injects object patches into their original object definitions.""" for patched_item, patched_namespace in self._patch_data_by_canonical_name.values(): patched_item_base_name = self._get_base_name(patched_item.name, patched_namespace.name) if patched_it...
Injects object patches into their original object definitions.
Below is the the instruction that describes the task: ### Input: Injects object patches into their original object definitions. ### Response: def _merge_patches(self): """Injects object patches into their original object definitions.""" for patched_item, patched_namespace in self._patch_data_by_can...
def words_amount_needed(entropybits: Union[int, float], entropy_w: Union[int, float], entropy_n: Union[int, float], amount_n: int) -> int: """Calculate words needed for a passphrase based on entropy.""" # Thanks to @julianor for this tip to...
Calculate words needed for a passphrase based on entropy.
Below is the the instruction that describes the task: ### Input: Calculate words needed for a passphrase based on entropy. ### Response: def words_amount_needed(entropybits: Union[int, float], entropy_w: Union[int, float], entropy_n: Union[int, float], ...
def validate_meta_object(meta: Dict[str, Any], allow_extra_meta_fields: bool) -> None: """ Validates that every key is one of `META_FIELDS` and has a value of the expected type. """ for key, value in meta.items(): if key in META_FIELDS: if type(value) is not META_FIELDS[key]: ...
Validates that every key is one of `META_FIELDS` and has a value of the expected type.
Below is the the instruction that describes the task: ### Input: Validates that every key is one of `META_FIELDS` and has a value of the expected type. ### Response: def validate_meta_object(meta: Dict[str, Any], allow_extra_meta_fields: bool) -> None: """ Validates that every key is one of `META_FIELDS` a...
def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, sent_at__gte=h24).count()
Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits
Below is the the instruction that describes the task: ### Input: Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits ### Response: def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours ...
def get_fills(self, order_id=None, symbol=None, side=None, order_type=None, start=None, end=None, page=None, limit=None): """Get a list of recent fills. https://docs.kucoin.com/#list-fills :param order_id: (optional) generated order id :type order_id: string :...
Get a list of recent fills. https://docs.kucoin.com/#list-fills :param order_id: (optional) generated order id :type order_id: string :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string :param side: (optional) buy or sell :type side: strin...
Below is the the instruction that describes the task: ### Input: Get a list of recent fills. https://docs.kucoin.com/#list-fills :param order_id: (optional) generated order id :type order_id: string :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string ...
def healpix_to_lonlat(healpix_index, nside, dx=None, dy=None, order='ring'): """ Convert HEALPix indices (optionally with offsets) to longitudes/latitudes. If no offsets (``dx`` and ``dy``) are provided, the coordinates will default to those at the center of the HEALPix pixels. Parameters ----...
Convert HEALPix indices (optionally with offsets) to longitudes/latitudes. If no offsets (``dx`` and ``dy``) are provided, the coordinates will default to those at the center of the HEALPix pixels. Parameters ---------- healpix_index : int or `~numpy.ndarray` HEALPix indices (as a scalar o...
Below is the the instruction that describes the task: ### Input: Convert HEALPix indices (optionally with offsets) to longitudes/latitudes. If no offsets (``dx`` and ``dy``) are provided, the coordinates will default to those at the center of the HEALPix pixels. Parameters ---------- healpix_i...
def pack(self, value=None): """Pack the message into a binary data. One of the basic operations on a Message is the pack operation. During the packing process, we convert all message attributes to binary format. Since that this is usually used before sending the message to a sw...
Pack the message into a binary data. One of the basic operations on a Message is the pack operation. During the packing process, we convert all message attributes to binary format. Since that this is usually used before sending the message to a switch, here we also call :meth:`...
Below is the the instruction that describes the task: ### Input: Pack the message into a binary data. One of the basic operations on a Message is the pack operation. During the packing process, we convert all message attributes to binary format. Since that this is usually used befo...
def set_tlsext_use_srtp(self, profiles): """ Enable support for negotiating SRTP keying material. :param bytes profiles: A colon delimited list of protection profile names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``. :return: None """ if not is...
Enable support for negotiating SRTP keying material. :param bytes profiles: A colon delimited list of protection profile names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``. :return: None
Below is the the instruction that describes the task: ### Input: Enable support for negotiating SRTP keying material. :param bytes profiles: A colon delimited list of protection profile names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``. :return: None ### Response: def se...
def get(self, request): """View for HTTP GET method. Returns template and context from generate_page_title and generate_sections to populate template. """ sections = self.generate_sections() if self.paginated: p = Paginator(sections, 25) page = ...
View for HTTP GET method. Returns template and context from generate_page_title and generate_sections to populate template.
Below is the the instruction that describes the task: ### Input: View for HTTP GET method. Returns template and context from generate_page_title and generate_sections to populate template. ### Response: def get(self, request): """View for HTTP GET method. Returns template and cont...
def splitnport(host, defport=-1): """Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.""" global _nportprog if _nportprog is None: ...
Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.
Below is the the instruction that describes the task: ### Input: Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number. ### Response: def splitnport(h...
def is_ccw(points): """ Check if connected planar points are counterclockwise. Parameters ----------- points: (n,2) float, connected points on a plane Returns ---------- ccw: bool, True if points are counterclockwise """ points = np.asanyarray(points, dtype=np.float64) if ...
Check if connected planar points are counterclockwise. Parameters ----------- points: (n,2) float, connected points on a plane Returns ---------- ccw: bool, True if points are counterclockwise
Below is the the instruction that describes the task: ### Input: Check if connected planar points are counterclockwise. Parameters ----------- points: (n,2) float, connected points on a plane Returns ---------- ccw: bool, True if points are counterclockwise ### Response: def is_ccw(points...
def _validate_instance(self, instance, errors, path_prefix=''): """Validates that the given instance of a document conforms to the given schema's structure and validations. Any validation errors are added to the given errors collection. The caller should assume the instance is considered valid i...
Validates that the given instance of a document conforms to the given schema's structure and validations. Any validation errors are added to the given errors collection. The caller should assume the instance is considered valid if the errors collection is empty when this method returns.
Below is the the instruction that describes the task: ### Input: Validates that the given instance of a document conforms to the given schema's structure and validations. Any validation errors are added to the given errors collection. The caller should assume the instance is considered valid if the ...
def insert_rows(self, table, rows, target_fields=None): """ A generic way to insert a set of tuples into a table. :param table: Name of the target table :type table: str :param rows: The rows to insert into the table :type rows: iterable of tuples :param target_f...
A generic way to insert a set of tuples into a table. :param table: Name of the target table :type table: str :param rows: The rows to insert into the table :type rows: iterable of tuples :param target_fields: The names of the columns to fill in the table :type target_fi...
Below is the the instruction that describes the task: ### Input: A generic way to insert a set of tuples into a table. :param table: Name of the target table :type table: str :param rows: The rows to insert into the table :type rows: iterable of tuples :param target_fields: ...
def deployment( *, block_uri: URI, contract_instance: str, contract_type: str, address: HexStr, transaction: HexStr = None, block: HexStr = None, deployment_bytecode: Dict[str, Any] = None, runtime_bytecode: Dict[str, Any] = None, compiler: Dict[str, Any] = None, ) -> Manifest: ...
Returns a manifest, with the newly included deployment. Requires a valid blockchain URI, however no validation is provided that this URI is unique amongst the other deployment URIs, so the user must take care that each blockchain URI represents a unique blockchain.
Below is the the instruction that describes the task: ### Input: Returns a manifest, with the newly included deployment. Requires a valid blockchain URI, however no validation is provided that this URI is unique amongst the other deployment URIs, so the user must take care that each blockchain URI represent...
def hide(self, wid, verbose=False): """ Hide and HTML browser in the Results Panel. :param wid: Window ID :param verbose: print more """ PARAMS={"id":wid} response=api(url=self.__url+"/hide?",PARAMS=PARAMS, method="GET", verbose=verbose) return response
Hide and HTML browser in the Results Panel. :param wid: Window ID :param verbose: print more
Below is the the instruction that describes the task: ### Input: Hide and HTML browser in the Results Panel. :param wid: Window ID :param verbose: print more ### Response: def hide(self, wid, verbose=False): """ Hide and HTML browser in the Results Panel. :param wid: Windo...
def _parse_top_level(self, body): """ Ensure compliance with the spec's top-level section """ link = 'jsonapi.org/format/#document-top-level' try: if not isinstance(body['data'], dict): raise TypeError except (KeyError, TypeError): self.fail('JSO...
Ensure compliance with the spec's top-level section
Below is the the instruction that describes the task: ### Input: Ensure compliance with the spec's top-level section ### Response: def _parse_top_level(self, body): """ Ensure compliance with the spec's top-level section """ link = 'jsonapi.org/format/#document-top-level' try: ...
def ICM(input_dim, num_outputs, kernel, W_rank=1,W=None,kappa=None,name='ICM'): """ Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality (does not include dimension of indices) :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the ...
Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality (does not include dimension of indices) :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B). :type kernel: a GPy kernel :param W_rank: number tu...
Below is the the instruction that describes the task: ### Input: Builds a kernel for an Intrinsic Coregionalization Model :input_dim: Input dimensionality (does not include dimension of indices) :num_outputs: Number of outputs :param kernel: kernel that will be multiplied by the coregionalize kernel (m...
def compare(testsuite, gold, select='i-id i-input mrs'): """ Compare two [incr tsdb()] profiles. Args: testsuite (str, TestSuite): path to the test [incr tsdb()] testsuite or a :class:`TestSuite` object gold (str, TestSuite): path to the gold [incr tsdb()] testsuite ...
Compare two [incr tsdb()] profiles. Args: testsuite (str, TestSuite): path to the test [incr tsdb()] testsuite or a :class:`TestSuite` object gold (str, TestSuite): path to the gold [incr tsdb()] testsuite or a :class:`TestSuite` object select: TSQL query to select (...
Below is the the instruction that describes the task: ### Input: Compare two [incr tsdb()] profiles. Args: testsuite (str, TestSuite): path to the test [incr tsdb()] testsuite or a :class:`TestSuite` object gold (str, TestSuite): path to the gold [incr tsdb()] testsuite ...
def connectionMade(self): """Send a HTTP POST command with the appropriate CIM over HTTP headers and payload.""" self.factory.request_xml = str(self.factory.payload) self.sendCommand('POST', '/cimom') self.sendHeader('Host', '%s:%d' % (self.transport.ad...
Send a HTTP POST command with the appropriate CIM over HTTP headers and payload.
Below is the the instruction that describes the task: ### Input: Send a HTTP POST command with the appropriate CIM over HTTP headers and payload. ### Response: def connectionMade(self): """Send a HTTP POST command with the appropriate CIM over HTTP headers and payload.""" self.fact...
def gradient_log_joint(self, x): """ The gradient of the log joint probability. For the Gaussian terms, this is d/dx [-1/2 x^T J x + h^T x] = -Jx + h. For the likelihood terms, we have for each time t d/dx log p(yt | xt) """ T, D = self.T, self...
The gradient of the log joint probability. For the Gaussian terms, this is d/dx [-1/2 x^T J x + h^T x] = -Jx + h. For the likelihood terms, we have for each time t d/dx log p(yt | xt)
Below is the the instruction that describes the task: ### Input: The gradient of the log joint probability. For the Gaussian terms, this is d/dx [-1/2 x^T J x + h^T x] = -Jx + h. For the likelihood terms, we have for each time t d/dx log p(yt | xt) ### Response: def grad...
async def SetMeterStatus(self, statues): ''' statues : typing.Sequence[~MeterStatusParam] Returns -> typing.Sequence[~ErrorResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='MetricsDebug', request='SetMeterStatus', ...
statues : typing.Sequence[~MeterStatusParam] Returns -> typing.Sequence[~ErrorResult]
Below is the the instruction that describes the task: ### Input: statues : typing.Sequence[~MeterStatusParam] Returns -> typing.Sequence[~ErrorResult] ### Response: async def SetMeterStatus(self, statues): ''' statues : typing.Sequence[~MeterStatusParam] Returns -> typing.Sequence[~...
def get_items(self, paginator, current_page): """Get list items for current page""" fields = self.get_model_config().get_list_fields() page = paginator.page(current_page) items = [] for item in page: items.append({ 'id': item.id, 'url...
Get list items for current page
Below is the the instruction that describes the task: ### Input: Get list items for current page ### Response: def get_items(self, paginator, current_page): """Get list items for current page""" fields = self.get_model_config().get_list_fields() page = paginator.page(current_page) ...
def _format_finite(negative, digits, dot_pos): """Given a (possibly empty) string of digits and an integer dot_pos indicating the position of the decimal point relative to the start of that string, output a formatted numeric string with the same value and same implicit exponent.""" # strip leading ...
Given a (possibly empty) string of digits and an integer dot_pos indicating the position of the decimal point relative to the start of that string, output a formatted numeric string with the same value and same implicit exponent.
Below is the the instruction that describes the task: ### Input: Given a (possibly empty) string of digits and an integer dot_pos indicating the position of the decimal point relative to the start of that string, output a formatted numeric string with the same value and same implicit exponent. ### Respo...
def _decode_next_layer(self, dict_, proto=None, length=None, *, version=4, ipv6_exthdr=None): """Decode next layer extractor. Positional arguments: * dict_ -- dict, info buffer * proto -- str, next layer protocol name * length -- int, valid (not padding) length ...
Decode next layer extractor. Positional arguments: * dict_ -- dict, info buffer * proto -- str, next layer protocol name * length -- int, valid (not padding) length Keyword Arguments: * version -- int, IP version (4 in default) ...
Below is the the instruction that describes the task: ### Input: Decode next layer extractor. Positional arguments: * dict_ -- dict, info buffer * proto -- str, next layer protocol name * length -- int, valid (not padding) length Keyword Arguments: *...
def generate_moffat_profile(seeing_fwhm, alpha): """Generate a normalized Moffat profile from its FWHM and alpha""" scale = 2 * math.sqrt(2**(1.0 / alpha) - 1) gamma = seeing_fwhm / scale amplitude = 1.0 / math.pi * (alpha - 1) / gamma**2 seeing_model = Moffat2D(amplitude=amplitude, ...
Generate a normalized Moffat profile from its FWHM and alpha
Below is the the instruction that describes the task: ### Input: Generate a normalized Moffat profile from its FWHM and alpha ### Response: def generate_moffat_profile(seeing_fwhm, alpha): """Generate a normalized Moffat profile from its FWHM and alpha""" scale = 2 * math.sqrt(2**(1.0 / alpha) - 1) ga...
def delete(name=None, group_id=None, region=None, key=None, keyid=None, profile=None, vpc_id=None, vpc_name=None): ''' Delete a security group. CLI example:: salt myminion boto_secgroup.delete mysecgroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
Delete a security group. CLI example:: salt myminion boto_secgroup.delete mysecgroup
Below is the the instruction that describes the task: ### Input: Delete a security group. CLI example:: salt myminion boto_secgroup.delete mysecgroup ### Response: def delete(name=None, group_id=None, region=None, key=None, keyid=None, profile=None, vpc_id=None, vpc_name=None): ''' ...
def apply_defaults(self, other_config): """ Applies default values from a different ConfigObject or ConfigKey object to this ConfigObject. If there are any values in this object that are also in the default object, it will use the values from this object. """ if isinstance(other...
Applies default values from a different ConfigObject or ConfigKey object to this ConfigObject. If there are any values in this object that are also in the default object, it will use the values from this object.
Below is the the instruction that describes the task: ### Input: Applies default values from a different ConfigObject or ConfigKey object to this ConfigObject. If there are any values in this object that are also in the default object, it will use the values from this object. ### Response: def apply_defau...
def call_s3guard_prune(credential_name): """ Runs S3Guard prune command on external account associated with the given credential_name. """ # Get the AWS credential account associated with the credential account = get_external_account(api, credential_name) # Invoke the prune command for the account by its n...
Runs S3Guard prune command on external account associated with the given credential_name.
Below is the the instruction that describes the task: ### Input: Runs S3Guard prune command on external account associated with the given credential_name. ### Response: def call_s3guard_prune(credential_name): """ Runs S3Guard prune command on external account associated with the given credential_name. "...
def declare_local_variable(self, raw_name, type=None, prepend=False): ''' This function may create a new variable in this scope. If raw_name has been used to create other variables, the new variable will hide all other variables created using raw_name. ''' # Get unique ID for the...
This function may create a new variable in this scope. If raw_name has been used to create other variables, the new variable will hide all other variables created using raw_name.
Below is the the instruction that describes the task: ### Input: This function may create a new variable in this scope. If raw_name has been used to create other variables, the new variable will hide all other variables created using raw_name. ### Response: def declare_local_variable(self, raw_name, type=N...
def get_field_identifiers(self): """ Builds a list of the field identifiers for all tables and joined tables by calling ``get_field_identifiers()`` on each table :return: list of field identifiers :rtype: list of str """ field_identifiers = [] for table i...
Builds a list of the field identifiers for all tables and joined tables by calling ``get_field_identifiers()`` on each table :return: list of field identifiers :rtype: list of str
Below is the the instruction that describes the task: ### Input: Builds a list of the field identifiers for all tables and joined tables by calling ``get_field_identifiers()`` on each table :return: list of field identifiers :rtype: list of str ### Response: def get_field_identifiers(self)...
def graphdata(data): """returns ratings and episode number to be used for making graphs""" data = jh.get_ratings(data) num = 1 rating_final = [] episode_final = [] for k,v in data.iteritems(): rating=[] epinum=[] for r in v: if r != None: r...
returns ratings and episode number to be used for making graphs
Below is the the instruction that describes the task: ### Input: returns ratings and episode number to be used for making graphs ### Response: def graphdata(data): """returns ratings and episode number to be used for making graphs""" data = jh.get_ratings(data) num = 1 rating_final = [] ...
def remove_global_hook(handler): """remove a callback from the list of global hooks :param handler: the callback function, previously added with global_hook, to remove from the list of global hooks :type handler: function :returns: bool, whether the handler was removed from the global ...
remove a callback from the list of global hooks :param handler: the callback function, previously added with global_hook, to remove from the list of global hooks :type handler: function :returns: bool, whether the handler was removed from the global hooks
Below is the the instruction that describes the task: ### Input: remove a callback from the list of global hooks :param handler: the callback function, previously added with global_hook, to remove from the list of global hooks :type handler: function :returns: bool, whether the handler...
def wrap2cylinder(script, radius=1, pitch=0, taper=0, pitch_func=None, taper_func=None): """Deform mesh around cylinder of radius and axis z y = 0 will be on the surface of radius "radius" pitch != 0 will create a helix, with distance "pitch" traveled in z for each rotation taper = ch...
Deform mesh around cylinder of radius and axis z y = 0 will be on the surface of radius "radius" pitch != 0 will create a helix, with distance "pitch" traveled in z for each rotation taper = change in r over z. E.g. a value of 0.5 will shrink r by 0.5 for every z length of 1
Below is the the instruction that describes the task: ### Input: Deform mesh around cylinder of radius and axis z y = 0 will be on the surface of radius "radius" pitch != 0 will create a helix, with distance "pitch" traveled in z for each rotation taper = change in r over z. E.g. a value of 0.5 will sh...
def _format_with_same_year_and_month(format_specifier): """ Return a version of `format_specifier` that renders a date assuming it has the same year and month as another date. Usually this means ommitting the year and month. This can be overridden by specifying a format that has `_SAME_YEAR_S...
Return a version of `format_specifier` that renders a date assuming it has the same year and month as another date. Usually this means ommitting the year and month. This can be overridden by specifying a format that has `_SAME_YEAR_SAME_MONTH` appended to the name in the project's `formats` spec...
Below is the the instruction that describes the task: ### Input: Return a version of `format_specifier` that renders a date assuming it has the same year and month as another date. Usually this means ommitting the year and month. This can be overridden by specifying a format that has `_SAME_YEAR_...
def constructTx(self): """ Construct the actual transaction and store it in the class's dict store """ ops = list() for op in self.ops: if isinstance(op, ProposalBuilder): # This operation is a proposal an needs to be deal with # di...
Construct the actual transaction and store it in the class's dict store
Below is the the instruction that describes the task: ### Input: Construct the actual transaction and store it in the class's dict store ### Response: def constructTx(self): """ Construct the actual transaction and store it in the class's dict store """ ops = list() ...
def run(self): """Execute the build command.""" module = self.distribution.ext_modules[0] base_dir = os.path.dirname(__file__) if base_dir: os.chdir(base_dir) exclusions = [] for define in self.define or []: module.define_macros.append(define) for library in self.libraries o...
Execute the build command.
Below is the the instruction that describes the task: ### Input: Execute the build command. ### Response: def run(self): """Execute the build command.""" module = self.distribution.ext_modules[0] base_dir = os.path.dirname(__file__) if base_dir: os.chdir(base_dir) exclusions = [] ...
def get_issuer(self): """ Gets the Issuer of the Logout Response Message :return: The Issuer :rtype: string """ issuer = None issuer_nodes = self.__query('/samlp:LogoutResponse/saml:Issuer') if len(issuer_nodes) == 1: issuer = OneLogin_Saml2_Ut...
Gets the Issuer of the Logout Response Message :return: The Issuer :rtype: string
Below is the the instruction that describes the task: ### Input: Gets the Issuer of the Logout Response Message :return: The Issuer :rtype: string ### Response: def get_issuer(self): """ Gets the Issuer of the Logout Response Message :return: The Issuer :rtype: strin...
def authorized_signup_handler(resp, remote, *args, **kwargs): """Handle sign-in/up functionality. :param remote: The remote application. :param resp: The response. :returns: Redirect response. """ # Remove any previously stored auto register session key session.pop(token_session_key(remote....
Handle sign-in/up functionality. :param remote: The remote application. :param resp: The response. :returns: Redirect response.
Below is the the instruction that describes the task: ### Input: Handle sign-in/up functionality. :param remote: The remote application. :param resp: The response. :returns: Redirect response. ### Response: def authorized_signup_handler(resp, remote, *args, **kwargs): """Handle sign-in/up function...
def get_pourbaix_plot(self, limits=None, title="", label_domains=True, plt=None): """ Plot Pourbaix diagram. Args: limits: 2D list containing limits of the Pourbaix diagram of the form [[xlo, xhi], [ylo, yhi]] title (str): Title ...
Plot Pourbaix diagram. Args: limits: 2D list containing limits of the Pourbaix diagram of the form [[xlo, xhi], [ylo, yhi]] title (str): Title to display on plot label_domains (bool): whether to label pourbaix domains plt (pyplot): Pyplot instance...
Below is the the instruction that describes the task: ### Input: Plot Pourbaix diagram. Args: limits: 2D list containing limits of the Pourbaix diagram of the form [[xlo, xhi], [ylo, yhi]] title (str): Title to display on plot label_domains (bool): whethe...
def send(self, src_file, filename, st_mode=DEFAULT_PUSH_MODE, mtime=None, timeout=None): """Push a file-like object to the device. Args: src_file: File-like object for reading from filename: Filename to push to on the device st_mode: stat mode for filename on the device mtime...
Push a file-like object to the device. Args: src_file: File-like object for reading from filename: Filename to push to on the device st_mode: stat mode for filename on the device mtime: modification time to set for the file on the device timeout: Timeout to use for the send operation....
Below is the the instruction that describes the task: ### Input: Push a file-like object to the device. Args: src_file: File-like object for reading from filename: Filename to push to on the device st_mode: stat mode for filename on the device mtime: modification time to set for the fil...
def fundarb( self, jsl_username, jsl_password, avolume=100, bvolume=100, ptype="price", ): """以字典形式返回分级A数据 :param jsl_username: 集思录用户名 :param jsl_password: 集思路登录密码 :param avolume: A成交额,单位百万 :param bvolume: B成交额,单位百万 :par...
以字典形式返回分级A数据 :param jsl_username: 集思录用户名 :param jsl_password: 集思路登录密码 :param avolume: A成交额,单位百万 :param bvolume: B成交额,单位百万 :param ptype: 溢价计算方式,price=现价,buy=买一,sell=卖一
Below is the the instruction that describes the task: ### Input: 以字典形式返回分级A数据 :param jsl_username: 集思录用户名 :param jsl_password: 集思路登录密码 :param avolume: A成交额,单位百万 :param bvolume: B成交额,单位百万 :param ptype: 溢价计算方式,price=现价,buy=买一,sell=卖一 ### Response: def fundarb( self, ...
def line(self, x, label=None, y='bottom', color='grey', **kwargs): ''' Creates a vertical line in the plot. :param x: The x coordinate of the line. Should be in the same units as the x-axis. :param string label: The label to be displayed. :par...
Creates a vertical line in the plot. :param x: The x coordinate of the line. Should be in the same units as the x-axis. :param string label: The label to be displayed. :param y: May be 'top', 'bottom' or int. The y coordinate of the te...
Below is the the instruction that describes the task: ### Input: Creates a vertical line in the plot. :param x: The x coordinate of the line. Should be in the same units as the x-axis. :param string label: The label to be displayed. :param y: ...
def deleteLink(self, linkdict): """Delete link if PDF""" CheckParent(self) val = _fitz.Page_deleteLink(self, linkdict) if linkdict["xref"] == 0: return linkid = linkdict["id"] try: linkobj = self._annot_refs[linkid] linkobj._erase() except...
Delete link if PDF
Below is the the instruction that describes the task: ### Input: Delete link if PDF ### Response: def deleteLink(self, linkdict): """Delete link if PDF""" CheckParent(self) val = _fitz.Page_deleteLink(self, linkdict) if linkdict["xref"] == 0: return linkid = linkdict["id"] ...
def log(self, message, severity=INFO, tag=u""): """ Add a given message to the log, and return its time. :param string message: the message to be added :param severity: the severity of the message :type severity: :class:`~aeneas.logger.Logger` :param string tag: the tag...
Add a given message to the log, and return its time. :param string message: the message to be added :param severity: the severity of the message :type severity: :class:`~aeneas.logger.Logger` :param string tag: the tag associated with the message; usually, th...
Below is the the instruction that describes the task: ### Input: Add a given message to the log, and return its time. :param string message: the message to be added :param severity: the severity of the message :type severity: :class:`~aeneas.logger.Logger` :param string tag: the ta...
def maintained_selection(): """Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... cmds.select('node', replace=True) >>> # Selection restored """ previous_selection = cmds.ls(selection=True) try: yi...
Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... cmds.select('node', replace=True) >>> # Selection restored
Below is the the instruction that describes the task: ### Input: Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... cmds.select('node', replace=True) >>> # Selection restored ### Response: def maintained_selection(): ...
def update_git_repos(clean=False): ''' Checkout git repos containing :ref:`Windows Software Package Definitions <windows-package-manager>`. .. important:: This function requires `Git for Windows`_ to be installed in order to work. When installing, make sure to select an installation opt...
Checkout git repos containing :ref:`Windows Software Package Definitions <windows-package-manager>`. .. important:: This function requires `Git for Windows`_ to be installed in order to work. When installing, make sure to select an installation option which permits the git executable to...
Below is the the instruction that describes the task: ### Input: Checkout git repos containing :ref:`Windows Software Package Definitions <windows-package-manager>`. .. important:: This function requires `Git for Windows`_ to be installed in order to work. When installing, make sure to sele...
def _make_complex(self): """Convert the real SHCoeffs class to the complex class.""" rcomplex_coeffs = _shtools.SHrtoc(self.coeffs, convention=1, switchcs=0) # These coefficients are using real floats, and need to be # converted to complex form....
Convert the real SHCoeffs class to the complex class.
Below is the the instruction that describes the task: ### Input: Convert the real SHCoeffs class to the complex class. ### Response: def _make_complex(self): """Convert the real SHCoeffs class to the complex class.""" rcomplex_coeffs = _shtools.SHrtoc(self.coeffs, ...
def safe_dump(data, stream=None, **kwds): """ Serialize a Python object into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead. """ return dump_all([data], stream, Dumper=SafeDumper, **kwds)
Serialize a Python object into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead.
Below is the the instruction that describes the task: ### Input: Serialize a Python object into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead. ### Response: def safe_dump(data, stream=None, **kwds): """ Serialize a Python object into a YAML strea...