_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q56300
DevicesService.disconnect
train
def disconnect(self, id): # pylint: disable=invalid-name,redefined-builtin """Close proxy connection to a device's management interface. :param id: Device ID as an int. """ return self.service.post(self.base+str(id)+'/disconnect/')
python
{ "resource": "" }
q56301
DevicesService.power_on
train
def power_on(self, id): # pylint: disable=invalid-name,redefined-builtin """Power on a device using it's power on command. :param id: Device ID as an int. :return: :class:`devices.PowerCmd <devices.PowerCmd>` object :rtype: devices.PowerCmd """ schema = PowerCmdSchema() ...
python
{ "resource": "" }
q56302
DevicesService.bulk_copy
train
def bulk_copy(self, ids): """Bulk copy a set of devices. :param ids: Int list of device IDs. :return: :class:`devices.Device <devices.Device>` list """ schema = DeviceSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
python
{ "resource": "" }
q56303
ensure_list
train
def ensure_list(value: Union[T, Sequence[T]]) -> Sequence[T]: """Wrap value in list if it is not one.""" if value is None: return [] return value if isinstance(value, list) else [value]
python
{ "resource": "" }
q56304
color
train
def color(out_string, color='grn'): """ Highlight string for terminal color coding. Purpose: We use this utility function to insert a ANSI/win32 color code | and Bright style marker before a string, and reset the color and | style after the string. We then return the string with these ...
python
{ "resource": "" }
q56305
color_diffs
train
def color_diffs(string): """ Add color ANSI codes for diff lines. Purpose: Adds the ANSI/win32 color coding for terminal output to output | produced from difflib. @param string: The string to be replacing @type string: str @returns: The new string with ANSI codes injected. @rtype: ...
python
{ "resource": "" }
q56306
index
train
def index(): """List linked accounts.""" oauth = current_app.extensions['oauthlib.client'] services = [] service_map = {} i = 0 for appid, conf in six.iteritems( current_app.config['OAUTHCLIENT_REMOTE_APPS']): if not conf.get('hide', False): services.append(dict...
python
{ "resource": "" }
q56307
element_id_by_label
train
def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for')
python
{ "resource": "" }
q56308
find_field
train
def find_field(browser, field, value): """Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element. """ return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, va...
python
{ "resource": "" }
q56309
find_any_field
train
def find_any_field(browser, field_types, field_name): """ Find a field of any of the specified types. """ return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) )
python
{ "resource": "" }
q56310
find_field_by_label
train
def find_field_by_label(browser, field, label): """Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id. """ return XPa...
python
{ "resource": "" }
q56311
wait_for
train
def wait_for(func): """ A decorator to invoke a function periodically until it returns a truthy value. """ def wrapped(*args, **kwargs): timeout = kwargs.pop('timeout', 15) start = time() result = None while time() - start < timeout: result = func(*args...
python
{ "resource": "" }
q56312
get_defaults
train
def get_defaults(): """ Returns a dictionary of variables and their possibly os-dependent defaults. """ DEFAULTS = {} # Determine the run-time pipe read/write buffer. if 'PC_PIPE_BUF' in os.pathconf_names: # unix x, y = os.pipe() DEFAULTS['PIPE_BUF'] = os.fpathconf(x...
python
{ "resource": "" }
q56313
site_url
train
def site_url(url): """ Determine the server URL. """ base_url = 'http://%s' % socket.gethostname() if server.port is not 80: base_url += ':%d' % server.port return urlparse.urljoin(base_url, url)
python
{ "resource": "" }
q56314
_get_external_id
train
def _get_external_id(account_info): """Get external id from account info.""" if all(k in account_info for k in ('external_id', 'external_method')): return dict(id=account_info['external_id'], method=account_info['external_method']) return None
python
{ "resource": "" }
q56315
oauth_get_user
train
def oauth_get_user(client_id, account_info=None, access_token=None): """Retrieve user object for the given request. Uses either the access token or extracted account information to retrieve the user object. :param client_id: The client id. :param account_info: The dictionary with the account info....
python
{ "resource": "" }
q56316
oauth_authenticate
train
def oauth_authenticate(client_id, user, require_existing_link=False): """Authenticate an oauth authorized callback. :param client_id: The client id. :param user: A user instance. :param require_existing_link: If ``True``, check if remote account exists. (Default: ``False``) :returns: ``True...
python
{ "resource": "" }
q56317
oauth_register
train
def oauth_register(form): """Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance. """ if form.validate(): data = form.to_dict() if not data.get('password'): data['password'] = '' user = register_user...
python
{ "resource": "" }
q56318
oauth_link_external_id
train
def oauth_link_external_id(user, external_id=None): """Link a user to an external id. :param user: A :class:`invenio_accounts.models.User` instance. :param external_id: The external id associated with the user. (Default: ``None``) :raises invenio_oauthclient.errors.AlreadyLinkedError: Raised if...
python
{ "resource": "" }
q56319
oauth_unlink_external_id
train
def oauth_unlink_external_id(external_id): """Unlink a user from an external id. :param external_id: The external id associated with the user. """ with db.session.begin_nested(): UserIdentity.query.filter_by(id=external_id['id'], method=external_id['method']...
python
{ "resource": "" }
q56320
create_registrationform
train
def create_registrationform(*args, **kwargs): """Make a registration form.""" class RegistrationForm(_security.confirm_register_form): password = None recaptcha = None return RegistrationForm(*args, **kwargs)
python
{ "resource": "" }
q56321
fill_form
train
def fill_form(form, data): """Prefill form with data. :param form: The form to fill. :param data: The data to insert in the form. :returns: A pre-filled form. """ for (key, value) in data.items(): if hasattr(form, key): if isinstance(value, dict): fill_form(g...
python
{ "resource": "" }
q56322
_get_csrf_disabled_param
train
def _get_csrf_disabled_param(): """Return the right param to disable CSRF depending on WTF-Form version. From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of `meta={csrf: True/False}`. """ import flask_wtf from pkg_resources import parse_version supports_meta = parse_...
python
{ "resource": "" }
q56323
ParallelRunner.run
train
def run(self): """ Find and load step definitions, and them find and load features under `base_path` specified on constructor """ try: self.loader.find_and_load_step_definitions() except StepLoadingError, e: print "Error loading step definitions:\n", e ...
python
{ "resource": "" }
q56324
open_connection
train
def open_connection(ip, username, password, function, args, write=False, conn_timeout=5, sess_timeout=300, port=22): """ Open a Jaide session with the device. To open a Jaide session to the device, and run the appropriate function against the device. Arguments for the downstream functio...
python
{ "resource": "" }
q56325
command
train
def command(jaide, commands, format="text", xpath=False): """ Run an operational command. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param commands: the operational commands to send to the device. @type commands: str or list @param format: The desired out...
python
{ "resource": "" }
q56326
shell
train
def shell(jaide, commands): """ Send shell commands to a device. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param commands: The shell commands to send to the device. @type commands: str or list. @returns: The output of the commands. @rtype str ""...
python
{ "resource": "" }
q56327
get_all_keys
train
def get_all_keys(reactor, key_type, value_type, etcd_address): """Returns all keys from etcd. :param reactor: reference to Twisted' reactor. :param etcd_address: Address with port number where etcd is running. :return: An instance of txaioetcd.Range containing all keys and their values....
python
{ "resource": "" }
q56328
Scan.stop
train
def stop(self, timeout=None): """ Send the GET request required to stop the scan If timeout is not specified we just send the request and return. When it is the method will wait for (at most) :timeout: seconds until the scan changes it's status/stops. If the timeout is reached t...
python
{ "resource": "" }
q56329
xrb_address_to_public_key
train
def xrb_address_to_public_key(address): """ Convert an xrb address to public key in bytes >>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i'\ '81r51e3i81r51e3i81r51e3imxssakuq') b'00000000000000000000000000000000' :param address: xrb address :typ...
python
{ "resource": "" }
q56330
generate_account
train
def generate_account(seed=None, index=0): """ Generates an adhoc account and keypair >>> account = generate_account(seed=unhexlify('0'*64)) {'address': u'xrb_3i1aq1cchnmbn9x5rsbap8b15akfh7wj7pwskuzi7ahz8oq6cobd99d4r3b7', 'private_key_bytes': '\x9f\x0eDLi\xf7zI\xbd\x0b\xe8\x9d\xb9,8\xfeq>\tc\x16\\\...
python
{ "resource": "" }
q56331
spasser
train
def spasser(inbox, s=None): """ Passes inputs with indecies in s. By default passes the whole inbox. Arguments: - s(sequence) [default: ``None``] The default translates to a range for all inputs of the "inbox" i.e. ``range(len(inbox))`` """ seq = (s or range(len(inbox))) ret...
python
{ "resource": "" }
q56332
sjoiner
train
def sjoiner(inbox, s=None, join=""): """ String joins input with indices in s. Arguments: - s(sequence) [default: ``None``] ``tuple`` or ``list`` of indices of the elements which will be joined. - join(``str``) [default: ``""``] String which will join the elements of the inbo...
python
{ "resource": "" }
q56333
load_item
train
def load_item(inbox, type="string", remove=True, buffer=None): """ Loads data from a file. Determines the file type automatically ``"file"``, ``"fifo"``, ``"socket"``, but allows to specify the representation type ``"string"`` or ``"mmap"`` for memory mapped access to the file. Returns the loaded...
python
{ "resource": "" }
q56334
pickle_dumps
train
def pickle_dumps(inbox): """ Serializes the first element of the input using the pickle protocol using the fastes binary protocol. """ # http://bugs.python.org/issue4074 gc.disable() str_ = cPickle.dumps(inbox[0], cPickle.HIGHEST_PROTOCOL) gc.enable() return str_
python
{ "resource": "" }
q56335
pickle_loads
train
def pickle_loads(inbox): """ Deserializes the first element of the input using the pickle protocol. """ gc.disable() obj = cPickle.loads(inbox[0]) gc.enable() return obj
python
{ "resource": "" }
q56336
json_dumps
train
def json_dumps(inbox): """ Serializes the first element of the input using the JSON protocol as implemented by the ``json`` Python 2.6 library. """ gc.disable() str_ = json.dumps(inbox[0]) gc.enable() return str_
python
{ "resource": "" }
q56337
json_loads
train
def json_loads(inbox): """ Deserializes the first element of the input using the JSON protocol as implemented by the ``json`` Python 2.6 library. """ gc.disable() obj = json.loads(inbox[0]) gc.enable() return obj
python
{ "resource": "" }
q56338
at_time_validate
train
def at_time_validate(ctx, param, value): """ Callback validating the at_time commit option. Purpose: Validates the `at time` option for the commit command. Only the | the following two formats are supported: 'hh:mm[:ss]' or | 'yyyy-mm-dd hh:mm[:ss]' (seconds are optional). @param ctx...
python
{ "resource": "" }
q56339
write_validate
train
def write_validate(ctx, param, value): """ Validate the -w option. Purpose: Validates the `-w`|`--write` option. Two arguments are expected. | The first is the mode, which must be in ['s', 'single', 'm', | 'multiple']. The mode determins if we're writing to one file for | all ...
python
{ "resource": "" }
q56340
write_out
train
def write_out(input): """ Callback function to write the output from the script. @param input: A tuple containing two things: | 1. None or Tuple of file mode and destination filepath | 2. The output of the jaide command that will be either | written to sys.std...
python
{ "resource": "" }
q56341
main
train
def main(ctx, host, password, port, quiet, session_timeout, connect_timeout, username): """ Manipulate one or more Junos devices. Purpose: The main function is the entry point for the jaide tool. Click | handles arguments, commands and options. The parameters passed to | this fun...
python
{ "resource": "" }
q56342
compare
train
def compare(ctx, commands): """ Run 'show | compare' for set commands. @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorator. @type ctx: click.C...
python
{ "resource": "" }
q56343
diff_config
train
def diff_config(ctx, second_host, mode): """ Config comparison between two devices. @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorator. @type...
python
{ "resource": "" }
q56344
AliasedGroup.get_command
train
def get_command(self, ctx, cmd_name): """ Allow for partial commands. """ rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)] if not matches: ...
python
{ "resource": "" }
q56345
convert
train
def convert(value, from_unit, to_unit): """ Converts a value from `from_unit` units to `to_unit` units :param value: value to convert :type value: int or str or decimal.Decimal :param from_unit: unit to convert from :type from_unit: str :param to_unit: unit to convert to :type to_unit...
python
{ "resource": "" }
q56346
endpoint
train
def endpoint(request): """Endpoint that SNS accesses. Includes logic verifying request""" # pylint: disable=too-many-return-statements,too-many-branches # In order to 'hide' the endpoint, all non-POST requests should return # the site's default HTTP404 if request.method != 'POST': raise Htt...
python
{ "resource": "" }
q56347
process_message
train
def process_message(message, notification): """ Function to process a JSON message delivered from Amazon """ # Confirm that there are 'notificationType' and 'mail' fields in our # message if not set(VITAL_MESSAGE_FIELDS) <= set(message): # At this point we're sure that it's Amazon sendin...
python
{ "resource": "" }
q56348
process_bounce
train
def process_bounce(message, notification): """Function to process a bounce notification""" mail = message['mail'] bounce = message['bounce'] bounces = [] for recipient in bounce['bouncedRecipients']: # Create each bounce record. Add to a list for reference later. bounces += [Bounce....
python
{ "resource": "" }
q56349
process_complaint
train
def process_complaint(message, notification): """Function to process a complaint notification""" mail = message['mail'] complaint = message['complaint'] if 'arrivalDate' in complaint: arrival_date = clean_time(complaint['arrivalDate']) else: arrival_date = None complaints = [] ...
python
{ "resource": "" }
q56350
process_delivery
train
def process_delivery(message, notification): """Function to process a delivery notification""" mail = message['mail'] delivery = message['delivery'] if 'timestamp' in delivery: delivered_datetime = clean_time(delivery['timestamp']) else: delivered_datetime = None deliveries = [...
python
{ "resource": "" }
q56351
click_on_label
train
def click_on_label(step, label): """ Click on a label """ with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str( '//label[normalize-space(text()) = "%s"]' % label)) elem.click()
python
{ "resource": "" }
q56352
element_focused
train
def element_focused(step, id): """ Check if the element is focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_true(step, elem == focused)
python
{ "resource": "" }
q56353
element_not_focused
train
def element_not_focused(step, id): """ Check if the element is not focused """ elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) focused = world.browser.switch_to_active_element() assert_false(step, elem == focused)
python
{ "resource": "" }
q56354
input_has_value
train
def input_has_value(step, field_name, value): """ Check that the form input element has given value. """ with AssertContextManager(step): text_field = find_any_field(world.browser, DATE_FIELDS + TEXT_FIELDS, field_name) ...
python
{ "resource": "" }
q56355
submit_form_id
train
def submit_form_id(step, id): """ Submit the form having given id. """ form = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id))) form.submit()
python
{ "resource": "" }
q56356
submit_form_action
train
def submit_form_action(step, url): """ Submit the form having given action URL. """ form = world.browser.find_element_by_xpath(str('//form[@action="%s"]' % url)) form.submit()
python
{ "resource": "" }
q56357
check_alert
train
def check_alert(step, text): """ Check the alert text """ try: alert = Alert(world.browser) assert_equals(alert.text, text) except WebDriverException: # PhantomJS is kinda poor pass
python
{ "resource": "" }
q56358
page_title
train
def page_title(step, title): """ Check that the page title matches the given one. """ with AssertContextManager(step): assert_equals(world.browser.title, title)
python
{ "resource": "" }
q56359
TagsService.get
train
def get(self, name): """Get a tag. :param name: Tag name as string. :return: :class:`tags.Tag <tags.Tag>` object :rtype: tags.Tag """ schema = TagSchema() resp = self.service.get_id(self.base, name) return self.service.decode(schema, resp)
python
{ "resource": "" }
q56360
TagsService.edit
train
def edit(self, resource): """Edit a tag. :param resource: :class:`tags.Tag <tags.Tag>` object :return: :class:`tags.Tag <tags.Tag>` object :rtype: tags.Tag """ schema = TagSchema(only=('name', 'configs', 'devices', 'packages', 'results')) json = self.service.enco...
python
{ "resource": "" }
q56361
Lease.remaining
train
def remaining(self): """ Get the remaining time-to-live of this lease. :returns: TTL in seconds. :rtype: int """ if self._expired: raise Expired() obj = { u'ID': self.lease_id, } data = json.dumps(obj).encode('utf8') ...
python
{ "resource": "" }
q56362
Lease.revoke
train
def revoke(self): """ Revokes a lease. All keys attached to the lease will expire and be deleted. :returns: Response header. :rtype: instance of :class:`txaioetcd.Header` """ if self._expired: raise Expired() obj = { # ID is the l...
python
{ "resource": "" }
q56363
Lease.refresh
train
def refresh(self): """ Keeps the lease alive by streaming keep alive requests from the client to the server and streaming keep alive responses from the server to the client. :returns: Response header. :rtype: instance of :class:`txaioetcd.Header` """ if s...
python
{ "resource": "" }
q56364
NewsCorpusGenerator.read_links_file
train
def read_links_file(self,file_path): ''' Read links and associated categories for specified articles in text file seperated by a space Args: file_path (str): The path to text file with news article links and category Returns: ...
python
{ "resource": "" }
q56365
Client.call
train
def call(self, action, params=None): """ Makes an RPC call to the server and returns the json response :param action: RPC method to call :type action: str :param params: Dict of arguments to send with RPC call :type params: dict :raises: :py:exc:`nano.rpc.RPCEx...
python
{ "resource": "" }
q56366
Client._process_value
train
def _process_value(self, value, type): """ Process a value that will be sent to backend :param value: the value to return :param type: hint for what sort of value this is :type type: str """ if not isinstance(value, six.string_types + (list,)): val...
python
{ "resource": "" }
q56367
Client.block_account
train
def block_account(self, hash): """ Returns the account containing block :param hash: Hash of the block to return account for :type hash: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.block_account( ... hash="000D1BAEC8EC208142C99059B393051BAC8380F9B5...
python
{ "resource": "" }
q56368
Client.block_count
train
def block_count(self): """ Reports the number of blocks in the ledger and unchecked synchronizing blocks :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.block_count() { "count": 1000, "unchecked": 10 } """ resp = self.call(...
python
{ "resource": "" }
q56369
Client.mrai_from_raw
train
def mrai_from_raw(self, amount): """ Divide a raw amount down by the Mrai ratio. :param amount: Amount in raw to convert to Mrai :type amount: int :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.mrai_from_raw(amount=1000000000000000000000000000000) 1 ...
python
{ "resource": "" }
q56370
Client.mrai_to_raw
train
def mrai_to_raw(self, amount): """ Multiply an Mrai amount by the Mrai ratio. :param amount: Amount in Mrai to convert to raw :type amount: int :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.mrai_to_raw(amount=1) 1000000000000000000000000000000 """ ...
python
{ "resource": "" }
q56371
Client.krai_from_raw
train
def krai_from_raw(self, amount): """ Divide a raw amount down by the krai ratio. :param amount: Amount in raw to convert to krai :type amount: int :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.krai_from_raw(amount=1000000000000000000000000000) 1 """ ...
python
{ "resource": "" }
q56372
Client.krai_to_raw
train
def krai_to_raw(self, amount): """ Multiply an krai amount by the krai ratio. :param amount: Amount in krai to convert to raw :type amount: int :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.krai_to_raw(amount=1) 1000000000000000000000000000 """ ...
python
{ "resource": "" }
q56373
Client.rai_from_raw
train
def rai_from_raw(self, amount): """ Divide a raw amount down by the rai ratio. :param amount: Amount in raw to convert to rai :type amount: int :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.rai_from_raw(amount=1000000000000000000000000) 1 """ ...
python
{ "resource": "" }
q56374
Client.rai_to_raw
train
def rai_to_raw(self, amount): """ Multiply an rai amount by the rai ratio. :param amount: Amount in rai to convert to raw :type amount: int :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.rai_to_raw(amount=1) 1000000000000000000000000 """ amo...
python
{ "resource": "" }
q56375
Client.payment_begin
train
def payment_begin(self, wallet): """ Begin a new payment session. Searches wallet for an account that's marked as available and has a 0 balance. If one is found, the account number is returned and is marked as unavailable. If no account is found, a new account is created, placed ...
python
{ "resource": "" }
q56376
Client.payment_init
train
def payment_init(self, wallet): """ Marks all accounts in wallet as available for being used as a payment session. :param wallet: Wallet to init payment in :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.payment_init( ... wallet="...
python
{ "resource": "" }
q56377
Client.payment_end
train
def payment_end(self, account, wallet): """ End a payment session. Marks the account as available for use in a payment session. :param account: Account to mark available :type account: str :param wallet: Wallet to end payment session for :type wallet: str ...
python
{ "resource": "" }
q56378
Client.representatives
train
def representatives(self, count=None, sorting=False): """ Returns a list of pairs of representative and its voting weight :param count: Max amount of representatives to return :type count: int :param sorting: If true, sorts by weight :type sorting: bool :raises...
python
{ "resource": "" }
q56379
Client.version
train
def version(self): """ Returns the node's RPC version :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.version() { "rpc_version": 1, "store_version": 10, "node_vendor": "RaiBlocks 9.0" } """ resp = self.call('version...
python
{ "resource": "" }
q56380
_extract_email
train
def _extract_email(gh): """Get user email from github.""" return next( (x.email for x in gh.emails() if x.verified and x.primary), None)
python
{ "resource": "" }
q56381
authorized
train
def authorized(resp, remote): """Authorized callback handler for GitHub. :param resp: The response. :param remote: The remote application. """ if resp and 'error' in resp: if resp['error'] == 'bad_verification_code': # See https://developer.github.com/v3/oauth/#bad-verification-...
python
{ "resource": "" }
q56382
initial_variant_sequences_from_reads
train
def initial_variant_sequences_from_reads( variant_reads, max_nucleotides_before_variant=None, max_nucleotides_after_variant=None): """ Get all unique sequences from reads spanning a variant locus. This will include partial sequences due to reads starting in the middle of the sequ...
python
{ "resource": "" }
q56383
trim_variant_sequences
train
def trim_variant_sequences(variant_sequences, min_variant_sequence_coverage): """ Trim VariantSequences to desired coverage and then combine any subsequences which get generated. """ n_total = len(variant_sequences) trimmed_variant_sequences = [ variant_sequence.trim_by_coverage(min_vari...
python
{ "resource": "" }
q56384
filter_variant_sequences
train
def filter_variant_sequences( variant_sequences, preferred_sequence_length, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,): """ Drop variant sequences which are shorter than request or don't have enough supporting reads. """ variant_sequences = trim_variant_seq...
python
{ "resource": "" }
q56385
reads_generator_to_sequences_generator
train
def reads_generator_to_sequences_generator( variant_and_reads_generator, min_alt_rna_reads=MIN_ALT_RNA_READS, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE, preferred_sequence_length=VARIANT_SEQUENCE_LENGTH, variant_sequence_assembly=VARIANT_SEQUENCE_ASSEMBLY): ...
python
{ "resource": "" }
q56386
VariantSequence.contains
train
def contains(self, other): """ Is the other VariantSequence a subsequence of this one? The two sequences must agree on the alt nucleotides, the prefix of the longer must contain the prefix of the shorter, and the suffix of the longer must contain the suffix of the shorter. ...
python
{ "resource": "" }
q56387
VariantSequence.left_overlaps
train
def left_overlaps(self, other, min_overlap_size=1): """ Does this VariantSequence overlap another on the left side? """ if self.alt != other.alt: # allele must match! return False if len(other.prefix) > len(self.prefix): # only consider strin...
python
{ "resource": "" }
q56388
VariantSequence.add_reads
train
def add_reads(self, reads): """ Create another VariantSequence with more supporting reads. """ if len(reads) == 0: return self new_reads = self.reads.union(reads) if len(new_reads) > len(self.reads): return VariantSequence( prefix=s...
python
{ "resource": "" }
q56389
VariantSequence.variant_indices
train
def variant_indices(self): """ When we combine prefix + alt + suffix into a single string, what are is base-0 index interval which gets us back the alt sequence? First returned index is inclusive, the second is exclusive. """ variant_start_index = len(self.prefix) ...
python
{ "resource": "" }
q56390
VariantSequence.coverage
train
def coverage(self): """ Returns NumPy array indicating number of reads covering each nucleotides of this sequence. """ variant_start_index, variant_end_index = self.variant_indices() n_nucleotides = len(self) coverage_array = np.zeros(n_nucleotides, dtype="int32")...
python
{ "resource": "" }
q56391
VariantSequence.trim_by_coverage
train
def trim_by_coverage(self, min_reads): """ Given the min number of reads overlapping each nucleotide of a variant sequence, trim this sequence by getting rid of positions which are overlapped by fewer reads than specified. """ read_count_array = self.coverage() lo...
python
{ "resource": "" }
q56392
trim_N_nucleotides
train
def trim_N_nucleotides(prefix, suffix): """ Drop all occurrences of 'N' from prefix and suffix nucleotide strings by trimming. """ if 'N' in prefix: # trim prefix to exclude all occurrences of N rightmost_index = prefix.rfind('N') logger.debug( "Trimming %d nucleo...
python
{ "resource": "" }
q56393
convert_from_bytes_if_necessary
train
def convert_from_bytes_if_necessary(prefix, suffix): """ Depending on how we extract data from pysam we may end up with either a string or a byte array of nucleotides. For consistency and simplicity, we want to only use strings in the rest of our code. """ if isinstance(prefix, bytes): p...
python
{ "resource": "" }
q56394
Producer.publish
train
def publish(self, data, **kwargs): """Validate operation type.""" assert data.get('op') in {'index', 'create', 'delete', 'update'} return super(Producer, self).publish(data, **kwargs)
python
{ "resource": "" }
q56395
RecordIndexer.index
train
def index(self, record): """Index a record. The caller is responsible for ensuring that the record has already been committed to the database. If a newer version of a record has already been indexed then the provided record will not be indexed. This behavior can be controlled by...
python
{ "resource": "" }
q56396
RecordIndexer.process_bulk_queue
train
def process_bulk_queue(self, es_bulk_kwargs=None): """Process bulk indexing queue. :param dict es_bulk_kwargs: Passed to :func:`elasticsearch:elasticsearch.helpers.bulk`. """ with current_celery_app.pool.acquire(block=True) as conn: consumer = Consumer( ...
python
{ "resource": "" }
q56397
RecordIndexer._bulk_op
train
def _bulk_op(self, record_id_iterator, op_type, index=None, doc_type=None): """Index record in Elasticsearch asynchronously. :param record_id_iterator: Iterator that yields record UUIDs. :param op_type: Indexing operation (one of ``index``, ``create``, ``delete`` or ``update``). ...
python
{ "resource": "" }
q56398
RecordIndexer._actionsiter
train
def _actionsiter(self, message_iterator): """Iterate bulk actions. :param message_iterator: Iterator yielding messages from a queue. """ for message in message_iterator: payload = message.decode() try: if payload['op'] == 'delete': ...
python
{ "resource": "" }
q56399
RecordIndexer._delete_action
train
def _delete_action(self, payload): """Bulk delete action. :param payload: Decoded message body. :returns: Dictionary defining an Elasticsearch bulk 'delete' action. """ index, doc_type = payload.get('index'), payload.get('doc_type') if not (index and doc_type): ...
python
{ "resource": "" }