code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def filter_by(lookup_dict, grain='os_family', merge=None, default='default', base=None): ''' .. versionadded:: 0.17.0 Look up the given grain in a given dictionary for the current OS and return the result Although this may occasionally be use...
.. versionadded:: 0.17.0 Look up the given grain in a given dictionary for the current OS and return the result Although this may occasionally be useful at the CLI, the primary intent of this function is for use in Jinja to make short work of creating lookup tables for OS-specific data. For exampl...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 0.17.0 Look up the given grain in a given dictionary for the current OS and return the result Although this may occasionally be useful at the CLI, the primary intent of this function is for use in Jinja to make shor...
def set_file_attr(filename, attr): """ Change a file's attributes on the local filesystem. The contents of C{attr} are used to change the permissions, owner, group ownership, and/or modification & access time of the file, depending on which attributes are present in C{attr}. ...
Change a file's attributes on the local filesystem. The contents of C{attr} are used to change the permissions, owner, group ownership, and/or modification & access time of the file, depending on which attributes are present in C{attr}. This is meant to be a handy helper function for t...
Below is the the instruction that describes the task: ### Input: Change a file's attributes on the local filesystem. The contents of C{attr} are used to change the permissions, owner, group ownership, and/or modification & access time of the file, depending on which attributes are present i...
def _file_path(self, container: Container, fn: str) -> str: """ Computes the base path for a given file. """ fn = self.resolve(container, fn) assert fn[0] == '/' fn = fn[1:] path = "files/{}/{}".format(container.uid, fn) return path
Computes the base path for a given file.
Below is the the instruction that describes the task: ### Input: Computes the base path for a given file. ### Response: def _file_path(self, container: Container, fn: str) -> str: """ Computes the base path for a given file. """ fn = self.resolve(container, fn) assert fn[0] ...
def pw_compare_class_sets(self, cset1: Set[ClassId], cset2: Set[ClassId]) -> Tuple[ICValue, ICValue, ICValue]: """ Compare two class profiles """ pairs = self.mica_ic_df.loc[cset1, cset2] max0 = pairs.max(axis=0) max1 = pairs.max(axis=1) idxmax0 = pairs.idxmax(axi...
Compare two class profiles
Below is the the instruction that describes the task: ### Input: Compare two class profiles ### Response: def pw_compare_class_sets(self, cset1: Set[ClassId], cset2: Set[ClassId]) -> Tuple[ICValue, ICValue, ICValue]: """ Compare two class profiles """ pairs = self.mica_ic_df.loc[cse...
def total_items(self, request): """ Get total number of items in the basket """ n_total = 0 for item in self.get_queryset(request): n_total += item.quantity return Response(data={"quantity": n_total}, status=status.HTTP_200_OK)
Get total number of items in the basket
Below is the the instruction that describes the task: ### Input: Get total number of items in the basket ### Response: def total_items(self, request): """ Get total number of items in the basket """ n_total = 0 for item in self.get_queryset(request): n_tota...
def render(self, name, value, attrs=None, **kwargs): """Widget render method.""" min_score = zxcvbn_min_score() message_title = _('Warning') message_body = _( 'This password would take ' '<em class="password_strength_time"></em> to crack.') strength_marku...
Widget render method.
Below is the the instruction that describes the task: ### Input: Widget render method. ### Response: def render(self, name, value, attrs=None, **kwargs): """Widget render method.""" min_score = zxcvbn_min_score() message_title = _('Warning') message_body = _( 'This passw...
def pos(x, context=None): """ Return ``x``. As usual, the result is rounded to the current context. The ``pos`` function can be useful for rounding an intermediate result, computed with a temporary increase in precision, back to the current context. For example:: >>> from bigfloat im...
Return ``x``. As usual, the result is rounded to the current context. The ``pos`` function can be useful for rounding an intermediate result, computed with a temporary increase in precision, back to the current context. For example:: >>> from bigfloat import precision >>> pow(3, 20) ...
Below is the the instruction that describes the task: ### Input: Return ``x``. As usual, the result is rounded to the current context. The ``pos`` function can be useful for rounding an intermediate result, computed with a temporary increase in precision, back to the current context. For example:...
def get_series_info(self, series_id): """ Get information about a series such as its title, frequency, observation start/end dates, units, notes, etc. Parameters ---------- series_id : str Fred series id such as 'CPIAUCSL' Returns ------- inf...
Get information about a series such as its title, frequency, observation start/end dates, units, notes, etc. Parameters ---------- series_id : str Fred series id such as 'CPIAUCSL' Returns ------- info : Series a pandas Series containing informat...
Below is the the instruction that describes the task: ### Input: Get information about a series such as its title, frequency, observation start/end dates, units, notes, etc. Parameters ---------- series_id : str Fred series id such as 'CPIAUCSL' Returns ------- ...
def on_click(self, handler): ''' Set up a handler for button or menu item clicks. Args: handler (func) : handler function to call when button is activated. Returns: None ''' self.on_event(ButtonClick, handler) self.on_event(MenuItemClick, handle...
Set up a handler for button or menu item clicks. Args: handler (func) : handler function to call when button is activated. Returns: None
Below is the the instruction that describes the task: ### Input: Set up a handler for button or menu item clicks. Args: handler (func) : handler function to call when button is activated. Returns: None ### Response: def on_click(self, handler): ''' Set up a handler...
def lstm(inputs, sequence_length, hparams, train, name, initial_state=None): """Adds a stack of LSTM layers on top of input. Args: inputs: The input `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. sequence_length: Lengths of the actual input sequence, excluding padding; a `Tensor` shaped ...
Adds a stack of LSTM layers on top of input. Args: inputs: The input `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. sequence_length: Lengths of the actual input sequence, excluding padding; a `Tensor` shaped `[batch_size]`. hparams: HParams; hyperparameters. train: bool; `True` whe...
Below is the the instruction that describes the task: ### Input: Adds a stack of LSTM layers on top of input. Args: inputs: The input `Tensor`, shaped `[batch_size, time_steps, hidden_size]`. sequence_length: Lengths of the actual input sequence, excluding padding; a `Tensor` shaped `[batch_size]...
def create_from_url(self, url, params=None): ''' /vi/iso/create_from_url POST - account Create a new ISO image on the current account. The ISO image will be downloaded from a given URL. Download status can be checked with the v1/iso/list call. Link: https://www.vultr.com...
/vi/iso/create_from_url POST - account Create a new ISO image on the current account. The ISO image will be downloaded from a given URL. Download status can be checked with the v1/iso/list call. Link: https://www.vultr.com/api/#iso_create_from_url
Below is the the instruction that describes the task: ### Input: /vi/iso/create_from_url POST - account Create a new ISO image on the current account. The ISO image will be downloaded from a given URL. Download status can be checked with the v1/iso/list call. Link: https://w...
def create_favorite(self, favorite, project): """CreateFavorite. [Preview API] Creates a ref favorite :param :class:`<GitRefFavorite> <azure.devops.v5_0.git.models.GitRefFavorite>` favorite: The ref favorite to create. :param str project: Project ID or project name :rtype: :class...
CreateFavorite. [Preview API] Creates a ref favorite :param :class:`<GitRefFavorite> <azure.devops.v5_0.git.models.GitRefFavorite>` favorite: The ref favorite to create. :param str project: Project ID or project name :rtype: :class:`<GitRefFavorite> <azure.devops.v5_0.git.models.GitRefFa...
Below is the the instruction that describes the task: ### Input: CreateFavorite. [Preview API] Creates a ref favorite :param :class:`<GitRefFavorite> <azure.devops.v5_0.git.models.GitRefFavorite>` favorite: The ref favorite to create. :param str project: Project ID or project name :r...
def decode_base64_and_inflate(value): """ base64 decodes and then inflates according to RFC1951 :param value: a deflated and encoded string :type value: string :returns: the string after decoding and inflating :rtype: string """ decoded = base64.b64decode(...
base64 decodes and then inflates according to RFC1951 :param value: a deflated and encoded string :type value: string :returns: the string after decoding and inflating :rtype: string
Below is the the instruction that describes the task: ### Input: base64 decodes and then inflates according to RFC1951 :param value: a deflated and encoded string :type value: string :returns: the string after decoding and inflating :rtype: string ### Response: def decode_base64_and...
def _sync_binary_dep_links(self, target, gopath, lib_binary_map): """Syncs symlinks under gopath to the library binaries of target's transitive dependencies. :param Target target: Target whose transitive dependencies must be linked. :param str gopath: $GOPATH of target whose "pkg/" directory must be popula...
Syncs symlinks under gopath to the library binaries of target's transitive dependencies. :param Target target: Target whose transitive dependencies must be linked. :param str gopath: $GOPATH of target whose "pkg/" directory must be populated with links to library binaries. :param dic...
Below is the the instruction that describes the task: ### Input: Syncs symlinks under gopath to the library binaries of target's transitive dependencies. :param Target target: Target whose transitive dependencies must be linked. :param str gopath: $GOPATH of target whose "pkg/" directory must be populated ...
def _fill_instance_child(xmldoc, element_name, return_type): '''Converts a child of the current dom element to the specified type. ''' element = xmldoc.find(_get_serialization_name(element_name)) if element is None: return None return_obj = return_type() _ETr...
Converts a child of the current dom element to the specified type.
Below is the the instruction that describes the task: ### Input: Converts a child of the current dom element to the specified type. ### Response: def _fill_instance_child(xmldoc, element_name, return_type): '''Converts a child of the current dom element to the specified type. ''' element = ...
def cache(*depends_on): """Caches function result in temporary file. Cache will be expired when modification date of files from `depends_on` will be changed. Only functions should be wrapped in `cache`, not methods. """ def cache_decorator(fn): @memoize @wraps(fn) def ...
Caches function result in temporary file. Cache will be expired when modification date of files from `depends_on` will be changed. Only functions should be wrapped in `cache`, not methods.
Below is the the instruction that describes the task: ### Input: Caches function result in temporary file. Cache will be expired when modification date of files from `depends_on` will be changed. Only functions should be wrapped in `cache`, not methods. ### Response: def cache(*depends_on): """Ca...
def chdir(self, target_directory): """Change current working directory to target directory. Args: target_directory: The path to new current working directory. Raises: OSError: if user lacks permission to enter the argument directory or if the target is n...
Change current working directory to target directory. Args: target_directory: The path to new current working directory. Raises: OSError: if user lacks permission to enter the argument directory or if the target is not a directory.
Below is the the instruction that describes the task: ### Input: Change current working directory to target directory. Args: target_directory: The path to new current working directory. Raises: OSError: if user lacks permission to enter the argument directory ...
def goto(reference_beats, estimated_beats, goto_threshold=0.35, goto_mu=0.2, goto_sigma=0.2): """Calculate Goto's score, a binary 1 or 0 depending on some specific heuristic criteria Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt')...
Calculate Goto's score, a binary 1 or 0 depending on some specific heuristic criteria Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt') >>> reference_beats = mir_eval.beat.trim_beats(reference_beats) >>> estimated_beats = mir_eval.io.load_events('estimated.txt') ...
Below is the the instruction that describes the task: ### Input: Calculate Goto's score, a binary 1 or 0 depending on some specific heuristic criteria Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt') >>> reference_beats = mir_eval.beat.trim_beats(reference_beats)...
def setNonExpert(self): """ Turns off 'expert' status whereby to allow a button to be disabled """ self._expert = False if self._active: self.enable() else: self.disable()
Turns off 'expert' status whereby to allow a button to be disabled
Below is the the instruction that describes the task: ### Input: Turns off 'expert' status whereby to allow a button to be disabled ### Response: def setNonExpert(self): """ Turns off 'expert' status whereby to allow a button to be disabled """ self._expert = False if self._...
def autocorr(x, lag=1): """Sample autocorrelation at specified lag. The autocorrelation is the correlation of x_i with x_{i+lag}. """ if not lag: return 1 if lag < 0: return # x = np.squeeze(asarray(x)) # mu = x.mean() # v = x.var() # return ((x[:-lag]-mu...
Sample autocorrelation at specified lag. The autocorrelation is the correlation of x_i with x_{i+lag}.
Below is the the instruction that describes the task: ### Input: Sample autocorrelation at specified lag. The autocorrelation is the correlation of x_i with x_{i+lag}. ### Response: def autocorr(x, lag=1): """Sample autocorrelation at specified lag. The autocorrelation is the correlation of x_i with x_...
def _md5_validation(self) -> bool: ''' Verifies the MD5 checksum. Only used in the __init__() function ''' fn = self.file if self.compressed_file is None else self.compressed_file md5 = hashlib.md5() block_size = 16384 with fn.open('rb') as f: ...
Verifies the MD5 checksum. Only used in the __init__() function
Below is the the instruction that describes the task: ### Input: Verifies the MD5 checksum. Only used in the __init__() function ### Response: def _md5_validation(self) -> bool: ''' Verifies the MD5 checksum. Only used in the __init__() function ''' fn = self.file if...
def response_schema(schema, code=200, required=False, description=None): """ Add response info into the swagger spec Usage: .. code-block:: python from aiohttp import web from marshmallow import Schema, fields class ResponseSchema(Schema): msg = fields.Str() ...
Add response info into the swagger spec Usage: .. code-block:: python from aiohttp import web from marshmallow import Schema, fields class ResponseSchema(Schema): msg = fields.Str() data = fields.Dict() @response_schema(ResponseSchema(), 200) ...
Below is the the instruction that describes the task: ### Input: Add response info into the swagger spec Usage: .. code-block:: python from aiohttp import web from marshmallow import Schema, fields class ResponseSchema(Schema): msg = fields.Str() data = f...
def ResolveForCreate(self, document): """Resolves the collection for creating the document based on the partition key. :param dict document: The document to be created. :return: Collection Self link or Name based link which should handle the Create operation. :r...
Resolves the collection for creating the document based on the partition key. :param dict document: The document to be created. :return: Collection Self link or Name based link which should handle the Create operation. :rtype: str
Below is the the instruction that describes the task: ### Input: Resolves the collection for creating the document based on the partition key. :param dict document: The document to be created. :return: Collection Self link or Name based link which should handle the Create o...
def create_storage(self, size=10, tier='maxiops', title='Storage disk', zone='fi-hel1', backup_rule={}): """ Create a Storage object. Returns an object based on the API's response. """ body = { 'storage': { 'size': size, 'tier': tier, ...
Create a Storage object. Returns an object based on the API's response.
Below is the the instruction that describes the task: ### Input: Create a Storage object. Returns an object based on the API's response. ### Response: def create_storage(self, size=10, tier='maxiops', title='Storage disk', zone='fi-hel1', backup_rule={}): """ Create a Storage object. Returns an obj...
def _verifyDiscoveredServices(self, claimed_id, services, to_match_endpoints): """See @L{_discoverAndVerify}""" # Search the services resulting from discovery to find one # that matches the information from the assertion failure_messages = [] fo...
See @L{_discoverAndVerify}
Below is the the instruction that describes the task: ### Input: See @L{_discoverAndVerify} ### Response: def _verifyDiscoveredServices(self, claimed_id, services, to_match_endpoints): """See @L{_discoverAndVerify}""" # Search the services resulting from discovery...
def _parseSections(self, data, elfHeader): """Returns a list of sections""" offset = elfHeader.header.e_shoff shdrs = [] for i in range(elfHeader.header.e_shnum): shdr = self.__classes.SHDR.from_buffer(data, offset) section_bytes = None ba_section_byte...
Returns a list of sections
Below is the the instruction that describes the task: ### Input: Returns a list of sections ### Response: def _parseSections(self, data, elfHeader): """Returns a list of sections""" offset = elfHeader.header.e_shoff shdrs = [] for i in range(elfHeader.header.e_shnum): sh...
def get_permissions(self): ''' Returns permissions for this directory or None if it's a special collection such as .session or .algo ''' response = self.client.getHelper(self.url, acl='true') if response.status_code != 200: raise DataApiError('Unable to get pe...
Returns permissions for this directory or None if it's a special collection such as .session or .algo
Below is the the instruction that describes the task: ### Input: Returns permissions for this directory or None if it's a special collection such as .session or .algo ### Response: def get_permissions(self): ''' Returns permissions for this directory or None if it's a special collection suc...
def lock(self): """Lock specified (abstract) requirements into (concrete) candidates. The locking procedure consists of four stages: * Resolve versions and dependency graph (powered by ResolveLib). * Walk the graph to determine "why" each candidate came to be, i.e. what top-l...
Lock specified (abstract) requirements into (concrete) candidates. The locking procedure consists of four stages: * Resolve versions and dependency graph (powered by ResolveLib). * Walk the graph to determine "why" each candidate came to be, i.e. what top-level requirements result in...
Below is the the instruction that describes the task: ### Input: Lock specified (abstract) requirements into (concrete) candidates. The locking procedure consists of four stages: * Resolve versions and dependency graph (powered by ResolveLib). * Walk the graph to determine "why" each candi...
def generate_html(): """ Generate an HTML file incorporating the images produced by this script """ html_file = open(html_filename, "w") html_file.write("<html><body>") html_file.write("<h1>Here are some graphs for you!</h1>") for image in [lines_filename, bars_filename, histogram_filename]:...
Generate an HTML file incorporating the images produced by this script
Below is the the instruction that describes the task: ### Input: Generate an HTML file incorporating the images produced by this script ### Response: def generate_html(): """ Generate an HTML file incorporating the images produced by this script """ html_file = open(html_filename, "w") html_fil...
def bool_from(obj, default=False): """Returns True if obj is not None and its string representation is not 0 or False (case-insensitive). If obj is None, 'default' is used. """ return str(obj).lower() not in ('0', 'false') if obj is not None else bool(default)
Returns True if obj is not None and its string representation is not 0 or False (case-insensitive). If obj is None, 'default' is used.
Below is the the instruction that describes the task: ### Input: Returns True if obj is not None and its string representation is not 0 or False (case-insensitive). If obj is None, 'default' is used. ### Response: def bool_from(obj, default=False): """Returns True if obj is not None and its string represen...
def exists(self, record_key): ''' a method to determine if a record exists in collection :param record_key: string with key of record :return: boolean reporting status ''' title = '%s.exists' % self.__class__.__name__ # validate...
a method to determine if a record exists in collection :param record_key: string with key of record :return: boolean reporting status
Below is the the instruction that describes the task: ### Input: a method to determine if a record exists in collection :param record_key: string with key of record :return: boolean reporting status ### Response: def exists(self, record_key): ''' a method to det...
def prefixedname_to_iriref(self, prefix: ShExDocParser.PrefixedNameContext) -> ShExJ.IRIREF: """ prefixedName: PNAME_LN | PNAME_NS PNAME_NS: PN_PREFIX? ':' ; PNAME_LN: PNAME_NS PN_LOCAL ; """ return ShExJ.IRIREF(self.prefixedname_to_str(prefix))
prefixedName: PNAME_LN | PNAME_NS PNAME_NS: PN_PREFIX? ':' ; PNAME_LN: PNAME_NS PN_LOCAL ;
Below is the the instruction that describes the task: ### Input: prefixedName: PNAME_LN | PNAME_NS PNAME_NS: PN_PREFIX? ':' ; PNAME_LN: PNAME_NS PN_LOCAL ; ### Response: def prefixedname_to_iriref(self, prefix: ShExDocParser.PrefixedNameContext) -> ShExJ.IRIREF: """ prefixedName: PN...
def passwd_keys(self, username): """Generator to return keys used to store passwords in peer store. NOTE: we support both legacy and new format to support mysql charm prior to refactor. This is necessary to avoid LP 1451890. """ keys = [] if username == 'mysql': ...
Generator to return keys used to store passwords in peer store. NOTE: we support both legacy and new format to support mysql charm prior to refactor. This is necessary to avoid LP 1451890.
Below is the the instruction that describes the task: ### Input: Generator to return keys used to store passwords in peer store. NOTE: we support both legacy and new format to support mysql charm prior to refactor. This is necessary to avoid LP 1451890. ### Response: def passwd_keys(self, username...
def get_param(self): """Method to get current optimizer's parameter value """ lr_list = self.lr_scheduler.get_lr() if len(lr_list) > 1: raise ValueError("Optimizer passed to lr_scheduler should have a single param group, " "but currently there are...
Method to get current optimizer's parameter value
Below is the the instruction that describes the task: ### Input: Method to get current optimizer's parameter value ### Response: def get_param(self): """Method to get current optimizer's parameter value """ lr_list = self.lr_scheduler.get_lr() if len(lr_list) > 1: raise ...
def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: """ Returns all income in the given period """ accounts = self.get_income_accounts() income = Decimal(0) for acct in accounts: acc_agg = AccountAggregate(self.book, acct) acc_bal = acc_agg....
Returns all income in the given period
Below is the the instruction that describes the task: ### Input: Returns all income in the given period ### Response: def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: """ Returns all income in the given period """ accounts = self.get_income_accounts() income = Deci...
def count_group_cached(group_id, failures=False, broker=None): """ Count the results in a group in the cache backend """ if not broker: broker = get_broker() group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id)) if group_list: if not failures: ...
Count the results in a group in the cache backend
Below is the the instruction that describes the task: ### Input: Count the results in a group in the cache backend ### Response: def count_group_cached(group_id, failures=False, broker=None): """ Count the results in a group in the cache backend """ if not broker: broker = get_broker() ...
def _wrapped_unsigned_div(a, b): """ Perform wrapped unsigned division on two StridedIntervals. :param a: The dividend (StridedInterval) :param b: The divisor (StridedInterval) :return: The quotient """ bits = max(a.bits, b.bits) divisor_lb, divisor_ub ...
Perform wrapped unsigned division on two StridedIntervals. :param a: The dividend (StridedInterval) :param b: The divisor (StridedInterval) :return: The quotient
Below is the the instruction that describes the task: ### Input: Perform wrapped unsigned division on two StridedIntervals. :param a: The dividend (StridedInterval) :param b: The divisor (StridedInterval) :return: The quotient ### Response: def _wrapped_unsigned_div(a, b): """ ...
def downgrade(engine, desired_version): """Downgrades the assets db at the given engine to the desired version. Parameters ---------- engine : Engine An SQLAlchemy engine to the assets database. desired_version : int The desired resulting version for the assets database. """ ...
Downgrades the assets db at the given engine to the desired version. Parameters ---------- engine : Engine An SQLAlchemy engine to the assets database. desired_version : int The desired resulting version for the assets database.
Below is the the instruction that describes the task: ### Input: Downgrades the assets db at the given engine to the desired version. Parameters ---------- engine : Engine An SQLAlchemy engine to the assets database. desired_version : int The desired resulting version for the assets...
def read(self, len): """Refresh the content of the input buffer, the old data are considered consumed This routine handle the I18N transcoding to internal UTF-8 """ ret = libxml2mod.xmlParserInputBufferRead(self._o, len) return ret
Refresh the content of the input buffer, the old data are considered consumed This routine handle the I18N transcoding to internal UTF-8
Below is the the instruction that describes the task: ### Input: Refresh the content of the input buffer, the old data are considered consumed This routine handle the I18N transcoding to internal UTF-8 ### Response: def read(self, len): """Refresh the content of the input buffer, the o...
def abort(): """ABORT Section 9.2.8""" a = TpPd(pd=0x5) b = MessageType(mesType=0x29) # 00101001 c = RejectCause() packet = a / b / c return packet
ABORT Section 9.2.8
Below is the the instruction that describes the task: ### Input: ABORT Section 9.2.8 ### Response: def abort(): """ABORT Section 9.2.8""" a = TpPd(pd=0x5) b = MessageType(mesType=0x29) # 00101001 c = RejectCause() packet = a / b / c return packet
def debug_tensor(tensor, name): """ Simple utility which helps with debugging. Takes a tensor and outputs: min, max, avg, std, number of NaNs, number of INFs. :param tensor: torch tensor :param name: name of the tensor (only for logging) """ logging.info(name) tensor = tensor.detach...
Simple utility which helps with debugging. Takes a tensor and outputs: min, max, avg, std, number of NaNs, number of INFs. :param tensor: torch tensor :param name: name of the tensor (only for logging)
Below is the the instruction that describes the task: ### Input: Simple utility which helps with debugging. Takes a tensor and outputs: min, max, avg, std, number of NaNs, number of INFs. :param tensor: torch tensor :param name: name of the tensor (only for logging) ### Response: def debug_tensor(...
def _get_annotations(cls): """ Get annotations for *cls*. """ anns = getattr(cls, "__annotations__", None) if anns is None: return {} # Verify that the annotations aren't merely inherited. for base_cls in cls.__mro__[1:]: if anns is getattr(base_cls, "__annotations__", None)...
Get annotations for *cls*.
Below is the the instruction that describes the task: ### Input: Get annotations for *cls*. ### Response: def _get_annotations(cls): """ Get annotations for *cls*. """ anns = getattr(cls, "__annotations__", None) if anns is None: return {} # Verify that the annotations aren't merel...
def calcFnWeight(node): '''Calculates the weight of a function definition by recursively counting its child nodes in the AST. Note that the tree traversal will become O(n^2) instead of O(n) if this feature is enabled.''' stack = [node] count = 0 while len(stack) > 0: node = stack.pop()...
Calculates the weight of a function definition by recursively counting its child nodes in the AST. Note that the tree traversal will become O(n^2) instead of O(n) if this feature is enabled.
Below is the the instruction that describes the task: ### Input: Calculates the weight of a function definition by recursively counting its child nodes in the AST. Note that the tree traversal will become O(n^2) instead of O(n) if this feature is enabled. ### Response: def calcFnWeight(node): '''Calc...
def pop_frame(self): """ Pops the current contextual frame off of the stack and returns the cursor to the frame's return position. """ try: offset, return_pos = self._frames.pop() except IndexError: raise IndexError('no frames to pop') self...
Pops the current contextual frame off of the stack and returns the cursor to the frame's return position.
Below is the the instruction that describes the task: ### Input: Pops the current contextual frame off of the stack and returns the cursor to the frame's return position. ### Response: def pop_frame(self): """ Pops the current contextual frame off of the stack and returns the cursor...
def fit_multinest(self, n_live_points=1000, basename='chains/single-', verbose=True, refit=False, overwrite=False, **kwargs): """ Fits model using MultiNest, via pymultinest. :param n_live_points: Number of live points to use for MultiNe...
Fits model using MultiNest, via pymultinest. :param n_live_points: Number of live points to use for MultiNest fit. :param basename: Where the MulitNest-generated files will live. By default this will be in a folder named `chains` in the current worki...
Below is the the instruction that describes the task: ### Input: Fits model using MultiNest, via pymultinest. :param n_live_points: Number of live points to use for MultiNest fit. :param basename: Where the MulitNest-generated files will live. By default thi...
def query(args): """ %prog query "SELECT feat_name FROM asm_feature WHERE feat_type = \\"{0}\\" AND end5 <= \\"{1}\\" AND end3 >= \\"{2}\\"" ::: datafile1 .... Script takes the data from tab-delimited datafile(s) and replaces the placeholders in the query which is then executed. Depending upon the type...
%prog query "SELECT feat_name FROM asm_feature WHERE feat_type = \\"{0}\\" AND end5 <= \\"{1}\\" AND end3 >= \\"{2}\\"" ::: datafile1 .... Script takes the data from tab-delimited datafile(s) and replaces the placeholders in the query which is then executed. Depending upon the type of query, results are ei...
Below is the the instruction that describes the task: ### Input: %prog query "SELECT feat_name FROM asm_feature WHERE feat_type = \\"{0}\\" AND end5 <= \\"{1}\\" AND end3 >= \\"{2}\\"" ::: datafile1 .... Script takes the data from tab-delimited datafile(s) and replaces the placeholders in the query which i...
def strip( text ): ''' Strips all color codes from a text. ''' members = [attr for attr in Colors.__dict__.keys() if not attr.startswith( "__" ) and not attr == 'strip'] for c in members: text = text.replace( vars( Colors )[c], '' ) return text
Strips all color codes from a text.
Below is the the instruction that describes the task: ### Input: Strips all color codes from a text. ### Response: def strip( text ): ''' Strips all color codes from a text. ''' members = [attr for attr in Colors.__dict__.keys() if not attr.startswith( "__" ) and not attr == 'strip'...
def safe_format_sh(s, **kwargs): """ :type s str """ to_replace = set(kwargs.keys()) & set(FORMAT_RE.findall(s)) for item in to_replace: s = s.replace("{{" + item + "}}", kwargs[item]) return s
:type s str
Below is the the instruction that describes the task: ### Input: :type s str ### Response: def safe_format_sh(s, **kwargs): """ :type s str """ to_replace = set(kwargs.keys()) & set(FORMAT_RE.findall(s)) for item in to_replace: s = s.replace("{{" + item + "}}", kwargs[item]) return s
def delete_object_in_seconds(self, cont, obj, seconds, extra_info=None): """ Sets the object in the specified container to be deleted after the specified number of seconds. The 'extra_info' parameter is included for backwards compatibility. It is no longer used at all, and will ...
Sets the object in the specified container to be deleted after the specified number of seconds. The 'extra_info' parameter is included for backwards compatibility. It is no longer used at all, and will not be modified with swiftclient info, since swiftclient is not used any more.
Below is the the instruction that describes the task: ### Input: Sets the object in the specified container to be deleted after the specified number of seconds. The 'extra_info' parameter is included for backwards compatibility. It is no longer used at all, and will not be modified with swi...
def make(data, samples): """ builds snps output """ ## get attr ploidy = data.paramsdict["max_alleles_consens"] names = [i.name for i in samples] longname = max([len(i) for i in names]) ## TODO: use iter cuz of super huge files inloci = open(os.path.join(\ data.dirs.outf...
builds snps output
Below is the the instruction that describes the task: ### Input: builds snps output ### Response: def make(data, samples): """ builds snps output """ ## get attr ploidy = data.paramsdict["max_alleles_consens"] names = [i.name for i in samples] longname = max([len(i) for i in names]) ## T...
def V_vertical_conical_concave(D, a, h): r'''Calculates volume of a vertical tank with a concave conical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V = \frac{\pi D^2}{12} \left(3h + a - \frac{(a+h)^3}{a^2}\right) ,\;\; 0 \le h < |a| .. math:...
r'''Calculates volume of a vertical tank with a concave conical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V = \frac{\pi D^2}{12} \left(3h + a - \frac{(a+h)^3}{a^2}\right) ,\;\; 0 \le h < |a| .. math:: V = \frac{\pi D^2}{12} (3h + a ),\;...
Below is the the instruction that describes the task: ### Input: r'''Calculates volume of a vertical tank with a concave conical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V = \frac{\pi D^2}{12} \left(3h + a - \frac{(a+h)^3}{a^2}\right) ,\;\; 0 \...
def add_common_check(self, actions, table, func): """ emitted before query :param actions: :param table: :param func: :return: """ self.common_checks.append([table, actions, func]) """def func(ability, user, action, available_columns: list): ...
emitted before query :param actions: :param table: :param func: :return:
Below is the the instruction that describes the task: ### Input: emitted before query :param actions: :param table: :param func: :return: ### Response: def add_common_check(self, actions, table, func): """ emitted before query :param actions: :param t...
def add_icon(icon_data, dest): """ Add icon to docset """ with open(os.path.join(dest, "icon.png"), "wb") as f: f.write(icon_data)
Add icon to docset
Below is the the instruction that describes the task: ### Input: Add icon to docset ### Response: def add_icon(icon_data, dest): """ Add icon to docset """ with open(os.path.join(dest, "icon.png"), "wb") as f: f.write(icon_data)
def hide(self, _unhide=False): """Hide object in the context of the logged in user. :param _unhide: If True, unhide the item instead. Use :meth:`~praw.objects.Hideable.unhide` instead of setting this manually. :returns: The json response from the server. """ ...
Hide object in the context of the logged in user. :param _unhide: If True, unhide the item instead. Use :meth:`~praw.objects.Hideable.unhide` instead of setting this manually. :returns: The json response from the server.
Below is the the instruction that describes the task: ### Input: Hide object in the context of the logged in user. :param _unhide: If True, unhide the item instead. Use :meth:`~praw.objects.Hideable.unhide` instead of setting this manually. :returns: The json response from...
def scatterAlign(seq1, seq2, window=7): """ Visually align two sequences. """ d1 = defaultdict(list) d2 = defaultdict(list) for (seq, section_dict) in [(seq1, d1), (seq2, d2)]: for i in range(len(seq) - window): section = seq[i:i + window] section_dict[section].ap...
Visually align two sequences.
Below is the the instruction that describes the task: ### Input: Visually align two sequences. ### Response: def scatterAlign(seq1, seq2, window=7): """ Visually align two sequences. """ d1 = defaultdict(list) d2 = defaultdict(list) for (seq, section_dict) in [(seq1, d1), (seq2, d2)]: ...
def trim(s, prefix=None, suffix=None, strict=False): """Trim a string, removing given prefix or suffix. :param s: String to trim :param prefix: Prefix to remove from ``s`` :param suffix: Suffix to remove from ``s`` :param strict: Whether the prefix or suffix must be present in ``s``. ...
Trim a string, removing given prefix or suffix. :param s: String to trim :param prefix: Prefix to remove from ``s`` :param suffix: Suffix to remove from ``s`` :param strict: Whether the prefix or suffix must be present in ``s``. By default, if the infix is not found, function will si...
Below is the the instruction that describes the task: ### Input: Trim a string, removing given prefix or suffix. :param s: String to trim :param prefix: Prefix to remove from ``s`` :param suffix: Suffix to remove from ``s`` :param strict: Whether the prefix or suffix must be present in ``s``. ...
def process_children(self, node, path, level, parent=None): """Process all children of `node`. `path` is the Xpath of `node` which is used in the 'select' attribute of XSLT templates. """ data_parent = parent if parent else node chs = node.i_children for ch in ch...
Process all children of `node`. `path` is the Xpath of `node` which is used in the 'select' attribute of XSLT templates.
Below is the the instruction that describes the task: ### Input: Process all children of `node`. `path` is the Xpath of `node` which is used in the 'select' attribute of XSLT templates. ### Response: def process_children(self, node, path, level, parent=None): """Process all children of `no...
def build_ascii_property_table(output): """Build and write out Unicode property table.""" if not os.path.exists(output): os.mkdir(output) gen_properties(output, ascii_props=True, append=True)
Build and write out Unicode property table.
Below is the the instruction that describes the task: ### Input: Build and write out Unicode property table. ### Response: def build_ascii_property_table(output): """Build and write out Unicode property table.""" if not os.path.exists(output): os.mkdir(output) gen_properties(output, ascii_prop...
def send(self, **kwargs): """Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request. ...
Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request.
Below is the the instruction that describes the task: ### Input: Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Respon...
def notification_preference(obj_type, profile): '''Display two radio buttons for turning notifications on or off. The default value is is have alerts_on = True. ''' default_alert_value = True if not profile: alerts_on = True else: notifications = profile.get('notifications', {}) ...
Display two radio buttons for turning notifications on or off. The default value is is have alerts_on = True.
Below is the the instruction that describes the task: ### Input: Display two radio buttons for turning notifications on or off. The default value is is have alerts_on = True. ### Response: def notification_preference(obj_type, profile): '''Display two radio buttons for turning notifications on or off. ...
def db_upgrade(version=None): """Upgrade the database""" v1 = get_db_version() migrate_api.upgrade(url=db_url, repository=db_repo, version=version) v2 = get_db_version() if v1 == v2: print 'Database already up-to-date.' else: print 'Upgraded: %s ... %s' % (v1, v2)
Upgrade the database
Below is the the instruction that describes the task: ### Input: Upgrade the database ### Response: def db_upgrade(version=None): """Upgrade the database""" v1 = get_db_version() migrate_api.upgrade(url=db_url, repository=db_repo, version=version) v2 = get_db_version() if v1 == v2: pri...
def lotus_root_geometry(): """Tomographic geometry for the lotus root dataset. Notes ----- See the article `Tomographic X-ray data of a lotus root filled with attenuating objects`_ for further information. See Also -------- lotus_root_geometry References ---------- .. _Tom...
Tomographic geometry for the lotus root dataset. Notes ----- See the article `Tomographic X-ray data of a lotus root filled with attenuating objects`_ for further information. See Also -------- lotus_root_geometry References ---------- .. _Tomographic X-ray data of a lotus roo...
Below is the the instruction that describes the task: ### Input: Tomographic geometry for the lotus root dataset. Notes ----- See the article `Tomographic X-ray data of a lotus root filled with attenuating objects`_ for further information. See Also -------- lotus_root_geometry Re...
def get(*args, **kwargs): """Get UserEXT objects.""" try: from invenio.modules.accounts.models import UserEXT except ImportError: from invenio_accounts.models import UserEXT q = UserEXT.query return q.count(), q.all()
Get UserEXT objects.
Below is the the instruction that describes the task: ### Input: Get UserEXT objects. ### Response: def get(*args, **kwargs): """Get UserEXT objects.""" try: from invenio.modules.accounts.models import UserEXT except ImportError: from invenio_accounts.models import UserEXT q = UserE...
def delete_db_entry(self, release): """Delete the db entries for releasefile and comment of the given release :param release: the release with the releasefile and comment db entries :type release: :class:`Release` :returns: an action status :rtype: :class:`ActionStatus` ...
Delete the db entries for releasefile and comment of the given release :param release: the release with the releasefile and comment db entries :type release: :class:`Release` :returns: an action status :rtype: :class:`ActionStatus` :raises: None
Below is the the instruction that describes the task: ### Input: Delete the db entries for releasefile and comment of the given release :param release: the release with the releasefile and comment db entries :type release: :class:`Release` :returns: an action status :rtype: :class:`...
def download_financialzip(): """ 会创建一个download/文件夹 """ result = get_filename() res = [] for item, md5 in result: if item in os.listdir(download_path) and md5==QA_util_file_md5('{}{}{}'.format(download_path,os.sep,item)): print('FILE {} is already in {}'.format(it...
会创建一个download/文件夹
Below is the the instruction that describes the task: ### Input: 会创建一个download/文件夹 ### Response: def download_financialzip(): """ 会创建一个download/文件夹 """ result = get_filename() res = [] for item, md5 in result: if item in os.listdir(download_path) and md5==QA_util_file_md5('{}{}{}'.f...
def stderr_avail(self): """Data is available in stderr, let's empty the queue and write it!""" data = self.interpreter.stderr_write.empty_queue() if data: self.write(data, error=True) self.flush(error=True)
Data is available in stderr, let's empty the queue and write it!
Below is the the instruction that describes the task: ### Input: Data is available in stderr, let's empty the queue and write it! ### Response: def stderr_avail(self): """Data is available in stderr, let's empty the queue and write it!""" data = self.interpreter.stderr_write.empty_queue() ...
def __experimental_range(start, stop, var, cond, loc={}): '''Utility function made to reproduce range() with unit integer step but with the added possibility of specifying a condition on the looping variable (e.g. var % 2 == 0) ''' locals().update(loc) if start < stop: for __ in ...
Utility function made to reproduce range() with unit integer step but with the added possibility of specifying a condition on the looping variable (e.g. var % 2 == 0)
Below is the the instruction that describes the task: ### Input: Utility function made to reproduce range() with unit integer step but with the added possibility of specifying a condition on the looping variable (e.g. var % 2 == 0) ### Response: def __experimental_range(start, stop, var, cond, loc=...
def FromDBInstance(db_token): """ Get a NEP5Token instance from a database token. Args: db_token (neo.Implementations.Wallets.peewee.Models.NEP5Token): Returns: NEP5Token: self. """ hash_ar = bytearray(binascii.unhexlify(db_token.ContractHash)) ...
Get a NEP5Token instance from a database token. Args: db_token (neo.Implementations.Wallets.peewee.Models.NEP5Token): Returns: NEP5Token: self.
Below is the the instruction that describes the task: ### Input: Get a NEP5Token instance from a database token. Args: db_token (neo.Implementations.Wallets.peewee.Models.NEP5Token): Returns: NEP5Token: self. ### Response: def FromDBInstance(db_token): """ ...
def entity_to_bulk(entities, resource_type_parent): """Convert Single TC Entity to Bulk format. .. Attention:: This method is subject to frequent changes Args: entities (dictionary): TC Entity to be converted to Bulk. resource_type_parent (string): The resource parent t...
Convert Single TC Entity to Bulk format. .. Attention:: This method is subject to frequent changes Args: entities (dictionary): TC Entity to be converted to Bulk. resource_type_parent (string): The resource parent type of the tc_data provided. Returns: (dic...
Below is the the instruction that describes the task: ### Input: Convert Single TC Entity to Bulk format. .. Attention:: This method is subject to frequent changes Args: entities (dictionary): TC Entity to be converted to Bulk. resource_type_parent (string): The resource pa...
def merge_mhc_peptide_calls(job, antigen_predictions, transgened_files): """ This module will merge all the calls from nodes 18 and 19, and will filter for the top X%% of binders of each allele. The module will then call the rank boosting script to finish off the pipeline. This module corresponds ...
This module will merge all the calls from nodes 18 and 19, and will filter for the top X%% of binders of each allele. The module will then call the rank boosting script to finish off the pipeline. This module corresponds to node 19 on the tree
Below is the the instruction that describes the task: ### Input: This module will merge all the calls from nodes 18 and 19, and will filter for the top X%% of binders of each allele. The module will then call the rank boosting script to finish off the pipeline. This module corresponds to node 19 on th...
def main(self, x): """ Transposed form FIR implementation, uses full precision """ for i in range(len(self.taps_fix_reversed)): self.next.mul[i] = x * self.taps_fix_reversed[i] if i == 0: self.next.acc[0] = self.mul[i] else: ...
Transposed form FIR implementation, uses full precision
Below is the the instruction that describes the task: ### Input: Transposed form FIR implementation, uses full precision ### Response: def main(self, x): """ Transposed form FIR implementation, uses full precision """ for i in range(len(self.taps_fix_reversed)): self.nex...
def sort_by_efficiency(self, reverse=True): """Sort the configurations in place. items with highest efficiency come first""" self._confs.sort(key=lambda c: c.efficiency, reverse=reverse) return self
Sort the configurations in place. items with highest efficiency come first
Below is the the instruction that describes the task: ### Input: Sort the configurations in place. items with highest efficiency come first ### Response: def sort_by_efficiency(self, reverse=True): """Sort the configurations in place. items with highest efficiency come first""" self._confs.sort(key...
def _schedule(self, delay: float, event: Callable, *args: Any, **kwargs: Any) -> int: """ Schedules a one-time event to be run along the simulation. The event is scheduled relative to current simulator time, so delay is expected to be a positive simulation time interval. The `event' parameter c...
Schedules a one-time event to be run along the simulation. The event is scheduled relative to current simulator time, so delay is expected to be a positive simulation time interval. The `event' parameter corresponds to a callable object (e.g. a function): it will be called so as to "execute" the event,...
Below is the the instruction that describes the task: ### Input: Schedules a one-time event to be run along the simulation. The event is scheduled relative to current simulator time, so delay is expected to be a positive simulation time interval. The `event' parameter corresponds to a callable obje...
def triads(reference_labels, estimated_labels): """Compare chords along triad (root & quality to #5) relationships. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_eval.io.load_labeled_interval...
Compare chords along triad (root & quality to #5) relationships. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab') >>> est_intervals, est_labels = mir_ev...
Below is the the instruction that describes the task: ### Input: Compare chords along triad (root & quality to #5) relationships. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_eval.io.load_la...
def field_get_subfields(field): """ Given a field, will place all subfields into a dictionary Parameters: * field - tuple: The field to get subfields for Returns: a dictionary, codes as keys and a list of values as the value """ pairs = {} for key, value in field[0]: if key in pairs and...
Given a field, will place all subfields into a dictionary Parameters: * field - tuple: The field to get subfields for Returns: a dictionary, codes as keys and a list of values as the value
Below is the the instruction that describes the task: ### Input: Given a field, will place all subfields into a dictionary Parameters: * field - tuple: The field to get subfields for Returns: a dictionary, codes as keys and a list of values as the value ### Response: def field_get_subfields(field): ...
def create_tcp_monitor(self, topics, batch_size=1, batch_duration=0, compression='gzip', format_type='json'): """Creates a TCP Monitor instance in Device Cloud for a given list of topics :param topics: a string list of topics (e.g. ['DeviceCore[U]', 'FileDat...
Creates a TCP Monitor instance in Device Cloud for a given list of topics :param topics: a string list of topics (e.g. ['DeviceCore[U]', 'FileDataCore']). :param batch_size: How many Msgs received before sending data. :param batch_duration: How long to wait before sending batc...
Below is the the instruction that describes the task: ### Input: Creates a TCP Monitor instance in Device Cloud for a given list of topics :param topics: a string list of topics (e.g. ['DeviceCore[U]', 'FileDataCore']). :param batch_size: How many Msgs received before sending data...
def excepthook(self, etype, evalue, tb): """this is sys.excepthook after init_crashhandler set self.verbose_crash=True to use our full crashhandler, instead of a regular traceback with a short message (crash_handler_lite) """ if self.verbose_crash: r...
this is sys.excepthook after init_crashhandler set self.verbose_crash=True to use our full crashhandler, instead of a regular traceback with a short message (crash_handler_lite)
Below is the the instruction that describes the task: ### Input: this is sys.excepthook after init_crashhandler set self.verbose_crash=True to use our full crashhandler, instead of a regular traceback with a short message (crash_handler_lite) ### Response: def excepthook(self, etype, evalu...
def edit(self, body): """Edit this comment. :param str body: (required), new body of the comment, Markdown formatted :returns: bool """ if body: json = self._json(self._patch(self._api, data=dumps({'body': body})), 200) ...
Edit this comment. :param str body: (required), new body of the comment, Markdown formatted :returns: bool
Below is the the instruction that describes the task: ### Input: Edit this comment. :param str body: (required), new body of the comment, Markdown formatted :returns: bool ### Response: def edit(self, body): """Edit this comment. :param str body: (required), new body o...
def control_loop(): '''Main loop of the capture agent, retrieving and checking the schedule as well as starting the capture process if necessry. ''' set_service_status(Service.CAPTURE, ServiceStatus.IDLE) notify.notify('READY=1') notify.notify('STATUS=Waiting') while not terminate(): ...
Main loop of the capture agent, retrieving and checking the schedule as well as starting the capture process if necessry.
Below is the the instruction that describes the task: ### Input: Main loop of the capture agent, retrieving and checking the schedule as well as starting the capture process if necessry. ### Response: def control_loop(): '''Main loop of the capture agent, retrieving and checking the schedule as well as...
def refreshCards( self ): """ Refreshes the results for the cards view of the browser. """ cards = self.cardWidget() factory = self.factory() self.setUpdatesEnabled(False) self.blockSignals(True) cards.setUpdatesEnabled(False) ...
Refreshes the results for the cards view of the browser.
Below is the the instruction that describes the task: ### Input: Refreshes the results for the cards view of the browser. ### Response: def refreshCards( self ): """ Refreshes the results for the cards view of the browser. """ cards = self.cardWidget() factory = self.fa...
def route_stanza(self, stanza): """Process stanza not addressed to us. Return "recipient-unavailable" return if it is not "error" nor "result" stanza. This method should be overriden in derived classes if they are supposed to handle stanzas not addressed directly to local ...
Process stanza not addressed to us. Return "recipient-unavailable" return if it is not "error" nor "result" stanza. This method should be overriden in derived classes if they are supposed to handle stanzas not addressed directly to local stream endpoint. :Parameters: ...
Below is the the instruction that describes the task: ### Input: Process stanza not addressed to us. Return "recipient-unavailable" return if it is not "error" nor "result" stanza. This method should be overriden in derived classes if they are supposed to handle stanzas not address...
def calculate_bar_widths(self, size, bardata): """ Return a list of bar widths, one for each bar in data. If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol. """ (maxcol, _) = size if self.bar_width...
Return a list of bar widths, one for each bar in data. If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol.
Below is the the instruction that describes the task: ### Input: Return a list of bar widths, one for each bar in data. If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol. ### Response: def calculate_bar_widths(self, size, bardata): ...
def create_index(self, index): """Creates and opens index folder for given index. If the index already exists, it just opens it, otherwise it creates it first. """ index._path = os.path.join(self.indexes_path, index._name) if whoosh.index.exists_in(index._path): _whoosh = whoosh.index.open_d...
Creates and opens index folder for given index. If the index already exists, it just opens it, otherwise it creates it first.
Below is the the instruction that describes the task: ### Input: Creates and opens index folder for given index. If the index already exists, it just opens it, otherwise it creates it first. ### Response: def create_index(self, index): """Creates and opens index folder for given index. If the index alr...
def _remove_os_link(): """ In a context, remove and restore os.link if it exists """ class NoValue: pass orig_val = getattr(os, 'link', NoValue) try: del os.link except Exception: pass try: yield fi...
In a context, remove and restore os.link if it exists
Below is the the instruction that describes the task: ### Input: In a context, remove and restore os.link if it exists ### Response: def _remove_os_link(): """ In a context, remove and restore os.link if it exists """ class NoValue: pass orig_val = getattr(os, ...
def inv(self): """The inverse transformation""" result = Complete(self.r.transpose(), np.dot(self.r.transpose(), -self.t)) result._cache_inv = self return result
The inverse transformation
Below is the the instruction that describes the task: ### Input: The inverse transformation ### Response: def inv(self): """The inverse transformation""" result = Complete(self.r.transpose(), np.dot(self.r.transpose(), -self.t)) result._cache_inv = self return result
def _on_connection_made(self): """ Gets called when the TCP connection to kik's servers is done and we are connected. Now we might initiate a login request or an auth request. """ if self.username is not None and self.password is not None and self.kik_node is not None: ...
Gets called when the TCP connection to kik's servers is done and we are connected. Now we might initiate a login request or an auth request.
Below is the the instruction that describes the task: ### Input: Gets called when the TCP connection to kik's servers is done and we are connected. Now we might initiate a login request or an auth request. ### Response: def _on_connection_made(self): """ Gets called when the TCP connection ...
def _UserUpdateSupportedFormats(self, origFormatList = []): """ Add supported formats to database table. Always called if the database table is empty. User can build a list of entries to add to the database table (one entry at a time). Once finished they select the finish option and all entries...
Add supported formats to database table. Always called if the database table is empty. User can build a list of entries to add to the database table (one entry at a time). Once finished they select the finish option and all entries will be added to the table. They can reset the list at any time bef...
Below is the the instruction that describes the task: ### Input: Add supported formats to database table. Always called if the database table is empty. User can build a list of entries to add to the database table (one entry at a time). Once finished they select the finish option and all entries wi...
def param_set_send(self, parm_name, parm_value, parm_type=None): '''wrapper for parameter set''' if self.mavlink10(): if parm_type == None: parm_type = mavlink.MAVLINK_TYPE_FLOAT self.mav.param_set_send(self.target_system, self.target_component, ...
wrapper for parameter set
Below is the the instruction that describes the task: ### Input: wrapper for parameter set ### Response: def param_set_send(self, parm_name, parm_value, parm_type=None): '''wrapper for parameter set''' if self.mavlink10(): if parm_type == None: parm_type = mavlink.MAVLIN...
def update_progress( self, completed_count, total_count, update_frequency=1, ): """ Update the task backend with both an estimated percentage complete and number of seconds remaining until completion. ``completed_count`` Number of task "units" that ha...
Update the task backend with both an estimated percentage complete and number of seconds remaining until completion. ``completed_count`` Number of task "units" that have been completed out of ``total_count`` total "units." ``update_frequency`` Only actually store the updated progress in...
Below is the the instruction that describes the task: ### Input: Update the task backend with both an estimated percentage complete and number of seconds remaining until completion. ``completed_count`` Number of task "units" that have been completed out of ``total_count`` total "units." ...
def Up(self, n = 1, dl = 0): """上方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.up_key, n)
上方向键n次
Below is the the instruction that describes the task: ### Input: 上方向键n次 ### Response: def Up(self, n = 1, dl = 0): """上方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.up_key, n)
def run(self): """ Attmept to deliver the first outgoing L{QueuedMessage}; return a time to reschedule if there are still more retries or outgoing messages to send. """ delay = None router = self.siteRouter for qmsg in self.store.query(_QueuedMessage, ...
Attmept to deliver the first outgoing L{QueuedMessage}; return a time to reschedule if there are still more retries or outgoing messages to send.
Below is the the instruction that describes the task: ### Input: Attmept to deliver the first outgoing L{QueuedMessage}; return a time to reschedule if there are still more retries or outgoing messages to send. ### Response: def run(self): """ Attmept to deliver the first outgoing L...
def lab_office(self, column=None, value=None, **kwargs): """Abbreviations, names, and locations of labratories and offices.""" return self._resolve_call('GIC_LAB_OFFICE', column, value, **kwargs)
Abbreviations, names, and locations of labratories and offices.
Below is the the instruction that describes the task: ### Input: Abbreviations, names, and locations of labratories and offices. ### Response: def lab_office(self, column=None, value=None, **kwargs): """Abbreviations, names, and locations of labratories and offices.""" return self._resolve_call('GI...
def _read_amino_acids(): """Read the amino acid information from a resource file.""" this_dir = os.path.dirname(os.path.abspath(__file__)) aa_file = os.path.join(this_dir, os.pardir, 'resources', 'amino_acids.tsv') amino_acids = {} amino_acids_reverse = {} with open(aa_file, 'rt') as fh: ...
Read the amino acid information from a resource file.
Below is the the instruction that describes the task: ### Input: Read the amino acid information from a resource file. ### Response: def _read_amino_acids(): """Read the amino acid information from a resource file.""" this_dir = os.path.dirname(os.path.abspath(__file__)) aa_file = os.path.join(this_dir...
def search_maintenance_window_entities(self, **kwargs): # noqa: E501 """Search over a customer's maintenance windows # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread...
Search over a customer's maintenance windows # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_maintenance_window_entities(async_req=True) >>> result = th...
Below is the the instruction that describes the task: ### Input: Search over a customer's maintenance windows # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.searc...
def first_active(self): """ Returns the first non-skipped actor. :return: the first active actor, None if not available :rtype: Actor """ result = None for actor in self.actors: if not actor.skip: result = actor break ...
Returns the first non-skipped actor. :return: the first active actor, None if not available :rtype: Actor
Below is the the instruction that describes the task: ### Input: Returns the first non-skipped actor. :return: the first active actor, None if not available :rtype: Actor ### Response: def first_active(self): """ Returns the first non-skipped actor. :return: the first acti...
def plot_contpix(self, x, y, contpix_x, contpix_y, figname): """ Plot baseline spec with continuum pix overlaid Parameters ---------- """ fig, axarr = plt.subplots(2, sharex=True) plt.xlabel(r"Wavelength $\lambda (\AA)$") plt.xlim(min(x), max(x)) ax = ax...
Plot baseline spec with continuum pix overlaid Parameters ----------
Below is the the instruction that describes the task: ### Input: Plot baseline spec with continuum pix overlaid Parameters ---------- ### Response: def plot_contpix(self, x, y, contpix_x, contpix_y, figname): """ Plot baseline spec with continuum pix overlaid Parameters ...
def channel(self, channel_id=None, auto_encode_decode=True): """Fetch a Channel object identified by the numeric channel_id, or create that object if it doesn't already exist. See Channel for meaning of auto_encode_decode. If the channel already exists, the auto_* flag will not be update...
Fetch a Channel object identified by the numeric channel_id, or create that object if it doesn't already exist. See Channel for meaning of auto_encode_decode. If the channel already exists, the auto_* flag will not be updated.
Below is the the instruction that describes the task: ### Input: Fetch a Channel object identified by the numeric channel_id, or create that object if it doesn't already exist. See Channel for meaning of auto_encode_decode. If the channel already exists, the auto_* flag will not be updated. ...
def build_tool(self, doc, entity): """Builds a tool object out of a string representation. Returns built tool. Raises SPDXValueError if failed to extract tool name or name is malformed """ match = self.tool_re.match(entity) if match and validations.validate_tool_name(matc...
Builds a tool object out of a string representation. Returns built tool. Raises SPDXValueError if failed to extract tool name or name is malformed
Below is the the instruction that describes the task: ### Input: Builds a tool object out of a string representation. Returns built tool. Raises SPDXValueError if failed to extract tool name or name is malformed ### Response: def build_tool(self, doc, entity): """Builds a tool object out of...
def _qualify_map(key, content): """ When a dictionary key is optional/optionalnull/mandatory, its corresponding _value_ is decorated in an Optional/OptionalNull/Mandatory tuple. This function undo the decoration when necessary. """ if not isinstance(key, basestring): return key, content ...
When a dictionary key is optional/optionalnull/mandatory, its corresponding _value_ is decorated in an Optional/OptionalNull/Mandatory tuple. This function undo the decoration when necessary.
Below is the the instruction that describes the task: ### Input: When a dictionary key is optional/optionalnull/mandatory, its corresponding _value_ is decorated in an Optional/OptionalNull/Mandatory tuple. This function undo the decoration when necessary. ### Response: def _qualify_map(key, content): ...
def send(self, request): """ Send request to server and return server response. """ self._logger.debug('Opening connection') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.connect((self._hos...
Send request to server and return server response.
Below is the the instruction that describes the task: ### Input: Send request to server and return server response. ### Response: def send(self, request): """ Send request to server and return server response. """ self._logger.debug('Opening connection') sock = socket.socket...