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 | Does the code read the contents of a file ?
| def read_file_contents(file_location, logger=None, fetch_if_remote=False):
if file_location.startswith('/'):
if (not os.path.exists(file_location)):
if logger:
logger.warning(('File does not exist: %s' % file_location))
raise FileNotFoundException(('%s: %s' % (_('File not found'), file_location)))
try:
f = open(file_location)
data = f.read()
f.close()
return data
except:
if logger:
log_exc(logger)
raise
if (not fetch_if_remote):
return None
if file_is_remote(file_location):
try:
handler = urllib2.urlopen(file_location)
data = handler.read()
handler.close()
return data
except urllib2.HTTPError:
if logger:
logger.warning(('File does not exist: %s' % file_location))
raise FileNotFoundException(('%s: %s' % (_('File not found'), file_location)))
| null | null | null | Yes
| codeqa | def read file contents file location logger None fetch if remote False if file location startswith '/' if not os path exists file location if logger logger warning ' Filedoesnotexist %s' % file location raise File Not Found Exception '%s %s' % ' Filenotfound' file location try f open file location data f read f close return dataexcept if logger log exc logger raiseif not fetch if remote return Noneif file is remote file location try handler urllib 2 urlopen file location data handler read handler close return dataexcept urllib 2 HTTP Error if logger logger warning ' Filedoesnotexist %s' % file location raise File Not Found Exception '%s %s' % ' Filenotfound' file location
| null | null | null | null | Question:
Does the code read the contents of a file ?
Code:
def read_file_contents(file_location, logger=None, fetch_if_remote=False):
if file_location.startswith('/'):
if (not os.path.exists(file_location)):
if logger:
logger.warning(('File does not exist: %s' % file_location))
raise FileNotFoundException(('%s: %s' % (_('File not found'), file_location)))
try:
f = open(file_location)
data = f.read()
f.close()
return data
except:
if logger:
log_exc(logger)
raise
if (not fetch_if_remote):
return None
if file_is_remote(file_location):
try:
handler = urllib2.urlopen(file_location)
data = handler.read()
handler.close()
return data
except urllib2.HTTPError:
if logger:
logger.warning(('File does not exist: %s' % file_location))
raise FileNotFoundException(('%s: %s' % (_('File not found'), file_location)))
|
null | null | null | What does the code read ?
| def read_file_contents(file_location, logger=None, fetch_if_remote=False):
if file_location.startswith('/'):
if (not os.path.exists(file_location)):
if logger:
logger.warning(('File does not exist: %s' % file_location))
raise FileNotFoundException(('%s: %s' % (_('File not found'), file_location)))
try:
f = open(file_location)
data = f.read()
f.close()
return data
except:
if logger:
log_exc(logger)
raise
if (not fetch_if_remote):
return None
if file_is_remote(file_location):
try:
handler = urllib2.urlopen(file_location)
data = handler.read()
handler.close()
return data
except urllib2.HTTPError:
if logger:
logger.warning(('File does not exist: %s' % file_location))
raise FileNotFoundException(('%s: %s' % (_('File not found'), file_location)))
| null | null | null | the contents of a file
| codeqa | def read file contents file location logger None fetch if remote False if file location startswith '/' if not os path exists file location if logger logger warning ' Filedoesnotexist %s' % file location raise File Not Found Exception '%s %s' % ' Filenotfound' file location try f open file location data f read f close return dataexcept if logger log exc logger raiseif not fetch if remote return Noneif file is remote file location try handler urllib 2 urlopen file location data handler read handler close return dataexcept urllib 2 HTTP Error if logger logger warning ' Filedoesnotexist %s' % file location raise File Not Found Exception '%s %s' % ' Filenotfound' file location
| null | null | null | null | Question:
What does the code read ?
Code:
def read_file_contents(file_location, logger=None, fetch_if_remote=False):
if file_location.startswith('/'):
if (not os.path.exists(file_location)):
if logger:
logger.warning(('File does not exist: %s' % file_location))
raise FileNotFoundException(('%s: %s' % (_('File not found'), file_location)))
try:
f = open(file_location)
data = f.read()
f.close()
return data
except:
if logger:
log_exc(logger)
raise
if (not fetch_if_remote):
return None
if file_is_remote(file_location):
try:
handler = urllib2.urlopen(file_location)
data = handler.read()
handler.close()
return data
except urllib2.HTTPError:
if logger:
logger.warning(('File does not exist: %s' % file_location))
raise FileNotFoundException(('%s: %s' % (_('File not found'), file_location)))
|
null | null | null | What does the code get ?
| def get_account_info(env, app, swift_source=None):
cache = cache_from_env(env)
if (not cache):
return None
(version, account, container, _) = split_path(env['PATH_INFO'], 2, 4, True)
cache_key = get_account_memcache_key(account)
env_key = ('swift.%s' % cache_key)
if (env_key not in env):
account_info = cache.get(cache_key)
if (not account_info):
resp = make_pre_authed_request(env, 'HEAD', ('/%s/%s' % (version, account)), swift_source=swift_source).get_response(app)
account_info = headers_to_account_info(resp.headers, resp.status_int)
env[env_key] = account_info
return env[env_key]
| null | null | null | the info structure for an account
| codeqa | def get account info env app swift source None cache cache from env env if not cache return None version account container split path env['PATH INFO'] 2 4 True cache key get account memcache key account env key 'swift %s' % cache key if env key not in env account info cache get cache key if not account info resp make pre authed request env 'HEAD' '/%s/%s' % version account swift source swift source get response app account info headers to account info resp headers resp status int env[env key] account inforeturn env[env key]
| null | null | null | null | Question:
What does the code get ?
Code:
def get_account_info(env, app, swift_source=None):
cache = cache_from_env(env)
if (not cache):
return None
(version, account, container, _) = split_path(env['PATH_INFO'], 2, 4, True)
cache_key = get_account_memcache_key(account)
env_key = ('swift.%s' % cache_key)
if (env_key not in env):
account_info = cache.get(cache_key)
if (not account_info):
resp = make_pre_authed_request(env, 'HEAD', ('/%s/%s' % (version, account)), swift_source=swift_source).get_response(app)
account_info = headers_to_account_info(resp.headers, resp.status_int)
env[env_key] = account_info
return env[env_key]
|
null | null | null | Does the code get the info structure for an account ?
| def get_account_info(env, app, swift_source=None):
cache = cache_from_env(env)
if (not cache):
return None
(version, account, container, _) = split_path(env['PATH_INFO'], 2, 4, True)
cache_key = get_account_memcache_key(account)
env_key = ('swift.%s' % cache_key)
if (env_key not in env):
account_info = cache.get(cache_key)
if (not account_info):
resp = make_pre_authed_request(env, 'HEAD', ('/%s/%s' % (version, account)), swift_source=swift_source).get_response(app)
account_info = headers_to_account_info(resp.headers, resp.status_int)
env[env_key] = account_info
return env[env_key]
| null | null | null | Yes
| codeqa | def get account info env app swift source None cache cache from env env if not cache return None version account container split path env['PATH INFO'] 2 4 True cache key get account memcache key account env key 'swift %s' % cache key if env key not in env account info cache get cache key if not account info resp make pre authed request env 'HEAD' '/%s/%s' % version account swift source swift source get response app account info headers to account info resp headers resp status int env[env key] account inforeturn env[env key]
| null | null | null | null | Question:
Does the code get the info structure for an account ?
Code:
def get_account_info(env, app, swift_source=None):
cache = cache_from_env(env)
if (not cache):
return None
(version, account, container, _) = split_path(env['PATH_INFO'], 2, 4, True)
cache_key = get_account_memcache_key(account)
env_key = ('swift.%s' % cache_key)
if (env_key not in env):
account_info = cache.get(cache_key)
if (not account_info):
resp = make_pre_authed_request(env, 'HEAD', ('/%s/%s' % (version, account)), swift_source=swift_source).get_response(app)
account_info = headers_to_account_info(resp.headers, resp.status_int)
env[env_key] = account_info
return env[env_key]
|
null | null | null | Is the namespace is visible in this context ?
| def _is_namespace_visible(context, namespace, status=None):
if context.is_admin:
return True
if (namespace['owner'] is None):
return True
if ('visibility' in namespace):
if (namespace['visibility'] == 'public'):
return True
if (context.owner is not None):
if (context.owner == namespace['owner']):
return True
return False
| null | null | null | Yes
| codeqa | def is namespace visible context namespace status None if context is admin return Trueif namespace['owner'] is None return Trueif 'visibility' in namespace if namespace['visibility'] 'public' return Trueif context owner is not None if context owner namespace['owner'] return Truereturn False
| null | null | null | null | Question:
Is the namespace is visible in this context ?
Code:
def _is_namespace_visible(context, namespace, status=None):
if context.is_admin:
return True
if (namespace['owner'] is None):
return True
if ('visibility' in namespace):
if (namespace['visibility'] == 'public'):
return True
if (context.owner is not None):
if (context.owner == namespace['owner']):
return True
return False
|
null | null | null | What is visible in this context ?
| def _is_namespace_visible(context, namespace, status=None):
if context.is_admin:
return True
if (namespace['owner'] is None):
return True
if ('visibility' in namespace):
if (namespace['visibility'] == 'public'):
return True
if (context.owner is not None):
if (context.owner == namespace['owner']):
return True
return False
| null | null | null | the namespace
| codeqa | def is namespace visible context namespace status None if context is admin return Trueif namespace['owner'] is None return Trueif 'visibility' in namespace if namespace['visibility'] 'public' return Trueif context owner is not None if context owner namespace['owner'] return Truereturn False
| null | null | null | null | Question:
What is visible in this context ?
Code:
def _is_namespace_visible(context, namespace, status=None):
if context.is_admin:
return True
if (namespace['owner'] is None):
return True
if ('visibility' in namespace):
if (namespace['visibility'] == 'public'):
return True
if (context.owner is not None):
if (context.owner == namespace['owner']):
return True
return False
|
null | null | null | Where is the namespace visible ?
| def _is_namespace_visible(context, namespace, status=None):
if context.is_admin:
return True
if (namespace['owner'] is None):
return True
if ('visibility' in namespace):
if (namespace['visibility'] == 'public'):
return True
if (context.owner is not None):
if (context.owner == namespace['owner']):
return True
return False
| null | null | null | in this context
| codeqa | def is namespace visible context namespace status None if context is admin return Trueif namespace['owner'] is None return Trueif 'visibility' in namespace if namespace['visibility'] 'public' return Trueif context owner is not None if context owner namespace['owner'] return Truereturn False
| null | null | null | null | Question:
Where is the namespace visible ?
Code:
def _is_namespace_visible(context, namespace, status=None):
if context.is_admin:
return True
if (namespace['owner'] is None):
return True
if ('visibility' in namespace):
if (namespace['visibility'] == 'public'):
return True
if (context.owner is not None):
if (context.owner == namespace['owner']):
return True
return False
|
null | null | null | How do commands run for minion startup ?
| def _retcode_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, template=None, umask=None, output_loglevel='quiet', log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, **kwargs):
return retcode(cmd, cwd=cwd, stdin=stdin, runas=runas, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, umask=umask, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, **kwargs)
| null | null | null | quietly
| codeqa | def retcode quiet cmd cwd None stdin None runas None shell DEFAULT SHELL python shell False env None clean env False template None umask None output loglevel 'quiet' log callback None timeout None reset system locale True ignore retcode False saltenv 'base' use vt False password None **kwargs return retcode cmd cwd cwd stdin stdin runas runas shell shell python shell python shell env env clean env clean env template template umask umask output loglevel output loglevel log callback log callback timeout timeout reset system locale reset system locale ignore retcode ignore retcode saltenv saltenv use vt use vt password password **kwargs
| null | null | null | null | Question:
How do commands run for minion startup ?
Code:
def _retcode_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, template=None, umask=None, output_loglevel='quiet', log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, **kwargs):
return retcode(cmd, cwd=cwd, stdin=stdin, runas=runas, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, umask=umask, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, **kwargs)
|
null | null | null | For what purpose do commands run quietly ?
| def _retcode_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, template=None, umask=None, output_loglevel='quiet', log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, **kwargs):
return retcode(cmd, cwd=cwd, stdin=stdin, runas=runas, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, umask=umask, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, **kwargs)
| null | null | null | for minion startup
| codeqa | def retcode quiet cmd cwd None stdin None runas None shell DEFAULT SHELL python shell False env None clean env False template None umask None output loglevel 'quiet' log callback None timeout None reset system locale True ignore retcode False saltenv 'base' use vt False password None **kwargs return retcode cmd cwd cwd stdin stdin runas runas shell shell python shell python shell env env clean env clean env template template umask umask output loglevel output loglevel log callback log callback timeout timeout reset system locale reset system locale ignore retcode ignore retcode saltenv saltenv use vt use vt password password **kwargs
| null | null | null | null | Question:
For what purpose do commands run quietly ?
Code:
def _retcode_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, template=None, umask=None, output_loglevel='quiet', log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, **kwargs):
return retcode(cmd, cwd=cwd, stdin=stdin, runas=runas, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, umask=umask, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, **kwargs)
|
null | null | null | How do a numeric string x ?
| def zfill(x, width):
if (not isinstance(x, basestring)):
x = repr(x)
return x.zfill(width)
| null | null | null | with zeros
| codeqa | def zfill x width if not isinstance x basestring x repr x return x zfill width
| null | null | null | null | Question:
How do a numeric string x ?
Code:
def zfill(x, width):
if (not isinstance(x, basestring)):
x = repr(x)
return x.zfill(width)
|
null | null | null | How do data assign to servers ?
| def hash_shard(word):
return ('server%d' % (hash(word) % 4))
| null | null | null | using a hash value
| codeqa | def hash shard word return 'server%d' % hash word % 4
| null | null | null | null | Question:
How do data assign to servers ?
Code:
def hash_shard(word):
return ('server%d' % (hash(word) % 4))
|
null | null | null | What does the code do ?
| def hash_shard(word):
return ('server%d' % (hash(word) % 4))
| null | null | null | a great job of assigning data to servers using a hash value
| codeqa | def hash shard word return 'server%d' % hash word % 4
| null | null | null | null | Question:
What does the code do ?
Code:
def hash_shard(word):
return ('server%d' % (hash(word) % 4))
|
null | null | null | Does the code do a great job of assigning data to servers using a hash value ?
| def hash_shard(word):
return ('server%d' % (hash(word) % 4))
| null | null | null | Yes
| codeqa | def hash shard word return 'server%d' % hash word % 4
| null | null | null | null | Question:
Does the code do a great job of assigning data to servers using a hash value ?
Code:
def hash_shard(word):
return ('server%d' % (hash(word) % 4))
|
null | null | null | What does the code remove from the given data structure ?
| def _remove_dots(src):
output = {}
for (key, val) in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
| null | null | null | dots
| codeqa | def remove dots src output {}for key val in six iteritems src if isinstance val dict val remove dots val output[key replace ' ' '-' ] valreturn output
| null | null | null | null | Question:
What does the code remove from the given data structure ?
Code:
def _remove_dots(src):
output = {}
for (key, val) in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
|
null | null | null | Does the code remove dots from the given data structure ?
| def _remove_dots(src):
output = {}
for (key, val) in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
| null | null | null | Yes
| codeqa | def remove dots src output {}for key val in six iteritems src if isinstance val dict val remove dots val output[key replace ' ' '-' ] valreturn output
| null | null | null | null | Question:
Does the code remove dots from the given data structure ?
Code:
def _remove_dots(src):
output = {}
for (key, val) in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output
|
null | null | null | What runs on each batch element ?
| def ctc_batch_cost(y_true, y_pred, input_length, label_length):
label_length = tf.to_int32(tf.squeeze(label_length))
input_length = tf.to_int32(tf.squeeze(input_length))
sparse_labels = tf.to_int32(ctc_label_dense_to_sparse(y_true, label_length))
y_pred = tf.log((tf.transpose(y_pred, perm=[1, 0, 2]) + 1e-08))
return tf.expand_dims(ctc.ctc_loss(inputs=y_pred, labels=sparse_labels, sequence_length=input_length), 1)
| null | null | null | ctc loss algorithm
| codeqa | def ctc batch cost y true y pred input length label length label length tf to int 32 tf squeeze label length input length tf to int 32 tf squeeze input length sparse labels tf to int 32 ctc label dense to sparse y true label length y pred tf log tf transpose y pred perm [1 0 2] + 1e- 08 return tf expand dims ctc ctc loss inputs y pred labels sparse labels sequence length input length 1
| null | null | null | null | Question:
What runs on each batch element ?
Code:
def ctc_batch_cost(y_true, y_pred, input_length, label_length):
label_length = tf.to_int32(tf.squeeze(label_length))
input_length = tf.to_int32(tf.squeeze(input_length))
sparse_labels = tf.to_int32(ctc_label_dense_to_sparse(y_true, label_length))
y_pred = tf.log((tf.transpose(y_pred, perm=[1, 0, 2]) + 1e-08))
return tf.expand_dims(ctc.ctc_loss(inputs=y_pred, labels=sparse_labels, sequence_length=input_length), 1)
|
null | null | null | What do an evolutionary algorithm apply ?
| def varOr(population, toolbox, lambda_, cxpb, mutpb):
assert ((cxpb + mutpb) <= 1.0), 'The sum of the crossover and mutation probabilities must be smaller or equal to 1.0.'
offspring = []
for _ in xrange(lambda_):
op_choice = random.random()
if (op_choice < cxpb):
(ind1, ind2) = map(toolbox.clone, random.sample(population, 2))
(ind1, ind2) = toolbox.mate(ind1, ind2)
del ind1.fitness.values
offspring.append(ind1)
elif (op_choice < (cxpb + mutpb)):
ind = toolbox.clone(random.choice(population))
(ind,) = toolbox.mutate(ind)
del ind.fitness.values
offspring.append(ind)
else:
offspring.append(random.choice(population))
return offspring
| null | null | null | only the variation part
| codeqa | def var Or population toolbox lambda cxpb mutpb assert cxpb + mutpb < 1 0 ' Thesumofthecrossoverandmutationprobabilitiesmustbesmallerorequalto 1 0 'offspring []for in xrange lambda op choice random random if op choice < cxpb ind 1 ind 2 map toolbox clone random sample population 2 ind 1 ind 2 toolbox mate ind 1 ind 2 del ind 1 fitness valuesoffspring append ind 1 elif op choice < cxpb + mutpb ind toolbox clone random choice population ind toolbox mutate ind del ind fitness valuesoffspring append ind else offspring append random choice population return offspring
| null | null | null | null | Question:
What do an evolutionary algorithm apply ?
Code:
def varOr(population, toolbox, lambda_, cxpb, mutpb):
assert ((cxpb + mutpb) <= 1.0), 'The sum of the crossover and mutation probabilities must be smaller or equal to 1.0.'
offspring = []
for _ in xrange(lambda_):
op_choice = random.random()
if (op_choice < cxpb):
(ind1, ind2) = map(toolbox.clone, random.sample(population, 2))
(ind1, ind2) = toolbox.mate(ind1, ind2)
del ind1.fitness.values
offspring.append(ind1)
elif (op_choice < (cxpb + mutpb)):
ind = toolbox.clone(random.choice(population))
(ind,) = toolbox.mutate(ind)
del ind.fitness.values
offspring.append(ind)
else:
offspring.append(random.choice(population))
return offspring
|
null | null | null | What is applying only the variation part ?
| def varOr(population, toolbox, lambda_, cxpb, mutpb):
assert ((cxpb + mutpb) <= 1.0), 'The sum of the crossover and mutation probabilities must be smaller or equal to 1.0.'
offspring = []
for _ in xrange(lambda_):
op_choice = random.random()
if (op_choice < cxpb):
(ind1, ind2) = map(toolbox.clone, random.sample(population, 2))
(ind1, ind2) = toolbox.mate(ind1, ind2)
del ind1.fitness.values
offspring.append(ind1)
elif (op_choice < (cxpb + mutpb)):
ind = toolbox.clone(random.choice(population))
(ind,) = toolbox.mutate(ind)
del ind.fitness.values
offspring.append(ind)
else:
offspring.append(random.choice(population))
return offspring
| null | null | null | an evolutionary algorithm
| codeqa | def var Or population toolbox lambda cxpb mutpb assert cxpb + mutpb < 1 0 ' Thesumofthecrossoverandmutationprobabilitiesmustbesmallerorequalto 1 0 'offspring []for in xrange lambda op choice random random if op choice < cxpb ind 1 ind 2 map toolbox clone random sample population 2 ind 1 ind 2 toolbox mate ind 1 ind 2 del ind 1 fitness valuesoffspring append ind 1 elif op choice < cxpb + mutpb ind toolbox clone random choice population ind toolbox mutate ind del ind fitness valuesoffspring append ind else offspring append random choice population return offspring
| null | null | null | null | Question:
What is applying only the variation part ?
Code:
def varOr(population, toolbox, lambda_, cxpb, mutpb):
assert ((cxpb + mutpb) <= 1.0), 'The sum of the crossover and mutation probabilities must be smaller or equal to 1.0.'
offspring = []
for _ in xrange(lambda_):
op_choice = random.random()
if (op_choice < cxpb):
(ind1, ind2) = map(toolbox.clone, random.sample(population, 2))
(ind1, ind2) = toolbox.mate(ind1, ind2)
del ind1.fitness.values
offspring.append(ind1)
elif (op_choice < (cxpb + mutpb)):
ind = toolbox.clone(random.choice(population))
(ind,) = toolbox.mutate(ind)
del ind.fitness.values
offspring.append(ind)
else:
offspring.append(random.choice(population))
return offspring
|
null | null | null | Do an evolutionary algorithm apply only the variation part ?
| def varOr(population, toolbox, lambda_, cxpb, mutpb):
assert ((cxpb + mutpb) <= 1.0), 'The sum of the crossover and mutation probabilities must be smaller or equal to 1.0.'
offspring = []
for _ in xrange(lambda_):
op_choice = random.random()
if (op_choice < cxpb):
(ind1, ind2) = map(toolbox.clone, random.sample(population, 2))
(ind1, ind2) = toolbox.mate(ind1, ind2)
del ind1.fitness.values
offspring.append(ind1)
elif (op_choice < (cxpb + mutpb)):
ind = toolbox.clone(random.choice(population))
(ind,) = toolbox.mutate(ind)
del ind.fitness.values
offspring.append(ind)
else:
offspring.append(random.choice(population))
return offspring
| null | null | null | Yes
| codeqa | def var Or population toolbox lambda cxpb mutpb assert cxpb + mutpb < 1 0 ' Thesumofthecrossoverandmutationprobabilitiesmustbesmallerorequalto 1 0 'offspring []for in xrange lambda op choice random random if op choice < cxpb ind 1 ind 2 map toolbox clone random sample population 2 ind 1 ind 2 toolbox mate ind 1 ind 2 del ind 1 fitness valuesoffspring append ind 1 elif op choice < cxpb + mutpb ind toolbox clone random choice population ind toolbox mutate ind del ind fitness valuesoffspring append ind else offspring append random choice population return offspring
| null | null | null | null | Question:
Do an evolutionary algorithm apply only the variation part ?
Code:
def varOr(population, toolbox, lambda_, cxpb, mutpb):
assert ((cxpb + mutpb) <= 1.0), 'The sum of the crossover and mutation probabilities must be smaller or equal to 1.0.'
offspring = []
for _ in xrange(lambda_):
op_choice = random.random()
if (op_choice < cxpb):
(ind1, ind2) = map(toolbox.clone, random.sample(population, 2))
(ind1, ind2) = toolbox.mate(ind1, ind2)
del ind1.fitness.values
offspring.append(ind1)
elif (op_choice < (cxpb + mutpb)):
ind = toolbox.clone(random.choice(population))
(ind,) = toolbox.mutate(ind)
del ind.fitness.values
offspring.append(ind)
else:
offspring.append(random.choice(population))
return offspring
|
null | null | null | Does the code compare the given timezone name with the system timezone name ?
| def zone_compare(timezone):
if ('Solaris' in __grains__['os_family']):
return (timezone == get_zone())
tzfile = _get_etc_localtime_path()
zonepath = _get_zone_file(timezone)
try:
return filecmp.cmp(tzfile, zonepath, shallow=False)
except OSError as exc:
problematic_file = exc.filename
if (problematic_file == zonepath):
raise SaltInvocationError('Can\'t find a local timezone "{0}"'.format(timezone))
elif (problematic_file == tzfile):
raise CommandExecutionError('Failed to read {0} to determine current timezone: {1}'.format(tzfile, exc.strerror))
raise
| null | null | null | Yes
| codeqa | def zone compare timezone if ' Solaris' in grains ['os family'] return timezone get zone tzfile get etc localtime path zonepath get zone file timezone try return filecmp cmp tzfile zonepath shallow False except OS Error as exc problematic file exc filenameif problematic file zonepath raise Salt Invocation Error ' Can\'tfindalocaltimezone"{ 0 }"' format timezone elif problematic file tzfile raise Command Execution Error ' Failedtoread{ 0 }todeterminecurrenttimezone {1 }' format tzfile exc strerror raise
| null | null | null | null | Question:
Does the code compare the given timezone name with the system timezone name ?
Code:
def zone_compare(timezone):
if ('Solaris' in __grains__['os_family']):
return (timezone == get_zone())
tzfile = _get_etc_localtime_path()
zonepath = _get_zone_file(timezone)
try:
return filecmp.cmp(tzfile, zonepath, shallow=False)
except OSError as exc:
problematic_file = exc.filename
if (problematic_file == zonepath):
raise SaltInvocationError('Can\'t find a local timezone "{0}"'.format(timezone))
elif (problematic_file == tzfile):
raise CommandExecutionError('Failed to read {0} to determine current timezone: {1}'.format(tzfile, exc.strerror))
raise
|
null | null | null | What does the code compare with the system timezone name ?
| def zone_compare(timezone):
if ('Solaris' in __grains__['os_family']):
return (timezone == get_zone())
tzfile = _get_etc_localtime_path()
zonepath = _get_zone_file(timezone)
try:
return filecmp.cmp(tzfile, zonepath, shallow=False)
except OSError as exc:
problematic_file = exc.filename
if (problematic_file == zonepath):
raise SaltInvocationError('Can\'t find a local timezone "{0}"'.format(timezone))
elif (problematic_file == tzfile):
raise CommandExecutionError('Failed to read {0} to determine current timezone: {1}'.format(tzfile, exc.strerror))
raise
| null | null | null | the given timezone name
| codeqa | def zone compare timezone if ' Solaris' in grains ['os family'] return timezone get zone tzfile get etc localtime path zonepath get zone file timezone try return filecmp cmp tzfile zonepath shallow False except OS Error as exc problematic file exc filenameif problematic file zonepath raise Salt Invocation Error ' Can\'tfindalocaltimezone"{ 0 }"' format timezone elif problematic file tzfile raise Command Execution Error ' Failedtoread{ 0 }todeterminecurrenttimezone {1 }' format tzfile exc strerror raise
| null | null | null | null | Question:
What does the code compare with the system timezone name ?
Code:
def zone_compare(timezone):
if ('Solaris' in __grains__['os_family']):
return (timezone == get_zone())
tzfile = _get_etc_localtime_path()
zonepath = _get_zone_file(timezone)
try:
return filecmp.cmp(tzfile, zonepath, shallow=False)
except OSError as exc:
problematic_file = exc.filename
if (problematic_file == zonepath):
raise SaltInvocationError('Can\'t find a local timezone "{0}"'.format(timezone))
elif (problematic_file == tzfile):
raise CommandExecutionError('Failed to read {0} to determine current timezone: {1}'.format(tzfile, exc.strerror))
raise
|
null | null | null | Does the code expose the function ?
| def expose(func=None, alias=None):
def expose_(func):
func.exposed = True
if (alias is not None):
if isinstance(alias, basestring):
parents[alias.replace('.', '_')] = func
else:
for a in alias:
parents[a.replace('.', '_')] = func
return func
import sys
import types
if isinstance(func, (types.FunctionType, types.MethodType)):
if (alias is None):
func.exposed = True
return func
else:
parents = sys._getframe(1).f_locals
return expose_(func)
elif (func is None):
if (alias is None):
parents = sys._getframe(1).f_locals
return expose_
else:
parents = sys._getframe(1).f_locals
return expose_
else:
parents = sys._getframe(1).f_locals
alias = func
return expose_
| null | null | null | Yes
| codeqa | def expose func None alias None def expose func func exposed Trueif alias is not None if isinstance alias basestring parents[alias replace ' ' ' ' ] funcelse for a in alias parents[a replace ' ' ' ' ] funcreturn funcimport sysimport typesif isinstance func types Function Type types Method Type if alias is None func exposed Truereturn funcelse parents sys getframe 1 f localsreturn expose func elif func is None if alias is None parents sys getframe 1 f localsreturn expose else parents sys getframe 1 f localsreturn expose else parents sys getframe 1 f localsalias funcreturn expose
| null | null | null | null | Question:
Does the code expose the function ?
Code:
def expose(func=None, alias=None):
def expose_(func):
func.exposed = True
if (alias is not None):
if isinstance(alias, basestring):
parents[alias.replace('.', '_')] = func
else:
for a in alias:
parents[a.replace('.', '_')] = func
return func
import sys
import types
if isinstance(func, (types.FunctionType, types.MethodType)):
if (alias is None):
func.exposed = True
return func
else:
parents = sys._getframe(1).f_locals
return expose_(func)
elif (func is None):
if (alias is None):
parents = sys._getframe(1).f_locals
return expose_
else:
parents = sys._getframe(1).f_locals
return expose_
else:
parents = sys._getframe(1).f_locals
alias = func
return expose_
|
null | null | null | What tries getting the page from the cache ?
| def cache_page(*args, **kwargs):
cache_alias = kwargs.pop('cache', None)
key_prefix = kwargs.pop('key_prefix', None)
assert (not kwargs), 'The only keyword arguments are cache and key_prefix'
if (len(args) > 1):
assert (len(args) == 2), 'cache_page accepts at most 2 arguments'
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[1], cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
elif callable(args[1]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)(args[1])
else:
assert False, 'cache_page must be passed a view function if called with two arguments'
elif (len(args) == 1):
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)
| null | null | null | views
| codeqa | def cache page *args **kwargs cache alias kwargs pop 'cache' None key prefix kwargs pop 'key prefix' None assert not kwargs ' Theonlykeywordargumentsarecacheandkey prefix'if len args > 1 assert len args 2 'cache pageacceptsatmost 2 arguments'if callable args[ 0 ] return decorator from middleware with args Cache Middleware cache timeout args[ 1 ] cache alias cache alias key prefix key prefix args[ 0 ] elif callable args[ 1 ] return decorator from middleware with args Cache Middleware cache timeout args[ 0 ] cache alias cache alias key prefix key prefix args[ 1 ] else assert False 'cache pagemustbepassedaviewfunctionifcalledwithtwoarguments'elif len args 1 if callable args[ 0 ] return decorator from middleware with args Cache Middleware cache alias cache alias key prefix key prefix args[ 0 ] else return decorator from middleware with args Cache Middleware cache timeout args[ 0 ] cache alias cache alias key prefix key prefix else return decorator from middleware with args Cache Middleware cache alias cache alias key prefix key prefix
| null | null | null | null | Question:
What tries getting the page from the cache ?
Code:
def cache_page(*args, **kwargs):
cache_alias = kwargs.pop('cache', None)
key_prefix = kwargs.pop('key_prefix', None)
assert (not kwargs), 'The only keyword arguments are cache and key_prefix'
if (len(args) > 1):
assert (len(args) == 2), 'cache_page accepts at most 2 arguments'
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[1], cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
elif callable(args[1]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)(args[1])
else:
assert False, 'cache_page must be passed a view function if called with two arguments'
elif (len(args) == 1):
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)
|
null | null | null | Does that get the page from the cache ?
| def cache_page(*args, **kwargs):
cache_alias = kwargs.pop('cache', None)
key_prefix = kwargs.pop('key_prefix', None)
assert (not kwargs), 'The only keyword arguments are cache and key_prefix'
if (len(args) > 1):
assert (len(args) == 2), 'cache_page accepts at most 2 arguments'
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[1], cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
elif callable(args[1]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)(args[1])
else:
assert False, 'cache_page must be passed a view function if called with two arguments'
elif (len(args) == 1):
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)
| null | null | null | Yes
| codeqa | def cache page *args **kwargs cache alias kwargs pop 'cache' None key prefix kwargs pop 'key prefix' None assert not kwargs ' Theonlykeywordargumentsarecacheandkey prefix'if len args > 1 assert len args 2 'cache pageacceptsatmost 2 arguments'if callable args[ 0 ] return decorator from middleware with args Cache Middleware cache timeout args[ 1 ] cache alias cache alias key prefix key prefix args[ 0 ] elif callable args[ 1 ] return decorator from middleware with args Cache Middleware cache timeout args[ 0 ] cache alias cache alias key prefix key prefix args[ 1 ] else assert False 'cache pagemustbepassedaviewfunctionifcalledwithtwoarguments'elif len args 1 if callable args[ 0 ] return decorator from middleware with args Cache Middleware cache alias cache alias key prefix key prefix args[ 0 ] else return decorator from middleware with args Cache Middleware cache timeout args[ 0 ] cache alias cache alias key prefix key prefix else return decorator from middleware with args Cache Middleware cache alias cache alias key prefix key prefix
| null | null | null | null | Question:
Does that get the page from the cache ?
Code:
def cache_page(*args, **kwargs):
cache_alias = kwargs.pop('cache', None)
key_prefix = kwargs.pop('key_prefix', None)
assert (not kwargs), 'The only keyword arguments are cache and key_prefix'
if (len(args) > 1):
assert (len(args) == 2), 'cache_page accepts at most 2 arguments'
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[1], cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
elif callable(args[1]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)(args[1])
else:
assert False, 'cache_page must be passed a view function if called with two arguments'
elif (len(args) == 1):
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)
|
null | null | null | What does views try ?
| def cache_page(*args, **kwargs):
cache_alias = kwargs.pop('cache', None)
key_prefix = kwargs.pop('key_prefix', None)
assert (not kwargs), 'The only keyword arguments are cache and key_prefix'
if (len(args) > 1):
assert (len(args) == 2), 'cache_page accepts at most 2 arguments'
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[1], cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
elif callable(args[1]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)(args[1])
else:
assert False, 'cache_page must be passed a view function if called with two arguments'
elif (len(args) == 1):
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)
| null | null | null | getting the page from the cache
| codeqa | def cache page *args **kwargs cache alias kwargs pop 'cache' None key prefix kwargs pop 'key prefix' None assert not kwargs ' Theonlykeywordargumentsarecacheandkey prefix'if len args > 1 assert len args 2 'cache pageacceptsatmost 2 arguments'if callable args[ 0 ] return decorator from middleware with args Cache Middleware cache timeout args[ 1 ] cache alias cache alias key prefix key prefix args[ 0 ] elif callable args[ 1 ] return decorator from middleware with args Cache Middleware cache timeout args[ 0 ] cache alias cache alias key prefix key prefix args[ 1 ] else assert False 'cache pagemustbepassedaviewfunctionifcalledwithtwoarguments'elif len args 1 if callable args[ 0 ] return decorator from middleware with args Cache Middleware cache alias cache alias key prefix key prefix args[ 0 ] else return decorator from middleware with args Cache Middleware cache timeout args[ 0 ] cache alias cache alias key prefix key prefix else return decorator from middleware with args Cache Middleware cache alias cache alias key prefix key prefix
| null | null | null | null | Question:
What does views try ?
Code:
def cache_page(*args, **kwargs):
cache_alias = kwargs.pop('cache', None)
key_prefix = kwargs.pop('key_prefix', None)
assert (not kwargs), 'The only keyword arguments are cache and key_prefix'
if (len(args) > 1):
assert (len(args) == 2), 'cache_page accepts at most 2 arguments'
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[1], cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
elif callable(args[1]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)(args[1])
else:
assert False, 'cache_page must be passed a view function if called with two arguments'
elif (len(args) == 1):
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)
|
null | null | null | What does that get from the cache ?
| def cache_page(*args, **kwargs):
cache_alias = kwargs.pop('cache', None)
key_prefix = kwargs.pop('key_prefix', None)
assert (not kwargs), 'The only keyword arguments are cache and key_prefix'
if (len(args) > 1):
assert (len(args) == 2), 'cache_page accepts at most 2 arguments'
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[1], cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
elif callable(args[1]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)(args[1])
else:
assert False, 'cache_page must be passed a view function if called with two arguments'
elif (len(args) == 1):
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)
| null | null | null | the page
| codeqa | def cache page *args **kwargs cache alias kwargs pop 'cache' None key prefix kwargs pop 'key prefix' None assert not kwargs ' Theonlykeywordargumentsarecacheandkey prefix'if len args > 1 assert len args 2 'cache pageacceptsatmost 2 arguments'if callable args[ 0 ] return decorator from middleware with args Cache Middleware cache timeout args[ 1 ] cache alias cache alias key prefix key prefix args[ 0 ] elif callable args[ 1 ] return decorator from middleware with args Cache Middleware cache timeout args[ 0 ] cache alias cache alias key prefix key prefix args[ 1 ] else assert False 'cache pagemustbepassedaviewfunctionifcalledwithtwoarguments'elif len args 1 if callable args[ 0 ] return decorator from middleware with args Cache Middleware cache alias cache alias key prefix key prefix args[ 0 ] else return decorator from middleware with args Cache Middleware cache timeout args[ 0 ] cache alias cache alias key prefix key prefix else return decorator from middleware with args Cache Middleware cache alias cache alias key prefix key prefix
| null | null | null | null | Question:
What does that get from the cache ?
Code:
def cache_page(*args, **kwargs):
cache_alias = kwargs.pop('cache', None)
key_prefix = kwargs.pop('key_prefix', None)
assert (not kwargs), 'The only keyword arguments are cache and key_prefix'
if (len(args) > 1):
assert (len(args) == 2), 'cache_page accepts at most 2 arguments'
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[1], cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
elif callable(args[1]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)(args[1])
else:
assert False, 'cache_page must be passed a view function if called with two arguments'
elif (len(args) == 1):
if callable(args[0]):
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)(args[0])
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
else:
return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)
|
null | null | null | Does the code add faces from loops ?
| def addFacesByConvexBottomTopLoop(faces, indexedLoopBottom, indexedLoopTop):
if ((len(indexedLoopBottom) == 0) or (len(indexedLoopTop) == 0)):
return
for indexedPointIndex in xrange(max(len(indexedLoopBottom), len(indexedLoopTop))):
indexedConvex = []
if (len(indexedLoopBottom) > 1):
indexedConvex.append(indexedLoopBottom[indexedPointIndex])
indexedConvex.append(indexedLoopBottom[((indexedPointIndex + 1) % len(indexedLoopBottom))])
else:
indexedConvex.append(indexedLoopBottom[0])
if (len(indexedLoopTop) > 1):
indexedConvex.append(indexedLoopTop[((indexedPointIndex + 1) % len(indexedLoopTop))])
indexedConvex.append(indexedLoopTop[indexedPointIndex])
else:
indexedConvex.append(indexedLoopTop[0])
addFacesByConvex(faces, indexedConvex)
| null | null | null | Yes
| codeqa | def add Faces By Convex Bottom Top Loop faces indexed Loop Bottom indexed Loop Top if len indexed Loop Bottom 0 or len indexed Loop Top 0 returnfor indexed Point Index in xrange max len indexed Loop Bottom len indexed Loop Top indexed Convex []if len indexed Loop Bottom > 1 indexed Convex append indexed Loop Bottom[indexed Point Index] indexed Convex append indexed Loop Bottom[ indexed Point Index + 1 % len indexed Loop Bottom ] else indexed Convex append indexed Loop Bottom[ 0 ] if len indexed Loop Top > 1 indexed Convex append indexed Loop Top[ indexed Point Index + 1 % len indexed Loop Top ] indexed Convex append indexed Loop Top[indexed Point Index] else indexed Convex append indexed Loop Top[ 0 ] add Faces By Convex faces indexed Convex
| null | null | null | null | Question:
Does the code add faces from loops ?
Code:
def addFacesByConvexBottomTopLoop(faces, indexedLoopBottom, indexedLoopTop):
if ((len(indexedLoopBottom) == 0) or (len(indexedLoopTop) == 0)):
return
for indexedPointIndex in xrange(max(len(indexedLoopBottom), len(indexedLoopTop))):
indexedConvex = []
if (len(indexedLoopBottom) > 1):
indexedConvex.append(indexedLoopBottom[indexedPointIndex])
indexedConvex.append(indexedLoopBottom[((indexedPointIndex + 1) % len(indexedLoopBottom))])
else:
indexedConvex.append(indexedLoopBottom[0])
if (len(indexedLoopTop) > 1):
indexedConvex.append(indexedLoopTop[((indexedPointIndex + 1) % len(indexedLoopTop))])
indexedConvex.append(indexedLoopTop[indexedPointIndex])
else:
indexedConvex.append(indexedLoopTop[0])
addFacesByConvex(faces, indexedConvex)
|
null | null | null | What does the code add from loops ?
| def addFacesByConvexBottomTopLoop(faces, indexedLoopBottom, indexedLoopTop):
if ((len(indexedLoopBottom) == 0) or (len(indexedLoopTop) == 0)):
return
for indexedPointIndex in xrange(max(len(indexedLoopBottom), len(indexedLoopTop))):
indexedConvex = []
if (len(indexedLoopBottom) > 1):
indexedConvex.append(indexedLoopBottom[indexedPointIndex])
indexedConvex.append(indexedLoopBottom[((indexedPointIndex + 1) % len(indexedLoopBottom))])
else:
indexedConvex.append(indexedLoopBottom[0])
if (len(indexedLoopTop) > 1):
indexedConvex.append(indexedLoopTop[((indexedPointIndex + 1) % len(indexedLoopTop))])
indexedConvex.append(indexedLoopTop[indexedPointIndex])
else:
indexedConvex.append(indexedLoopTop[0])
addFacesByConvex(faces, indexedConvex)
| null | null | null | faces
| codeqa | def add Faces By Convex Bottom Top Loop faces indexed Loop Bottom indexed Loop Top if len indexed Loop Bottom 0 or len indexed Loop Top 0 returnfor indexed Point Index in xrange max len indexed Loop Bottom len indexed Loop Top indexed Convex []if len indexed Loop Bottom > 1 indexed Convex append indexed Loop Bottom[indexed Point Index] indexed Convex append indexed Loop Bottom[ indexed Point Index + 1 % len indexed Loop Bottom ] else indexed Convex append indexed Loop Bottom[ 0 ] if len indexed Loop Top > 1 indexed Convex append indexed Loop Top[ indexed Point Index + 1 % len indexed Loop Top ] indexed Convex append indexed Loop Top[indexed Point Index] else indexed Convex append indexed Loop Top[ 0 ] add Faces By Convex faces indexed Convex
| null | null | null | null | Question:
What does the code add from loops ?
Code:
def addFacesByConvexBottomTopLoop(faces, indexedLoopBottom, indexedLoopTop):
if ((len(indexedLoopBottom) == 0) or (len(indexedLoopTop) == 0)):
return
for indexedPointIndex in xrange(max(len(indexedLoopBottom), len(indexedLoopTop))):
indexedConvex = []
if (len(indexedLoopBottom) > 1):
indexedConvex.append(indexedLoopBottom[indexedPointIndex])
indexedConvex.append(indexedLoopBottom[((indexedPointIndex + 1) % len(indexedLoopBottom))])
else:
indexedConvex.append(indexedLoopBottom[0])
if (len(indexedLoopTop) > 1):
indexedConvex.append(indexedLoopTop[((indexedPointIndex + 1) % len(indexedLoopTop))])
indexedConvex.append(indexedLoopTop[indexedPointIndex])
else:
indexedConvex.append(indexedLoopTop[0])
addFacesByConvex(faces, indexedConvex)
|
null | null | null | What does the supplied function take ?
| def takes_kwargs(function):
return bool((function.__code__.co_flags & 8))
| null | null | null | keyword arguments
| codeqa | def takes kwargs function return bool function code co flags & 8
| null | null | null | null | Question:
What does the supplied function take ?
Code:
def takes_kwargs(function):
return bool((function.__code__.co_flags & 8))
|
null | null | null | What takes keyword arguments ?
| def takes_kwargs(function):
return bool((function.__code__.co_flags & 8))
| null | null | null | the supplied function
| codeqa | def takes kwargs function return bool function code co flags & 8
| null | null | null | null | Question:
What takes keyword arguments ?
Code:
def takes_kwargs(function):
return bool((function.__code__.co_flags & 8))
|
null | null | null | Does the supplied function take keyword arguments ?
| def takes_kwargs(function):
return bool((function.__code__.co_flags & 8))
| null | null | null | Yes
| codeqa | def takes kwargs function return bool function code co flags & 8
| null | null | null | null | Question:
Does the supplied function take keyword arguments ?
Code:
def takes_kwargs(function):
return bool((function.__code__.co_flags & 8))
|
null | null | null | Are backticks removed in python 3 ?
| def python_3000_backticks(logical_line):
pos = logical_line.find('`')
if (pos > (-1)):
(yield (pos, "W604 backticks are deprecated, use 'repr()'"))
| null | null | null | Yes
| codeqa | def python 3000 backticks logical line pos logical line find '`' if pos > -1 yield pos "W 604 backticksaredeprecated use'repr '"
| null | null | null | null | Question:
Are backticks removed in python 3 ?
Code:
def python_3000_backticks(logical_line):
pos = logical_line.find('`')
if (pos > (-1)):
(yield (pos, "W604 backticks are deprecated, use 'repr()'"))
|
null | null | null | What are removed in python 3 ?
| def python_3000_backticks(logical_line):
pos = logical_line.find('`')
if (pos > (-1)):
(yield (pos, "W604 backticks are deprecated, use 'repr()'"))
| null | null | null | backticks
| codeqa | def python 3000 backticks logical line pos logical line find '`' if pos > -1 yield pos "W 604 backticksaredeprecated use'repr '"
| null | null | null | null | Question:
What are removed in python 3 ?
Code:
def python_3000_backticks(logical_line):
pos = logical_line.find('`')
if (pos > (-1)):
(yield (pos, "W604 backticks are deprecated, use 'repr()'"))
|
null | null | null | Where are backticks removed ?
| def python_3000_backticks(logical_line):
pos = logical_line.find('`')
if (pos > (-1)):
(yield (pos, "W604 backticks are deprecated, use 'repr()'"))
| null | null | null | in python 3
| codeqa | def python 3000 backticks logical line pos logical line find '`' if pos > -1 yield pos "W 604 backticksaredeprecated use'repr '"
| null | null | null | null | Question:
Where are backticks removed ?
Code:
def python_3000_backticks(logical_line):
pos = logical_line.find('`')
if (pos > (-1)):
(yield (pos, "W604 backticks are deprecated, use 'repr()'"))
|
null | null | null | Does the code make matched text upper case ?
| @builtin(u'Upper-case text (ignore tags)', upper, apply_func_to_html_text)
def replace_uppercase_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
return apply_func_to_html_text(match, upper)
| null | null | null | Yes
| codeqa | @builtin u' Upper-casetext ignoretags ' upper apply func to html text def replace uppercase ignore tags match number file name metadata dictionaries data functions *args **kwargs return apply func to html text match upper
| null | null | null | null | Question:
Does the code make matched text upper case ?
Code:
@builtin(u'Upper-case text (ignore tags)', upper, apply_func_to_html_text)
def replace_uppercase_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
return apply_func_to_html_text(match, upper)
|
null | null | null | What does the code make ?
| @builtin(u'Upper-case text (ignore tags)', upper, apply_func_to_html_text)
def replace_uppercase_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
return apply_func_to_html_text(match, upper)
| null | null | null | matched text upper case
| codeqa | @builtin u' Upper-casetext ignoretags ' upper apply func to html text def replace uppercase ignore tags match number file name metadata dictionaries data functions *args **kwargs return apply func to html text match upper
| null | null | null | null | Question:
What does the code make ?
Code:
@builtin(u'Upper-case text (ignore tags)', upper, apply_func_to_html_text)
def replace_uppercase_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
return apply_func_to_html_text(match, upper)
|
null | null | null | How does class choose ?
| def iso9660(path):
IMPLEMENTATIONS = [('isoinfo', has_isoinfo, Iso9660IsoInfo), ('iso-read', has_isoread, Iso9660IsoRead), ('mount', can_mount, Iso9660Mount)]
for (name, check, klass) in IMPLEMENTATIONS:
if check():
logging.debug('Automatically chosen class for iso9660: %s', name)
return klass(path)
return None
| null | null | null | accordingly
| codeqa | def iso 9660 path IMPLEMENTATIONS [ 'isoinfo' has isoinfo Iso 9660 Iso Info 'iso-read' has isoread Iso 9660 Iso Read 'mount' can mount Iso 9660 Mount ]for name check klass in IMPLEMENTATIONS if check logging debug ' Automaticallychosenclassforiso 9660 %s' name return klass path return None
| null | null | null | null | Question:
How does class choose ?
Code:
def iso9660(path):
IMPLEMENTATIONS = [('isoinfo', has_isoinfo, Iso9660IsoInfo), ('iso-read', has_isoread, Iso9660IsoRead), ('mount', can_mount, Iso9660Mount)]
for (name, check, klass) in IMPLEMENTATIONS:
if check():
logging.debug('Automatically chosen class for iso9660: %s', name)
return klass(path)
return None
|
null | null | null | Does the code validate the beacon configuration ?
| def __validate__(config):
if (not isinstance(config, dict)):
return (False, 'Configuration for haproxy beacon must be a dictionary.')
if ('haproxy' not in config):
return (False, 'Configuration for haproxy beacon requires a list of backends and servers')
return (True, 'Valid beacon configuration')
| null | null | null | Yes
| codeqa | def validate config if not isinstance config dict return False ' Configurationforhaproxybeaconmustbeadictionary ' if 'haproxy' not in config return False ' Configurationforhaproxybeaconrequiresalistofbackendsandservers' return True ' Validbeaconconfiguration'
| null | null | null | null | Question:
Does the code validate the beacon configuration ?
Code:
def __validate__(config):
if (not isinstance(config, dict)):
return (False, 'Configuration for haproxy beacon must be a dictionary.')
if ('haproxy' not in config):
return (False, 'Configuration for haproxy beacon requires a list of backends and servers')
return (True, 'Valid beacon configuration')
|
null | null | null | What does the code validate ?
| def __validate__(config):
if (not isinstance(config, dict)):
return (False, 'Configuration for haproxy beacon must be a dictionary.')
if ('haproxy' not in config):
return (False, 'Configuration for haproxy beacon requires a list of backends and servers')
return (True, 'Valid beacon configuration')
| null | null | null | the beacon configuration
| codeqa | def validate config if not isinstance config dict return False ' Configurationforhaproxybeaconmustbeadictionary ' if 'haproxy' not in config return False ' Configurationforhaproxybeaconrequiresalistofbackendsandservers' return True ' Validbeaconconfiguration'
| null | null | null | null | Question:
What does the code validate ?
Code:
def __validate__(config):
if (not isinstance(config, dict)):
return (False, 'Configuration for haproxy beacon must be a dictionary.')
if ('haproxy' not in config):
return (False, 'Configuration for haproxy beacon requires a list of backends and servers')
return (True, 'Valid beacon configuration')
|
null | null | null | What is containing the new value for variable ?
| def set_emerge_default_opts(value):
return set_var('EMERGE_DEFAULT_OPTS', value)
| null | null | null | a dict
| codeqa | def set emerge default opts value return set var 'EMERGE DEFAULT OPTS' value
| null | null | null | null | Question:
What is containing the new value for variable ?
Code:
def set_emerge_default_opts(value):
return set_var('EMERGE_DEFAULT_OPTS', value)
|
null | null | null | Does the code interpolate the string using values from the dictionary ?
| def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
| null | null | null | Yes
| codeqa | def reparam string dictionary dictionary dictionary copy result []for live chunk in interpolate string if live v eval chunk dictionary result append sqlquote v else result append chunk return SQL Query join result ''
| null | null | null | null | Question:
Does the code interpolate the string using values from the dictionary ?
Code:
def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
|
null | null | null | Does the code take a string and a dictionary ?
| def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
| null | null | null | Yes
| codeqa | def reparam string dictionary dictionary dictionary copy result []for live chunk in interpolate string if live v eval chunk dictionary result append sqlquote v else result append chunk return SQL Query join result ''
| null | null | null | null | Question:
Does the code take a string and a dictionary ?
Code:
def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
|
null | null | null | Does the code use values from the dictionary ?
| def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
| null | null | null | Yes
| codeqa | def reparam string dictionary dictionary dictionary copy result []for live chunk in interpolate string if live v eval chunk dictionary result append sqlquote v else result append chunk return SQL Query join result ''
| null | null | null | null | Question:
Does the code use values from the dictionary ?
Code:
def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
|
null | null | null | What does the code take ?
| def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
| null | null | null | a string and a dictionary
| codeqa | def reparam string dictionary dictionary dictionary copy result []for live chunk in interpolate string if live v eval chunk dictionary result append sqlquote v else result append chunk return SQL Query join result ''
| null | null | null | null | Question:
What does the code take ?
Code:
def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
|
null | null | null | How does the code interpolate the string ?
| def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
| null | null | null | using values from the dictionary
| codeqa | def reparam string dictionary dictionary dictionary copy result []for live chunk in interpolate string if live v eval chunk dictionary result append sqlquote v else result append chunk return SQL Query join result ''
| null | null | null | null | Question:
How does the code interpolate the string ?
Code:
def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
|
null | null | null | What does the code use ?
| def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
| null | null | null | values from the dictionary
| codeqa | def reparam string dictionary dictionary dictionary copy result []for live chunk in interpolate string if live v eval chunk dictionary result append sqlquote v else result append chunk return SQL Query join result ''
| null | null | null | null | Question:
What does the code use ?
Code:
def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
|
null | null | null | What does the code interpolate using values from the dictionary ?
| def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
| null | null | null | the string
| codeqa | def reparam string dictionary dictionary dictionary copy result []for live chunk in interpolate string if live v eval chunk dictionary result append sqlquote v else result append chunk return SQL Query join result ''
| null | null | null | null | Question:
What does the code interpolate using values from the dictionary ?
Code:
def reparam(string_, dictionary):
dictionary = dictionary.copy()
result = []
for (live, chunk) in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
|
null | null | null | What is started on the server ?
| def stream_with_context(generator_or_function):
try:
gen = iter(generator_or_function)
except TypeError:
def decorator(*args, **kwargs):
gen = generator_or_function()
return stream_with_context(gen)
return update_wrapper(decorator, generator_or_function)
def generator():
ctx = _request_ctx_stack.top
if (ctx is None):
raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.')
with ctx:
(yield None)
try:
for item in gen:
(yield item)
finally:
if hasattr(gen, 'close'):
gen.close()
wrapped_g = generator()
next(wrapped_g)
return wrapped_g
| null | null | null | the response
| codeqa | def stream with context generator or function try gen iter generator or function except Type Error def decorator *args **kwargs gen generator or function return stream with context gen return update wrapper decorator generator or function def generator ctx request ctx stack topif ctx is None raise Runtime Error ' Attemptedtostreamwithcontextbuttherewasnocontextinthefirstplacetokeeparound ' with ctx yield None try for item in gen yield item finally if hasattr gen 'close' gen close wrapped g generator next wrapped g return wrapped g
| null | null | null | null | Question:
What is started on the server ?
Code:
def stream_with_context(generator_or_function):
try:
gen = iter(generator_or_function)
except TypeError:
def decorator(*args, **kwargs):
gen = generator_or_function()
return stream_with_context(gen)
return update_wrapper(decorator, generator_or_function)
def generator():
ctx = _request_ctx_stack.top
if (ctx is None):
raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.')
with ctx:
(yield None)
try:
for item in gen:
(yield item)
finally:
if hasattr(gen, 'close'):
gen.close()
wrapped_g = generator()
next(wrapped_g)
return wrapped_g
|
null | null | null | When do request contexts disappear ?
| def stream_with_context(generator_or_function):
try:
gen = iter(generator_or_function)
except TypeError:
def decorator(*args, **kwargs):
gen = generator_or_function()
return stream_with_context(gen)
return update_wrapper(decorator, generator_or_function)
def generator():
ctx = _request_ctx_stack.top
if (ctx is None):
raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.')
with ctx:
(yield None)
try:
for item in gen:
(yield item)
finally:
if hasattr(gen, 'close'):
gen.close()
wrapped_g = generator()
next(wrapped_g)
return wrapped_g
| null | null | null | when the response is started on the server
| codeqa | def stream with context generator or function try gen iter generator or function except Type Error def decorator *args **kwargs gen generator or function return stream with context gen return update wrapper decorator generator or function def generator ctx request ctx stack topif ctx is None raise Runtime Error ' Attemptedtostreamwithcontextbuttherewasnocontextinthefirstplacetokeeparound ' with ctx yield None try for item in gen yield item finally if hasattr gen 'close' gen close wrapped g generator next wrapped g return wrapped g
| null | null | null | null | Question:
When do request contexts disappear ?
Code:
def stream_with_context(generator_or_function):
try:
gen = iter(generator_or_function)
except TypeError:
def decorator(*args, **kwargs):
gen = generator_or_function()
return stream_with_context(gen)
return update_wrapper(decorator, generator_or_function)
def generator():
ctx = _request_ctx_stack.top
if (ctx is None):
raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.')
with ctx:
(yield None)
try:
for item in gen:
(yield item)
finally:
if hasattr(gen, 'close'):
gen.close()
wrapped_g = generator()
next(wrapped_g)
return wrapped_g
|
null | null | null | Is the response started on the server when ?
| def stream_with_context(generator_or_function):
try:
gen = iter(generator_or_function)
except TypeError:
def decorator(*args, **kwargs):
gen = generator_or_function()
return stream_with_context(gen)
return update_wrapper(decorator, generator_or_function)
def generator():
ctx = _request_ctx_stack.top
if (ctx is None):
raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.')
with ctx:
(yield None)
try:
for item in gen:
(yield item)
finally:
if hasattr(gen, 'close'):
gen.close()
wrapped_g = generator()
next(wrapped_g)
return wrapped_g
| null | null | null | Yes
| codeqa | def stream with context generator or function try gen iter generator or function except Type Error def decorator *args **kwargs gen generator or function return stream with context gen return update wrapper decorator generator or function def generator ctx request ctx stack topif ctx is None raise Runtime Error ' Attemptedtostreamwithcontextbuttherewasnocontextinthefirstplacetokeeparound ' with ctx yield None try for item in gen yield item finally if hasattr gen 'close' gen close wrapped g generator next wrapped g return wrapped g
| null | null | null | null | Question:
Is the response started on the server when ?
Code:
def stream_with_context(generator_or_function):
try:
gen = iter(generator_or_function)
except TypeError:
def decorator(*args, **kwargs):
gen = generator_or_function()
return stream_with_context(gen)
return update_wrapper(decorator, generator_or_function)
def generator():
ctx = _request_ctx_stack.top
if (ctx is None):
raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.')
with ctx:
(yield None)
try:
for item in gen:
(yield item)
finally:
if hasattr(gen, 'close'):
gen.close()
wrapped_g = generator()
next(wrapped_g)
return wrapped_g
|
null | null | null | Where is the response started when ?
| def stream_with_context(generator_or_function):
try:
gen = iter(generator_or_function)
except TypeError:
def decorator(*args, **kwargs):
gen = generator_or_function()
return stream_with_context(gen)
return update_wrapper(decorator, generator_or_function)
def generator():
ctx = _request_ctx_stack.top
if (ctx is None):
raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.')
with ctx:
(yield None)
try:
for item in gen:
(yield item)
finally:
if hasattr(gen, 'close'):
gen.close()
wrapped_g = generator()
next(wrapped_g)
return wrapped_g
| null | null | null | on the server
| codeqa | def stream with context generator or function try gen iter generator or function except Type Error def decorator *args **kwargs gen generator or function return stream with context gen return update wrapper decorator generator or function def generator ctx request ctx stack topif ctx is None raise Runtime Error ' Attemptedtostreamwithcontextbuttherewasnocontextinthefirstplacetokeeparound ' with ctx yield None try for item in gen yield item finally if hasattr gen 'close' gen close wrapped g generator next wrapped g return wrapped g
| null | null | null | null | Question:
Where is the response started when ?
Code:
def stream_with_context(generator_or_function):
try:
gen = iter(generator_or_function)
except TypeError:
def decorator(*args, **kwargs):
gen = generator_or_function()
return stream_with_context(gen)
return update_wrapper(decorator, generator_or_function)
def generator():
ctx = _request_ctx_stack.top
if (ctx is None):
raise RuntimeError('Attempted to stream with context but there was no context in the first place to keep around.')
with ctx:
(yield None)
try:
for item in gen:
(yield item)
finally:
if hasattr(gen, 'close'):
gen.close()
wrapped_g = generator()
next(wrapped_g)
return wrapped_g
|
null | null | null | How do a given string shorten ?
| def shorten(body, keep_header=0, keep_trailer=0):
if (keep_header and (not keep_trailer) and (len(body) > keep_header)):
return ('..%s' % body[:keep_header])
if (keep_trailer and (not keep_header) and (len(body) > keep_trailer)):
return ('..%s' % body[(- keep_header):])
if (keep_header and keep_trailer and (len(body) > (keep_header + keep_trailer))):
return ('%s .. %s' % (body[:keep_header], body[(- keep_trailer):]))
return body
| null | null | null | smartly
| codeqa | def shorten body keep header 0 keep trailer 0 if keep header and not keep trailer and len body > keep header return ' %s' % body[ keep header] if keep trailer and not keep header and len body > keep trailer return ' %s' % body[ - keep header ] if keep header and keep trailer and len body > keep header + keep trailer return '%s %s' % body[ keep header] body[ - keep trailer ] return body
| null | null | null | null | Question:
How do a given string shorten ?
Code:
def shorten(body, keep_header=0, keep_trailer=0):
if (keep_header and (not keep_trailer) and (len(body) > keep_header)):
return ('..%s' % body[:keep_header])
if (keep_trailer and (not keep_header) and (len(body) > keep_trailer)):
return ('..%s' % body[(- keep_header):])
if (keep_header and keep_trailer and (len(body) > (keep_header + keep_trailer))):
return ('%s .. %s' % (body[:keep_header], body[(- keep_trailer):]))
return body
|
null | null | null | What does the code create ?
| def make_vals(val, klass, klass_inst=None, prop=None, part=False, base64encode=False):
cinst = None
if isinstance(val, dict):
cinst = klass().loadd(val, base64encode=base64encode)
else:
try:
cinst = klass().set_text(val)
except ValueError:
if (not part):
cis = [make_vals(sval, klass, klass_inst, prop, True, base64encode) for sval in val]
setattr(klass_inst, prop, cis)
else:
raise
if part:
return cinst
elif cinst:
cis = [cinst]
setattr(klass_inst, prop, cis)
| null | null | null | a class instance with a specified value
| codeqa | def make vals val klass klass inst None prop None part False base 64 encode False cinst Noneif isinstance val dict cinst klass loadd val base 64 encode base 64 encode else try cinst klass set text val except Value Error if not part cis [make vals sval klass klass inst prop True base 64 encode for sval in val]setattr klass inst prop cis else raiseif part return cinstelif cinst cis [cinst]setattr klass inst prop cis
| null | null | null | null | Question:
What does the code create ?
Code:
def make_vals(val, klass, klass_inst=None, prop=None, part=False, base64encode=False):
cinst = None
if isinstance(val, dict):
cinst = klass().loadd(val, base64encode=base64encode)
else:
try:
cinst = klass().set_text(val)
except ValueError:
if (not part):
cis = [make_vals(sval, klass, klass_inst, prop, True, base64encode) for sval in val]
setattr(klass_inst, prop, cis)
else:
raise
if part:
return cinst
elif cinst:
cis = [cinst]
setattr(klass_inst, prop, cis)
|
null | null | null | Does the code create a class instance with a specified value ?
| def make_vals(val, klass, klass_inst=None, prop=None, part=False, base64encode=False):
cinst = None
if isinstance(val, dict):
cinst = klass().loadd(val, base64encode=base64encode)
else:
try:
cinst = klass().set_text(val)
except ValueError:
if (not part):
cis = [make_vals(sval, klass, klass_inst, prop, True, base64encode) for sval in val]
setattr(klass_inst, prop, cis)
else:
raise
if part:
return cinst
elif cinst:
cis = [cinst]
setattr(klass_inst, prop, cis)
| null | null | null | Yes
| codeqa | def make vals val klass klass inst None prop None part False base 64 encode False cinst Noneif isinstance val dict cinst klass loadd val base 64 encode base 64 encode else try cinst klass set text val except Value Error if not part cis [make vals sval klass klass inst prop True base 64 encode for sval in val]setattr klass inst prop cis else raiseif part return cinstelif cinst cis [cinst]setattr klass inst prop cis
| null | null | null | null | Question:
Does the code create a class instance with a specified value ?
Code:
def make_vals(val, klass, klass_inst=None, prop=None, part=False, base64encode=False):
cinst = None
if isinstance(val, dict):
cinst = klass().loadd(val, base64encode=base64encode)
else:
try:
cinst = klass().set_text(val)
except ValueError:
if (not part):
cis = [make_vals(sval, klass, klass_inst, prop, True, base64encode) for sval in val]
setattr(klass_inst, prop, cis)
else:
raise
if part:
return cinst
elif cinst:
cis = [cinst]
setattr(klass_inst, prop, cis)
|
null | null | null | Does the code display the login form ?
| def do_authentication(environ, start_response, authn_context, key, redirect_uri, headers=None):
logger.debug('Do authentication')
auth_info = AUTHN_BROKER.pick(authn_context)
if len(auth_info):
(method, reference) = auth_info[0]
logger.debug(('Authn chosen: %s (ref=%s)' % (method, reference)))
return method(environ, start_response, reference, key, redirect_uri, headers)
else:
resp = Unauthorized('No usable authentication method')
return resp(environ, start_response)
| null | null | null | Yes
| codeqa | def do authentication environ start response authn context key redirect uri headers None logger debug ' Doauthentication' auth info AUTHN BROKER pick authn context if len auth info method reference auth info[ 0 ]logger debug ' Authnchosen %s ref %s ' % method reference return method environ start response reference key redirect uri headers else resp Unauthorized ' Nousableauthenticationmethod' return resp environ start response
| null | null | null | null | Question:
Does the code display the login form ?
Code:
def do_authentication(environ, start_response, authn_context, key, redirect_uri, headers=None):
logger.debug('Do authentication')
auth_info = AUTHN_BROKER.pick(authn_context)
if len(auth_info):
(method, reference) = auth_info[0]
logger.debug(('Authn chosen: %s (ref=%s)' % (method, reference)))
return method(environ, start_response, reference, key, redirect_uri, headers)
else:
resp = Unauthorized('No usable authentication method')
return resp(environ, start_response)
|
null | null | null | What does the code display ?
| def do_authentication(environ, start_response, authn_context, key, redirect_uri, headers=None):
logger.debug('Do authentication')
auth_info = AUTHN_BROKER.pick(authn_context)
if len(auth_info):
(method, reference) = auth_info[0]
logger.debug(('Authn chosen: %s (ref=%s)' % (method, reference)))
return method(environ, start_response, reference, key, redirect_uri, headers)
else:
resp = Unauthorized('No usable authentication method')
return resp(environ, start_response)
| null | null | null | the login form
| codeqa | def do authentication environ start response authn context key redirect uri headers None logger debug ' Doauthentication' auth info AUTHN BROKER pick authn context if len auth info method reference auth info[ 0 ]logger debug ' Authnchosen %s ref %s ' % method reference return method environ start response reference key redirect uri headers else resp Unauthorized ' Nousableauthenticationmethod' return resp environ start response
| null | null | null | null | Question:
What does the code display ?
Code:
def do_authentication(environ, start_response, authn_context, key, redirect_uri, headers=None):
logger.debug('Do authentication')
auth_info = AUTHN_BROKER.pick(authn_context)
if len(auth_info):
(method, reference) = auth_info[0]
logger.debug(('Authn chosen: %s (ref=%s)' % (method, reference)))
return method(environ, start_response, reference, key, redirect_uri, headers)
else:
resp = Unauthorized('No usable authentication method')
return resp(environ, start_response)
|
null | null | null | For what purpose does this function truncate digests that are longer than a given elliptic curve keys length ?
| def _truncate_digest_for_ecdsa(ec_key_cdata, digest, backend):
_lib = backend._lib
_ffi = backend._ffi
group = _lib.EC_KEY_get0_group(ec_key_cdata)
with backend._tmp_bn_ctx() as bn_ctx:
order = _lib.BN_CTX_get(bn_ctx)
backend.openssl_assert((order != _ffi.NULL))
res = _lib.EC_GROUP_get_order(group, order, bn_ctx)
backend.openssl_assert((res == 1))
order_bits = _lib.BN_num_bits(order)
return _truncate_digest(digest, order_bits)
| null | null | null | so they can be signed
| codeqa | def truncate digest for ecdsa ec key cdata digest backend lib backend lib ffi backend ffigroup lib EC KEY get 0 group ec key cdata with backend tmp bn ctx as bn ctx order lib BN CTX get bn ctx backend openssl assert order ffi NULL res lib EC GROUP get order group order bn ctx backend openssl assert res 1 order bits lib BN num bits order return truncate digest digest order bits
| null | null | null | null | Question:
For what purpose does this function truncate digests that are longer than a given elliptic curve keys length ?
Code:
def _truncate_digest_for_ecdsa(ec_key_cdata, digest, backend):
_lib = backend._lib
_ffi = backend._ffi
group = _lib.EC_KEY_get0_group(ec_key_cdata)
with backend._tmp_bn_ctx() as bn_ctx:
order = _lib.BN_CTX_get(bn_ctx)
backend.openssl_assert((order != _ffi.NULL))
res = _lib.EC_GROUP_get_order(group, order, bn_ctx)
backend.openssl_assert((res == 1))
order_bits = _lib.BN_num_bits(order)
return _truncate_digest(digest, order_bits)
|
null | null | null | Does the code add a column to a table ?
| def table_add_column(table, name, col_type, session, default=None):
if isinstance(table, basestring):
table = table_schema(table, session)
if (name in table_columns(table, session)):
return
if (not isinstance(col_type, TypeEngine)):
col_type = col_type()
type_string = session.bind.engine.dialect.type_compiler.process(col_type)
statement = (u'ALTER TABLE %s ADD %s %s' % (table.name, name, type_string))
session.execute(statement)
if (default is not None):
table = table_schema(table.name, session)
if (not isinstance(default, (ColumnDefault, Sequence))):
default = ColumnDefault(default)
default._set_parent(getattr(table.c, name))
statement = table.update().values({name: default.execute(bind=session.bind)})
session.execute(statement)
| null | null | null | Yes
| codeqa | def table add column table name col type session default None if isinstance table basestring table table schema table session if name in table columns table session returnif not isinstance col type Type Engine col type col type type string session bind engine dialect type compiler process col type statement u'ALTERTABLE%s ADD%s%s' % table name name type string session execute statement if default is not None table table schema table name session if not isinstance default Column Default Sequence default Column Default default default set parent getattr table c name statement table update values {name default execute bind session bind } session execute statement
| null | null | null | null | Question:
Does the code add a column to a table ?
Code:
def table_add_column(table, name, col_type, session, default=None):
if isinstance(table, basestring):
table = table_schema(table, session)
if (name in table_columns(table, session)):
return
if (not isinstance(col_type, TypeEngine)):
col_type = col_type()
type_string = session.bind.engine.dialect.type_compiler.process(col_type)
statement = (u'ALTER TABLE %s ADD %s %s' % (table.name, name, type_string))
session.execute(statement)
if (default is not None):
table = table_schema(table.name, session)
if (not isinstance(default, (ColumnDefault, Sequence))):
default = ColumnDefault(default)
default._set_parent(getattr(table.c, name))
statement = table.update().values({name: default.execute(bind=session.bind)})
session.execute(statement)
|
null | null | null | What does the code add to a table ?
| def table_add_column(table, name, col_type, session, default=None):
if isinstance(table, basestring):
table = table_schema(table, session)
if (name in table_columns(table, session)):
return
if (not isinstance(col_type, TypeEngine)):
col_type = col_type()
type_string = session.bind.engine.dialect.type_compiler.process(col_type)
statement = (u'ALTER TABLE %s ADD %s %s' % (table.name, name, type_string))
session.execute(statement)
if (default is not None):
table = table_schema(table.name, session)
if (not isinstance(default, (ColumnDefault, Sequence))):
default = ColumnDefault(default)
default._set_parent(getattr(table.c, name))
statement = table.update().values({name: default.execute(bind=session.bind)})
session.execute(statement)
| null | null | null | a column
| codeqa | def table add column table name col type session default None if isinstance table basestring table table schema table session if name in table columns table session returnif not isinstance col type Type Engine col type col type type string session bind engine dialect type compiler process col type statement u'ALTERTABLE%s ADD%s%s' % table name name type string session execute statement if default is not None table table schema table name session if not isinstance default Column Default Sequence default Column Default default default set parent getattr table c name statement table update values {name default execute bind session bind } session execute statement
| null | null | null | null | Question:
What does the code add to a table ?
Code:
def table_add_column(table, name, col_type, session, default=None):
if isinstance(table, basestring):
table = table_schema(table, session)
if (name in table_columns(table, session)):
return
if (not isinstance(col_type, TypeEngine)):
col_type = col_type()
type_string = session.bind.engine.dialect.type_compiler.process(col_type)
statement = (u'ALTER TABLE %s ADD %s %s' % (table.name, name, type_string))
session.execute(statement)
if (default is not None):
table = table_schema(table.name, session)
if (not isinstance(default, (ColumnDefault, Sequence))):
default = ColumnDefault(default)
default._set_parent(getattr(table.c, name))
statement = table.update().values({name: default.execute(bind=session.bind)})
session.execute(statement)
|
null | null | null | What does the code write ?
| def write_cache_time(f, t):
if isinstance(t, int):
t = (t, 0)
elif isinstance(t, float):
(secs, nsecs) = divmod(t, 1.0)
t = (int(secs), int((nsecs * 1000000000)))
elif (not isinstance(t, tuple)):
raise TypeError(t)
f.write(struct.pack('>LL', *t))
| null | null | null | a cache time
| codeqa | def write cache time f t if isinstance t int t t 0 elif isinstance t float secs nsecs divmod t 1 0 t int secs int nsecs * 1000000000 elif not isinstance t tuple raise Type Error t f write struct pack '>LL' *t
| null | null | null | null | Question:
What does the code write ?
Code:
def write_cache_time(f, t):
if isinstance(t, int):
t = (t, 0)
elif isinstance(t, float):
(secs, nsecs) = divmod(t, 1.0)
t = (int(secs), int((nsecs * 1000000000)))
elif (not isinstance(t, tuple)):
raise TypeError(t)
f.write(struct.pack('>LL', *t))
|
null | null | null | Does the code write a cache time ?
| def write_cache_time(f, t):
if isinstance(t, int):
t = (t, 0)
elif isinstance(t, float):
(secs, nsecs) = divmod(t, 1.0)
t = (int(secs), int((nsecs * 1000000000)))
elif (not isinstance(t, tuple)):
raise TypeError(t)
f.write(struct.pack('>LL', *t))
| null | null | null | Yes
| codeqa | def write cache time f t if isinstance t int t t 0 elif isinstance t float secs nsecs divmod t 1 0 t int secs int nsecs * 1000000000 elif not isinstance t tuple raise Type Error t f write struct pack '>LL' *t
| null | null | null | null | Question:
Does the code write a cache time ?
Code:
def write_cache_time(f, t):
if isinstance(t, int):
t = (t, 0)
elif isinstance(t, float):
(secs, nsecs) = divmod(t, 1.0)
t = (int(secs), int((nsecs * 1000000000)))
elif (not isinstance(t, tuple)):
raise TypeError(t)
f.write(struct.pack('>LL', *t))
|
null | null | null | How do the two variables fall ?
| def covariance(X, Y, condition=None, **kwargs):
return expectation(((X - expectation(X, condition, **kwargs)) * (Y - expectation(Y, condition, **kwargs))), condition, **kwargs)
| null | null | null | together
| codeqa | def covariance X Y condition None **kwargs return expectation X - expectation X condition **kwargs * Y - expectation Y condition **kwargs condition **kwargs
| null | null | null | null | Question:
How do the two variables fall ?
Code:
def covariance(X, Y, condition=None, **kwargs):
return expectation(((X - expectation(X, condition, **kwargs)) * (Y - expectation(Y, condition, **kwargs))), condition, **kwargs)
|
null | null | null | How will the two variables rise ?
| def covariance(X, Y, condition=None, **kwargs):
return expectation(((X - expectation(X, condition, **kwargs)) * (Y - expectation(Y, condition, **kwargs))), condition, **kwargs)
| null | null | null | together
| codeqa | def covariance X Y condition None **kwargs return expectation X - expectation X condition **kwargs * Y - expectation Y condition **kwargs condition **kwargs
| null | null | null | null | Question:
How will the two variables rise ?
Code:
def covariance(X, Y, condition=None, **kwargs):
return expectation(((X - expectation(X, condition, **kwargs)) * (Y - expectation(Y, condition, **kwargs))), condition, **kwargs)
|
null | null | null | What does the code update ?
| def update_user_permissions(userid, profile='grafana', **kwargs):
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
response = requests.put('{0}/api/admin/users/{1}/permissions'.format(profile['grafana_url'], userid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get('grafana_timeout', 3))
if (response.status_code >= 400):
response.raise_for_status()
return response.json()
| null | null | null | a user password
| codeqa | def update user permissions userid profile 'grafana' **kwargs if isinstance profile string types profile salt ['config option'] profile response requests put '{ 0 }/api/admin/users/{ 1 }/permissions' format profile['grafana url'] userid json kwargs auth get auth profile headers get headers profile timeout profile get 'grafana timeout' 3 if response status code > 400 response raise for status return response json
| null | null | null | null | Question:
What does the code update ?
Code:
def update_user_permissions(userid, profile='grafana', **kwargs):
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
response = requests.put('{0}/api/admin/users/{1}/permissions'.format(profile['grafana_url'], userid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get('grafana_timeout', 3))
if (response.status_code >= 400):
response.raise_for_status()
return response.json()
|
null | null | null | Does the code update a user password ?
| def update_user_permissions(userid, profile='grafana', **kwargs):
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
response = requests.put('{0}/api/admin/users/{1}/permissions'.format(profile['grafana_url'], userid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get('grafana_timeout', 3))
if (response.status_code >= 400):
response.raise_for_status()
return response.json()
| null | null | null | Yes
| codeqa | def update user permissions userid profile 'grafana' **kwargs if isinstance profile string types profile salt ['config option'] profile response requests put '{ 0 }/api/admin/users/{ 1 }/permissions' format profile['grafana url'] userid json kwargs auth get auth profile headers get headers profile timeout profile get 'grafana timeout' 3 if response status code > 400 response raise for status return response json
| null | null | null | null | Question:
Does the code update a user password ?
Code:
def update_user_permissions(userid, profile='grafana', **kwargs):
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
response = requests.put('{0}/api/admin/users/{1}/permissions'.format(profile['grafana_url'], userid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get('grafana_timeout', 3))
if (response.status_code >= 400):
response.raise_for_status()
return response.json()
|
null | null | null | What does the code get ?
| def getNewDerivation(elementNode, prefix, sideLength):
return RotateDerivation(elementNode, prefix)
| null | null | null | new derivation
| codeqa | def get New Derivation element Node prefix side Length return Rotate Derivation element Node prefix
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewDerivation(elementNode, prefix, sideLength):
return RotateDerivation(elementNode, prefix)
|
null | null | null | What does the code kill ?
| def kill_app(proc):
try:
os.kill(proc.pid, SIGINT)
except Exception as j:
Error(('Error killing app: %s' % j))
return False
return True
| null | null | null | a process
| codeqa | def kill app proc try os kill proc pid SIGINT except Exception as j Error ' Errorkillingapp %s' % j return Falsereturn True
| null | null | null | null | Question:
What does the code kill ?
Code:
def kill_app(proc):
try:
os.kill(proc.pid, SIGINT)
except Exception as j:
Error(('Error killing app: %s' % j))
return False
return True
|
null | null | null | What does the code initialize ?
| def _init_command_completion():
log.completion.debug('Initializing command completion.')
model = miscmodels.CommandCompletionModel()
_instances[usertypes.Completion.command] = model
| null | null | null | the command completion model
| codeqa | def init command completion log completion debug ' Initializingcommandcompletion ' model miscmodels Command Completion Model instances[usertypes Completion command] model
| null | null | null | null | Question:
What does the code initialize ?
Code:
def _init_command_completion():
log.completion.debug('Initializing command completion.')
model = miscmodels.CommandCompletionModel()
_instances[usertypes.Completion.command] = model
|
null | null | null | For what purpose do methods decorate with this ?
| def authenticated(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if (not self.current_user):
if (self.request.method in ('GET', 'HEAD')):
url = self.get_login_url()
if ('?' not in url):
if urlparse.urlsplit(url).scheme:
next_url = self.request.full_url()
else:
next_url = self.request.uri
url += ('?' + urlencode(dict(next=next_url)))
self.redirect(url)
return
raise HTTPError(403)
return method(self, *args, **kwargs)
return wrapper
| null | null | null | to require that the user be logged in
| codeqa | def authenticated method @functools wraps method def wrapper self *args **kwargs if not self current user if self request method in 'GET' 'HEAD' url self get login url if '?' not in url if urlparse urlsplit url scheme next url self request full url else next url self request uriurl + '?' + urlencode dict next next url self redirect url returnraise HTTP Error 403 return method self *args **kwargs return wrapper
| null | null | null | null | Question:
For what purpose do methods decorate with this ?
Code:
def authenticated(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if (not self.current_user):
if (self.request.method in ('GET', 'HEAD')):
url = self.get_login_url()
if ('?' not in url):
if urlparse.urlsplit(url).scheme:
next_url = self.request.full_url()
else:
next_url = self.request.uri
url += ('?' + urlencode(dict(next=next_url)))
self.redirect(url)
return
raise HTTPError(403)
return method(self, *args, **kwargs)
return wrapper
|
null | null | null | What has the given * name * ?
| def import_by_name(name, prefixes=[None]):
tried = []
for prefix in prefixes:
try:
if prefix:
prefixed_name = '.'.join([prefix, name])
else:
prefixed_name = name
(obj, parent) = _import_by_name(prefixed_name)
return (prefixed_name, obj, parent)
except ImportError:
tried.append(prefixed_name)
raise ImportError(('no module named %s' % ' or '.join(tried)))
| null | null | null | a python object
| codeqa | def import by name name prefixes [ None] tried []for prefix in prefixes try if prefix prefixed name ' ' join [prefix name] else prefixed name name obj parent import by name prefixed name return prefixed name obj parent except Import Error tried append prefixed name raise Import Error 'nomodulenamed%s' % 'or' join tried
| null | null | null | null | Question:
What has the given * name * ?
Code:
def import_by_name(name, prefixes=[None]):
tried = []
for prefix in prefixes:
try:
if prefix:
prefixed_name = '.'.join([prefix, name])
else:
prefixed_name = name
(obj, parent) = _import_by_name(prefixed_name)
return (prefixed_name, obj, parent)
except ImportError:
tried.append(prefixed_name)
raise ImportError(('no module named %s' % ' or '.join(tried)))
|
null | null | null | What does a python object have ?
| def import_by_name(name, prefixes=[None]):
tried = []
for prefix in prefixes:
try:
if prefix:
prefixed_name = '.'.join([prefix, name])
else:
prefixed_name = name
(obj, parent) = _import_by_name(prefixed_name)
return (prefixed_name, obj, parent)
except ImportError:
tried.append(prefixed_name)
raise ImportError(('no module named %s' % ' or '.join(tried)))
| null | null | null | the given * name *
| codeqa | def import by name name prefixes [ None] tried []for prefix in prefixes try if prefix prefixed name ' ' join [prefix name] else prefixed name name obj parent import by name prefixed name return prefixed name obj parent except Import Error tried append prefixed name raise Import Error 'nomodulenamed%s' % 'or' join tried
| null | null | null | null | Question:
What does a python object have ?
Code:
def import_by_name(name, prefixes=[None]):
tried = []
for prefix in prefixes:
try:
if prefix:
prefixed_name = '.'.join([prefix, name])
else:
prefixed_name = name
(obj, parent) = _import_by_name(prefixed_name)
return (prefixed_name, obj, parent)
except ImportError:
tried.append(prefixed_name)
raise ImportError(('no module named %s' % ' or '.join(tried)))
|
null | null | null | By how much do fashion dominate ?
| def const_non_dominated_sort(iterable, key=(lambda x: x), allowequality=True):
items = set(iterable)
fronts = []
while items:
front = const_non_dominated_front(items, key, allowequality)
items -= front
fronts.append(front)
return fronts
| null | null | null | non
| codeqa | def const non dominated sort iterable key lambda x x allowequality True items set iterable fronts []while items front const non dominated front items key allowequality items - frontfronts append front return fronts
| null | null | null | null | Question:
By how much do fashion dominate ?
Code:
def const_non_dominated_sort(iterable, key=(lambda x: x), allowequality=True):
items = set(iterable)
fronts = []
while items:
front = const_non_dominated_front(items, key, allowequality)
items -= front
fronts.append(front)
return fronts
|
null | null | null | How is a list sorted ?
| def const_non_dominated_sort(iterable, key=(lambda x: x), allowequality=True):
items = set(iterable)
fronts = []
while items:
front = const_non_dominated_front(items, key, allowequality)
items -= front
fronts.append(front)
return fronts
| null | null | null | in a non - dominating fashion
| codeqa | def const non dominated sort iterable key lambda x x allowequality True items set iterable fronts []while items front const non dominated front items key allowequality items - frontfronts append front return fronts
| null | null | null | null | Question:
How is a list sorted ?
Code:
def const_non_dominated_sort(iterable, key=(lambda x: x), allowequality=True):
items = set(iterable)
fronts = []
while items:
front = const_non_dominated_front(items, key, allowequality)
items -= front
fronts.append(front)
return fronts
|
null | null | null | What is using the given translation_function name ?
| def do_translate(message, translation_function):
eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
global _default, _active
t = _active.get(currentThread(), None)
if (t is not None):
result = getattr(t, translation_function)(eol_message)
else:
if (_default is None):
from google.appengine._internal.django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
result = getattr(_default, translation_function)(eol_message)
if isinstance(message, SafeData):
return mark_safe(result)
return result
| null | null | null | message
| codeqa | def do translate message translation function eol message message replace '\r\n' '\n' replace '\r' '\n' global default activet active get current Thread None if t is not None result getattr t translation function eol message else if default is None from google appengine internal django conf import settings default translation settings LANGUAGE CODE result getattr default translation function eol message if isinstance message Safe Data return mark safe result return result
| null | null | null | null | Question:
What is using the given translation_function name ?
Code:
def do_translate(message, translation_function):
eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
global _default, _active
t = _active.get(currentThread(), None)
if (t is not None):
result = getattr(t, translation_function)(eol_message)
else:
if (_default is None):
from google.appengine._internal.django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
result = getattr(_default, translation_function)(eol_message)
if isinstance(message, SafeData):
return mark_safe(result)
return result
|
null | null | null | What do message use ?
| def do_translate(message, translation_function):
eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
global _default, _active
t = _active.get(currentThread(), None)
if (t is not None):
result = getattr(t, translation_function)(eol_message)
else:
if (_default is None):
from google.appengine._internal.django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
result = getattr(_default, translation_function)(eol_message)
if isinstance(message, SafeData):
return mark_safe(result)
return result
| null | null | null | the given translation_function name
| codeqa | def do translate message translation function eol message message replace '\r\n' '\n' replace '\r' '\n' global default activet active get current Thread None if t is not None result getattr t translation function eol message else if default is None from google appengine internal django conf import settings default translation settings LANGUAGE CODE result getattr default translation function eol message if isinstance message Safe Data return mark safe result return result
| null | null | null | null | Question:
What do message use ?
Code:
def do_translate(message, translation_function):
eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
global _default, _active
t = _active.get(currentThread(), None)
if (t is not None):
result = getattr(t, translation_function)(eol_message)
else:
if (_default is None):
from google.appengine._internal.django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
result = getattr(_default, translation_function)(eol_message)
if isinstance(message, SafeData):
return mark_safe(result)
return result
|
null | null | null | How does headers return ?
| def get_headers(hide_env=True):
headers = dict(request.headers.items())
if (hide_env and ('show_env' not in request.args)):
for key in ENV_HEADERS:
try:
del headers[key]
except KeyError:
pass
return CaseInsensitiveDict(headers.items())
| null | null | null | from request context
| codeqa | def get headers hide env True headers dict request headers items if hide env and 'show env' not in request args for key in ENV HEADERS try del headers[key]except Key Error passreturn Case Insensitive Dict headers items
| null | null | null | null | Question:
How does headers return ?
Code:
def get_headers(hide_env=True):
headers = dict(request.headers.items())
if (hide_env and ('show_env' not in request.args)):
for key in ENV_HEADERS:
try:
del headers[key]
except KeyError:
pass
return CaseInsensitiveDict(headers.items())
|
null | null | null | What does the code remove ?
| @error.context_aware
def lv_remove(vg_name, lv_name):
error.context(('Removing volume /dev/%s/%s' % (vg_name, lv_name)), logging.info)
if (not vg_check(vg_name)):
raise error.TestError('Volume group could not be found')
if (not lv_check(vg_name, lv_name)):
raise error.TestError('Logical volume could not be found')
cmd = ('lvremove -f %s/%s' % (vg_name, lv_name))
result = utils.run(cmd)
logging.info(result.stdout.rstrip())
| null | null | null | a logical volume
| codeqa | @error context awaredef lv remove vg name lv name error context ' Removingvolume/dev/%s/%s' % vg name lv name logging info if not vg check vg name raise error Test Error ' Volumegroupcouldnotbefound' if not lv check vg name lv name raise error Test Error ' Logicalvolumecouldnotbefound' cmd 'lvremove-f%s/%s' % vg name lv name result utils run cmd logging info result stdout rstrip
| null | null | null | null | Question:
What does the code remove ?
Code:
@error.context_aware
def lv_remove(vg_name, lv_name):
error.context(('Removing volume /dev/%s/%s' % (vg_name, lv_name)), logging.info)
if (not vg_check(vg_name)):
raise error.TestError('Volume group could not be found')
if (not lv_check(vg_name, lv_name)):
raise error.TestError('Logical volume could not be found')
cmd = ('lvremove -f %s/%s' % (vg_name, lv_name))
result = utils.run(cmd)
logging.info(result.stdout.rstrip())
|
null | null | null | How did handler deny ?
| @requires_csrf_token
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if (template_name != ERROR_403_TEMPLATE_NAME):
raise
return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
return http.HttpResponseForbidden(template.render(request=request, context={'exception': force_text(exception)}))
| null | null | null | permission
| codeqa | @requires csrf tokendef permission denied request exception template name ERROR 403 TEMPLATE NAME try template loader get template template name except Template Does Not Exist if template name ERROR 403 TEMPLATE NAME raisereturn http Http Response Forbidden '<h 1 > 403 Forbidden</h 1 >' content type 'text/html' return http Http Response Forbidden template render request request context {'exception' force text exception }
| null | null | null | null | Question:
How did handler deny ?
Code:
@requires_csrf_token
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if (template_name != ERROR_403_TEMPLATE_NAME):
raise
return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
return http.HttpResponseForbidden(template.render(request=request, context={'exception': force_text(exception)}))
|
null | null | null | What does the code require ?
| @pytest.fixture
def trans_member():
return _require_user('trans_member', 'Transactional member')
| null | null | null | a member user
| codeqa | @pytest fixturedef trans member return require user 'trans member' ' Transactionalmember'
| null | null | null | null | Question:
What does the code require ?
Code:
@pytest.fixture
def trans_member():
return _require_user('trans_member', 'Transactional member')
|
null | null | null | How do a directory tree delete ?
| def rmtree(path, ignore_errors=False, onerror=auto_chmod):
if ignore_errors:
def onerror(*args):
pass
elif (onerror is None):
def onerror(*args):
raise
names = []
try:
names = os.listdir(path)
except os.error as err:
onerror(os.listdir, path, sys.exc_info())
for name in names:
fullname = os.path.join(path, name)
try:
mode = os.lstat(fullname).st_mode
except os.error:
mode = 0
if stat.S_ISDIR(mode):
rmtree(fullname, ignore_errors, onerror)
else:
try:
os.remove(fullname)
except os.error as err:
onerror(os.remove, fullname, sys.exc_info())
try:
os.rmdir(path)
except os.error:
onerror(os.rmdir, path, sys.exc_info())
| null | null | null | recursively
| codeqa | def rmtree path ignore errors False onerror auto chmod if ignore errors def onerror *args passelif onerror is None def onerror *args raisenames []try names os listdir path except os error as err onerror os listdir path sys exc info for name in names fullname os path join path name try mode os lstat fullname st modeexcept os error mode 0if stat S ISDIR mode rmtree fullname ignore errors onerror else try os remove fullname except os error as err onerror os remove fullname sys exc info try os rmdir path except os error onerror os rmdir path sys exc info
| null | null | null | null | Question:
How do a directory tree delete ?
Code:
def rmtree(path, ignore_errors=False, onerror=auto_chmod):
if ignore_errors:
def onerror(*args):
pass
elif (onerror is None):
def onerror(*args):
raise
names = []
try:
names = os.listdir(path)
except os.error as err:
onerror(os.listdir, path, sys.exc_info())
for name in names:
fullname = os.path.join(path, name)
try:
mode = os.lstat(fullname).st_mode
except os.error:
mode = 0
if stat.S_ISDIR(mode):
rmtree(fullname, ignore_errors, onerror)
else:
try:
os.remove(fullname)
except os.error as err:
onerror(os.remove, fullname, sys.exc_info())
try:
os.rmdir(path)
except os.error:
onerror(os.rmdir, path, sys.exc_info())
|
null | null | null | What does the code create ?
| def instantiateAddCallbacksBeforeResult(n):
d = defer.Deferred()
def f(result):
return result
for i in xrange(n):
d.addCallback(f)
d.addErrback(f)
d.addBoth(f)
d.addCallbacks(f)
d.callback(1)
| null | null | null | a deferred
| codeqa | def instantiate Add Callbacks Before Result n d defer Deferred def f result return resultfor i in xrange n d add Callback f d add Errback f d add Both f d add Callbacks f d callback 1
| null | null | null | null | Question:
What does the code create ?
Code:
def instantiateAddCallbacksBeforeResult(n):
d = defer.Deferred()
def f(result):
return result
for i in xrange(n):
d.addCallback(f)
d.addErrback(f)
d.addBoth(f)
d.addCallbacks(f)
d.callback(1)
|
null | null | null | How do all files in this directory and all subdirectories check ?
| def input_dir(self, dirname):
dirname = dirname.rstrip('/')
if self.excluded(dirname):
return 0
counters = self.options.report.counters
verbose = self.options.verbose
filepatterns = self.options.filename
runner = self.runner
for (root, dirs, files) in os.walk(dirname):
if verbose:
print ('directory ' + root)
counters['directories'] += 1
for subdir in sorted(dirs):
if self.excluded(os.path.join(root, subdir)):
dirs.remove(subdir)
for filename in sorted(files):
if (pep8.filename_match(filename, filepatterns) and (not self.excluded(filename))):
runner(os.path.join(root, filename))
| null | null | null | code
| codeqa | def input dir self dirname dirname dirname rstrip '/' if self excluded dirname return 0counters self options report countersverbose self options verbosefilepatterns self options filenamerunner self runnerfor root dirs files in os walk dirname if verbose print 'directory' + root counters['directories'] + 1for subdir in sorted dirs if self excluded os path join root subdir dirs remove subdir for filename in sorted files if pep 8 filename match filename filepatterns and not self excluded filename runner os path join root filename
| null | null | null | null | Question:
How do all files in this directory and all subdirectories check ?
Code:
def input_dir(self, dirname):
dirname = dirname.rstrip('/')
if self.excluded(dirname):
return 0
counters = self.options.report.counters
verbose = self.options.verbose
filepatterns = self.options.filename
runner = self.runner
for (root, dirs, files) in os.walk(dirname):
if verbose:
print ('directory ' + root)
counters['directories'] += 1
for subdir in sorted(dirs):
if self.excluded(os.path.join(root, subdir)):
dirs.remove(subdir)
for filename in sorted(files):
if (pep8.filename_match(filename, filepatterns) and (not self.excluded(filename))):
runner(os.path.join(root, filename))
|
null | null | null | What does the code tell a file has changed ?
| def touched(dst):
import warnings
warnings.warn('macostools.touched() has been deprecated', DeprecationWarning, 2)
| null | null | null | the finder
| codeqa | def touched dst import warningswarnings warn 'macostools touched hasbeendeprecated' Deprecation Warning 2
| null | null | null | null | Question:
What does the code tell a file has changed ?
Code:
def touched(dst):
import warnings
warnings.warn('macostools.touched() has been deprecated', DeprecationWarning, 2)
|
null | null | null | How does the source directory walk ?
| def _GetFilesRecursively(path, excl_regexps=['#.*', '\\..+', '.*~$', '.*\\.pyc$', '.*_test.py$', '.*_pkg.py$']):
entries = os.listdir(path)
dirs = [e for e in entries if (os.path.isdir(os.path.join(path, e)) and _FileMatches(e, excl_regexps))]
files = [os.path.join(path, e) for e in entries if (os.path.isfile(os.path.join(path, e)) and _FileMatches(e, excl_regexps))]
for d in dirs:
files += _GetFilesRecursively(os.path.join(path, d), excl_regexps)
return files
| null | null | null | recursively
| codeqa | def Get Files Recursively path excl regexps ['# *' '\\ +' ' *~$' ' *\\ pyc$' ' * test py$' ' * pkg py$'] entries os listdir path dirs [e for e in entries if os path isdir os path join path e and File Matches e excl regexps ]files [os path join path e for e in entries if os path isfile os path join path e and File Matches e excl regexps ]for d in dirs files + Get Files Recursively os path join path d excl regexps return files
| null | null | null | null | Question:
How does the source directory walk ?
Code:
def _GetFilesRecursively(path, excl_regexps=['#.*', '\\..+', '.*~$', '.*\\.pyc$', '.*_test.py$', '.*_pkg.py$']):
entries = os.listdir(path)
dirs = [e for e in entries if (os.path.isdir(os.path.join(path, e)) and _FileMatches(e, excl_regexps))]
files = [os.path.join(path, e) for e in entries if (os.path.isfile(os.path.join(path, e)) and _FileMatches(e, excl_regexps))]
for d in dirs:
files += _GetFilesRecursively(os.path.join(path, d), excl_regexps)
return files
|
null | null | null | How does matching files locate ?
| def _GetFilesRecursively(path, excl_regexps=['#.*', '\\..+', '.*~$', '.*\\.pyc$', '.*_test.py$', '.*_pkg.py$']):
entries = os.listdir(path)
dirs = [e for e in entries if (os.path.isdir(os.path.join(path, e)) and _FileMatches(e, excl_regexps))]
files = [os.path.join(path, e) for e in entries if (os.path.isfile(os.path.join(path, e)) and _FileMatches(e, excl_regexps))]
for d in dirs:
files += _GetFilesRecursively(os.path.join(path, d), excl_regexps)
return files
| null | null | null | recursively
| codeqa | def Get Files Recursively path excl regexps ['# *' '\\ +' ' *~$' ' *\\ pyc$' ' * test py$' ' * pkg py$'] entries os listdir path dirs [e for e in entries if os path isdir os path join path e and File Matches e excl regexps ]files [os path join path e for e in entries if os path isfile os path join path e and File Matches e excl regexps ]for d in dirs files + Get Files Recursively os path join path d excl regexps return files
| null | null | null | null | Question:
How does matching files locate ?
Code:
def _GetFilesRecursively(path, excl_regexps=['#.*', '\\..+', '.*~$', '.*\\.pyc$', '.*_test.py$', '.*_pkg.py$']):
entries = os.listdir(path)
dirs = [e for e in entries if (os.path.isdir(os.path.join(path, e)) and _FileMatches(e, excl_regexps))]
files = [os.path.join(path, e) for e in entries if (os.path.isfile(os.path.join(path, e)) and _FileMatches(e, excl_regexps))]
for d in dirs:
files += _GetFilesRecursively(os.path.join(path, d), excl_regexps)
return files
|
null | null | null | What d the code get by i d ?
| def get_action_by_id(action_id):
action = None
try:
action = Action.get_by_id(action_id)
except (ValueError, ValidationError) as e:
LOG.warning('Database lookup for action with id="%s" resulted in exception: %s', action_id, e)
raise StackStormDBObjectNotFoundError(('Unable to find action with id="%s"' % action_id))
return action
| null | null | null | action
| codeqa | def get action by id action id action Nonetry action Action get by id action id except Value Error Validation Error as e LOG warning ' Databaselookupforactionwithid "%s"resultedinexception %s' action id e raise Stack Storm DB Object Not Found Error ' Unabletofindactionwithid "%s"' % action id return action
| null | null | null | null | Question:
What d the code get by i d ?
Code:
def get_action_by_id(action_id):
action = None
try:
action = Action.get_by_id(action_id)
except (ValueError, ValidationError) as e:
LOG.warning('Database lookup for action with id="%s" resulted in exception: %s', action_id, e)
raise StackStormDBObjectNotFoundError(('Unable to find action with id="%s"' % action_id))
return action
|
null | null | null | What did the code require ?
| def register(linter):
linter.register_checker(SimilarChecker(linter))
| null | null | null | method to auto register this checker
| codeqa | def register linter linter register checker Similar Checker linter
| null | null | null | null | Question:
What did the code require ?
Code:
def register(linter):
linter.register_checker(SimilarChecker(linter))
|
null | null | null | What did the code set ?
| def config(name, value):
ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
if __opts__['test']:
ret['comment'] = 'Configuring {0} to {1}'.format(name, value)
return ret
__salt__['trafficserver.set_config'](name, value)
ret['result'] = True
ret['comment'] = 'Configured {0} to {1}'.format(name, value)
return ret
| null | null | null | traffic server configuration variable values
| codeqa | def config name value ret {'name' name 'changes' {} 'result' None 'comment' ''}if opts ['test'] ret['comment'] ' Configuring{ 0 }to{ 1 }' format name value return ret salt ['trafficserver set config'] name value ret['result'] Trueret['comment'] ' Configured{ 0 }to{ 1 }' format name value return ret
| null | null | null | null | Question:
What did the code set ?
Code:
def config(name, value):
ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
if __opts__['test']:
ret['comment'] = 'Configuring {0} to {1}'.format(name, value)
return ret
__salt__['trafficserver.set_config'](name, value)
ret['result'] = True
ret['comment'] = 'Configured {0} to {1}'.format(name, value)
return ret
|
null | null | null | When do 1 return ?
| def start_x_config_set(kodi_setting, all_settings):
return '1'
| null | null | null | always
| codeqa | def start x config set kodi setting all settings return '1 '
| null | null | null | null | Question:
When do 1 return ?
Code:
def start_x_config_set(kodi_setting, all_settings):
return '1'
|
null | null | null | What does the code get ?
| def _getAccessibleAttribute(attributeName, elementNode):
if (attributeName in globalGetAccessibleAttributeSet):
return getattr(Setting(elementNode), attributeName, None)
return None
| null | null | null | the accessible attribute
| codeqa | def get Accessible Attribute attribute Name element Node if attribute Name in global Get Accessible Attribute Set return getattr Setting element Node attribute Name None return None
| null | null | null | null | Question:
What does the code get ?
Code:
def _getAccessibleAttribute(attributeName, elementNode):
if (attributeName in globalGetAccessibleAttributeSet):
return getattr(Setting(elementNode), attributeName, None)
return None
|
null | null | null | How do serial number fetch from the certificate ?
| def cert_get_serial(cert):
return cert.serial
| null | null | null | code
| codeqa | def cert get serial cert return cert serial
| null | null | null | null | Question:
How do serial number fetch from the certificate ?
Code:
def cert_get_serial(cert):
return cert.serial
|
null | null | null | What does the code get ?
| def getString(value):
return str(value)
| null | null | null | the string
| codeqa | def get String value return str value
| null | null | null | null | Question:
What does the code get ?
Code:
def getString(value):
return str(value)
|
null | null | null | What matches the literal string |s| ?
| def Str(*strs):
if (len(strs) == 1):
return Str1(strs[0])
else:
result = Alt(*tuple(map(Str1, strs)))
result.str = ('Str(%s)' % ','.join(map(repr, strs)))
return result
| null | null | null | an re
| codeqa | def Str *strs if len strs 1 return Str 1 strs[ 0 ] else result Alt *tuple map Str 1 strs result str ' Str %s ' % ' ' join map repr strs return result
| null | null | null | null | Question:
What matches the literal string |s| ?
Code:
def Str(*strs):
if (len(strs) == 1):
return Str1(strs[0])
else:
result = Alt(*tuple(map(Str1, strs)))
result.str = ('Str(%s)' % ','.join(map(repr, strs)))
return result
|
null | null | null | What do method return ?
| def bind_method(cls, name, func):
if (not PY3):
setattr(cls, name, types.MethodType(func, None, cls))
else:
setattr(cls, name, func)
| null | null | null | none
| codeqa | def bind method cls name func if not PY 3 setattr cls name types Method Type func None cls else setattr cls name func
| null | null | null | null | Question:
What do method return ?
Code:
def bind_method(cls, name, func):
if (not PY3):
setattr(cls, name, types.MethodType(func, None, cls))
else:
setattr(cls, name, func)
|
null | null | null | What returns none ?
| def bind_method(cls, name, func):
if (not PY3):
setattr(cls, name, types.MethodType(func, None, cls))
else:
setattr(cls, name, func)
| null | null | null | method
| codeqa | def bind method cls name func if not PY 3 setattr cls name types Method Type func None cls else setattr cls name func
| null | null | null | null | Question:
What returns none ?
Code:
def bind_method(cls, name, func):
if (not PY3):
setattr(cls, name, types.MethodType(func, None, cls))
else:
setattr(cls, name, func)
|
null | null | null | For what purpose does the translation object fetch ?
| def activate(language):
_active.value = translation(language)
| null | null | null | for a given tuple of application name and language
| codeqa | def activate language active value translation language
| null | null | null | null | Question:
For what purpose does the translation object fetch ?
Code:
def activate(language):
_active.value = translation(language)
|
null | null | null | What does the code get ?
| def _getAccessibleAttribute(attributeName, stringObject):
if (attributeName in globalNativeFunctionSet):
return getattr(stringObject, attributeName, None)
if (attributeName in globalAccessibleAttributeSet):
stringAttribute = StringAttribute(stringObject)
return getattr(stringAttribute, attributeName, None)
return None
| null | null | null | the accessible attribute
| codeqa | def get Accessible Attribute attribute Name string Object if attribute Name in global Native Function Set return getattr string Object attribute Name None if attribute Name in global Accessible Attribute Set string Attribute String Attribute string Object return getattr string Attribute attribute Name None return None
| null | null | null | null | Question:
What does the code get ?
Code:
def _getAccessibleAttribute(attributeName, stringObject):
if (attributeName in globalNativeFunctionSet):
return getattr(stringObject, attributeName, None)
if (attributeName in globalAccessibleAttributeSet):
stringAttribute = StringAttribute(stringObject)
return getattr(stringAttribute, attributeName, None)
return None
|
null | null | null | What does the code normalize ?
| def _norm_version(version, build=''):
l = string.split(version, '.')
if build:
l.append(build)
try:
ints = map(int, l)
except ValueError:
strings = l
else:
strings = map(str, ints)
version = string.join(strings[:3], '.')
return version
| null | null | null | the version
| codeqa | def norm version version build '' l string split version ' ' if build l append build try ints map int l except Value Error strings lelse strings map str ints version string join strings[ 3] ' ' return version
| null | null | null | null | Question:
What does the code normalize ?
Code:
def _norm_version(version, build=''):
l = string.split(version, '.')
if build:
l.append(build)
try:
ints = map(int, l)
except ValueError:
strings = l
else:
strings = map(str, ints)
version = string.join(strings[:3], '.')
return version
|
null | null | null | What does the code return using the format major ?
| def _norm_version(version, build=''):
l = string.split(version, '.')
if build:
l.append(build)
try:
ints = map(int, l)
except ValueError:
strings = l
else:
strings = map(str, ints)
version = string.join(strings[:3], '.')
return version
| null | null | null | a single version string
| codeqa | def norm version version build '' l string split version ' ' if build l append build try ints map int l except Value Error strings lelse strings map str ints version string join strings[ 3] ' ' return version
| null | null | null | null | Question:
What does the code return using the format major ?
Code:
def _norm_version(version, build=''):
l = string.split(version, '.')
if build:
l.append(build)
try:
ints = map(int, l)
except ValueError:
strings = l
else:
strings = map(str, ints)
version = string.join(strings[:3], '.')
return version
|
null | null | null | What does the code build ?
| def _norm_version(version, build=''):
l = string.split(version, '.')
if build:
l.append(build)
try:
ints = map(int, l)
except ValueError:
strings = l
else:
strings = map(str, ints)
version = string.join(strings[:3], '.')
return version
| null | null | null | strings
| codeqa | def norm version version build '' l string split version ' ' if build l append build try ints map int l except Value Error strings lelse strings map str ints version string join strings[ 3] ' ' return version
| null | null | null | null | Question:
What does the code build ?
Code:
def _norm_version(version, build=''):
l = string.split(version, '.')
if build:
l.append(build)
try:
ints = map(int, l)
except ValueError:
strings = l
else:
strings = map(str, ints)
version = string.join(strings[:3], '.')
return version
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.