labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2
values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4
values | answer stringlengths 2 905 | src stringclasses 3
values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What do helper call ?
| def CallSetAllowedModule(name, desired):
if (USING_SDK and (name == 'django')):
sys.path[:] = [dirname for dirname in sys.path if (not dirname.startswith(os.path.join(PYTHON_LIB, 'lib', 'django')))]
if (desired in ('0.96', '1.2', '1.3')):
sys.path.insert(1, os.path.join(PYTHON_LIB, 'lib', ('django-' + desired)))
SetAllowedModule(name)
| null | null | null | setallowedmodule
| codeqa | def Call Set Allowed Module name desired if USING SDK and name 'django' sys path[ ] [dirname for dirname in sys path if not dirname startswith os path join PYTHON LIB 'lib' 'django' ]if desired in '0 96 ' '1 2' '1 3' sys path insert 1 os path join PYTHON LIB 'lib' 'django-' + desired Set Allowed Module name
| null | null | null | null | Question:
What do helper call ?
Code:
def CallSetAllowedModule(name, desired):
if (USING_SDK and (name == 'django')):
sys.path[:] = [dirname for dirname in sys.path if (not dirname.startswith(os.path.join(PYTHON_LIB, 'lib', 'django')))]
if (desired in ('0.96', '1.2', '1.3')):
sys.path.insert(1, os.path.join(PYTHON_LIB, 'lib', ('django-' + desired)))
SetAllowedModule(name)
|
null | null | null | What does the code get from the database ?
| def get_repository_by_name(app, sa_session, repo_name):
return sa_session.query(app.model.Repository).filter_by(name=repo_name).one()
| null | null | null | a repository
| codeqa | def get repository by name app sa session repo name return sa session query app model Repository filter by name repo name one
| null | null | null | null | Question:
What does the code get from the database ?
Code:
def get_repository_by_name(app, sa_session, repo_name):
return sa_session.query(app.model.Repository).filter_by(name=repo_name).one()
|
null | null | null | What does the code generate ?
| def bind(uuid, version):
(major, minor) = version.split('.')
major = struct.pack('<H', int(major))
minor = struct.pack('<H', int(minor))
bind = '\x05\x00'
bind += '\x0b'
bind += '\x03'
bind += '\x10\x00\x00\x00'
bind += 'H\x00'
bind += '\x00\x00'
bind += '\x00\x00\x00\x00'
bind += '\xb8\x10'
bind += '\xb8\x10'
bind += '\x00\x00\x00\x00'
bind += '\x01'
bind += '\x00\x00\x00'
bind += '\x00\x00'
bind += '\x01'
bind += '\x00'
bind += misc.uuid_str_to_bin(uuid)
bind += major
bind += minor
bind += '\x04]\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00+\x10H`'
bind += '\x02\x00\x00\x00'
return bind
| null | null | null | the data necessary to bind to the specified interface
| codeqa | def bind uuid version major minor version split ' ' major struct pack '<H' int major minor struct pack '<H' int minor bind '\x 05 \x 00 'bind + '\x 0 b'bind + '\x 03 'bind + '\x 10 \x 00 \x 00 \x 00 'bind + 'H\x 00 'bind + '\x 00 \x 00 'bind + '\x 00 \x 00 \x 00 \x 00 'bind + '\xb 8 \x 10 'bind + '\xb 8 \x 10 'bind + '\x 00 \x 00 \x 00 \x 00 'bind + '\x 01 'bind + '\x 00 \x 00 \x 00 'bind + '\x 00 \x 00 'bind + '\x 01 'bind + '\x 00 'bind + misc uuid str to bin uuid bind + majorbind + minorbind + '\x 04 ]\x 88 \x 8 a\xeb\x 1 c\xc 9 \x 11 \x 9 f\xe 8 \x 08 \x 00 +\x 10 H`'bind + '\x 02 \x 00 \x 00 \x 00 'return bind
| null | null | null | null | Question:
What does the code generate ?
Code:
def bind(uuid, version):
(major, minor) = version.split('.')
major = struct.pack('<H', int(major))
minor = struct.pack('<H', int(minor))
bind = '\x05\x00'
bind += '\x0b'
bind += '\x03'
bind += '\x10\x00\x00\x00'
bind += 'H\x00'
bind += '\x00\x00'
bind += '\x00\x00\x00\x00'
bind += '\xb8\x10'
bind += '\xb8\x10'
bind += '\x00\x00\x00\x00'
bind += '\x01'
bind += '\x00\x00\x00'
bind += '\x00\x00'
bind += '\x01'
bind += '\x00'
bind += misc.uuid_str_to_bin(uuid)
bind += major
bind += minor
bind += '\x04]\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00+\x10H`'
bind += '\x02\x00\x00\x00'
return bind
|
null | null | null | What does the code get ?
| def getElementsPath(subName=''):
return getJoinedPath(getGeometryUtilitiesPath('evaluate_elements'), subName)
| null | null | null | the evaluate_elements directory path
| codeqa | def get Elements Path sub Name '' return get Joined Path get Geometry Utilities Path 'evaluate elements' sub Name
| null | null | null | null | Question:
What does the code get ?
Code:
def getElementsPath(subName=''):
return getJoinedPath(getGeometryUtilitiesPath('evaluate_elements'), subName)
|
null | null | null | When do the message and the tensor print ?
| def print_tensor(x, message=''):
return tf.Print(x, [x], message)
| null | null | null | when evaluated
| codeqa | def print tensor x message '' return tf Print x [x] message
| null | null | null | null | Question:
When do the message and the tensor print ?
Code:
def print_tensor(x, message=''):
return tf.Print(x, [x], message)
|
null | null | null | What does the code truncate after a certain number of letters argument ?
| @register.filter(is_safe=True)
@stringfilter
def truncateletters(value, arg):
from django_extensions.utils.text import truncate_letters
try:
length = int(arg)
except ValueError:
return value
return truncate_letters(value, length)
| null | null | null | a string
| codeqa | @register filter is safe True @stringfilterdef truncateletters value arg from django extensions utils text import truncate letterstry length int arg except Value Error return valuereturn truncate letters value length
| null | null | null | null | Question:
What does the code truncate after a certain number of letters argument ?
Code:
@register.filter(is_safe=True)
@stringfilter
def truncateletters(value, arg):
from django_extensions.utils.text import truncate_letters
try:
length = int(arg)
except ValueError:
return value
return truncate_letters(value, length)
|
null | null | null | When does the code truncate a string ?
| @register.filter(is_safe=True)
@stringfilter
def truncateletters(value, arg):
from django_extensions.utils.text import truncate_letters
try:
length = int(arg)
except ValueError:
return value
return truncate_letters(value, length)
| null | null | null | after a certain number of letters argument
| codeqa | @register filter is safe True @stringfilterdef truncateletters value arg from django extensions utils text import truncate letterstry length int arg except Value Error return valuereturn truncate letters value length
| null | null | null | null | Question:
When does the code truncate a string ?
Code:
@register.filter(is_safe=True)
@stringfilter
def truncateletters(value, arg):
from django_extensions.utils.text import truncate_letters
try:
length = int(arg)
except ValueError:
return value
return truncate_letters(value, length)
|
null | null | null | When do letters truncate ?
| @register.filter(is_safe=True)
@stringfilter
def truncateletters(value, arg):
from django_extensions.utils.text import truncate_letters
try:
length = int(arg)
except ValueError:
return value
return truncate_letters(value, length)
| null | null | null | after
| codeqa | @register filter is safe True @stringfilterdef truncateletters value arg from django extensions utils text import truncate letterstry length int arg except Value Error return valuereturn truncate letters value length
| null | null | null | null | Question:
When do letters truncate ?
Code:
@register.filter(is_safe=True)
@stringfilter
def truncateletters(value, arg):
from django_extensions.utils.text import truncate_letters
try:
length = int(arg)
except ValueError:
return value
return truncate_letters(value, length)
|
null | null | null | Who d ftx1000008x ?
| def obtain_serial_number(show_ver):
match = re.search('Processor board ID (.+)', show_ver)
if match:
return match.group(1).strip()
else:
return None
| null | null | null | i
| codeqa | def obtain serial number show ver match re search ' Processorboard ID + ' show ver if match return match group 1 strip else return None
| null | null | null | null | Question:
Who d ftx1000008x ?
Code:
def obtain_serial_number(show_ver):
match = re.search('Processor board ID (.+)', show_ver)
if match:
return match.group(1).strip()
else:
return None
|
null | null | null | What row correspond to the one hot encoding of each element in y a matrix ?
| def to_one_hot(y, nb_class, dtype=None):
ret = theano.tensor.zeros((y.shape[0], nb_class), dtype=dtype)
ret = theano.tensor.set_subtensor(ret[(theano.tensor.arange(y.shape[0]), y)], 1)
return ret
| null | null | null | each row
| codeqa | def to one hot y nb class dtype None ret theano tensor zeros y shape[ 0 ] nb class dtype dtype ret theano tensor set subtensor ret[ theano tensor arange y shape[ 0 ] y ] 1 return ret
| null | null | null | null | Question:
What row correspond to the one hot encoding of each element in y a matrix ?
Code:
def to_one_hot(y, nb_class, dtype=None):
ret = theano.tensor.zeros((y.shape[0], nb_class), dtype=dtype)
ret = theano.tensor.set_subtensor(ret[(theano.tensor.arange(y.shape[0]), y)], 1)
return ret
|
null | null | null | Where row each row correspond to the one hot encoding of each element in y ?
| def to_one_hot(y, nb_class, dtype=None):
ret = theano.tensor.zeros((y.shape[0], nb_class), dtype=dtype)
ret = theano.tensor.set_subtensor(ret[(theano.tensor.arange(y.shape[0]), y)], 1)
return ret
| null | null | null | a matrix
| codeqa | def to one hot y nb class dtype None ret theano tensor zeros y shape[ 0 ] nb class dtype dtype ret theano tensor set subtensor ret[ theano tensor arange y shape[ 0 ] y ] 1 return ret
| null | null | null | null | Question:
Where row each row correspond to the one hot encoding of each element in y ?
Code:
def to_one_hot(y, nb_class, dtype=None):
ret = theano.tensor.zeros((y.shape[0], nb_class), dtype=dtype)
ret = theano.tensor.set_subtensor(ret[(theano.tensor.arange(y.shape[0]), y)], 1)
return ret
|
null | null | null | What does the code compute ?
| def _fwd_bem_linear_collocation_solution(m):
for surf in m['surfs']:
complete_surface_info(surf, copy=False, verbose=False)
logger.info('Computing the linear collocation solution...')
logger.info(' Matrix coefficients...')
coeff = _fwd_bem_lin_pot_coeff(m['surfs'])
m['nsol'] = len(coeff)
logger.info(' Inverting the coefficient matrix...')
nps = [surf['np'] for surf in m['surfs']]
m['solution'] = _fwd_bem_multi_solution(coeff, m['gamma'], nps)
if (len(m['surfs']) == 3):
ip_mult = (m['sigma'][1] / m['sigma'][2])
if (ip_mult <= FIFF.FWD_BEM_IP_APPROACH_LIMIT):
logger.info('IP approach required...')
logger.info(' Matrix coefficients (homog)...')
coeff = _fwd_bem_lin_pot_coeff([m['surfs'][(-1)]])
logger.info(' Inverting the coefficient matrix (homog)...')
ip_solution = _fwd_bem_homog_solution(coeff, [m['surfs'][(-1)]['np']])
logger.info(' Modify the original solution to incorporate IP approach...')
_fwd_bem_ip_modify_solution(m['solution'], ip_solution, ip_mult, nps)
m['bem_method'] = FIFF.FWD_BEM_LINEAR_COLL
logger.info('Solution ready.')
| null | null | null | the linear collocation potential solution
| codeqa | def fwd bem linear collocation solution m for surf in m['surfs'] complete surface info surf copy False verbose False logger info ' Computingthelinearcollocationsolution ' logger info ' Matrixcoefficients ' coeff fwd bem lin pot coeff m['surfs'] m['nsol'] len coeff logger info ' Invertingthecoefficientmatrix ' nps [surf['np'] for surf in m['surfs']]m['solution'] fwd bem multi solution coeff m['gamma'] nps if len m['surfs'] 3 ip mult m['sigma'][ 1 ] / m['sigma'][ 2 ] if ip mult < FIFF FWD BEM IP APPROACH LIMIT logger info 'I Papproachrequired ' logger info ' Matrixcoefficients homog ' coeff fwd bem lin pot coeff [m['surfs'][ -1 ]] logger info ' Invertingthecoefficientmatrix homog ' ip solution fwd bem homog solution coeff [m['surfs'][ -1 ]['np']] logger info ' Modifytheoriginalsolutiontoincorporate I Papproach ' fwd bem ip modify solution m['solution'] ip solution ip mult nps m['bem method'] FIFF FWD BEM LINEAR COL Llogger info ' Solutionready '
| null | null | null | null | Question:
What does the code compute ?
Code:
def _fwd_bem_linear_collocation_solution(m):
for surf in m['surfs']:
complete_surface_info(surf, copy=False, verbose=False)
logger.info('Computing the linear collocation solution...')
logger.info(' Matrix coefficients...')
coeff = _fwd_bem_lin_pot_coeff(m['surfs'])
m['nsol'] = len(coeff)
logger.info(' Inverting the coefficient matrix...')
nps = [surf['np'] for surf in m['surfs']]
m['solution'] = _fwd_bem_multi_solution(coeff, m['gamma'], nps)
if (len(m['surfs']) == 3):
ip_mult = (m['sigma'][1] / m['sigma'][2])
if (ip_mult <= FIFF.FWD_BEM_IP_APPROACH_LIMIT):
logger.info('IP approach required...')
logger.info(' Matrix coefficients (homog)...')
coeff = _fwd_bem_lin_pot_coeff([m['surfs'][(-1)]])
logger.info(' Inverting the coefficient matrix (homog)...')
ip_solution = _fwd_bem_homog_solution(coeff, [m['surfs'][(-1)]['np']])
logger.info(' Modify the original solution to incorporate IP approach...')
_fwd_bem_ip_modify_solution(m['solution'], ip_solution, ip_mult, nps)
m['bem_method'] = FIFF.FWD_BEM_LINEAR_COLL
logger.info('Solution ready.')
|
null | null | null | What chooses stable versions currently ?
| def latest_version(*names, **kwargs):
refresh = salt.utils.is_true(kwargs.pop('refresh', True))
if refresh:
refresh_db()
def get_version(pkg_info):
return (pkg_info['versions']['stable'] or pkg_info['versions']['devel'])
versions_dict = dict(((key, get_version(val)) for (key, val) in six.iteritems(_info(*names))))
if (len(names) == 1):
return next(six.itervalues(versions_dict))
else:
return versions_dict
| null | null | null | the latest version of the named package available for upgrade or installation
| codeqa | def latest version *names **kwargs refresh salt utils is true kwargs pop 'refresh' True if refresh refresh db def get version pkg info return pkg info['versions']['stable'] or pkg info['versions']['devel'] versions dict dict key get version val for key val in six iteritems info *names if len names 1 return next six itervalues versions dict else return versions dict
| null | null | null | null | Question:
What chooses stable versions currently ?
Code:
def latest_version(*names, **kwargs):
refresh = salt.utils.is_true(kwargs.pop('refresh', True))
if refresh:
refresh_db()
def get_version(pkg_info):
return (pkg_info['versions']['stable'] or pkg_info['versions']['devel'])
versions_dict = dict(((key, get_version(val)) for (key, val) in six.iteritems(_info(*names))))
if (len(names) == 1):
return next(six.itervalues(versions_dict))
else:
return versions_dict
|
null | null | null | What do the latest version of the named package available for upgrade or installation choose currently ?
| def latest_version(*names, **kwargs):
refresh = salt.utils.is_true(kwargs.pop('refresh', True))
if refresh:
refresh_db()
def get_version(pkg_info):
return (pkg_info['versions']['stable'] or pkg_info['versions']['devel'])
versions_dict = dict(((key, get_version(val)) for (key, val) in six.iteritems(_info(*names))))
if (len(names) == 1):
return next(six.itervalues(versions_dict))
else:
return versions_dict
| null | null | null | stable versions
| codeqa | def latest version *names **kwargs refresh salt utils is true kwargs pop 'refresh' True if refresh refresh db def get version pkg info return pkg info['versions']['stable'] or pkg info['versions']['devel'] versions dict dict key get version val for key val in six iteritems info *names if len names 1 return next six itervalues versions dict else return versions dict
| null | null | null | null | Question:
What do the latest version of the named package available for upgrade or installation choose currently ?
Code:
def latest_version(*names, **kwargs):
refresh = salt.utils.is_true(kwargs.pop('refresh', True))
if refresh:
refresh_db()
def get_version(pkg_info):
return (pkg_info['versions']['stable'] or pkg_info['versions']['devel'])
versions_dict = dict(((key, get_version(val)) for (key, val) in six.iteritems(_info(*names))))
if (len(names) == 1):
return next(six.itervalues(versions_dict))
else:
return versions_dict
|
null | null | null | What does the code build ?
| def buildSlicedNetwork():
N = FeedForwardNetwork('sliced')
a = LinearLayer(2, name='a')
b = LinearLayer(2, name='b')
N.addInputModule(a)
N.addOutputModule(b)
N.addConnection(FullConnection(a, b, inSliceTo=1, outSliceFrom=1))
N.addConnection(FullConnection(a, b, inSliceFrom=1, outSliceTo=1))
N.sortModules()
return N
| null | null | null | a network with shared connections
| codeqa | def build Sliced Network N Feed Forward Network 'sliced' a Linear Layer 2 name 'a' b Linear Layer 2 name 'b' N add Input Module a N add Output Module b N add Connection Full Connection a b in Slice To 1 out Slice From 1 N add Connection Full Connection a b in Slice From 1 out Slice To 1 N sort Modules return N
| null | null | null | null | Question:
What does the code build ?
Code:
def buildSlicedNetwork():
N = FeedForwardNetwork('sliced')
a = LinearLayer(2, name='a')
b = LinearLayer(2, name='b')
N.addInputModule(a)
N.addOutputModule(b)
N.addConnection(FullConnection(a, b, inSliceTo=1, outSliceFrom=1))
N.addConnection(FullConnection(a, b, inSliceFrom=1, outSliceTo=1))
N.sortModules()
return N
|
null | null | null | What does google alert ?
| def ping_google(sitemap_url=None, ping_url=PING_URL):
if (sitemap_url is None):
try:
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index')
except urlresolvers.NoReverseMatch:
try:
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap')
except urlresolvers.NoReverseMatch:
pass
if (sitemap_url is None):
raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
url = ('http://%s%s' % (current_site.domain, sitemap_url))
params = urlencode({'sitemap': url})
urlopen(('%s?%s' % (ping_url, params)))
| null | null | null | that the sitemap for the current site has been updated
| codeqa | def ping google sitemap url None ping url PING URL if sitemap url is None try sitemap url urlresolvers reverse 'django contrib sitemaps views index' except urlresolvers No Reverse Match try sitemap url urlresolvers reverse 'django contrib sitemaps views sitemap' except urlresolvers No Reverse Match passif sitemap url is None raise Sitemap Not Found " Youdidn'tprovideasitemap url andthesitemap UR Lcouldn'tbeauto-detected " from django contrib sites models import Sitecurrent site Site objects get current url 'http //%s%s' % current site domain sitemap url params urlencode {'sitemap' url} urlopen '%s?%s' % ping url params
| null | null | null | null | Question:
What does google alert ?
Code:
def ping_google(sitemap_url=None, ping_url=PING_URL):
if (sitemap_url is None):
try:
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index')
except urlresolvers.NoReverseMatch:
try:
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap')
except urlresolvers.NoReverseMatch:
pass
if (sitemap_url is None):
raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
url = ('http://%s%s' % (current_site.domain, sitemap_url))
params = urlencode({'sitemap': url})
urlopen(('%s?%s' % (ping_url, params)))
|
null | null | null | What alerts that the sitemap for the current site has been updated ?
| def ping_google(sitemap_url=None, ping_url=PING_URL):
if (sitemap_url is None):
try:
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index')
except urlresolvers.NoReverseMatch:
try:
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap')
except urlresolvers.NoReverseMatch:
pass
if (sitemap_url is None):
raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
url = ('http://%s%s' % (current_site.domain, sitemap_url))
params = urlencode({'sitemap': url})
urlopen(('%s?%s' % (ping_url, params)))
| null | null | null | google
| codeqa | def ping google sitemap url None ping url PING URL if sitemap url is None try sitemap url urlresolvers reverse 'django contrib sitemaps views index' except urlresolvers No Reverse Match try sitemap url urlresolvers reverse 'django contrib sitemaps views sitemap' except urlresolvers No Reverse Match passif sitemap url is None raise Sitemap Not Found " Youdidn'tprovideasitemap url andthesitemap UR Lcouldn'tbeauto-detected " from django contrib sites models import Sitecurrent site Site objects get current url 'http //%s%s' % current site domain sitemap url params urlencode {'sitemap' url} urlopen '%s?%s' % ping url params
| null | null | null | null | Question:
What alerts that the sitemap for the current site has been updated ?
Code:
def ping_google(sitemap_url=None, ping_url=PING_URL):
if (sitemap_url is None):
try:
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index')
except urlresolvers.NoReverseMatch:
try:
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap')
except urlresolvers.NoReverseMatch:
pass
if (sitemap_url is None):
raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
url = ('http://%s%s' % (current_site.domain, sitemap_url))
params = urlencode({'sitemap': url})
urlopen(('%s?%s' % (ping_url, params)))
|
null | null | null | What does the code ensure ?
| def cache_cluster_absent(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for (k, v) in args.items() if (not k.startswith('_'))])
exists = __salt__['boto3_elasticache.cache_cluster_exists'](name, region=region, key=key, keyid=keyid, profile=profile)
if exists:
if __opts__['test']:
ret['comment'] = 'Cache cluster {0} would be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto3_elasticache.delete_cache_cluster'](name, wait=wait, region=region, key=key, keyid=keyid, profile=profile, **args)
if deleted:
ret['changes']['old'] = name
ret['changes']['new'] = None
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} cache cluster.'.format(name)
else:
ret['comment'] = 'Cache cluster {0} already absent.'.format(name)
return ret
| null | null | null | a given cache cluster is deleted
| codeqa | def cache cluster absent name wait 600 region None key None keyid None profile None **args ret {'name' name 'result' True 'comment' '' 'changes' {}}args dict [ k v for k v in args items if not k startswith ' ' ] exists salt ['boto 3 elasticache cache cluster exists'] name region region key key keyid keyid profile profile if exists if opts ['test'] ret['comment'] ' Cachecluster{ 0 }wouldberemoved ' format name ret['result'] Nonereturn retdeleted salt ['boto 3 elasticache delete cache cluster'] name wait wait region region key key keyid keyid profile profile **args if deleted ret['changes']['old'] nameret['changes']['new'] Noneelse ret['result'] Falseret['comment'] ' Failedtodelete{ 0 }cachecluster ' format name else ret['comment'] ' Cachecluster{ 0 }alreadyabsent ' format name return ret
| null | null | null | null | Question:
What does the code ensure ?
Code:
def cache_cluster_absent(name, wait=600, region=None, key=None, keyid=None, profile=None, **args):
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for (k, v) in args.items() if (not k.startswith('_'))])
exists = __salt__['boto3_elasticache.cache_cluster_exists'](name, region=region, key=key, keyid=keyid, profile=profile)
if exists:
if __opts__['test']:
ret['comment'] = 'Cache cluster {0} would be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto3_elasticache.delete_cache_cluster'](name, wait=wait, region=region, key=key, keyid=keyid, profile=profile, **args)
if deleted:
ret['changes']['old'] = name
ret['changes']['new'] = None
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} cache cluster.'.format(name)
else:
ret['comment'] = 'Cache cluster {0} already absent.'.format(name)
return ret
|
null | null | null | When does the password expire ?
| def set_change(name, date):
_set_account_policy(name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return (get_change(name) == date)
| null | null | null | the date
| codeqa | def set change name date set account policy name 'using Expiration Date 1expiration Date GMT {0 }' format date return get change name date
| null | null | null | null | Question:
When does the password expire ?
Code:
def set_change(name, date):
_set_account_policy(name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return (get_change(name) == date)
|
null | null | null | What does the code take ?
| def take_snapshot():
if (not is_tracing()):
raise RuntimeError('the tracemalloc module must be tracing memory allocations to take a snapshot')
traces = _get_traces()
traceback_limit = get_traceback_limit()
return Snapshot(traces, traceback_limit)
| null | null | null | a snapshot of traces of memory blocks allocated by python
| codeqa | def take snapshot if not is tracing raise Runtime Error 'thetracemallocmodulemustbetracingmemoryallocationstotakeasnapshot' traces get traces traceback limit get traceback limit return Snapshot traces traceback limit
| null | null | null | null | Question:
What does the code take ?
Code:
def take_snapshot():
if (not is_tracing()):
raise RuntimeError('the tracemalloc module must be tracing memory allocations to take a snapshot')
traces = _get_traces()
traceback_limit = get_traceback_limit()
return Snapshot(traces, traceback_limit)
|
null | null | null | What catches database integrity errors ?
| def catch_integrity_errors(session):
def decorated(func):
'Returns a decorated version of ``func``, as described in the\n wrapper defined within.\n\n '
@wraps(func)
def wrapped(*args, **kw):
'Executes ``func(*args, **kw)`` but catches any exception\n that warrants a database rollback.\n\n '
try:
return func(*args, **kw)
except SQLAlchemyError as exception:
session.rollback()
status = (409 if is_conflict(exception) else 400)
detail = str(exception)
title = un_camel_case(exception.__class__.__name__)
return error_response(status, cause=exception, detail=detail, title=title)
return wrapped
return decorated
| null | null | null | a decorator
| codeqa | def catch integrity errors session def decorated func ' Returnsadecoratedversionof``func`` asdescribedinthe\nwrapperdefinedwithin \n\n'@wraps func def wrapped *args **kw ' Executes``func *args **kw ``butcatchesanyexception\nthatwarrantsadatabaserollback \n\n'try return func *args **kw except SQL Alchemy Error as exception session rollback status 409 if is conflict exception else 400 detail str exception title un camel case exception class name return error response status cause exception detail detail title title return wrappedreturn decorated
| null | null | null | null | Question:
What catches database integrity errors ?
Code:
def catch_integrity_errors(session):
def decorated(func):
'Returns a decorated version of ``func``, as described in the\n wrapper defined within.\n\n '
@wraps(func)
def wrapped(*args, **kw):
'Executes ``func(*args, **kw)`` but catches any exception\n that warrants a database rollback.\n\n '
try:
return func(*args, **kw)
except SQLAlchemyError as exception:
session.rollback()
status = (409 if is_conflict(exception) else 400)
detail = str(exception)
title = un_camel_case(exception.__class__.__name__)
return error_response(status, cause=exception, detail=detail, title=title)
return wrapped
return decorated
|
null | null | null | What does a decorator catch ?
| def catch_integrity_errors(session):
def decorated(func):
'Returns a decorated version of ``func``, as described in the\n wrapper defined within.\n\n '
@wraps(func)
def wrapped(*args, **kw):
'Executes ``func(*args, **kw)`` but catches any exception\n that warrants a database rollback.\n\n '
try:
return func(*args, **kw)
except SQLAlchemyError as exception:
session.rollback()
status = (409 if is_conflict(exception) else 400)
detail = str(exception)
title = un_camel_case(exception.__class__.__name__)
return error_response(status, cause=exception, detail=detail, title=title)
return wrapped
return decorated
| null | null | null | database integrity errors
| codeqa | def catch integrity errors session def decorated func ' Returnsadecoratedversionof``func`` asdescribedinthe\nwrapperdefinedwithin \n\n'@wraps func def wrapped *args **kw ' Executes``func *args **kw ``butcatchesanyexception\nthatwarrantsadatabaserollback \n\n'try return func *args **kw except SQL Alchemy Error as exception session rollback status 409 if is conflict exception else 400 detail str exception title un camel case exception class name return error response status cause exception detail detail title title return wrappedreturn decorated
| null | null | null | null | Question:
What does a decorator catch ?
Code:
def catch_integrity_errors(session):
def decorated(func):
'Returns a decorated version of ``func``, as described in the\n wrapper defined within.\n\n '
@wraps(func)
def wrapped(*args, **kw):
'Executes ``func(*args, **kw)`` but catches any exception\n that warrants a database rollback.\n\n '
try:
return func(*args, **kw)
except SQLAlchemyError as exception:
session.rollback()
status = (409 if is_conflict(exception) else 400)
detail = str(exception)
title = un_camel_case(exception.__class__.__name__)
return error_response(status, cause=exception, detail=detail, title=title)
return wrapped
return decorated
|
null | null | null | What does the code display according to the predefined versions settings ?
| def version(parser, token):
bits = token.split_contents()
if ((len(bits) != 3) and (len(bits) != 5)):
raise TemplateSyntaxError("'version' tag takes 2 or 4 arguments")
if ((len(bits) == 5) and (bits[3] != 'as')):
raise TemplateSyntaxError("second argument to 'version' tag must be 'as'")
if (len(bits) == 3):
return VersionNode(parser.compile_filter(bits[1]), parser.compile_filter(bits[2]), None)
if (len(bits) == 5):
return VersionNode(parser.compile_filter(bits[1]), parser.compile_filter(bits[2]), bits[4])
| null | null | null | a version of an existing image
| codeqa | def version parser token bits token split contents if len bits 3 and len bits 5 raise Template Syntax Error "'version'tagtakes 2 or 4 arguments" if len bits 5 and bits[ 3 ] 'as' raise Template Syntax Error "secondargumentto'version'tagmustbe'as'" if len bits 3 return Version Node parser compile filter bits[ 1 ] parser compile filter bits[ 2 ] None if len bits 5 return Version Node parser compile filter bits[ 1 ] parser compile filter bits[ 2 ] bits[ 4 ]
| null | null | null | null | Question:
What does the code display according to the predefined versions settings ?
Code:
def version(parser, token):
bits = token.split_contents()
if ((len(bits) != 3) and (len(bits) != 5)):
raise TemplateSyntaxError("'version' tag takes 2 or 4 arguments")
if ((len(bits) == 5) and (bits[3] != 'as')):
raise TemplateSyntaxError("second argument to 'version' tag must be 'as'")
if (len(bits) == 3):
return VersionNode(parser.compile_filter(bits[1]), parser.compile_filter(bits[2]), None)
if (len(bits) == 5):
return VersionNode(parser.compile_filter(bits[1]), parser.compile_filter(bits[2]), bits[4])
|
null | null | null | What does the code compute ?
| def dice(u, v):
u = _validate_vector(u)
v = _validate_vector(v)
if (u.dtype == bool):
ntt = (u & v).sum()
else:
ntt = (u * v).sum()
(nft, ntf) = _nbool_correspond_ft_tf(u, v)
return (float((ntf + nft)) / float((((2.0 * ntt) + ntf) + nft)))
| null | null | null | the dice dissimilarity between two boolean 1-d arrays
| codeqa | def dice u v u validate vector u v validate vector v if u dtype bool ntt u & v sum else ntt u * v sum nft ntf nbool correspond ft tf u v return float ntf + nft / float 2 0 * ntt + ntf + nft
| null | null | null | null | Question:
What does the code compute ?
Code:
def dice(u, v):
u = _validate_vector(u)
v = _validate_vector(v)
if (u.dtype == bool):
ntt = (u & v).sum()
else:
ntt = (u * v).sum()
(nft, ntf) = _nbool_correspond_ft_tf(u, v)
return (float((ntf + nft)) / float((((2.0 * ntt) + ntf) + nft)))
|
null | null | null | What is user assigned ?
| def check_role(username, role):
return (role in get_roles(username))
| null | null | null | a specific role on switch
| codeqa | def check role username role return role in get roles username
| null | null | null | null | Question:
What is user assigned ?
Code:
def check_role(username, role):
return (role in get_roles(username))
|
null | null | null | When can a pool not execute all submitted jobs ?
| def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
| null | null | null | at once
| codeqa | def test simple concurrency pool make pool 1 1 for i in range 3 pool put Fake Tar Partition 1 pool join
| null | null | null | null | Question:
When can a pool not execute all submitted jobs ?
Code:
def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
|
null | null | null | What does the code try ?
| def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
| null | null | null | a pool that can not execute all submitted jobs at once
| codeqa | def test simple concurrency pool make pool 1 1 for i in range 3 pool put Fake Tar Partition 1 pool join
| null | null | null | null | Question:
What does the code try ?
Code:
def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
|
null | null | null | What can a pool not execute at once ?
| def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
| null | null | null | all submitted jobs
| codeqa | def test simple concurrency pool make pool 1 1 for i in range 3 pool put Fake Tar Partition 1 pool join
| null | null | null | null | Question:
What can a pool not execute at once ?
Code:
def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
|
null | null | null | Can a pool execute all submitted jobs at once ?
| def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
| null | null | null | No
| codeqa | def test simple concurrency pool make pool 1 1 for i in range 3 pool put Fake Tar Partition 1 pool join
| null | null | null | null | Question:
Can a pool execute all submitted jobs at once ?
Code:
def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
|
null | null | null | What can not execute all submitted jobs at once ?
| def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
| null | null | null | a pool
| codeqa | def test simple concurrency pool make pool 1 1 for i in range 3 pool put Fake Tar Partition 1 pool join
| null | null | null | null | Question:
What can not execute all submitted jobs at once ?
Code:
def test_simple_concurrency():
pool = make_pool(1, 1)
for i in range(3):
pool.put(FakeTarPartition(1))
pool.join()
|
null | null | null | What does the code normalize ?
| def rax_slugify(value):
return ('rax_%s' % re.sub('[^\\w-]', '_', value).lower().lstrip('_'))
| null | null | null | the key name
| codeqa | def rax slugify value return 'rax %s' % re sub '[^\\w-]' ' ' value lower lstrip ' '
| null | null | null | null | Question:
What does the code normalize ?
Code:
def rax_slugify(value):
return ('rax_%s' % re.sub('[^\\w-]', '_', value).lower().lstrip('_'))
|
null | null | null | What does the code normalize ?
| def normalize_excludes(rootpath, excludes):
return [path.abspath(exclude) for exclude in excludes]
| null | null | null | the excluded directory list
| codeqa | def normalize excludes rootpath excludes return [path abspath exclude for exclude in excludes]
| null | null | null | null | Question:
What does the code normalize ?
Code:
def normalize_excludes(rootpath, excludes):
return [path.abspath(exclude) for exclude in excludes]
|
null | null | null | When are percentile summaries sorted ?
| def merge_and_compress_summaries(vals_and_weights):
vals_and_weights = [x for x in vals_and_weights if x]
if (not vals_and_weights):
return ()
it = merge_sorted(*[zip(x, y) for (x, y) in vals_and_weights])
vals = []
weights = []
vals_append = vals.append
weights_append = weights.append
(val, weight) = (prev_val, prev_weight) = next(it)
for (val, weight) in it:
if (val == prev_val):
prev_weight += weight
else:
vals_append(prev_val)
weights_append(prev_weight)
(prev_val, prev_weight) = (val, weight)
if (val == prev_val):
vals_append(prev_val)
weights_append(prev_weight)
return (vals, weights)
| null | null | null | already
| codeqa | def merge and compress summaries vals and weights vals and weights [x for x in vals and weights if x]if not vals and weights return it merge sorted *[zip x y for x y in vals and weights] vals []weights []vals append vals appendweights append weights append val weight prev val prev weight next it for val weight in it if val prev val prev weight + weightelse vals append prev val weights append prev weight prev val prev weight val weight if val prev val vals append prev val weights append prev weight return vals weights
| null | null | null | null | Question:
When are percentile summaries sorted ?
Code:
def merge_and_compress_summaries(vals_and_weights):
vals_and_weights = [x for x in vals_and_weights if x]
if (not vals_and_weights):
return ()
it = merge_sorted(*[zip(x, y) for (x, y) in vals_and_weights])
vals = []
weights = []
vals_append = vals.append
weights_append = weights.append
(val, weight) = (prev_val, prev_weight) = next(it)
for (val, weight) in it:
if (val == prev_val):
prev_weight += weight
else:
vals_append(prev_val)
weights_append(prev_weight)
(prev_val, prev_weight) = (val, weight)
if (val == prev_val):
vals_append(prev_val)
weights_append(prev_weight)
return (vals, weights)
|
null | null | null | How does the code extract user information ?
| def ssl_get_cert_from_request(request):
certkey = 'SSL_CLIENT_S_DN'
cert = request.META.get(certkey, '')
if (not cert):
cert = request.META.get(('HTTP_' + certkey), '')
if (not cert):
try:
cert = request._req.subprocess_env.get(certkey, '')
except Exception:
return ''
return cert
| null | null | null | from certificate
| codeqa | def ssl get cert from request request certkey 'SSL CLIENT S DN'cert request META get certkey '' if not cert cert request META get 'HTTP ' + certkey '' if not cert try cert request req subprocess env get certkey '' except Exception return ''return cert
| null | null | null | null | Question:
How does the code extract user information ?
Code:
def ssl_get_cert_from_request(request):
certkey = 'SSL_CLIENT_S_DN'
cert = request.META.get(certkey, '')
if (not cert):
cert = request.META.get(('HTTP_' + certkey), '')
if (not cert):
try:
cert = request._req.subprocess_env.get(certkey, '')
except Exception:
return ''
return cert
|
null | null | null | How does the object to process the given format return ?
| def get_processor(format, mapping):
try:
obj_info = mapping[format]
except KeyError:
if (format is None):
raise ValueError('Format required (lower case string)')
elif (not isinstance(format, basestring)):
raise TypeError('Need a string for the file format (lower case)')
elif (format != format.lower()):
raise ValueError(('Format string %r should be lower case' % format))
else:
raise ValueError(('Unknown format %r. Supported formats are %r' % (format, "', '".join(mapping))))
(mod_name, obj_name) = obj_info
mod = __import__(('Bio.SearchIO.%s' % mod_name), fromlist=[''])
return getattr(mod, obj_name)
| null | null | null | according to the mapping
| codeqa | def get processor format mapping try obj info mapping[format]except Key Error if format is None raise Value Error ' Formatrequired lowercasestring ' elif not isinstance format basestring raise Type Error ' Needastringforthefileformat lowercase ' elif format format lower raise Value Error ' Formatstring%rshouldbelowercase' % format else raise Value Error ' Unknownformat%r Supportedformatsare%r' % format "' '" join mapping mod name obj name obj infomod import ' Bio Search IO %s' % mod name fromlist [''] return getattr mod obj name
| null | null | null | null | Question:
How does the object to process the given format return ?
Code:
def get_processor(format, mapping):
try:
obj_info = mapping[format]
except KeyError:
if (format is None):
raise ValueError('Format required (lower case string)')
elif (not isinstance(format, basestring)):
raise TypeError('Need a string for the file format (lower case)')
elif (format != format.lower()):
raise ValueError(('Format string %r should be lower case' % format))
else:
raise ValueError(('Unknown format %r. Supported formats are %r' % (format, "', '".join(mapping))))
(mod_name, obj_name) = obj_info
mod = __import__(('Bio.SearchIO.%s' % mod_name), fromlist=[''])
return getattr(mod, obj_name)
|
null | null | null | In which direction must string change into boolean defaults to true ?
| def env_to_bool(input):
if isinstance(input, str):
if (input == 'False'):
return False
else:
return True
else:
return input
| null | null | null | from environment variable
| codeqa | def env to bool input if isinstance input str if input ' False' return Falseelse return Trueelse return input
| null | null | null | null | Question:
In which direction must string change into boolean defaults to true ?
Code:
def env_to_bool(input):
if isinstance(input, str):
if (input == 'False'):
return False
else:
return True
else:
return input
|
null | null | null | What does the code generate ?
| def random_name(size=6):
return ('CLOUD-TEST-' + ''.join((random.choice((string.ascii_uppercase + string.digits)) for x in range(size))))
| null | null | null | a random cloud instance name
| codeqa | def random name size 6 return 'CLOUD-TEST-' + '' join random choice string ascii uppercase + string digits for x in range size
| null | null | null | null | Question:
What does the code generate ?
Code:
def random_name(size=6):
return ('CLOUD-TEST-' + ''.join((random.choice((string.ascii_uppercase + string.digits)) for x in range(size))))
|
null | null | null | What can a function be used ?
| @pytest.fixture()
def execute_task(manager):
def execute(task_name, abort=False, options=None):
u'\n Use to execute one test task from config.\n\n :param abort: If `True` expect (and require) this task to abort.\n '
log.info((u'********** Running task: %s ********** ' % task_name))
config = manager.config[u'tasks'][task_name]
task = Task(manager, task_name, config=config, options=options)
try:
if abort:
with pytest.raises(TaskAbort):
task.execute()
else:
task.execute()
finally:
try:
task.session.close()
except Exception:
pass
return task
return execute
| null | null | null | to execute and return a named task in config argument
| codeqa | @pytest fixture def execute task manager def execute task name abort False options None u'\n Usetoexecuteonetesttaskfromconfig \n\n paramabort If` True`expect andrequire thistasktoabort \n'log info u'********** Runningtask %s**********' % task name config manager config[u'tasks'][task name]task Task manager task name config config options options try if abort with pytest raises Task Abort task execute else task execute finally try task session close except Exception passreturn taskreturn execute
| null | null | null | null | Question:
What can a function be used ?
Code:
@pytest.fixture()
def execute_task(manager):
def execute(task_name, abort=False, options=None):
u'\n Use to execute one test task from config.\n\n :param abort: If `True` expect (and require) this task to abort.\n '
log.info((u'********** Running task: %s ********** ' % task_name))
config = manager.config[u'tasks'][task_name]
task = Task(manager, task_name, config=config, options=options)
try:
if abort:
with pytest.raises(TaskAbort):
task.execute()
else:
task.execute()
finally:
try:
task.session.close()
except Exception:
pass
return task
return execute
|
null | null | null | What can be used to execute and return a named task in config argument ?
| @pytest.fixture()
def execute_task(manager):
def execute(task_name, abort=False, options=None):
u'\n Use to execute one test task from config.\n\n :param abort: If `True` expect (and require) this task to abort.\n '
log.info((u'********** Running task: %s ********** ' % task_name))
config = manager.config[u'tasks'][task_name]
task = Task(manager, task_name, config=config, options=options)
try:
if abort:
with pytest.raises(TaskAbort):
task.execute()
else:
task.execute()
finally:
try:
task.session.close()
except Exception:
pass
return task
return execute
| null | null | null | a function
| codeqa | @pytest fixture def execute task manager def execute task name abort False options None u'\n Usetoexecuteonetesttaskfromconfig \n\n paramabort If` True`expect andrequire thistasktoabort \n'log info u'********** Runningtask %s**********' % task name config manager config[u'tasks'][task name]task Task manager task name config config options options try if abort with pytest raises Task Abort task execute else task execute finally try task session close except Exception passreturn taskreturn execute
| null | null | null | null | Question:
What can be used to execute and return a named task in config argument ?
Code:
@pytest.fixture()
def execute_task(manager):
def execute(task_name, abort=False, options=None):
u'\n Use to execute one test task from config.\n\n :param abort: If `True` expect (and require) this task to abort.\n '
log.info((u'********** Running task: %s ********** ' % task_name))
config = manager.config[u'tasks'][task_name]
task = Task(manager, task_name, config=config, options=options)
try:
if abort:
with pytest.raises(TaskAbort):
task.execute()
else:
task.execute()
finally:
try:
task.session.close()
except Exception:
pass
return task
return execute
|
null | null | null | Where is the image uniform and less than mask ?
| def test_image_less_than_mask():
image = np.ones((5, 5))
mask = (np.ones((5, 5)) * 2)
assert_close(reconstruction(image, mask), 1)
| null | null | null | test reconstruction
| codeqa | def test image less than mask image np ones 5 5 mask np ones 5 5 * 2 assert close reconstruction image mask 1
| null | null | null | null | Question:
Where is the image uniform and less than mask ?
Code:
def test_image_less_than_mask():
image = np.ones((5, 5))
mask = (np.ones((5, 5)) * 2)
assert_close(reconstruction(image, mask), 1)
|
null | null | null | What is uniform and less than mask test reconstruction ?
| def test_image_less_than_mask():
image = np.ones((5, 5))
mask = (np.ones((5, 5)) * 2)
assert_close(reconstruction(image, mask), 1)
| null | null | null | the image
| codeqa | def test image less than mask image np ones 5 5 mask np ones 5 5 * 2 assert close reconstruction image mask 1
| null | null | null | null | Question:
What is uniform and less than mask test reconstruction ?
Code:
def test_image_less_than_mask():
image = np.ones((5, 5))
mask = (np.ones((5, 5)) * 2)
assert_close(reconstruction(image, mask), 1)
|
null | null | null | What does the code initialize via --colorize ?
| def _InitColorize(output_file):
color = False
if ((options.options.colorize is not None) and curses and ((options.options.color == 'yes') or ((options.options.color == 'auto') and output_file.isatty()))):
try:
curses.setupterm()
if (curses.tigetnum('colors') > 0):
color = True
except Exception:
pass
if (not color):
return []
directives = []
normal = unicode(curses.tigetstr('sgr0'), 'ascii')
fg_color = unicode((curses.tigetstr('setaf') or curses.tigetstr('setf') or ''), 'ascii')
for directive in options.options.colorize:
(regexp, color_index) = directive.split('=')
color = unicode(curses.tparm(fg_color, int(color_index)), 'ascii')
directives.append(ColorDirective(re.compile(regexp), color, normal))
return directives
| null | null | null | the colorization directives
| codeqa | def Init Colorize output file color Falseif options options colorize is not None and curses and options options color 'yes' or options options color 'auto' and output file isatty try curses setupterm if curses tigetnum 'colors' > 0 color Trueexcept Exception passif not color return []directives []normal unicode curses tigetstr 'sgr 0 ' 'ascii' fg color unicode curses tigetstr 'setaf' or curses tigetstr 'setf' or '' 'ascii' for directive in options options colorize regexp color index directive split ' ' color unicode curses tparm fg color int color index 'ascii' directives append Color Directive re compile regexp color normal return directives
| null | null | null | null | Question:
What does the code initialize via --colorize ?
Code:
def _InitColorize(output_file):
color = False
if ((options.options.colorize is not None) and curses and ((options.options.color == 'yes') or ((options.options.color == 'auto') and output_file.isatty()))):
try:
curses.setupterm()
if (curses.tigetnum('colors') > 0):
color = True
except Exception:
pass
if (not color):
return []
directives = []
normal = unicode(curses.tigetstr('sgr0'), 'ascii')
fg_color = unicode((curses.tigetstr('setaf') or curses.tigetstr('setf') or ''), 'ascii')
for directive in options.options.colorize:
(regexp, color_index) = directive.split('=')
color = unicode(curses.tparm(fg_color, int(color_index)), 'ascii')
directives.append(ColorDirective(re.compile(regexp), color, normal))
return directives
|
null | null | null | How does the code initialize the colorization directives ?
| def _InitColorize(output_file):
color = False
if ((options.options.colorize is not None) and curses and ((options.options.color == 'yes') or ((options.options.color == 'auto') and output_file.isatty()))):
try:
curses.setupterm()
if (curses.tigetnum('colors') > 0):
color = True
except Exception:
pass
if (not color):
return []
directives = []
normal = unicode(curses.tigetstr('sgr0'), 'ascii')
fg_color = unicode((curses.tigetstr('setaf') or curses.tigetstr('setf') or ''), 'ascii')
for directive in options.options.colorize:
(regexp, color_index) = directive.split('=')
color = unicode(curses.tparm(fg_color, int(color_index)), 'ascii')
directives.append(ColorDirective(re.compile(regexp), color, normal))
return directives
| null | null | null | via --colorize
| codeqa | def Init Colorize output file color Falseif options options colorize is not None and curses and options options color 'yes' or options options color 'auto' and output file isatty try curses setupterm if curses tigetnum 'colors' > 0 color Trueexcept Exception passif not color return []directives []normal unicode curses tigetstr 'sgr 0 ' 'ascii' fg color unicode curses tigetstr 'setaf' or curses tigetstr 'setf' or '' 'ascii' for directive in options options colorize regexp color index directive split ' ' color unicode curses tparm fg color int color index 'ascii' directives append Color Directive re compile regexp color normal return directives
| null | null | null | null | Question:
How does the code initialize the colorization directives ?
Code:
def _InitColorize(output_file):
color = False
if ((options.options.colorize is not None) and curses and ((options.options.color == 'yes') or ((options.options.color == 'auto') and output_file.isatty()))):
try:
curses.setupterm()
if (curses.tigetnum('colors') > 0):
color = True
except Exception:
pass
if (not color):
return []
directives = []
normal = unicode(curses.tigetstr('sgr0'), 'ascii')
fg_color = unicode((curses.tigetstr('setaf') or curses.tigetstr('setf') or ''), 'ascii')
for directive in options.options.colorize:
(regexp, color_index) = directive.split('=')
color = unicode(curses.tparm(fg_color, int(color_index)), 'ascii')
directives.append(ColorDirective(re.compile(regexp), color, normal))
return directives
|
null | null | null | What meant to be matched against log filename and target curses color escape codes ?
| def _InitColorize(output_file):
color = False
if ((options.options.colorize is not None) and curses and ((options.options.color == 'yes') or ((options.options.color == 'auto') and output_file.isatty()))):
try:
curses.setupterm()
if (curses.tigetnum('colors') > 0):
color = True
except Exception:
pass
if (not color):
return []
directives = []
normal = unicode(curses.tigetstr('sgr0'), 'ascii')
fg_color = unicode((curses.tigetstr('setaf') or curses.tigetstr('setf') or ''), 'ascii')
for directive in options.options.colorize:
(regexp, color_index) = directive.split('=')
color = unicode(curses.tparm(fg_color, int(color_index)), 'ascii')
directives.append(ColorDirective(re.compile(regexp), color, normal))
return directives
| null | null | null | compiled regular expressions
| codeqa | def Init Colorize output file color Falseif options options colorize is not None and curses and options options color 'yes' or options options color 'auto' and output file isatty try curses setupterm if curses tigetnum 'colors' > 0 color Trueexcept Exception passif not color return []directives []normal unicode curses tigetstr 'sgr 0 ' 'ascii' fg color unicode curses tigetstr 'setaf' or curses tigetstr 'setf' or '' 'ascii' for directive in options options colorize regexp color index directive split ' ' color unicode curses tparm fg color int color index 'ascii' directives append Color Directive re compile regexp color normal return directives
| null | null | null | null | Question:
What meant to be matched against log filename and target curses color escape codes ?
Code:
def _InitColorize(output_file):
color = False
if ((options.options.colorize is not None) and curses and ((options.options.color == 'yes') or ((options.options.color == 'auto') and output_file.isatty()))):
try:
curses.setupterm()
if (curses.tigetnum('colors') > 0):
color = True
except Exception:
pass
if (not color):
return []
directives = []
normal = unicode(curses.tigetstr('sgr0'), 'ascii')
fg_color = unicode((curses.tigetstr('setaf') or curses.tigetstr('setf') or ''), 'ascii')
for directive in options.options.colorize:
(regexp, color_index) = directive.split('=')
color = unicode(curses.tparm(fg_color, int(color_index)), 'ascii')
directives.append(ColorDirective(re.compile(regexp), color, normal))
return directives
|
null | null | null | When do a string represent time ?
| def time2isoz(t=None):
if (t is None):
t = time.time()
(year, mon, mday, hour, min, sec) = time.gmtime(t)[:6]
return ('%04d-%02d-%02d %02d:%02d:%02dZ' % (year, mon, mday, hour, min, sec))
| null | null | null | in seconds
| codeqa | def time 2 isoz t None if t is None t time time year mon mday hour min sec time gmtime t [ 6]return '% 04 d-% 02 d-% 02 d% 02 d %02 d %02 d Z' % year mon mday hour min sec
| null | null | null | null | Question:
When do a string represent time ?
Code:
def time2isoz(t=None):
if (t is None):
t = time.time()
(year, mon, mday, hour, min, sec) = time.gmtime(t)[:6]
return ('%04d-%02d-%02d %02d:%02d:%02dZ' % (year, mon, mday, hour, min, sec))
|
null | null | null | When do a string representing time in seconds return code ?
| def time2isoz(t=None):
if (t is None):
t = time.time()
(year, mon, mday, hour, min, sec) = time.gmtime(t)[:6]
return ('%04d-%02d-%02d %02d:%02d:%02dZ' % (year, mon, mday, hour, min, sec))
| null | null | null | since epoch
| codeqa | def time 2 isoz t None if t is None t time time year mon mday hour min sec time gmtime t [ 6]return '% 04 d-% 02 d-% 02 d% 02 d %02 d %02 d Z' % year mon mday hour min sec
| null | null | null | null | Question:
When do a string representing time in seconds return code ?
Code:
def time2isoz(t=None):
if (t is None):
t = time.time()
(year, mon, mday, hour, min, sec) = time.gmtime(t)[:6]
return ('%04d-%02d-%02d %02d:%02d:%02dZ' % (year, mon, mday, hour, min, sec))
|
null | null | null | What does the code create ?
| def group_create(context, data_dict):
if (data_dict.get('type') == 'organization'):
raise Exception(_('Trying to create an organization as a group'))
_check_access('group_create', context, data_dict)
return _group_or_org_create(context, data_dict)
| null | null | null | a new group
| codeqa | def group create context data dict if data dict get 'type' 'organization' raise Exception ' Tryingtocreateanorganizationasagroup' check access 'group create' context data dict return group or org create context data dict
| null | null | null | null | Question:
What does the code create ?
Code:
def group_create(context, data_dict):
if (data_dict.get('type') == 'organization'):
raise Exception(_('Trying to create an organization as a group'))
_check_access('group_create', context, data_dict)
return _group_or_org_create(context, data_dict)
|
null | null | null | What does the code build ?
| def build_flow_dict(G, R):
flow_dict = {}
for u in G:
flow_dict[u] = dict(((v, 0) for v in G[u]))
flow_dict[u].update(((v, attr['flow']) for (v, attr) in R[u].items() if (attr['flow'] > 0)))
return flow_dict
| null | null | null | a flow dictionary from a residual network
| codeqa | def build flow dict G R flow dict {}for u in G flow dict[u] dict v 0 for v in G[u] flow dict[u] update v attr['flow'] for v attr in R[u] items if attr['flow'] > 0 return flow dict
| null | null | null | null | Question:
What does the code build ?
Code:
def build_flow_dict(G, R):
flow_dict = {}
for u in G:
flow_dict[u] = dict(((v, 0) for v in G[u]))
flow_dict[u].update(((v, attr['flow']) for (v, attr) in R[u].items() if (attr['flow'] > 0)))
return flow_dict
|
null | null | null | What is removing extra data ?
| def version_clean(version):
return re.match('^~?[<>]?=?([^<>=:\\[]+).*$', version)
| null | null | null | the version string
| codeqa | def version clean version return re match '^~?[<>]? ? [^<> \\[]+ *$' version
| null | null | null | null | Question:
What is removing extra data ?
Code:
def version_clean(version):
return re.match('^~?[<>]?=?([^<>=:\\[]+).*$', version)
|
null | null | null | What does the code clean ?
| def version_clean(version):
return re.match('^~?[<>]?=?([^<>=:\\[]+).*$', version)
| null | null | null | the version string removing extra data
| codeqa | def version clean version return re match '^~?[<>]? ? [^<> \\[]+ *$' version
| null | null | null | null | Question:
What does the code clean ?
Code:
def version_clean(version):
return re.match('^~?[<>]?=?([^<>=:\\[]+).*$', version)
|
null | null | null | What does the code create ?
| def create_credential_resolver(session):
profile_name = (session.get_config_variable('profile') or 'default')
credential_file = session.get_config_variable('credentials_file')
config_file = session.get_config_variable('config_file')
metadata_timeout = session.get_config_variable('metadata_service_timeout')
num_attempts = session.get_config_variable('metadata_service_num_attempts')
env_provider = EnvProvider()
providers = [env_provider, AssumeRoleProvider(load_config=(lambda : session.full_config), client_creator=session.create_client, cache={}, profile_name=profile_name), SharedCredentialProvider(creds_filename=credential_file, profile_name=profile_name), ConfigProvider(config_filename=config_file, profile_name=profile_name), OriginalEC2Provider(), BotoProvider(), ContainerProvider(), InstanceMetadataProvider(iam_role_fetcher=InstanceMetadataFetcher(timeout=metadata_timeout, num_attempts=num_attempts))]
explicit_profile = session.get_config_variable('profile', methods=('instance',))
if (explicit_profile is not None):
providers.remove(env_provider)
logger.debug('Skipping environment variable credential check because profile name was explicitly set.')
resolver = CredentialResolver(providers=providers)
return resolver
| null | null | null | a default credential resolver
| codeqa | def create credential resolver session profile name session get config variable 'profile' or 'default' credential file session get config variable 'credentials file' config file session get config variable 'config file' metadata timeout session get config variable 'metadata service timeout' num attempts session get config variable 'metadata service num attempts' env provider Env Provider providers [env provider Assume Role Provider load config lambda session full config client creator session create client cache {} profile name profile name Shared Credential Provider creds filename credential file profile name profile name Config Provider config filename config file profile name profile name Original EC 2 Provider Boto Provider Container Provider Instance Metadata Provider iam role fetcher Instance Metadata Fetcher timeout metadata timeout num attempts num attempts ]explicit profile session get config variable 'profile' methods 'instance' if explicit profile is not None providers remove env provider logger debug ' Skippingenvironmentvariablecredentialcheckbecauseprofilenamewasexplicitlyset ' resolver Credential Resolver providers providers return resolver
| null | null | null | null | Question:
What does the code create ?
Code:
def create_credential_resolver(session):
profile_name = (session.get_config_variable('profile') or 'default')
credential_file = session.get_config_variable('credentials_file')
config_file = session.get_config_variable('config_file')
metadata_timeout = session.get_config_variable('metadata_service_timeout')
num_attempts = session.get_config_variable('metadata_service_num_attempts')
env_provider = EnvProvider()
providers = [env_provider, AssumeRoleProvider(load_config=(lambda : session.full_config), client_creator=session.create_client, cache={}, profile_name=profile_name), SharedCredentialProvider(creds_filename=credential_file, profile_name=profile_name), ConfigProvider(config_filename=config_file, profile_name=profile_name), OriginalEC2Provider(), BotoProvider(), ContainerProvider(), InstanceMetadataProvider(iam_role_fetcher=InstanceMetadataFetcher(timeout=metadata_timeout, num_attempts=num_attempts))]
explicit_profile = session.get_config_variable('profile', methods=('instance',))
if (explicit_profile is not None):
providers.remove(env_provider)
logger.debug('Skipping environment variable credential check because profile name was explicitly set.')
resolver = CredentialResolver(providers=providers)
return resolver
|
null | null | null | What does a view decorator enforce ?
| def ssl_required(view_func):
@wraps(view_func)
def _checkssl(request, *args, **kwargs):
if (settings.SESSION_COOKIE_SECURE and (not request.is_secure())):
url_str = request.build_absolute_uri()
url_str = url_str.replace('http://', 'https://')
return http.HttpResponseRedirect(url_str)
return view_func(request, *args, **kwargs)
return _checkssl
| null | null | null | https
| codeqa | def ssl required view func @wraps view func def checkssl request *args **kwargs if settings SESSION COOKIE SECURE and not request is secure url str request build absolute uri url str url str replace 'http //' 'https //' return http Http Response Redirect url str return view func request *args **kwargs return checkssl
| null | null | null | null | Question:
What does a view decorator enforce ?
Code:
def ssl_required(view_func):
@wraps(view_func)
def _checkssl(request, *args, **kwargs):
if (settings.SESSION_COOKIE_SECURE and (not request.is_secure())):
url_str = request.build_absolute_uri()
url_str = url_str.replace('http://', 'https://')
return http.HttpResponseRedirect(url_str)
return view_func(request, *args, **kwargs)
return _checkssl
|
null | null | null | What does the code remove ?
| @pytest.fixture
def remove_fake_project_dir(request):
def fin_remove_fake_project_dir():
if os.path.isdir('fake-project'):
utils.rmtree('fake-project')
request.addfinalizer(fin_remove_fake_project_dir)
| null | null | null | the fake project directory created during the tests
| codeqa | @pytest fixturedef remove fake project dir request def fin remove fake project dir if os path isdir 'fake-project' utils rmtree 'fake-project' request addfinalizer fin remove fake project dir
| null | null | null | null | Question:
What does the code remove ?
Code:
@pytest.fixture
def remove_fake_project_dir(request):
def fin_remove_fake_project_dir():
if os.path.isdir('fake-project'):
utils.rmtree('fake-project')
request.addfinalizer(fin_remove_fake_project_dir)
|
null | null | null | When did the fake project directory create ?
| @pytest.fixture
def remove_fake_project_dir(request):
def fin_remove_fake_project_dir():
if os.path.isdir('fake-project'):
utils.rmtree('fake-project')
request.addfinalizer(fin_remove_fake_project_dir)
| null | null | null | during the tests
| codeqa | @pytest fixturedef remove fake project dir request def fin remove fake project dir if os path isdir 'fake-project' utils rmtree 'fake-project' request addfinalizer fin remove fake project dir
| null | null | null | null | Question:
When did the fake project directory create ?
Code:
@pytest.fixture
def remove_fake_project_dir(request):
def fin_remove_fake_project_dir():
if os.path.isdir('fake-project'):
utils.rmtree('fake-project')
request.addfinalizer(fin_remove_fake_project_dir)
|
null | null | null | What is defining at some point in the change log ?
| def clean_dependency_relationships(trans, metadata_dict, tool_shed_repository, tool_shed_url):
for rrda in tool_shed_repository.required_repositories:
rd = rrda.repository_dependency
r = rd.repository
if can_eliminate_repository_dependency(metadata_dict, tool_shed_url, r.name, r.owner):
message = 'Repository dependency %s by owner %s is not required by repository %s, owner %s, '
message += 'removing from list of repository dependencies.'
log.debug((message % (r.name, r.owner, tool_shed_repository.name, tool_shed_repository.owner)))
trans.install_model.context.delete(rrda)
trans.install_model.context.flush()
for td in tool_shed_repository.tool_dependencies:
if can_eliminate_tool_dependency(metadata_dict, td.name, td.type, td.version):
message = 'Tool dependency %s, version %s is not required by repository %s, owner %s, '
message += 'removing from list of tool dependencies.'
log.debug((message % (td.name, td.version, tool_shed_repository.name, tool_shed_repository.owner)))
trans.install_model.context.delete(td)
trans.install_model.context.flush()
| null | null | null | a package dependency
| codeqa | def clean dependency relationships trans metadata dict tool shed repository tool shed url for rrda in tool shed repository required repositories rd rrda repository dependencyr rd repositoryif can eliminate repository dependency metadata dict tool shed url r name r owner message ' Repositorydependency%sbyowner%sisnotrequiredbyrepository%s owner%s 'message + 'removingfromlistofrepositorydependencies 'log debug message % r name r owner tool shed repository name tool shed repository owner trans install model context delete rrda trans install model context flush for td in tool shed repository tool dependencies if can eliminate tool dependency metadata dict td name td type td version message ' Tooldependency%s version%sisnotrequiredbyrepository%s owner%s 'message + 'removingfromlistoftooldependencies 'log debug message % td name td version tool shed repository name tool shed repository owner trans install model context delete td trans install model context flush
| null | null | null | null | Question:
What is defining at some point in the change log ?
Code:
def clean_dependency_relationships(trans, metadata_dict, tool_shed_repository, tool_shed_url):
for rrda in tool_shed_repository.required_repositories:
rd = rrda.repository_dependency
r = rd.repository
if can_eliminate_repository_dependency(metadata_dict, tool_shed_url, r.name, r.owner):
message = 'Repository dependency %s by owner %s is not required by repository %s, owner %s, '
message += 'removing from list of repository dependencies.'
log.debug((message % (r.name, r.owner, tool_shed_repository.name, tool_shed_repository.owner)))
trans.install_model.context.delete(rrda)
trans.install_model.context.flush()
for td in tool_shed_repository.tool_dependencies:
if can_eliminate_tool_dependency(metadata_dict, td.name, td.type, td.version):
message = 'Tool dependency %s, version %s is not required by repository %s, owner %s, '
message += 'removing from list of tool dependencies.'
log.debug((message % (td.name, td.version, tool_shed_repository.name, tool_shed_repository.owner)))
trans.install_model.context.delete(td)
trans.install_model.context.flush()
|
null | null | null | Where do a package dependency define ?
| def clean_dependency_relationships(trans, metadata_dict, tool_shed_repository, tool_shed_url):
for rrda in tool_shed_repository.required_repositories:
rd = rrda.repository_dependency
r = rd.repository
if can_eliminate_repository_dependency(metadata_dict, tool_shed_url, r.name, r.owner):
message = 'Repository dependency %s by owner %s is not required by repository %s, owner %s, '
message += 'removing from list of repository dependencies.'
log.debug((message % (r.name, r.owner, tool_shed_repository.name, tool_shed_repository.owner)))
trans.install_model.context.delete(rrda)
trans.install_model.context.flush()
for td in tool_shed_repository.tool_dependencies:
if can_eliminate_tool_dependency(metadata_dict, td.name, td.type, td.version):
message = 'Tool dependency %s, version %s is not required by repository %s, owner %s, '
message += 'removing from list of tool dependencies.'
log.debug((message % (td.name, td.version, tool_shed_repository.name, tool_shed_repository.owner)))
trans.install_model.context.delete(td)
trans.install_model.context.flush()
| null | null | null | at some point in the change log
| codeqa | def clean dependency relationships trans metadata dict tool shed repository tool shed url for rrda in tool shed repository required repositories rd rrda repository dependencyr rd repositoryif can eliminate repository dependency metadata dict tool shed url r name r owner message ' Repositorydependency%sbyowner%sisnotrequiredbyrepository%s owner%s 'message + 'removingfromlistofrepositorydependencies 'log debug message % r name r owner tool shed repository name tool shed repository owner trans install model context delete rrda trans install model context flush for td in tool shed repository tool dependencies if can eliminate tool dependency metadata dict td name td type td version message ' Tooldependency%s version%sisnotrequiredbyrepository%s owner%s 'message + 'removingfromlistoftooldependencies 'log debug message % td name td version tool shed repository name tool shed repository owner trans install model context delete td trans install model context flush
| null | null | null | null | Question:
Where do a package dependency define ?
Code:
def clean_dependency_relationships(trans, metadata_dict, tool_shed_repository, tool_shed_url):
for rrda in tool_shed_repository.required_repositories:
rd = rrda.repository_dependency
r = rd.repository
if can_eliminate_repository_dependency(metadata_dict, tool_shed_url, r.name, r.owner):
message = 'Repository dependency %s by owner %s is not required by repository %s, owner %s, '
message += 'removing from list of repository dependencies.'
log.debug((message % (r.name, r.owner, tool_shed_repository.name, tool_shed_repository.owner)))
trans.install_model.context.delete(rrda)
trans.install_model.context.flush()
for td in tool_shed_repository.tool_dependencies:
if can_eliminate_tool_dependency(metadata_dict, td.name, td.type, td.version):
message = 'Tool dependency %s, version %s is not required by repository %s, owner %s, '
message += 'removing from list of tool dependencies.'
log.debug((message % (td.name, td.version, tool_shed_repository.name, tool_shed_repository.owner)))
trans.install_model.context.delete(td)
trans.install_model.context.flush()
|
null | null | null | What did the code give ?
| def static(path):
return StaticNode.handle_simple(path)
| null | null | null | a relative path to a static asset
| codeqa | def static path return Static Node handle simple path
| null | null | null | null | Question:
What did the code give ?
Code:
def static(path):
return StaticNode.handle_simple(path)
|
null | null | null | What does the code emit without formatting ?
| def _EmitLineUnformatted(state):
prev_lineno = None
while state.next_token:
previous_token = state.next_token.previous_token
previous_lineno = previous_token.lineno
if previous_token.is_multiline_string:
previous_lineno += previous_token.value.count(u'\n')
if previous_token.is_continuation:
newline = False
else:
newline = ((prev_lineno is not None) and (state.next_token.lineno > previous_lineno))
prev_lineno = state.next_token.lineno
state.AddTokenToState(newline=newline, dry_run=False)
| null | null | null | the line
| codeqa | def Emit Line Unformatted state prev lineno Nonewhile state next token previous token state next token previous tokenprevious lineno previous token linenoif previous token is multiline string previous lineno + previous token value count u'\n' if previous token is continuation newline Falseelse newline prev lineno is not None and state next token lineno > previous lineno prev lineno state next token linenostate Add Token To State newline newline dry run False
| null | null | null | null | Question:
What does the code emit without formatting ?
Code:
def _EmitLineUnformatted(state):
prev_lineno = None
while state.next_token:
previous_token = state.next_token.previous_token
previous_lineno = previous_token.lineno
if previous_token.is_multiline_string:
previous_lineno += previous_token.value.count(u'\n')
if previous_token.is_continuation:
newline = False
else:
newline = ((prev_lineno is not None) and (state.next_token.lineno > previous_lineno))
prev_lineno = state.next_token.lineno
state.AddTokenToState(newline=newline, dry_run=False)
|
null | null | null | How does the code emit the line ?
| def _EmitLineUnformatted(state):
prev_lineno = None
while state.next_token:
previous_token = state.next_token.previous_token
previous_lineno = previous_token.lineno
if previous_token.is_multiline_string:
previous_lineno += previous_token.value.count(u'\n')
if previous_token.is_continuation:
newline = False
else:
newline = ((prev_lineno is not None) and (state.next_token.lineno > previous_lineno))
prev_lineno = state.next_token.lineno
state.AddTokenToState(newline=newline, dry_run=False)
| null | null | null | without formatting
| codeqa | def Emit Line Unformatted state prev lineno Nonewhile state next token previous token state next token previous tokenprevious lineno previous token linenoif previous token is multiline string previous lineno + previous token value count u'\n' if previous token is continuation newline Falseelse newline prev lineno is not None and state next token lineno > previous lineno prev lineno state next token linenostate Add Token To State newline newline dry run False
| null | null | null | null | Question:
How does the code emit the line ?
Code:
def _EmitLineUnformatted(state):
prev_lineno = None
while state.next_token:
previous_token = state.next_token.previous_token
previous_lineno = previous_token.lineno
if previous_token.is_multiline_string:
previous_lineno += previous_token.value.count(u'\n')
if previous_token.is_continuation:
newline = False
else:
newline = ((prev_lineno is not None) and (state.next_token.lineno > previous_lineno))
prev_lineno = state.next_token.lineno
state.AddTokenToState(newline=newline, dry_run=False)
|
null | null | null | How do the contents of the blog filter ?
| def do_filter(parser, token):
(_, rest) = token.contents.split(None, 1)
filter_expr = parser.compile_filter(('var|%s' % rest))
nodelist = parser.parse(('endfilter',))
parser.delete_first_token()
return FilterNode(filter_expr, nodelist)
| null | null | null | through variable filters
| codeqa | def do filter parser token rest token contents split None 1 filter expr parser compile filter 'var %s' % rest nodelist parser parse 'endfilter' parser delete first token return Filter Node filter expr nodelist
| null | null | null | null | Question:
How do the contents of the blog filter ?
Code:
def do_filter(parser, token):
(_, rest) = token.contents.split(None, 1)
filter_expr = parser.compile_filter(('var|%s' % rest))
nodelist = parser.parse(('endfilter',))
parser.delete_first_token()
return FilterNode(filter_expr, nodelist)
|
null | null | null | What does the code compute ?
| def skeletonize_3d(img):
if ((img.ndim < 2) or (img.ndim > 3)):
raise ValueError(('skeletonize_3d can only handle 2D or 3D images; got img.ndim = %s instead.' % img.ndim))
img = np.ascontiguousarray(img)
img = img_as_ubyte(img, force_copy=False)
img_o = img
if (img.ndim == 2):
img_o = img[np.newaxis, ...]
img_o = np.pad(img_o, pad_width=1, mode='constant')
maxval = img_o.max()
img_o[(img_o != 0)] = 1
img_o = np.asarray(_compute_thin_image(img_o))
img_o = crop(img_o, crop_width=1)
if (img.ndim == 2):
img_o = img_o[0]
img_o *= maxval
return img_o
| null | null | null | the skeleton of a binary image
| codeqa | def skeletonize 3d img if img ndim < 2 or img ndim > 3 raise Value Error 'skeletonize 3dcanonlyhandle 2 Dor 3 Dimages gotimg ndim %sinstead ' % img ndim img np ascontiguousarray img img img as ubyte img force copy False img o imgif img ndim 2 img o img[np newaxis ]img o np pad img o pad width 1 mode 'constant' maxval img o max img o[ img o 0 ] 1img o np asarray compute thin image img o img o crop img o crop width 1 if img ndim 2 img o img o[ 0 ]img o * maxvalreturn img o
| null | null | null | null | Question:
What does the code compute ?
Code:
def skeletonize_3d(img):
if ((img.ndim < 2) or (img.ndim > 3)):
raise ValueError(('skeletonize_3d can only handle 2D or 3D images; got img.ndim = %s instead.' % img.ndim))
img = np.ascontiguousarray(img)
img = img_as_ubyte(img, force_copy=False)
img_o = img
if (img.ndim == 2):
img_o = img[np.newaxis, ...]
img_o = np.pad(img_o, pad_width=1, mode='constant')
maxval = img_o.max()
img_o[(img_o != 0)] = 1
img_o = np.asarray(_compute_thin_image(img_o))
img_o = crop(img_o, crop_width=1)
if (img.ndim == 2):
img_o = img_o[0]
img_o *= maxval
return img_o
|
null | null | null | What mapped to the on ?
| @require_context
def mapped_array(shape, dtype=np.float, strides=None, order='C', stream=0, portable=False, wc=False):
(shape, strides, dtype) = _prepare_shape_strides_dtype(shape, strides, dtype, order)
bytesize = driver.memory_size_from_info(shape, strides, dtype.itemsize)
buffer = current_context().memhostalloc(bytesize, mapped=True)
npary = np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, buffer=buffer)
mappedview = np.ndarray.view(npary, type=devicearray.MappedNDArray)
mappedview.device_setup(buffer, stream=stream)
return mappedview
| null | null | null | a buffer
| codeqa | @require contextdef mapped array shape dtype np float strides None order 'C' stream 0 portable False wc False shape strides dtype prepare shape strides dtype shape strides dtype order bytesize driver memory size from info shape strides dtype itemsize buffer current context memhostalloc bytesize mapped True npary np ndarray shape shape strides strides dtype dtype order order buffer buffer mappedview np ndarray view npary type devicearray Mapped ND Array mappedview device setup buffer stream stream return mappedview
| null | null | null | null | Question:
What mapped to the on ?
Code:
@require_context
def mapped_array(shape, dtype=np.float, strides=None, order='C', stream=0, portable=False, wc=False):
(shape, strides, dtype) = _prepare_shape_strides_dtype(shape, strides, dtype, order)
bytesize = driver.memory_size_from_info(shape, strides, dtype.itemsize)
buffer = current_context().memhostalloc(bytesize, mapped=True)
npary = np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, buffer=buffer)
mappedview = np.ndarray.view(npary, type=devicearray.MappedNDArray)
mappedview.device_setup(buffer, stream=stream)
return mappedview
|
null | null | null | Where did a buffer map to the ?
| @require_context
def mapped_array(shape, dtype=np.float, strides=None, order='C', stream=0, portable=False, wc=False):
(shape, strides, dtype) = _prepare_shape_strides_dtype(shape, strides, dtype, order)
bytesize = driver.memory_size_from_info(shape, strides, dtype.itemsize)
buffer = current_context().memhostalloc(bytesize, mapped=True)
npary = np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, buffer=buffer)
mappedview = np.ndarray.view(npary, type=devicearray.MappedNDArray)
mappedview.device_setup(buffer, stream=stream)
return mappedview
| null | null | null | on
| codeqa | @require contextdef mapped array shape dtype np float strides None order 'C' stream 0 portable False wc False shape strides dtype prepare shape strides dtype shape strides dtype order bytesize driver memory size from info shape strides dtype itemsize buffer current context memhostalloc bytesize mapped True npary np ndarray shape shape strides strides dtype dtype order order buffer buffer mappedview np ndarray view npary type devicearray Mapped ND Array mappedview device setup buffer stream stream return mappedview
| null | null | null | null | Question:
Where did a buffer map to the ?
Code:
@require_context
def mapped_array(shape, dtype=np.float, strides=None, order='C', stream=0, portable=False, wc=False):
(shape, strides, dtype) = _prepare_shape_strides_dtype(shape, strides, dtype, order)
bytesize = driver.memory_size_from_info(shape, strides, dtype.itemsize)
buffer = current_context().memhostalloc(bytesize, mapped=True)
npary = np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, buffer=buffer)
mappedview = np.ndarray.view(npary, type=devicearray.MappedNDArray)
mappedview.device_setup(buffer, stream=stream)
return mappedview
|
null | null | null | What does the code remove ?
| @register_useless
@register_canonicalize
@register_specialize
@gof.local_optimizer([Subtensor])
def local_useless_slice(node):
if isinstance(node.op, Subtensor):
slices = get_idx_list(node.inputs, node.op.idx_list)
last_slice = len(slices)
for s in slices[::(-1)]:
if (isinstance(s, slice) and (s.start is None) and (s.stop is None) and ((s.step is None) or (T.extract_constant(s.step, only_process_constants=True) == 1))):
last_slice -= 1
else:
break
if (last_slice < len(slices)):
subtens = Subtensor(slices[:last_slice])
sl_ins = Subtensor.collapse(slices[:last_slice], (lambda x: isinstance(x, T.Variable)))
out = subtens(node.inputs[0], *sl_ins)
copy_stack_trace(node.outputs, out)
return [out]
| null | null | null | subtensor of the form x[0
| codeqa | @register useless@register canonicalize@register specialize@gof local optimizer [ Subtensor] def local useless slice node if isinstance node op Subtensor slices get idx list node inputs node op idx list last slice len slices for s in slices[ -1 ] if isinstance s slice and s start is None and s stop is None and s step is None or T extract constant s step only process constants True 1 last slice - 1else breakif last slice < len slices subtens Subtensor slices[ last slice] sl ins Subtensor collapse slices[ last slice] lambda x isinstance x T Variable out subtens node inputs[ 0 ] *sl ins copy stack trace node outputs out return [out]
| null | null | null | null | Question:
What does the code remove ?
Code:
@register_useless
@register_canonicalize
@register_specialize
@gof.local_optimizer([Subtensor])
def local_useless_slice(node):
if isinstance(node.op, Subtensor):
slices = get_idx_list(node.inputs, node.op.idx_list)
last_slice = len(slices)
for s in slices[::(-1)]:
if (isinstance(s, slice) and (s.start is None) and (s.stop is None) and ((s.step is None) or (T.extract_constant(s.step, only_process_constants=True) == 1))):
last_slice -= 1
else:
break
if (last_slice < len(slices)):
subtens = Subtensor(slices[:last_slice])
sl_ins = Subtensor.collapse(slices[:last_slice], (lambda x: isinstance(x, T.Variable)))
out = subtens(node.inputs[0], *sl_ins)
copy_stack_trace(node.outputs, out)
return [out]
|
null | null | null | What does the code strip ?
| def strip(path, count):
path = '/'.join(path.split(os.sep))
return path.split('/', count)[(-1)]
| null | null | null | the count first slash of the path
| codeqa | def strip path count path '/' join path split os sep return path split '/' count [ -1 ]
| null | null | null | null | Question:
What does the code strip ?
Code:
def strip(path, count):
path = '/'.join(path.split(os.sep))
return path.split('/', count)[(-1)]
|
null | null | null | What does the code invalidate ?
| @receiver(models.signals.post_save, sender=SkippedReverification)
@receiver(models.signals.post_delete, sender=SkippedReverification)
def invalidate_skipped_verification_cache(sender, instance, **kwargs):
cache_key = SkippedReverification.cache_key_name(instance.user.id, unicode(instance.course_id))
cache.delete(cache_key)
| null | null | null | the cache of skipped verification model
| codeqa | @receiver models signals post save sender Skipped Reverification @receiver models signals post delete sender Skipped Reverification def invalidate skipped verification cache sender instance **kwargs cache key Skipped Reverification cache key name instance user id unicode instance course id cache delete cache key
| null | null | null | null | Question:
What does the code invalidate ?
Code:
@receiver(models.signals.post_save, sender=SkippedReverification)
@receiver(models.signals.post_delete, sender=SkippedReverification)
def invalidate_skipped_verification_cache(sender, instance, **kwargs):
cache_key = SkippedReverification.cache_key_name(instance.user.id, unicode(instance.course_id))
cache.delete(cache_key)
|
null | null | null | How did elements distribute ?
| def shared_normal(num_rows, num_cols, scale=1):
return theano.shared(numpy.random.normal(scale=scale, size=(num_rows, num_cols)).astype(theano.config.floatX))
| null | null | null | normally
| codeqa | def shared normal num rows num cols scale 1 return theano shared numpy random normal scale scale size num rows num cols astype theano config float X
| null | null | null | null | Question:
How did elements distribute ?
Code:
def shared_normal(num_rows, num_cols, scale=1):
return theano.shared(numpy.random.normal(scale=scale, size=(num_rows, num_cols)).astype(theano.config.floatX))
|
null | null | null | What does the code initialize with normally distributed elements ?
| def shared_normal(num_rows, num_cols, scale=1):
return theano.shared(numpy.random.normal(scale=scale, size=(num_rows, num_cols)).astype(theano.config.floatX))
| null | null | null | a matrix shared variable
| codeqa | def shared normal num rows num cols scale 1 return theano shared numpy random normal scale scale size num rows num cols astype theano config float X
| null | null | null | null | Question:
What does the code initialize with normally distributed elements ?
Code:
def shared_normal(num_rows, num_cols, scale=1):
return theano.shared(numpy.random.normal(scale=scale, size=(num_rows, num_cols)).astype(theano.config.floatX))
|
null | null | null | How does the code initialize a matrix shared variable ?
| def shared_normal(num_rows, num_cols, scale=1):
return theano.shared(numpy.random.normal(scale=scale, size=(num_rows, num_cols)).astype(theano.config.floatX))
| null | null | null | with normally distributed elements
| codeqa | def shared normal num rows num cols scale 1 return theano shared numpy random normal scale scale size num rows num cols astype theano config float X
| null | null | null | null | Question:
How does the code initialize a matrix shared variable ?
Code:
def shared_normal(num_rows, num_cols, scale=1):
return theano.shared(numpy.random.normal(scale=scale, size=(num_rows, num_cols)).astype(theano.config.floatX))
|
null | null | null | What does the code make ?
| def multicall(conf, context, topic, msg, timeout=None):
return rpc_amqp.multicall(conf, context, topic, msg, timeout, rpc_amqp.get_connection_pool(conf, Connection))
| null | null | null | a call that returns multiple times
| codeqa | def multicall conf context topic msg timeout None return rpc amqp multicall conf context topic msg timeout rpc amqp get connection pool conf Connection
| null | null | null | null | Question:
What does the code make ?
Code:
def multicall(conf, context, topic, msg, timeout=None):
return rpc_amqp.multicall(conf, context, topic, msg, timeout, rpc_amqp.get_connection_pool(conf, Connection))
|
null | null | null | When does a call return ?
| def multicall(conf, context, topic, msg, timeout=None):
return rpc_amqp.multicall(conf, context, topic, msg, timeout, rpc_amqp.get_connection_pool(conf, Connection))
| null | null | null | multiple times
| codeqa | def multicall conf context topic msg timeout None return rpc amqp multicall conf context topic msg timeout rpc amqp get connection pool conf Connection
| null | null | null | null | Question:
When does a call return ?
Code:
def multicall(conf, context, topic, msg, timeout=None):
return rpc_amqp.multicall(conf, context, topic, msg, timeout, rpc_amqp.get_connection_pool(conf, Connection))
|
null | null | null | When do hash return ?
| def gen_query_hash(sql):
sql = COMMENTS_REGEX.sub('', sql)
sql = ''.join(sql.split()).lower()
return hashlib.md5(sql.encode('utf-8')).hexdigest()
| null | null | null | after stripping all comments
| codeqa | def gen query hash sql sql COMMENTS REGEX sub '' sql sql '' join sql split lower return hashlib md 5 sql encode 'utf- 8 ' hexdigest
| null | null | null | null | Question:
When do hash return ?
Code:
def gen_query_hash(sql):
sql = COMMENTS_REGEX.sub('', sql)
sql = ''.join(sql.split()).lower()
return hashlib.md5(sql.encode('utf-8')).hexdigest()
|
null | null | null | What does the code call ?
| def prepare_class(name, bases=(), kwds=None):
if (kwds is None):
kwds = {}
else:
kwds = dict(kwds)
if ('metaclass' in kwds):
meta = kwds.pop('metaclass')
elif bases:
meta = type(bases[0])
else:
meta = type
if isinstance(meta, type):
meta = _calculate_meta(meta, bases)
if hasattr(meta, '__prepare__'):
ns = meta.__prepare__(name, bases, **kwds)
else:
ns = {}
return (meta, ns, kwds)
| null | null | null | the _ _ prepare _ _ method of the appropriate metaclass
| codeqa | def prepare class name bases kwds None if kwds is None kwds {}else kwds dict kwds if 'metaclass' in kwds meta kwds pop 'metaclass' elif bases meta type bases[ 0 ] else meta typeif isinstance meta type meta calculate meta meta bases if hasattr meta ' prepare ' ns meta prepare name bases **kwds else ns {}return meta ns kwds
| null | null | null | null | Question:
What does the code call ?
Code:
def prepare_class(name, bases=(), kwds=None):
if (kwds is None):
kwds = {}
else:
kwds = dict(kwds)
if ('metaclass' in kwds):
meta = kwds.pop('metaclass')
elif bases:
meta = type(bases[0])
else:
meta = type
if isinstance(meta, type):
meta = _calculate_meta(meta, bases)
if hasattr(meta, '__prepare__'):
ns = meta.__prepare__(name, bases, **kwds)
else:
ns = {}
return (meta, ns, kwds)
|
null | null | null | What does the code turn into a device name ?
| def device(portnum):
return ('COM%d' % (portnum + 1))
| null | null | null | a port number
| codeqa | def device portnum return 'COM%d' % portnum + 1
| null | null | null | null | Question:
What does the code turn into a device name ?
Code:
def device(portnum):
return ('COM%d' % (portnum + 1))
|
null | null | null | What does the code get ?
| def listMediaFiles(path):
if ((not dir) or (not ek(os.path.isdir, path))):
return []
files = []
for curFile in ek(os.listdir, path):
fullCurFile = ek(os.path.join, path, curFile)
if (ek(os.path.isdir, fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
| null | null | null | a list of files possibly containing media in a path
| codeqa | def list Media Files path if not dir or not ek os path isdir path return []files []for cur File in ek os listdir path full Cur File ek os path join path cur File if ek os path isdir full Cur File and not cur File startswith u' ' and not cur File u' Extras' files + list Media Files full Cur File elif is Media File cur File files append full Cur File return files
| null | null | null | null | Question:
What does the code get ?
Code:
def listMediaFiles(path):
if ((not dir) or (not ek(os.path.isdir, path))):
return []
files = []
for curFile in ek(os.listdir, path):
fullCurFile = ek(os.path.join, path, curFile)
if (ek(os.path.isdir, fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
|
null | null | null | What is containing media in a path ?
| def listMediaFiles(path):
if ((not dir) or (not ek(os.path.isdir, path))):
return []
files = []
for curFile in ek(os.listdir, path):
fullCurFile = ek(os.path.join, path, curFile)
if (ek(os.path.isdir, fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
| null | null | null | files
| codeqa | def list Media Files path if not dir or not ek os path isdir path return []files []for cur File in ek os listdir path full Cur File ek os path join path cur File if ek os path isdir full Cur File and not cur File startswith u' ' and not cur File u' Extras' files + list Media Files full Cur File elif is Media File cur File files append full Cur File return files
| null | null | null | null | Question:
What is containing media in a path ?
Code:
def listMediaFiles(path):
if ((not dir) or (not ek(os.path.isdir, path))):
return []
files = []
for curFile in ek(os.listdir, path):
fullCurFile = ek(os.path.join, path, curFile)
if (ek(os.path.isdir, fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
|
null | null | null | What is containing media possibly in a path ?
| def listMediaFiles(path):
if ((not dir) or (not ek(os.path.isdir, path))):
return []
files = []
for curFile in ek(os.listdir, path):
fullCurFile = ek(os.path.join, path, curFile)
if (ek(os.path.isdir, fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
| null | null | null | files
| codeqa | def list Media Files path if not dir or not ek os path isdir path return []files []for cur File in ek os listdir path full Cur File ek os path join path cur File if ek os path isdir full Cur File and not cur File startswith u' ' and not cur File u' Extras' files + list Media Files full Cur File elif is Media File cur File files append full Cur File return files
| null | null | null | null | Question:
What is containing media possibly in a path ?
Code:
def listMediaFiles(path):
if ((not dir) or (not ek(os.path.isdir, path))):
return []
files = []
for curFile in ek(os.listdir, path):
fullCurFile = ek(os.path.join, path, curFile)
if (ek(os.path.isdir, fullCurFile) and (not curFile.startswith(u'.')) and (not (curFile == u'Extras'))):
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
|
null | null | null | What does the code get ?
| def getUniqueToken(word):
uniqueString = '@#!'
for character in uniqueString:
if (character not in word):
return character
uniqueNumber = 0
while True:
for character in uniqueString:
uniqueToken = (character + str(uniqueNumber))
if (uniqueToken not in word):
return uniqueToken
uniqueNumber += 1
| null | null | null | unique token
| codeqa | def get Unique Token word unique String '@# 'for character in unique String if character not in word return characterunique Number 0while True for character in unique String unique Token character + str unique Number if unique Token not in word return unique Tokenunique Number + 1
| null | null | null | null | Question:
What does the code get ?
Code:
def getUniqueToken(word):
uniqueString = '@#!'
for character in uniqueString:
if (character not in word):
return character
uniqueNumber = 0
while True:
for character in uniqueString:
uniqueToken = (character + str(uniqueNumber))
if (uniqueToken not in word):
return uniqueToken
uniqueNumber += 1
|
null | null | null | What does the code get out of the string ?
| def getMP(data, count=1):
mp = []
c = 0
for i in range(count):
(length,) = struct.unpack('>L', data[c:(c + 4)])
mp.append(Util.number.bytes_to_long(data[(c + 4):((c + 4) + length)]))
c += (4 + length)
return (tuple(mp) + (data[c:],))
| null | null | null | multiple precision integer
| codeqa | def get MP data count 1 mp []c 0for i in range count length struct unpack '>L' data[c c + 4 ] mp append Util number bytes to long data[ c + 4 c + 4 + length ] c + 4 + length return tuple mp + data[c ]
| null | null | null | null | Question:
What does the code get out of the string ?
Code:
def getMP(data, count=1):
mp = []
c = 0
for i in range(count):
(length,) = struct.unpack('>L', data[c:(c + 4)])
mp.append(Util.number.bytes_to_long(data[(c + 4):((c + 4) + length)]))
c += (4 + length)
return (tuple(mp) + (data[c:],))
|
null | null | null | What does the code get ?
| def getFilePaths(fileInDirectory=''):
directoryName = os.getcwd()
if (fileInDirectory != ''):
directoryName = os.path.dirname(fileInDirectory)
return getFilePathsByDirectory(directoryName)
| null | null | null | the file paths in the directory of the file in directory
| codeqa | def get File Paths file In Directory '' directory Name os getcwd if file In Directory '' directory Name os path dirname file In Directory return get File Paths By Directory directory Name
| null | null | null | null | Question:
What does the code get ?
Code:
def getFilePaths(fileInDirectory=''):
directoryName = os.getcwd()
if (fileInDirectory != ''):
directoryName = os.path.dirname(fileInDirectory)
return getFilePathsByDirectory(directoryName)
|
null | null | null | What does the code load ?
| def load_signatures(filename, cache=True):
global SIGNATURE_CACHE
f = open(filename, 'r')
sigjson = f.read()
f.close()
sigdata = simplejson.loads(sigjson)
if cache:
SIGNATURE_CACHE = sigdata
| null | null | null | the import signatures for distros
| codeqa | def load signatures filename cache True global SIGNATURE CACH Ef open filename 'r' sigjson f read f close sigdata simplejson loads sigjson if cache SIGNATURE CACHE sigdata
| null | null | null | null | Question:
What does the code load ?
Code:
def load_signatures(filename, cache=True):
global SIGNATURE_CACHE
f = open(filename, 'r')
sigjson = f.read()
f.close()
sigdata = simplejson.loads(sigjson)
if cache:
SIGNATURE_CACHE = sigdata
|
null | null | null | What should accept any default options here ?
| def handle_default_options(options):
if options.settings:
os.environ[u'DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
| null | null | null | all commands
| codeqa | def handle default options options if options settings os environ[u'DJANGO SETTINGS MODULE'] options settingsif options pythonpath sys path insert 0 options pythonpath
| null | null | null | null | Question:
What should accept any default options here ?
Code:
def handle_default_options(options):
if options.settings:
os.environ[u'DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
|
null | null | null | Who can handle them before searching for user commands ?
| def handle_default_options(options):
if options.settings:
os.environ[u'DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
| null | null | null | managementutility
| codeqa | def handle default options options if options settings os environ[u'DJANGO SETTINGS MODULE'] options settingsif options pythonpath sys path insert 0 options pythonpath
| null | null | null | null | Question:
Who can handle them before searching for user commands ?
Code:
def handle_default_options(options):
if options.settings:
os.environ[u'DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
|
null | null | null | Who d to lookup config configuration name the job ?
| def undo_jid(jid, config='root'):
(pre_snapshot, post_snapshot) = _get_jid_snapshots(jid, config=config)
return undo(config, num_pre=pre_snapshot, num_post=post_snapshot)
| null | null | null | i
| codeqa | def undo jid jid config 'root' pre snapshot post snapshot get jid snapshots jid config config return undo config num pre pre snapshot num post post snapshot
| null | null | null | null | Question:
Who d to lookup config configuration name the job ?
Code:
def undo_jid(jid, config='root'):
(pre_snapshot, post_snapshot) = _get_jid_snapshots(jid, config=config)
return undo(config, num_pre=pre_snapshot, num_post=post_snapshot)
|
null | null | null | What is enabled on the server ?
| def status():
out = int(_psrdp('echo $RDP.AllowTSConnections').strip())
return (out != 0)
| null | null | null | rdp
| codeqa | def status out int psrdp 'echo$RDP Allow TS Connections' strip return out 0
| null | null | null | null | Question:
What is enabled on the server ?
Code:
def status():
out = int(_psrdp('echo $RDP.AllowTSConnections').strip())
return (out != 0)
|
null | null | null | What does the code find ?
| def shortest_hops(gr, s):
if (not gr.has_node(s)):
raise Exception(('Node %s is not in graph' % s))
else:
dist = {}
q = deque([s])
nodes_explored = set([s])
for n in gr.nodes():
if (n == s):
dist[n] = 0
else:
dist[n] = float('inf')
while (len(q) != 0):
node = q.popleft()
for each in gr.neighbors(node):
if (each not in nodes_explored):
nodes_explored.add(each)
q.append(each)
dist[each] = (dist[node] + 1)
return dist
| null | null | null | the shortest number of hops required to reach a node from s
| codeqa | def shortest hops gr s if not gr has node s raise Exception ' Node%sisnotingraph' % s else dist {}q deque [s] nodes explored set [s] for n in gr nodes if n s dist[n] 0else dist[n] float 'inf' while len q 0 node q popleft for each in gr neighbors node if each not in nodes explored nodes explored add each q append each dist[each] dist[node] + 1 return dist
| null | null | null | null | Question:
What does the code find ?
Code:
def shortest_hops(gr, s):
if (not gr.has_node(s)):
raise Exception(('Node %s is not in graph' % s))
else:
dist = {}
q = deque([s])
nodes_explored = set([s])
for n in gr.nodes():
if (n == s):
dist[n] = 0
else:
dist[n] = float('inf')
while (len(q) != 0):
node = q.popleft()
for each in gr.neighbors(node):
if (each not in nodes_explored):
nodes_explored.add(each)
q.append(each)
dist[each] = (dist[node] + 1)
return dist
|
null | null | null | What causes the stored response to be returned ?
| def _match_request(http_request, stored_request):
if ((http_request.uri.host is not None) and (http_request.uri.host != stored_request.uri.host)):
return False
elif (http_request.uri.path != stored_request.uri.path):
return False
elif (http_request.method != stored_request.method):
return False
elif (('gsessionid' in http_request.uri.query) or ('gsessionid' in stored_request.uri.query)):
if ('gsessionid' not in stored_request.uri.query):
return False
elif ('gsessionid' not in http_request.uri.query):
return False
elif (http_request.uri.query['gsessionid'] != stored_request.uri.query['gsessionid']):
return False
return True
| null | null | null | a stored request
| codeqa | def match request http request stored request if http request uri host is not None and http request uri host stored request uri host return Falseelif http request uri path stored request uri path return Falseelif http request method stored request method return Falseelif 'gsessionid' in http request uri query or 'gsessionid' in stored request uri query if 'gsessionid' not in stored request uri query return Falseelif 'gsessionid' not in http request uri query return Falseelif http request uri query['gsessionid'] stored request uri query['gsessionid'] return Falsereturn True
| null | null | null | null | Question:
What causes the stored response to be returned ?
Code:
def _match_request(http_request, stored_request):
if ((http_request.uri.host is not None) and (http_request.uri.host != stored_request.uri.host)):
return False
elif (http_request.uri.path != stored_request.uri.path):
return False
elif (http_request.method != stored_request.method):
return False
elif (('gsessionid' in http_request.uri.query) or ('gsessionid' in stored_request.uri.query)):
if ('gsessionid' not in stored_request.uri.query):
return False
elif ('gsessionid' not in http_request.uri.query):
return False
elif (http_request.uri.query['gsessionid'] != stored_request.uri.query['gsessionid']):
return False
return True
|
null | null | null | What do a stored request because ?
| def _match_request(http_request, stored_request):
if ((http_request.uri.host is not None) and (http_request.uri.host != stored_request.uri.host)):
return False
elif (http_request.uri.path != stored_request.uri.path):
return False
elif (http_request.method != stored_request.method):
return False
elif (('gsessionid' in http_request.uri.query) or ('gsessionid' in stored_request.uri.query)):
if ('gsessionid' not in stored_request.uri.query):
return False
elif ('gsessionid' not in http_request.uri.query):
return False
elif (http_request.uri.query['gsessionid'] != stored_request.uri.query['gsessionid']):
return False
return True
| null | null | null | the stored response to be returned
| codeqa | def match request http request stored request if http request uri host is not None and http request uri host stored request uri host return Falseelif http request uri path stored request uri path return Falseelif http request method stored request method return Falseelif 'gsessionid' in http request uri query or 'gsessionid' in stored request uri query if 'gsessionid' not in stored request uri query return Falseelif 'gsessionid' not in http request uri query return Falseelif http request uri query['gsessionid'] stored request uri query['gsessionid'] return Falsereturn True
| null | null | null | null | Question:
What do a stored request because ?
Code:
def _match_request(http_request, stored_request):
if ((http_request.uri.host is not None) and (http_request.uri.host != stored_request.uri.host)):
return False
elif (http_request.uri.path != stored_request.uri.path):
return False
elif (http_request.method != stored_request.method):
return False
elif (('gsessionid' in http_request.uri.query) or ('gsessionid' in stored_request.uri.query)):
if ('gsessionid' not in stored_request.uri.query):
return False
elif ('gsessionid' not in http_request.uri.query):
return False
elif (http_request.uri.query['gsessionid'] != stored_request.uri.query['gsessionid']):
return False
return True
|
null | null | null | What does the code create if it already exists ?
| @utils.no_4byte_params
def metadef_tag_create(context, namespace_name, tag_dict, session=None):
session = (session or get_session())
return metadef_tag_api.create(context, namespace_name, tag_dict, session)
| null | null | null | a metadata - schema tag
| codeqa | @utils no 4byte paramsdef metadef tag create context namespace name tag dict session None session session or get session return metadef tag api create context namespace name tag dict session
| null | null | null | null | Question:
What does the code create if it already exists ?
Code:
@utils.no_4byte_params
def metadef_tag_create(context, namespace_name, tag_dict, session=None):
session = (session or get_session())
return metadef_tag_api.create(context, namespace_name, tag_dict, session)
|
null | null | null | What does the code get ?
| def _yield_all_instance_groups(emr_conn, cluster_id, *args, **kwargs):
for resp in _repeat(emr_conn.list_instance_groups, cluster_id, *args, **kwargs):
for group in getattr(resp, 'instancegroups', []):
(yield group)
| null | null | null | all instance groups for the given cluster
| codeqa | def yield all instance groups emr conn cluster id *args **kwargs for resp in repeat emr conn list instance groups cluster id *args **kwargs for group in getattr resp 'instancegroups' [] yield group
| null | null | null | null | Question:
What does the code get ?
Code:
def _yield_all_instance_groups(emr_conn, cluster_id, *args, **kwargs):
for resp in _repeat(emr_conn.list_instance_groups, cluster_id, *args, **kwargs):
for group in getattr(resp, 'instancegroups', []):
(yield group)
|
null | null | null | What does the code run ?
| def run(command):
termAddress = AE.AECreateDesc(typeApplicationBundleID, 'com.apple.Terminal')
theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress, kAutoGenerateReturnID, kAnyTransactionID)
commandDesc = AE.AECreateDesc(typeChar, command)
theEvent.AEPutParamDesc(kAECommandClass, commandDesc)
try:
theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
except AE.Error as why:
if (why[0] != (-600)):
raise
os.system(START_TERMINAL)
time.sleep(1)
theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
| null | null | null | a shell command in a new terminal
| codeqa | def run command term Address AE AE Create Desc type Application Bundle ID 'com apple Terminal' the Event AE AE Create Apple Event kAE Core Suite kAE Do Script term Address k Auto Generate Return ID k Any Transaction ID command Desc AE AE Create Desc type Char command the Event AE Put Param Desc kAE Command Class command Desc try the Event AE Send SEND MODE kAE Normal Priority kAE Default Timeout except AE Error as why if why[ 0 ] -600 raiseos system START TERMINAL time sleep 1 the Event AE Send SEND MODE kAE Normal Priority kAE Default Timeout
| null | null | null | null | Question:
What does the code run ?
Code:
def run(command):
termAddress = AE.AECreateDesc(typeApplicationBundleID, 'com.apple.Terminal')
theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress, kAutoGenerateReturnID, kAnyTransactionID)
commandDesc = AE.AECreateDesc(typeChar, command)
theEvent.AEPutParamDesc(kAECommandClass, commandDesc)
try:
theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
except AE.Error as why:
if (why[0] != (-600)):
raise
os.system(START_TERMINAL)
time.sleep(1)
theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
|
null | null | null | How is the feature structure obtained ?
| def substitute_bindings(fstruct, bindings, fs_class=u'default'):
if (fs_class == u'default'):
fs_class = _default_fs_class(fstruct)
fstruct = copy.deepcopy(fstruct)
_substitute_bindings(fstruct, bindings, fs_class, set())
return fstruct
| null | null | null | by replacing each variable bound by bindings with its binding
| codeqa | def substitute bindings fstruct bindings fs class u'default' if fs class u'default' fs class default fs class fstruct fstruct copy deepcopy fstruct substitute bindings fstruct bindings fs class set return fstruct
| null | null | null | null | Question:
How is the feature structure obtained ?
Code:
def substitute_bindings(fstruct, bindings, fs_class=u'default'):
if (fs_class == u'default'):
fs_class = _default_fs_class(fstruct)
fstruct = copy.deepcopy(fstruct)
_substitute_bindings(fstruct, bindings, fs_class, set())
return fstruct
|
null | null | null | What does the code make ?
| def _make_req(node, part, method, path, _headers, stype, conn_timeout=5, response_timeout=15):
with Timeout(conn_timeout):
conn = http_connect(node['ip'], node['port'], node['device'], part, method, path, headers=_headers)
with Timeout(response_timeout):
resp = conn.getresponse()
resp.read()
if (not is_success(resp.status)):
raise DirectClientException(stype, method, node, part, path, resp)
return resp
| null | null | null | request to backend storage node
| codeqa | def make req node part method path headers stype conn timeout 5 response timeout 15 with Timeout conn timeout conn http connect node['ip'] node['port'] node['device'] part method path headers headers with Timeout response timeout resp conn getresponse resp read if not is success resp status raise Direct Client Exception stype method node part path resp return resp
| null | null | null | null | Question:
What does the code make ?
Code:
def _make_req(node, part, method, path, _headers, stype, conn_timeout=5, response_timeout=15):
with Timeout(conn_timeout):
conn = http_connect(node['ip'], node['port'], node['device'], part, method, path, headers=_headers)
with Timeout(response_timeout):
resp = conn.getresponse()
resp.read()
if (not is_success(resp.status)):
raise DirectClientException(stype, method, node, part, path, resp)
return resp
|
null | null | null | What does the code make ?
| def _make_transform_card(fro, to, r_lpa, r_nasion, r_rpa):
diff_1 = (r_nasion - r_lpa)
ex = (r_rpa - r_lpa)
alpha = (np.dot(diff_1, ex) / np.dot(ex, ex))
ex /= np.sqrt(np.sum((ex * ex)))
trans = np.eye(4)
move = (((1.0 - alpha) * r_lpa) + (alpha * r_rpa))
trans[:3, 3] = move
trans[:3, 0] = ex
ey = (r_nasion - move)
ey /= np.sqrt(np.sum((ey * ey)))
trans[:3, 1] = ey
trans[:3, 2] = np.cross(ex, ey)
return Transform(fro, to, trans)
| null | null | null | a transform
| codeqa | def make transform card fro to r lpa r nasion r rpa diff 1 r nasion - r lpa ex r rpa - r lpa alpha np dot diff 1 ex / np dot ex ex ex / np sqrt np sum ex * ex trans np eye 4 move 1 0 - alpha * r lpa + alpha * r rpa trans[ 3 3] movetrans[ 3 0] exey r nasion - move ey / np sqrt np sum ey * ey trans[ 3 1] eytrans[ 3 2] np cross ex ey return Transform fro to trans
| null | null | null | null | Question:
What does the code make ?
Code:
def _make_transform_card(fro, to, r_lpa, r_nasion, r_rpa):
diff_1 = (r_nasion - r_lpa)
ex = (r_rpa - r_lpa)
alpha = (np.dot(diff_1, ex) / np.dot(ex, ex))
ex /= np.sqrt(np.sum((ex * ex)))
trans = np.eye(4)
move = (((1.0 - alpha) * r_lpa) + (alpha * r_rpa))
trans[:3, 3] = move
trans[:3, 0] = ex
ey = (r_nasion - move)
ey /= np.sqrt(np.sum((ey * ey)))
trans[:3, 1] = ey
trans[:3, 2] = np.cross(ex, ey)
return Transform(fro, to, trans)
|
null | null | null | When are functions executed ?
| def _run_exitfuncs():
exc_info = None
while _exithandlers:
(func, targs, kargs) = _exithandlers.pop()
try:
func(*targs, **kargs)
except SystemExit:
exc_info = sys.exc_info()
except:
import traceback
print >>sys.stderr, 'Error in atexit._run_exitfuncs:'
traceback.print_exc()
exc_info = sys.exc_info()
if (exc_info is not None):
raise exc_info[0], exc_info[1], exc_info[2]
| null | null | null | last in
| codeqa | def run exitfuncs exc info Nonewhile exithandlers func targs kargs exithandlers pop try func *targs **kargs except System Exit exc info sys exc info except import tracebackprint >>sys stderr ' Errorinatexit run exitfuncs 'traceback print exc exc info sys exc info if exc info is not None raise exc info[ 0 ] exc info[ 1 ] exc info[ 2 ]
| null | null | null | null | Question:
When are functions executed ?
Code:
def _run_exitfuncs():
exc_info = None
while _exithandlers:
(func, targs, kargs) = _exithandlers.pop()
try:
func(*targs, **kargs)
except SystemExit:
exc_info = sys.exc_info()
except:
import traceback
print >>sys.stderr, 'Error in atexit._run_exitfuncs:'
traceback.print_exc()
exc_info = sys.exc_info()
if (exc_info is not None):
raise exc_info[0], exc_info[1], exc_info[2]
|
null | null | null | Where does the code convert the group i d to the group name on this system ?
| def gid_to_group(gid):
func_name = '{0}.gid_to_group'.format(__virtualname__)
if (__opts__.get('fun', '') == func_name):
log.info('The function {0} should not be used on Windows systems; see function docs for details.'.format(func_name))
return uid_to_user(gid)
| null | null | null | under windows
| codeqa | def gid to group gid func name '{ 0 } gid to group' format virtualname if opts get 'fun' '' func name log info ' Thefunction{ 0 }shouldnotbeusedon Windowssystems seefunctiondocsfordetails ' format func name return uid to user gid
| null | null | null | null | Question:
Where does the code convert the group i d to the group name on this system ?
Code:
def gid_to_group(gid):
func_name = '{0}.gid_to_group'.format(__virtualname__)
if (__opts__.get('fun', '') == func_name):
log.info('The function {0} should not be used on Windows systems; see function docs for details.'.format(func_name))
return uid_to_user(gid)
|
null | null | null | What does the code convert to the group name on this system under windows ?
| def gid_to_group(gid):
func_name = '{0}.gid_to_group'.format(__virtualname__)
if (__opts__.get('fun', '') == func_name):
log.info('The function {0} should not be used on Windows systems; see function docs for details.'.format(func_name))
return uid_to_user(gid)
| null | null | null | the group i d
| codeqa | def gid to group gid func name '{ 0 } gid to group' format virtualname if opts get 'fun' '' func name log info ' Thefunction{ 0 }shouldnotbeusedon Windowssystems seefunctiondocsfordetails ' format func name return uid to user gid
| null | null | null | null | Question:
What does the code convert to the group name on this system under windows ?
Code:
def gid_to_group(gid):
func_name = '{0}.gid_to_group'.format(__virtualname__)
if (__opts__.get('fun', '') == func_name):
log.info('The function {0} should not be used on Windows systems; see function docs for details.'.format(func_name))
return uid_to_user(gid)
|
null | null | null | Where do with the code deal ?
| def make_string_uc(seq):
seq = seq[8:]
return make_string(seq)
| null | null | null | in the first 8 bytes of a user comment
| codeqa | def make string uc seq seq seq[ 8 ]return make string seq
| null | null | null | null | Question:
Where do with the code deal ?
Code:
def make_string_uc(seq):
seq = seq[8:]
return make_string(seq)
|
null | null | null | What deals in the first 8 bytes of a user comment ?
| def make_string_uc(seq):
seq = seq[8:]
return make_string(seq)
| null | null | null | with the code
| codeqa | def make string uc seq seq seq[ 8 ]return make string seq
| null | null | null | null | Question:
What deals in the first 8 bytes of a user comment ?
Code:
def make_string_uc(seq):
seq = seq[8:]
return make_string(seq)
|
null | null | null | What does the code make ?
| @requires_duration
def slide_out(clip, duration, side):
(w, h) = clip.size
t_s = (clip.duration - duration)
pos_dict = {'left': (lambda t: (min(0, (w * (1 - ((t - ts) / duration)))), 'center')), 'right': (lambda t: (max(0, (w * (((t - ts) / duration) - 1))), 'center')), 'top': (lambda t: ('center', min(0, (h * (1 - ((t - ts) / duration)))))), 'bottom': (lambda t: ('center', max(0, (h * (((t - ts) / duration) - 1)))))}
return clip.set_pos(pos_dict[side])
| null | null | null | the clip go away by one side of the screen
| codeqa | @requires durationdef slide out clip duration side w h clip sizet s clip duration - duration pos dict {'left' lambda t min 0 w * 1 - t - ts / duration 'center' 'right' lambda t max 0 w * t - ts / duration - 1 'center' 'top' lambda t 'center' min 0 h * 1 - t - ts / duration 'bottom' lambda t 'center' max 0 h * t - ts / duration - 1 }return clip set pos pos dict[side]
| null | null | null | null | Question:
What does the code make ?
Code:
@requires_duration
def slide_out(clip, duration, side):
(w, h) = clip.size
t_s = (clip.duration - duration)
pos_dict = {'left': (lambda t: (min(0, (w * (1 - ((t - ts) / duration)))), 'center')), 'right': (lambda t: (max(0, (w * (((t - ts) / duration) - 1))), 'center')), 'top': (lambda t: ('center', min(0, (h * (1 - ((t - ts) / duration)))))), 'bottom': (lambda t: ('center', max(0, (h * (((t - ts) / duration) - 1)))))}
return clip.set_pos(pos_dict[side])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.