code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def translate_to_zipkin(self, span_datas): """Translate the opencensus spans to zipkin spans. :type span_datas: list of :class: `~opencensus.trace.span_data.SpanData` :param span_datas: SpanData tuples to emit :rtype: list :returns: List of zipkin format...
Translate the opencensus spans to zipkin spans. :type span_datas: list of :class: `~opencensus.trace.span_data.SpanData` :param span_datas: SpanData tuples to emit :rtype: list :returns: List of zipkin format spans.
Below is the the instruction that describes the task: ### Input: Translate the opencensus spans to zipkin spans. :type span_datas: list of :class: `~opencensus.trace.span_data.SpanData` :param span_datas: SpanData tuples to emit :rtype: list :returns: List o...
def _fixPe(self): """ Fixes the necessary fields in the PE file instance in order to create a valid PE32. i.e. SizeOfImage. """ sizeOfImage = 0 for sh in self.sectionHeaders: sizeOfImage += sh.misc self.ntHeaders.optionaHeader.sizeoOfImage.value = self._sectio...
Fixes the necessary fields in the PE file instance in order to create a valid PE32. i.e. SizeOfImage.
Below is the the instruction that describes the task: ### Input: Fixes the necessary fields in the PE file instance in order to create a valid PE32. i.e. SizeOfImage. ### Response: def _fixPe(self): """ Fixes the necessary fields in the PE file instance in order to create a valid PE32. i.e. SizeOfI...
def to_html(self, classes=None, notebook=False, border=None): """ Render a DataFrame to a html table. Parameters ---------- classes : str or list-like classes to include in the `class` attribute of the opening ``<table>`` tag, in addition to the default "...
Render a DataFrame to a html table. Parameters ---------- classes : str or list-like classes to include in the `class` attribute of the opening ``<table>`` tag, in addition to the default "dataframe". notebook : {True, False}, optional, default False ...
Below is the the instruction that describes the task: ### Input: Render a DataFrame to a html table. Parameters ---------- classes : str or list-like classes to include in the `class` attribute of the opening ``<table>`` tag, in addition to the default "dataframe". ...
def parse_FASTA_files(options, fasta_file_contents): ''' This function iterates through each filepath in fasta_file_contents and returns a dict mapping (pdbid, chain, file_name) tuples to sequences: - options is the OptionParser member; - fasta_file_contents is a map from input filenames to the ...
This function iterates through each filepath in fasta_file_contents and returns a dict mapping (pdbid, chain, file_name) tuples to sequences: - options is the OptionParser member; - fasta_file_contents is a map from input filenames to the associated FASTA file contents.
Below is the the instruction that describes the task: ### Input: This function iterates through each filepath in fasta_file_contents and returns a dict mapping (pdbid, chain, file_name) tuples to sequences: - options is the OptionParser member; - fasta_file_contents is a map from input filenames...
def dem_url_dia(dt_day='2015-06-22'): """Obtiene las urls de descarga de los datos de demanda energética de un día concreto.""" def _url_tipo_dato(str_dia, k): url = SERVER + '/archives/{}/download_json?locale=es'.format(D_TIPOS_REQ_DEM[k]) if type(str_dia) is str: return url + '&da...
Obtiene las urls de descarga de los datos de demanda energética de un día concreto.
Below is the the instruction that describes the task: ### Input: Obtiene las urls de descarga de los datos de demanda energética de un día concreto. ### Response: def dem_url_dia(dt_day='2015-06-22'): """Obtiene las urls de descarga de los datos de demanda energética de un día concreto.""" def _url_tipo_d...
def is_topology(self, layers=None): ''' valid the topology ''' if layers is None: layers = self.layers layers_nodle = [] result = [] for i, layer in enumerate(layers): if layer.is_delete is False: layers_nodle.append(i) ...
valid the topology
Below is the the instruction that describes the task: ### Input: valid the topology ### Response: def is_topology(self, layers=None): ''' valid the topology ''' if layers is None: layers = self.layers layers_nodle = [] result = [] for i, layer in ...
def close(self) -> None: """ Closes the connection. """ if self.transport is not None and not self.transport.is_closing(): self.transport.close() if self._connect_lock.locked(): self._connect_lock.release() self.protocol = None self.trans...
Closes the connection.
Below is the the instruction that describes the task: ### Input: Closes the connection. ### Response: def close(self) -> None: """ Closes the connection. """ if self.transport is not None and not self.transport.is_closing(): self.transport.close() if self._conne...
def _complex_dtype(dtype): """Patched version of :func:`sporco.linalg.complex_dtype`.""" dt = cp.dtype(dtype) if dt == cp.dtype('float128'): return cp.dtype('complex256') elif dt == cp.dtype('float64'): return cp.dtype('complex128') else: return cp.dtype('complex64')
Patched version of :func:`sporco.linalg.complex_dtype`.
Below is the the instruction that describes the task: ### Input: Patched version of :func:`sporco.linalg.complex_dtype`. ### Response: def _complex_dtype(dtype): """Patched version of :func:`sporco.linalg.complex_dtype`.""" dt = cp.dtype(dtype) if dt == cp.dtype('float128'): return cp.dtype('c...
def tcp_reassembly(packet, *, count=NotImplemented): """Store data for TCP reassembly.""" if 'TCP' in packet: ip = packet['IP'] if 'IP' in packet else packet['IPv6'] tcp = packet['TCP'] data = dict( bufid=( ipaddress.ip_address(ip.src), # source IP addre...
Store data for TCP reassembly.
Below is the the instruction that describes the task: ### Input: Store data for TCP reassembly. ### Response: def tcp_reassembly(packet, *, count=NotImplemented): """Store data for TCP reassembly.""" if 'TCP' in packet: ip = packet['IP'] if 'IP' in packet else packet['IPv6'] tcp = packet['T...
def ramp(time, slope, start, finish=0): """ Implements vensim's and xmile's RAMP function Parameters ---------- time: function The current time of modelling slope: float The slope of the ramp starting at zero at time start start: float Time at which the ramp begins ...
Implements vensim's and xmile's RAMP function Parameters ---------- time: function The current time of modelling slope: float The slope of the ramp starting at zero at time start start: float Time at which the ramp begins finish: float Optional. Time at which the...
Below is the the instruction that describes the task: ### Input: Implements vensim's and xmile's RAMP function Parameters ---------- time: function The current time of modelling slope: float The slope of the ramp starting at zero at time start start: float Time at which ...
def addbr(name): ''' Create new bridge with the given name ''' fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name) return Bridge(name)
Create new bridge with the given name
Below is the the instruction that describes the task: ### Input: Create new bridge with the given name ### Response: def addbr(name): ''' Create new bridge with the given name ''' fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name) return Bridge(name)
def attach_volume(volume_id, instance_id, device, region=None, key=None, keyid=None, profile=None): ''' Attach an EBS volume to an EC2 instance. .. volume_id (string) – The ID of the EBS volume to be attached. instance_id (string) – The ID of the EC2 instance to at...
Attach an EBS volume to an EC2 instance. .. volume_id (string) – The ID of the EBS volume to be attached. instance_id (string) – The ID of the EC2 instance to attach the volume to. device (string) – The device on the instance through which the volume is exposed (e.g. /dev/sdh) ...
Below is the the instruction that describes the task: ### Input: Attach an EBS volume to an EC2 instance. .. volume_id (string) – The ID of the EBS volume to be attached. instance_id (string) – The ID of the EC2 instance to attach the volume to. device (string) – The device ...
def read_html(io, match='.+', flavor=None, header=None, index_col=None, skiprows=None, attrs=None, parse_dates=False, tupleize_cols=None, thousands=',', encoding=None, decimal='.', converters=None, na_values=None, keep_default_na=True, displayed_only=True): r"...
r"""Read HTML tables into a ``list`` of ``DataFrame`` objects. Parameters ---------- io : str or file-like A URL, a file-like object, or a raw string containing HTML. Note that lxml only accepts the http, ftp and file url protocols. If you have a URL that starts with ``'https'`` you...
Below is the the instruction that describes the task: ### Input: r"""Read HTML tables into a ``list`` of ``DataFrame`` objects. Parameters ---------- io : str or file-like A URL, a file-like object, or a raw string containing HTML. Note that lxml only accepts the http, ftp and file url ...
def get_top_referrers(self): """ :calls: `GET /repos/:owner/:repo/traffic/popular/referrers <https://developer.github.com/v3/repos/traffic/>`_ :rtype: :class:`list` of :class:`github.Referrer.Referrer` """ headers, data = self._requester.requestJsonAndCheck( "GET", ...
:calls: `GET /repos/:owner/:repo/traffic/popular/referrers <https://developer.github.com/v3/repos/traffic/>`_ :rtype: :class:`list` of :class:`github.Referrer.Referrer`
Below is the the instruction that describes the task: ### Input: :calls: `GET /repos/:owner/:repo/traffic/popular/referrers <https://developer.github.com/v3/repos/traffic/>`_ :rtype: :class:`list` of :class:`github.Referrer.Referrer` ### Response: def get_top_referrers(self): """ :calls: `G...
def strip_xml_declaration(file_or_xml): """ Removes XML declaration line from file or string passed in. If file_or_xml is not a file or string, it is returned as is. """ xml_content = _xml_content_to_string(file_or_xml) if not isinstance(xml_content, string_types): return xml_content ...
Removes XML declaration line from file or string passed in. If file_or_xml is not a file or string, it is returned as is.
Below is the the instruction that describes the task: ### Input: Removes XML declaration line from file or string passed in. If file_or_xml is not a file or string, it is returned as is. ### Response: def strip_xml_declaration(file_or_xml): """ Removes XML declaration line from file or string passed in...
def process(self, candidates): """ :arg list candidates: list of Candidates :returns: list of Candidates where score is at least min_score, if and only if one or more Candidates have at least min_score. Otherwise, returns original list of Candidates. "...
:arg list candidates: list of Candidates :returns: list of Candidates where score is at least min_score, if and only if one or more Candidates have at least min_score. Otherwise, returns original list of Candidates.
Below is the the instruction that describes the task: ### Input: :arg list candidates: list of Candidates :returns: list of Candidates where score is at least min_score, if and only if one or more Candidates have at least min_score. Otherwise, returns original list of Can...
def save_npz_dict(save_list=None, name='model.npz', sess=None): """Input parameters and the file name, save parameters as a dictionary into .npz file. Use ``tl.files.load_and_assign_npz_dict()`` to restore. Parameters ---------- save_list : list of parameters A list of parameters (tensor) ...
Input parameters and the file name, save parameters as a dictionary into .npz file. Use ``tl.files.load_and_assign_npz_dict()`` to restore. Parameters ---------- save_list : list of parameters A list of parameters (tensor) to be saved. name : str The name of the `.npz` file. se...
Below is the the instruction that describes the task: ### Input: Input parameters and the file name, save parameters as a dictionary into .npz file. Use ``tl.files.load_and_assign_npz_dict()`` to restore. Parameters ---------- save_list : list of parameters A list of parameters (tensor) to...
def check_weather(self): ''' Query the configured/queried station and return the weather data ''' if self.station_id is None: # Failed to get the nearest station ID when first launched, so # retry it. self.get_station_id() self.data['update_er...
Query the configured/queried station and return the weather data
Below is the the instruction that describes the task: ### Input: Query the configured/queried station and return the weather data ### Response: def check_weather(self): ''' Query the configured/queried station and return the weather data ''' if self.station_id is None: #...
def check_url_accessibility(url, timeout=10): ''' Check whether the URL accessible and returns HTTP 200 OK or not if not raises ValidationError ''' if(url=='localhost'): url = 'http://127.0.0.1' try: req = urllib2.urlopen(url, timeout=timeout) if (req.getcode()==20...
Check whether the URL accessible and returns HTTP 200 OK or not if not raises ValidationError
Below is the the instruction that describes the task: ### Input: Check whether the URL accessible and returns HTTP 200 OK or not if not raises ValidationError ### Response: def check_url_accessibility(url, timeout=10): ''' Check whether the URL accessible and returns HTTP 200 OK or not if no...
def get_ssl_context(private_key, certificate): """Get ssl context from private key and certificate paths. The return value is used when calling Flask. i.e. app.run(ssl_context=get_ssl_context(,,,)) """ if ( certificate and os.path.isfile(certificate) and private_key a...
Get ssl context from private key and certificate paths. The return value is used when calling Flask. i.e. app.run(ssl_context=get_ssl_context(,,,))
Below is the the instruction that describes the task: ### Input: Get ssl context from private key and certificate paths. The return value is used when calling Flask. i.e. app.run(ssl_context=get_ssl_context(,,,)) ### Response: def get_ssl_context(private_key, certificate): """Get ssl context from priva...
def mode_to_str(mode): """ Converts a tf.estimator.ModeKeys in a nice readable string. :param mode: The mdoe as a tf.estimator.ModeKeys :return: A human readable string representing the mode. """ if mode == tf.estimator.ModeKeys.TRAIN: return "train" if mode == tf.estimator.ModeKeys....
Converts a tf.estimator.ModeKeys in a nice readable string. :param mode: The mdoe as a tf.estimator.ModeKeys :return: A human readable string representing the mode.
Below is the the instruction that describes the task: ### Input: Converts a tf.estimator.ModeKeys in a nice readable string. :param mode: The mdoe as a tf.estimator.ModeKeys :return: A human readable string representing the mode. ### Response: def mode_to_str(mode): """ Converts a tf.estimator.Mode...
def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True
Suspend a server
Below is the the instruction that describes the task: ### Input: Suspend a server ### Response: def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True
def _process_ssh_rsa(self, data): """Parses ssh-rsa public keys.""" current_position, raw_e = self._unpack_by_int(data, 0) current_position, raw_n = self._unpack_by_int(data, current_position) unpacked_e = self._parse_long(raw_e) unpacked_n = self._parse_long(raw_n) sel...
Parses ssh-rsa public keys.
Below is the the instruction that describes the task: ### Input: Parses ssh-rsa public keys. ### Response: def _process_ssh_rsa(self, data): """Parses ssh-rsa public keys.""" current_position, raw_e = self._unpack_by_int(data, 0) current_position, raw_n = self._unpack_by_int(data, current_p...
def convert_tokens_to_ids(self, tokens): """Converts a sequence of tokens into ids using the vocab.""" ids = [] for token in tokens: ids.append(self.vocab[token]) if len(ids) > self.max_len: logger.warning( "Token indices sequence length is longer ...
Converts a sequence of tokens into ids using the vocab.
Below is the the instruction that describes the task: ### Input: Converts a sequence of tokens into ids using the vocab. ### Response: def convert_tokens_to_ids(self, tokens): """Converts a sequence of tokens into ids using the vocab.""" ids = [] for token in tokens: ids.append(...
def flip_alleles(genotypes): """Flip the alleles of an Genotypes instance.""" warnings.warn("deprecated: use 'Genotypes.flip_coded'", DeprecationWarning) genotypes.reference, genotypes.coded = (genotypes.coded, genotypes.reference) genotypes.genotypes = 2 - ge...
Flip the alleles of an Genotypes instance.
Below is the the instruction that describes the task: ### Input: Flip the alleles of an Genotypes instance. ### Response: def flip_alleles(genotypes): """Flip the alleles of an Genotypes instance.""" warnings.warn("deprecated: use 'Genotypes.flip_coded'", DeprecationWarning) genotypes.reference, genoty...
def _bg(self, coro: coroutine) -> asyncio.Task: """Run coro in background, log errors""" async def runner(): try: await coro except: self._log.exception("async: Coroutine raised exception") return asyncio.ensure_future(runner())
Run coro in background, log errors
Below is the the instruction that describes the task: ### Input: Run coro in background, log errors ### Response: def _bg(self, coro: coroutine) -> asyncio.Task: """Run coro in background, log errors""" async def runner(): try: await coro except: ...
def match_planted(fk_candidate_observations, match_filename, bright_limit=BRIGHT_LIMIT, object_planted=OBJECT_PLANTED, minimum_bright_detections=MINIMUM_BRIGHT_DETECTIONS, bright_fraction=MINIMUM_BRIGHT_FRACTION): """ Using the fk_candidate_observations as input get the Object.planted file fro...
Using the fk_candidate_observations as input get the Object.planted file from VOSpace and match planted sources with found sources. The Object.planted list is pulled from VOSpace based on the standard file-layout and name of the first exposure as read from the .astrom file. :param fk_candidate_observa...
Below is the the instruction that describes the task: ### Input: Using the fk_candidate_observations as input get the Object.planted file from VOSpace and match planted sources with found sources. The Object.planted list is pulled from VOSpace based on the standard file-layout and name of the first exp...
def databunch(self, path:PathOrStr=None, bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False, **kwargs)->'DataBunch': "Create an `DataBunch` fro...
Create an `DataBunch` from self, `path` will override `self.path`, `kwargs` are passed to `DataBunch.create`.
Below is the the instruction that describes the task: ### Input: Create an `DataBunch` from self, `path` will override `self.path`, `kwargs` are passed to `DataBunch.create`. ### Response: def databunch(self, path:PathOrStr=None, bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:...
def get_api_service(self, name=None): """Returns the specific service config definition""" try: svc = self.services_by_name.get(name, None) if svc is None: raise ValueError(f"Couldn't find the API service configuration") return svc except: # N...
Returns the specific service config definition
Below is the the instruction that describes the task: ### Input: Returns the specific service config definition ### Response: def get_api_service(self, name=None): """Returns the specific service config definition""" try: svc = self.services_by_name.get(name, None) if svc is...
def _make_path(self, items): '''Returns a relative path for the given dictionary of items. Uses this url rule's url pattern and replaces instances of <var_name> with the appropriate value from the items dict. ''' for key, val in items.items(): if not isinstance(val, ...
Returns a relative path for the given dictionary of items. Uses this url rule's url pattern and replaces instances of <var_name> with the appropriate value from the items dict.
Below is the the instruction that describes the task: ### Input: Returns a relative path for the given dictionary of items. Uses this url rule's url pattern and replaces instances of <var_name> with the appropriate value from the items dict. ### Response: def _make_path(self, items): '''Re...
def graphql_query(self, query_hash: str, variables: Dict[str, Any], referer: Optional[str] = None, rhx_gis: Optional[str] = None) -> Dict[str, Any]: """ Do a GraphQL Query. :param query_hash: Query identifying hash. :param variables: Variables for the Query. ...
Do a GraphQL Query. :param query_hash: Query identifying hash. :param variables: Variables for the Query. :param referer: HTTP Referer, or None. :param rhx_gis: 'rhx_gis' variable as somewhere returned by Instagram, needed to 'sign' request :return: The server's response diction...
Below is the the instruction that describes the task: ### Input: Do a GraphQL Query. :param query_hash: Query identifying hash. :param variables: Variables for the Query. :param referer: HTTP Referer, or None. :param rhx_gis: 'rhx_gis' variable as somewhere returned by Instagram, ne...
def save_current_figure_as(self): """Save the currently selected figure.""" if self.current_thumbnail is not None: self.save_figure_as(self.current_thumbnail.canvas.fig, self.current_thumbnail.canvas.fmt)
Save the currently selected figure.
Below is the the instruction that describes the task: ### Input: Save the currently selected figure. ### Response: def save_current_figure_as(self): """Save the currently selected figure.""" if self.current_thumbnail is not None: self.save_figure_as(self.current_thumbnail.canvas.fig, ...
def attribute( self, attr_type, attr_value, displayed=False, source=None, unique=True, formatter=None ): """Return instance of Attribute unique: * False - Attribute type:value can be duplicated. * Type - Attribute type has to be unique (e.g., only 1 Description Attri...
Return instance of Attribute unique: * False - Attribute type:value can be duplicated. * Type - Attribute type has to be unique (e.g., only 1 Description Attribute). * True - Attribute type:value combo must be unique. Args: attr_type (str): The ThreatCon...
Below is the the instruction that describes the task: ### Input: Return instance of Attribute unique: * False - Attribute type:value can be duplicated. * Type - Attribute type has to be unique (e.g., only 1 Description Attribute). * True - Attribute type:value combo must...
def add(self, name, value, bitmask=DEFMASK): """Add an enum member Args: name: Name of the member value: value of the member bitmask: bitmask. Only use if enum is a bitfield. """ _add_enum_member(self._eid, name, value, bitmask)
Add an enum member Args: name: Name of the member value: value of the member bitmask: bitmask. Only use if enum is a bitfield.
Below is the the instruction that describes the task: ### Input: Add an enum member Args: name: Name of the member value: value of the member bitmask: bitmask. Only use if enum is a bitfield. ### Response: def add(self, name, value, bitmask=DEFMASK): """Add an e...
def layers_intersect(layer_a, layer_b): """Check if extents of two layers intersect. :param layer_a: One of the two layers to test overlapping :type layer_a: QgsMapLayer :param layer_b: The second of the two layers to test overlapping :type layer_b: QgsMapLayer :returns: true if the layers in...
Check if extents of two layers intersect. :param layer_a: One of the two layers to test overlapping :type layer_a: QgsMapLayer :param layer_b: The second of the two layers to test overlapping :type layer_b: QgsMapLayer :returns: true if the layers intersect, false if they are disjoint :rtype:...
Below is the the instruction that describes the task: ### Input: Check if extents of two layers intersect. :param layer_a: One of the two layers to test overlapping :type layer_a: QgsMapLayer :param layer_b: The second of the two layers to test overlapping :type layer_b: QgsMapLayer :returns:...
def service_registry(self, sr): """ Sets service registry object in context, doesn't check it Args: sr: EFServiceRegistry object """ if type(sr) is not EFServiceRegistry: raise TypeError("sr value must be type 'EFServiceRegistry'") self._service_registry = sr
Sets service registry object in context, doesn't check it Args: sr: EFServiceRegistry object
Below is the the instruction that describes the task: ### Input: Sets service registry object in context, doesn't check it Args: sr: EFServiceRegistry object ### Response: def service_registry(self, sr): """ Sets service registry object in context, doesn't check it Args: sr: EFServiceRe...
def butter_lowpass_filter(data, sample_rate, cutoff=10, order=4, plot=False): """ `Low-pass filter <http://stackoverflow.com/questions/25191620/ creating-lowpass-filter-in-scipy-understanding-methods-and-units>`_ data by the [order]th order zero lag Butterworth filter whose cut frequency is ...
`Low-pass filter <http://stackoverflow.com/questions/25191620/ creating-lowpass-filter-in-scipy-understanding-methods-and-units>`_ data by the [order]th order zero lag Butterworth filter whose cut frequency is set to [cutoff] Hz. :param data: time-series data, :type data: numpy array of...
Below is the the instruction that describes the task: ### Input: `Low-pass filter <http://stackoverflow.com/questions/25191620/ creating-lowpass-filter-in-scipy-understanding-methods-and-units>`_ data by the [order]th order zero lag Butterworth filter whose cut frequency is set to [cutoff] Hz. ...
def fetch(TableName,M,I,numin,numax,ParameterGroups=[],Parameters=[]): """ INPUT PARAMETERS: TableName: local table name to fetch in (required) M: HITRAN molecule number (required) I: HITRAN isotopologue number (required) numin: lower wavenumb...
INPUT PARAMETERS: TableName: local table name to fetch in (required) M: HITRAN molecule number (required) I: HITRAN isotopologue number (required) numin: lower wavenumber bound (required) numax: upper wavenumber bound (requir...
Below is the the instruction that describes the task: ### Input: INPUT PARAMETERS: TableName: local table name to fetch in (required) M: HITRAN molecule number (required) I: HITRAN isotopologue number (required) numin: lower wavenumber bound ...
def _create_context_jar(self, compile_context): """Jar up the compile_context to its output jar location. TODO(stuhood): In the medium term, we hope to add compiler support for this step, which would allow the jars to be used as compile _inputs_ as well. Currently using jar'd compile outputs as compile...
Jar up the compile_context to its output jar location. TODO(stuhood): In the medium term, we hope to add compiler support for this step, which would allow the jars to be used as compile _inputs_ as well. Currently using jar'd compile outputs as compile inputs would make the compiler's analysis useless. ...
Below is the the instruction that describes the task: ### Input: Jar up the compile_context to its output jar location. TODO(stuhood): In the medium term, we hope to add compiler support for this step, which would allow the jars to be used as compile _inputs_ as well. Currently using jar'd compile outputs ...
def _validate_color(self, color): """Validates color, raising error if invalid.""" three_digit_pattern = compile("^[a-f0-9]{3}$") six_digit_pattern = compile("^[a-f0-9]{6}$") if not match(three_digit_pattern, color)\ and not match(six_digit_pattern, color): ...
Validates color, raising error if invalid.
Below is the the instruction that describes the task: ### Input: Validates color, raising error if invalid. ### Response: def _validate_color(self, color): """Validates color, raising error if invalid.""" three_digit_pattern = compile("^[a-f0-9]{3}$") six_digit_pattern = compile("^[a-f0-9]...
def count_lines(path, extensions=None, excluded_dirnames=None): """Return number of source code lines for all filenames in subdirectories of *path* with names ending with *extensions* Directory names *excluded_dirnames* will be ignored""" if extensions is None: extensions = ['.py', '.pyw', ...
Return number of source code lines for all filenames in subdirectories of *path* with names ending with *extensions* Directory names *excluded_dirnames* will be ignored
Below is the the instruction that describes the task: ### Input: Return number of source code lines for all filenames in subdirectories of *path* with names ending with *extensions* Directory names *excluded_dirnames* will be ignored ### Response: def count_lines(path, extensions=None, excluded_dirnames=...
def longest_increasing_subsequence(sequence): """ Dynamic Programming Algorithm for counting the length of longest increasing subsequence type sequence: List[int] """ length = len(sequence) counts = [1 for _ in range(length)] for i in range(1, length): for j in range(0, i): ...
Dynamic Programming Algorithm for counting the length of longest increasing subsequence type sequence: List[int]
Below is the the instruction that describes the task: ### Input: Dynamic Programming Algorithm for counting the length of longest increasing subsequence type sequence: List[int] ### Response: def longest_increasing_subsequence(sequence): """ Dynamic Programming Algorithm for counting the length...
def naverage(wave, indep_min=None, indep_max=None): r""" Return the numerical average of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integer or float ...
r""" Return the numerical average of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of c...
Below is the the instruction that describes the task: ### Input: r""" Return the numerical average of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param indep_min: Independent vector start point of computation :type indep_min: integ...
def _identify_eds_ing(first, second): """Find nodes connecting adjacent edges. Args: first(Edge): Edge object representing the first edge. second(Edge): Edge object representing the second edge. Returns: tuple[int, int, set[int]]: The first two values repres...
Find nodes connecting adjacent edges. Args: first(Edge): Edge object representing the first edge. second(Edge): Edge object representing the second edge. Returns: tuple[int, int, set[int]]: The first two values represent left and right node indicies ...
Below is the the instruction that describes the task: ### Input: Find nodes connecting adjacent edges. Args: first(Edge): Edge object representing the first edge. second(Edge): Edge object representing the second edge. Returns: tuple[int, int, set[int]]: The fir...
def logging_auditlog_clss_clss(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-ras") auditlog = ET.SubElement(logging, "auditlog") clss = ET.SubElement(auditlog, "clas...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def logging_auditlog_clss_clss(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-...
def save(self, refreshing=None, next_action=None, json_last_refresh=None, data_blob=None): """ save or update the component on the Ariane server cache :param refreshing: the new refreshing value - default None and ignored :param next_action: the new next action - default None and ignored...
save or update the component on the Ariane server cache :param refreshing: the new refreshing value - default None and ignored :param next_action: the new next action - default None and ignored :param json_last_refresh: the new json last refresh - default the date of this call :param dat...
Below is the the instruction that describes the task: ### Input: save or update the component on the Ariane server cache :param refreshing: the new refreshing value - default None and ignored :param next_action: the new next action - default None and ignored :param json_last_refresh: the new...
def set_contents_from_file(self, fp, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None, res_upload_handler=None, size=None): """ Store an object in GS using the name of the Key object as the key in GS and the conte...
Store an object in GS using the name of the Key object as the key in GS and the contents of the file pointed to by 'fp' as the contents. :type fp: file :param fp: the file whose contents are to be uploaded :type headers: dict :param headers: additional HTTP headers to b...
Below is the the instruction that describes the task: ### Input: Store an object in GS using the name of the Key object as the key in GS and the contents of the file pointed to by 'fp' as the contents. :type fp: file :param fp: the file whose contents are to be uploaded :ty...
def single(a, b, distance_function): """ Given two collections ``a`` and ``b``, this will return the distance of the points which are closest together. ``distance_function`` is used to determine the distance between two elements. Example:: >>> single([1, 2], [3, 4], lambda x, y: abs(x-y))...
Given two collections ``a`` and ``b``, this will return the distance of the points which are closest together. ``distance_function`` is used to determine the distance between two elements. Example:: >>> single([1, 2], [3, 4], lambda x, y: abs(x-y)) 1 # (distance between 2 and 3)
Below is the the instruction that describes the task: ### Input: Given two collections ``a`` and ``b``, this will return the distance of the points which are closest together. ``distance_function`` is used to determine the distance between two elements. Example:: >>> single([1, 2], [3, 4], la...
def put_file(self, key, file, ttl_secs=None): """Like :meth:`~simplekv.KeyValueStore.put_file`, but with an additional parameter: :param ttl_secs: Number of seconds until the key expires. See above for valid values. :raises exceptions.ValueError: If ...
Like :meth:`~simplekv.KeyValueStore.put_file`, but with an additional parameter: :param ttl_secs: Number of seconds until the key expires. See above for valid values. :raises exceptions.ValueError: If ``ttl_secs`` is invalid.
Below is the the instruction that describes the task: ### Input: Like :meth:`~simplekv.KeyValueStore.put_file`, but with an additional parameter: :param ttl_secs: Number of seconds until the key expires. See above for valid values. :raises exceptions.Val...
def loads(self, param): ''' Checks the return parameters generating new proxy instances to avoid query concurrences from shared proxies and creating proxies for actors from another host. ''' if isinstance(param, ProxyRef): try: return self.look...
Checks the return parameters generating new proxy instances to avoid query concurrences from shared proxies and creating proxies for actors from another host.
Below is the the instruction that describes the task: ### Input: Checks the return parameters generating new proxy instances to avoid query concurrences from shared proxies and creating proxies for actors from another host. ### Response: def loads(self, param): ''' Checks the return...
def encode_data(self): """Encode the data back into a dict.""" output_data = {} output_data["groupTypeList"] = encode_array(self.group_type_list, 4, 0) output_data["xCoordList"] = encode_array(self.x_coord_list, 10, 1000) output_data["yCoordList"] = encode_array(self.y_coord_list...
Encode the data back into a dict.
Below is the the instruction that describes the task: ### Input: Encode the data back into a dict. ### Response: def encode_data(self): """Encode the data back into a dict.""" output_data = {} output_data["groupTypeList"] = encode_array(self.group_type_list, 4, 0) output_data["xCoor...
def json_doc_to_xml(json_obj, lang='en', custom_namespace=None): """Converts a Open511 JSON document to XML. lang: the appropriate language code Takes a dict deserialized from JSON, returns an lxml Element. Accepts only the full root-level JSON object from an Open511 response.""" if 'meta' not in...
Converts a Open511 JSON document to XML. lang: the appropriate language code Takes a dict deserialized from JSON, returns an lxml Element. Accepts only the full root-level JSON object from an Open511 response.
Below is the the instruction that describes the task: ### Input: Converts a Open511 JSON document to XML. lang: the appropriate language code Takes a dict deserialized from JSON, returns an lxml Element. Accepts only the full root-level JSON object from an Open511 response. ### Response: def json_do...
def get_ccle_mutations(gene_list, cell_lines, mutation_type=None): """Return a dict of mutations in given genes and cell lines from CCLE. This is a specialized call to get_mutations tailored to CCLE cell lines. Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get ...
Return a dict of mutations in given genes and cell lines from CCLE. This is a specialized call to get_mutations tailored to CCLE cell lines. Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get mutations in cell_lines : list[str] A list of CCLE cell line n...
Below is the the instruction that describes the task: ### Input: Return a dict of mutations in given genes and cell lines from CCLE. This is a specialized call to get_mutations tailored to CCLE cell lines. Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get mutat...
def create_attribute_model(self, initial_value=None): # type: (Any) -> AttributeModel """Make an AttributeModel instance of the correct type for this Meta Args: initial_value: The initial value the Attribute should take Returns: AttributeModel: The created attri...
Make an AttributeModel instance of the correct type for this Meta Args: initial_value: The initial value the Attribute should take Returns: AttributeModel: The created attribute model instance
Below is the the instruction that describes the task: ### Input: Make an AttributeModel instance of the correct type for this Meta Args: initial_value: The initial value the Attribute should take Returns: AttributeModel: The created attribute model instance ### Response: d...
def hsl_to_rgb(h, s, l): """Convert a color in h, s, l to a color in r, g, b""" h /= 360 s /= 100 l /= 100 m2 = l * (s + 1) if l <= .5 else l + s - l * s m1 = 2 * l - m2 def h_to_rgb(h): h = h % 1 if 6 * h < 1: return m1 + 6 * h * (m2 - m1) if 2 * h < 1:...
Convert a color in h, s, l to a color in r, g, b
Below is the the instruction that describes the task: ### Input: Convert a color in h, s, l to a color in r, g, b ### Response: def hsl_to_rgb(h, s, l): """Convert a color in h, s, l to a color in r, g, b""" h /= 360 s /= 100 l /= 100 m2 = l * (s + 1) if l <= .5 else l + s - l * s m1 = 2 *...
def _createReservoir(self, linkResult, replaceParamFile): """ Create GSSHAPY Reservoir Objects Method """ # Extract header variables from link result object header = linkResult['header'] # Cases if linkResult['type'] == 'LAKE': # Lake handler ...
Create GSSHAPY Reservoir Objects Method
Below is the the instruction that describes the task: ### Input: Create GSSHAPY Reservoir Objects Method ### Response: def _createReservoir(self, linkResult, replaceParamFile): """ Create GSSHAPY Reservoir Objects Method """ # Extract header variables from link result object ...
def plot_shape(gdf, fc='#cbe0f0', ec='#999999', linewidth=1, alpha=1, figsize=(6,6), margin=0.02, axis_off=True): """ Plot a GeoDataFrame of place boundary geometries. Parameters ---------- gdf : GeoDataFrame the gdf containing the geometries to plot fc : string or list ...
Plot a GeoDataFrame of place boundary geometries. Parameters ---------- gdf : GeoDataFrame the gdf containing the geometries to plot fc : string or list the facecolor (or list of facecolors) for the polygons ec : string or list the edgecolor (or list of edgecolors) for the p...
Below is the the instruction that describes the task: ### Input: Plot a GeoDataFrame of place boundary geometries. Parameters ---------- gdf : GeoDataFrame the gdf containing the geometries to plot fc : string or list the facecolor (or list of facecolors) for the polygons ec : s...
def create_v4_signature(self, request_params): ''' Create URI and signature headers based on AWS V4 signing process. Refer to https://docs.aws.amazon.com/AlexaWebInfoService/latest/ApiReferenceArticle.html for request params. :param request_params: dictionary of request parameters ...
Create URI and signature headers based on AWS V4 signing process. Refer to https://docs.aws.amazon.com/AlexaWebInfoService/latest/ApiReferenceArticle.html for request params. :param request_params: dictionary of request parameters :return: URL and header to be passed to requests.get
Below is the the instruction that describes the task: ### Input: Create URI and signature headers based on AWS V4 signing process. Refer to https://docs.aws.amazon.com/AlexaWebInfoService/latest/ApiReferenceArticle.html for request params. :param request_params: dictionary of request parameters ...
def _setupCache(self): """ Setup the cache based on the provided values for localCacheDir. """ # we first check whether the cache directory exists. If it doesn't, create it. if not os.path.exists(self.localCacheDir): # Create a temporary directory as this worker's pri...
Setup the cache based on the provided values for localCacheDir.
Below is the the instruction that describes the task: ### Input: Setup the cache based on the provided values for localCacheDir. ### Response: def _setupCache(self): """ Setup the cache based on the provided values for localCacheDir. """ # we first check whether the cache directory ...
def strip_rst(docs): ''' Strip/replace reStructuredText directives in docstrings ''' for func, docstring in six.iteritems(docs): log.debug('Stripping docstring for %s', func) if not docstring: continue docstring_new = docstring if six.PY3 else salt.utils.data.encode(d...
Strip/replace reStructuredText directives in docstrings
Below is the the instruction that describes the task: ### Input: Strip/replace reStructuredText directives in docstrings ### Response: def strip_rst(docs): ''' Strip/replace reStructuredText directives in docstrings ''' for func, docstring in six.iteritems(docs): log.debug('Stripping docstr...
def render_tag(self, tag_func): """ Creates a tag using the decorated func as the render function for the template tag node. The render function takes two arguments - the template context and the tag token. """ @wraps(tag_func) def tag_wrapper(parser, token): ...
Creates a tag using the decorated func as the render function for the template tag node. The render function takes two arguments - the template context and the tag token.
Below is the the instruction that describes the task: ### Input: Creates a tag using the decorated func as the render function for the template tag node. The render function takes two arguments - the template context and the tag token. ### Response: def render_tag(self, tag_func): """ ...
def PublicIPs(self): """Returns PublicIPs object associated with the server. """ if not self.public_ips: self.public_ips = clc.v2.PublicIPs(server=self,public_ips_lst=self.ip_addresses,session=self.session) return(self.public_ips)
Returns PublicIPs object associated with the server.
Below is the the instruction that describes the task: ### Input: Returns PublicIPs object associated with the server. ### Response: def PublicIPs(self): """Returns PublicIPs object associated with the server. """ if not self.public_ips: self.public_ips = clc.v2.PublicIPs(server=self,public_ips_lst=self.ip_...
def _symbol_trades(self, symbols): ''' Query last_trade in parallel for multiple symbols and return in dict. symbols: list[str] return: dict[str -> polygon.Trade] ''' @skip_http_error((404, 504)) def fetch(symbol): return self._api.polygon.l...
Query last_trade in parallel for multiple symbols and return in dict. symbols: list[str] return: dict[str -> polygon.Trade]
Below is the the instruction that describes the task: ### Input: Query last_trade in parallel for multiple symbols and return in dict. symbols: list[str] return: dict[str -> polygon.Trade] ### Response: def _symbol_trades(self, symbols): ''' Query last_trade in parallel fo...
def calibrate(self, data, dsid): """Calibrate the data.""" tic = datetime.now() data15hdr = self.header['15_DATA_HEADER'] calibration = dsid.calibration channel = dsid.name # even though all the channels may not be present in the file, # the header does have cal...
Calibrate the data.
Below is the the instruction that describes the task: ### Input: Calibrate the data. ### Response: def calibrate(self, data, dsid): """Calibrate the data.""" tic = datetime.now() data15hdr = self.header['15_DATA_HEADER'] calibration = dsid.calibration channel = dsid.name ...
def show_vcs_output_vcs_nodes_vcs_node_info_node_hw_sync_state(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_vcs = ET.Element("show_vcs") config = show_vcs output = ET.SubElement(show_vcs, "output") vcs_nodes = ET.SubElement(output...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def show_vcs_output_vcs_nodes_vcs_node_info_node_hw_sync_state(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_vcs = ET.Element("show_vcs") confi...
def getSNPSetsList() : """Return the names of all imported snp sets""" import rabaDB.filters as rfilt f = rfilt.RabaQuery(SNPMaster) names = [] for g in f.iterRun() : names.append(g.setName) return names
Return the names of all imported snp sets
Below is the the instruction that describes the task: ### Input: Return the names of all imported snp sets ### Response: def getSNPSetsList() : """Return the names of all imported snp sets""" import rabaDB.filters as rfilt f = rfilt.RabaQuery(SNPMaster) names = [] for g in f.iterRun() : names.append(g.setNa...
def send_post(self, mri, method_name, **params): """Abstract method to dispatch a Post to the server Args: mri (str): The mri of the Block method_name (str): The name of the Method within the Block params: The parameters to send Returns: The retu...
Abstract method to dispatch a Post to the server Args: mri (str): The mri of the Block method_name (str): The name of the Method within the Block params: The parameters to send Returns: The return results from the server
Below is the the instruction that describes the task: ### Input: Abstract method to dispatch a Post to the server Args: mri (str): The mri of the Block method_name (str): The name of the Method within the Block params: The parameters to send Returns: ...
def _get_struct_glowfilter(self): """Get the values for the GLOWFILTER record.""" obj = _make_object("GlowFilter") obj.GlowColor = self._get_struct_rgba() obj.BlurX = unpack_fixed16(self._src) obj.BlurY = unpack_fixed16(self._src) obj.Strength = unpack_fixed8(self._src) ...
Get the values for the GLOWFILTER record.
Below is the the instruction that describes the task: ### Input: Get the values for the GLOWFILTER record. ### Response: def _get_struct_glowfilter(self): """Get the values for the GLOWFILTER record.""" obj = _make_object("GlowFilter") obj.GlowColor = self._get_struct_rgba() obj.Blu...
def load(file,encoding=None): """load(file,encoding=None) -> object This function reads a tnetstring from a file and parses it into a python object. The file must support the read() method, and this function promises not to read more data than necessary. """ # Read the length prefix one char ...
load(file,encoding=None) -> object This function reads a tnetstring from a file and parses it into a python object. The file must support the read() method, and this function promises not to read more data than necessary.
Below is the the instruction that describes the task: ### Input: load(file,encoding=None) -> object This function reads a tnetstring from a file and parses it into a python object. The file must support the read() method, and this function promises not to read more data than necessary. ### Response: ...
def parse_radl(data): """ Parse a RADL document in JSON. Args.: - data(str or list): document to parse. Return(RADL): RADL object. """ if not isinstance(data, list): if os.path.isfile(data): f = open(data) data = "".join(f.readlines()) f.close() ...
Parse a RADL document in JSON. Args.: - data(str or list): document to parse. Return(RADL): RADL object.
Below is the the instruction that describes the task: ### Input: Parse a RADL document in JSON. Args.: - data(str or list): document to parse. Return(RADL): RADL object. ### Response: def parse_radl(data): """ Parse a RADL document in JSON. Args.: - data(str or list): document to par...
def make_tree(data, rng_state, leaf_size=30, angular=False): """Construct a random projection tree based on ``data`` with leaves of size at most ``leaf_size``. Parameters ---------- data: array of shape (n_samples, n_features) The original data to be split rng_state: array of int64, shap...
Construct a random projection tree based on ``data`` with leaves of size at most ``leaf_size``. Parameters ---------- data: array of shape (n_samples, n_features) The original data to be split rng_state: array of int64, shape (3,) The internal state of the rng leaf_size: int (opt...
Below is the the instruction that describes the task: ### Input: Construct a random projection tree based on ``data`` with leaves of size at most ``leaf_size``. Parameters ---------- data: array of shape (n_samples, n_features) The original data to be split rng_state: array of int64, sha...
def start(self): """Start a thread to handle Vera blocked polling.""" self._poll_thread = threading.Thread(target=self._run_poll_server, name='Vera Poll Thread') self._poll_thread.deamon = True self._poll_thread.start()
Start a thread to handle Vera blocked polling.
Below is the the instruction that describes the task: ### Input: Start a thread to handle Vera blocked polling. ### Response: def start(self): """Start a thread to handle Vera blocked polling.""" self._poll_thread = threading.Thread(target=self._run_poll_server, ...
def http_post(url, data=None, opt=opt_default): """ Shortcut for urlopen (POST) + read. We'll probably want to add a nice timeout here later too. """ return _http_request(url, method='POST', data=_marshalled(data), opt=opt)
Shortcut for urlopen (POST) + read. We'll probably want to add a nice timeout here later too.
Below is the the instruction that describes the task: ### Input: Shortcut for urlopen (POST) + read. We'll probably want to add a nice timeout here later too. ### Response: def http_post(url, data=None, opt=opt_default): """ Shortcut for urlopen (POST) + read. We'll probably want to add a nice time...
def unbind(self, ticket, device_id, user_id): """ 解绑设备 详情请参考 https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7 :param ticket: 绑定操作合法性的凭证(由微信后台生成,第三方H5通过客户端jsapi获得) :param device_id: 设备id :param user_id: 用户对应的openid :return: 返回的 JSON 数据包 """...
解绑设备 详情请参考 https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7 :param ticket: 绑定操作合法性的凭证(由微信后台生成,第三方H5通过客户端jsapi获得) :param device_id: 设备id :param user_id: 用户对应的openid :return: 返回的 JSON 数据包
Below is the the instruction that describes the task: ### Input: 解绑设备 详情请参考 https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7 :param ticket: 绑定操作合法性的凭证(由微信后台生成,第三方H5通过客户端jsapi获得) :param device_id: 设备id :param user_id: 用户对应的openid :return: 返回的 JSON 数据包 ### Resp...
def replace(self, key, value): """ Replaces the entry for a key only if it is currently mapped to some value. This is equivalent to: >>> if map.contains_key(key): >>> return map.put(key,value) >>> else: >>> return None except that ...
Replaces the entry for a key only if it is currently mapped to some value. This is equivalent to: >>> if map.contains_key(key): >>> return map.put(key,value) >>> else: >>> return None except that the action is performed atomically. **Warn...
Below is the the instruction that describes the task: ### Input: Replaces the entry for a key only if it is currently mapped to some value. This is equivalent to: >>> if map.contains_key(key): >>> return map.put(key,value) >>> else: >>> return None ...
def read_py_url(url, errors='replace', skip_encoding_cookie=True): """Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are...
Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are the same as for bytes.decode(), but here 'replace' is the default. ...
Below is the the instruction that describes the task: ### Input: Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are the ...
def _ctypes_ex_assign(executable): """Return a list of code lines to allocate and assign the local parameter definitions that match those in the signature of the wrapped executable. """ result = [] for p in executable.ordered_parameters: _ctypes_code_parameter(result, p, "assign") if ty...
Return a list of code lines to allocate and assign the local parameter definitions that match those in the signature of the wrapped executable.
Below is the the instruction that describes the task: ### Input: Return a list of code lines to allocate and assign the local parameter definitions that match those in the signature of the wrapped executable. ### Response: def _ctypes_ex_assign(executable): """Return a list of code lines to allocate and as...
def open(self): """Open the connection with the device.""" try: self.device.open() except ConnectTimeoutError as cte: raise ConnectionException(cte.msg) self.device.timeout = self.timeout self.device._conn._session.transport.set_keepalive(self.keepalive) ...
Open the connection with the device.
Below is the the instruction that describes the task: ### Input: Open the connection with the device. ### Response: def open(self): """Open the connection with the device.""" try: self.device.open() except ConnectTimeoutError as cte: raise ConnectionException(cte.msg...
def _bnot32(ins): """ Negates top (Bitwise NOT) of the stack (32 bits in DEHL) """ output = _32bit_oper(ins.quad[2]) output.append('call __BNOT32') output.append('push de') output.append('push hl') REQUIRES.add('bnot32.asm') return output
Negates top (Bitwise NOT) of the stack (32 bits in DEHL)
Below is the the instruction that describes the task: ### Input: Negates top (Bitwise NOT) of the stack (32 bits in DEHL) ### Response: def _bnot32(ins): """ Negates top (Bitwise NOT) of the stack (32 bits in DEHL) """ output = _32bit_oper(ins.quad[2]) output.append('call __BNOT32') output.appe...
def _zscore(a): """ Calculating z-score of data on the first axis. If the numbers in any column are all equal, scipy.stats.zscore will return NaN for this column. We shall correct them all to be zeros. Parameters ---------- a: numpy array Returns ------- zscore: num...
Calculating z-score of data on the first axis. If the numbers in any column are all equal, scipy.stats.zscore will return NaN for this column. We shall correct them all to be zeros. Parameters ---------- a: numpy array Returns ------- zscore: numpy array The z-s...
Below is the the instruction that describes the task: ### Input: Calculating z-score of data on the first axis. If the numbers in any column are all equal, scipy.stats.zscore will return NaN for this column. We shall correct them all to be zeros. Parameters ---------- a: numpy a...
def to(self, to_emails, global_substitutions=None, is_multiple=False, p=0): """Adds To objects to the Personalization object :param to_emails: An To or list of To objects :type to_emails: To, list(To), str, tuple :param global_substitutions: A dict of substitutions for all recipients ...
Adds To objects to the Personalization object :param to_emails: An To or list of To objects :type to_emails: To, list(To), str, tuple :param global_substitutions: A dict of substitutions for all recipients :type global_substitutions: dict :param is_multiple: Create a new personi...
Below is the the instruction that describes the task: ### Input: Adds To objects to the Personalization object :param to_emails: An To or list of To objects :type to_emails: To, list(To), str, tuple :param global_substitutions: A dict of substitutions for all recipients :type global...
def login(self, account=None, app_account=None, flush=True): """ Log into the connected host using the best method available. If an account is not given, default to the account that was used during the last call to login(). If a previous call was not made, use the account that wa...
Log into the connected host using the best method available. If an account is not given, default to the account that was used during the last call to login(). If a previous call was not made, use the account that was passed to the constructor. If that also fails, raise a TypeError. ...
Below is the the instruction that describes the task: ### Input: Log into the connected host using the best method available. If an account is not given, default to the account that was used during the last call to login(). If a previous call was not made, use the account that was passed to ...
def send(self, timeout=None): """Returns an event or None if no events occur before timeout.""" if self.sigint_event and is_main_thread(): with ReplacedSigIntHandler(self.sigint_handler): return self._send(timeout) else: return self._send(timeout)
Returns an event or None if no events occur before timeout.
Below is the the instruction that describes the task: ### Input: Returns an event or None if no events occur before timeout. ### Response: def send(self, timeout=None): """Returns an event or None if no events occur before timeout.""" if self.sigint_event and is_main_thread(): with Repl...
def tmpdir(prefix='npythy_tempdir_', delete=True): ''' tmpdir() creates a temporary directory and yields its path. At python exit, the directory and all of its contents are recursively deleted (so long as the the normal python exit process is allowed to call the atexit handlers). tmpdir(prefix) ...
tmpdir() creates a temporary directory and yields its path. At python exit, the directory and all of its contents are recursively deleted (so long as the the normal python exit process is allowed to call the atexit handlers). tmpdir(prefix) uses the given prefix in the tempfile.mkdtemp() call. ...
Below is the the instruction that describes the task: ### Input: tmpdir() creates a temporary directory and yields its path. At python exit, the directory and all of its contents are recursively deleted (so long as the the normal python exit process is allowed to call the atexit handlers). tmpdir(pr...
def pinch(self, direction='in', percent=0.6, duration=2.0, dead_zone=0.1): """ Squeezing or expanding 2 fingers on this UI with given motion range and duration. Args: direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding ...
Squeezing or expanding 2 fingers on this UI with given motion range and duration. Args: direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding percent (:py:obj:`float`): squeezing range from or expanding range to of the bounds of the U...
Below is the the instruction that describes the task: ### Input: Squeezing or expanding 2 fingers on this UI with given motion range and duration. Args: direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding percent (:py:obj:`float...
def pack_lob_data(remaining_size, payload, row_header_start_pos, row_lobs): """ After parameter row has been written, append the lobs and update the corresponding lob headers with lob position and lob size: :param payload: payload object (io.BytesIO instance) :param row_header_st...
After parameter row has been written, append the lobs and update the corresponding lob headers with lob position and lob size: :param payload: payload object (io.BytesIO instance) :param row_header_start_pos: absolute position of start position of row within payload :param row_lobs: list...
Below is the the instruction that describes the task: ### Input: After parameter row has been written, append the lobs and update the corresponding lob headers with lob position and lob size: :param payload: payload object (io.BytesIO instance) :param row_header_start_pos: absolute position ...
def map(self, f_list: List[Callable[[np.ndarray], int]], axis: int = 0, chunksize: int = 1000, selection: np.ndarray = None) -> List[np.ndarray]: """ Apply a function along an axis without loading the entire dataset in memory. Args: f_list (list of func): Function(s) that takes a numpy ndarray as argument ...
Apply a function along an axis without loading the entire dataset in memory. Args: f_list (list of func): Function(s) that takes a numpy ndarray as argument axis (int): Axis along which to apply the function (0 = rows, 1 = columns) chunksize (int): Number of rows (columns) to load per chunk selectio...
Below is the the instruction that describes the task: ### Input: Apply a function along an axis without loading the entire dataset in memory. Args: f_list (list of func): Function(s) that takes a numpy ndarray as argument axis (int): Axis along which to apply the function (0 = rows, 1 = columns) chu...
def get_app_region_products(self, app_uri): """获得指定应用所在区域的产品信息 Args: - app_uri: 应用的完整标识 Returns: 返回产品信息列表,若失败则返回None """ apps, retInfo = self.list_apps() if apps is None: return None for app in apps: if (app.get('...
获得指定应用所在区域的产品信息 Args: - app_uri: 应用的完整标识 Returns: 返回产品信息列表,若失败则返回None
Below is the the instruction that describes the task: ### Input: 获得指定应用所在区域的产品信息 Args: - app_uri: 应用的完整标识 Returns: 返回产品信息列表,若失败则返回None ### Response: def get_app_region_products(self, app_uri): """获得指定应用所在区域的产品信息 Args: - app_uri: 应用的完整标识 ...
def _get_label_uuid(xapi, rectype, label): ''' Internal, returns label's uuid ''' try: return getattr(xapi, rectype).get_by_name_label(label)[0] except Exception: return False
Internal, returns label's uuid
Below is the the instruction that describes the task: ### Input: Internal, returns label's uuid ### Response: def _get_label_uuid(xapi, rectype, label): ''' Internal, returns label's uuid ''' try: return getattr(xapi, rectype).get_by_name_label(label)[0] except Exception: return...
def dict_str(dict_, **dictkw): r""" Makes a pretty printable / human-readable string representation of a dictionary. In most cases this string could be evaled. Args: dict_ (dict_): a dictionary Args: dict_ (dict_): a dictionary **dictkw: stritems, strkeys, strvals, nl, new...
r""" Makes a pretty printable / human-readable string representation of a dictionary. In most cases this string could be evaled. Args: dict_ (dict_): a dictionary Args: dict_ (dict_): a dictionary **dictkw: stritems, strkeys, strvals, nl, newlines, truncate, nobr, ...
Below is the the instruction that describes the task: ### Input: r""" Makes a pretty printable / human-readable string representation of a dictionary. In most cases this string could be evaled. Args: dict_ (dict_): a dictionary Args: dict_ (dict_): a dictionary **dictkw: s...
def matches(self, _filter): """ Returns whether the instance matches the given filter text. :param _filter: A regex filter. If it starts with `<identifier>:`, then the part before the colon will be used as an attribute and the part after will be a...
Returns whether the instance matches the given filter text. :param _filter: A regex filter. If it starts with `<identifier>:`, then the part before the colon will be used as an attribute and the part after will be applied to that attribute. :type _filter:...
Below is the the instruction that describes the task: ### Input: Returns whether the instance matches the given filter text. :param _filter: A regex filter. If it starts with `<identifier>:`, then the part before the colon will be used as an attribute and the...
def get_binding(self, schema, data): """ For a given schema, get a binding mediator providing links to the RDF terms matching that schema. """ schema = self.parent.get_schema(schema) return Binding(schema, self.parent.resolver, data=data)
For a given schema, get a binding mediator providing links to the RDF terms matching that schema.
Below is the the instruction that describes the task: ### Input: For a given schema, get a binding mediator providing links to the RDF terms matching that schema. ### Response: def get_binding(self, schema, data): """ For a given schema, get a binding mediator providing links to the RDF ter...
def set_s3_bucket(self, region, name, bucketName): """Sets the S3 bucket location for logfile delivery Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail bucketName (`str`): Name of the S3 bucket to deliver log files to R...
Sets the S3 bucket location for logfile delivery Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail bucketName (`str`): Name of the S3 bucket to deliver log files to Returns: `None`
Below is the the instruction that describes the task: ### Input: Sets the S3 bucket location for logfile delivery Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail bucketName (`str`): Name of the S3 bucket to deliver log files to ...
def _index_audio_ibm(self, basename=None, replace_already_indexed=False, continuous=True, model="en-US_BroadbandModel", word_confidence=True, word_alternatives_threshold=0.9, profanity_filter_for_US_results=False): """ Implements...
Implements a search-suitable interface for Watson speech API. Some explaination of the parameters here have been taken from [1]_ Parameters ---------- basename : str, optional A specific basename to be indexed and is placed in src_dir e.g `audio.wav`. ...
Below is the the instruction that describes the task: ### Input: Implements a search-suitable interface for Watson speech API. Some explaination of the parameters here have been taken from [1]_ Parameters ---------- basename : str, optional A specific basename to be ind...
def last_kstp_from_kper(hds,kper): """ function to find the last time step (kstp) for a give stress period (kper) in a modflow head save file. Parameters ---------- hds : flopy.utils.HeadFile kper : int the zero-index stress period number Returns ------- kstp : int ...
function to find the last time step (kstp) for a give stress period (kper) in a modflow head save file. Parameters ---------- hds : flopy.utils.HeadFile kper : int the zero-index stress period number Returns ------- kstp : int the zero-based last time step during stre...
Below is the the instruction that describes the task: ### Input: function to find the last time step (kstp) for a give stress period (kper) in a modflow head save file. Parameters ---------- hds : flopy.utils.HeadFile kper : int the zero-index stress period number Returns ---...
def write_if_allowed(filename: str, content: str, overwrite: bool = False, mock: bool = False) -> None: """ Writes the contents to a file, if permitted. Args: filename: filename to write content: contents to write overwr...
Writes the contents to a file, if permitted. Args: filename: filename to write content: contents to write overwrite: permit overwrites? mock: pretend to write, but don't Raises: RuntimeError: if file exists but overwriting not permitted
Below is the the instruction that describes the task: ### Input: Writes the contents to a file, if permitted. Args: filename: filename to write content: contents to write overwrite: permit overwrites? mock: pretend to write, but don't Raises: RuntimeError: if file e...
def appendGuideline(self, position=None, angle=None, name=None, color=None, guideline=None): """ Append a new guideline to the font. >>> guideline = font.appendGuideline((50, 0), 90) >>> guideline = font.appendGuideline((0, 540), 0, name="overshoot", >>> color=(0, 0,...
Append a new guideline to the font. >>> guideline = font.appendGuideline((50, 0), 90) >>> guideline = font.appendGuideline((0, 540), 0, name="overshoot", >>> color=(0, 0, 0, 0.2)) **position** must be a :ref:`type-coordinate` indicating the position of the guideline...
Below is the the instruction that describes the task: ### Input: Append a new guideline to the font. >>> guideline = font.appendGuideline((50, 0), 90) >>> guideline = font.appendGuideline((0, 540), 0, name="overshoot", >>> color=(0, 0, 0, 0.2)) **position** must be a :r...
def set_temperature(self, temp): """Set both the driver and passenger temperature to temp.""" temp = round(temp, 1) self.__manual_update_time = time.time() data = self._controller.command(self._id, 'set_temps', {"driver_temp": temp, ...
Set both the driver and passenger temperature to temp.
Below is the the instruction that describes the task: ### Input: Set both the driver and passenger temperature to temp. ### Response: def set_temperature(self, temp): """Set both the driver and passenger temperature to temp.""" temp = round(temp, 1) self.__manual_update_time = time.time() ...
def get_foreign_key_base_declaration_sql(self, foreign_key): """ Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint of a field declaration to be used in statements like CREATE TABLE. :param foreign_key: The foreign key :type foreign_key: ForeignKeyCo...
Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint of a field declaration to be used in statements like CREATE TABLE. :param foreign_key: The foreign key :type foreign_key: ForeignKeyConstraint :rtype: str
Below is the the instruction that describes the task: ### Input: Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint of a field declaration to be used in statements like CREATE TABLE. :param foreign_key: The foreign key :type foreign_key: ForeignKeyConstraint ...
def create_workspace(namespace, name, authorizationDomain="", attributes=None): """Create a new FireCloud Workspace. Args: namespace (str): project to which workspace belongs name (str): Workspace name protected (bool): If True, this workspace is protected by dbGaP credentia...
Create a new FireCloud Workspace. Args: namespace (str): project to which workspace belongs name (str): Workspace name protected (bool): If True, this workspace is protected by dbGaP credentials. This option is only available if your FireCloud account is linked to yo...
Below is the the instruction that describes the task: ### Input: Create a new FireCloud Workspace. Args: namespace (str): project to which workspace belongs name (str): Workspace name protected (bool): If True, this workspace is protected by dbGaP credentials. This option is...