text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maybe_obj(str_or_obj):
"""If argument is not a string, return it. Otherwise import the dotted name and return that. """ |
if not isinstance(str_or_obj, six.string_types):
return str_or_obj
parts = str_or_obj.split(".")
mod, modname = None, None
for p in parts:
modname = p if modname is None else "%s.%s" % (modname, p)
try:
mod = __import__(modname)
except ImportError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_menu():
"""Generate a new list of menus.""" |
root_menu = Menu(list(copy.deepcopy(settings.WAFER_MENUS)))
for dynamic_menu_func in settings.WAFER_DYNAMIC_MENUS:
dynamic_menu_func = maybe_obj(dynamic_menu_func)
dynamic_menu_func(root_menu)
return root_menu |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def lock(self):
'''
Try to get locked the file
- the function will wait until the file is unlocked if 'wait' was defined as locktype
- the funciton will raise AlreadyLocked exception if 'lock' was defined as locktype
'''
# Open file
self.__fd = open(self.__lockfi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _make_handler(state_token, done_function):
'''
Makes a a handler class to use inside the basic python HTTP server.
state_token is the expected state token.
done_function is a function that is called, with the code passed to it.
'''
class LocalServerHandler(BaseHTTPServer.BaseHTTPRequestHan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def configuration():
'Loads configuration from the file system.'
defaults = '''
[oauth2]
hostname = localhost
port = 9876
api_endpoint = https://api.coursera.org
auth_endpoint = https://accounts.coursera.org/oauth2/v1/auth
token_endpoint = https://accounts.coursera.org/oauth2/v1/token
verify_tls = True
token_ca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _load_token_cache(self):
'Reads the local fs cache for pre-authorized access tokens'
try:
logging.debug('About to read from local file cache file %s',
self.token_cache_file)
with open(self.token_cache_file, 'rb') as f:
fs_cached = cPi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _save_token_cache(self, new_cache):
'Write out to the filesystem a cache of the OAuth2 information.'
logging.debug('Looking to write to local authentication cache...')
if not self._check_token_cache_type(new_cache):
logging.error('Attempt to save a bad value: %s', new_cache)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _check_token_cache_type(self, cache_value):
'''
Checks the cache_value for appropriate type correctness.
Pass strict=True for strict validation to ensure the latest types are
being written.
Returns true is correct type, False otherwise.
'''
def check_string_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _authorize_new_tokens(self):
'''
Stands up a new localhost http server and retrieves new OAuth2 access
tokens from the Coursera OAuth2 server.
'''
logging.info('About to request new OAuth2 tokens from Coursera.')
# Attempt to request new tokens from Coursera via the b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _exchange_refresh_tokens(self):
'Exchanges a refresh token for an access token'
if self.token_cache is not None and 'refresh' in self.token_cache:
# Attempt to use the refresh token to get a new access token.
refresh_form = {
'grant_type': 'refresh_token',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def foreignkey(element, exceptions):
'''
function to determine if each select field needs a create button or not
'''
label = element.field.__dict__['label']
try:
label = unicode(label)
except NameError:
pass
if (not label) or (label in exceptions):
return False
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize_by_field(value, field):
""" Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them """ |
if isinstance(field, forms.DateTimeField):
value = parse_datetime(value)
elif isinstance(field, forms.DateField):
value = parse_date(value)
elif isinstance(field, forms.TimeField):
value = parse_time(value)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def main():
"Boots up the command line tool"
logging.captureWarnings(True)
args = build_parser().parse_args()
# Configure logging
args.setup_logging(args)
# Dispatch into the appropriate subcommand function.
try:
return args.func(args)
except SystemExit:
raise
except:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def objectatrib(instance, atrib):
'''
this filter is going to be useful to execute an object method or get an
object attribute dynamically. this method is going to take into account
the atrib param can contains underscores
'''
atrib = atrib.replace("__", ".")
atribs = []
atribs = atrib.s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def upload_path(instance, filename):
'''
This method is created to return the path to upload files. This path must be
different from any other to avoid problems.
'''
path_separator = "/"
date_separator = "-"
ext_separator = "."
empty_string = ""
# get the model name
model_name = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def remove_getdisplay(field_name):
'''
for string 'get_FIELD_NAME_display' return 'FIELD_NAME'
'''
str_ini = 'get_'
str_end = '_display'
if str_ini == field_name[0:len(str_ini)] and str_end == field_name[(-1) * len(str_end):]:
field_name = field_name[len(str_ini):(-1) * len(str_end)]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def append(self, filename_in_zip, file_contents):
'''
Appends a file with name filename_in_zip and contents of
file_contents to the in-memory zip.
'''
# Set the file pointer to the end of the file
self.in_memory_zip.seek(-1, io.SEEK_END)
# Get a handle to the in-... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def writetofile(self, filename):
'''Writes the in-memory zip to a file.'''
f = open(filename, "w")
f.write(self.read())
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sponsor_image_url(sponsor, name):
"""Returns the corresponding url from the sponsors images""" |
if sponsor.files.filter(name=name).exists():
# We avoid worrying about multiple matches by always
# returning the first one.
return sponsor.files.filter(name=name).first().item.url
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sponsor_tagged_image(sponsor, tag):
"""returns the corresponding url from the tagged image list.""" |
if sponsor.files.filter(tag_name=tag).exists():
return sponsor.files.filter(tag_name=tag).first().tagged_file.item.url
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ifusergroup(parser, token):
""" Check to see if the currently logged in user belongs to a specific group. Requires the Django authentication contrib app and ... |
try:
tokensp = token.split_contents()
groups = []
groups+=tokensp[1:]
except ValueError:
raise template.TemplateSyntaxError("Tag 'ifusergroup' requires at least 1 argument.")
nodelist_true = parser.parse(('else', 'endifusergroup'))
token = parser.next_token()
if to... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def OpenHandle(self):
'''Gets a handle for use with other vSphere Guest API functions. The guest library
handle provides a context for accessing information about the virtual machine.
Virtual machine statistics and state data are associated with a particular guest library
handl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def CloseHandle(self):
'''Releases a handle acquired with VMGuestLib_OpenHandle'''
if hasattr(self, 'handle'):
ret = vmGuestLib.VMGuestLib_CloseHandle(self.handle.value)
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
del(self.handle) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def UpdateInfo(self):
'''Updates information about the virtual machine. This information is associated with
the VMGuestLibHandle.
VMGuestLib_UpdateInfo requires similar CPU resources to a system call and
therefore can affect performance. If you are concerned about performance, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetSessionId(self):
'''Retrieves the VMSessionID for the current session. Call this function after calling
VMGuestLib_UpdateInfo. If VMGuestLib_UpdateInfo has never been called,
VMGuestLib_GetSessionId returns VMGUESTLIB_ERROR_NO_INFO.'''
sid = c_void_p()
ret = vmGuestL... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetCpuLimitMHz(self):
'''Retrieves the upperlimit of processor use in MHz available to the virtual
machine. For information about setting the CPU limit, see "Limits and
Reservations" on page 14.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetCpuLimitMHz(self.handl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetCpuReservationMHz(self):
'''Retrieves the minimum processing power in MHz reserved for the virtual
machine. For information about setting a CPU reservation, see "Limits and
Reservations" on page 14.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetCpuReservationM... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetCpuShares(self):
'''Retrieves the number of CPU shares allocated to the virtual machine. For
information about how an ESX server uses CPU shares to manage virtual
machine priority, see the vSphere Resource Management Guide.'''
counter = c_uint()
ret = vmGuestLib.VMGu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetElapsedMs(self):
'''Retrieves the number of milliseconds that have passed in the virtual
machine since it last started running on the server. The count of elapsed
time restarts each time the virtual machine is powered on, resumed, or
migrated using VMotion. This value cou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetHostProcessorSpeed(self):
'''Retrieves the speed of the ESX system's physical CPU in MHz.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetHostProcessorSpeed(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetMemActiveMB(self):
'''Retrieves the amount of memory the virtual machine is actively using its
estimated working set size.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemActiveMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGue... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetMemLimitMB(self):
'''Retrieves the upper limit of memory that is available to the virtual
machine. For information about setting a memory limit, see "Limits and
Reservations" on page 14.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemLimitMB(self.handle.valu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetMemMappedMB(self):
'''Retrieves the amount of memory that is allocated to the virtual machine.
Memory that is ballooned, swapped, or has never been accessed is
excluded.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemMappedMB(self.handle.value, byref(counter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetMemOverheadMB(self):
'''Retrieves the amount of "overhead" memory associated with this virtual
machine that is currently consumed on the host system. Overhead
memory is additional memory that is reserved for data structures required
by the virtualization layer.'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetMemReservationMB(self):
'''Retrieves the minimum amount of memory that is reserved for the virtual
machine. For information about setting a memory reservation, see "Limits
and Reservations" on page 14.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemReservati... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetMemShares(self):
'''Retrieves the number of memory shares allocated to the virtual machine.
For information about how an ESX server uses memory shares to manage
virtual machine priority, see the vSphere Resource Management Guide.'''
counter = c_uint()
ret = vmGuestLi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetMemSwappedMB(self):
'''Retrieves the amount of memory that has been reclaimed from this virtual
machine by transparently swapping guest memory to disk.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemSwappedMB(self.handle.value, byref(counter))
if ret != VMGUEST... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetMemTargetSizeMB(self):
'''Retrieves the size of the target memory allocation for this virtual machine.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemTargetSizeMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetMemUsedMB(self):
'''Retrieves the estimated amount of physical host memory currently
consumed for this virtual machine's physical memory.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemUsedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def wafer_form_helper(context, helper_name):
'''
Find the specified Crispy FormHelper and instantiate it.
Handy when you are crispyifying other apps' forms.
'''
request = context.request
module, class_name = helper_name.rsplit('.', 1)
if module not in sys.modules:
__import__(module)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page_menus(root_menu):
"""Add page menus.""" |
for page in Page.objects.filter(include_in_menu=True):
path = page.get_path()
menu = path[0] if len(path) > 1 else None
try:
root_menu.add_item(page.name, page.get_absolute_url(), menu=menu)
except MenuError as e:
logger.error("Bad menu item %r for page with ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def redirect_profile(request):
'''
The default destination from logging in, redirect to the actual profile URL
'''
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('wafer_user_profile',
args=(request.user.username,)))
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reviewed_badge(user, talk):
"""Returns a badge for the user's reviews of the talk""" |
context = {
'reviewed': False,
}
review = None
if user and not user.is_anonymous():
review = talk.reviews.filter(reviewer=user).first()
if review:
context['reviewed'] = True
context['review_is_current'] = review.is_current()
return context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def form_valid(self, form, forms):
""" Called if all forms are valid. Creates a Recipe instance along with associated Ingredients and Instructions and then redir... |
if self.object:
form.save()
for (formobj, linkerfield) in forms:
if form != formobj:
formobj.save()
else:
self.object = form.save()
for (formobj, linkerfield) in forms:
if form != formobj:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def form_invalid(self, form, forms, open_tabs, position_form_default):
""" Called if a form is invalid. Re-renders the context data with the data-filled forms an... |
# return self.render_to_response( self.get_context_data( form = form, forms = forms ) )
return self.render_to_response(self.get_context_data(form=form, forms=forms, open_tabs=open_tabs, position_form_default=position_form_default)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def univariate_envelope_plot(x, mean, std, ax=None, base_alpha=0.375, envelopes=[1, 3], lb=None, ub=None, expansion=10, **kwargs):
"""Make a plot of a mean curve... |
if ax is None:
f = plt.figure()
ax = f.add_subplot(1, 1, 1)
elif ax == 'gca':
ax = plt.gca()
mean = scipy.asarray(mean, dtype=float).copy()
std = scipy.asarray(std, dtype=float).copy()
# Truncate the data so matplotlib doesn't die:
if lb is not None and ub is n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_token(self):
"""Gains token from secure backend service. :return: Token formatted for Cocaine protocol header. """ |
grant_type = 'client_credentials'
channel = yield self._tvm.ticket_full(
self._client_id, self._client_secret, grant_type, {})
ticket = yield channel.rx.get()
raise gen.Return(self._make_token(ticket)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_summary(summaryfile, **kwargs):
"""Extracting information from an albacore summary file. Only reads which have a >0 length are returned. The fields b... |
logging.info("Nanoget: Collecting metrics from summary file {} for {} sequencing".format(
summaryfile, kwargs["readtype"]))
ut.check_existance(summaryfile)
if kwargs["readtype"] == "1D":
cols = ["read_id", "run_id", "channel", "start_time", "duration",
"sequence_length_templ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_bam(bam, samtype="bam"):
"""Check if bam file is valid. Bam file should: - exists - has an index (create if necessary) - is sorted by coordinate - has ... |
ut.check_existance(bam)
samfile = pysam.AlignmentFile(bam, "rb")
if not samfile.has_index():
pysam.index(bam)
samfile = pysam.AlignmentFile(bam, "rb") # Need to reload the samfile after creating index
logging.info("Nanoget: No index for bam file could be found, created index.")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_ubam(bam, **kwargs):
"""Extracting metrics from unaligned bam format Extracting lengths """ |
logging.info("Nanoget: Starting to collect statistics from ubam file {}.".format(bam))
samfile = pysam.AlignmentFile(bam, "rb", check_sq=False)
if not samfile.has_index():
pysam.index(bam)
# Need to reload the samfile after creating index
samfile = pysam.AlignmentFile(bam, "rb")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_bam(bam, **kwargs):
"""Combines metrics from bam after extraction. Processing function: calls pool of worker functions to extract from a bam file the... |
logging.info("Nanoget: Starting to collect statistics from bam file {}.".format(bam))
samfile = check_bam(bam)
chromosomes = samfile.references
params = zip([bam] * len(chromosomes), chromosomes)
with cfutures.ProcessPoolExecutor() as executor:
datadf = pd.DataFrame(
data=[res f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_from_bam(params):
"""Extracts metrics from bam. Worker function per chromosome loop over a bam file and create list with tuples containing metrics: -... |
bam, chromosome = params
samfile = pysam.AlignmentFile(bam, "rb")
return [
(read.query_name,
nanomath.ave_qual(read.query_qualities),
nanomath.ave_qual(read.query_alignment_qualities),
read.query_length,
read.query_alignment_length,
read.mapping_quality,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_pID(read):
"""Return the percent identity of a read. based on the NM tag if present, if not calculate from MD tag and CIGAR string read.query_alignment_l... |
try:
return 100 * (1 - read.get_tag("NM") / read.query_alignment_length)
except KeyError:
try:
return 100 * (1 - (parse_MD(read.get_tag("MD")) + parse_CIGAR(read.cigartuples))
/ read.query_alignment_length)
except KeyError:
return None
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_compressed_input(inputfq, file_type="fastq"):
"""Return handles from compressed files according to extension. Check for which fastq input is presented... |
ut.check_existance(inputfq)
if inputfq.endswith(('.gz', 'bgz')):
import gzip
logging.info("Nanoget: Decompressing gzipped {} {}".format(file_type, inputfq))
return gzip.open(inputfq, 'rt')
elif inputfq.endswith('.bz2'):
import bz2
logging.info("Nanoget: Decompressing... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_fasta(fasta, **kwargs):
"""Combine metrics extracted from a fasta file.""" |
logging.info("Nanoget: Starting to collect statistics from a fasta file.")
inputfasta = handle_compressed_input(fasta, file_type="fasta")
return ut.reduce_memory_usage(pd.DataFrame(
data=[len(rec) for rec in SeqIO.parse(inputfasta, "fasta")],
columns=["lengths"]
).dropna()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_fastq_plain(fastq, **kwargs):
"""Combine metrics extracted from a fastq file.""" |
logging.info("Nanoget: Starting to collect statistics from plain fastq file.")
inputfastq = handle_compressed_input(fastq)
return ut.reduce_memory_usage(pd.DataFrame(
data=[res for res in extract_from_fastq(inputfastq) if res],
columns=["quals", "lengths"]
).dropna()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stream_fastq_full(fastq, threads):
"""Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality ... |
logging.info("Nanoget: Starting to collect full metrics from plain fastq file.")
inputfastq = handle_compressed_input(fastq)
with cfutures.ProcessPoolExecutor(max_workers=threads) as executor:
for results in executor.map(extract_all_from_fastq, SeqIO.parse(inputfastq, "fastq")):
yield r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_fastq_rich(fastq, **kwargs):
"""Extract metrics from a richer fastq file. Extract information from fastq files generated by albacore or MinKNOW, cont... |
logging.info("Nanoget: Starting to collect statistics from rich fastq file.")
inputfastq = handle_compressed_input(fastq)
res = []
for record in SeqIO.parse(inputfastq, "fastq"):
try:
read_info = info_to_dict(record.description)
res.append(
(nanomath.ave_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fq_minimal(fq):
"""Minimal fastq metrics extractor. Quickly parse a fasta/fastq file - but makes expectations on the file format There will be dragons if une... |
try:
while True:
time = next(fq)[1:].split(" ")[4][11:-1]
length = len(next(fq))
next(fq)
next(fq)
yield time, length
except StopIteration:
yield None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_piece(string, index):
""" Returns Piece subclass given index of piece. :type: index: int :type: loc Location :raise: KeyError """ |
piece = string[index].strip()
piece = piece.upper()
piece_dict = {'R': Rook,
'P': Pawn,
'B': Bishop,
'N': Knight,
'Q': Queen,
'K': King}
try:
return piece_dict[piece]
except KeyError:
raise Val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def short_alg(algebraic_string, input_color, position):
""" Converts a string written in short algebraic form, the color of the side whose turn it is, and the co... |
return make_legal(incomplete_alg(algebraic_string, input_color, position), position) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def implicify_hydrogens(self):
""" remove explicit hydrogen if possible :return: number of removed hydrogens """ |
explicit = defaultdict(list)
c = 0
for n, atom in self.atoms():
if atom.element == 'H':
for m in self.neighbors(n):
if self._node[m].element != 'H':
explicit[m].append(n)
for n, h in explicit.items():
a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def explicify_hydrogens(self):
""" add explicit hydrogens to atoms :return: number of added atoms """ |
tmp = []
for n, atom in self.atoms():
if atom.element != 'H':
for _ in range(atom.get_implicit_h([x.order for x in self._adj[n].values()])):
tmp.append(n)
for n in tmp:
self.add_bond(n, self.add_atom(H), Bond())
self.flush_cac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_valence(self):
""" check valences of all atoms :return: list of invalid atoms """ |
return [x for x, atom in self.atoms() if not atom.check_valence(self.environment(x))] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _matcher(self, other):
""" return VF2 GraphMatcher MoleculeContainer < MoleculeContainer MoleculeContainer < CGRContainer """ |
if isinstance(other, (self._get_subclass('CGRContainer'), MoleculeContainer)):
return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: x == y)
raise TypeError('only cgr-cgr possible') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_datetime(date):
"""Turn a date into a datetime at midnight. """ |
return datetime.datetime.combine(date, datetime.datetime.min.time()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_size_changes(self, issue):
"""Yield an IssueSnapshot for each time the issue size changed """ |
# Find the first size change, if any
try:
size_changes = list(filter(lambda h: h.field == 'Story Points',
itertools.chain.from_iterable([c.items for c in issue.changelog.histories])))
except AttributeError:
return
# If we ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_changes(self, issue, include_resolution_changes=True):
"""Yield an IssueSnapshot for each time the issue changed status or resolution """ |
is_resolved = False
# Find the first status change, if any
try:
status_changes = list(filter(
lambda h: h.field == 'status',
itertools.chain.from_iterable([c.items for c in issue.changelog.histories])))
except AttributeError:
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_issues(self, criteria={}, jql=None, order='KEY ASC', verbose=False, changelog=True):
"""Return a list of issues with changelog metadata. Searches for th... |
query = []
if criteria.get('project', False):
query.append('project IN (%s)' % ', '.join(['"%s"' % p for p in criteria['project']]))
if criteria.get('issue_types', False):
query.append('issueType IN (%s)' % ', '.join(['"%s"' % t for t in criteria['issue_types']]))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_catalogs(self):
""" Lists existing catalogs respect to ui view template format """ |
_form = CatalogSelectForm(current=self.current)
_form.set_choices_of('catalog', [(i, i) for i in fixture_bucket.get_keys()])
self.form_out(_form) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_catalog(self):
""" Get existing catalog and fill the form with the model data. If given key not found as catalog, it generates an empty catalog data form... |
catalog_data = fixture_bucket.get(self.input['form']['catalog'])
# define add or edit based on catalog data exists
add_or_edit = "Edit" if catalog_data.exists else "Add"
# generate form
catalog_edit_form = CatalogEditForm(
current=self.current,
title='... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_catalog(self):
""" Saves the catalog data to given key Cancels if the cmd is cancel Notifies user with the process. """ |
if self.input["cmd"] == 'save_catalog':
try:
edited_object = dict()
for i in self.input["form"]["CatalogDatas"]:
edited_object[i["catalog_key"]] = {"en": i["en"], "tr": i["tr"]}
newobj = fixture_bucket.get(self.input["object_key"]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_truthy(*dicts):
"""Merge multiple dictionaries, keeping the truthy values in case of key collisions. Accepts any number of dictionaries, or any other o... |
merged = {}
for d in dicts:
for k, v in d.items():
merged[k] = v or merged.get(k, v)
return merged |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perform(self):
"""Perform the version upgrade on the database. """ |
db_versions = self.table.versions()
version = self.version
if (version.is_processed(db_versions) and
not self.config.force_version == self.version.number):
self.log(
u'version {} is already installed'.format(version.number)
)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _perform_version(self, version):
"""Inner method for version upgrade. Not intended for standalone use. This method performs the actual version upgrade with a... |
if version.is_noop():
self.log(u'version {} is a noop'.format(version.number))
else:
self.log(u'execute base pre-operations')
for operation in version.pre_operations():
operation.execute(self.log)
if self.config.mode:
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_upgrade(self):
""" open websocket connection """ |
self.current.output['cmd'] = 'upgrade'
self.current.output['user_id'] = self.current.user_id
self.terminate_existing_login()
self.current.user.bind_private_channel(self.current.session.sess_id)
user_sess = UserSessionID(self.current.user_id)
user_sess.set(self.current.se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_view(self):
""" Authenticate user with given credentials. Connects user's queue and exchange """ |
self.current.output['login_process'] = True
self.current.task_data['login_successful'] = False
if self.current.is_auth:
self._do_upgrade()
else:
try:
auth_result = self.current.auth.authenticate(
self.current.input['username'],... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __get_mapping(self, structures):
""" match each pattern to each molecule. if all patterns matches with all molecules return generator of all possible mapping... |
for c in permutations(structures, len(self.__patterns)):
for m in product(*(x.get_substructure_mapping(y, limit=0) for x, y in zip(self.__patterns, c))):
mapping = {}
for i in m:
mapping.update(i)
if mapping:
yi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, default=None):
""" return the cached value or default if it can't be found :param default: default value :return: cached value """ |
d = cache.get(self.key)
return ((json.loads(d.decode('utf-8')) if self.serialize else d)
if d is not None
else default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, val, lifetime=None):
""" set cache value :param val: any picklable object :param lifetime: exprition time in sec :return: val """ |
cache.set(self.key,
(json.dumps(val) if self.serialize else val),
lifetime or settings.DEFAULT_CACHE_EXPIRE_TIME)
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all(self):
""" Get all list items. Returns: Cache backend response. """ |
result = cache.lrange(self.key, 0, -1)
return (json.loads(item.decode('utf-8')) for item in result if
item) if self.serialize else result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_item(self, val):
""" Removes given item from the list. Args: val: Item Returns: Cache backend response. """ |
return cache.lrem(self.key, json.dumps(val)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush(cls, *args):
""" Removes all keys of this namespace Without args, clears all keys starting with cls.PREFIX if called with args, clears keys starting wi... |
return _remove_keys([], [(cls._make_key(args) if args else cls.PREFIX) + '*']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_or_expire_session(self):
""" Deletes session if keepalive request expired otherwise updates the keepalive timestamp value """ |
if not hasattr(self, 'key'):
return
now = time.time()
timestamp = float(self.get() or 0) or now
sess_id = self.sess_id or UserSessionID(self.user_id).get()
if sess_id and now - timestamp > self.SESSION_EXPIRE_TIME:
Session(sess_id).delete()
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_message_for_lane_change(sender, **kwargs):
""" Sends a message to possible owners of the current workflows next lane. Args: **kwargs: ``current`` and ``... |
current = kwargs['current']
owners = kwargs['possible_owners']
if 'lane_change_invite' in current.task_data:
msg_context = current.task_data.pop('lane_change_invite')
else:
msg_context = DEFAULT_LANE_CHANGE_INVITE_MSG
wfi = WFCache(current).get_instance()
# Deletion of used pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_password(sender, **kwargs):
""" Encrypts password of the user. """ |
if sender.model_class.__name__ == 'User':
usr = kwargs['object']
if not usr.password.startswith('$pbkdf2'):
usr.set_password(usr.password)
usr.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channel_list(self):
""" Main screen for channel management. Channels listed and operations can be chosen on the screen. If there is an error message like non... |
if self.current.task_data.get('msg', False):
if self.current.task_data.get('target_channel_key', False):
self.current.output['msgbox'] = {'type': 'info',
"title": _(u"Successful Operation"),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channel_choice_control(self):
""" It controls errors. If there is an error, returns channel list screen with error message. """ |
self.current.task_data['control'], self.current.task_data['msg'] \
= self.selection_error_control(self.input['form'])
if self.current.task_data['control']:
self.current.task_data['option'] = self.input['cmd']
self.current.task_data['split_operation'] = False
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_new_channel(self):
""" Features of new channel are specified like channel's name, owner etc. """ |
self.current.task_data['new_channel'] = True
_form = NewChannelForm(Channel(), current=self.current)
_form.title = _(u"Specify Features of New Channel to Create")
_form.forward = fields.Button(_(u"Create"), flow="find_target_channel")
self.form_out(_form) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_new_channel(self):
""" It saves new channel according to specified channel features. """ |
form_info = self.input['form']
channel = Channel(typ=15, name=form_info['name'],
description=form_info['description'],
owner_id=form_info['owner_id'])
channel.blocking_save()
self.current.task_data['target_channel_key'] = channel.key |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choose_existing_channel(self):
""" It is a channel choice list and chosen channels at previous step shouldn't be on the screen. """ |
if self.current.task_data.get('msg', False):
self.show_warning_messages()
_form = ChannelListForm()
_form.title = _(u"Choose a Channel Which Will Be Merged With Chosen Channels")
for channel in Channel.objects.filter(typ=15).exclude(
key__in=self.current.t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def existing_choice_control(self):
""" It controls errors. It generates an error message if zero or more than one channels are selected. """ |
self.current.task_data['existing'] = False
self.current.task_data['msg'] = _(u"You should choose just one channel to do operation.")
keys, names = self.return_selected_form_items(self.input['form']['ChannelList'])
if len(keys) == 1:
self.current.task_data['existing'] = True
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_channel(self):
""" A channel can be splitted to new channel or other existing channel. It creates subscribers list as selectable to moved. """ |
if self.current.task_data.get('msg', False):
self.show_warning_messages()
self.current.task_data['split_operation'] = True
channel = Channel.objects.get(self.current.task_data['chosen_channels'][0])
_form = SubscriberListForm(title=_(u'Choose Subscribers to Migrate'))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscriber_choice_control(self):
""" It controls subscribers choice and generates error message if there is a non-choice. """ |
self.current.task_data['option'] = None
self.current.task_data['chosen_subscribers'], names = self.return_selected_form_items(
self.input['form']['SubscriberList'])
self.current.task_data[
'msg'] = "You should choose at least one subscriber for migration operation."
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_complete_channel(self):
""" Channels and theirs subscribers are moved completely to new channel or existing channel. """ |
to_channel = Channel.objects.get(self.current.task_data['target_channel_key'])
chosen_channels = self.current.task_data['chosen_channels']
chosen_channels_names = self.current.task_data['chosen_channels_names']
with BlockSave(Subscriber, query_dict={'channel_id': to_channel.key}):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_chosen_subscribers(self):
""" After splitting operation, only chosen subscribers are moved to new channel or existing channel. """ |
from_channel = Channel.objects.get(self.current.task_data['chosen_channels'][0])
to_channel = Channel.objects.get(self.current.task_data['target_channel_key'])
with BlockSave(Subscriber, query_dict={'channel_id': to_channel.key}):
for subscriber in Subscriber.objects.filter(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_and_move_messages(from_channel, to_channel):
""" While splitting channel and moving chosen subscribers to new channel, old channel's messages are copied... |
with BlockSave(Message, query_dict={'channel_id': to_channel.key}):
for message in Message.objects.filter(channel=from_channel, typ=15):
message.key = ''
message.channel = to_channel
message.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_warning_messages(self, title=_(u"Incorrect Operation"), box_type='warning'):
""" It shows incorrect operations or successful operation messages. Args: t... |
msg = self.current.task_data['msg']
self.current.output['msgbox'] = {'type': box_type, "title": title, "msg": msg}
del self.current.task_data['msg'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def return_selected_form_items(form_info):
""" It returns chosen keys list from a given form. Args: form_info: serialized list of dict form data Returns: selecte... |
selected_keys = []
selected_names = []
for chosen in form_info:
if chosen['choice']:
selected_keys.append(chosen['key'])
selected_names.append(chosen['name'])
return selected_keys, selected_names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def selection_error_control(self, form_info):
""" It controls the selection from the form according to the operations, and returns an error message if it does no... |
keys, names = self.return_selected_form_items(form_info['ChannelList'])
chosen_channels_number = len(keys)
if form_info['new_channel'] and chosen_channels_number < 2:
return False, _(
u"You should choose at least two channel to merge operation at a new channel.")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.