code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _fbp_filter(norm_freq, filter_type, frequency_scaling): """Create a smoothing filter for FBP. Parameters ---------- norm_freq : `array-like` Frequencies normalized to lie in the interval [0, 1]. filter_type : {'Ram-Lak', 'Shepp-Logan', 'Cosine', 'Hamming', 'Hann', cal...
Create a smoothing filter for FBP. Parameters ---------- norm_freq : `array-like` Frequencies normalized to lie in the interval [0, 1]. filter_type : {'Ram-Lak', 'Shepp-Logan', 'Cosine', 'Hamming', 'Hann', callable} The type of filter to be used. If a string i...
Below is the the instruction that describes the task: ### Input: Create a smoothing filter for FBP. Parameters ---------- norm_freq : `array-like` Frequencies normalized to lie in the interval [0, 1]. filter_type : {'Ram-Lak', 'Shepp-Logan', 'Cosine', 'Hamming', 'Hann', c...
def _chunk_with_padding(self, iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # _chunk_with_padding('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)
Collect data into fixed-length chunks or blocks
Below is the the instruction that describes the task: ### Input: Collect data into fixed-length chunks or blocks ### Response: def _chunk_with_padding(self, iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # _chunk_with_padding('ABCDEFG', 3, 'x') --> ABC DEF Gxx" ...
def irfftn(a, s, axes=None): """ Compute the inverse of the multi-dimensional discrete Fourier transform for real input. This function is a wrapper for :func:`pyfftw.interfaces.numpy_fft.irfftn`, with an interface similar to that of :func:`numpy.fft.irfftn`. Parameters ---------- a : ar...
Compute the inverse of the multi-dimensional discrete Fourier transform for real input. This function is a wrapper for :func:`pyfftw.interfaces.numpy_fft.irfftn`, with an interface similar to that of :func:`numpy.fft.irfftn`. Parameters ---------- a : array_like Input array s : sequen...
Below is the the instruction that describes the task: ### Input: Compute the inverse of the multi-dimensional discrete Fourier transform for real input. This function is a wrapper for :func:`pyfftw.interfaces.numpy_fft.irfftn`, with an interface similar to that of :func:`numpy.fft.irfftn`. Paramete...
def _columns_to_kwargs(conversion_table, columns, row): """ Given a list of column names, and a list of values (a row), return a dict of kwargs that may be used to instantiate a MarketHistoryEntry or MarketOrder object. :param dict conversion_table: The conversion table to use for mapping s...
Given a list of column names, and a list of values (a row), return a dict of kwargs that may be used to instantiate a MarketHistoryEntry or MarketOrder object. :param dict conversion_table: The conversion table to use for mapping spec names to kwargs. :param list columns: A list of column names...
Below is the the instruction that describes the task: ### Input: Given a list of column names, and a list of values (a row), return a dict of kwargs that may be used to instantiate a MarketHistoryEntry or MarketOrder object. :param dict conversion_table: The conversion table to use for mapping ...
def evaluate(self, dataset): '''Evaluate the current model parameters on a dataset. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A set of data to use for evaluating the model. Returns ------- monitors : OrderedDict ...
Evaluate the current model parameters on a dataset. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A set of data to use for evaluating the model. Returns ------- monitors : OrderedDict A dictionary mapping monitor nam...
Below is the the instruction that describes the task: ### Input: Evaluate the current model parameters on a dataset. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A set of data to use for evaluating the model. Returns ------- ...
def form_valid(self, form): if self.__pk: obj = PurchasesAlbaran.objects.get(pk=self.__pk) self.request.albaran = obj form.instance.albaran = obj form.instance.validator_user = self.request.user raise Exception("revisar StorageBatch") """ bat...
batch = StorageBatch.objects.filter(pk=form.data['batch']).first() if not batch: errors = form._errors.setdefault("batch", ErrorList()) errors.append(_("Batch invalid")) return super(LineAlbaranCreate, self).form_invalid(form)
Below is the the instruction that describes the task: ### Input: batch = StorageBatch.objects.filter(pk=form.data['batch']).first() if not batch: errors = form._errors.setdefault("batch", ErrorList()) errors.append(_("Batch invalid")) return super(LineAlbaranCreate, self)...
def _jseq(self, cols, converter=None): """Return a JVM Seq of Columns from a list of Column or names""" return _to_seq(self.sql_ctx._sc, cols, converter)
Return a JVM Seq of Columns from a list of Column or names
Below is the the instruction that describes the task: ### Input: Return a JVM Seq of Columns from a list of Column or names ### Response: def _jseq(self, cols, converter=None): """Return a JVM Seq of Columns from a list of Column or names""" return _to_seq(self.sql_ctx._sc, cols, converter)
def broadcast(*sinks_): """The |broadcast| decorator creates a |push| object that receives a message by ``yield`` and then sends this message on to all the given sinks. .. |broadcast| replace:: :py:func:`broadcast` """ @push def bc(): sinks = [s() for s in sinks_] while True: ...
The |broadcast| decorator creates a |push| object that receives a message by ``yield`` and then sends this message on to all the given sinks. .. |broadcast| replace:: :py:func:`broadcast`
Below is the the instruction that describes the task: ### Input: The |broadcast| decorator creates a |push| object that receives a message by ``yield`` and then sends this message on to all the given sinks. .. |broadcast| replace:: :py:func:`broadcast` ### Response: def broadcast(*sinks_): """The |bro...
def main(): ''' Sets up command line parser for Toil/ADAM based k-mer counter, and launches k-mer counter with optional Spark cluster. ''' parser = argparse.ArgumentParser() # add parser arguments parser.add_argument('--input_path', help='The full path to the input ...
Sets up command line parser for Toil/ADAM based k-mer counter, and launches k-mer counter with optional Spark cluster.
Below is the the instruction that describes the task: ### Input: Sets up command line parser for Toil/ADAM based k-mer counter, and launches k-mer counter with optional Spark cluster. ### Response: def main(): ''' Sets up command line parser for Toil/ADAM based k-mer counter, and launches k-mer cou...
def _get_wheel_metadata_from_wheel( backend, metadata_directory, config_settings): """Build a wheel and extract the metadata from it. Fallback for when the build backend does not define the 'get_wheel_metadata' hook. """ from zipfile import ZipFile whl_basename = backend.build_wheel(met...
Build a wheel and extract the metadata from it. Fallback for when the build backend does not define the 'get_wheel_metadata' hook.
Below is the the instruction that describes the task: ### Input: Build a wheel and extract the metadata from it. Fallback for when the build backend does not define the 'get_wheel_metadata' hook. ### Response: def _get_wheel_metadata_from_wheel( backend, metadata_directory, config_settings): "...
def update(self): ''' Use primitive parameters to set basic objects. This is an extremely stripped-down version of update for CobbDouglasEconomy. Parameters ---------- none Returns ------- none ''' self.kSS = 1.0 self.MSS...
Use primitive parameters to set basic objects. This is an extremely stripped-down version of update for CobbDouglasEconomy. Parameters ---------- none Returns ------- none
Below is the the instruction that describes the task: ### Input: Use primitive parameters to set basic objects. This is an extremely stripped-down version of update for CobbDouglasEconomy. Parameters ---------- none Returns ------- none ### Response: def u...
def add_reference_context_args(parser): """ Extends an ArgumentParser instance with the following commandline arguments: --context-size """ reference_context_group = parser.add_argument_group("Reference Transcripts") parser.add_argument( "--context-size", default=CDNA_CONTEXT...
Extends an ArgumentParser instance with the following commandline arguments: --context-size
Below is the the instruction that describes the task: ### Input: Extends an ArgumentParser instance with the following commandline arguments: --context-size ### Response: def add_reference_context_args(parser): """ Extends an ArgumentParser instance with the following commandline arguments: ...
def instance(self, counter=None): """Returns all the information regarding a specific pipeline run See the `Go pipeline instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-pipeline-instance Args: counter (int): The pipeline instance to fetch. ...
Returns all the information regarding a specific pipeline run See the `Go pipeline instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-pipeline-instance Args: counter (int): The pipeline instance to fetch. If falsey returns the latest pipeline in...
Below is the the instruction that describes the task: ### Input: Returns all the information regarding a specific pipeline run See the `Go pipeline instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-pipeline-instance Args: counter (int): The pipeline in...
def sc_to_fc(spvec, nmax, mmax, nrows, ncols): """assume Ncols is even""" fdata = np.zeros([int(nrows), ncols], dtype=np.complex128) for k in xrange(0, int(ncols / 2)): if k < mmax: kk = k ind = mindx(kk, nmax, mmax) vec = spvec[ind:ind + nmax - np.abs(...
assume Ncols is even
Below is the the instruction that describes the task: ### Input: assume Ncols is even ### Response: def sc_to_fc(spvec, nmax, mmax, nrows, ncols): """assume Ncols is even""" fdata = np.zeros([int(nrows), ncols], dtype=np.complex128) for k in xrange(0, int(ncols / 2)): if k < mmax: ...
def format_header_cell(val): """ Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and all other '_' to spaces. """ return re.sub('_', ' ', re.sub(r'(_Px_)', '(', re.sub(r'(_xP_)', ')', str(val) )))
Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and all other '_' to spaces.
Below is the the instruction that describes the task: ### Input: Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and all other '_' to spaces. ### Response: def format_header_cell(val): """ Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' ...
def run(*args, **kwargs): """ Please dont use. Instead use `luigi` binary. Run from cmdline using argparse. :param use_dynamic_argparse: Deprecated and ignored """ luigi_run_result = _run(*args, **kwargs) return luigi_run_result if kwargs.get('detailed_summary') else luigi_run_result.sched...
Please dont use. Instead use `luigi` binary. Run from cmdline using argparse. :param use_dynamic_argparse: Deprecated and ignored
Below is the the instruction that describes the task: ### Input: Please dont use. Instead use `luigi` binary. Run from cmdline using argparse. :param use_dynamic_argparse: Deprecated and ignored ### Response: def run(*args, **kwargs): """ Please dont use. Instead use `luigi` binary. Run from...
def from_center(self, x=None, y=None, z=None, r=None, theta=None, h=None, reference=None): """ Accepts a set of (:x:, :y:, :z:) ratios for Cartesian or (:r:, :theta:, :h:) rations/angle for Polar and returns :Vector: using :reference: as origin """ coo...
Accepts a set of (:x:, :y:, :z:) ratios for Cartesian or (:r:, :theta:, :h:) rations/angle for Polar and returns :Vector: using :reference: as origin
Below is the the instruction that describes the task: ### Input: Accepts a set of (:x:, :y:, :z:) ratios for Cartesian or (:r:, :theta:, :h:) rations/angle for Polar and returns :Vector: using :reference: as origin ### Response: def from_center(self, x=None, y=None, z=None, r=None, ...
def _equivalent(self, char, prev, next, implicitA): """ Transliterate a Latin character equivalent to Devanagari. Add VIRAMA for ligatures. Convert standalone to dependent vowels. """ result = [] if char.isVowel == False: result.append(char.c...
Transliterate a Latin character equivalent to Devanagari. Add VIRAMA for ligatures. Convert standalone to dependent vowels.
Below is the the instruction that describes the task: ### Input: Transliterate a Latin character equivalent to Devanagari. Add VIRAMA for ligatures. Convert standalone to dependent vowels. ### Response: def _equivalent(self, char, prev, next, implicitA): """ Transliterate a Latin c...
def add_annotation_layer(self, annotation_file, layer_name): """ adds all markables from the given annotation layer to the discourse graph. """ assert os.path.isfile(annotation_file), \ "Annotation file doesn't exist: {}".format(annotation_file) tree = etree.p...
adds all markables from the given annotation layer to the discourse graph.
Below is the the instruction that describes the task: ### Input: adds all markables from the given annotation layer to the discourse graph. ### Response: def add_annotation_layer(self, annotation_file, layer_name): """ adds all markables from the given annotation layer to the discourse ...
def display_buffer(self, buffer, redraw=True): """ display provided buffer :param buffer: Buffer :return: """ logger.debug("display buffer %r", buffer) self.buffer_movement_history.append(buffer) self.current_buffer = buffer self._set_main_widget(...
display provided buffer :param buffer: Buffer :return:
Below is the the instruction that describes the task: ### Input: display provided buffer :param buffer: Buffer :return: ### Response: def display_buffer(self, buffer, redraw=True): """ display provided buffer :param buffer: Buffer :return: """ logge...
def visit_and_update_expressions(self, visitor_fn): """Create an updated version (if needed) of the Filter via the visitor pattern.""" new_predicate = self.predicate.visit_and_update(visitor_fn) if new_predicate is not self.predicate: return Filter(new_predicate) else: ...
Create an updated version (if needed) of the Filter via the visitor pattern.
Below is the the instruction that describes the task: ### Input: Create an updated version (if needed) of the Filter via the visitor pattern. ### Response: def visit_and_update_expressions(self, visitor_fn): """Create an updated version (if needed) of the Filter via the visitor pattern.""" new_pred...
def enterprise_login_required(view): """ View decorator for allowing authenticated user with valid enterprise UUID. This decorator requires enterprise identifier as a parameter `enterprise_uuid`. This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to the decorated view . ...
View decorator for allowing authenticated user with valid enterprise UUID. This decorator requires enterprise identifier as a parameter `enterprise_uuid`. This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to the decorated view . If there is no enterprise in database against ...
Below is the the instruction that describes the task: ### Input: View decorator for allowing authenticated user with valid enterprise UUID. This decorator requires enterprise identifier as a parameter `enterprise_uuid`. This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to the...
def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString): """Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default="("); can also be a pyparsing...
Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default="("); can also be a pyparsing expression - closer - closing character for a nested list (default=")"); can ...
Below is the the instruction that describes the task: ### Input: Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default="("); can also be a pyparsing expression ...
def get_extension(filepath, check_if_exists=False, allowed_exts=ALLOWED_EXTS): """Return the extension of fpath. Parameters ---------- fpath: string File name or path check_if_exists: bool allowed_exts: dict Dictionary of strings, where the key if the last part of a complex ('.' separ...
Return the extension of fpath. Parameters ---------- fpath: string File name or path check_if_exists: bool allowed_exts: dict Dictionary of strings, where the key if the last part of a complex ('.' separated) extension and the value is the previous part. For example: for the '.nii...
Below is the the instruction that describes the task: ### Input: Return the extension of fpath. Parameters ---------- fpath: string File name or path check_if_exists: bool allowed_exts: dict Dictionary of strings, where the key if the last part of a complex ('.' separated) extension ...
def process_results(self, paragraph): """Routes Zeppelin output types to corresponding handlers.""" if 'editorMode' in paragraph['config']: mode = paragraph['config']['editorMode'].split('/')[-1] if 'results' in paragraph and paragraph['results']['msg']: msg = par...
Routes Zeppelin output types to corresponding handlers.
Below is the the instruction that describes the task: ### Input: Routes Zeppelin output types to corresponding handlers. ### Response: def process_results(self, paragraph): """Routes Zeppelin output types to corresponding handlers.""" if 'editorMode' in paragraph['config']: mode = parag...
def container_running(self, container_name): """ Finds out if a container with name ``container_name`` is running. :return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise. :rtype: Optional[docker.models.container.Container] """ ...
Finds out if a container with name ``container_name`` is running. :return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise. :rtype: Optional[docker.models.container.Container]
Below is the the instruction that describes the task: ### Input: Finds out if a container with name ``container_name`` is running. :return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise. :rtype: Optional[docker.models.container.Container] ### Response: ...
def giflogo(self,id,title=None,scale=0.8,info_str=''): """ m.giflogo(id,title=None,scale=0.8) -- (Requires seqlogo package) Make a gif sequence logo """ return giflogo(self,id,title,scale)
m.giflogo(id,title=None,scale=0.8) -- (Requires seqlogo package) Make a gif sequence logo
Below is the the instruction that describes the task: ### Input: m.giflogo(id,title=None,scale=0.8) -- (Requires seqlogo package) Make a gif sequence logo ### Response: def giflogo(self,id,title=None,scale=0.8,info_str=''): """ m.giflogo(id,title=None,scale=0.8) -- (Requires seqlogo package) Make a...
def get_disease(self, disease_name=None, disease_id=None, definition=None, parent_ids=None, tree_numbers=None, parent_tree_numbers=None, slim_mapping=None, synonym=None, alt_disease_id=None, limit=None, as_df=False): """ Get diseases :param bool as_df: if...
Get diseases :param bool as_df: if set to True result returns as `pandas.DataFrame` :param int limit: maximum number of results :param str disease_name: disease name :param str disease_id: disease identifier :param str definition: definition of disease :param str parent_...
Below is the the instruction that describes the task: ### Input: Get diseases :param bool as_df: if set to True result returns as `pandas.DataFrame` :param int limit: maximum number of results :param str disease_name: disease name :param str disease_id: disease identifier :p...
def _shadow_model_variables(shadow_vars): """ Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``. Returns: list of (shadow_model_var, local_model_var) used for syncing. """ G = tf.get_default_graph() curr_shadow_vars = set(...
Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``. Returns: list of (shadow_model_var, local_model_var) used for syncing.
Below is the the instruction that describes the task: ### Input: Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``. Returns: list of (shadow_model_var, local_model_var) used for syncing. ### Response: def _shadow_model_variables(shadow_vars): """ ...
def com_google_fonts_check_family_tnum_horizontal_metrics(fonts): """All tabular figures must have the same width across the RIBBI-family.""" from fontbakery.constants import RIBBI_STYLE_NAMES from fontTools.ttLib import TTFont RIBBI_ttFonts = [TTFont(f) for f in fonts if s...
All tabular figures must have the same width across the RIBBI-family.
Below is the the instruction that describes the task: ### Input: All tabular figures must have the same width across the RIBBI-family. ### Response: def com_google_fonts_check_family_tnum_horizontal_metrics(fonts): """All tabular figures must have the same width across the RIBBI-family.""" from fontbakery.cons...
def flux_up(self, fluxUpBottom, emission=None): '''Compute downwelling radiative flux at interfaces between layers. Inputs: * fluxDownTop: flux down at top * emission: emission from atmospheric levels (N) defaults to zero if not given Returns: ...
Compute downwelling radiative flux at interfaces between layers. Inputs: * fluxDownTop: flux down at top * emission: emission from atmospheric levels (N) defaults to zero if not given Returns: * vector of downwelling radiative flux between levels (N+...
Below is the the instruction that describes the task: ### Input: Compute downwelling radiative flux at interfaces between layers. Inputs: * fluxDownTop: flux down at top * emission: emission from atmospheric levels (N) defaults to zero if not given Returns: ...
def children(self, primary=None): """ :param primary: if None, then all parents are returned. If True, then only foreign keys composed of primary key attributes are considered. If False, the only foreign keys including at least one non-primary attribute are considered. :...
:param primary: if None, then all parents are returned. If True, then only foreign keys composed of primary key attributes are considered. If False, the only foreign keys including at least one non-primary attribute are considered. :return: dict of tables with foreign keys referencing s...
Below is the the instruction that describes the task: ### Input: :param primary: if None, then all parents are returned. If True, then only foreign keys composed of primary key attributes are considered. If False, the only foreign keys including at least one non-primary attribute are consid...
async def _request(self, method, url, loop=None, timeout=None, **kwargs): """Make a request through AIOHTTP.""" session = self.session or aiohttp.ClientSession( loop=loop, conn_timeout=timeout, read_timeout=timeout) try: async with session.request(method, url, **kwargs) a...
Make a request through AIOHTTP.
Below is the the instruction that describes the task: ### Input: Make a request through AIOHTTP. ### Response: async def _request(self, method, url, loop=None, timeout=None, **kwargs): """Make a request through AIOHTTP.""" session = self.session or aiohttp.ClientSession( loop=loop, conn...
def project_geometry(geometry, crs=None, to_crs=None, to_latlong=False): """ Project a shapely Polygon or MultiPolygon from lat-long to UTM, or vice-versa Parameters ---------- geometry : shapely Polygon or MultiPolygon the geometry to project crs : dict the starting coordin...
Project a shapely Polygon or MultiPolygon from lat-long to UTM, or vice-versa Parameters ---------- geometry : shapely Polygon or MultiPolygon the geometry to project crs : dict the starting coordinate reference system of the passed-in geometry, default value (None) will set...
Below is the the instruction that describes the task: ### Input: Project a shapely Polygon or MultiPolygon from lat-long to UTM, or vice-versa Parameters ---------- geometry : shapely Polygon or MultiPolygon the geometry to project crs : dict the starting coordinate reference sy...
def apply_transform(self, transform): """ Apply a transformation matrix to the current path in- place Parameters ----------- transform : (d+1, d+1) float Homogenous transformation for vertices """ dimension = self.vertices.shape[1] transform = n...
Apply a transformation matrix to the current path in- place Parameters ----------- transform : (d+1, d+1) float Homogenous transformation for vertices
Below is the the instruction that describes the task: ### Input: Apply a transformation matrix to the current path in- place Parameters ----------- transform : (d+1, d+1) float Homogenous transformation for vertices ### Response: def apply_transform(self, transform): """ ...
def methods(self) -> 'PrettyDir': """Returns all methods of the inspected object. Note that "methods" can mean "functions" when inspecting a module. """ return PrettyDir( self.obj, [ pattr for pattr in self.pattrs i...
Returns all methods of the inspected object. Note that "methods" can mean "functions" when inspecting a module.
Below is the the instruction that describes the task: ### Input: Returns all methods of the inspected object. Note that "methods" can mean "functions" when inspecting a module. ### Response: def methods(self) -> 'PrettyDir': """Returns all methods of the inspected object. Note that "metho...
def rest_get_stream(self, url, auth=None, verify=True, cert=None): """ Perform a chunked GET request to url with optional authentication This is specifically to download files. """ res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert) return res.raw, r...
Perform a chunked GET request to url with optional authentication This is specifically to download files.
Below is the the instruction that describes the task: ### Input: Perform a chunked GET request to url with optional authentication This is specifically to download files. ### Response: def rest_get_stream(self, url, auth=None, verify=True, cert=None): """ Perform a chunked GET request to ur...
def to_ut1unix(time: Union[str, datetime, float, np.ndarray]) -> np.ndarray: """ converts time inputs to UT1 seconds since Unix epoch """ # keep this order time = totime(time) if isinstance(time, (float, int)): return time if isinstance(time, (tuple, list, np.ndarray)): ass...
converts time inputs to UT1 seconds since Unix epoch
Below is the the instruction that describes the task: ### Input: converts time inputs to UT1 seconds since Unix epoch ### Response: def to_ut1unix(time: Union[str, datetime, float, np.ndarray]) -> np.ndarray: """ converts time inputs to UT1 seconds since Unix epoch """ # keep this order time = ...
def replicasResource(self): """returns a list of replices""" if self._replicasResource is None: self._replicasResource = {} for replica in self.replicas: self._replicasResource["replicaName"] = replica.name self._replicasResource["replicaID"] = rep...
returns a list of replices
Below is the the instruction that describes the task: ### Input: returns a list of replices ### Response: def replicasResource(self): """returns a list of replices""" if self._replicasResource is None: self._replicasResource = {} for replica in self.replicas: ...
def make_network_graph(compact, expression_names, lookup_names): """ Make a network graph, represented as of nodes and a set of edges. The nodes are represented as tuples: (name: string, input_dim: Dim, label: string, output_dim: Dim, children: set[name], features: string) # The edges are represented as dict ...
Make a network graph, represented as of nodes and a set of edges. The nodes are represented as tuples: (name: string, input_dim: Dim, label: string, output_dim: Dim, children: set[name], features: string) # The edges are represented as dict of children to sets of parents: (child: string) -> [(parent: string, feat...
Below is the the instruction that describes the task: ### Input: Make a network graph, represented as of nodes and a set of edges. The nodes are represented as tuples: (name: string, input_dim: Dim, label: string, output_dim: Dim, children: set[name], features: string) # The edges are represented as dict of c...
def create(app_id: int = None, login: str = None, password: str = None, service_token: str = None, proxies: dict = None) -> API: """ Creates an API instance, requires app ID, login and password or service token to create connection :param app_id: int: specifi...
Creates an API instance, requires app ID, login and password or service token to create connection :param app_id: int: specifies app ID :param login: str: specifies login, can be phone number or email :param password: str: specifies password :param service_token: str: specifies password service tok...
Below is the the instruction that describes the task: ### Input: Creates an API instance, requires app ID, login and password or service token to create connection :param app_id: int: specifies app ID :param login: str: specifies login, can be phone number or email :param password: str: specifies p...
def draw_lnm_samples(**kwargs): ''' Draw samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The secon...
Draw samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass
Below is the the instruction that describes the task: ### Input: Draw samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass ...
def loads(astring): """Decompress and deserialize string into a Python object via pickle.""" try: return pickle.loads(lzma.decompress(astring)) except lzma.LZMAError as e: raise SerializerError( 'Cannot decompress object ("{}")'.format(str(e)) ...
Decompress and deserialize string into a Python object via pickle.
Below is the the instruction that describes the task: ### Input: Decompress and deserialize string into a Python object via pickle. ### Response: def loads(astring): """Decompress and deserialize string into a Python object via pickle.""" try: return pickle.loads(lzma.decompress(astring...
def profile(name, profile, onlyif=None, unless=None, opts=None, **kwargs): ''' Create a single instance on a cloud provider, using a salt-cloud profile. Note that while profiles used this function do take any configuration argument that would normally be used to create an instance using a profile, ...
Create a single instance on a cloud provider, using a salt-cloud profile. Note that while profiles used this function do take any configuration argument that would normally be used to create an instance using a profile, this state will not verify the state of any of those arguments on an existing insta...
Below is the the instruction that describes the task: ### Input: Create a single instance on a cloud provider, using a salt-cloud profile. Note that while profiles used this function do take any configuration argument that would normally be used to create an instance using a profile, this state will no...
def posterior_step(logposts, dim): """Finds the last time a chain made a jump > dim/2. Parameters ---------- logposts : array 1D array of values that are proportional to the log posterior values. dim : int The dimension of the parameter space. Returns ------- int ...
Finds the last time a chain made a jump > dim/2. Parameters ---------- logposts : array 1D array of values that are proportional to the log posterior values. dim : int The dimension of the parameter space. Returns ------- int The index of the last time the logpost m...
Below is the the instruction that describes the task: ### Input: Finds the last time a chain made a jump > dim/2. Parameters ---------- logposts : array 1D array of values that are proportional to the log posterior values. dim : int The dimension of the parameter space. Returns...
def _ComputeUniquifier(self, debuggee): """Computes debuggee uniquifier. The debuggee uniquifier has to be identical on all instances. Therefore the uniquifier should not include any random numbers and should only be based on inputs that are guaranteed to be the same on all instances. Args: ...
Computes debuggee uniquifier. The debuggee uniquifier has to be identical on all instances. Therefore the uniquifier should not include any random numbers and should only be based on inputs that are guaranteed to be the same on all instances. Args: debuggee: complete debuggee message without the...
Below is the the instruction that describes the task: ### Input: Computes debuggee uniquifier. The debuggee uniquifier has to be identical on all instances. Therefore the uniquifier should not include any random numbers and should only be based on inputs that are guaranteed to be the same on all instan...
def _synthesize_multiple_python(self, text_file, output_file_path, quit_after=None, backwards=False): """ Synthesize multiple fragments via a Python call. :rtype: tuple (result, (anchors, current_time, num_chars)) """ self.log(u"Synthesizing multiple via a Python call...") ...
Synthesize multiple fragments via a Python call. :rtype: tuple (result, (anchors, current_time, num_chars))
Below is the the instruction that describes the task: ### Input: Synthesize multiple fragments via a Python call. :rtype: tuple (result, (anchors, current_time, num_chars)) ### Response: def _synthesize_multiple_python(self, text_file, output_file_path, quit_after=None, backwards=False): """ ...
def combined(cls, code, path=None, extra_args=None): """ Compile combined-json with abi,bin,devdoc,userdoc. @param code: literal solidity code as a string. @param path: absolute path to solidity-file. Note: code & path are mutually exclusive! @param extra_args: Eith...
Compile combined-json with abi,bin,devdoc,userdoc. @param code: literal solidity code as a string. @param path: absolute path to solidity-file. Note: code & path are mutually exclusive! @param extra_args: Either a space separated string or a list of extra ...
Below is the the instruction that describes the task: ### Input: Compile combined-json with abi,bin,devdoc,userdoc. @param code: literal solidity code as a string. @param path: absolute path to solidity-file. Note: code & path are mutually exclusive! @param extra_args: ...
def get_logger(name="peyotl"): """Returns a logger with name set as given. See _read_logging_config for a description of the env var/config file cascade that controls configuration of the logger. """ logger = logging.getLogger(name) if len(logger.handlers) == 0: log_init_warnings = [] ...
Returns a logger with name set as given. See _read_logging_config for a description of the env var/config file cascade that controls configuration of the logger.
Below is the the instruction that describes the task: ### Input: Returns a logger with name set as given. See _read_logging_config for a description of the env var/config file cascade that controls configuration of the logger. ### Response: def get_logger(name="peyotl"): """Returns a logger with name set a...
def previous_obj(self): """Returns a model obj that is the first occurrence of a previous obj relative to this object's appointment. Override this method if not am EDC subject model / CRF. """ previous_obj = None if self.previous_visit: try: p...
Returns a model obj that is the first occurrence of a previous obj relative to this object's appointment. Override this method if not am EDC subject model / CRF.
Below is the the instruction that describes the task: ### Input: Returns a model obj that is the first occurrence of a previous obj relative to this object's appointment. Override this method if not am EDC subject model / CRF. ### Response: def previous_obj(self): """Returns a model obj th...
def bottom(self, N, mask=NotSpecified, groupby=NotSpecified): """ Construct a Filter matching the bottom N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the bottom N asset values for each group. Parameters ---------- N : in...
Construct a Filter matching the bottom N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the bottom N asset values for each group. Parameters ---------- N : int Number of assets passing the returned filter each day. mask ...
Below is the the instruction that describes the task: ### Input: Construct a Filter matching the bottom N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the bottom N asset values for each group. Parameters ---------- N : int ...
def prepare(self): """ Returns an aioxmpp.stanza.Message built from the Message and prepared to be sent. Returns: aioxmpp.stanza.Message: the message prepared to be sent """ msg = aioxmpp.stanza.Message( to=self.to, from_=self.sender, ...
Returns an aioxmpp.stanza.Message built from the Message and prepared to be sent. Returns: aioxmpp.stanza.Message: the message prepared to be sent
Below is the the instruction that describes the task: ### Input: Returns an aioxmpp.stanza.Message built from the Message and prepared to be sent. Returns: aioxmpp.stanza.Message: the message prepared to be sent ### Response: def prepare(self): """ Returns an aioxmpp.stanza.Messa...
def _updateNonDefaultsForInspector(self, inspectorRegItem, inspector): """ Store the (non-default) config values for the current inspector in a local dictionary. This dictionary is later used to store value for persistence. This function must be called after the inspector was drawn beca...
Store the (non-default) config values for the current inspector in a local dictionary. This dictionary is later used to store value for persistence. This function must be called after the inspector was drawn because that may update some derived config values (e.g. ranges)
Below is the the instruction that describes the task: ### Input: Store the (non-default) config values for the current inspector in a local dictionary. This dictionary is later used to store value for persistence. This function must be called after the inspector was drawn because that may u...
def prior_draw(self, N=1): """ Draw ``N`` samples from the prior. """ p = np.random.ranf(size=(N, self.ndim)) p = (self._upper_right - self._lower_left) * p + self._lower_left return p
Draw ``N`` samples from the prior.
Below is the the instruction that describes the task: ### Input: Draw ``N`` samples from the prior. ### Response: def prior_draw(self, N=1): """ Draw ``N`` samples from the prior. """ p = np.random.ranf(size=(N, self.ndim)) p = (self._upper_right - self._lower_left) * p + se...
def set_connections_params(self, harakiri=None, timeout_socket=None): """Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. """ self._set_aliased('harakiri', ha...
Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60.
Below is the the instruction that describes the task: ### Input: Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. ### Response: def set_connections_params(self, harakiri=None, ti...
def pdf_link(self, link_f, y, Y_metadata=None): """ Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})\\exp (-y\\lambda(f_{i})) :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y...
Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})\\exp (-y\\lambda(f_{i})) :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata which is not used ...
Below is the the instruction that describes the task: ### Input: Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})\\exp (-y\\lambda(f_{i})) :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type ...
def get_topics(yaml_info): ''' Returns the names of all of the topics in the bag, and prints them to stdout if requested ''' # Pull out the topic info names = [] # Store all of the topics in a dictionary topics = yaml_info['topics'] for topic in topics: names.append(topic['to...
Returns the names of all of the topics in the bag, and prints them to stdout if requested
Below is the the instruction that describes the task: ### Input: Returns the names of all of the topics in the bag, and prints them to stdout if requested ### Response: def get_topics(yaml_info): ''' Returns the names of all of the topics in the bag, and prints them to stdout if requested '...
def do_bulk_config_update(hostnames): """ Given a list of hostnames, update the configs of all the datanodes, tasktrackers and regionservers on those hosts. """ api = ApiResource(CM_HOST, username=CM_USER, password=CM_PASSWD) hosts = collect_hosts(api, hostnames) # Set config for h in hosts: config...
Given a list of hostnames, update the configs of all the datanodes, tasktrackers and regionservers on those hosts.
Below is the the instruction that describes the task: ### Input: Given a list of hostnames, update the configs of all the datanodes, tasktrackers and regionservers on those hosts. ### Response: def do_bulk_config_update(hostnames): """ Given a list of hostnames, update the configs of all the datanodes, tas...
def _insert(self, feature, cursor): """ Insert a feature into the database. """ try: cursor.execute(constants._INSERT, feature.astuple()) except sqlite3.ProgrammingError: cursor.execute( constants._INSERT, feature.astuple(self.default_encod...
Insert a feature into the database.
Below is the the instruction that describes the task: ### Input: Insert a feature into the database. ### Response: def _insert(self, feature, cursor): """ Insert a feature into the database. """ try: cursor.execute(constants._INSERT, feature.astuple()) except sql...
def terminal_type(cls): """ returns darwin, cygwin, cmd, or linux """ what = sys.platform kind = 'UNDEFINED_TERMINAL_TYPE' if 'linux' in what: kind = 'linux' elif 'darwin' in what: kind = 'darwin' elif 'cygwin' in what: ...
returns darwin, cygwin, cmd, or linux
Below is the the instruction that describes the task: ### Input: returns darwin, cygwin, cmd, or linux ### Response: def terminal_type(cls): """ returns darwin, cygwin, cmd, or linux """ what = sys.platform kind = 'UNDEFINED_TERMINAL_TYPE' if 'linux' in what: ...
def navigation(self, id=None): """Function decorator for navbar registration. Convenience function, calls :meth:`.register_element` with ``id`` and the decorated function as ``elem``. :param id: ID to pass on. If ``None``, uses the decorated functions name. "...
Function decorator for navbar registration. Convenience function, calls :meth:`.register_element` with ``id`` and the decorated function as ``elem``. :param id: ID to pass on. If ``None``, uses the decorated functions name.
Below is the the instruction that describes the task: ### Input: Function decorator for navbar registration. Convenience function, calls :meth:`.register_element` with ``id`` and the decorated function as ``elem``. :param id: ID to pass on. If ``None``, uses the decorated functions ...
def build_factored_variational_loss(model, observed_time_series, init_batch_shape=(), seed=None, name=None): """Build a loss function for variational inference in STS models....
Build a loss function for variational inference in STS models. Variational inference searches for the distribution within some family of approximate posteriors that minimizes a divergence between the approximate posterior `q(z)` and true posterior `p(z|observed_time_series)`. By converting inference to optimiz...
Below is the the instruction that describes the task: ### Input: Build a loss function for variational inference in STS models. Variational inference searches for the distribution within some family of approximate posteriors that minimizes a divergence between the approximate posterior `q(z)` and true poster...
def run_timed(self, **kwargs): """ Run the motor for the amount of time specified in `time_sp` and then stop the motor using the action specified by `stop_action`. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN_TIMED
Run the motor for the amount of time specified in `time_sp` and then stop the motor using the action specified by `stop_action`.
Below is the the instruction that describes the task: ### Input: Run the motor for the amount of time specified in `time_sp` and then stop the motor using the action specified by `stop_action`. ### Response: def run_timed(self, **kwargs): """ Run the motor for the amount of time specified i...
def parse_template_config(template_config_data): """ >>> from tests import doctest_utils >>> convert_html_to_text = registration_settings.VERIFICATION_EMAIL_HTML_TO_TEXT_CONVERTER # noqa: E501 >>> parse_template_config({}) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ...
>>> from tests import doctest_utils >>> convert_html_to_text = registration_settings.VERIFICATION_EMAIL_HTML_TO_TEXT_CONVERTER # noqa: E501 >>> parse_template_config({}) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ImproperlyConfigured >>> parse_template_config({ ...
Below is the the instruction that describes the task: ### Input: >>> from tests import doctest_utils >>> convert_html_to_text = registration_settings.VERIFICATION_EMAIL_HTML_TO_TEXT_CONVERTER # noqa: E501 >>> parse_template_config({}) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call las...
def UpdateSNMPObjs(): """ Function that does the actual data update. """ global threadingString LogMsg("Beginning data update.") data = "" # Obtain the data by calling an external command. We don't use # subprocess.check_output() here for compatibility with Python versions # older than 2.7. LogMsg("Calling e...
Function that does the actual data update.
Below is the the instruction that describes the task: ### Input: Function that does the actual data update. ### Response: def UpdateSNMPObjs(): """ Function that does the actual data update. """ global threadingString LogMsg("Beginning data update.") data = "" # Obtain the data by calling an external comma...
def cmd_takeoff(self, args): '''take off''' if ( len(args) != 1): print("Usage: takeoff ALTITUDE_IN_METERS") return if (len(args) == 1): altitude = float(args[0]) print("Take Off started") self.master.mav.command_long_send( ...
take off
Below is the the instruction that describes the task: ### Input: take off ### Response: def cmd_takeoff(self, args): '''take off''' if ( len(args) != 1): print("Usage: takeoff ALTITUDE_IN_METERS") return if (len(args) == 1): altitude = float(args[0]) ...
def is_pa_terminal(cls, ball_tally, strike_tally, pitch_res, event_cd): """ Is PA terminal :param ball_tally: Ball telly :param strike_tally: Strike telly :param pitch_res: pitching result(Retrosheet format) :param event_cd: Event code :return: FLG(T or F) ...
Is PA terminal :param ball_tally: Ball telly :param strike_tally: Strike telly :param pitch_res: pitching result(Retrosheet format) :param event_cd: Event code :return: FLG(T or F)
Below is the the instruction that describes the task: ### Input: Is PA terminal :param ball_tally: Ball telly :param strike_tally: Strike telly :param pitch_res: pitching result(Retrosheet format) :param event_cd: Event code :return: FLG(T or F) ### Response: def is_pa_termi...
def doDup(self, WHAT={}, **params): """This function will perform the command -dup.""" if hasattr(WHAT, '_modified'): for key, value in WHAT._modified(): if WHAT.__new2old__.has_key(key): self._addDBParam(WHAT.__new2old__[key].encode('utf-8'), value) else: self._addDBParam(key, value) self....
This function will perform the command -dup.
Below is the the instruction that describes the task: ### Input: This function will perform the command -dup. ### Response: def doDup(self, WHAT={}, **params): """This function will perform the command -dup.""" if hasattr(WHAT, '_modified'): for key, value in WHAT._modified(): if WHAT.__new2old__.has_k...
def get_pulls_review_comments(self, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet, since=github.GithubObject.NotSet): """ :calls: `GET /repos/:owner/:repo/pulls/comments <http://developer.github.com/v3/pulls/comments>`_ :param sort: string :param direction: string...
:calls: `GET /repos/:owner/:repo/pulls/comments <http://developer.github.com/v3/pulls/comments>`_ :param sort: string :param direction: string :param since: datetime.datetime :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.PullRequestComment.PullRequestComment`
Below is the the instruction that describes the task: ### Input: :calls: `GET /repos/:owner/:repo/pulls/comments <http://developer.github.com/v3/pulls/comments>`_ :param sort: string :param direction: string :param since: datetime.datetime :rtype: :class:`github.PaginatedList.Paginat...
def _p_o(self, o): """ Returns the output probability for symbol o from all hidden states Parameters ---------- o : float A single observation. Return ------ p_o : ndarray (N) p_o[i] is the probability density of the observation o...
Returns the output probability for symbol o from all hidden states Parameters ---------- o : float A single observation. Return ------ p_o : ndarray (N) p_o[i] is the probability density of the observation o from state i emission distribution ...
Below is the the instruction that describes the task: ### Input: Returns the output probability for symbol o from all hidden states Parameters ---------- o : float A single observation. Return ------ p_o : ndarray (N) p_o[i] is the probabilit...
def upgrade(self): """Upgrade the config file. """ warn('Upgrading ' + self.filename) if self.backup_config(self.filename): return self.write_default_config(self.filename) return False
Upgrade the config file.
Below is the the instruction that describes the task: ### Input: Upgrade the config file. ### Response: def upgrade(self): """Upgrade the config file. """ warn('Upgrading ' + self.filename) if self.backup_config(self.filename): return self.write_default_config(self.filen...
async def _execute(self, appt): ''' Fire off the task to make the storm query ''' user = self.core.auth.user(appt.useriden) if user is None: logger.warning('Unknown user %s in stored appointment', appt.useriden) await self._markfailed(appt) ret...
Fire off the task to make the storm query
Below is the the instruction that describes the task: ### Input: Fire off the task to make the storm query ### Response: async def _execute(self, appt): ''' Fire off the task to make the storm query ''' user = self.core.auth.user(appt.useriden) if user is None: l...
def shift(ol,**kwargs): ''' from elist.jprint import pobj from elist.elist import * ol = [1,2,3,4] id(ol) rslt = shift(ol) pobj(rslt) ol id(ol) id(rslt['list']) #### ol = [1,2,3,4] id(ol) rslt = shift(ol,mode="or...
from elist.jprint import pobj from elist.elist import * ol = [1,2,3,4] id(ol) rslt = shift(ol) pobj(rslt) ol id(ol) id(rslt['list']) #### ol = [1,2,3,4] id(ol) rslt = shift(ol,mode="original") rslt ol ...
Below is the the instruction that describes the task: ### Input: from elist.jprint import pobj from elist.elist import * ol = [1,2,3,4] id(ol) rslt = shift(ol) pobj(rslt) ol id(ol) id(rslt['list']) #### ol = [1,2,3,4] id(ol) ...
def std_velocity(particle, social, state): """ Standard particle velocity update according to the equation: :math:`v_{ij}(t+1) &= \\omega v_{ij}(t) + \ c_1 r_{1j}(t)[y_{ij}(t) - x_{ij}(t)]\\:+ \ c_2 r_{2j}(t)[\\hat{y}_{ij}(t) - x_{ij}(t)],\\;\\;\ \\forall\\; j \\in\\; \\{1,...,n\\}` If a v...
Standard particle velocity update according to the equation: :math:`v_{ij}(t+1) &= \\omega v_{ij}(t) + \ c_1 r_{1j}(t)[y_{ij}(t) - x_{ij}(t)]\\:+ \ c_2 r_{2j}(t)[\\hat{y}_{ij}(t) - x_{ij}(t)],\\;\\;\ \\forall\\; j \\in\\; \\{1,...,n\\}` If a v_max parameter is supplied (state.params['v_max'] is no...
Below is the the instruction that describes the task: ### Input: Standard particle velocity update according to the equation: :math:`v_{ij}(t+1) &= \\omega v_{ij}(t) + \ c_1 r_{1j}(t)[y_{ij}(t) - x_{ij}(t)]\\:+ \ c_2 r_{2j}(t)[\\hat{y}_{ij}(t) - x_{ij}(t)],\\;\\;\ \\forall\\; j \\in\\; \\{1,...,n\\...
def diff(self): """The Difference between a PDA and a DFA""" self.mmb.complement(self.alphabet) self.mmb.minimize() print 'start intersection' self.mmc = self._intesect() print 'end intersection' return self.mmc
The Difference between a PDA and a DFA
Below is the the instruction that describes the task: ### Input: The Difference between a PDA and a DFA ### Response: def diff(self): """The Difference between a PDA and a DFA""" self.mmb.complement(self.alphabet) self.mmb.minimize() print 'start intersection' self.mmc = sel...
def write_out_sitemap(self, opath): """ Banana banana """ if opath not in self.written_out_sitemaps: Extension.formatted_sitemap = self.formatter.format_navigation( self.app.project) if Extension.formatted_sitemap: escaped_sitemap =...
Banana banana
Below is the the instruction that describes the task: ### Input: Banana banana ### Response: def write_out_sitemap(self, opath): """ Banana banana """ if opath not in self.written_out_sitemaps: Extension.formatted_sitemap = self.formatter.format_navigation( ...
def parse(date_string, date_formats=None, languages=None, locales=None, region=None, settings=None): """Parse date and time from given date string. :param date_string: A string representing date and/or time in a recognizably valid format. :type date_string: str|unicode :param date_formats: ...
Parse date and time from given date string. :param date_string: A string representing date and/or time in a recognizably valid format. :type date_string: str|unicode :param date_formats: A list of format strings using directives as given `here <https://docs.python.org/2/library/dat...
Below is the the instruction that describes the task: ### Input: Parse date and time from given date string. :param date_string: A string representing date and/or time in a recognizably valid format. :type date_string: str|unicode :param date_formats: A list of format strings using dir...
def _calculate_hour_and_minute(float_hour): """Calculate hour and minutes as integers from a float hour.""" hour, minute = int(float_hour), int(round((float_hour - int(float_hour)) * 60)) if minute == 60: return hour + 1, 0 else: return hour, minute
Calculate hour and minutes as integers from a float hour.
Below is the the instruction that describes the task: ### Input: Calculate hour and minutes as integers from a float hour. ### Response: def _calculate_hour_and_minute(float_hour): """Calculate hour and minutes as integers from a float hour.""" hour, minute = int(float_hour), int(round((float_hour ...
def setSignalHeader(self, edfsignal, channel_info): """ Sets the parameter for signal edfsignal. channel_info should be a dict with these values: 'label' : channel label (string, <= 16 characters, must be unique) 'dimension' : physical dimension (e.g., mV) (stri...
Sets the parameter for signal edfsignal. channel_info should be a dict with these values: 'label' : channel label (string, <= 16 characters, must be unique) 'dimension' : physical dimension (e.g., mV) (string, <= 8 characters) 'sample_rate' : sample frequency in her...
Below is the the instruction that describes the task: ### Input: Sets the parameter for signal edfsignal. channel_info should be a dict with these values: 'label' : channel label (string, <= 16 characters, must be unique) 'dimension' : physical dimension (e.g., mV) (string,...
def export(self, output=Mimetypes.PLAINTEXT, exclude=None, **kwargs): """ Export the collection item in the Mimetype required. ..note:: If current implementation does not have special mimetypes, reuses default_export method :param output: Mimetype to export to (Uses Mimetypes) :type ou...
Export the collection item in the Mimetype required. ..note:: If current implementation does not have special mimetypes, reuses default_export method :param output: Mimetype to export to (Uses Mimetypes) :type output: str :param exclude: Informations to exclude. Specific to implementat...
Below is the the instruction that describes the task: ### Input: Export the collection item in the Mimetype required. ..note:: If current implementation does not have special mimetypes, reuses default_export method :param output: Mimetype to export to (Uses Mimetypes) :type output: str ...
def _compute_soil_amplification(cls, C, vs30, pga_rock, imt): """ Compute soil amplification (5th, 6th, and 7th terms in equation 1, page 1706) and add the B/C site condition as implemented by NSHMP. Call :meth:`AtkinsonBoore2003SInterNSHMP2008._compute_soil_amplification` ...
Compute soil amplification (5th, 6th, and 7th terms in equation 1, page 1706) and add the B/C site condition as implemented by NSHMP. Call :meth:`AtkinsonBoore2003SInterNSHMP2008._compute_soil_amplification`
Below is the the instruction that describes the task: ### Input: Compute soil amplification (5th, 6th, and 7th terms in equation 1, page 1706) and add the B/C site condition as implemented by NSHMP. Call :meth:`AtkinsonBoore2003SInterNSHMP2008._compute_soil_amplification` ### Response: def...
def generate_api_doc(self, uri): '''Make autodoc documentation template string for a module Parameters ---------- uri : string python location of module - e.g 'sphinx.builder' Returns ------- head : string Module name, table of contents. ...
Make autodoc documentation template string for a module Parameters ---------- uri : string python location of module - e.g 'sphinx.builder' Returns ------- head : string Module name, table of contents. body : string Function a...
Below is the the instruction that describes the task: ### Input: Make autodoc documentation template string for a module Parameters ---------- uri : string python location of module - e.g 'sphinx.builder' Returns ------- head : string Module ...
def read_seal_status(self): """Read the seal status of the Vault. This is an unauthenticated endpoint. Supported methods: GET: /sys/seal-status. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict """ api_path = '/...
Read the seal status of the Vault. This is an unauthenticated endpoint. Supported methods: GET: /sys/seal-status. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict
Below is the the instruction that describes the task: ### Input: Read the seal status of the Vault. This is an unauthenticated endpoint. Supported methods: GET: /sys/seal-status. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict ###...
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidSourceableForm._init_metadata(self) osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._copyright_registration_default = self._mdata['copyright_registration']['default_string_values'][0] ...
Initialize form metadata
Below is the the instruction that describes the task: ### Input: Initialize form metadata ### Response: def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidSourceableForm._init_metadata(self) osid_objects.OsidObjectForm._init_metadata(self, **kwargs) ...
def read_slaext(self,filename,params=None,force=False,timerange=None,datatype=None,**kwargs): """ Read AVISO Along-Track SLAEXT regional products :return outStr: Output data structure containing all recorded parameters as specificied by NetCDF file PARAMETER list. ...
Read AVISO Along-Track SLAEXT regional products :return outStr: Output data structure containing all recorded parameters as specificied by NetCDF file PARAMETER list. :author: Renaud Dussurget
Below is the the instruction that describes the task: ### Input: Read AVISO Along-Track SLAEXT regional products :return outStr: Output data structure containing all recorded parameters as specificied by NetCDF file PARAMETER list. :author: Renaud Dussurget ### Response: def read_slaext...
def read_flags_from_files(self, argv, force_gnu=True): """Processes command line args, but also allow args to be read from file. Args: argv: [str], a list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that...
Processes command line args, but also allow args to be read from file. Args: argv: [str], a list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. ...
Below is the the instruction that describes the task: ### Input: Processes command line args, but also allow args to be read from file. Args: argv: [str], a list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". No...
def annotation_spec_set_path(cls, project, annotation_spec_set): """Return a fully-qualified annotation_spec_set string.""" return google.api_core.path_template.expand( "projects/{project}/annotationSpecSets/{annotation_spec_set}", project=project, annotation_spec_set...
Return a fully-qualified annotation_spec_set string.
Below is the the instruction that describes the task: ### Input: Return a fully-qualified annotation_spec_set string. ### Response: def annotation_spec_set_path(cls, project, annotation_spec_set): """Return a fully-qualified annotation_spec_set string.""" return google.api_core.path_template.expand...
def authenticate(self, request, identification, password=None, check_password=True): """ Authenticates a user through the combination email/username with password. :param request: The authenticate() method of authentication backends requires request as the first ...
Authenticates a user through the combination email/username with password. :param request: The authenticate() method of authentication backends requires request as the first positional argument from Django 2.1. :param identification: A string containing the ...
Below is the the instruction that describes the task: ### Input: Authenticates a user through the combination email/username with password. :param request: The authenticate() method of authentication backends requires request as the first positional argument from Django 2.1....
def start(self): """ Start or restart (the :meth:`~pypot.primitive.primitive.Primitive.stop` method will automatically be called) the primitive. """ if not self.robot._primitive_manager.running: raise RuntimeError('Cannot run a primitive when the sync is stopped!') StoppableThread.s...
Start or restart (the :meth:`~pypot.primitive.primitive.Primitive.stop` method will automatically be called) the primitive.
Below is the the instruction that describes the task: ### Input: Start or restart (the :meth:`~pypot.primitive.primitive.Primitive.stop` method will automatically be called) the primitive. ### Response: def start(self): """ Start or restart (the :meth:`~pypot.primitive.primitive.Primitive.stop` method will...
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['ds'] = self._ds return json.dumps(json_dict)
:return: str
Below is the the instruction that describes the task: ### Input: :return: str ### Response: def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['ds'] = self._ds return json.dumps(json_dict)
def update_record(self, msg_id, rec): """Update the data in an existing record.""" query = "UPDATE %s SET "%self.table sets = [] keys = sorted(rec.keys()) values = [] for key in keys: sets.append('%s = ?'%key) values.append(rec[key]) query ...
Update the data in an existing record.
Below is the the instruction that describes the task: ### Input: Update the data in an existing record. ### Response: def update_record(self, msg_id, rec): """Update the data in an existing record.""" query = "UPDATE %s SET "%self.table sets = [] keys = sorted(rec.keys()) va...
def flush(table='filter', chain='', family='ipv4'): ''' Flush the chain in the specified table, flush all chains in the specified table if chain is not specified. CLI Example: .. code-block:: bash salt '*' nftables.flush filter salt '*' nftables.flush filter input IPv6: ...
Flush the chain in the specified table, flush all chains in the specified table if chain is not specified. CLI Example: .. code-block:: bash salt '*' nftables.flush filter salt '*' nftables.flush filter input IPv6: salt '*' nftables.flush filter input family=ipv6
Below is the the instruction that describes the task: ### Input: Flush the chain in the specified table, flush all chains in the specified table if chain is not specified. CLI Example: .. code-block:: bash salt '*' nftables.flush filter salt '*' nftables.flush filter input I...
def _get_index_points(self, index_points=None): """Return `index_points` if not None, else `self._index_points`. Args: index_points: if given, this is what is returned; else, `self._index_points` Returns: index_points: the given arg, if not None, else the class member `self._index_...
Return `index_points` if not None, else `self._index_points`. Args: index_points: if given, this is what is returned; else, `self._index_points` Returns: index_points: the given arg, if not None, else the class member `self._index_points`. Rases: ValueError: if `index_points...
Below is the the instruction that describes the task: ### Input: Return `index_points` if not None, else `self._index_points`. Args: index_points: if given, this is what is returned; else, `self._index_points` Returns: index_points: the given arg, if not None, else the class member ...
def extend_dirichlet(p): """ extend_dirichlet(p) Concatenates 1-sum(p) to the end of p and returns. """ if len(np.shape(p)) > 1: return np.hstack((p, np.atleast_2d(1. - np.sum(p)))) else: return np.hstack((p, 1. - np.sum(p)))
extend_dirichlet(p) Concatenates 1-sum(p) to the end of p and returns.
Below is the the instruction that describes the task: ### Input: extend_dirichlet(p) Concatenates 1-sum(p) to the end of p and returns. ### Response: def extend_dirichlet(p): """ extend_dirichlet(p) Concatenates 1-sum(p) to the end of p and returns. """ if len(np.shape(p)) > 1: re...
def table(tab): """Access IPTables transactionally in a uniform way. Ensures all access is done without autocommit and that only the outer most task commits, and also ensures we refresh once and commit once. """ global open_tables if tab in open_tables: yield open_tables[tab] else: ...
Access IPTables transactionally in a uniform way. Ensures all access is done without autocommit and that only the outer most task commits, and also ensures we refresh once and commit once.
Below is the the instruction that describes the task: ### Input: Access IPTables transactionally in a uniform way. Ensures all access is done without autocommit and that only the outer most task commits, and also ensures we refresh once and commit once. ### Response: def table(tab): """Access IPTables...
def text(self, txt, x, y, width=None, height=1000000, outline=False, draw=True, **kwargs): ''' Draws a string of text according to current font settings. :param txt: Text to output :param x: x-coordinate of the top left corner :param y: y-coordinate of the top left corner ...
Draws a string of text according to current font settings. :param txt: Text to output :param x: x-coordinate of the top left corner :param y: y-coordinate of the top left corner :param width: text width :param height: text height :param outline: If True draws outline tex...
Below is the the instruction that describes the task: ### Input: Draws a string of text according to current font settings. :param txt: Text to output :param x: x-coordinate of the top left corner :param y: y-coordinate of the top left corner :param width: text width :param ...
def form_valid(self, form): """First call the parent's form valid then let the user know it worked.""" form_valid_from_parent = super(HostCreate, self).form_valid(form) messages.success(self.request, 'Host {} Successfully Created'.format(self.object)) return form_valid_from_parent
First call the parent's form valid then let the user know it worked.
Below is the the instruction that describes the task: ### Input: First call the parent's form valid then let the user know it worked. ### Response: def form_valid(self, form): """First call the parent's form valid then let the user know it worked.""" form_valid_from_parent = super(HostCreate, self...
def zrlist(self, name_start, name_end, limit=10): """ Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. ...
Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of zs...
Below is the the instruction that describes the task: ### Input: Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. ...
def bool_element(element, name, default=True): """ Returns the bool value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The default valu...
Returns the bool value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The default value to return if the element is not defined :type defaul...
Below is the the instruction that describes the task: ### Input: Returns the bool value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The de...
def show_hc(kwargs=None, call=None): ''' Show the details of an existing health check. CLI Example: .. code-block:: bash salt-cloud -f show_hc gce name=hc ''' if call != 'function': raise SaltCloudSystemExit( 'The show_hc function must be called with -f or --functi...
Show the details of an existing health check. CLI Example: .. code-block:: bash salt-cloud -f show_hc gce name=hc
Below is the the instruction that describes the task: ### Input: Show the details of an existing health check. CLI Example: .. code-block:: bash salt-cloud -f show_hc gce name=hc ### Response: def show_hc(kwargs=None, call=None): ''' Show the details of an existing health check. CLI...