code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _getNearestMappingIndexList(fromValList, toValList): ''' Finds the indicies for data points that are closest to each other. The inputs should be in relative time, scaled from 0 to 1 e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1] will output [0, 1, 1, 2] ''' indexList = [] for...
Finds the indicies for data points that are closest to each other. The inputs should be in relative time, scaled from 0 to 1 e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1] will output [0, 1, 1, 2]
Below is the the instruction that describes the task: ### Input: Finds the indicies for data points that are closest to each other. The inputs should be in relative time, scaled from 0 to 1 e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1] will output [0, 1, 1, 2] ### Response: def _getNearestMappi...
def request(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were replied by a reply socket. Note that the iterable returns as many parts as sent by repliers. Also, the sender func...
Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were replied by a reply socket. Note that the iterable returns as many parts as sent by repliers. Also, the sender function has a ``print`` like signa...
Below is the the instruction that describes the task: ### Input: Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were replied by a reply socket. Note that the iterable returns as many parts as sent by r...
def date(page): """ Return the date, nicely-formatted """ soup = BeautifulSoup(page) try: page_date = soup.find('input', attrs={'name': 'date'})['value'] parsed_date = datetime.strptime(page_date, '%Y-%m-%d') return parsed_date.strftime('%a, %b %d, %Y') except: re...
Return the date, nicely-formatted
Below is the the instruction that describes the task: ### Input: Return the date, nicely-formatted ### Response: def date(page): """ Return the date, nicely-formatted """ soup = BeautifulSoup(page) try: page_date = soup.find('input', attrs={'name': 'date'})['value'] parsed_date ...
def potential_radiation(dates, lon, lat, timezone, terrain_slope=0, terrain_slope_azimuth=0, cloud_fraction=0, split=False): """ Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E...
Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E. and Elder, K. (2006): A Meteorological Distribution System for High-Resolution Terrestrial Modeling (MicroMet), J. Hydrometeorol., 7, 217–234. Correct...
Below is the the instruction that describes the task: ### Input: Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E. and Elder, K. (2006): A Meteorological Distribution System for High-Resolution Terrestri...
def send(self, message) : "puts a message in the outgoing queue." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if serial = ct.c_uint() if not dbus.dbus_connection_send(self._dbobj, message._dbobj, ct.byref(serial)) : ...
puts a message in the outgoing queue.
Below is the the instruction that describes the task: ### Input: puts a message in the outgoing queue. ### Response: def send(self, message) : "puts a message in the outgoing queue." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if ...
def _search_capability(self, base): """Given a class, return a list of all of the derived classes that are themselves derived from Capability.""" if _debug: Collector._debug("_search_capability %r", base) rslt = [] for cls in base.__bases__: if issubclass(cls, Collec...
Given a class, return a list of all of the derived classes that are themselves derived from Capability.
Below is the the instruction that describes the task: ### Input: Given a class, return a list of all of the derived classes that are themselves derived from Capability. ### Response: def _search_capability(self, base): """Given a class, return a list of all of the derived classes that are t...
def _parse_formula(s): """Parse formula string.""" scanner = re.compile(r''' (\s+) | # whitespace (\(|\)) | # group ([A-Z][a-z]*) | # element (\d+) | # number ([a-z]) | # variable (\Z) | # end (.) # error ...
Parse formula string.
Below is the the instruction that describes the task: ### Input: Parse formula string. ### Response: def _parse_formula(s): """Parse formula string.""" scanner = re.compile(r''' (\s+) | # whitespace (\(|\)) | # group ([A-Z][a-z]*) | # element (\d+) | # ...
def active(self): """Returns all outlets that are currently active and have sales.""" qs = self.get_queryset() return qs.filter( models.Q( models.Q(start_date__isnull=True) | models.Q(start_date__lte=now().date()) ) & models.Q( ...
Returns all outlets that are currently active and have sales.
Below is the the instruction that describes the task: ### Input: Returns all outlets that are currently active and have sales. ### Response: def active(self): """Returns all outlets that are currently active and have sales.""" qs = self.get_queryset() return qs.filter( models.Q(...
def get_irradiance(self, surface_tilt, surface_azimuth, solar_zenith, solar_azimuth, dni, ghi, dhi, dni_extra=None, airmass=None, model='haydavies', **kwargs): """ Uses the :func:`irradiance.get_total_irradiance` function to ca...
Uses the :func:`irradiance.get_total_irradiance` function to calculate the plane of array irradiance components on a tilted surface defined by the input data and ``self.albedo``. For a given set of solar zenith and azimuth angles, the surface tilt and azimuth parameters are typically de...
Below is the the instruction that describes the task: ### Input: Uses the :func:`irradiance.get_total_irradiance` function to calculate the plane of array irradiance components on a tilted surface defined by the input data and ``self.albedo``. For a given set of solar zenith and azimuth ang...
def get_stream(self, error_callback=None, live=True): """ Get room stream to listen for messages. Kwargs: error_callback (func): Callback to call when an error occurred (parameters: exception) live (bool): If True, issue a live stream, otherwise an offline stream Return...
Get room stream to listen for messages. Kwargs: error_callback (func): Callback to call when an error occurred (parameters: exception) live (bool): If True, issue a live stream, otherwise an offline stream Returns: :class:`Stream`. Stream
Below is the the instruction that describes the task: ### Input: Get room stream to listen for messages. Kwargs: error_callback (func): Callback to call when an error occurred (parameters: exception) live (bool): If True, issue a live stream, otherwise an offline stream Ret...
def present(name, tag=None, build=None, load=None, force=False, insecure_registry=False, client_timeout=salt.utils.docker.CLIENT_TIMEOUT, dockerfile=None, sls=None, base='opensuse/python', saltenv='ba...
.. versionchanged:: 2018.3.0 The ``tag`` argument has been added. It is now required unless pulling from a registry. Ensure that an image is present. The image can either be pulled from a Docker registry, built from a Dockerfile, loaded from a saved image, or built by running SLS files agai...
Below is the the instruction that describes the task: ### Input: .. versionchanged:: 2018.3.0 The ``tag`` argument has been added. It is now required unless pulling from a registry. Ensure that an image is present. The image can either be pulled from a Docker registry, built from a Dockerfi...
def send(self, data): """Send some part of message to the socket.""" bytes_sent = self._sock.send(extract_bytes(data)) self.bytes_written += bytes_sent return bytes_sent
Send some part of message to the socket.
Below is the the instruction that describes the task: ### Input: Send some part of message to the socket. ### Response: def send(self, data): """Send some part of message to the socket.""" bytes_sent = self._sock.send(extract_bytes(data)) self.bytes_written += bytes_sent return byte...
def _UpdateCampaignDSASetting(client, campaign_id, feed_id): """Updates the campaign DSA setting to DSA pagefeeds. Args: client: an AdWordsClient instance. campaign_id: a str Campaign ID. feed_id: a str page Feed ID. Raises: ValueError: If the given campaign is found not to be a dynamic search a...
Updates the campaign DSA setting to DSA pagefeeds. Args: client: an AdWordsClient instance. campaign_id: a str Campaign ID. feed_id: a str page Feed ID. Raises: ValueError: If the given campaign is found not to be a dynamic search ad campaign.
Below is the the instruction that describes the task: ### Input: Updates the campaign DSA setting to DSA pagefeeds. Args: client: an AdWordsClient instance. campaign_id: a str Campaign ID. feed_id: a str page Feed ID. Raises: ValueError: If the given campaign is found not to be a dynamic searc...
def insert_element(self, vector, value, idx, name=''): """ Returns vector with vector[idx] replaced by value. The result is undefined if the idx is larger or equal the vector length. """ instr = instructions.InsertElement(self.block, vector, value, idx, ...
Returns vector with vector[idx] replaced by value. The result is undefined if the idx is larger or equal the vector length.
Below is the the instruction that describes the task: ### Input: Returns vector with vector[idx] replaced by value. The result is undefined if the idx is larger or equal the vector length. ### Response: def insert_element(self, vector, value, idx, name=''): """ Returns vector with vector[id...
def add_metric(self, metric: float) -> None: """ Record a new value of the metric and update the various things that depend on it. """ new_best = ((self._best_so_far is None) or (self._should_decrease and metric < self._best_so_far) or (not self._s...
Record a new value of the metric and update the various things that depend on it.
Below is the the instruction that describes the task: ### Input: Record a new value of the metric and update the various things that depend on it. ### Response: def add_metric(self, metric: float) -> None: """ Record a new value of the metric and update the various things that depend on it. ...
def select(self, *keys): """ 指定查询返回结果中只包含某些字段。可以重复调用,每次调用的包含内容都将会被返回。 :param keys: 包含字段名 :rtype: Query """ if len(keys) == 1 and isinstance(keys[0], (list, tuple)): keys = keys[0] self._select += keys return self
指定查询返回结果中只包含某些字段。可以重复调用,每次调用的包含内容都将会被返回。 :param keys: 包含字段名 :rtype: Query
Below is the the instruction that describes the task: ### Input: 指定查询返回结果中只包含某些字段。可以重复调用,每次调用的包含内容都将会被返回。 :param keys: 包含字段名 :rtype: Query ### Response: def select(self, *keys): """ 指定查询返回结果中只包含某些字段。可以重复调用,每次调用的包含内容都将会被返回。 :param keys: 包含字段名 :rtype: Query "...
def _line_wrapper(self,diffs): """Returns iterator that splits (wraps) mdiff text lines""" # pull from/to data and flags from mdiff iterator for fromdata,todata,flag in diffs: # check for context separators and pass them through if flag is None: yield fro...
Returns iterator that splits (wraps) mdiff text lines
Below is the the instruction that describes the task: ### Input: Returns iterator that splits (wraps) mdiff text lines ### Response: def _line_wrapper(self,diffs): """Returns iterator that splits (wraps) mdiff text lines""" # pull from/to data and flags from mdiff iterator for fromdata,tod...
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if vars is None: vars = {} define_rx = re.compile("#de...
Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary.
Below is the the instruction that describes the task: ### Input: Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. ### Response: def parse_config_h(fp, vars=None): ...
def do_tree(self, params): """ \x1b[1mNAME\x1b[0m tree - Print the tree under a given path \x1b[1mSYNOPSIS\x1b[0m tree [path] [max_depth] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * max_depth: max recursion limit (0 is no limit) (default: 0) \x1b[1mEXAMPLES\x1b[0m ...
\x1b[1mNAME\x1b[0m tree - Print the tree under a given path \x1b[1mSYNOPSIS\x1b[0m tree [path] [max_depth] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * max_depth: max recursion limit (0 is no limit) (default: 0) \x1b[1mEXAMPLES\x1b[0m > tree . ├── zo...
Below is the the instruction that describes the task: ### Input: \x1b[1mNAME\x1b[0m tree - Print the tree under a given path \x1b[1mSYNOPSIS\x1b[0m tree [path] [max_depth] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * max_depth: max recursion limit (0 is no limit) (defaul...
def sign(self, message): """Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return crypto.sign(self._key, me...
Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key.
Below is the the instruction that describes the task: ### Input: Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key. ### Response: def sign(self, message): """Signs a message. Args: ...
def has_text_frame(self): """ Return |True| if this data label has a text frame (implying it has custom data label text), and |False| otherwise. Assigning |True| causes a text frame to be added if not already present. Assigning |False| causes any existing text frame to be removed...
Return |True| if this data label has a text frame (implying it has custom data label text), and |False| otherwise. Assigning |True| causes a text frame to be added if not already present. Assigning |False| causes any existing text frame to be removed along with any text contained in the ...
Below is the the instruction that describes the task: ### Input: Return |True| if this data label has a text frame (implying it has custom data label text), and |False| otherwise. Assigning |True| causes a text frame to be added if not already present. Assigning |False| causes any existing t...
def gen_random_key(size=32): """ Generate a cryptographically-secure random key. This is done by using Python 2.4's os.urandom, or PyCrypto. """ import os if hasattr(os, "urandom"): # Python 2.4+ return os.urandom(size) # Try using PyCrypto if available try: from Crypto....
Generate a cryptographically-secure random key. This is done by using Python 2.4's os.urandom, or PyCrypto.
Below is the the instruction that describes the task: ### Input: Generate a cryptographically-secure random key. This is done by using Python 2.4's os.urandom, or PyCrypto. ### Response: def gen_random_key(size=32): """ Generate a cryptographically-secure random key. This is done by using Python 2....
def get_service_key(self, service_name, key_name): """ Returns the service key details. Similar to `cf service-key`. """ for key in self._get_service_keys(service_name)['resources']: if key_name == key['entity']['name']: guid = key['metadata']['guid']...
Returns the service key details. Similar to `cf service-key`.
Below is the the instruction that describes the task: ### Input: Returns the service key details. Similar to `cf service-key`. ### Response: def get_service_key(self, service_name, key_name): """ Returns the service key details. Similar to `cf service-key`. """ for...
def get_entry_url(self, entry): """ Return the URL of a blog entry, relative to this page. """ # It could be possible this page is fetched as fallback, while the 'entry' does have a translation. # - Currently django-fluent-pages 1.0b3 `Page.objects.get_for_path()` assigns the lan...
Return the URL of a blog entry, relative to this page.
Below is the the instruction that describes the task: ### Input: Return the URL of a blog entry, relative to this page. ### Response: def get_entry_url(self, entry): """ Return the URL of a blog entry, relative to this page. """ # It could be possible this page is fetched as fallbac...
def create(cls, *args, **kwargs) -> 'Entity': """Create a new record in the repository. Also performs unique validations before creating the entity :param args: positional arguments for the entity :param kwargs: keyword arguments for the entity """ logger.debug( ...
Create a new record in the repository. Also performs unique validations before creating the entity :param args: positional arguments for the entity :param kwargs: keyword arguments for the entity
Below is the the instruction that describes the task: ### Input: Create a new record in the repository. Also performs unique validations before creating the entity :param args: positional arguments for the entity :param kwargs: keyword arguments for the entity ### Response: def create(cls...
def getArticles(self, page=1, count=100, sortBy = "rel", sortByAsc = False, returnInfo=ReturnInfo()): """ return a list of articles that match the topic page @param page: which page of the results to return (default:...
return a list of articles that match the topic page @param page: which page of the results to return (default: 1) @param count: number of articles to return (default: 100) @param sortBy: how are articles sorted. Options: id (internal id), date (publishing date), cosSim (closeness to the event ce...
Below is the the instruction that describes the task: ### Input: return a list of articles that match the topic page @param page: which page of the results to return (default: 1) @param count: number of articles to return (default: 100) @param sortBy: how are articles sorted. Options: id (in...
def update_pareto_optimal_tuples(self, new_pareto_tuple): """ # this function should be optimized Parameters ---------- new_pareto_tuple: LabelTimeSimple Returns ------- added: bool whether new_pareto_tuple was added to the set of pareto-opti...
# this function should be optimized Parameters ---------- new_pareto_tuple: LabelTimeSimple Returns ------- added: bool whether new_pareto_tuple was added to the set of pareto-optimal tuples
Below is the the instruction that describes the task: ### Input: # this function should be optimized Parameters ---------- new_pareto_tuple: LabelTimeSimple Returns ------- added: bool whether new_pareto_tuple was added to the set of pareto-optimal tuple...
def get_changed(self, p1, p2): """ Return the loci that are in clusters that have changed between partitions p1 and p2 """ if p1 is None or p2 is None: return list(range(len(self.insts))) return set(flatten_list(set(p1) - set(p2)))
Return the loci that are in clusters that have changed between partitions p1 and p2
Below is the the instruction that describes the task: ### Input: Return the loci that are in clusters that have changed between partitions p1 and p2 ### Response: def get_changed(self, p1, p2): """ Return the loci that are in clusters that have changed between partitions p1 and p2 ...
def get_parsed_context(context_arg): """Parse input context string and returns context as dictionary.""" if not context_arg: logger.debug("pipeline invoked without context arg set. For " "this json parser you're looking for something " "like: " ...
Parse input context string and returns context as dictionary.
Below is the the instruction that describes the task: ### Input: Parse input context string and returns context as dictionary. ### Response: def get_parsed_context(context_arg): """Parse input context string and returns context as dictionary.""" if not context_arg: logger.debug("pipeline invoked wi...
def do_rmdep(self, args): """Removes dependent variables currently set for plotting/tabulating etc.""" for arg in args.split(): if arg in self.curargs["dependents"]: self.curargs["dependents"].remove(arg) if arg in self.curargs["plottypes"]: del se...
Removes dependent variables currently set for plotting/tabulating etc.
Below is the the instruction that describes the task: ### Input: Removes dependent variables currently set for plotting/tabulating etc. ### Response: def do_rmdep(self, args): """Removes dependent variables currently set for plotting/tabulating etc.""" for arg in args.split(): if arg in...
def get_builds(self, job_name): """ Retrieve all builds from a job""" if self.blacklist_jobs and job_name in self.blacklist_jobs: logger.warning("Not getting blacklisted job: %s", job_name) return payload = {'depth': self.detail_depth} url_build = urijoin(self.b...
Retrieve all builds from a job
Below is the the instruction that describes the task: ### Input: Retrieve all builds from a job ### Response: def get_builds(self, job_name): """ Retrieve all builds from a job""" if self.blacklist_jobs and job_name in self.blacklist_jobs: logger.warning("Not getting blacklisted job: %...
def _cr_decode(self, msg): """CR: Custom values""" if int(msg[4:6]) > 0: index = int(msg[4:6])-1 return {'values': [self._cr_one_custom_value_decode(index, msg[6:12])]} else: part = 6 ret = [] for i in range(Max.SETTINGS.value): ...
CR: Custom values
Below is the the instruction that describes the task: ### Input: CR: Custom values ### Response: def _cr_decode(self, msg): """CR: Custom values""" if int(msg[4:6]) > 0: index = int(msg[4:6])-1 return {'values': [self._cr_one_custom_value_decode(index, msg[6:12])]} e...
def resolve(self, ref, document=None): """Resolve a ref within the schema. This is just a convenience method, since RefResolver returns both a URI and the resolved value, and we usually just need the resolved value. :param str ref: URI to resolve. :param dict document: Optional...
Resolve a ref within the schema. This is just a convenience method, since RefResolver returns both a URI and the resolved value, and we usually just need the resolved value. :param str ref: URI to resolve. :param dict document: Optional schema in which to resolve the URI. :retu...
Below is the the instruction that describes the task: ### Input: Resolve a ref within the schema. This is just a convenience method, since RefResolver returns both a URI and the resolved value, and we usually just need the resolved value. :param str ref: URI to resolve. :param dict...
def attributesGTF(inGTF): """ List the type of attributes in a the attribute section of a GTF file :param inGTF: GTF dataframe to be analysed :returns: a list of attributes present in the attribute section """ df=pd.DataFrame(inGTF['attribute'].str.split(";").tolist()) desc=[] for i in...
List the type of attributes in a the attribute section of a GTF file :param inGTF: GTF dataframe to be analysed :returns: a list of attributes present in the attribute section
Below is the the instruction that describes the task: ### Input: List the type of attributes in a the attribute section of a GTF file :param inGTF: GTF dataframe to be analysed :returns: a list of attributes present in the attribute section ### Response: def attributesGTF(inGTF): """ List the type...
def status(backend): '''print the status for all or one of the backends. ''' print('[backend status]') settings = read_client_secrets() print('There are %s clients found in secrets.' %len(settings)) if 'SREGISTRY_CLIENT' in settings: print('active: %s' %settings['SREGISTRY_CLIENT']) ...
print the status for all or one of the backends.
Below is the the instruction that describes the task: ### Input: print the status for all or one of the backends. ### Response: def status(backend): '''print the status for all or one of the backends. ''' print('[backend status]') settings = read_client_secrets() print('There are %s clients fou...
def attachment_upload(instance, filename): """Stores the attachment in a "per module/appname/primary key" folder""" return 'attachments/{app}_{model}/{pk}/{filename}'.format( app=instance.content_object._meta.app_label, model=instance.content_object._meta.object_name.lower(), pk=instance...
Stores the attachment in a "per module/appname/primary key" folder
Below is the the instruction that describes the task: ### Input: Stores the attachment in a "per module/appname/primary key" folder ### Response: def attachment_upload(instance, filename): """Stores the attachment in a "per module/appname/primary key" folder""" return 'attachments/{app}_{model}/{pk}/{filen...
def assign_private_ip_addresses(network_interface_name=None, network_interface_id=None, private_ip_addresses=None, secondary_private_ip_address_count=None, allow_reassignment=False, region=None, key=None, keyid=None, profile...
Assigns one or more secondary private IP addresses to a network interface. network_interface_id (string) - ID of the network interface to associate the IP with (exclusive with 'network_interface_name') network_interface_name (string) - Name of the network interface to associate the IP with (exc...
Below is the the instruction that describes the task: ### Input: Assigns one or more secondary private IP addresses to a network interface. network_interface_id (string) - ID of the network interface to associate the IP with (exclusive with 'network_interface_name') network_interface_name (...
def get_base_wrappers(method='get', template_name='', predicates=(), wrappers=()): """ basic View Wrappers used by view_config. """ wrappers += (preserve_view(MethodPredicate(method), *predicates),) if template_name: wrappers += (render_template(template_name),) return wrappers
basic View Wrappers used by view_config.
Below is the the instruction that describes the task: ### Input: basic View Wrappers used by view_config. ### Response: def get_base_wrappers(method='get', template_name='', predicates=(), wrappers=()): """ basic View Wrappers used by view_config. """ wrappers += (preserve_view(MethodPredicate(method),...
def set_item_class_name(cls_obj): """ Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux """ if '__tohu__items__name__' in...
Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux
Below is the the instruction that describes the task: ### Input: Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux ### Response: def...
def json_2_nic(json_obj): """ transform JSON obj coming from Ariane to ariane_clip3 object :param json_obj: the JSON obj coming from Ariane :return: ariane_clip3 NIC object """ LOGGER.debug("NIC.json_2_nic") return NIC(nic_id=json_obj['nicID'], ...
transform JSON obj coming from Ariane to ariane_clip3 object :param json_obj: the JSON obj coming from Ariane :return: ariane_clip3 NIC object
Below is the the instruction that describes the task: ### Input: transform JSON obj coming from Ariane to ariane_clip3 object :param json_obj: the JSON obj coming from Ariane :return: ariane_clip3 NIC object ### Response: def json_2_nic(json_obj): """ transform JSON obj coming from ...
def create_ospf_area_with_message_digest_auth(): """ If you require message-digest authentication for your OSPFArea, you must create an OSPF key chain configuration. """ OSPFKeyChain.create(name='secure-keychain', key_chain_entry=[{'key': 'fookey', ...
If you require message-digest authentication for your OSPFArea, you must create an OSPF key chain configuration.
Below is the the instruction that describes the task: ### Input: If you require message-digest authentication for your OSPFArea, you must create an OSPF key chain configuration. ### Response: def create_ospf_area_with_message_digest_auth(): """ If you require message-digest authentication for your OSPF...
def play_Bars(self, bars, channels, bpm=120): """Play several bars (a list of Bar objects) at the same time. A list of channels should also be provided. The tempo can be changed by providing one or more of the NoteContainers with a bpm argument. """ self.notify_listeners(self.MS...
Play several bars (a list of Bar objects) at the same time. A list of channels should also be provided. The tempo can be changed by providing one or more of the NoteContainers with a bpm argument.
Below is the the instruction that describes the task: ### Input: Play several bars (a list of Bar objects) at the same time. A list of channels should also be provided. The tempo can be changed by providing one or more of the NoteContainers with a bpm argument. ### Response: def play_Bars(self, ba...
def get_loss(self, logits: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol: """ Returns loss and softmax output symbols given logits and integer-coded labels. :param logits: Shape: (batch_size * target_seq_len, target_vocab_size). :param labels: Shape: (batch_size * target_seq_le...
Returns loss and softmax output symbols given logits and integer-coded labels. :param logits: Shape: (batch_size * target_seq_len, target_vocab_size). :param labels: Shape: (batch_size * target_seq_len,). :return: Loss symbol.
Below is the the instruction that describes the task: ### Input: Returns loss and softmax output symbols given logits and integer-coded labels. :param logits: Shape: (batch_size * target_seq_len, target_vocab_size). :param labels: Shape: (batch_size * target_seq_len,). :return: Loss symbol....
def quick_send(self, send, echo=None, loglevel=logging.INFO): """Quick and dirty send that ignores background tasks. Intended for internal use. """ shutit = self.shutit shutit.log('Quick send: ' + send, level=loglevel) res = self.sendline(ShutItSendSpec(self, send=send, ...
Quick and dirty send that ignores background tasks. Intended for internal use.
Below is the the instruction that describes the task: ### Input: Quick and dirty send that ignores background tasks. Intended for internal use. ### Response: def quick_send(self, send, echo=None, loglevel=logging.INFO): """Quick and dirty send that ignores background tasks. Intended for internal use. """ shu...
def shutdown(self): """ clean shutdown of the nameserver and the config file (if written) """ if not self.pyro_ns is None: self.pyro_ns.shutdown() self.pyro_ns = None if not self.conf_fn is None: os.remove(self.conf_fn) self.conf_fn = None
clean shutdown of the nameserver and the config file (if written)
Below is the the instruction that describes the task: ### Input: clean shutdown of the nameserver and the config file (if written) ### Response: def shutdown(self): """ clean shutdown of the nameserver and the config file (if written) """ if not self.pyro_ns is None: self.pyro_ns.shutdown() self.pyr...
def CER(prediction, true_labels): """ Calculates the classification error rate for an N-class classification problem Parameters: prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your prediction true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing the ground t...
Calculates the classification error rate for an N-class classification problem Parameters: prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your prediction true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing the ground truth labels for the input array, organized...
Below is the the instruction that describes the task: ### Input: Calculates the classification error rate for an N-class classification problem Parameters: prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your prediction true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray` ...
def _as_published_topic(self): """This stream as a PublishedTopic if it is published otherwise None """ oop = self.get_operator_output_port() if not hasattr(oop, 'export'): return export = oop.export if export['type'] != 'properties': return ...
This stream as a PublishedTopic if it is published otherwise None
Below is the the instruction that describes the task: ### Input: This stream as a PublishedTopic if it is published otherwise None ### Response: def _as_published_topic(self): """This stream as a PublishedTopic if it is published otherwise None """ oop = self.get_operator_output_port() ...
def insert(self, i, tag1, tag2, cmd="prevtag", x=None, y=None): """ Inserts a new rule that updates words with tag1 to tag2, given constraints x and y, e.g., Context.append("TO < NN", "VB") """ if " < " in tag1 and not x and not y: tag1, x = tag1.split(" < "); cmd="prevta...
Inserts a new rule that updates words with tag1 to tag2, given constraints x and y, e.g., Context.append("TO < NN", "VB")
Below is the the instruction that describes the task: ### Input: Inserts a new rule that updates words with tag1 to tag2, given constraints x and y, e.g., Context.append("TO < NN", "VB") ### Response: def insert(self, i, tag1, tag2, cmd="prevtag", x=None, y=None): """ Inserts a new rule that up...
def random_offspring(self): "Returns an offspring with the associated weight(s)" function_set = self.function_set function_selection = self._function_selection_ins function_selection.density = self.population.density function_selection.unfeasible_functions.clear() for i i...
Returns an offspring with the associated weight(s)
Below is the the instruction that describes the task: ### Input: Returns an offspring with the associated weight(s) ### Response: def random_offspring(self): "Returns an offspring with the associated weight(s)" function_set = self.function_set function_selection = self._function_selection_i...
def static_dimensions(self): """ Return all constant dimensions. """ dimensions = [] for dim in self.kdims: if len(set(self.dimension_values(dim.name))) == 1: dimensions.append(dim) return dimensions
Return all constant dimensions.
Below is the the instruction that describes the task: ### Input: Return all constant dimensions. ### Response: def static_dimensions(self): """ Return all constant dimensions. """ dimensions = [] for dim in self.kdims: if len(set(self.dimension_values(dim.name)))...
def securityHandler(self, value): """ sets the security handler """ if isinstance(value, abstract.BaseSecurityHandler): if isinstance(value, security.AGOLTokenSecurityHandler): self._securityHandler = value self._token = value.token self._usern...
sets the security handler
Below is the the instruction that describes the task: ### Input: sets the security handler ### Response: def securityHandler(self, value): """ sets the security handler """ if isinstance(value, abstract.BaseSecurityHandler): if isinstance(value, security.AGOLTokenSecurityHandler): ...
def replace_between_tags(text, repl_, start_tag, end_tag=None): r""" Replaces text between sentinal lines in a block of text. Args: text (str): repl_ (str): start_tag (str): end_tag (str): (default=None) Returns: str: new_text CommandLine: python -m...
r""" Replaces text between sentinal lines in a block of text. Args: text (str): repl_ (str): start_tag (str): end_tag (str): (default=None) Returns: str: new_text CommandLine: python -m utool.util_str --exec-replace_between_tags Example: >>...
Below is the the instruction that describes the task: ### Input: r""" Replaces text between sentinal lines in a block of text. Args: text (str): repl_ (str): start_tag (str): end_tag (str): (default=None) Returns: str: new_text CommandLine: python -...
def eval_condition(self, event): """ Evaluates the breakpoint condition, if any was set. @type event: L{Event} @param event: Debug event triggered by the breakpoint. @rtype: bool @return: C{True} to dispatch the event, C{False} otherwise. """ condition...
Evaluates the breakpoint condition, if any was set. @type event: L{Event} @param event: Debug event triggered by the breakpoint. @rtype: bool @return: C{True} to dispatch the event, C{False} otherwise.
Below is the the instruction that describes the task: ### Input: Evaluates the breakpoint condition, if any was set. @type event: L{Event} @param event: Debug event triggered by the breakpoint. @rtype: bool @return: C{True} to dispatch the event, C{False} otherwise. ### Response:...
def client(self): """Returns client session object""" if self._client is None: self._client = get_session(self.user_agent) return self._client
Returns client session object
Below is the the instruction that describes the task: ### Input: Returns client session object ### Response: def client(self): """Returns client session object""" if self._client is None: self._client = get_session(self.user_agent) return self._client
def get_notification_result(self, stream_id): """ Get result for specified stream The function returns: 'Success' or 'failure reason' or ('Unregistered', timestamp) """ with self._connection.get_response(stream_id) as response: if response.status == 200: ...
Get result for specified stream The function returns: 'Success' or 'failure reason' or ('Unregistered', timestamp)
Below is the the instruction that describes the task: ### Input: Get result for specified stream The function returns: 'Success' or 'failure reason' or ('Unregistered', timestamp) ### Response: def get_notification_result(self, stream_id): """ Get result for specified stream The fun...
def verifychain_from_cafile(self, cafile, untrusted_file=None): """ Does the same job as .verifychain() but using the list of anchors from the cafile. This is useful (because more efficient) if you have a lot of certificates to verify do it that way: it avoids the creation of a c...
Does the same job as .verifychain() but using the list of anchors from the cafile. This is useful (because more efficient) if you have a lot of certificates to verify do it that way: it avoids the creation of a cafile from anchors at each call. As for .verifychain(), a list of untrusted...
Below is the the instruction that describes the task: ### Input: Does the same job as .verifychain() but using the list of anchors from the cafile. This is useful (because more efficient) if you have a lot of certificates to verify do it that way: it avoids the creation of a cafile from anch...
def safe_dict(obj_or_func, **kwargs): """ Create a dict from any object with all attributes, but not the ones starting with an underscore _ Useful for objects or function that return an object that have no __dict__ attribute, like psutil functions. """ if callable(obj_or_func): res = obj_or_...
Create a dict from any object with all attributes, but not the ones starting with an underscore _ Useful for objects or function that return an object that have no __dict__ attribute, like psutil functions.
Below is the the instruction that describes the task: ### Input: Create a dict from any object with all attributes, but not the ones starting with an underscore _ Useful for objects or function that return an object that have no __dict__ attribute, like psutil functions. ### Response: def safe_dict(obj_or_func...
def transform_expression_columns(df, fn=np.log2, prefix='Intensity '): """ Apply transformation to expression columns. Default is log2 transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return: """ df = df.copy(...
Apply transformation to expression columns. Default is log2 transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return:
Below is the the instruction that describes the task: ### Input: Apply transformation to expression columns. Default is log2 transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return: ### Response: def transform_expression...
def read_metrics_file(path: str) -> List[Dict[str, Any]]: """ Reads lines metrics file and returns list of mappings of key and values. :param path: File to read metric values from. :return: Dictionary of metric names (e.g. perplexity-train) mapping to a list of values. """ with open(path) as fi...
Reads lines metrics file and returns list of mappings of key and values. :param path: File to read metric values from. :return: Dictionary of metric names (e.g. perplexity-train) mapping to a list of values.
Below is the the instruction that describes the task: ### Input: Reads lines metrics file and returns list of mappings of key and values. :param path: File to read metric values from. :return: Dictionary of metric names (e.g. perplexity-train) mapping to a list of values. ### Response: def read_metrics_fi...
def add_listener(self, include_value=False, item_added_func=None, item_removed_func=None): """ Adds an item listener for this queue. Listener will be notified for all queue add/remove events. :param include_value: (bool), whether received events include the updated item or not (optional). ...
Adds an item listener for this queue. Listener will be notified for all queue add/remove events. :param include_value: (bool), whether received events include the updated item or not (optional). :param item_added_func: Function to be called when an item is added to this set (optional). :param i...
Below is the the instruction that describes the task: ### Input: Adds an item listener for this queue. Listener will be notified for all queue add/remove events. :param include_value: (bool), whether received events include the updated item or not (optional). :param item_added_func: Function to be ...
async def emit(self, record: LogRecord): # type: ignore """ Emit a record. Output the record to the file, catering for rollover as described in `do_rollover`. """ try: if self.should_rollover(record): async with self._rollover_lock: ...
Emit a record. Output the record to the file, catering for rollover as described in `do_rollover`.
Below is the the instruction that describes the task: ### Input: Emit a record. Output the record to the file, catering for rollover as described in `do_rollover`. ### Response: async def emit(self, record: LogRecord): # type: ignore """ Emit a record. Output the record t...
def profiler(self): """Creates a dictionary from the profile scheme(s)""" logging.info('Loading profiles') # Initialise variables profiledata = defaultdict(make_dict) reverse_profiledata = dict() profileset = set() # Find all the unique profiles to use with a set ...
Creates a dictionary from the profile scheme(s)
Below is the the instruction that describes the task: ### Input: Creates a dictionary from the profile scheme(s) ### Response: def profiler(self): """Creates a dictionary from the profile scheme(s)""" logging.info('Loading profiles') # Initialise variables profiledata = defaultdict(...
def get_qi_name(self, qi_type, band='B00', data_format=MimeType.GML): """ :param qi_type: type of quality indicator :type qi_type: str :param band: band name :type band: str :param data_format: format of the file :type data_format: MimeType :return: name o...
:param qi_type: type of quality indicator :type qi_type: str :param band: band name :type band: str :param data_format: format of the file :type data_format: MimeType :return: name of gml file :rtype: str
Below is the the instruction that describes the task: ### Input: :param qi_type: type of quality indicator :type qi_type: str :param band: band name :type band: str :param data_format: format of the file :type data_format: MimeType :return: name of gml file :r...
def set_headline(self, level, message, timestamp=None, now_reference=None): """Set the persistent headline message for this service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents timestamp (float): An option...
Set the persistent headline message for this service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents timestamp (float): An optional monotonic value in seconds for when the message was created now_referenc...
Below is the the instruction that describes the task: ### Input: Set the persistent headline message for this service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents timestamp (float): An optional monotonic value...
def out_interactions_iter(self, nbunch=None, t=None): """Return an iterator over the out interactions present in a given snapshot. Edges are returned as tuples in the order (node, neighbor). Parameters ---------- nbunch : iterable container, optional (default= all nodes...
Return an iterator over the out interactions present in a given snapshot. Edges are returned as tuples in the order (node, neighbor). Parameters ---------- nbunch : iterable container, optional (default= all nodes) A container of nodes. The container will be iterat...
Below is the the instruction that describes the task: ### Input: Return an iterator over the out interactions present in a given snapshot. Edges are returned as tuples in the order (node, neighbor). Parameters ---------- nbunch : iterable container, optional (default= all n...
def _AddVolume(self, volume): """Adds a volume. Args: volume (Volume): a volume. Raises: KeyError: if volume is already set for the corresponding volume identifier. """ if volume.identifier in self._volumes: raise KeyError( 'Volume object already set for volum...
Adds a volume. Args: volume (Volume): a volume. Raises: KeyError: if volume is already set for the corresponding volume identifier.
Below is the the instruction that describes the task: ### Input: Adds a volume. Args: volume (Volume): a volume. Raises: KeyError: if volume is already set for the corresponding volume identifier. ### Response: def _AddVolume(self, volume): """Adds a volume. Args: vol...
def finish_target(self, name): """Finishes progress bar for a specified target.""" # We have to write a msg about finished target with self._lock: pbar = self._bar(name, 100, 100) if sys.stdout.isatty(): self.clearln() self._print(pbar) ...
Finishes progress bar for a specified target.
Below is the the instruction that describes the task: ### Input: Finishes progress bar for a specified target. ### Response: def finish_target(self, name): """Finishes progress bar for a specified target.""" # We have to write a msg about finished target with self._lock: pbar = ...
def su(self) -> 'Gate': """Convert gate tensor to the special unitary group.""" rank = 2**self.qubit_nb U = asarray(self.asoperator()) U /= np.linalg.det(U) ** (1/rank) return Gate(tensor=U, qubits=self.qubits)
Convert gate tensor to the special unitary group.
Below is the the instruction that describes the task: ### Input: Convert gate tensor to the special unitary group. ### Response: def su(self) -> 'Gate': """Convert gate tensor to the special unitary group.""" rank = 2**self.qubit_nb U = asarray(self.asoperator()) U /= np.linalg.det(...
def to_etree(source, root_tag=None): """ Convert various representations of an XML structure to a etree Element Args: source -- The source object to be converted - ET.Element\ElementTree, dict or string. Keyword args: root_tag -- A optional parent tag in which to wrap the x...
Convert various representations of an XML structure to a etree Element Args: source -- The source object to be converted - ET.Element\ElementTree, dict or string. Keyword args: root_tag -- A optional parent tag in which to wrap the xml tree if no root in dict representation. ...
Below is the the instruction that describes the task: ### Input: Convert various representations of an XML structure to a etree Element Args: source -- The source object to be converted - ET.Element\ElementTree, dict or string. Keyword args: root_tag -- A optional parent ta...
def _add_call_item_to_queue(pending_work_items, running_work_items, work_ids, call_queue): """Fills call_queue with _WorkItems from pending_work_items. This function never blocks. Args: pending_work_items: A dict m...
Fills call_queue with _WorkItems from pending_work_items. This function never blocks. Args: pending_work_items: A dict mapping work ids to _WorkItems e.g. {5: <_WorkItem...>, 6: <_WorkItem...>, ...} work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids a...
Below is the the instruction that describes the task: ### Input: Fills call_queue with _WorkItems from pending_work_items. This function never blocks. Args: pending_work_items: A dict mapping work ids to _WorkItems e.g. {5: <_WorkItem...>, 6: <_WorkItem...>, ...} work_ids: A qu...
def start(self): """Start the Consumers. :return: """ if not self.connection: self.create_connection() while True: try: channel = self.connection.channel() channel.queue.declare('simple_queue') channel.basic...
Start the Consumers. :return:
Below is the the instruction that describes the task: ### Input: Start the Consumers. :return: ### Response: def start(self): """Start the Consumers. :return: """ if not self.connection: self.create_connection() while True: try: ...
def add_resource_permissions(*args, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ # for each of our content types for resource in find_api_classes('v1_api', ModelResource): auth = resource._meta.authorization content_type = ContentType.object...
This syncdb hooks takes care of adding a view permission too all our content types.
Below is the the instruction that describes the task: ### Input: This syncdb hooks takes care of adding a view permission too all our content types. ### Response: def add_resource_permissions(*args, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ ...
def plot_dry_adiabats(self, p=None, theta=None, **kwargs): r'''Plot dry adiabats. Adds dry adiabats (lines of constant potential temperature) to the plot. The default style of these lines is dashed red lines with an alpha value of 0.5. These can be overridden using keyword arguments. ...
r'''Plot dry adiabats. Adds dry adiabats (lines of constant potential temperature) to the plot. The default style of these lines is dashed red lines with an alpha value of 0.5. These can be overridden using keyword arguments. Parameters ---------- p : array_like, option...
Below is the the instruction that describes the task: ### Input: r'''Plot dry adiabats. Adds dry adiabats (lines of constant potential temperature) to the plot. The default style of these lines is dashed red lines with an alpha value of 0.5. These can be overridden using keyword arguments. ...
def _backup_dir_item(self, dir_path, process_bar): """ Backup one dir item :param dir_path: filesystem_walk.DirEntryPath() instance """ self.path_helper.set_src_filepath(dir_path) if self.path_helper.abs_src_filepath is None: self.total_errored_items += 1 ...
Backup one dir item :param dir_path: filesystem_walk.DirEntryPath() instance
Below is the the instruction that describes the task: ### Input: Backup one dir item :param dir_path: filesystem_walk.DirEntryPath() instance ### Response: def _backup_dir_item(self, dir_path, process_bar): """ Backup one dir item :param dir_path: filesystem_walk.DirEntryPath() in...
async def run(self, wait_for_completion=True): """Run scene. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ activate_scene = ActivateScene( pyvlx=self.pyvlx, wait_for_comp...
Run scene. Parameters: * wait_for_completion: If set, function will return after device has reached target position.
Below is the the instruction that describes the task: ### Input: Run scene. Parameters: * wait_for_completion: If set, function will return after device has reached target position. ### Response: async def run(self, wait_for_completion=True): """Run scene. Para...
def listAllFiles (directory, suffix=None, abspath=False): """Returns the list of all files within the input directory and all subdirectories. """ files = [] directory = expandPath(directory) for dirpath, dirnames, filenames in os.walk(directory, followlinks=True): if suffix: ...
Returns the list of all files within the input directory and all subdirectories.
Below is the the instruction that describes the task: ### Input: Returns the list of all files within the input directory and all subdirectories. ### Response: def listAllFiles (directory, suffix=None, abspath=False): """Returns the list of all files within the input directory and all subdirectories. ...
def candles(self, pair, timeframe=None): """Return a queue containing all received candles data. :param pair: str, Symbol pair to request data for :param timeframe: str :return: Queue() """ timeframe = '1m' if not timeframe else timeframe key = ('candles', pair, ...
Return a queue containing all received candles data. :param pair: str, Symbol pair to request data for :param timeframe: str :return: Queue()
Below is the the instruction that describes the task: ### Input: Return a queue containing all received candles data. :param pair: str, Symbol pair to request data for :param timeframe: str :return: Queue() ### Response: def candles(self, pair, timeframe=None): """Return a queue co...
def item_from_topics(key, topics): """Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns: Single topic matching the key Raises: IndexError (int): With number of required arguments for t...
Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns: Single topic matching the key Raises: IndexError (int): With number of required arguments for the key
Below is the the instruction that describes the task: ### Input: Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns: Single topic matching the key Raises: IndexError (int): With number of required ...
def get_cimobject_header(obj): """ Return the value for the CIM-XML extension header field 'CIMObject', using the given object. This function implements the rules defined in DSP0200 section 6.3.7 "CIMObject". The format of the CIMObject value is similar but not identical to a local WBEM URI (on...
Return the value for the CIM-XML extension header field 'CIMObject', using the given object. This function implements the rules defined in DSP0200 section 6.3.7 "CIMObject". The format of the CIMObject value is similar but not identical to a local WBEM URI (one without namespace type and authority), as...
Below is the the instruction that describes the task: ### Input: Return the value for the CIM-XML extension header field 'CIMObject', using the given object. This function implements the rules defined in DSP0200 section 6.3.7 "CIMObject". The format of the CIMObject value is similar but not identical ...
def get_arr(self): """ Get the heatmap's array within the value range originally provided in ``__init__()``. The HeatmapsOnImage object saves heatmaps internally in the value range ``(min=0.0, max=1.0)``. This function converts the internal representation to ``(min=min_value, max=max_va...
Get the heatmap's array within the value range originally provided in ``__init__()``. The HeatmapsOnImage object saves heatmaps internally in the value range ``(min=0.0, max=1.0)``. This function converts the internal representation to ``(min=min_value, max=max_value)``, where ``min_value`` and...
Below is the the instruction that describes the task: ### Input: Get the heatmap's array within the value range originally provided in ``__init__()``. The HeatmapsOnImage object saves heatmaps internally in the value range ``(min=0.0, max=1.0)``. This function converts the internal representation t...
def iris_investigate(self, domains=None, data_updated_after=None, expiration_date=None, create_date=None, active=None, **kwargs): """Returns back a list of domains based on the provided filters. The following filters are available beyond what is parameterized as kwargs: ...
Returns back a list of domains based on the provided filters. The following filters are available beyond what is parameterized as kwargs: - ip: Search for domains having this IP. - email: Search for domains with this email in their data. - email_domain: Search for domains wh...
Below is the the instruction that describes the task: ### Input: Returns back a list of domains based on the provided filters. The following filters are available beyond what is parameterized as kwargs: - ip: Search for domains having this IP. - email: Search for domains with this e...
def receive(self): """ receive the next PDU from the watchman service If the client has activated subscriptions or logs then this PDU may be a unilateral PDU sent by the service to inform the client of a log event or subscription change. It may also simply be the response porti...
receive the next PDU from the watchman service If the client has activated subscriptions or logs then this PDU may be a unilateral PDU sent by the service to inform the client of a log event or subscription change. It may also simply be the response portion of a request initiat...
Below is the the instruction that describes the task: ### Input: receive the next PDU from the watchman service If the client has activated subscriptions or logs then this PDU may be a unilateral PDU sent by the service to inform the client of a log event or subscription change. It...
def get_icon_for(self, brain_or_object): """Get the navigation portlet icon for the brain or object The cache key ensures that the lookup is done only once per domain name """ portal_types = api.get_tool("portal_types") fti = portal_types.getTypeInfo(api.get_portal_type(brain_or...
Get the navigation portlet icon for the brain or object The cache key ensures that the lookup is done only once per domain name
Below is the the instruction that describes the task: ### Input: Get the navigation portlet icon for the brain or object The cache key ensures that the lookup is done only once per domain name ### Response: def get_icon_for(self, brain_or_object): """Get the navigation portlet icon for the brain o...
async def get_ltd_product(session, slug=None, url=None): """Get the product resource (JSON document) from the LSST the Docs API. Parameters ---------- session : `aiohttp.ClientSession` Your application's aiohttp client session. See http://aiohttp.readthedocs.io/en/stable/client.html. ...
Get the product resource (JSON document) from the LSST the Docs API. Parameters ---------- session : `aiohttp.ClientSession` Your application's aiohttp client session. See http://aiohttp.readthedocs.io/en/stable/client.html. slug : `str`, optional Slug identfying the product. Th...
Below is the the instruction that describes the task: ### Input: Get the product resource (JSON document) from the LSST the Docs API. Parameters ---------- session : `aiohttp.ClientSession` Your application's aiohttp client session. See http://aiohttp.readthedocs.io/en/stable/client.htm...
def count(self, weighted=True): """Return numberic count of rows considered for cube response.""" return self._measures.weighted_n if weighted else self._measures.unweighted_n
Return numberic count of rows considered for cube response.
Below is the the instruction that describes the task: ### Input: Return numberic count of rows considered for cube response. ### Response: def count(self, weighted=True): """Return numberic count of rows considered for cube response.""" return self._measures.weighted_n if weighted else self._measur...
def _add_generate_sub_commands(self): """ Sub commands for generating models for usage by clients. Currently supports Google Closure. """ gen_parser = self._subparsers_handle.add_parser( name="gen", help="generate client side model stubs, filters" ...
Sub commands for generating models for usage by clients. Currently supports Google Closure.
Below is the the instruction that describes the task: ### Input: Sub commands for generating models for usage by clients. Currently supports Google Closure. ### Response: def _add_generate_sub_commands(self): """ Sub commands for generating models for usage by clients. Currently sup...
def report_up(self, service, port): """ Report the given service's present node as up by creating/updating its respective znode in Zookeeper and setting the znode's data to the serialized representation of the node. Waits for zookeeper to be connected before taking any action. ...
Report the given service's present node as up by creating/updating its respective znode in Zookeeper and setting the znode's data to the serialized representation of the node. Waits for zookeeper to be connected before taking any action.
Below is the the instruction that describes the task: ### Input: Report the given service's present node as up by creating/updating its respective znode in Zookeeper and setting the znode's data to the serialized representation of the node. Waits for zookeeper to be connected before taking ...
def get_starsep_RaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg): """Calculate separation.""" sep = deltaStarsRaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg) sgn, deg, mn, sec = degToDms(sep) if deg != 0: txt = '%02d:%02d:%06.3f' % (deg, mn, sec) else: txt = '%02d:%06.3f' % (mn, sec) ...
Calculate separation.
Below is the the instruction that describes the task: ### Input: Calculate separation. ### Response: def get_starsep_RaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg): """Calculate separation.""" sep = deltaStarsRaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg) sgn, deg, mn, sec = degToDms(sep) if deg !=...
def html_for_env_var(key): """Returns an HTML snippet for an environment variable. Args: key: A string representing an environment variable name. Returns: String HTML representing the value and variable. """ value = os.getenv(key) return KEY_VALUE_TEMPLATE.format(key, value)
Returns an HTML snippet for an environment variable. Args: key: A string representing an environment variable name. Returns: String HTML representing the value and variable.
Below is the the instruction that describes the task: ### Input: Returns an HTML snippet for an environment variable. Args: key: A string representing an environment variable name. Returns: String HTML representing the value and variable. ### Response: def html_for_env_var(key): """Re...
def randomDecimalField(self, model_class, field_name): """ Validate if the field has a `max_digits` and `decimal_places` And generating the unique decimal number. """ decimal_field = model_class._meta.get_field(field_name) max_digits = None decimal_places = None ...
Validate if the field has a `max_digits` and `decimal_places` And generating the unique decimal number.
Below is the the instruction that describes the task: ### Input: Validate if the field has a `max_digits` and `decimal_places` And generating the unique decimal number. ### Response: def randomDecimalField(self, model_class, field_name): """ Validate if the field has a `max_digits` and `dec...
def bandpass(self, frequency, width_q=2.0, constant_skirt=False): '''Apply a two-pole Butterworth band-pass filter with the given central frequency, and (3dB-point) band-width. The filter rolls off at 6dB per octave (20dB per decade) and is described in detail in http://musicdsp.org/file...
Apply a two-pole Butterworth band-pass filter with the given central frequency, and (3dB-point) band-width. The filter rolls off at 6dB per octave (20dB per decade) and is described in detail in http://musicdsp.org/files/Audio-EQ-Cookbook.txt Parameters ---------- freque...
Below is the the instruction that describes the task: ### Input: Apply a two-pole Butterworth band-pass filter with the given central frequency, and (3dB-point) band-width. The filter rolls off at 6dB per octave (20dB per decade) and is described in detail in http://musicdsp.org/files/Audio-...
def cursor_position_col(self): """ Current column. (0-based.) """ # (Don't use self.text_before_cursor to calculate this. Creating # substrings and doing rsplit is too expensive for getting the cursor # position.) _, line_start_index = self._find_line_start_index(...
Current column. (0-based.)
Below is the the instruction that describes the task: ### Input: Current column. (0-based.) ### Response: def cursor_position_col(self): """ Current column. (0-based.) """ # (Don't use self.text_before_cursor to calculate this. Creating # substrings and doing rsplit is too e...
def to_dict(self): """Pack the load averages into a nicely-keyed dictionary.""" result = {} for meta in self.intervals.values(): result[meta.display] = meta.value return result
Pack the load averages into a nicely-keyed dictionary.
Below is the the instruction that describes the task: ### Input: Pack the load averages into a nicely-keyed dictionary. ### Response: def to_dict(self): """Pack the load averages into a nicely-keyed dictionary.""" result = {} for meta in self.intervals.values(): result[meta.disp...
def replace_data(self, chart_data): """ Use the categories and series values in the |ChartData| object *chart_data* to replace those in the XML and Excel worksheet for this chart. """ rewriter = SeriesXmlRewriterFactory(self.chart_type, chart_data) rewriter.replac...
Use the categories and series values in the |ChartData| object *chart_data* to replace those in the XML and Excel worksheet for this chart.
Below is the the instruction that describes the task: ### Input: Use the categories and series values in the |ChartData| object *chart_data* to replace those in the XML and Excel worksheet for this chart. ### Response: def replace_data(self, chart_data): """ Use the categories and s...
def convertafield(field_comm, field_val, field_iddname): """convert field based on field info in IDD""" convinidd = ConvInIDD() field_typ = field_comm.get('type', [None])[0] conv = convinidd.conv_dict().get(field_typ, convinidd.no_type) return conv(field_val, field_iddname)
convert field based on field info in IDD
Below is the the instruction that describes the task: ### Input: convert field based on field info in IDD ### Response: def convertafield(field_comm, field_val, field_iddname): """convert field based on field info in IDD""" convinidd = ConvInIDD() field_typ = field_comm.get('type', [None])[0] c...
def split(pipe, splitter, skip_empty=False): ''' this function works a lot like groupby but splits on given patterns, the same behavior as str.split provides. if skip_empty is True, split only yields pieces that have contents Example: splitting 1011101010101 by ...
this function works a lot like groupby but splits on given patterns, the same behavior as str.split provides. if skip_empty is True, split only yields pieces that have contents Example: splitting 1011101010101 by 10 returns ,11,,,,1 Or if s...
Below is the the instruction that describes the task: ### Input: this function works a lot like groupby but splits on given patterns, the same behavior as str.split provides. if skip_empty is True, split only yields pieces that have contents Example: splitting 1011101010101 ...
def get_retained_chimeras(output_fp_de_novo_nonchimeras, output_fp_ref_nonchimeras, output_combined_fp, chimeras_retention='union'): """ Gets union or intersection of two supplied fasta files output_fp_de_novo_nonchimeras: filepath o...
Gets union or intersection of two supplied fasta files output_fp_de_novo_nonchimeras: filepath of nonchimeras from de novo usearch detection. output_fp_ref_nonchimeras: filepath of nonchimeras from reference based usearch detection. output_combined_fp: filepath to write retained sequences to. ...
Below is the the instruction that describes the task: ### Input: Gets union or intersection of two supplied fasta files output_fp_de_novo_nonchimeras: filepath of nonchimeras from de novo usearch detection. output_fp_ref_nonchimeras: filepath of nonchimeras from reference based usearch detection....
def iterators(self, frequency=None): """ Returns the iterators (i.e. subject_id, visit_id) that the pipeline iterates over Parameters ---------- frequency : str | None A selected data frequency to use to determine which iterators are required. If ...
Returns the iterators (i.e. subject_id, visit_id) that the pipeline iterates over Parameters ---------- frequency : str | None A selected data frequency to use to determine which iterators are required. If None, all input frequencies of the pipeline are ...
Below is the the instruction that describes the task: ### Input: Returns the iterators (i.e. subject_id, visit_id) that the pipeline iterates over Parameters ---------- frequency : str | None A selected data frequency to use to determine which iterators are r...
def vcfmeltsamples(table, *samples): """ Melt the samples columns. E.g.:: >>> import petl as etl >>> # activate bio extensions ... import petlx.bio >>> table1 = ( ... etl ... .fromvcf('fixture/sample.vcf') ... .vcfmeltsamples() ......
Melt the samples columns. E.g.:: >>> import petl as etl >>> # activate bio extensions ... import petlx.bio >>> table1 = ( ... etl ... .fromvcf('fixture/sample.vcf') ... .vcfmeltsamples() ... ) >>> table1 +-------+-----+----...
Below is the the instruction that describes the task: ### Input: Melt the samples columns. E.g.:: >>> import petl as etl >>> # activate bio extensions ... import petlx.bio >>> table1 = ( ... etl ... .fromvcf('fixture/sample.vcf') ... .vcfmelts...
def djfrontend_jquery_scrollto(version=None): """ Returns the jQuery ScrollTo plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file. """ if version is None: version = getattr(settings, 'DJFRONTEND_JQUERY_SCROLLTO', DJFRONTEND_JQUERY_SCROLL...
Returns the jQuery ScrollTo plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file.
Below is the the instruction that describes the task: ### Input: Returns the jQuery ScrollTo plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file. ### Response: def djfrontend_jquery_scrollto(version=None): """ Returns the jQuery ScrollTo plugin fil...