_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q259100 | OMXPlayer.quit | validation | def quit(self):
"""
Quit the player, blocking until the process has died
"""
if self._process is None:
logger.debug('Quit was called after self._process had already been released')
return
try:
logger.debug('Quitting OMXPlayer')
proc... | python | {
"resource": ""
} |
q259101 | BlogDetailView.render_to_response | validation | def render_to_response(self, context, **response_kwargs):
"""
Returns a response with a template depending if the request is ajax
or not and it renders with the given context.
"""
if self.request.is_ajax():
template = self.page_template
else:
temp... | python | {
"resource": ""
} |
q259102 | translate_value | validation | def translate_value(document_field, form_value):
"""
Given a document_field and a form_value this will translate the value
to the correct result for mongo to use.
"""
value = form_value
if isinstance(document_field, ReferenceField):
value = document_field.document_type.objects.get(id=for... | python | {
"resource": ""
} |
q259103 | trim_field_key | validation | def trim_field_key(document, field_key):
"""
Returns the smallest delimited version of field_key that
is an attribute on document.
return (key, left_over_array)
"""
trimming = True
left_over_key_values = []
current_key = field_key
while trimming and current_key:
if hasattr(d... | python | {
"resource": ""
} |
q259104 | BaseMongoAdmin.has_edit_permission | validation | def has_edit_permission(self, request):
""" Can edit this object """
return request.user.is_authenticated and request.user.is_active and request.user.is_staff | python | {
"resource": ""
} |
q259105 | BaseMongoAdmin.has_add_permission | validation | def has_add_permission(self, request):
""" Can add this object """
return request.user.is_authenticated and request.user.is_active and request.user.is_staff | python | {
"resource": ""
} |
q259106 | BaseMongoAdmin.has_delete_permission | validation | def has_delete_permission(self, request):
""" Can delete this object """
return request.user.is_authenticated and request.user.is_active and request.user.is_superuser | python | {
"resource": ""
} |
q259107 | MongoModelFormBaseMixin.set_form_fields | validation | def set_form_fields(self, form_field_dict, parent_key=None, field_type=None):
"""
Set the form fields for every key in the form_field_dict.
Params:
form_field_dict -- a dictionary created by get_form_field_dict
parent_key -- the key for the previous key in the recursive call... | python | {
"resource": ""
} |
q259108 | MongoModelFormBaseMixin.get_field_value | validation | def get_field_value(self, field_key):
"""
Given field_key will return value held at self.model_instance. If
model_instance has not been provided will return None.
"""
def get_value(document, field_key):
# Short circuit the function if we do not have a document
... | python | {
"resource": ""
} |
q259109 | has_digit | validation | def has_digit(string_or_list, sep="_"):
"""
Given a string or a list will return true if the last word or
element is a digit. sep is used when a string is given to know
what separates one word from another.
"""
if isinstance(string_or_list, (tuple, list)):
list_length = len(string_or_li... | python | {
"resource": ""
} |
q259110 | make_key | validation | def make_key(*args, **kwargs):
"""
Given any number of lists and strings will join them in order as one
string separated by the sep kwarg. sep defaults to u"_".
Add exclude_last_string=True as a kwarg to exclude the last item in a
given string after being split by sep. Note if you only have one w... | python | {
"resource": ""
} |
q259111 | MongoModelForm.set_fields | validation | def set_fields(self):
"""Sets existing data to form fields."""
# Get dictionary map of current model
if self.is_initialized:
self.model_map_dict = self.create_document_dictionary(self.model_instance)
else:
self.model_map_dict = self.create_document_dictionary(sel... | python | {
"resource": ""
} |
q259112 | MongoModelForm.set_post_data | validation | def set_post_data(self):
"""
Need to set form data so that validation on all post data occurs and
places newly entered form data on the form object.
"""
self.form.data = self.post_data_dict
# Specifically adding list field keys to the form so they are included
... | python | {
"resource": ""
} |
q259113 | MongoModelForm.get_form | validation | def get_form(self):
"""
Generate the form for view.
"""
self.set_fields()
if self.post_data_dict is not None:
self.set_post_data()
return self.form | python | {
"resource": ""
} |
q259114 | MongoModelForm.create_list_dict | validation | def create_list_dict(self, document, list_field, doc_key):
"""
Genereates a dictionary representation of the list field. Document
should be the document the list_field comes from.
DO NOT CALL DIRECTLY
"""
list_dict = {"_document": document}
if isinstance(list_fi... | python | {
"resource": ""
} |
q259115 | MongoModelForm.create_document_dictionary | validation | def create_document_dictionary(self, document, document_key=None,
owner_document=None):
"""
Given document generates a dictionary representation of the document.
Includes the widget for each for each field in the document.
"""
... | python | {
"resource": ""
} |
q259116 | get_widget | validation | def get_widget(model_field, disabled=False):
"""Choose which widget to display for a field."""
attrs = get_attrs(model_field, disabled)
if hasattr(model_field, "max_length") and not model_field.max_length:
return forms.Textarea(attrs=attrs)
elif isinstance(model_field, DateTimeField):
... | python | {
"resource": ""
} |
q259117 | get_attrs | validation | def get_attrs(model_field, disabled=False):
"""Set attributes on the display widget."""
attrs = {}
attrs['class'] = 'span6 xlarge'
if disabled or isinstance(model_field, ObjectIdField):
attrs['class'] += ' disabled'
attrs['readonly'] = 'readonly'
return attrs | python | {
"resource": ""
} |
q259118 | get_form_field_class | validation | def get_form_field_class(model_field):
"""Gets the default form field for a mongoenigne field."""
FIELD_MAPPING = {
IntField: forms.IntegerField,
StringField: forms.CharField,
FloatField: forms.FloatField,
BooleanField: forms.BooleanField,
DateTimeField: forms.DateTimeF... | python | {
"resource": ""
} |
q259119 | DocumentListView.get_qset | validation | def get_qset(self, queryset, q):
"""Performs filtering against the default queryset returned by
mongoengine.
"""
if self.mongoadmin.search_fields and q:
params = {}
for field in self.mongoadmin.search_fields:
if field == 'id':
... | python | {
"resource": ""
} |
q259120 | DocumentListView.get_context_data | validation | def get_context_data(self, **kwargs):
"""Injects data into the context to replicate CBV ListView."""
context = super(DocumentListView, self).get_context_data(**kwargs)
context = self.set_permissions_in_context(context)
if not context['has_view_permission']:
return HttpRespon... | python | {
"resource": ""
} |
q259121 | DocumentListView.post | validation | def post(self, request, *args, **kwargs):
"""Creates new mongoengine records."""
# TODO - make sure to check the rights of the poster
#self.get_queryset() # TODO - write something that grabs the document class better
form_class = self.get_form_class()
form = self.get_form(form_cl... | python | {
"resource": ""
} |
q259122 | MongonautViewMixin.get_mongoadmins | validation | def get_mongoadmins(self):
""" Returns a list of all mongoadmin implementations for the site """
apps = []
for app_name in settings.INSTALLED_APPS:
mongoadmin = "{0}.mongoadmin".format(app_name)
try:
module = import_module(mongoadmin)
except Im... | python | {
"resource": ""
} |
q259123 | MongonautViewMixin.set_mongonaut_base | validation | def set_mongonaut_base(self):
""" Sets a number of commonly used attributes """
if hasattr(self, "app_label"):
# prevents us from calling this multiple times
return None
self.app_label = self.kwargs.get('app_label')
self.document_name = self.kwargs.get('document_n... | python | {
"resource": ""
} |
q259124 | MongonautViewMixin.set_permissions_in_context | validation | def set_permissions_in_context(self, context={}):
""" Provides permissions for mongoadmin for use in the context"""
context['has_view_permission'] = self.mongoadmin.has_view_permission(self.request)
context['has_edit_permission'] = self.mongoadmin.has_edit_permission(self.request)
conte... | python | {
"resource": ""
} |
q259125 | MongonautFormViewMixin.process_post_form | validation | def process_post_form(self, success_message=None):
"""
As long as the form is set on the view this method will validate the form
and save the submitted data. Only call this if you are posting data.
The given success_message will be used with the djanog messages framework
if the ... | python | {
"resource": ""
} |
q259126 | MongonautFormViewMixin.process_document | validation | def process_document(self, document, form_key, passed_key):
"""
Given the form_key will evaluate the document and set values correctly for
the document given.
"""
if passed_key is not None:
current_key, remaining_key_array = trim_field_key(document, passed_key)
... | python | {
"resource": ""
} |
q259127 | MongonautFormViewMixin.set_embedded_doc | validation | def set_embedded_doc(self, document, form_key, current_key, remaining_key):
"""Get the existing embedded document if it exists, else created it."""
embedded_doc = getattr(document, current_key, False)
if not embedded_doc:
embedded_doc = document._fields[current_key].document_type_ob... | python | {
"resource": ""
} |
q259128 | MongonautFormViewMixin.set_list_field | validation | def set_list_field(self, document, form_key, current_key, remaining_key, key_array_digit):
"""1. Figures out what value the list ought to have
2. Sets the list
"""
document_field = document._fields.get(current_key)
# Figure out what value the list ought to have
# Non... | python | {
"resource": ""
} |
q259129 | with_tz | validation | def with_tz(request):
"""
Get the time with TZ enabled
"""
dt = datetime.now()
t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}')
c = RequestContext(request)
response = t.render(c)
return HttpResponse(response) | python | {
"resource": ""
} |
q259130 | without_tz | validation | def without_tz(request):
"""
Get the time without TZ enabled
"""
t = Template('{% load tz %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}')
c = RequestContext(request)
response = t.render(c)
return HttpResponse(response) | python | {
"resource": ""
} |
q259131 | is_valid_ip | validation | def is_valid_ip(ip_address):
""" Check Validity of an IP address """
try:
ip = ipaddress.ip_address(u'' + ip_address)
return True
except ValueError as e:
return False | python | {
"resource": ""
} |
q259132 | is_local_ip | validation | def is_local_ip(ip_address):
""" Check if IP is local """
try:
ip = ipaddress.ip_address(u'' + ip_address)
return ip.is_loopback
except ValueError as e:
return None | python | {
"resource": ""
} |
q259133 | EasyTimezoneMiddleware.process_request | validation | def process_request(self, request):
"""
If we can get a valid IP from the request,
look up that address in the database to get the appropriate timezone
and activate it.
Else, use the default.
"""
if not request:
return
if not db_loaded:
... | python | {
"resource": ""
} |
q259134 | ElasticQuery.search | validation | def search(self):
""" This is the most important method """
try:
filters = json.loads(self.query)
except ValueError:
return False
result = self.model_query
if 'filter'in filters.keys():
result = self.parse_filter(filters['filter'])
if ... | python | {
"resource": ""
} |
q259135 | ElasticQuery.parse_filter | validation | def parse_filter(self, filters):
""" This method process the filters """
for filter_type in filters:
if filter_type == 'or' or filter_type == 'and':
conditions = []
for field in filters[filter_type]:
if self.is_field_allowed(field):
... | python | {
"resource": ""
} |
q259136 | ElasticQuery.create_query | validation | def create_query(self, attr):
""" Mix all values and make the query """
field = attr[0]
operator = attr[1]
value = attr[2]
model = self.model
if '.' in field:
field_items = field.split('.')
field_name = getattr(model, field_items[0], None)
... | python | {
"resource": ""
} |
q259137 | SMTP_dummy.sendmail | validation | def sendmail(self, msg_from, msg_to, msg):
"""Remember the recipients."""
SMTP_dummy.msg_from = msg_from
SMTP_dummy.msg_to = msg_to
SMTP_dummy.msg = msg | python | {
"resource": ""
} |
q259138 | parsemail | validation | def parsemail(raw_message):
"""Parse message headers, then remove BCC header."""
message = email.parser.Parser().parsestr(raw_message)
# Detect encoding
detected = chardet.detect(bytearray(raw_message, "utf-8"))
encoding = detected["encoding"]
print(">>> encoding {}".format(encoding))
for p... | python | {
"resource": ""
} |
q259139 | _create_boundary | validation | def _create_boundary(message):
"""Add boundary parameter to multipart message if they are not present."""
if not message.is_multipart() or message.get_boundary() is not None:
return message
# HACK: Python2 lists do not natively have a `copy` method. Unfortunately,
# due to a bug in the Backport ... | python | {
"resource": ""
} |
q259140 | make_message_multipart | validation | def make_message_multipart(message):
"""Convert a message into a multipart message."""
if not message.is_multipart():
multipart_message = email.mime.multipart.MIMEMultipart('alternative')
for header_key in set(message.keys()):
# Preserve duplicate headers
values = message... | python | {
"resource": ""
} |
q259141 | convert_markdown | validation | def convert_markdown(message):
"""Convert markdown in message text to HTML."""
assert message['Content-Type'].startswith("text/markdown")
del message['Content-Type']
# Convert the text from markdown and then make the message multipart
message = make_message_multipart(message)
for payload_item in... | python | {
"resource": ""
} |
q259142 | addattachments | validation | def addattachments(message, template_path):
"""Add the attachments from the message from the commandline options."""
if 'attachment' not in message:
return message, 0
message = make_message_multipart(message)
attachment_filepaths = message.get_all('attachment', failobj=[])
template_parent_... | python | {
"resource": ""
} |
q259143 | sendmail | validation | def sendmail(message, sender, recipients, config_filename):
"""Send email message using Python SMTP library."""
# Read config file from disk to get SMTP server host, port, username
if not hasattr(sendmail, "host"):
config = configparser.RawConfigParser()
config.read(config_filename)
... | python | {
"resource": ""
} |
q259144 | create_sample_input_files | validation | def create_sample_input_files(template_filename,
database_filename,
config_filename):
"""Create sample template email and database."""
print("Creating sample template email {}".format(template_filename))
if os.path.exists(template_filename):
... | python | {
"resource": ""
} |
q259145 | cli | validation | def cli(sample, dry_run, limit, no_limit,
database_filename, template_filename, config_filename):
"""Command line interface."""
# pylint: disable=too-many-arguments
mailmerge.api.main(
sample=sample,
dry_run=dry_run,
limit=limit,
no_limit=no_limit,
database_fi... | python | {
"resource": ""
} |
q259146 | with_continuations | validation | def with_continuations(**c):
"""
A decorator for defining tail-call optimized functions.
Example
-------
@with_continuations()
def factorial(n, k, self=None):
return self(n-1, k*n) if n > 1 else k
@with_continuations()
def identity(x, self=None):
... | python | {
"resource": ""
} |
q259147 | parse_int_list | validation | def parse_int_list(string):
"""
Parses a string of numbers and ranges into a list of integers. Ranges
are separated by dashes and inclusive of both the start and end number.
Example:
parse_int_list("8 9 10,11-13") == [8,9,10,11,12,13]
"""
integers = []
for comma_part in string.split... | python | {
"resource": ""
} |
q259148 | BasePeonyClient._get_base_url | validation | def _get_base_url(base_url, api, version):
"""
create the base url for the api
Parameters
----------
base_url : str
format of the base_url using {api} and {version}
api : str
name of the api to use
version : str
version of ... | python | {
"resource": ""
} |
q259149 | BasePeonyClient.request | validation | async def request(self, method, url, future,
headers=None,
session=None,
encoding=None,
**kwargs):
"""
Make requests to the REST API
Parameters
----------
future : asyncio.Future
... | python | {
"resource": ""
} |
q259150 | BasePeonyClient.stream_request | validation | def stream_request(self, method, url, headers=None, _session=None,
*args, **kwargs):
"""
Make requests to the Streaming API
Parameters
----------
method : str
Method to be used by the request
url : str
URL of the resourc... | python | {
"resource": ""
} |
q259151 | BasePeonyClient.get_tasks | validation | def get_tasks(self):
"""
Get the tasks attached to the instance
Returns
-------
list
List of tasks (:class:`asyncio.Task`)
"""
tasks = self._get_tasks()
tasks.extend(self._streams.get_tasks(self))
return tasks | python | {
"resource": ""
} |
q259152 | BasePeonyClient.run_tasks | validation | async def run_tasks(self):
""" Run the tasks attached to the instance """
tasks = self.get_tasks()
self._gathered_tasks = asyncio.gather(*tasks, loop=self.loop)
try:
await self._gathered_tasks
except CancelledError:
pass | python | {
"resource": ""
} |
q259153 | BasePeonyClient.close | validation | async def close(self):
""" properly close the client """
tasks = self._get_close_tasks()
if tasks:
await asyncio.wait(tasks)
self._session = None | python | {
"resource": ""
} |
q259154 | PeonyClient._chunked_upload | validation | async def _chunked_upload(self, media, media_size,
path=None,
media_type=None,
media_category=None,
chunk_size=2**20,
**params):
"""
upload media in c... | python | {
"resource": ""
} |
q259155 | PeonyClient.upload_media | validation | async def upload_media(self, file_,
media_type=None,
media_category=None,
chunked=None,
size_limit=None,
**params):
"""
upload a media on twitter
Parameters... | python | {
"resource": ""
} |
q259156 | _parse_iedb_response | validation | def _parse_iedb_response(response):
"""Take the binding predictions returned by IEDB's web API
and parse them into a DataFrame
Expect response to look like:
allele seq_num start end length peptide ic50 percentile_rank
HLA-A*01:01 1 2 10 9 LYNTVATLY 2145.70 3.7
HLA-A*01:01 1 5 ... | python | {
"resource": ""
} |
q259157 | IedbBasePredictor.predict_subsequences | validation | def predict_subsequences(self, sequence_dict, peptide_lengths=None):
"""Given a dictionary mapping unique keys to amino acid sequences,
run MHC binding predictions on all candidate epitopes extracted from
sequences and return a EpitopeCollection.
Parameters
----------
fa... | python | {
"resource": ""
} |
q259158 | get_args | validation | def get_args(func, skip=0):
"""
Hackish way to get the arguments of a function
Parameters
----------
func : callable
Function to get the arguments from
skip : int, optional
Arguments to skip, defaults to 0 set it to 1 to skip the
``self`` argument of a method.
R... | python | {
"resource": ""
} |
q259159 | log_error | validation | def log_error(msg=None, exc_info=None, logger=None, **kwargs):
"""
log an exception and its traceback on the logger defined
Parameters
----------
msg : str, optional
A message to add to the error
exc_info : tuple
Information about the current exception
logger : logging.L... | python | {
"resource": ""
} |
q259160 | get_media_metadata | validation | async def get_media_metadata(data, path=None):
"""
Get all the file's metadata and read any kind of file object
Parameters
----------
data : bytes
first bytes of the file (the mimetype shoudl be guessed from the
file headers
path : str, optional
path to the file
... | python | {
"resource": ""
} |
q259161 | get_size | validation | async def get_size(media):
"""
Get the size of a file
Parameters
----------
media : file object
The file object of the media
Returns
-------
int
The size of the file
"""
if hasattr(media, 'seek'):
await execute(media.seek(0, os.SEEK_END))
siz... | python | {
"resource": ""
} |
q259162 | set_debug | validation | def set_debug():
""" activates error messages, useful during development """
logging.basicConfig(level=logging.WARNING)
peony.logger.setLevel(logging.DEBUG) | python | {
"resource": ""
} |
q259163 | BindingPrediction.clone_with_updates | validation | def clone_with_updates(self, **kwargs):
"""Returns new BindingPrediction with updated fields"""
fields_dict = self.to_dict()
fields_dict.update(kwargs)
return BindingPrediction(**fields_dict) | python | {
"resource": ""
} |
q259164 | IdIterator.get_data | validation | def get_data(self, response):
""" Get the data from the response """
if self._response_list:
return response
elif self._response_key is None:
if hasattr(response, "items"):
for key, data in response.items():
if (hasattr(data, "__getitem... | python | {
"resource": ""
} |
q259165 | SinceIdIterator.call_on_response | validation | async def call_on_response(self, data):
"""
Try to fill the gaps and strip last tweet from the response
if its id is that of the first tweet of the last response
Parameters
----------
data : list
The response data
"""
since_id = self.kwargs.ge... | python | {
"resource": ""
} |
q259166 | get_oauth_token | validation | async def get_oauth_token(consumer_key, consumer_secret, callback_uri="oob"):
"""
Get a temporary oauth token
Parameters
----------
consumer_key : str
Your consumer key
consumer_secret : str
Your consumer secret
callback_uri : str, optional
Callback uri, defaults to ... | python | {
"resource": ""
} |
q259167 | get_oauth_verifier | validation | async def get_oauth_verifier(oauth_token):
"""
Open authorize page in a browser,
print the url if it didn't work
Arguments
---------
oauth_token : str
The oauth token received in :func:`get_oauth_token`
Returns
-------
str
The PIN entered by the user
"""
url... | python | {
"resource": ""
} |
q259168 | get_access_token | validation | async def get_access_token(consumer_key, consumer_secret,
oauth_token, oauth_token_secret,
oauth_verifier, **kwargs):
"""
get the access token of the user
Parameters
----------
consumer_key : str
Your consumer key
consumer_secret... | python | {
"resource": ""
} |
q259169 | parse_token | validation | def parse_token(response):
"""
parse the responses containing the tokens
Parameters
----------
response : str
The response containing the tokens
Returns
-------
dict
The parsed tokens
"""
items = response.split("&")
items = [item.split("=") for item in items... | python | {
"resource": ""
} |
q259170 | NetChop.predict | validation | def predict(self, sequences):
"""
Return netChop predictions for each position in each sequence.
Parameters
-----------
sequences : list of string
Amino acid sequences to predict cleavage for
Returns
-----------
list of list of float
... | python | {
"resource": ""
} |
q259171 | NetChop.parse_netchop | validation | def parse_netchop(netchop_output):
"""
Parse netChop stdout.
"""
line_iterator = iter(netchop_output.decode().split("\n"))
scores = []
for line in line_iterator:
if "pos" in line and 'AA' in line and 'score' in line:
scores.append([])
... | python | {
"resource": ""
} |
q259172 | BindingPredictionCollection.to_dataframe | validation | def to_dataframe(
self,
columns=BindingPrediction.fields + ("length",)):
"""
Converts collection of BindingPrediction objects to DataFrame
"""
return pd.DataFrame.from_records(
[tuple([getattr(x, name) for name in columns]) for x in self],
... | python | {
"resource": ""
} |
q259173 | NetMHC | validation | def NetMHC(alleles,
default_peptide_lengths=[9],
program_name="netMHC"):
"""
This function wraps NetMHC3 and NetMHC4 to automatically detect which class
to use. Currently based on running the '-h' command and looking for
discriminating substrings between the versions.
"""
#... | python | {
"resource": ""
} |
q259174 | MHCflurry.predict_peptides | validation | def predict_peptides(self, peptides):
"""
Predict MHC affinity for peptides.
"""
# importing locally to avoid slowing down CLI applications which
# don't use MHCflurry
from mhcflurry.encodable_sequences import EncodableSequences
binding_predictions = []
... | python | {
"resource": ""
} |
q259175 | seq_to_str | validation | def seq_to_str(obj, sep=","):
"""
Given a sequence convert it to a comma separated string.
If, however, the argument is a single object, return its string
representation.
"""
if isinstance(obj, string_classes):
return obj
elif isinstance(obj, (list, tuple)):
return sep.join([... | python | {
"resource": ""
} |
q259176 | create_input_peptides_files | validation | def create_input_peptides_files(
peptides,
max_peptides_per_file=None,
group_by_length=False):
"""
Creates one or more files containing one peptide per line,
returns names of files.
"""
if group_by_length:
peptide_lengths = {len(p) for p in peptides}
peptide_g... | python | {
"resource": ""
} |
q259177 | BasePredictor._check_peptide_lengths | validation | def _check_peptide_lengths(self, peptide_lengths=None):
"""
If peptide lengths not specified, then try using the default
lengths associated with this predictor object. If those aren't
a valid non-empty sequence of integers, then raise an exception.
Otherwise return the peptide le... | python | {
"resource": ""
} |
q259178 | BasePredictor._check_peptide_inputs | validation | def _check_peptide_inputs(self, peptides):
"""
Check peptide sequences to make sure they are valid for this predictor.
"""
require_iterable_of(peptides, string_types)
check_X = not self.allow_X_in_peptides
check_lower = not self.allow_lowercase_in_peptides
check_m... | python | {
"resource": ""
} |
q259179 | BasePredictor.predict_subsequences | validation | def predict_subsequences(
self,
sequence_dict,
peptide_lengths=None):
"""
Given a dictionary mapping sequence names to amino acid strings,
and an optional list of peptide lengths, returns a
BindingPredictionCollection.
"""
if isinstance... | python | {
"resource": ""
} |
q259180 | BasePredictor._check_hla_alleles | validation | def _check_hla_alleles(
alleles,
valid_alleles=None):
"""
Given a list of HLA alleles and an optional list of valid
HLA alleles, return a set of alleles that we will pass into
the MHC binding predictor.
"""
require_iterable_of(alleles, string_types... | python | {
"resource": ""
} |
q259181 | StreamResponse._connect | validation | async def _connect(self):
"""
Connect to the stream
Returns
-------
asyncio.coroutine
The streaming response
"""
logger.debug("connecting to the stream")
await self.client.setup
if self.session is None:
self.session = s... | python | {
"resource": ""
} |
q259182 | StreamResponse.connect | validation | async def connect(self):
"""
Create the connection
Returns
-------
self
Raises
------
exception.PeonyException
On a response status in 4xx that are not status 420 or 429
Also on statuses in 1xx or 3xx since this should not be ... | python | {
"resource": ""
} |
q259183 | Handler.with_prefix | validation | def with_prefix(self, prefix, strict=False):
"""
decorator to handle commands with prefixes
Parameters
----------
prefix : str
the prefix of the command
strict : bool, optional
If set to True the command must be at the beginning
of... | python | {
"resource": ""
} |
q259184 | BDClient.set_tz | validation | async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
settings = await self.api.account.settings.get()
tz = settings.time_zone.tzinfo_name
os.environ['TZ'] = tz
time.tzset() | python | {
"resource": ""
} |
q259185 | run_command | validation | def run_command(args, **kwargs):
"""
Given a list whose first element is a command name, followed by arguments,
execute it and show timing info.
"""
assert len(args) > 0
start_time = time.time()
process = AsyncProcess(args, **kwargs)
process.wait()
elapsed_time = time.time() - start_... | python | {
"resource": ""
} |
q259186 | run_multiple_commands_redirect_stdout | validation | def run_multiple_commands_redirect_stdout(
multiple_args_dict,
print_commands=True,
process_limit=-1,
polling_freq=0.5,
**kwargs):
"""
Run multiple shell commands in parallel, write each of their
stdout output to files associated with each command.
Parameters
... | python | {
"resource": ""
} |
q259187 | loads | validation | def loads(json_data, encoding="utf-8", **kwargs):
"""
Custom loads function with an object_hook and automatic decoding
Parameters
----------
json_data : str
The JSON data to decode
*args
Positional arguments, passed to :func:`json.loads`
encoding : :obj:`str`, optional
... | python | {
"resource": ""
} |
q259188 | read | validation | async def read(response, loads=loads, encoding=None):
"""
read the data of the response
Parameters
----------
response : aiohttp.ClientResponse
response
loads : callable
json loads function
encoding : :obj:`str`, optional
character encoding of the response, if se... | python | {
"resource": ""
} |
q259189 | doc | validation | def doc(func):
"""
Find the message shown when someone calls the help command
Parameters
----------
func : function
the function
Returns
-------
str
The help message for this command
"""
stripped_chars = " \t"
if hasattr(func, '__doc__'):
docstr... | python | {
"resource": ""
} |
q259190 | permission_check | validation | def permission_check(data, command_permissions,
command=None, permissions=None):
"""
Check the permissions of the user requesting a command
Parameters
----------
data : dict
message data
command_permissions : dict
permissions of the command, contains all... | python | {
"resource": ""
} |
q259191 | main | validation | def main(args_list=None):
"""
Script to make pMHC binding predictions from amino acid sequences.
Usage example:
mhctools
--sequence SFFPIQQQQQAAALLLI \
--sequence SILQQQAQAQQAQAASSSC \
--extract-subsequences \
--mhc-predictor netmhc \
--mh... | python | {
"resource": ""
} |
q259192 | NetMHCIIpan._prepare_drb_allele_name | validation | def _prepare_drb_allele_name(self, parsed_beta_allele):
"""
Assume that we're dealing with a human DRB allele
which NetMHCIIpan treats differently because there is
little population diversity in the DR-alpha gene
"""
if "DRB" not in parsed_beta_allele.gene:
ra... | python | {
"resource": ""
} |
q259193 | get_error | validation | def get_error(data):
""" return the error if there is a corresponding exception """
if isinstance(data, dict):
if 'errors' in data:
error = data['errors'][0]
else:
error = data.get('error', None)
if isinstance(error, dict):
if error.get('code') in err... | python | {
"resource": ""
} |
q259194 | throw | validation | async def throw(response, loads=None, encoding=None, **kwargs):
""" Get the response data if possible and raise an exception """
if loads is None:
loads = data_processing.loads
data = await data_processing.read(response, loads=loads,
encoding=encoding)
err... | python | {
"resource": ""
} |
q259195 | ErrorDict.code | validation | def code(self, code):
""" Decorator to associate a code to an exception """
def decorator(exception):
self[code] = exception
return exception
return decorator | python | {
"resource": ""
} |
q259196 | PeonyHeaders.prepare_request | validation | async def prepare_request(self, method, url,
headers=None,
skip_params=False,
proxy=None,
**kwargs):
"""
prepare all the arguments for the request
Parameters
---------... | python | {
"resource": ""
} |
q259197 | PeonyHeaders._user_headers | validation | def _user_headers(self, headers=None):
""" Make sure the user doesn't override the Authorization header """
h = self.copy()
if headers is not None:
keys = set(headers.keys())
if h.get('Authorization', False):
keys -= {'Authorization'}
for key... | python | {
"resource": ""
} |
q259198 | process_keys | validation | def process_keys(func):
"""
Raise error for keys that are not strings
and add the prefix if it is missing
"""
@wraps(func)
def decorated(self, k, *args):
if not isinstance(k, str):
msg = "%s: key must be a string" % self.__class__.__name__
raise ValueError(msg)
... | python | {
"resource": ""
} |
q259199 | Functions._get | validation | def _get(self, text):
"""
Analyze the text to get the right function
Parameters
----------
text : str
The text that could call a function
"""
if self.strict:
match = self.prog.match(text)
if match:
cmd = mat... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.