code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def add_nodes(self, nodes): """ Add a given node or list of nodes to self.node_list. Args: node (Node or list[Node]): the node or list of nodes to add to the graph Returns: None Examples: Adding one node: :: >>> from blur.marko...
Add a given node or list of nodes to self.node_list. Args: node (Node or list[Node]): the node or list of nodes to add to the graph Returns: None Examples: Adding one node: :: >>> from blur.markov.node import Node >>> graph = Graph...
Below is the the instruction that describes the task: ### Input: Add a given node or list of nodes to self.node_list. Args: node (Node or list[Node]): the node or list of nodes to add to the graph Returns: None Examples: Adding one node: :: ...
def iter_create_panes(self, w, wconf): """ Return :class:`libtmux.Pane` iterating through window config dict. Run ``shell_command`` with ``$ tmux send-keys``. Parameters ---------- w : :class:`libtmux.Window` window to create panes for wconf : dict ...
Return :class:`libtmux.Pane` iterating through window config dict. Run ``shell_command`` with ``$ tmux send-keys``. Parameters ---------- w : :class:`libtmux.Window` window to create panes for wconf : dict config section for window Returns ...
Below is the the instruction that describes the task: ### Input: Return :class:`libtmux.Pane` iterating through window config dict. Run ``shell_command`` with ``$ tmux send-keys``. Parameters ---------- w : :class:`libtmux.Window` window to create panes for wcon...
def begin_episode(self, agent_indices): """Reset the recurrent states and stored episode. Args: agent_indices: Tensor containing current batch indices. Returns: Summary tensor. """ with tf.name_scope('begin_episode/'): if self._last_state is None: reset_state = tf.no_op()...
Reset the recurrent states and stored episode. Args: agent_indices: Tensor containing current batch indices. Returns: Summary tensor.
Below is the the instruction that describes the task: ### Input: Reset the recurrent states and stored episode. Args: agent_indices: Tensor containing current batch indices. Returns: Summary tensor. ### Response: def begin_episode(self, agent_indices): """Reset the recurrent states and st...
def get_stride(self): """Calculate the stride for the spectrogram This method returns the stride as a `float`, or `None` to indicate selected usage of `TimeSeries.spectrogram2`. """ fftlength = float(self.args.secpfft) overlap = fftlength * self.args.overlap stri...
Calculate the stride for the spectrogram This method returns the stride as a `float`, or `None` to indicate selected usage of `TimeSeries.spectrogram2`.
Below is the the instruction that describes the task: ### Input: Calculate the stride for the spectrogram This method returns the stride as a `float`, or `None` to indicate selected usage of `TimeSeries.spectrogram2`. ### Response: def get_stride(self): """Calculate the stride for the spec...
def age(self, as_at_date=None): """ Compute the person's age """ if self.date_of_death != None or self.is_deceased == True: return None as_at_date = date.today() if as_at_date == None else as_at_date if self.date_of_birth != None: if (as_...
Compute the person's age
Below is the the instruction that describes the task: ### Input: Compute the person's age ### Response: def age(self, as_at_date=None): """ Compute the person's age """ if self.date_of_death != None or self.is_deceased == True: return None as_at_date = date.toda...
def python_value(self, value): """Convert the database value to a pythonic value.""" value = coerce_to_bytes(value) obj = HashValue(value) obj.field = self return obj
Convert the database value to a pythonic value.
Below is the the instruction that describes the task: ### Input: Convert the database value to a pythonic value. ### Response: def python_value(self, value): """Convert the database value to a pythonic value.""" value = coerce_to_bytes(value) obj = HashValue(value) obj.field = self ...
def type_search(self, basetype, symbolstr, origin): """Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbols, e....
Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbols, e.g. this%sym%sym2%go. :arg origin: an instance of the Mo...
Below is the the instruction that describes the task: ### Input: Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbo...
def diff_asymmetric(self, catalogue, prime_label, tokenizer, output_fh): """Returns `output_fh` populated with CSV results giving the difference in n-grams between the witnesses of labelled sets of works in `catalogue`, limited to those works labelled with `prime_label`. :param ...
Returns `output_fh` populated with CSV results giving the difference in n-grams between the witnesses of labelled sets of works in `catalogue`, limited to those works labelled with `prime_label`. :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogu...
Below is the the instruction that describes the task: ### Input: Returns `output_fh` populated with CSV results giving the difference in n-grams between the witnesses of labelled sets of works in `catalogue`, limited to those works labelled with `prime_label`. :param catalogue: cata...
def location_path(self, path): """ Set the Location-Path of the response. :type path: String :param path: the Location-Path as a string """ path = path.strip("/") tmp = path.split("?") path = tmp[0] paths = path.split("/") for p in paths: ...
Set the Location-Path of the response. :type path: String :param path: the Location-Path as a string
Below is the the instruction that describes the task: ### Input: Set the Location-Path of the response. :type path: String :param path: the Location-Path as a string ### Response: def location_path(self, path): """ Set the Location-Path of the response. :type path: String ...
def setPixmapSize( self, size ): """ Sets the pixmap size to the inputed value. :param size | <QSize> """ self._pixmapSize = size self.setMinimumHeight(size.height()) self.adjustMinimumWidth()
Sets the pixmap size to the inputed value. :param size | <QSize>
Below is the the instruction that describes the task: ### Input: Sets the pixmap size to the inputed value. :param size | <QSize> ### Response: def setPixmapSize( self, size ): """ Sets the pixmap size to the inputed value. :param size | <QSize> ...
def _print_cline(self, buf, i, icol): """ Print clines after multirow-blocks are finished """ for cl in self.clinebuf: if cl[0] == i: buf.write('\\cline{{{cl:d}-{icol:d}}}\n' .format(cl=cl[1], icol=icol)) # remove entries that...
Print clines after multirow-blocks are finished
Below is the the instruction that describes the task: ### Input: Print clines after multirow-blocks are finished ### Response: def _print_cline(self, buf, i, icol): """ Print clines after multirow-blocks are finished """ for cl in self.clinebuf: if cl[0] == i: ...
def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile)
Open the given HTML file in a browser.
Below is the the instruction that describes the task: ### Input: Open the given HTML file in a browser. ### Response: def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) el...
def random_nicks(self, letter=None, gender='u', count=1): """ Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random n...
Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random nicks :raises: ValueError
Below is the the instruction that describes the task: ### Input: Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random nicks ...
def get_common_parameters(input_files, collection=None): """Gets a list of variable params that are common across all input files. If no common parameters are found, a ``ValueError`` is raised. Parameters ---------- input_files : list of str List of input files to load. collection : st...
Gets a list of variable params that are common across all input files. If no common parameters are found, a ``ValueError`` is raised. Parameters ---------- input_files : list of str List of input files to load. collection : str, optional What group of parameters to load. Can be the...
Below is the the instruction that describes the task: ### Input: Gets a list of variable params that are common across all input files. If no common parameters are found, a ``ValueError`` is raised. Parameters ---------- input_files : list of str List of input files to load. collection...
def pause(self, device): """ Pause the given device. Args: device (str): Device ID. Returns: dict: with keys ``success`` and ``error``. """ resp = self.post('pause', params={'device': device}, return_response=True...
Pause the given device. Args: device (str): Device ID. Returns: dict: with keys ``success`` and ``error``.
Below is the the instruction that describes the task: ### Input: Pause the given device. Args: device (str): Device ID. Returns: dict: with keys ``success`` and ``error``. ### Response: def pause(self, device): """ Pause the given device. ...
def plot_classifier_errors(predictions, absolute=True, max_relative_size=50, absolute_size=50, title=None, outfile=None, wait=True): """ Plots the classifers for the given list of predictions. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html ...
Plots the classifers for the given list of predictions. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param predictions: the predictions to plot :type predictions: list :param absolute: whether to use absolute errors as size or relative ones :type absolute: bo...
Below is the the instruction that describes the task: ### Input: Plots the classifers for the given list of predictions. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param predictions: the predictions to plot :type predictions: list :param absolute: whether t...
def get_conn(cls): """Return a connection object to the ldap database""" conn = cls._conn if conn is None or conn.closed: conn = ldap3.Connection( settings.CAS_LDAP_SERVER, settings.CAS_LDAP_USER, settings.CAS_LDAP_PASSWORD, ...
Return a connection object to the ldap database
Below is the the instruction that describes the task: ### Input: Return a connection object to the ldap database ### Response: def get_conn(cls): """Return a connection object to the ldap database""" conn = cls._conn if conn is None or conn.closed: conn = ldap3.Connection( ...
def changes(ctx, check, dry_run): """Show all the pending PRs for a given check.""" if not dry_run and check not in get_valid_checks(): abort('Check `{}` is not an Agent-based Integration'.format(check)) # get the name of the current release tag cur_version = get_version_string(check) targe...
Show all the pending PRs for a given check.
Below is the the instruction that describes the task: ### Input: Show all the pending PRs for a given check. ### Response: def changes(ctx, check, dry_run): """Show all the pending PRs for a given check.""" if not dry_run and check not in get_valid_checks(): abort('Check `{}` is not an Agent-based ...
def urlencode(self): """ Convert dictionary into a query string; keys are assumed to always be str """ output = ('%s=%s' % (k, quote(v)) for k, v in self.items()) return '&'.join(output)
Convert dictionary into a query string; keys are assumed to always be str
Below is the the instruction that describes the task: ### Input: Convert dictionary into a query string; keys are assumed to always be str ### Response: def urlencode(self): """ Convert dictionary into a query string; keys are assumed to always be str """ output = ('...
def deactivate_workflow_transitions(cr, model, transitions=None): """ Disable workflow transitions for workflows on a given model. This can be necessary for automatic workflow transitions when writing to an object via the ORM in the post migration step. Returns a dictionary to be used on reactivate_...
Disable workflow transitions for workflows on a given model. This can be necessary for automatic workflow transitions when writing to an object via the ORM in the post migration step. Returns a dictionary to be used on reactivate_workflow_transitions :param model: the model for which workflow transitio...
Below is the the instruction that describes the task: ### Input: Disable workflow transitions for workflows on a given model. This can be necessary for automatic workflow transitions when writing to an object via the ORM in the post migration step. Returns a dictionary to be used on reactivate_workflow_...
def filter(cls, pythons): """ Given a map of python interpreters in the format provided by PythonInterpreter.find(), filter out duplicate versions and versions we would prefer not to use. Returns a map in the same format as find. """ good = [] MAJOR, MINOR, SUBMINOR = range(3) de...
Given a map of python interpreters in the format provided by PythonInterpreter.find(), filter out duplicate versions and versions we would prefer not to use. Returns a map in the same format as find.
Below is the the instruction that describes the task: ### Input: Given a map of python interpreters in the format provided by PythonInterpreter.find(), filter out duplicate versions and versions we would prefer not to use. Returns a map in the same format as find. ### Response: def filter(cls, pythons...
def upload_chunk(self): """ Upload chunk of file. """ self._retried = 0 self._do_request() self.offset = int(self.request.response_headers.get('upload-offset')) if self.log_func: msg = '{} bytes uploaded ...'.format(self.offset) self.log_fu...
Upload chunk of file.
Below is the the instruction that describes the task: ### Input: Upload chunk of file. ### Response: def upload_chunk(self): """ Upload chunk of file. """ self._retried = 0 self._do_request() self.offset = int(self.request.response_headers.get('upload-offset')) ...
def youtube(keyword=None): """Open youtube. Args: keyword (optional): Search word. """ if keyword is None: web.open('https://www.youtube.com/watch?v=L_mBVT2jBFw') else: web.open(quote('https://www.youtube.com/results?search_query={}'.format(keyword), RESERVED))
Open youtube. Args: keyword (optional): Search word.
Below is the the instruction that describes the task: ### Input: Open youtube. Args: keyword (optional): Search word. ### Response: def youtube(keyword=None): """Open youtube. Args: keyword (optional): Search word. """ if keyword is None: web.open('https://www.youtube....
def download_files(self, dataset_files, destination='.'): """ Downloads file(s) to a local destination. :param dataset_files: :type dataset_files: list of :class: `DatasetFile` :param destination: The path to the desired local download destination :type destination: str ...
Downloads file(s) to a local destination. :param dataset_files: :type dataset_files: list of :class: `DatasetFile` :param destination: The path to the desired local download destination :type destination: str :param chunk: Whether or not to chunk the file. Default True :...
Below is the the instruction that describes the task: ### Input: Downloads file(s) to a local destination. :param dataset_files: :type dataset_files: list of :class: `DatasetFile` :param destination: The path to the desired local download destination :type destination: str :...
def resolve_dep_from_path(self, depname): """ If we can find the dep in the PATH, then we consider it to be a system dependency that we should not bundle in the package """ if is_system_dep(depname): return True for d in self._path: name = os.path.join(d, depname...
If we can find the dep in the PATH, then we consider it to be a system dependency that we should not bundle in the package
Below is the the instruction that describes the task: ### Input: If we can find the dep in the PATH, then we consider it to be a system dependency that we should not bundle in the package ### Response: def resolve_dep_from_path(self, depname): """ If we can find the dep in the PATH, then we conside...
def used_options(self): """Return options already used in the command line rtype: command.Option generator """ for option_str in filter(lambda c: c.startswith('-'), self.words): for option in list(self.cmd.options.values()): if option_str in option.op...
Return options already used in the command line rtype: command.Option generator
Below is the the instruction that describes the task: ### Input: Return options already used in the command line rtype: command.Option generator ### Response: def used_options(self): """Return options already used in the command line rtype: command.Option generator ...
def set_var_index(self, name, index, var): """ Overwrite the values in variable "name" with data from var, at the flattened (C-contiguous style) indices. Indices is a vector of 0-based integers, of the same length as the vector var. For some implementations it can be equi...
Overwrite the values in variable "name" with data from var, at the flattened (C-contiguous style) indices. Indices is a vector of 0-based integers, of the same length as the vector var. For some implementations it can be equivalent and more efficient to do: `get_var(name)...
Below is the the instruction that describes the task: ### Input: Overwrite the values in variable "name" with data from var, at the flattened (C-contiguous style) indices. Indices is a vector of 0-based integers, of the same length as the vector var. For some implementations it can b...
def delete(self, source): '''Thread worker for download operation.''' s3url = S3URL(source) message('Delete %s', source) if not self.opt.dry_run: self.s3.delete_object(Bucket=s3url.bucket, Key=s3url.path)
Thread worker for download operation.
Below is the the instruction that describes the task: ### Input: Thread worker for download operation. ### Response: def delete(self, source): '''Thread worker for download operation.''' s3url = S3URL(source) message('Delete %s', source) if not self.opt.dry_run: self.s3.delete_object(Bucket=...
def push(self, obj): """Pushes a new item to the stack""" rv = getattr(self._local, "stack", None) if rv is None: self._local.stack = rv = [] rv.append(obj) return rv
Pushes a new item to the stack
Below is the the instruction that describes the task: ### Input: Pushes a new item to the stack ### Response: def push(self, obj): """Pushes a new item to the stack""" rv = getattr(self._local, "stack", None) if rv is None: self._local.stack = rv = [] rv.append(obj) ...
def time_stats(self, **kwargs): """Get time stats for the object. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabTimeTrackingError: If the time tracking update cannot ...
Get time stats for the object. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabTimeTrackingError: If the time tracking update cannot be done
Below is the the instruction that describes the task: ### Input: Get time stats for the object. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabTimeTrackingError: If the ti...
def save(self): """ IPAddress can only change its PTR record. Saves the current state, PUT /ip_address/uuid. """ body = {'ip_address': {'ptr_record': self.ptr_record}} data = self.cloud_manager.request('PUT', '/ip_address/' + self.address, body) self._reset(**data['ip_add...
IPAddress can only change its PTR record. Saves the current state, PUT /ip_address/uuid.
Below is the the instruction that describes the task: ### Input: IPAddress can only change its PTR record. Saves the current state, PUT /ip_address/uuid. ### Response: def save(self): """ IPAddress can only change its PTR record. Saves the current state, PUT /ip_address/uuid. """ bo...
def gradients_X(self, dL_dK, X, X2): """Derivative of the covariance matrix with respect to X""" return self._comp_grads(dL_dK, X, X2)[3]
Derivative of the covariance matrix with respect to X
Below is the the instruction that describes the task: ### Input: Derivative of the covariance matrix with respect to X ### Response: def gradients_X(self, dL_dK, X, X2): """Derivative of the covariance matrix with respect to X""" return self._comp_grads(dL_dK, X, X2)[3]
def import_components_from_dataframe(network, dataframe, cls_name): """ Import components from a pandas DataFrame. If columns are missing then defaults are used. If extra columns are added, these are left in the resulting component dataframe. Parameters ---------- dataframe : pandas.DataF...
Import components from a pandas DataFrame. If columns are missing then defaults are used. If extra columns are added, these are left in the resulting component dataframe. Parameters ---------- dataframe : pandas.DataFrame cls_name : string Name of class of component Examples ...
Below is the the instruction that describes the task: ### Input: Import components from a pandas DataFrame. If columns are missing then defaults are used. If extra columns are added, these are left in the resulting component dataframe. Parameters ---------- dataframe : pandas.DataFrame cl...
def IS_calc(TP, FP, FN, POP): """ Calculate IS (Information score). :param TP: true positive :type TP : int :param FP: false positive :type FP : int :param FN: false negative :type FN : int :param POP: population :type POP : int :return: IS as float """ try: ...
Calculate IS (Information score). :param TP: true positive :type TP : int :param FP: false positive :type FP : int :param FN: false negative :type FN : int :param POP: population :type POP : int :return: IS as float
Below is the the instruction that describes the task: ### Input: Calculate IS (Information score). :param TP: true positive :type TP : int :param FP: false positive :type FP : int :param FN: false negative :type FN : int :param POP: population :type POP : int :return: IS as floa...
def action(source, func): """Perform an action for each element of an asynchronous sequence without modifying it. The given function can be synchronous or asynchronous. """ if asyncio.iscoroutinefunction(func): async def innerfunc(arg): await func(arg) return arg ...
Perform an action for each element of an asynchronous sequence without modifying it. The given function can be synchronous or asynchronous.
Below is the the instruction that describes the task: ### Input: Perform an action for each element of an asynchronous sequence without modifying it. The given function can be synchronous or asynchronous. ### Response: def action(source, func): """Perform an action for each element of an asynchronous ...
def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwargs) found = self._hash.get_node(key) if not found and len(self._down_connections) > 0: raise self.HostListExhausted...
The first argument is assumed to be the ``key`` for routing.
Below is the the instruction that describes the task: ### Input: The first argument is assumed to be the ``key`` for routing. ### Response: def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwar...
def _query_service(self, name): """Query an individual service""" if self.query_cmd: try: return sos_get_command_output("%s %s" % (self.query_cmd, name)) except Exception: return None return None
Query an individual service
Below is the the instruction that describes the task: ### Input: Query an individual service ### Response: def _query_service(self, name): """Query an individual service""" if self.query_cmd: try: return sos_get_command_output("%s %s" % (self.query_cmd, name)) ...
def assemble(asmcode, pc=0, fork=DEFAULT_FORK): """ Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) :type fork: str ...
Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) :type fork: str :return: the hex representation of the bytecode ...
Below is the the instruction that describes the task: ### Input: Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) :type fo...
def _compute_total_chunks(self, chunk_size): # type: (Descriptor, int) -> int """Compute total number of chunks for entity :param Descriptor self: this :param int chunk_size: chunk size :rtype: int :return: num chunks """ try: chunks = int(math...
Compute total number of chunks for entity :param Descriptor self: this :param int chunk_size: chunk size :rtype: int :return: num chunks
Below is the the instruction that describes the task: ### Input: Compute total number of chunks for entity :param Descriptor self: this :param int chunk_size: chunk size :rtype: int :return: num chunks ### Response: def _compute_total_chunks(self, chunk_size): # type: (Descr...
def sign_envelope(envelope, key_file): """Sign the given soap request with the given key""" doc = etree.fromstring(envelope) body = get_body(doc) queue = SignQueue() queue.push_and_mark(body) security_node = ensure_security_header(doc, queue) security_token_node = create_binary_security_to...
Sign the given soap request with the given key
Below is the the instruction that describes the task: ### Input: Sign the given soap request with the given key ### Response: def sign_envelope(envelope, key_file): """Sign the given soap request with the given key""" doc = etree.fromstring(envelope) body = get_body(doc) queue = SignQueue() qu...
def from_tuples(cls, tups): """ Create a new IntervalTree from an iterable of 2- or 3-tuples, where the tuple lists begin, end, and optionally data. """ ivs = [Interval(*t) for t in tups] return IntervalTree(ivs)
Create a new IntervalTree from an iterable of 2- or 3-tuples, where the tuple lists begin, end, and optionally data.
Below is the the instruction that describes the task: ### Input: Create a new IntervalTree from an iterable of 2- or 3-tuples, where the tuple lists begin, end, and optionally data. ### Response: def from_tuples(cls, tups): """ Create a new IntervalTree from an iterable of 2- or 3-tuples, ...
def fuse(args): """ %prog fuse *.bed *.anchors Fuse gene orders based on anchors file. """ from jcvi.algorithms.graph import BiGraph p = OptionParser(fuse.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) bedfiles = [x for x in args i...
%prog fuse *.bed *.anchors Fuse gene orders based on anchors file.
Below is the the instruction that describes the task: ### Input: %prog fuse *.bed *.anchors Fuse gene orders based on anchors file. ### Response: def fuse(args): """ %prog fuse *.bed *.anchors Fuse gene orders based on anchors file. """ from jcvi.algorithms.graph import BiGraph p = O...
def sample(self, model, num_samples, epsilon, lmin=1, lmax=1, thin=1, burn=0, session=None, initialize=True, anchor=True, logprobs=True): """ A straight-forward HMC implementation. The mass matrix is assumed to be the identity. The gpflow mod...
A straight-forward HMC implementation. The mass matrix is assumed to be the identity. The gpflow model must implement `build_objective` method to build `f` function (tensor) which in turn based on model's internal trainable parameters `x`. f(x) = E(x) we then generate samp...
Below is the the instruction that describes the task: ### Input: A straight-forward HMC implementation. The mass matrix is assumed to be the identity. The gpflow model must implement `build_objective` method to build `f` function (tensor) which in turn based on model's internal trainable pa...
def get(cls, rkey): """Get image previously registered with key rkey. If key not exist, raise StockImageException """ if rkey in cls._cached: logger.info('Resource %s is in cache.' % rkey) return cls._cached[rkey] if rkey in cls._stock: img = ...
Get image previously registered with key rkey. If key not exist, raise StockImageException
Below is the the instruction that describes the task: ### Input: Get image previously registered with key rkey. If key not exist, raise StockImageException ### Response: def get(cls, rkey): """Get image previously registered with key rkey. If key not exist, raise StockImageException ...
def _add_field(self, field_type, name, value): """Adds a new field to a specified dictionary. The field is also added as a process attribute. field_type can be 'input', 'diagnostics' """ try: self.__getattribute__(field_type).update({name: value}) except: raise Va...
Adds a new field to a specified dictionary. The field is also added as a process attribute. field_type can be 'input', 'diagnostics'
Below is the the instruction that describes the task: ### Input: Adds a new field to a specified dictionary. The field is also added as a process attribute. field_type can be 'input', 'diagnostics' ### Response: def _add_field(self, field_type, name, value): """Adds a new field to a specified dicti...
def language(l): ''' Use this as a decorator (implicitly or explicitly). ''' # Usage: @language('en') or function = language('en')(function) def decorator(f): ''' Decorator used to prepend the language as an argument. ''' @wraps(f) def wrapper(*args, **kwargs): return f(l, *args, **kwargs) return wrapp...
Use this as a decorator (implicitly or explicitly).
Below is the the instruction that describes the task: ### Input: Use this as a decorator (implicitly or explicitly). ### Response: def language(l): ''' Use this as a decorator (implicitly or explicitly). ''' # Usage: @language('en') or function = language('en')(function) def decorator(f): ''' Decorator used...
def _init_metadata(self): """stub""" QuestionFilesFormRecord._init_metadata(self) FirstAngleProjectionFormRecord._init_metadata(self) super(MultiChoiceOrthoQuestionFormRecord, self)._init_metadata()
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def _init_metadata(self): """stub""" QuestionFilesFormRecord._init_metadata(self) FirstAngleProjectionFormRecord._init_metadata(self) super(MultiChoiceOrthoQuestionFormRecord, self)._init_metadata()
def _zip_with_scalars(args): """Zips across args in order and replaces non-iterables with repeats.""" zipped = [] for arg in args: if isinstance(arg, prettytensor.PrettyTensor): zipped.append(arg if arg.is_sequence() else itertools.repeat(arg)) elif (isinstance(arg, collections.Sequence) and ...
Zips across args in order and replaces non-iterables with repeats.
Below is the the instruction that describes the task: ### Input: Zips across args in order and replaces non-iterables with repeats. ### Response: def _zip_with_scalars(args): """Zips across args in order and replaces non-iterables with repeats.""" zipped = [] for arg in args: if isinstance(arg, prettyten...
def get_list_class(context, list): """ Returns the class to use for the passed in list. We just build something up from the object type for the list. """ return "list_%s_%s" % (list.model._meta.app_label, list.model._meta.model_name)
Returns the class to use for the passed in list. We just build something up from the object type for the list.
Below is the the instruction that describes the task: ### Input: Returns the class to use for the passed in list. We just build something up from the object type for the list. ### Response: def get_list_class(context, list): """ Returns the class to use for the passed in list. We just build something...
def make_main_index(struct, selection='"Protein"', ndx='main.ndx', oldndx=None): """Make index file with the special groups. This routine adds the group __main__ and the group __environment__ to the end of the index file. __main__ contains what the user defines as the *central* and *most important* par...
Make index file with the special groups. This routine adds the group __main__ and the group __environment__ to the end of the index file. __main__ contains what the user defines as the *central* and *most important* parts of the system. __environment__ is everything else. The template mdp file, fo...
Below is the the instruction that describes the task: ### Input: Make index file with the special groups. This routine adds the group __main__ and the group __environment__ to the end of the index file. __main__ contains what the user defines as the *central* and *most important* parts of the syste...
def transcode(self, source, destinations, **kwargs): """ Changes the compression characteristics of an audio and/or video stream. Allows you to change the resolution of a source stream, change the bitrate of a stream, change a VP8 or MPEG2 stream into H.264 and much more. Allow u...
Changes the compression characteristics of an audio and/or video stream. Allows you to change the resolution of a source stream, change the bitrate of a stream, change a VP8 or MPEG2 stream into H.264 and much more. Allow users to create overlays on the final stream as well as crop strea...
Below is the the instruction that describes the task: ### Input: Changes the compression characteristics of an audio and/or video stream. Allows you to change the resolution of a source stream, change the bitrate of a stream, change a VP8 or MPEG2 stream into H.264 and much more. Allow users...
def debug_text_screen(self, text: str, pos: Union[Point2, Point3, tuple, list], color=None, size: int = 8): """ Draws a text on the screen with coordinates 0 <= x, y <= 1. Don't forget to add 'await self._client.send_debug'. """ assert len(pos) >= 2 assert 0 <= pos[0] <= 1 assert 0 <= po...
Draws a text on the screen with coordinates 0 <= x, y <= 1. Don't forget to add 'await self._client.send_debug'.
Below is the the instruction that describes the task: ### Input: Draws a text on the screen with coordinates 0 <= x, y <= 1. Don't forget to add 'await self._client.send_debug'. ### Response: def debug_text_screen(self, text: str, pos: Union[Point2, Point3, tuple, list], color=None, size: int = 8): """ Dra...
def resizeEvent(self, event): """ Handles a resize event for this overlay, centering the central widget if one is found. :param event | <QtCore.QEvent> """ super(XOverlayWidget, self).resizeEvent(event) self.adjustSize()
Handles a resize event for this overlay, centering the central widget if one is found. :param event | <QtCore.QEvent>
Below is the the instruction that describes the task: ### Input: Handles a resize event for this overlay, centering the central widget if one is found. :param event | <QtCore.QEvent> ### Response: def resizeEvent(self, event): """ Handles a resize event for this overlay, cente...
def convert_to_int(value): """Attempts to convert a specified value to an integer :param value: Content to be converted into an integer :type value: string or int """ if not value: return None # Apart from numbers also accept values that end with px if isinstance(value, str): ...
Attempts to convert a specified value to an integer :param value: Content to be converted into an integer :type value: string or int
Below is the the instruction that describes the task: ### Input: Attempts to convert a specified value to an integer :param value: Content to be converted into an integer :type value: string or int ### Response: def convert_to_int(value): """Attempts to convert a specified value to an integer :pa...
def write_name (self, url_data): """Write url_data.name.""" args = (self.part("name"), cgi.escape(url_data.name)) self.writeln(u"<tr><td>%s</td><td>`%s'</td></tr>" % args)
Write url_data.name.
Below is the the instruction that describes the task: ### Input: Write url_data.name. ### Response: def write_name (self, url_data): """Write url_data.name.""" args = (self.part("name"), cgi.escape(url_data.name)) self.writeln(u"<tr><td>%s</td><td>`%s'</td></tr>" % args)
def print_name_version(self): """ Print program name and version and exit. :rtype: int """ if self.use_sys: self.print_generic(u"%s v%s" % (self.NAME, aeneas_version)) return self.exit(self.HELP_EXIT_CODE)
Print program name and version and exit. :rtype: int
Below is the the instruction that describes the task: ### Input: Print program name and version and exit. :rtype: int ### Response: def print_name_version(self): """ Print program name and version and exit. :rtype: int """ if self.use_sys: self.print_ge...
def duration(self): """ The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010). """ self._check_ps() rstar = self.system.central.radius k = self.r/rstar dur = self.period / np.pi arg = rstar/self.a * np.s...
The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010).
Below is the the instruction that describes the task: ### Input: The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010). ### Response: def duration(self): """ The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) ...
def add_petabencana_layer(self): """Add petabencana layer to the map. This uses the PetaBencana API to fetch the latest floods in JK. See https://data.petabencana.id/floods """ from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog dialog = PetaBencanaDialog(se...
Add petabencana layer to the map. This uses the PetaBencana API to fetch the latest floods in JK. See https://data.petabencana.id/floods
Below is the the instruction that describes the task: ### Input: Add petabencana layer to the map. This uses the PetaBencana API to fetch the latest floods in JK. See https://data.petabencana.id/floods ### Response: def add_petabencana_layer(self): """Add petabencana layer to the map. ...
def setAuthLevel(self, level_uri, level, alias=None): """Set the value for the given auth level type. @param level: string representation of an authentication level valid for level_uri @param alias: An optional namespace alias for the given auth level URI. May be omitte...
Set the value for the given auth level type. @param level: string representation of an authentication level valid for level_uri @param alias: An optional namespace alias for the given auth level URI. May be omitted if the alias is not significant. The library will u...
Below is the the instruction that describes the task: ### Input: Set the value for the given auth level type. @param level: string representation of an authentication level valid for level_uri @param alias: An optional namespace alias for the given auth level URI. May be om...
def _get_choices(self): """ Redefine standard method. """ if not self._choices: self._choices = tuple( (x.name, getattr(x, 'verbose_name', x.name) or x.name) for x in self.choices_class.constants() ) return self._choices
Redefine standard method.
Below is the the instruction that describes the task: ### Input: Redefine standard method. ### Response: def _get_choices(self): """ Redefine standard method. """ if not self._choices: self._choices = tuple( (x.name, getattr(x, 'verbose_name', x.name) or ...
def find_links_to(links, node): """Find links to a node. :param links: forward links of a workflow :type links: Mapping[NodeId, Set[(NodeId, ArgumentType, [int|str]])] :param node: index to a node :type node: int :returns: dictionary of sources for each argument :r...
Find links to a node. :param links: forward links of a workflow :type links: Mapping[NodeId, Set[(NodeId, ArgumentType, [int|str]])] :param node: index to a node :type node: int :returns: dictionary of sources for each argument :rtype: Mapping[(ArgumentType, [int|str])...
Below is the the instruction that describes the task: ### Input: Find links to a node. :param links: forward links of a workflow :type links: Mapping[NodeId, Set[(NodeId, ArgumentType, [int|str]])] :param node: index to a node :type node: int :returns: dictionary of so...
def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canon...
Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com
Below is the the instruction that describes the task: ### Input: Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canon...
def setGridPen( self, gridPen ): """ Sets the pen that will be used when drawing the grid lines. :param gridPen | <QtGui.QPen> || <QtGui.QColor> """ delegate = self.itemDelegate() if ( isinstance(delegate, XTreeWidgetDelegate) ): delegate...
Sets the pen that will be used when drawing the grid lines. :param gridPen | <QtGui.QPen> || <QtGui.QColor>
Below is the the instruction that describes the task: ### Input: Sets the pen that will be used when drawing the grid lines. :param gridPen | <QtGui.QPen> || <QtGui.QColor> ### Response: def setGridPen( self, gridPen ): """ Sets the pen that will be used when drawing the g...
def merge(self, other): """Merges non-default options from :obj:`other`, replacing existing values. This operation can be thought of as somewhat similar to compositing other onto options with the operation of :obj:`OVER <OPERATOR_OVER>`. """ cairo.cairo_font_opti...
Merges non-default options from :obj:`other`, replacing existing values. This operation can be thought of as somewhat similar to compositing other onto options with the operation of :obj:`OVER <OPERATOR_OVER>`.
Below is the the instruction that describes the task: ### Input: Merges non-default options from :obj:`other`, replacing existing values. This operation can be thought of as somewhat similar to compositing other onto options with the operation of :obj:`OVER <OPERATOR_OVER>`. ### Resp...
def import_object(name): """ Import module and return object from it. *name* is :class:`str` in format ``module.path.ObjectClass``. :: >>> import_command('module.path.ObjectClass') <class 'module.path.ObjectClass'> """ parts = name.split('.') if len(parts) < 2: raise...
Import module and return object from it. *name* is :class:`str` in format ``module.path.ObjectClass``. :: >>> import_command('module.path.ObjectClass') <class 'module.path.ObjectClass'>
Below is the the instruction that describes the task: ### Input: Import module and return object from it. *name* is :class:`str` in format ``module.path.ObjectClass``. :: >>> import_command('module.path.ObjectClass') <class 'module.path.ObjectClass'> ### Response: def import_object(name): ...
def _product(shape) -> Iterator[Tuple[int, ...]]: """Should return all "subdevice index combinations" for sequences with arbitrary dimensions: >>> from hydpy.core.netcdftools import NetCDFVariableFlat >>> _product = NetCDFVariableFlat.__dict__['_product'].__func__ >>> for comb i...
Should return all "subdevice index combinations" for sequences with arbitrary dimensions: >>> from hydpy.core.netcdftools import NetCDFVariableFlat >>> _product = NetCDFVariableFlat.__dict__['_product'].__func__ >>> for comb in _product([1, 2, 3]): ... print(comb) (0...
Below is the the instruction that describes the task: ### Input: Should return all "subdevice index combinations" for sequences with arbitrary dimensions: >>> from hydpy.core.netcdftools import NetCDFVariableFlat >>> _product = NetCDFVariableFlat.__dict__['_product'].__func__ >>> fo...
def node_filter(self, name, **kwargs): """ Returns a decorator function for adding a node filter. Args: name (str): The name of the filter. **kwargs: Variable keyword arguments for the filter. Returns: Callable[[Callable[[Element, Any], bool]]]: A de...
Returns a decorator function for adding a node filter. Args: name (str): The name of the filter. **kwargs: Variable keyword arguments for the filter. Returns: Callable[[Callable[[Element, Any], bool]]]: A decorator function for adding a node filter.
Below is the the instruction that describes the task: ### Input: Returns a decorator function for adding a node filter. Args: name (str): The name of the filter. **kwargs: Variable keyword arguments for the filter. Returns: Callable[[Callable[[Element, Any], boo...
def djfrontend_normalize(version=None): """ Returns Normalize CSS file. Included in HTML5 Boilerplate. """ if version is None: version = getattr(settings, 'DJFRONTEND_NORMALIZE', DJFRONTEND_NORMALIZE_DEFAULT) return format_html( '<link rel="stylesheet" href="{0}djfrontend/css/no...
Returns Normalize CSS file. Included in HTML5 Boilerplate.
Below is the the instruction that describes the task: ### Input: Returns Normalize CSS file. Included in HTML5 Boilerplate. ### Response: def djfrontend_normalize(version=None): """ Returns Normalize CSS file. Included in HTML5 Boilerplate. """ if version is None: version = getattr(...
def get_attribute_data(attr_ids, node_ids, **kwargs): """ For a given attribute or set of attributes, return all the resources and resource scenarios in the network """ node_attrs = db.DBSession.query(ResourceAttr).\ options(joinedload_all('attr')...
For a given attribute or set of attributes, return all the resources and resource scenarios in the network
Below is the the instruction that describes the task: ### Input: For a given attribute or set of attributes, return all the resources and resource scenarios in the network ### Response: def get_attribute_data(attr_ids, node_ids, **kwargs): """ For a given attribute or set of attributes, return...
def get_easter_monday(self, year): "Return the date of the monday after easter" sunday = self.get_easter_sunday(year) return sunday + timedelta(days=1)
Return the date of the monday after easter
Below is the the instruction that describes the task: ### Input: Return the date of the monday after easter ### Response: def get_easter_monday(self, year): "Return the date of the monday after easter" sunday = self.get_easter_sunday(year) return sunday + timedelta(days=1)
def fit(self, fitfunction, parinit, unfittableparameters=(), *args, **kwargs): """Perform a nonlinear least-squares fit, using sastool.misc.fitter.Fitter() Other arguments and keyword arguments will be passed through to the __init__ method of Fitter. For example, these are: - lbounds ...
Perform a nonlinear least-squares fit, using sastool.misc.fitter.Fitter() Other arguments and keyword arguments will be passed through to the __init__ method of Fitter. For example, these are: - lbounds - ubounds - ytransform - loss - method Returns: the...
Below is the the instruction that describes the task: ### Input: Perform a nonlinear least-squares fit, using sastool.misc.fitter.Fitter() Other arguments and keyword arguments will be passed through to the __init__ method of Fitter. For example, these are: - lbounds - ubounds ...
def trim_ordered_range_list(ranges,start,finish): """A function to help with slicing a mapping Start with a list of ranges and get another list of ranges constrained by start (0-indexed) and finish (1-indexed) :param ranges: ordered non-overlapping ranges on the same chromosome :param start: start 0-i...
A function to help with slicing a mapping Start with a list of ranges and get another list of ranges constrained by start (0-indexed) and finish (1-indexed) :param ranges: ordered non-overlapping ranges on the same chromosome :param start: start 0-indexed :param finish: ending 1-indexed :type ...
Below is the the instruction that describes the task: ### Input: A function to help with slicing a mapping Start with a list of ranges and get another list of ranges constrained by start (0-indexed) and finish (1-indexed) :param ranges: ordered non-overlapping ranges on the same chromosome :param st...
def send_msg(self, message): """Send a SLIP-encoded message over the stream. :param bytes message: The message to encode and send """ packet = self.driver.send(message) self.send_bytes(packet)
Send a SLIP-encoded message over the stream. :param bytes message: The message to encode and send
Below is the the instruction that describes the task: ### Input: Send a SLIP-encoded message over the stream. :param bytes message: The message to encode and send ### Response: def send_msg(self, message): """Send a SLIP-encoded message over the stream. :param bytes message: The message t...
def redraw(self): """ Redraw the Vispy canvas """ if self._multiscat is not None: self._multiscat._update() self.vispy_widget.canvas.update()
Redraw the Vispy canvas
Below is the the instruction that describes the task: ### Input: Redraw the Vispy canvas ### Response: def redraw(self): """ Redraw the Vispy canvas """ if self._multiscat is not None: self._multiscat._update() self.vispy_widget.canvas.update()
def format_errors(self, errors, many): """Format validation errors as JSON Error objects.""" if not errors: return {} if isinstance(errors, (list, tuple)): return {'errors': errors} formatted_errors = [] if many: for index, errors in iteritems...
Format validation errors as JSON Error objects.
Below is the the instruction that describes the task: ### Input: Format validation errors as JSON Error objects. ### Response: def format_errors(self, errors, many): """Format validation errors as JSON Error objects.""" if not errors: return {} if isinstance(errors, (list, tuple...
def get_or_create_ec2_instance(name=None, group=None, release=None, verbose=0, backend_opts=None): """ Creates a new EC2 instance. You should normally run get_or_create() instead of directly calling this. """ from burlap.common import shelf, OrderedDict from boto.exception import EC2ResponseErr...
Creates a new EC2 instance. You should normally run get_or_create() instead of directly calling this.
Below is the the instruction that describes the task: ### Input: Creates a new EC2 instance. You should normally run get_or_create() instead of directly calling this. ### Response: def get_or_create_ec2_instance(name=None, group=None, release=None, verbose=0, backend_opts=None): """ Creates a new EC2 ...
def _read(self, ti, try_number, metadata=None): """ Read logs of given task instance and try_number from Wasb remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from ...
Read logs of given task instance and try_number from Wasb remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from :param metadata: log metadata, can be ...
Below is the the instruction that describes the task: ### Input: Read logs of given task instance and try_number from Wasb remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from ...
def update_links_and_ffts(self): """FFT (856) Dealing with files.""" for field in record_get_field_instances(self.record, tag='856', ind1='4'): subs = field_get_subfields(field) newsub...
FFT (856) Dealing with files.
Below is the the instruction that describes the task: ### Input: FFT (856) Dealing with files. ### Response: def update_links_and_ffts(self): """FFT (856) Dealing with files.""" for field in record_get_field_instances(self.record, tag='856', ...
def _extract_and_reconstruct_as_path(self, update_msg): """Extracts advertised AS path attributes in the given update message and reconstructs AS_PATH from AS_PATH and AS4_PATH if needed.""" umsg_pattrs = update_msg.pathattr_map as_aggregator = umsg_pattrs.get(BGP_ATTR_TYPE_AGGREGATOR, ...
Extracts advertised AS path attributes in the given update message and reconstructs AS_PATH from AS_PATH and AS4_PATH if needed.
Below is the the instruction that describes the task: ### Input: Extracts advertised AS path attributes in the given update message and reconstructs AS_PATH from AS_PATH and AS4_PATH if needed. ### Response: def _extract_and_reconstruct_as_path(self, update_msg): """Extracts advertised AS path attr...
def is_course_run_enrollable(course_run): """ Return true if the course run is enrollable, false otherwise. We look for the following criteria: - end is greater than now OR null - enrollment_start is less than now OR null - enrollment_end is greater than now OR null """ now = datetime.d...
Return true if the course run is enrollable, false otherwise. We look for the following criteria: - end is greater than now OR null - enrollment_start is less than now OR null - enrollment_end is greater than now OR null
Below is the the instruction that describes the task: ### Input: Return true if the course run is enrollable, false otherwise. We look for the following criteria: - end is greater than now OR null - enrollment_start is less than now OR null - enrollment_end is greater than now OR null ### Response:...
def experiment_pb( hparam_infos, metric_infos, user='', description='', time_created_secs=None): """Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. ...
Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. metric_infos: Array of api_pb2.MetricInfo messages. Describes the metrics used in the experiment. See the document...
Below is the the instruction that describes the task: ### Input: Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. metric_infos: Array of api_pb2.MetricInfo messages. D...
def _calculateCoverageMasks(proteindb, peptidedb): """Calcualte the sequence coverage masks for all proteindb elements. Private method used by :class:`ProteinDatabase`. A coverage mask is a numpy boolean array with the length of the protein sequence. Each protein position that has been ...
Calcualte the sequence coverage masks for all proteindb elements. Private method used by :class:`ProteinDatabase`. A coverage mask is a numpy boolean array with the length of the protein sequence. Each protein position that has been covered in at least one peptide is set to True. Covera...
Below is the the instruction that describes the task: ### Input: Calcualte the sequence coverage masks for all proteindb elements. Private method used by :class:`ProteinDatabase`. A coverage mask is a numpy boolean array with the length of the protein sequence. Each protein position that ha...
def _copy_future_state(source, dest): """Internal helper to copy state from another Future. The other Future may be a concurrent.futures.Future. """ assert source.done() if dest.cancelled(): return assert not dest.done() if source.cancelled(): dest.cancel() else: ...
Internal helper to copy state from another Future. The other Future may be a concurrent.futures.Future.
Below is the the instruction that describes the task: ### Input: Internal helper to copy state from another Future. The other Future may be a concurrent.futures.Future. ### Response: def _copy_future_state(source, dest): """Internal helper to copy state from another Future. The other Future may be a co...
def get_daily(self, date=None): """ Get time entries for a date (defaults to today). """ if date == None: return self.get("/daily.json") url = "/daily/{}/{}/{}.json".format(date.year, date.month, date.day) return self.get(url)
Get time entries for a date (defaults to today).
Below is the the instruction that describes the task: ### Input: Get time entries for a date (defaults to today). ### Response: def get_daily(self, date=None): """ Get time entries for a date (defaults to today). """ if date == None: return self.get("/daily.json") ...
def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) return qc
Returns a circuit putting 2 qubits in the Bell state.
Below is the the instruction that describes the task: ### Input: Returns a circuit putting 2 qubits in the Bell state. ### Response: def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc...
def geo2mag(incoord): """geographic coordinate to magnetic coordinate (coarse): Parameters ---------- incoord : numpy.array of shape (2,*) array([[glat0,glat1,glat2,...],[glon0,glon1,glon2,...]), where glat, glon are geographic latitude and longitude (or if you have only one po...
geographic coordinate to magnetic coordinate (coarse): Parameters ---------- incoord : numpy.array of shape (2,*) array([[glat0,glat1,glat2,...],[glon0,glon1,glon2,...]), where glat, glon are geographic latitude and longitude (or if you have only one point it is [[glat,glon]]). ...
Below is the the instruction that describes the task: ### Input: geographic coordinate to magnetic coordinate (coarse): Parameters ---------- incoord : numpy.array of shape (2,*) array([[glat0,glat1,glat2,...],[glon0,glon1,glon2,...]), where glat, glon are geographic latitude and longi...
def callback_save_poly(): '''Perform polyfit once regions selected Globals: cal_fname, data (read-only, so no declaration) ''' import datetime import pylleo import yamlord import itertools def _check_param_regions(param, regions, cal_dict): msg = ''' <b>{}</b> was...
Perform polyfit once regions selected Globals: cal_fname, data (read-only, so no declaration)
Below is the the instruction that describes the task: ### Input: Perform polyfit once regions selected Globals: cal_fname, data (read-only, so no declaration) ### Response: def callback_save_poly(): '''Perform polyfit once regions selected Globals: cal_fname, data (read-only, so no declaration) '...
def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret
Load the response from json data, return the dictionary or raw text
Below is the the instruction that describes the task: ### Input: Load the response from json data, return the dictionary or raw text ### Response: def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(res...
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. """ AXU = self.AX + self.U Y0 = (self.rho*(self.block_sep0(AXU) - self.S)) / (self.W**2 + self.rho) Y1 = self.Pcn(self.block_...
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.
Below is the the instruction that describes the task: ### Input: r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. ### Response: def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. """ AXU = self.AX + self.U Y0 ...
def _acquire_request_connection(self, request): '''Return a connection.''' host = request.url_info.hostname port = request.url_info.port use_ssl = request.url_info.scheme == 'https' tunnel = request.url_info.scheme != 'http' connection = yield from self._acquire_connecti...
Return a connection.
Below is the the instruction that describes the task: ### Input: Return a connection. ### Response: def _acquire_request_connection(self, request): '''Return a connection.''' host = request.url_info.hostname port = request.url_info.port use_ssl = request.url_info.scheme == 'https' ...
def generate(self): """Return a generator that yields pieces of XML.""" # atom demands either an author element in every entry or a global one if not self.author: if False in map(lambda e: bool(e.author), self.entries): self.author = ({'name': u'unbekannter Autor'},) ...
Return a generator that yields pieces of XML.
Below is the the instruction that describes the task: ### Input: Return a generator that yields pieces of XML. ### Response: def generate(self): """Return a generator that yields pieces of XML.""" # atom demands either an author element in every entry or a global one if not self.author: ...
def persistent_write(self, address, byte, refresh_config=False): ''' Write a single byte to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). byte : int Value to write to address. ...
Write a single byte to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). byte : int Value to write to address. refresh_config : bool, optional Is ``True``, :meth:`load_config()` i...
Below is the the instruction that describes the task: ### Input: Write a single byte to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). byte : int Value to write to address. refresh_con...
def load_feedback(): """ Open existing feedback file """ result = {} if os.path.exists(_feedback_file): f = open(_feedback_file, 'r') cont = f.read() f.close() else: cont = '{}' try: result = json.loads(cont) if cont else {} except ValueError as e: ...
Open existing feedback file
Below is the the instruction that describes the task: ### Input: Open existing feedback file ### Response: def load_feedback(): """ Open existing feedback file """ result = {} if os.path.exists(_feedback_file): f = open(_feedback_file, 'r') cont = f.read() f.close() else: ...
def set_search_url(self, url): """ Reads given query string and stores key-value tuples :param url: A string containing a valid URL to parse arguments from """ if url[0] == '?': url = url[1:] self.arguments = {} for key, value in parse_qs(url).items(): ...
Reads given query string and stores key-value tuples :param url: A string containing a valid URL to parse arguments from
Below is the the instruction that describes the task: ### Input: Reads given query string and stores key-value tuples :param url: A string containing a valid URL to parse arguments from ### Response: def set_search_url(self, url): """ Reads given query string and stores key-value tuples :...
async def start_monitoring(self): """Start monitoring for interesting events.""" data = generate_query( b'\x7F\x01\xDC\x99\x80\x00\x04\x00\x00\x00\x00\x00\x00') await self._send_data(data) resp = await self._read_data() if resp is None: _LOGGER.warning("...
Start monitoring for interesting events.
Below is the the instruction that describes the task: ### Input: Start monitoring for interesting events. ### Response: async def start_monitoring(self): """Start monitoring for interesting events.""" data = generate_query( b'\x7F\x01\xDC\x99\x80\x00\x04\x00\x00\x00\x00\x00\x00') ...
def _restore(self, builder): """ The restore extension. :param builder: The query builder :type builder: orator.orm.builder.Builder """ builder.with_trashed() return builder.update({builder.get_model().get_deleted_at_column(): None})
The restore extension. :param builder: The query builder :type builder: orator.orm.builder.Builder
Below is the the instruction that describes the task: ### Input: The restore extension. :param builder: The query builder :type builder: orator.orm.builder.Builder ### Response: def _restore(self, builder): """ The restore extension. :param builder: The query builder ...
def from_str(cls, label: str) -> int: """ Convert given string label of decay type to special index Args: label: name of decay type. Set of values: `"linear"`, `"cosine"`, `"exponential"`, `"onecycle"`, `"trapezoid"`, `["polynomial", K]`, where K is ...
Convert given string label of decay type to special index Args: label: name of decay type. Set of values: `"linear"`, `"cosine"`, `"exponential"`, `"onecycle"`, `"trapezoid"`, `["polynomial", K]`, where K is a polynomial power Returns: index of ...
Below is the the instruction that describes the task: ### Input: Convert given string label of decay type to special index Args: label: name of decay type. Set of values: `"linear"`, `"cosine"`, `"exponential"`, `"onecycle"`, `"trapezoid"`, `["polynomial", K]`, ...
def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1., sep:str=' ', decoder=decode_spec_tokens): "Return the `n_words` that come after `text` using beam search." ds = self.data.single_dl.dataset self.model.reset() ...
Return the `n_words` that come after `text` using beam search.
Below is the the instruction that describes the task: ### Input: Return the `n_words` that come after `text` using beam search. ### Response: def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1., sep:str=' ', decoder=decode_spec_tok...
def insert_table(self, label = None, name = None, **kwargs): """ Insert a table in the Survey object """ data_frame = kwargs.pop('data_frame', None) if data_frame is None: data_frame = kwargs.pop('dataframe', None) to_hdf_kwargs = kwargs.pop('to_hdf_kwargs',...
Insert a table in the Survey object
Below is the the instruction that describes the task: ### Input: Insert a table in the Survey object ### Response: def insert_table(self, label = None, name = None, **kwargs): """ Insert a table in the Survey object """ data_frame = kwargs.pop('data_frame', None) if data_fr...
def components_for_entity(self, entity: int) -> Tuple[C, ...]: """Retrieve all Components for a specific Entity, as a Tuple. Retrieve all Components for a specific Entity. The method is probably not appropriate to use in your Processors, but might be useful for saving state, or passing ...
Retrieve all Components for a specific Entity, as a Tuple. Retrieve all Components for a specific Entity. The method is probably not appropriate to use in your Processors, but might be useful for saving state, or passing specific Components between World instances. Unlike most other met...
Below is the the instruction that describes the task: ### Input: Retrieve all Components for a specific Entity, as a Tuple. Retrieve all Components for a specific Entity. The method is probably not appropriate to use in your Processors, but might be useful for saving state, or passing speci...