code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def alpha(self, x, y, kwargs, k=None): """ deflection angles :param x: x-position (preferentially arcsec) :type x: numpy array :param y: y-position (preferentially arcsec) :type y: numpy array :param kwargs: list of keyword arguments of lens model parameters matc...
deflection angles :param x: x-position (preferentially arcsec) :type x: numpy array :param y: y-position (preferentially arcsec) :type y: numpy array :param kwargs: list of keyword arguments of lens model parameters matching the lens model classes :param k: only evaluate...
Below is the the instruction that describes the task: ### Input: deflection angles :param x: x-position (preferentially arcsec) :type x: numpy array :param y: y-position (preferentially arcsec) :type y: numpy array :param kwargs: list of keyword arguments of lens model param...
def microsoft(self, key, x86=False): """ Return key in Microsoft software registry. Parameters ---------- key: str Registry key path where look. x86: str Force x86 software registry. Return ------ str: value """ ...
Return key in Microsoft software registry. Parameters ---------- key: str Registry key path where look. x86: str Force x86 software registry. Return ------ str: value
Below is the the instruction that describes the task: ### Input: Return key in Microsoft software registry. Parameters ---------- key: str Registry key path where look. x86: str Force x86 software registry. Return ------ str: value ##...
def get(self, wheel=False): """Downloads the package from PyPI. Returns: Full path of the downloaded file. Raises: PermissionError if the save_dir is not writable. """ try: url = get_url(self.client, self.name, self.version, ...
Downloads the package from PyPI. Returns: Full path of the downloaded file. Raises: PermissionError if the save_dir is not writable.
Below is the the instruction that describes the task: ### Input: Downloads the package from PyPI. Returns: Full path of the downloaded file. Raises: PermissionError if the save_dir is not writable. ### Response: def get(self, wheel=False): """Downloads the package fr...
def check_engine(handle): """Check availability of requested template engine.""" if handle == 'help': dump_engines() sys.exit(0) if handle not in engines.engines: print('Engine "%s" is not available.' % (handle,), file=sys.stderr) sys.exit(1)
Check availability of requested template engine.
Below is the the instruction that describes the task: ### Input: Check availability of requested template engine. ### Response: def check_engine(handle): """Check availability of requested template engine.""" if handle == 'help': dump_engines() sys.exit(0) if handle not in engines.engi...
def get_model(client, model_id): """Sample ID: go/samples-tracker/1510""" # [START bigquery_get_model] from google.cloud import bigquery # TODO(developer): Construct a BigQuery client object. # client = bigquery.Client() # TODO(developer): Set model_id to the ID of the model to fetch. # m...
Sample ID: go/samples-tracker/1510
Below is the the instruction that describes the task: ### Input: Sample ID: go/samples-tracker/1510 ### Response: def get_model(client, model_id): """Sample ID: go/samples-tracker/1510""" # [START bigquery_get_model] from google.cloud import bigquery # TODO(developer): Construct a BigQuery client...
def _download_sdss_image( self): """*download sdss image* """ self.log.info('starting the ``_download_sdss_image`` method') opt = "" if self.grid: opt += "G" if self.label: opt += "L" if self.photocat: opt += "P" ...
*download sdss image*
Below is the the instruction that describes the task: ### Input: *download sdss image* ### Response: def _download_sdss_image( self): """*download sdss image* """ self.log.info('starting the ``_download_sdss_image`` method') opt = "" if self.grid: op...
def get(self, requirement): """ Get a distribution archive from any of the available caches. :param requirement: A :class:`.Requirement` object. :returns: The absolute pathname of a local file or :data:`None` when the distribution archive is missing from all available ...
Get a distribution archive from any of the available caches. :param requirement: A :class:`.Requirement` object. :returns: The absolute pathname of a local file or :data:`None` when the distribution archive is missing from all available caches.
Below is the the instruction that describes the task: ### Input: Get a distribution archive from any of the available caches. :param requirement: A :class:`.Requirement` object. :returns: The absolute pathname of a local file or :data:`None` when the distribution archive is missin...
def _find_files(self): """Find files recursively in the root path using provided extensions. :return: list of absolute file paths """ files = [] for ext in self.extensions: ext_files = util.find_files(self.root, "*" + ext) log.debug("found {} '*{}...
Find files recursively in the root path using provided extensions. :return: list of absolute file paths
Below is the the instruction that describes the task: ### Input: Find files recursively in the root path using provided extensions. :return: list of absolute file paths ### Response: def _find_files(self): """Find files recursively in the root path using provided extensions. ...
def get_enumerations_from_bit_mask(enumeration, mask): """ A utility function that creates a list of enumeration values from a bit mask for a specific mask enumeration class. Args: enumeration (class): The enumeration class from which to draw enumeration values. mask (int): ...
A utility function that creates a list of enumeration values from a bit mask for a specific mask enumeration class. Args: enumeration (class): The enumeration class from which to draw enumeration values. mask (int): The bit mask from which to identify enumeration values. Return...
Below is the the instruction that describes the task: ### Input: A utility function that creates a list of enumeration values from a bit mask for a specific mask enumeration class. Args: enumeration (class): The enumeration class from which to draw enumeration values. mask (int)...
def create(self, fullname, shortname, category_id, **kwargs): """ Create a new course :param string fullname: The course's fullname :param string shortname: The course's shortname :param int category_id: The course's category :keyword string idnumber: (optional) Course ...
Create a new course :param string fullname: The course's fullname :param string shortname: The course's shortname :param int category_id: The course's category :keyword string idnumber: (optional) Course ID number. \ Yes, it's a string, blame Moodle. :keyword int su...
Below is the the instruction that describes the task: ### Input: Create a new course :param string fullname: The course's fullname :param string shortname: The course's shortname :param int category_id: The course's category :keyword string idnumber: (optional) Course ID number. \ ...
def _extract_packages(self): """ Extract a package in a new directory. """ if not hasattr(self, "retrieved_packages_unpacked"): self.retrieved_packages_unpacked = [self.package_name] for path in self.retrieved_packages_unpacked: package_name = basename(pat...
Extract a package in a new directory.
Below is the the instruction that describes the task: ### Input: Extract a package in a new directory. ### Response: def _extract_packages(self): """ Extract a package in a new directory. """ if not hasattr(self, "retrieved_packages_unpacked"): self.retrieved_packages_un...
def do_commits(self): """ Perform len(MARKED_DAYS)*self.max_commits and Push to the Repository """ git_clone_command = "git clone " + str(self.git_repo_url) subprocess.call(git_clone_command, shell=True) subprocess.check_call( ['touch', 'gitHeart.txt'], cw...
Perform len(MARKED_DAYS)*self.max_commits and Push to the Repository
Below is the the instruction that describes the task: ### Input: Perform len(MARKED_DAYS)*self.max_commits and Push to the Repository ### Response: def do_commits(self): """ Perform len(MARKED_DAYS)*self.max_commits and Push to the Repository """ git_clone_command = "git clone "...
def get_protein_coding_genes( path_or_buffer, include_polymorphic_pseudogenes=True, remove_duplicates=True, **kwargs): r"""Get list of all protein-coding genes based on Ensembl GTF file. Parameters ---------- See :func:`get_genes` function. Returns ------- ...
r"""Get list of all protein-coding genes based on Ensembl GTF file. Parameters ---------- See :func:`get_genes` function. Returns ------- `pandas.DataFrame` Table with rows corresponding to protein-coding genes.
Below is the the instruction that describes the task: ### Input: r"""Get list of all protein-coding genes based on Ensembl GTF file. Parameters ---------- See :func:`get_genes` function. Returns ------- `pandas.DataFrame` Table with rows corresponding to protein-coding genes. #...
def get_all_host_templates(resource_root, cluster_name="default"): """ Get all host templates in a cluster. @param cluster_name: Cluster name. @return: ApiList of ApiHostTemplate objects for all host templates in a cluster. @since: API v3 """ return call(resource_root.get, HOST_TEMPLATES_PATH % (clu...
Get all host templates in a cluster. @param cluster_name: Cluster name. @return: ApiList of ApiHostTemplate objects for all host templates in a cluster. @since: API v3
Below is the the instruction that describes the task: ### Input: Get all host templates in a cluster. @param cluster_name: Cluster name. @return: ApiList of ApiHostTemplate objects for all host templates in a cluster. @since: API v3 ### Response: def get_all_host_templates(resource_root, cluster_name="defaul...
def _init_metadata(self): """stub""" super(EulerRotationAnswerFormRecord, self)._init_metadata() self._euler_rotation_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'ang...
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def _init_metadata(self): """stub""" super(EulerRotationAnswerFormRecord, self)._init_metadata() self._euler_rotation_metadata = { 'element_id': Id(self.my_osid_object_form._authority, ...
def append(self, child, *args, **kwargs): """See :meth:`AbstractElement.append`""" #Accept Word instances instead of WordReference, references will be automagically used upon serialisation if isinstance(child, (Word, Morpheme, Phoneme)) and WordReference in self.ACCEPTED_DATA: #We do...
See :meth:`AbstractElement.append`
Below is the the instruction that describes the task: ### Input: See :meth:`AbstractElement.append` ### Response: def append(self, child, *args, **kwargs): """See :meth:`AbstractElement.append`""" #Accept Word instances instead of WordReference, references will be automagically used upon serialisat...
def convert_objects(self, convert_dates=True, convert_numeric=False, convert_timedeltas=True, copy=True): """ Attempt to infer better dtype for object columns. .. deprecated:: 0.21.0 Parameters ---------- convert_dates : boolean, default True ...
Attempt to infer better dtype for object columns. .. deprecated:: 0.21.0 Parameters ---------- convert_dates : boolean, default True If True, convert to date where possible. If 'coerce', force conversion, with unconvertible values becoming NaT. convert_n...
Below is the the instruction that describes the task: ### Input: Attempt to infer better dtype for object columns. .. deprecated:: 0.21.0 Parameters ---------- convert_dates : boolean, default True If True, convert to date where possible. If 'coerce', force ...
def conv(self, num_out_channels, k_height, k_width, d_height=1, d_width=1, mode="SAME", input_layer=None, num_channels_in=None, use_batch_norm=None, stddev=None, activation="rel...
Construct a conv2d layer on top of cnn.
Below is the the instruction that describes the task: ### Input: Construct a conv2d layer on top of cnn. ### Response: def conv(self, num_out_channels, k_height, k_width, d_height=1, d_width=1, mode="SAME", input_layer=None,...
def any_shared(enum_one, enum_two): ''' Truthy if any element in enum_one is present in enum_two ''' if not is_collection(enum_one) or not is_collection(enum_two): return False enum_one = enum_one if isinstance(enum_one, (set, dict)) else set(enum_one) enum_two = enum_two if isins...
Truthy if any element in enum_one is present in enum_two
Below is the the instruction that describes the task: ### Input: Truthy if any element in enum_one is present in enum_two ### Response: def any_shared(enum_one, enum_two): ''' Truthy if any element in enum_one is present in enum_two ''' if not is_collection(enum_one) or not is_collection(enum_t...
def string(self) -> bytes: """The capabilities string without the enclosing square brackets.""" if self._raw is not None: return self._raw self._raw = raw = BytesFormat(b' ').join( [b'CAPABILITY', b'IMAP4rev1'] + self.capabilities) return raw
The capabilities string without the enclosing square brackets.
Below is the the instruction that describes the task: ### Input: The capabilities string without the enclosing square brackets. ### Response: def string(self) -> bytes: """The capabilities string without the enclosing square brackets.""" if self._raw is not None: return self._raw ...
def register_hook(self, hook, priority='NORMAL'): """Register a hook into the hook list. Args: hook (:obj:`Hook`): The hook to be registered. priority (int or str or :obj:`Priority`): Hook priority. Lower value means higher priority. """ assert is...
Register a hook into the hook list. Args: hook (:obj:`Hook`): The hook to be registered. priority (int or str or :obj:`Priority`): Hook priority. Lower value means higher priority.
Below is the the instruction that describes the task: ### Input: Register a hook into the hook list. Args: hook (:obj:`Hook`): The hook to be registered. priority (int or str or :obj:`Priority`): Hook priority. Lower value means higher priority. ### Response: def re...
def parse_duration(duration): """Attepmts to parse an ISO8601 formatted ``duration``. Returns a ``datetime.timedelta`` object. """ duration = str(duration).upper().strip() elements = ELEMENTS.copy() for pattern in (SIMPLE_DURATION, COMBINED_DURATION): if pattern.match(duration): ...
Attepmts to parse an ISO8601 formatted ``duration``. Returns a ``datetime.timedelta`` object.
Below is the the instruction that describes the task: ### Input: Attepmts to parse an ISO8601 formatted ``duration``. Returns a ``datetime.timedelta`` object. ### Response: def parse_duration(duration): """Attepmts to parse an ISO8601 formatted ``duration``. Returns a ``datetime.timedelta`` object. ...
def run_radia_with_merge(job, rna_bam, tumor_bam, normal_bam, univ_options, radia_options): """ A wrapper for the the entire RADIA sub-graph. :param dict rna_bam: Dict dicts of bam and bai for tumor RNA-Seq obtained by running STAR within ProTECT. :param dict tumor_bam: Dict of bam and bai f...
A wrapper for the the entire RADIA sub-graph. :param dict rna_bam: Dict dicts of bam and bai for tumor RNA-Seq obtained by running STAR within ProTECT. :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq :param dict normal_bam: Dict of bam and bai for normal DNA-Seq :param dict univ...
Below is the the instruction that describes the task: ### Input: A wrapper for the the entire RADIA sub-graph. :param dict rna_bam: Dict dicts of bam and bai for tumor RNA-Seq obtained by running STAR within ProTECT. :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq :param dict no...
def uncomment(path, regex, char='#', backup='.bak'): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regu...
.. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the...
Below is the the instruction that describes the task: ### Input: .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Uncomment specified commented lines in a file path The full path to the file to be edited regex A regular expression used to find the lines ...
def _initialized_adjustments(self, prstGeom): """ Return an initialized list of adjustment values based on the contents of *prstGeom* """ if prstGeom is None: return [] davs = AutoShapeType.default_adjustment_values(prstGeom.prst) adjustments = [Adjust...
Return an initialized list of adjustment values based on the contents of *prstGeom*
Below is the the instruction that describes the task: ### Input: Return an initialized list of adjustment values based on the contents of *prstGeom* ### Response: def _initialized_adjustments(self, prstGeom): """ Return an initialized list of adjustment values based on the contents ...
def _structure_attr_from_tuple(self, a, name, value): """Handle an individual attrs attribute.""" type_ = a.type if type_ is None: # No type metadata. return value return self._structure_func.dispatch(type_)(value, type_)
Handle an individual attrs attribute.
Below is the the instruction that describes the task: ### Input: Handle an individual attrs attribute. ### Response: def _structure_attr_from_tuple(self, a, name, value): """Handle an individual attrs attribute.""" type_ = a.type if type_ is None: # No type metadata. ...
def ssl_required(allow_non_ssl=False): """ Views decorated with this will always get redirected to https except when allow_non_ssl is set to true. """ def wrapper(view_func): def _checkssl(request, *args, **kwargs): # allow_non_ssl=True lets non-https requests to come ...
Views decorated with this will always get redirected to https except when allow_non_ssl is set to true.
Below is the the instruction that describes the task: ### Input: Views decorated with this will always get redirected to https except when allow_non_ssl is set to true. ### Response: def ssl_required(allow_non_ssl=False): """ Views decorated with this will always get redirected to https except when...
def _caveat_v1_to_dict(c): ''' Return a caveat as a dictionary for export as the JSON macaroon v1 format. ''' serialized = {} if len(c.caveat_id) > 0: serialized['cid'] = c.caveat_id if c.verification_key_id: serialized['vid'] = utils.raw_urlsafe_b64encode( c.verifica...
Return a caveat as a dictionary for export as the JSON macaroon v1 format.
Below is the the instruction that describes the task: ### Input: Return a caveat as a dictionary for export as the JSON macaroon v1 format. ### Response: def _caveat_v1_to_dict(c): ''' Return a caveat as a dictionary for export as the JSON macaroon v1 format. ''' serialized = {} if len(c.ca...
def sweep(self, mode, speed=None): """Starts the output current sweep. :param mode: The sweep mode. Valid entries are `'UP'`, `'DOWN'`, `'PAUSE'`or `'ZERO'`. If in shim mode, `'LIMIT'` is valid as well. :param speed: The sweeping speed. Valid entries are `'FAST'`, `'SLOW'` ...
Starts the output current sweep. :param mode: The sweep mode. Valid entries are `'UP'`, `'DOWN'`, `'PAUSE'`or `'ZERO'`. If in shim mode, `'LIMIT'` is valid as well. :param speed: The sweeping speed. Valid entries are `'FAST'`, `'SLOW'` or `None`.
Below is the the instruction that describes the task: ### Input: Starts the output current sweep. :param mode: The sweep mode. Valid entries are `'UP'`, `'DOWN'`, `'PAUSE'`or `'ZERO'`. If in shim mode, `'LIMIT'` is valid as well. :param speed: The sweeping speed. Valid entries are `'FAS...
def cli(env, identifier, allocation, port, routing_type, routing_method): """Edit an existing load balancer service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) # check if any input is provided if not any([allocation, port, routing_t...
Edit an existing load balancer service group.
Below is the the instruction that describes the task: ### Input: Edit an existing load balancer service group. ### Response: def cli(env, identifier, allocation, port, routing_type, routing_method): """Edit an existing load balancer service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) loa...
def canonical_extension(fmt_ext): """ Canonical extension of file format extension Converts the format extension fmt_ext into the canonical extension for that format. For example, ``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value ...
Canonical extension of file format extension Converts the format extension fmt_ext into the canonical extension for that format. For example, ``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value :param fmt_ext: A string representing an ex...
Below is the the instruction that describes the task: ### Input: Canonical extension of file format extension Converts the format extension fmt_ext into the canonical extension for that format. For example, ``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for for...
def process_request( self, path: str, request_headers: Headers ) -> Union[Optional[HTTPResponse], Awaitable[Optional[HTTPResponse]]]: """ Intercept the HTTP request and return an HTTP response if needed. ``request_headers`` is a :class:`~websockets.http.Headers` instance. I...
Intercept the HTTP request and return an HTTP response if needed. ``request_headers`` is a :class:`~websockets.http.Headers` instance. If this method returns ``None``, the WebSocket handshake continues. If it returns a status code, headers and a response body, that HTTP response is sen...
Below is the the instruction that describes the task: ### Input: Intercept the HTTP request and return an HTTP response if needed. ``request_headers`` is a :class:`~websockets.http.Headers` instance. If this method returns ``None``, the WebSocket handshake continues. If it returns a status...
def order_id(self, order_id): """ Sets the order_id of this ChargeRequest. The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field. :param order_id: T...
Sets the order_id of this ChargeRequest. The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field. :param order_id: The order_id of this ChargeRequest. :type: ...
Below is the the instruction that describes the task: ### Input: Sets the order_id of this ChargeRequest. The ID of the order to associate with this transaction. If you provide this value, the `amount_money` value of your request must __exactly match__ the value of the order's `total_money` field. ...
def get_total_DOS(self): """Return frequency points and total DOS as a tuple. Returns ------- A tuple with (frequency_points, total_dos). frequency_points: ndarray shape=(frequency_sampling_points, ), dtype='double' total_dos: shape=(frequency_sa...
Return frequency points and total DOS as a tuple. Returns ------- A tuple with (frequency_points, total_dos). frequency_points: ndarray shape=(frequency_sampling_points, ), dtype='double' total_dos: shape=(frequency_sampling_points, ), dtype='double'
Below is the the instruction that describes the task: ### Input: Return frequency points and total DOS as a tuple. Returns ------- A tuple with (frequency_points, total_dos). frequency_points: ndarray shape=(frequency_sampling_points, ), dtype='double' total_dos...
def load_nameserver_credentials(self, working_directory, num_tries=60, interval=1): """ loads the nameserver credentials in cases where master and workers share a filesystem Parameters ---------- working_directory: str the working directory for the HPB run (see master) num_tries: int number of at...
loads the nameserver credentials in cases where master and workers share a filesystem Parameters ---------- working_directory: str the working directory for the HPB run (see master) num_tries: int number of attempts to find the file (default 60) interval: float waiting period between the attem...
Below is the the instruction that describes the task: ### Input: loads the nameserver credentials in cases where master and workers share a filesystem Parameters ---------- working_directory: str the working directory for the HPB run (see master) num_tries: int number of attempts to find the file...
def _postQueuedEvents(self, interval=0.01): """Private method to post queued events (e.g. Quartz events). Each event in queue is a tuple (event call, args to event call). """ while len(self.eventList) > 0: (nextEvent, args) = self.eventList.popleft() nextEvent(*a...
Private method to post queued events (e.g. Quartz events). Each event in queue is a tuple (event call, args to event call).
Below is the the instruction that describes the task: ### Input: Private method to post queued events (e.g. Quartz events). Each event in queue is a tuple (event call, args to event call). ### Response: def _postQueuedEvents(self, interval=0.01): """Private method to post queued events (e.g. Quart...
def get_paginator(self, operation_name): """Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is ``create_foo``, and you'd...
Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is ``create_foo``, and you'd normally invoke the operation as ``clie...
Below is the the instruction that describes the task: ### Input: Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is ``create...
def iterate_storyline(ctx): """ iterate the last storyline from the last visited story part :param ctx: :return: """ logger.debug('# start iterate') compiled_story = ctx.compiled_story() if not compiled_story: return for step in range(ctx.current_step(), ...
iterate the last storyline from the last visited story part :param ctx: :return:
Below is the the instruction that describes the task: ### Input: iterate the last storyline from the last visited story part :param ctx: :return: ### Response: def iterate_storyline(ctx): """ iterate the last storyline from the last visited story part :param ctx: :return: """ logg...
def frac(x, context=None): """ Return the fractional part of ``x``. The result has the same sign as ``x``. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_frac, (BigFloat._implicit_convert(x),), context, )
Return the fractional part of ``x``. The result has the same sign as ``x``.
Below is the the instruction that describes the task: ### Input: Return the fractional part of ``x``. The result has the same sign as ``x``. ### Response: def frac(x, context=None): """ Return the fractional part of ``x``. The result has the same sign as ``x``. """ return _apply_function...
def error(self, error): """ set the error """ # TODO: check length with value? # TODO: type checks (similar to value) if self.direction not in ['x', 'y', 'z'] and error is not None: raise ValueError("error only accepted for x, y, z dimensions") if isi...
set the error
Below is the the instruction that describes the task: ### Input: set the error ### Response: def error(self, error): """ set the error """ # TODO: check length with value? # TODO: type checks (similar to value) if self.direction not in ['x', 'y', 'z'] and error is no...
def create_server_and_run_forever(self, loop=None, **server_config): """ Helper function which constructs an HTTP server and listens the loop forever. This function exists only to remove boilerplate code for starting up a growler app. Args: **server_config: ...
Helper function which constructs an HTTP server and listens the loop forever. This function exists only to remove boilerplate code for starting up a growler app. Args: **server_config: These keyword arguments are forwarded directly to the BaseEventLoop.creat...
Below is the the instruction that describes the task: ### Input: Helper function which constructs an HTTP server and listens the loop forever. This function exists only to remove boilerplate code for starting up a growler app. Args: **server_config: These keyword argume...
def fromutc(self, dt): "datetime in UTC -> datetime in local time." if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") dtoff = dt.utcoffset() if d...
datetime in UTC -> datetime in local time.
Below is the the instruction that describes the task: ### Input: datetime in UTC -> datetime in local time. ### Response: def fromutc(self, dt): "datetime in UTC -> datetime in local time." if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") ...
def l2_regularizer(weight=1.0, scope=None): """Define a L2 regularizer. Args: weight: scale the loss by this factor. scope: Optional scope for name_scope. Returns: a regularizer function. """ def regularizer(tensor): with tf.name_scope(scope, 'L2Regularizer', [tensor]): l2_weight = tf....
Define a L2 regularizer. Args: weight: scale the loss by this factor. scope: Optional scope for name_scope. Returns: a regularizer function.
Below is the the instruction that describes the task: ### Input: Define a L2 regularizer. Args: weight: scale the loss by this factor. scope: Optional scope for name_scope. Returns: a regularizer function. ### Response: def l2_regularizer(weight=1.0, scope=None): """Define a L2 regularizer. ...
def _get_columns(self, blueprint): """ Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint :rtype: list """ columns = [] for column in blueprint.get_added_columns(): sql = self.wrap(column) + '...
Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint :rtype: list
Below is the the instruction that describes the task: ### Input: Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint :rtype: list ### Response: def _get_columns(self, blueprint): """ Get the blueprint's columns definitions. ...
def reset(self): """set sensible defaults""" self.start = 1 self.count = None self.end = None self.stride = 1 self.format = "%d"
set sensible defaults
Below is the the instruction that describes the task: ### Input: set sensible defaults ### Response: def reset(self): """set sensible defaults""" self.start = 1 self.count = None self.end = None self.stride = 1 self.format = "%d"
def load_from_config(cp, model, **kwargs): """Loads a sampler from the given config file. This looks for a name in the section ``[sampler]`` to determine which sampler class to load. That sampler's ``from_config`` is then called. Parameters ---------- cp : WorkflowConfigParser Config p...
Loads a sampler from the given config file. This looks for a name in the section ``[sampler]`` to determine which sampler class to load. That sampler's ``from_config`` is then called. Parameters ---------- cp : WorkflowConfigParser Config parser to read from. model : pycbc.inference.mo...
Below is the the instruction that describes the task: ### Input: Loads a sampler from the given config file. This looks for a name in the section ``[sampler]`` to determine which sampler class to load. That sampler's ``from_config`` is then called. Parameters ---------- cp : WorkflowConfigPars...
def to_bytes(value, encoding='utf-8'): """Converts a string value to bytes, if necessary. Unfortunately, ``six.b`` is insufficient for this task since in Python 2 because it does not modify ``unicode`` objects. Args: value (Union[str, bytes]): The value to be converted. encoding (str):...
Converts a string value to bytes, if necessary. Unfortunately, ``six.b`` is insufficient for this task since in Python 2 because it does not modify ``unicode`` objects. Args: value (Union[str, bytes]): The value to be converted. encoding (str): The encoding to use to convert unicode to byt...
Below is the the instruction that describes the task: ### Input: Converts a string value to bytes, if necessary. Unfortunately, ``six.b`` is insufficient for this task since in Python 2 because it does not modify ``unicode`` objects. Args: value (Union[str, bytes]): The value to be converted. ...
def GetFileEntryByPath(self, path): """Retrieves a file entry for a path. Args: path (str): path of the file entry. Returns: FakeFileEntry: a file entry or None if not available. """ if path is None: return None file_entry_type, _ = self._paths.get(path, (None, None)) if...
Retrieves a file entry for a path. Args: path (str): path of the file entry. Returns: FakeFileEntry: a file entry or None if not available.
Below is the the instruction that describes the task: ### Input: Retrieves a file entry for a path. Args: path (str): path of the file entry. Returns: FakeFileEntry: a file entry or None if not available. ### Response: def GetFileEntryByPath(self, path): """Retrieves a file entry for a pa...
def find_default_container(builder, # type: HasReqsHints default_container=None, # type: Text use_biocontainers=None, # type: bool ): # type: (...) -> Optional[Text] """Default finder for default containers.""" ...
Default finder for default containers.
Below is the the instruction that describes the task: ### Input: Default finder for default containers. ### Response: def find_default_container(builder, # type: HasReqsHints default_container=None, # type: Text use_biocontainers=None, # typ...
def observableFractionCMDX(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the sam...
Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the same as mask.restrictCatalogToObservable space. However, for technical reasons it ...
Below is the the instruction that describes the task: ### Input: Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the same as mask.restrictCatal...
def risearch(self): "instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials" if self._risearch is None: self._risearch = ResourceIndex(self.fedora_root, self.username, self.password) return self._risearch
instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials
Below is the the instruction that describes the task: ### Input: instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials ### Response: def risearch(self): "instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials" if self._risearch is...
def set_log_level(logger_name: str, log_level: str, propagate: bool = False): """Set the log level of the specified logger.""" log = logging.getLogger(logger_name) log.propagate = propagate log.setLevel(log_level)
Set the log level of the specified logger.
Below is the the instruction that describes the task: ### Input: Set the log level of the specified logger. ### Response: def set_log_level(logger_name: str, log_level: str, propagate: bool = False): """Set the log level of the specified logger.""" log = logging.getLogger(logger_name) log.propagate = p...
def _gen_last_current_relation(self, post_id): ''' Generate the relation for the post and last post viewed. ''' last_post_id = self.get_secure_cookie('last_post_uid') if last_post_id: last_post_id = last_post_id.decode('utf-8') self.set_secure_cookie('last_pos...
Generate the relation for the post and last post viewed.
Below is the the instruction that describes the task: ### Input: Generate the relation for the post and last post viewed. ### Response: def _gen_last_current_relation(self, post_id): ''' Generate the relation for the post and last post viewed. ''' last_post_id = self.get_secure_cook...
def allLayers(self): """ returns all layers for the service """ url = self._url + "/layers" params = { "f" : "json" } res = self._get(url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._p...
returns all layers for the service
Below is the the instruction that describes the task: ### Input: returns all layers for the service ### Response: def allLayers(self): """ returns all layers for the service """ url = self._url + "/layers" params = { "f" : "json" } res = self._get(url, param_dict...
def torrents(self, **filters): """ Returns a list of torrents matching the supplied filters. :param filter: Current status of the torrents. :param category: Fetch all torrents with the supplied label. :param sort: Sort torrents by. :param reverse: Enable reverse sorting....
Returns a list of torrents matching the supplied filters. :param filter: Current status of the torrents. :param category: Fetch all torrents with the supplied label. :param sort: Sort torrents by. :param reverse: Enable reverse sorting. :param limit: Limit the number of torrents...
Below is the the instruction that describes the task: ### Input: Returns a list of torrents matching the supplied filters. :param filter: Current status of the torrents. :param category: Fetch all torrents with the supplied label. :param sort: Sort torrents by. :param reverse: Enabl...
def get_nice_alert(self, value): """Return the alert relative to the Nice configuration list""" value = str(value) try: if value in self.get_limit('nice_critical'): return 'CRITICAL' except KeyError: pass try: if value in self.g...
Return the alert relative to the Nice configuration list
Below is the the instruction that describes the task: ### Input: Return the alert relative to the Nice configuration list ### Response: def get_nice_alert(self, value): """Return the alert relative to the Nice configuration list""" value = str(value) try: if value in self.get_li...
def tag(self, tokens): """Return a list of (token, tag) tuples for a given list of tokens.""" tags = [] for token in tokens: normalized = self.lexicon[token].normalized for regex, tag in self.regexes: if regex.match(normalized): tags.ap...
Return a list of (token, tag) tuples for a given list of tokens.
Below is the the instruction that describes the task: ### Input: Return a list of (token, tag) tuples for a given list of tokens. ### Response: def tag(self, tokens): """Return a list of (token, tag) tuples for a given list of tokens.""" tags = [] for token in tokens: normalized...
def _station_load(network, station, crit_stations): """ Checks for over-loading of stations. Parameters ---------- network : :class:`~.grid.network.Network` station : :class:`~.grid.components.LVStation` or :class:`~.grid.components.MVStation` crit_stations : :pandas:`pandas.DataFrame<dataf...
Checks for over-loading of stations. Parameters ---------- network : :class:`~.grid.network.Network` station : :class:`~.grid.components.LVStation` or :class:`~.grid.components.MVStation` crit_stations : :pandas:`pandas.DataFrame<dataframe>` Dataframe containing over-loaded stations, their ...
Below is the the instruction that describes the task: ### Input: Checks for over-loading of stations. Parameters ---------- network : :class:`~.grid.network.Network` station : :class:`~.grid.components.LVStation` or :class:`~.grid.components.MVStation` crit_stations : :pandas:`pandas.DataFrame<...
def executeMetricsQuery(self, tmaster, queryString, start_time, end_time, callback=None): """ Get the specified metrics for the given query in this topology. Returns the following dict on success: { "timeline": [{ "instance": <instance>, "data": { <start_time> : <numeric ...
Get the specified metrics for the given query in this topology. Returns the following dict on success: { "timeline": [{ "instance": <instance>, "data": { <start_time> : <numeric value>, <start_time> : <numeric value>, ... } }, { ... ...
Below is the the instruction that describes the task: ### Input: Get the specified metrics for the given query in this topology. Returns the following dict on success: { "timeline": [{ "instance": <instance>, "data": { <start_time> : <numeric value>, <start_time> : ...
def prepare(self): """Log access.""" request_time = 1000.0 * self.request.request_time() access_log.info( "%d %s %.2fms", self.get_status(), self._request_summary(), request_time)
Log access.
Below is the the instruction that describes the task: ### Input: Log access. ### Response: def prepare(self): """Log access.""" request_time = 1000.0 * self.request.request_time() access_log.info( "%d %s %.2fms", self.get_status(), self._request_summary(), reque...
def p_ind8_I(p): """ reg8_I : LP IX PLUS expr RP | LP IX MINUS expr RP | LP IY PLUS expr RP | LP IY MINUS expr RP | LP IX PLUS pexpr RP | LP IX MINUS pexpr RP | LP IY PLUS pexpr RP | LP IY MINUS pexpr RP ...
reg8_I : LP IX PLUS expr RP | LP IX MINUS expr RP | LP IY PLUS expr RP | LP IY MINUS expr RP | LP IX PLUS pexpr RP | LP IX MINUS pexpr RP | LP IY PLUS pexpr RP | LP IY MINUS pexpr RP
Below is the the instruction that describes the task: ### Input: reg8_I : LP IX PLUS expr RP | LP IX MINUS expr RP | LP IY PLUS expr RP | LP IY MINUS expr RP | LP IX PLUS pexpr RP | LP IX MINUS pexpr RP | LP IY PLUS pexpr RP ...
def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) if not vm_size: raise SaltCloudNotFound('No size specified for this VM.') i...
Return the VM's size. Used by create_node().
Below is the the instruction that describes the task: ### Input: Return the VM's size. Used by create_node(). ### Response: def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, _...
def build(values): ''' Parameters ---------- values: [term, ...] Returns ------- IndexStore ''' idxstore = IndexStore() idxstore._i2val = list(values) idxstore._val2i = {term:i for i,term in enumerate(values)} idxstore._next_i = len(values) return idxstore
Parameters ---------- values: [term, ...] Returns ------- IndexStore
Below is the the instruction that describes the task: ### Input: Parameters ---------- values: [term, ...] Returns ------- IndexStore ### Response: def build(values): ''' Parameters ---------- values: [term, ...] Returns ------- IndexStore ''' idxstore = IndexStore() idxstore._i2val...
def query_relative(self, query, event_time=None, relative_duration_before=None, relative_duration_after=None): """Perform the query and calculate the time range based on the relative values.""" assert event_time is None or isinstance(event_time, datetime.datetime) assert relative_duration_before...
Perform the query and calculate the time range based on the relative values.
Below is the the instruction that describes the task: ### Input: Perform the query and calculate the time range based on the relative values. ### Response: def query_relative(self, query, event_time=None, relative_duration_before=None, relative_duration_after=None): """Perform the query and calculate the t...
def delete_date(self, date): """ Remove the date line from the textual representation. This doesn't remove any entry line. """ self.lines = [ line for line in self.lines if not isinstance(line, DateLine) or line.date != date ] self.lines =...
Remove the date line from the textual representation. This doesn't remove any entry line.
Below is the the instruction that describes the task: ### Input: Remove the date line from the textual representation. This doesn't remove any entry line. ### Response: def delete_date(self, date): """ Remove the date line from the textual representation. This doesn't remove any ent...
def update_from_sam(self, sam, sam_reader): '''Updates graph info from a pysam.AlignedSegment object''' if sam.is_unmapped \ or sam.mate_is_unmapped \ or (sam.reference_id == sam.next_reference_id): return new_link = link.Link(sam, sam_reader, self.ref_lengths) ...
Updates graph info from a pysam.AlignedSegment object
Below is the the instruction that describes the task: ### Input: Updates graph info from a pysam.AlignedSegment object ### Response: def update_from_sam(self, sam, sam_reader): '''Updates graph info from a pysam.AlignedSegment object''' if sam.is_unmapped \ or sam.mate_is_unmapped \ ...
def build_kcorrection_array( log, redshiftArray, snTypesArray, snLightCurves, pathToOutputDirectory, plot=True): """ *Given the random redshiftArray and snTypeArray, generate a dictionary of k-correction polynomials (one for each filter) for every object.* **...
*Given the random redshiftArray and snTypeArray, generate a dictionary of k-correction polynomials (one for each filter) for every object.* **Key Arguments:** - ``log`` -- logger - ``redshiftArray`` -- the pre-generated redshift array - ``snTypesArray`` -- the pre-generated array of random ...
Below is the the instruction that describes the task: ### Input: *Given the random redshiftArray and snTypeArray, generate a dictionary of k-correction polynomials (one for each filter) for every object.* **Key Arguments:** - ``log`` -- logger - ``redshiftArray`` -- the pre-generated redshift a...
def list_users(app, appbuilder): """ List all users on the database """ _appbuilder = import_application(app, appbuilder) echo_header("List of users") for user in _appbuilder.sm.get_all_users(): click.echo( "username:{0} | email:{1} | role:{2}".format( use...
List all users on the database
Below is the the instruction that describes the task: ### Input: List all users on the database ### Response: def list_users(app, appbuilder): """ List all users on the database """ _appbuilder = import_application(app, appbuilder) echo_header("List of users") for user in _appbuilder.sm...
def get_user_roles(user): """Get a list of a users's roles.""" if user: groups = user.groups.all() # Important! all() query may be cached on User with prefetch_related. roles = (RolesManager.retrieve_role(group.name) for group in groups if group.name in RolesManager.get_roles_names()) ...
Get a list of a users's roles.
Below is the the instruction that describes the task: ### Input: Get a list of a users's roles. ### Response: def get_user_roles(user): """Get a list of a users's roles.""" if user: groups = user.groups.all() # Important! all() query may be cached on User with prefetch_related. roles = (R...
def env(): """Verify NVME variables and construct exported variables""" if cij.ssh.env(): cij.err("cij.nvme.env: invalid SSH environment") return 1 nvme = cij.env_to_dict(PREFIX, REQUIRED) nvme["DEV_PATH"] = os.path.join("/dev", nvme["DEV_NAME"]) # get version, chunks, luns and c...
Verify NVME variables and construct exported variables
Below is the the instruction that describes the task: ### Input: Verify NVME variables and construct exported variables ### Response: def env(): """Verify NVME variables and construct exported variables""" if cij.ssh.env(): cij.err("cij.nvme.env: invalid SSH environment") return 1 nvm...
def get(self, timeout=None): # type: (float) -> T """Return the result or raise the error the function has produced""" self.wait(timeout) if isinstance(self._result, Exception): raise self._result return self._result
Return the result or raise the error the function has produced
Below is the the instruction that describes the task: ### Input: Return the result or raise the error the function has produced ### Response: def get(self, timeout=None): # type: (float) -> T """Return the result or raise the error the function has produced""" self.wait(timeout) if ...
def has_edge_evidence(self, u: BaseEntity, v: BaseEntity, key: str) -> bool: """Check if the given edge has an evidence.""" return self._has_edge_attr(u, v, key, EVIDENCE)
Check if the given edge has an evidence.
Below is the the instruction that describes the task: ### Input: Check if the given edge has an evidence. ### Response: def has_edge_evidence(self, u: BaseEntity, v: BaseEntity, key: str) -> bool: """Check if the given edge has an evidence.""" return self._has_edge_attr(u, v, key, EVIDENCE)
def process_request(self, req, resp): """ Process the request before routing it. We always enforce the use of SSL. """ if goldman.config.TLS_REQUIRED and req.protocol != 'https': abort(TLSRequired)
Process the request before routing it. We always enforce the use of SSL.
Below is the the instruction that describes the task: ### Input: Process the request before routing it. We always enforce the use of SSL. ### Response: def process_request(self, req, resp): """ Process the request before routing it. We always enforce the use of SSL. """ i...
def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor: """ Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match. """ if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb: raise ValueError('Incompatibly vectors. Qubits and rank must ma...
Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match.
Below is the the instruction that describes the task: ### Input: Hilbert-Schmidt inner product between qubit vectors The tensor rank and qubits must match. ### Response: def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor: """ Hilbert-Schmidt inner product between qubit vectors The...
def block_matrix(A, B, C, D): r"""Generate the operator matrix with quadrants .. math:: \begin{pmatrix} A B \\ C D \end{pmatrix} Args: A (Matrix): Matrix of shape ``(n, m)`` B (Matrix): Matrix of shape ``(n, k)`` C (Matrix): Matrix of shape ``(l, m)`` D (Matrix): Ma...
r"""Generate the operator matrix with quadrants .. math:: \begin{pmatrix} A B \\ C D \end{pmatrix} Args: A (Matrix): Matrix of shape ``(n, m)`` B (Matrix): Matrix of shape ``(n, k)`` C (Matrix): Matrix of shape ``(l, m)`` D (Matrix): Matrix of shape ``(l, k)`` Retu...
Below is the the instruction that describes the task: ### Input: r"""Generate the operator matrix with quadrants .. math:: \begin{pmatrix} A B \\ C D \end{pmatrix} Args: A (Matrix): Matrix of shape ``(n, m)`` B (Matrix): Matrix of shape ``(n, k)`` C (Matrix): Matrix of shap...
def exam_reliability_by_datetime( datetime_axis, datetime_new_axis, reliable_distance): """A datetime-version that takes datetime object list as x_axis reliable_distance equals to the time difference in seconds. """ numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in date...
A datetime-version that takes datetime object list as x_axis reliable_distance equals to the time difference in seconds.
Below is the the instruction that describes the task: ### Input: A datetime-version that takes datetime object list as x_axis reliable_distance equals to the time difference in seconds. ### Response: def exam_reliability_by_datetime( datetime_axis, datetime_new_axis, reliable_distance): """A dateti...
def openBiocamFile(filename, verbose=False): """Open a Biocam hdf5 file, read and return the recording info, pick te correct method to access raw data, and return this to the caller.""" rf = h5py.File(filename, 'r') # Read recording variables recVars = rf.require_group('3BRecInfo/3BRecVars/') # bitD...
Open a Biocam hdf5 file, read and return the recording info, pick te correct method to access raw data, and return this to the caller.
Below is the the instruction that describes the task: ### Input: Open a Biocam hdf5 file, read and return the recording info, pick te correct method to access raw data, and return this to the caller. ### Response: def openBiocamFile(filename, verbose=False): """Open a Biocam hdf5 file, read and return the reco...
def compile_dependencies(self, sourcepath, include_self=False): """ Apply compile on all dependencies Args: sourcepath (string): Sass source path to compile to its destination using project settings. Keyword Arguments: include_self (bool): If ``T...
Apply compile on all dependencies Args: sourcepath (string): Sass source path to compile to its destination using project settings. Keyword Arguments: include_self (bool): If ``True`` the given sourcepath is add to items to compile, else only its...
Below is the the instruction that describes the task: ### Input: Apply compile on all dependencies Args: sourcepath (string): Sass source path to compile to its destination using project settings. Keyword Arguments: include_self (bool): If ``True`` the given...
def pop_object(self, element): ''' Pop the object element if the object contains an higher TLP then allowed. ''' redacted_text = "Redacted. Object contained TLP value higher than allowed." element['id'] = '' element['url'] = '' element['type'] = '' eleme...
Pop the object element if the object contains an higher TLP then allowed.
Below is the the instruction that describes the task: ### Input: Pop the object element if the object contains an higher TLP then allowed. ### Response: def pop_object(self, element): ''' Pop the object element if the object contains an higher TLP then allowed. ''' redacted_text = ...
def run(self, subdirectory=None): """ Write out project file and run GSSHA simulation """ with tmp_chdir(self.gssha_directory): if self.hotstart_minimal_mode: # remove all optional output cards for gssha_optional_output_card in self.GSSHA_OPTIO...
Write out project file and run GSSHA simulation
Below is the the instruction that describes the task: ### Input: Write out project file and run GSSHA simulation ### Response: def run(self, subdirectory=None): """ Write out project file and run GSSHA simulation """ with tmp_chdir(self.gssha_directory): if self.hotstart...
def add_tileset(self, tileset): """ Add a tileset to the map :param tileset: TiledTileset """ assert (isinstance(tileset, TiledTileset)) self.tilesets.append(tileset)
Add a tileset to the map :param tileset: TiledTileset
Below is the the instruction that describes the task: ### Input: Add a tileset to the map :param tileset: TiledTileset ### Response: def add_tileset(self, tileset): """ Add a tileset to the map :param tileset: TiledTileset """ assert (isinstance(tileset, TiledTileset)) ...
def audio_visual_key(name=None): """ Creates the grammar for an Audio Visual Key code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field """ if name is None: name = 'AVI Field' societ...
Creates the grammar for an Audio Visual Key code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field
Below is the the instruction that describes the task: ### Input: Creates the grammar for an Audio Visual Key code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field ### Response: def audio_visual_key(name=Non...
def report_by_year(self, summary_fct=None, years=None, ltd=1, prior_n_yrs=None, first_n_yrs=None, ranges=None, bm_rets=None): """Summarize the profit and loss by year :param summary_fct: function(ProfitAndLoss) and returns a dict or Series :param years: int, array, boolean...
Summarize the profit and loss by year :param summary_fct: function(ProfitAndLoss) and returns a dict or Series :param years: int, array, boolean or None. If boolean and False, then show no years. If int or array show only those years, else show all years if None :param ltd:...
Below is the the instruction that describes the task: ### Input: Summarize the profit and loss by year :param summary_fct: function(ProfitAndLoss) and returns a dict or Series :param years: int, array, boolean or None. If boolean and False, then show no years. If int or array s...
def down(self, migration_id): """Rollback to migration.""" if not self.check_directory(): return for migration in self.get_migrations_to_down(migration_id): logger.info('Rollback migration %s' % migration.filename) migration_module = self.load_migration_file...
Rollback to migration.
Below is the the instruction that describes the task: ### Input: Rollback to migration. ### Response: def down(self, migration_id): """Rollback to migration.""" if not self.check_directory(): return for migration in self.get_migrations_to_down(migration_id): logger....
def _get_timestamp(dirname_full, remove): """ Get the timestamp from the timestamp file. Optionally mark it for removal if we're going to write another one. """ record_filename = os.path.join(dirname_full, RECORD_FILENAME) if not os.path.exists(record_filename): return None mtime ...
Get the timestamp from the timestamp file. Optionally mark it for removal if we're going to write another one.
Below is the the instruction that describes the task: ### Input: Get the timestamp from the timestamp file. Optionally mark it for removal if we're going to write another one. ### Response: def _get_timestamp(dirname_full, remove): """ Get the timestamp from the timestamp file. Optionally mark it...
def humanize_filesize(bytes_size): """Returns human readable filesize. :param int bytes_size: :rtype: str """ if not bytes_size: return '0 B' names = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB') name_idx = int(math.floor(math.log(bytes_size, 1024))) size = round(b...
Returns human readable filesize. :param int bytes_size: :rtype: str
Below is the the instruction that describes the task: ### Input: Returns human readable filesize. :param int bytes_size: :rtype: str ### Response: def humanize_filesize(bytes_size): """Returns human readable filesize. :param int bytes_size: :rtype: str """ if not bytes_size: r...
def _onNavigate(self, index): '''Handle selection of path segment.''' if index > 0: self.setLocation( self._locationWidget.itemData(index), interactive=True )
Handle selection of path segment.
Below is the the instruction that describes the task: ### Input: Handle selection of path segment. ### Response: def _onNavigate(self, index): '''Handle selection of path segment.''' if index > 0: self.setLocation( self._locationWidget.itemData(index), interactive=True ...
def evalsha(self, sha, numkeys, *keys_and_args): """Emulates evalsha""" if not self.script_exists(sha)[0]: raise RedisError("Sha not registered") script_callable = Script(self, self.shas[sha], self.load_lua_dependencies) numkeys = max(numkeys, 0) keys = keys_and_args[...
Emulates evalsha
Below is the the instruction that describes the task: ### Input: Emulates evalsha ### Response: def evalsha(self, sha, numkeys, *keys_and_args): """Emulates evalsha""" if not self.script_exists(sha)[0]: raise RedisError("Sha not registered") script_callable = Script(self, self.s...
def handle(self, request_headers={}, signature_header=None): """Handle request.""" if self.client.webhook_secret is None: raise ValueError('Error: no webhook secret.') encoded_header = self._get_signature_header(signature_header, request_headers) decoded_request = self._decod...
Handle request.
Below is the the instruction that describes the task: ### Input: Handle request. ### Response: def handle(self, request_headers={}, signature_header=None): """Handle request.""" if self.client.webhook_secret is None: raise ValueError('Error: no webhook secret.') encoded_header =...
def _compute_magnitude_scaling_term(self, C, mag): """ Compute and return magnitude scaling term in equation 2, page 970. """ c1 = self.CONSTS['c1'] if mag <= c1: return C['b1'] + C['b2'] * (mag - c1) + C['b3'] * (8.5 - mag) ** 2 else: ...
Compute and return magnitude scaling term in equation 2, page 970.
Below is the the instruction that describes the task: ### Input: Compute and return magnitude scaling term in equation 2, page 970. ### Response: def _compute_magnitude_scaling_term(self, C, mag): """ Compute and return magnitude scaling term in equation 2, page 970. ""...
def random_sn_types_array( log, sampleNumber, relativeSNRates, pathToOutputPlotDirectory, plot=False): """ *Generate random supernova types from the weighted distributions set in the simulation settings file* **Key Arguments:** - ``log`` -- logger - `...
*Generate random supernova types from the weighted distributions set in the simulation settings file* **Key Arguments:** - ``log`` -- logger - ``sampleNumber`` -- the sample number, i.e. array size - ``relativeSNRates`` -- dictionary of the rates - ``pathToOutputPlotDirectory`` -- p...
Below is the the instruction that describes the task: ### Input: *Generate random supernova types from the weighted distributions set in the simulation settings file* **Key Arguments:** - ``log`` -- logger - ``sampleNumber`` -- the sample number, i.e. array size - ``relativeSNRates`` --...
def generate_or_fail(self): """ Attempts to generate a random acyclic graph, raising an InvariantError if unable to. """ t1 = self.generate_random_table() t2 = self.generate_random_table() f1 = self.generate_func(t1) f2 = self.generate_func(t2) ed...
Attempts to generate a random acyclic graph, raising an InvariantError if unable to.
Below is the the instruction that describes the task: ### Input: Attempts to generate a random acyclic graph, raising an InvariantError if unable to. ### Response: def generate_or_fail(self): """ Attempts to generate a random acyclic graph, raising an InvariantError if unable to. ...
def get(cls, uni_char): """Return the Unicode block of the given Unicode character""" uni_char = unicod(uni_char) # Force to Unicode code_point = ord(uni_char) if Block._RANGE_KEYS is None: Block._RANGE_KEYS = sorted(Block._RANGES.keys()) idx = bisect.bisect_left(Blo...
Return the Unicode block of the given Unicode character
Below is the the instruction that describes the task: ### Input: Return the Unicode block of the given Unicode character ### Response: def get(cls, uni_char): """Return the Unicode block of the given Unicode character""" uni_char = unicod(uni_char) # Force to Unicode code_point = ord(uni_c...
def is_interface_up(interface): """ Checks if an interface is up. :param interface: interface name :returns: boolean """ if sys.platform.startswith("linux"): if interface not in psutil.net_if_addrs(): return False import fcntl SIOCGIFFLAGS = 0x8913 ...
Checks if an interface is up. :param interface: interface name :returns: boolean
Below is the the instruction that describes the task: ### Input: Checks if an interface is up. :param interface: interface name :returns: boolean ### Response: def is_interface_up(interface): """ Checks if an interface is up. :param interface: interface name :returns: boolean """ ...
def delete(self, storagemodel:object, modeldefinition = None) -> bool: """ delete the blob from storage """ deleted = False blobservice = modeldefinition['blobservice'] container_name = modeldefinition['container'] blob_name = storagemodel.name try: if blobs...
delete the blob from storage
Below is the the instruction that describes the task: ### Input: delete the blob from storage ### Response: def delete(self, storagemodel:object, modeldefinition = None) -> bool: """ delete the blob from storage """ deleted = False blobservice = modeldefinition['blobservice'] conta...
def x(self, position=None): """Set/Get actor position along x axis.""" p = self.GetPosition() if position is None: return p[0] self.SetPosition(position, p[1], p[2]) if self.trail: self.updateTrail() return self
Set/Get actor position along x axis.
Below is the the instruction that describes the task: ### Input: Set/Get actor position along x axis. ### Response: def x(self, position=None): """Set/Get actor position along x axis.""" p = self.GetPosition() if position is None: return p[0] self.SetPosition(position, p...
def players(self, postgame, game_type): """Return parsed players.""" for i, attributes in self._players(): yield self._parse_player(i, attributes, postgame, game_type)
Return parsed players.
Below is the the instruction that describes the task: ### Input: Return parsed players. ### Response: def players(self, postgame, game_type): """Return parsed players.""" for i, attributes in self._players(): yield self._parse_player(i, attributes, postgame, game_type)
def _hash_outputs(self, index, sighash_type): '''BIP143 hashOutputs implementation Args: index (int): index of input being signed sighash_type (int): SIGHASH_SINGLE or SIGHASH_ALL Returns: (bytes): the hashOutputs, a 32 byte hash ''' if...
BIP143 hashOutputs implementation Args: index (int): index of input being signed sighash_type (int): SIGHASH_SINGLE or SIGHASH_ALL Returns: (bytes): the hashOutputs, a 32 byte hash
Below is the the instruction that describes the task: ### Input: BIP143 hashOutputs implementation Args: index (int): index of input being signed sighash_type (int): SIGHASH_SINGLE or SIGHASH_ALL Returns: (bytes): the hashOutputs, a 32 byte hash ### Respon...
def constantrotating_to_static(frame_r, frame_i, w, t=None): """ Transform from a constantly rotating frame to a static, inertial frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `...
Transform from a constantly rotating frame to a static, inertial frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit` t : quantity_like (optional) Required i...
Below is the the instruction that describes the task: ### Input: Transform from a constantly rotating frame to a static, inertial frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `~gal...
def get_google_songs(self, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Create song list from user's Google Music library. Parameters: include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the M...
Create song list from user's Google Music library. Parameters: include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Mobileclient client. Patterns are Python regex patterns. Google Music songs are filtered out if the given meta...
Below is the the instruction that describes the task: ### Input: Create song list from user's Google Music library. Parameters: include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Mobileclient client. Patterns are Python rege...