labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2 values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4 values | answer stringlengths 2 905 | src stringclasses 3 values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What does the code create ?
| def create_bootstrap_script(extra_text, python_version=''):
filename = __file__
if filename.endswith('.pyc'):
filename = filename[:(-1)]
f = codecs.open(filename, 'r', encoding='utf-8')
content = f.read()
f.close()
py_exe = ('python%s' % python_version)
content = ((('#!/usr/bin/env %s\n' % py_exe) + '## WARNING: This file is generated\n') + content)
return content.replace('##EXTEND##', extra_text)
| null | null | null | a bootstrap script
| codeqa | def create bootstrap script extra text python version '' filename file if filename endswith ' pyc' filename filename[ -1 ]f codecs open filename 'r' encoding 'utf- 8 ' content f read f close py exe 'python%s' % python version content '# /usr/bin/env%s\n' % py exe + '##WARNING Thisfileisgenerated\n' + content return content replace '##EXTEND##' extra text
| null | null | null | null | Question:
What does the code create ?
Code:
def create_bootstrap_script(extra_text, python_version=''):
filename = __file__
if filename.endswith('.pyc'):
filename = filename[:(-1)]
f = codecs.open(filename, 'r', encoding='utf-8')
content = f.read()
f.close()
py_exe = ('python%s' % python_version)
content = ((('#!/usr/bin/env %s\n' % py_exe) + '## WARNING: This file is generated\n') + content)
return content.replace('##EXTEND##', extra_text)
|
null | null | null | What does the code find ?
| def intersect_trust_region(x, s, Delta):
a = np.dot(s, s)
if (a == 0):
raise ValueError('`s` is zero.')
b = np.dot(x, s)
c = (np.dot(x, x) - (Delta ** 2))
if (c > 0):
raise ValueError('`x` is not within the trust region.')
d = np.sqrt(((b * b) - (a * c)))
q = (- (b + copysign(d, b)))
t1 = (q / a)
t2 = (c / q)
if (t1 < t2):
return (t1, t2)
else:
return (t2, t1)
| null | null | null | the intersection of a line with the boundary of a trust region
| codeqa | def intersect trust region x s Delta a np dot s s if a 0 raise Value Error '`s`iszero ' b np dot x s c np dot x x - Delta ** 2 if c > 0 raise Value Error '`x`isnotwithinthetrustregion ' d np sqrt b * b - a * c q - b + copysign d b t1 q / a t2 c / q if t1 < t2 return t1 t2 else return t2 t1
| null | null | null | null | Question:
What does the code find ?
Code:
def intersect_trust_region(x, s, Delta):
a = np.dot(s, s)
if (a == 0):
raise ValueError('`s` is zero.')
b = np.dot(x, s)
c = (np.dot(x, x) - (Delta ** 2))
if (c > 0):
raise ValueError('`x` is not within the trust region.')
d = np.sqrt(((b * b) - (a * c)))
q = (- (b + copysign(d, b)))
t1 = (q / a)
t2 = (c / q)
if (t1 < t2):
return (t1, t2)
else:
return (t2, t1)
|
null | null | null | Where do they appear ?
| def get_alias(ip):
hosts = _list_hosts()
if (ip in hosts):
return hosts[ip]
return []
| null | null | null | in which
| codeqa | def get alias ip hosts list hosts if ip in hosts return hosts[ip]return []
| null | null | null | null | Question:
Where do they appear ?
Code:
def get_alias(ip):
hosts = _list_hosts()
if (ip in hosts):
return hosts[ip]
return []
|
null | null | null | What do user merge ?
| @pytest.mark.django_db
def test_merge_user(en_tutorial_po, member, member2):
unit = _create_submission_and_suggestion(en_tutorial_po, member)
accounts.utils.UserMerger(member, member2).merge()
_test_user_merged(unit, member, member2)
| null | null | null | to another user
| codeqa | @pytest mark django dbdef test merge user en tutorial po member member 2 unit create submission and suggestion en tutorial po member accounts utils User Merger member member 2 merge test user merged unit member member 2
| null | null | null | null | Question:
What do user merge ?
Code:
@pytest.mark.django_db
def test_merge_user(en_tutorial_po, member, member2):
unit = _create_submission_and_suggestion(en_tutorial_po, member)
accounts.utils.UserMerger(member, member2).merge()
_test_user_merged(unit, member, member2)
|
null | null | null | What do them use ?
| def get_verifier(context, img_signature_certificate_uuid, img_signature_hash_method, img_signature, img_signature_key_type):
image_meta_props = {'img_signature_uuid': img_signature_certificate_uuid, 'img_signature_hash_method': img_signature_hash_method, 'img_signature': img_signature, 'img_signature_key_type': img_signature_key_type}
for key in image_meta_props.keys():
if (image_meta_props[key] is None):
raise exception.SignatureVerificationError(reason=(_('Required image properties for signature verification do not exist. Cannot verify signature. Missing property: %s') % key))
signature = get_signature(img_signature)
hash_method = get_hash_method(img_signature_hash_method)
signature_key_type = SignatureKeyType.lookup(img_signature_key_type)
public_key = get_public_key(context, img_signature_certificate_uuid, signature_key_type)
verifier = signature_key_type.create_verifier(signature, hash_method, public_key)
if verifier:
return verifier
else:
raise exception.SignatureVerificationError(reason=_('Error occurred while creating the verifier'))
| null | null | null | to create a verifier
| codeqa | def get verifier context img signature certificate uuid img signature hash method img signature img signature key type image meta props {'img signature uuid' img signature certificate uuid 'img signature hash method' img signature hash method 'img signature' img signature 'img signature key type' img signature key type}for key in image meta props keys if image meta props[key] is None raise exception Signature Verification Error reason ' Requiredimagepropertiesforsignatureverificationdonotexist Cannotverifysignature Missingproperty %s' % key signature get signature img signature hash method get hash method img signature hash method signature key type Signature Key Type lookup img signature key type public key get public key context img signature certificate uuid signature key type verifier signature key type create verifier signature hash method public key if verifier return verifierelse raise exception Signature Verification Error reason ' Erroroccurredwhilecreatingtheverifier'
| null | null | null | null | Question:
What do them use ?
Code:
def get_verifier(context, img_signature_certificate_uuid, img_signature_hash_method, img_signature, img_signature_key_type):
image_meta_props = {'img_signature_uuid': img_signature_certificate_uuid, 'img_signature_hash_method': img_signature_hash_method, 'img_signature': img_signature, 'img_signature_key_type': img_signature_key_type}
for key in image_meta_props.keys():
if (image_meta_props[key] is None):
raise exception.SignatureVerificationError(reason=(_('Required image properties for signature verification do not exist. Cannot verify signature. Missing property: %s') % key))
signature = get_signature(img_signature)
hash_method = get_hash_method(img_signature_hash_method)
signature_key_type = SignatureKeyType.lookup(img_signature_key_type)
public_key = get_public_key(context, img_signature_certificate_uuid, signature_key_type)
verifier = signature_key_type.create_verifier(signature, hash_method, public_key)
if verifier:
return verifier
else:
raise exception.SignatureVerificationError(reason=_('Error occurred while creating the verifier'))
|
null | null | null | What do the list of base classes provide ?
| def _ancestors_to_call(klass_node, method='__init__'):
to_call = {}
for base_node in klass_node.ancestors(recurs=False):
try:
to_call[base_node] = next(base_node.igetattr(method))
except astroid.InferenceError:
continue
return to_call
| null | null | null | the queried method
| codeqa | def ancestors to call klass node method ' init ' to call {}for base node in klass node ancestors recurs False try to call[base node] next base node igetattr method except astroid Inference Error continuereturn to call
| null | null | null | null | Question:
What do the list of base classes provide ?
Code:
def _ancestors_to_call(klass_node, method='__init__'):
to_call = {}
for base_node in klass_node.ancestors(recurs=False):
try:
to_call[base_node] = next(base_node.igetattr(method))
except astroid.InferenceError:
continue
return to_call
|
null | null | null | What is providing the queried method ?
| def _ancestors_to_call(klass_node, method='__init__'):
to_call = {}
for base_node in klass_node.ancestors(recurs=False):
try:
to_call[base_node] = next(base_node.igetattr(method))
except astroid.InferenceError:
continue
return to_call
| null | null | null | the list of base classes
| codeqa | def ancestors to call klass node method ' init ' to call {}for base node in klass node ancestors recurs False try to call[base node] next base node igetattr method except astroid Inference Error continuereturn to call
| null | null | null | null | Question:
What is providing the queried method ?
Code:
def _ancestors_to_call(klass_node, method='__init__'):
to_call = {}
for base_node in klass_node.ancestors(recurs=False):
try:
to_call[base_node] = next(base_node.igetattr(method))
except astroid.InferenceError:
continue
return to_call
|
null | null | null | Where are keys are the list of base classes providing the queried method ?
| def _ancestors_to_call(klass_node, method='__init__'):
to_call = {}
for base_node in klass_node.ancestors(recurs=False):
try:
to_call[base_node] = next(base_node.igetattr(method))
except astroid.InferenceError:
continue
return to_call
| null | null | null | a dictionary
| codeqa | def ancestors to call klass node method ' init ' to call {}for base node in klass node ancestors recurs False try to call[base node] next base node igetattr method except astroid Inference Error continuereturn to call
| null | null | null | null | Question:
Where are keys are the list of base classes providing the queried method ?
Code:
def _ancestors_to_call(klass_node, method='__init__'):
to_call = {}
for base_node in klass_node.ancestors(recurs=False):
try:
to_call[base_node] = next(base_node.igetattr(method))
except astroid.InferenceError:
continue
return to_call
|
null | null | null | What does the code start ?
| def salt_master():
import salt.cli.daemons
master = salt.cli.daemons.Master()
master.start()
| null | null | null | the salt master
| codeqa | def salt master import salt cli daemonsmaster salt cli daemons Master master start
| null | null | null | null | Question:
What does the code start ?
Code:
def salt_master():
import salt.cli.daemons
master = salt.cli.daemons.Master()
master.start()
|
null | null | null | What did the code set ?
| def setExtendedPoint(lineSegmentEnd, pointOriginal, x):
if ((x > min(lineSegmentEnd.point.real, pointOriginal.real)) and (x < max(lineSegmentEnd.point.real, pointOriginal.real))):
lineSegmentEnd.point = complex(x, pointOriginal.imag)
| null | null | null | the point in the extended line segment
| codeqa | def set Extended Point line Segment End point Original x if x > min line Segment End point real point Original real and x < max line Segment End point real point Original real line Segment End point complex x point Original imag
| null | null | null | null | Question:
What did the code set ?
Code:
def setExtendedPoint(lineSegmentEnd, pointOriginal, x):
if ((x > min(lineSegmentEnd.point.real, pointOriginal.real)) and (x < max(lineSegmentEnd.point.real, pointOriginal.real))):
lineSegmentEnd.point = complex(x, pointOriginal.imag)
|
null | null | null | What does the code clear ?
| def Clf():
global LOC
LOC = None
_Brewer.ClearIter()
pyplot.clf()
fig = pyplot.gcf()
fig.set_size_inches(8, 6)
| null | null | null | the figure and any hints that have been set
| codeqa | def Clf global LOCLOC None Brewer Clear Iter pyplot clf fig pyplot gcf fig set size inches 8 6
| null | null | null | null | Question:
What does the code clear ?
Code:
def Clf():
global LOC
LOC = None
_Brewer.ClearIter()
pyplot.clf()
fig = pyplot.gcf()
fig.set_size_inches(8, 6)
|
null | null | null | What does the code return ?
| def format_user(user, show_url=True):
out = '\x02{}\x02'.format(user['username'])
if user['description']:
out += ': "{}"'.format(formatting.truncate(user['description']))
if user['city']:
out += ': {}'.format(user['city'])
if user['country']:
out += ', {}'.format(formatting.truncate(user['country']))
out += ' - \x02{track_count:,}\x02 tracks, \x02{playlist_count:,}\x02 playlists, \x02{followers_count:,}\x02 followers, \x02{followings_count:,}\x02 followed'.format(**user)
if show_url:
out += ' - {}'.format(web.try_shorten(user['permalink_url']))
return out
| null | null | null | a formatted string
| codeqa | def format user user show url True out '\x 02 {}\x 02 ' format user['username'] if user['description'] out + ' "{}"' format formatting truncate user['description'] if user['city'] out + ' {}' format user['city'] if user['country'] out + ' {}' format formatting truncate user['country'] out + '-\x 02 {track count }\x 02 tracks \x 02 {playlist count }\x 02 playlists \x 02 {followers count }\x 02 followers \x 02 {followings count }\x 02 followed' format **user if show url out + '-{}' format web try shorten user['permalink url'] return out
| null | null | null | null | Question:
What does the code return ?
Code:
def format_user(user, show_url=True):
out = '\x02{}\x02'.format(user['username'])
if user['description']:
out += ': "{}"'.format(formatting.truncate(user['description']))
if user['city']:
out += ': {}'.format(user['city'])
if user['country']:
out += ', {}'.format(formatting.truncate(user['country']))
out += ' - \x02{track_count:,}\x02 tracks, \x02{playlist_count:,}\x02 playlists, \x02{followers_count:,}\x02 followers, \x02{followings_count:,}\x02 followed'.format(**user)
if show_url:
out += ' - {}'.format(web.try_shorten(user['permalink_url']))
return out
|
null | null | null | What must bucket names not contain ?
| def check_lowercase_bucketname(n):
if (not (n + 'a').islower()):
raise BotoClientError('Bucket names cannot contain upper-case characters when using either the sub-domain or virtual hosting calling format.')
return True
| null | null | null | uppercase characters
| codeqa | def check lowercase bucketname n if not n + 'a' islower raise Boto Client Error ' Bucketnamescannotcontainupper-casecharacterswhenusingeitherthesub-domainorvirtualhostingcallingformat ' return True
| null | null | null | null | Question:
What must bucket names not contain ?
Code:
def check_lowercase_bucketname(n):
if (not (n + 'a').islower()):
raise BotoClientError('Bucket names cannot contain upper-case characters when using either the sub-domain or virtual hosting calling format.')
return True
|
null | null | null | Must bucket names contain uppercase characters ?
| def check_lowercase_bucketname(n):
if (not (n + 'a').islower()):
raise BotoClientError('Bucket names cannot contain upper-case characters when using either the sub-domain or virtual hosting calling format.')
return True
| null | null | null | No
| codeqa | def check lowercase bucketname n if not n + 'a' islower raise Boto Client Error ' Bucketnamescannotcontainupper-casecharacterswhenusingeitherthesub-domainorvirtualhostingcallingformat ' return True
| null | null | null | null | Question:
Must bucket names contain uppercase characters ?
Code:
def check_lowercase_bucketname(n):
if (not (n + 'a').islower()):
raise BotoClientError('Bucket names cannot contain upper-case characters when using either the sub-domain or virtual hosting calling format.')
return True
|
null | null | null | What must not contain uppercase characters ?
| def check_lowercase_bucketname(n):
if (not (n + 'a').islower()):
raise BotoClientError('Bucket names cannot contain upper-case characters when using either the sub-domain or virtual hosting calling format.')
return True
| null | null | null | bucket names
| codeqa | def check lowercase bucketname n if not n + 'a' islower raise Boto Client Error ' Bucketnamescannotcontainupper-casecharacterswhenusingeitherthesub-domainorvirtualhostingcallingformat ' return True
| null | null | null | null | Question:
What must not contain uppercase characters ?
Code:
def check_lowercase_bucketname(n):
if (not (n + 'a').islower()):
raise BotoClientError('Bucket names cannot contain upper-case characters when using either the sub-domain or virtual hosting calling format.')
return True
|
null | null | null | What does the code send ?
| def put(url, data=None, **kwargs):
return request('put', url, data=data, **kwargs)
| null | null | null | a put request
| codeqa | def put url data None **kwargs return request 'put' url data data **kwargs
| null | null | null | null | Question:
What does the code send ?
Code:
def put(url, data=None, **kwargs):
return request('put', url, data=data, **kwargs)
|
null | null | null | When does that be in second ?
| def assertIn(first, second, msg=''):
(a, b) = (first, second)
assert (a in b), ('%s: %r is not in %r' % (msg.format(a, b), a, b))
| null | null | null | first
| codeqa | def assert In first second msg '' a b first second assert a in b '%s %risnotin%r' % msg format a b a b
| null | null | null | null | Question:
When does that be in second ?
Code:
def assertIn(first, second, msg=''):
(a, b) = (first, second)
assert (a in b), ('%s: %r is not in %r' % (msg.format(a, b), a, b))
|
null | null | null | What does the code calculate ?
| def queens_fitness(genome):
fitness = 0
for check_queen_col in range(len(genome)):
is_attacked = 0
for other_queen_col in range(len(genome)):
if (check_queen_col != other_queen_col):
check_queen_row = int(genome[check_queen_col])
other_queen_row = int(genome[other_queen_col])
if (check_queen_row == other_queen_row):
is_attacked = 1
break
elif (abs((check_queen_row - other_queen_row)) == abs((check_queen_col - other_queen_col))):
is_attacked = 1
break
if (not is_attacked):
fitness += 1
return fitness
| null | null | null | the fitness of an organization of queens on the chessboard
| codeqa | def queens fitness genome fitness 0for check queen col in range len genome is attacked 0for other queen col in range len genome if check queen col other queen col check queen row int genome[check queen col] other queen row int genome[other queen col] if check queen row other queen row is attacked 1breakelif abs check queen row - other queen row abs check queen col - other queen col is attacked 1breakif not is attacked fitness + 1return fitness
| null | null | null | null | Question:
What does the code calculate ?
Code:
def queens_fitness(genome):
fitness = 0
for check_queen_col in range(len(genome)):
is_attacked = 0
for other_queen_col in range(len(genome)):
if (check_queen_col != other_queen_col):
check_queen_row = int(genome[check_queen_col])
other_queen_row = int(genome[other_queen_col])
if (check_queen_row == other_queen_row):
is_attacked = 1
break
elif (abs((check_queen_row - other_queen_row)) == abs((check_queen_col - other_queen_col))):
is_attacked = 1
break
if (not is_attacked):
fitness += 1
return fitness
|
null | null | null | What is using various interfaces ?
| def test_preprocess():
try:
keys = [('PYLEARN2_' + str(uuid.uuid1())[:8]) for _ in xrange(3)]
strs = [('${%s}' % k) for k in keys]
os.environ[keys[0]] = keys[1]
assert (preprocess(strs[0]) == keys[1])
assert (preprocess(strs[1], environ={keys[1]: keys[2]}) == keys[2])
assert (preprocess(strs[0], environ={keys[0]: keys[2]}) == keys[2])
raised = False
try:
preprocess(strs[2], environ={keys[1]: keys[0]})
except ValueError:
raised = True
assert raised
finally:
for key in keys:
if (key in os.environ):
del os.environ[key]
| null | null | null | that preprocess
| codeqa | def test preprocess try keys [ 'PYLEARN 2 ' + str uuid uuid 1 [ 8] for in xrange 3 ]strs [ '${%s}' % k for k in keys]os environ[keys[ 0 ]] keys[ 1 ]assert preprocess strs[ 0 ] keys[ 1 ] assert preprocess strs[ 1 ] environ {keys[ 1 ] keys[ 2 ]} keys[ 2 ] assert preprocess strs[ 0 ] environ {keys[ 0 ] keys[ 2 ]} keys[ 2 ] raised Falsetry preprocess strs[ 2 ] environ {keys[ 1 ] keys[ 0 ]} except Value Error raised Trueassert raisedfinally for key in keys if key in os environ del os environ[key]
| null | null | null | null | Question:
What is using various interfaces ?
Code:
def test_preprocess():
try:
keys = [('PYLEARN2_' + str(uuid.uuid1())[:8]) for _ in xrange(3)]
strs = [('${%s}' % k) for k in keys]
os.environ[keys[0]] = keys[1]
assert (preprocess(strs[0]) == keys[1])
assert (preprocess(strs[1], environ={keys[1]: keys[2]}) == keys[2])
assert (preprocess(strs[0], environ={keys[0]: keys[2]}) == keys[2])
raised = False
try:
preprocess(strs[2], environ={keys[1]: keys[0]})
except ValueError:
raised = True
assert raised
finally:
for key in keys:
if (key in os.environ):
del os.environ[key]
|
null | null | null | What returns the default value for a key in the registry ?
| def GetRegistryDefaultValue(subkey, rootkey=None):
if (rootkey is None):
rootkey = GetRootKey()
return win32api.RegQueryValue(rootkey, subkey)
| null | null | null | a helper
| codeqa | def Get Registry Default Value subkey rootkey None if rootkey is None rootkey Get Root Key return win 32 api Reg Query Value rootkey subkey
| null | null | null | null | Question:
What returns the default value for a key in the registry ?
Code:
def GetRegistryDefaultValue(subkey, rootkey=None):
if (rootkey is None):
rootkey = GetRootKey()
return win32api.RegQueryValue(rootkey, subkey)
|
null | null | null | When did between 2 possible properties choose ?
| def choose_int(g1, g2):
(v1, c1) = g1
(v2, c2) = g2
if (v1 == v2):
return (v1, (1 - ((1 - c1) * (1 - c2))))
elif (c1 > c2):
return (v1, (c1 - c2))
else:
return (v2, (c2 - c1))
| null | null | null | when they are integers
| codeqa | def choose int g1 g2 v1 c1 g1 v2 c2 g2 if v1 v2 return v1 1 - 1 - c1 * 1 - c2 elif c1 > c2 return v1 c1 - c2 else return v2 c2 - c1
| null | null | null | null | Question:
When did between 2 possible properties choose ?
Code:
def choose_int(g1, g2):
(v1, c1) = g1
(v2, c2) = g2
if (v1 == v2):
return (v1, (1 - ((1 - c1) * (1 - c2))))
elif (c1 > c2):
return (v1, (c1 - c2))
else:
return (v2, (c2 - c1))
|
null | null | null | What used to choose between 2 possible properties when they are integers function ?
| def choose_int(g1, g2):
(v1, c1) = g1
(v2, c2) = g2
if (v1 == v2):
return (v1, (1 - ((1 - c1) * (1 - c2))))
elif (c1 > c2):
return (v1, (c1 - c2))
else:
return (v2, (c2 - c1))
| null | null | null | by merge_similar_guesses
| codeqa | def choose int g1 g2 v1 c1 g1 v2 c2 g2 if v1 v2 return v1 1 - 1 - c1 * 1 - c2 elif c1 > c2 return v1 c1 - c2 else return v2 c2 - c1
| null | null | null | null | Question:
What used to choose between 2 possible properties when they are integers function ?
Code:
def choose_int(g1, g2):
(v1, c1) = g1
(v2, c2) = g2
if (v1 == v2):
return (v1, (1 - ((1 - c1) * (1 - c2))))
elif (c1 > c2):
return (v1, (c1 - c2))
else:
return (v2, (c2 - c1))
|
null | null | null | What does the code locate by name or dotted path ?
| def locate(path, forceload=0):
parts = [part for part in split(path, '.') if part]
(module, n) = (None, 0)
while (n < len(parts)):
nextmodule = safeimport(join(parts[:(n + 1)], '.'), forceload)
if nextmodule:
(module, n) = (nextmodule, (n + 1))
else:
break
if module:
object = module
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
elif hasattr(__builtin__, path):
return getattr(__builtin__, path)
| null | null | null | an object
| codeqa | def locate path forceload 0 parts [part for part in split path ' ' if part] module n None 0 while n < len parts nextmodule safeimport join parts[ n + 1 ] ' ' forceload if nextmodule module n nextmodule n + 1 else breakif module object modulefor part in parts[n ] try object getattr object part except Attribute Error return Nonereturn objectelif hasattr builtin path return getattr builtin path
| null | null | null | null | Question:
What does the code locate by name or dotted path ?
Code:
def locate(path, forceload=0):
parts = [part for part in split(path, '.') if part]
(module, n) = (None, 0)
while (n < len(parts)):
nextmodule = safeimport(join(parts[:(n + 1)], '.'), forceload)
if nextmodule:
(module, n) = (nextmodule, (n + 1))
else:
break
if module:
object = module
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
elif hasattr(__builtin__, path):
return getattr(__builtin__, path)
|
null | null | null | How does the code locate an object ?
| def locate(path, forceload=0):
parts = [part for part in split(path, '.') if part]
(module, n) = (None, 0)
while (n < len(parts)):
nextmodule = safeimport(join(parts[:(n + 1)], '.'), forceload)
if nextmodule:
(module, n) = (nextmodule, (n + 1))
else:
break
if module:
object = module
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
elif hasattr(__builtin__, path):
return getattr(__builtin__, path)
| null | null | null | by name or dotted path
| codeqa | def locate path forceload 0 parts [part for part in split path ' ' if part] module n None 0 while n < len parts nextmodule safeimport join parts[ n + 1 ] ' ' forceload if nextmodule module n nextmodule n + 1 else breakif module object modulefor part in parts[n ] try object getattr object part except Attribute Error return Nonereturn objectelif hasattr builtin path return getattr builtin path
| null | null | null | null | Question:
How does the code locate an object ?
Code:
def locate(path, forceload=0):
parts = [part for part in split(path, '.') if part]
(module, n) = (None, 0)
while (n < len(parts)):
nextmodule = safeimport(join(parts[:(n + 1)], '.'), forceload)
if nextmodule:
(module, n) = (nextmodule, (n + 1))
else:
break
if module:
object = module
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
elif hasattr(__builtin__, path):
return getattr(__builtin__, path)
|
null | null | null | What does the code create by loading the current server - side document ?
| def pull_session(session_id=None, url='default', app_path='/', io_loop=None):
coords = _SessionCoordinates(dict(session_id=session_id, url=url, app_path=app_path))
session = ClientSession(session_id=session_id, websocket_url=coords.websocket_url, io_loop=io_loop)
session.pull()
return session
| null | null | null | a session
| codeqa | def pull session session id None url 'default' app path '/' io loop None coords Session Coordinates dict session id session id url url app path app path session Client Session session id session id websocket url coords websocket url io loop io loop session pull return session
| null | null | null | null | Question:
What does the code create by loading the current server - side document ?
Code:
def pull_session(session_id=None, url='default', app_path='/', io_loop=None):
coords = _SessionCoordinates(dict(session_id=session_id, url=url, app_path=app_path))
session = ClientSession(session_id=session_id, websocket_url=coords.websocket_url, io_loop=io_loop)
session.pull()
return session
|
null | null | null | How does the code create a session ?
| def pull_session(session_id=None, url='default', app_path='/', io_loop=None):
coords = _SessionCoordinates(dict(session_id=session_id, url=url, app_path=app_path))
session = ClientSession(session_id=session_id, websocket_url=coords.websocket_url, io_loop=io_loop)
session.pull()
return session
| null | null | null | by loading the current server - side document
| codeqa | def pull session session id None url 'default' app path '/' io loop None coords Session Coordinates dict session id session id url url app path app path session Client Session session id session id websocket url coords websocket url io loop io loop session pull return session
| null | null | null | null | Question:
How does the code create a session ?
Code:
def pull_session(session_id=None, url='default', app_path='/', io_loop=None):
coords = _SessionCoordinates(dict(session_id=session_id, url=url, app_path=app_path))
session = ClientSession(session_id=session_id, websocket_url=coords.websocket_url, io_loop=io_loop)
session.pull()
return session
|
null | null | null | When do less room take ?
| def datetime_f(dttm):
if dttm:
dttm = dttm.isoformat()
now_iso = datetime.now().isoformat()
if (now_iso[:10] == dttm[:10]):
dttm = dttm[11:]
elif (now_iso[:4] == dttm[:4]):
dttm = dttm[5:]
return u'<nobr>{}</nobr>'.format(dttm)
| null | null | null | when it is recent
| codeqa | def datetime f dttm if dttm dttm dttm isoformat now iso datetime now isoformat if now iso[ 10 ] dttm[ 10 ] dttm dttm[ 11 ]elif now iso[ 4] dttm[ 4] dttm dttm[ 5 ]return u'<nobr>{}</nobr>' format dttm
| null | null | null | null | Question:
When do less room take ?
Code:
def datetime_f(dttm):
if dttm:
dttm = dttm.isoformat()
now_iso = datetime.now().isoformat()
if (now_iso[:10] == dttm[:10]):
dttm = dttm[11:]
elif (now_iso[:4] == dttm[:4]):
dttm = dttm[5:]
return u'<nobr>{}</nobr>'.format(dttm)
|
null | null | null | How do a test skip ?
| def skip(reason):
def decorator(test_item):
if (isinstance(test_item, type) and issubclass(test_item, TestCase)):
test_item.__unittest_skip__ = True
test_item.__unittest_skip_why__ = reason
return test_item
@functools.wraps(test_item)
def skip_wrapper(*args, **kwargs):
raise SkipTest(reason)
return skip_wrapper
return decorator
| null | null | null | unconditionally
| codeqa | def skip reason def decorator test item if isinstance test item type and issubclass test item Test Case test item unittest skip Truetest item unittest skip why reasonreturn test item@functools wraps test item def skip wrapper *args **kwargs raise Skip Test reason return skip wrapperreturn decorator
| null | null | null | null | Question:
How do a test skip ?
Code:
def skip(reason):
def decorator(test_item):
if (isinstance(test_item, type) and issubclass(test_item, TestCase)):
test_item.__unittest_skip__ = True
test_item.__unittest_skip_why__ = reason
return test_item
@functools.wraps(test_item)
def skip_wrapper(*args, **kwargs):
raise SkipTest(reason)
return skip_wrapper
return decorator
|
null | null | null | What does the code ensure ?
| def fixup_namespace_packages(path_item, parent=None):
imp.acquire_lock()
try:
for package in _namespace_packages.get(parent, ()):
subpath = _handle_ns(package, path_item)
if subpath:
fixup_namespace_packages(subpath, package)
finally:
imp.release_lock()
| null | null | null | that previously - declared namespace packages include path_item
| codeqa | def fixup namespace packages path item parent None imp acquire lock try for package in namespace packages get parent subpath handle ns package path item if subpath fixup namespace packages subpath package finally imp release lock
| null | null | null | null | Question:
What does the code ensure ?
Code:
def fixup_namespace_packages(path_item, parent=None):
imp.acquire_lock()
try:
for package in _namespace_packages.get(parent, ()):
subpath = _handle_ns(package, path_item)
if subpath:
fixup_namespace_packages(subpath, package)
finally:
imp.release_lock()
|
null | null | null | When did namespace packages declare ?
| def fixup_namespace_packages(path_item, parent=None):
imp.acquire_lock()
try:
for package in _namespace_packages.get(parent, ()):
subpath = _handle_ns(package, path_item)
if subpath:
fixup_namespace_packages(subpath, package)
finally:
imp.release_lock()
| null | null | null | previously
| codeqa | def fixup namespace packages path item parent None imp acquire lock try for package in namespace packages get parent subpath handle ns package path item if subpath fixup namespace packages subpath package finally imp release lock
| null | null | null | null | Question:
When did namespace packages declare ?
Code:
def fixup_namespace_packages(path_item, parent=None):
imp.acquire_lock()
try:
for package in _namespace_packages.get(parent, ()):
subpath = _handle_ns(package, path_item)
if subpath:
fixup_namespace_packages(subpath, package)
finally:
imp.release_lock()
|
null | null | null | What does the code kill ?
| @register(u'unix-word-rubout')
def unix_word_rubout(event, WORD=True):
buff = event.current_buffer
pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD)
if (pos is None):
pos = (- buff.cursor_position)
if pos:
deleted = buff.delete_before_cursor(count=(- pos))
if event.is_repeat:
deleted += event.cli.clipboard.get_data().text
event.cli.clipboard.set_text(deleted)
else:
event.cli.output.bell()
| null | null | null | the word behind point
| codeqa | @register u'unix-word-rubout' def unix word rubout event WORD True buff event current bufferpos buff document find start of previous word count event arg WORD WORD if pos is None pos - buff cursor position if pos deleted buff delete before cursor count - pos if event is repeat deleted + event cli clipboard get data textevent cli clipboard set text deleted else event cli output bell
| null | null | null | null | Question:
What does the code kill ?
Code:
@register(u'unix-word-rubout')
def unix_word_rubout(event, WORD=True):
buff = event.current_buffer
pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD)
if (pos is None):
pos = (- buff.cursor_position)
if pos:
deleted = buff.delete_before_cursor(count=(- pos))
if event.is_repeat:
deleted += event.cli.clipboard.get_data().text
event.cli.clipboard.set_text(deleted)
else:
event.cli.output.bell()
|
null | null | null | What did the code rectify ?
| def relu(x, alpha=0.0, max_value=None):
if (alpha != 0.0):
negative_part = tf.nn.relu((- x))
x = tf.nn.relu(x)
if (max_value is not None):
max_value = _to_tensor(max_value, x.dtype.base_dtype)
zero = _to_tensor(0.0, x.dtype.base_dtype)
x = tf.clip_by_value(x, zero, max_value)
if (alpha != 0.0):
alpha = _to_tensor(alpha, x.dtype.base_dtype)
x -= (alpha * negative_part)
return x
| null | null | null | linear unit
| codeqa | def relu x alpha 0 0 max value None if alpha 0 0 negative part tf nn relu - x x tf nn relu x if max value is not None max value to tensor max value x dtype base dtype zero to tensor 0 0 x dtype base dtype x tf clip by value x zero max value if alpha 0 0 alpha to tensor alpha x dtype base dtype x - alpha * negative part return x
| null | null | null | null | Question:
What did the code rectify ?
Code:
def relu(x, alpha=0.0, max_value=None):
if (alpha != 0.0):
negative_part = tf.nn.relu((- x))
x = tf.nn.relu(x)
if (max_value is not None):
max_value = _to_tensor(max_value, x.dtype.base_dtype)
zero = _to_tensor(0.0, x.dtype.base_dtype)
x = tf.clip_by_value(x, zero, max_value)
if (alpha != 0.0):
alpha = _to_tensor(alpha, x.dtype.base_dtype)
x -= (alpha * negative_part)
return x
|
null | null | null | How do authors create ?
| def generate_authors():
jenkins_email = 'jenkins@review.(openstack|stackforge).org'
old_authors = 'AUTHORS.in'
new_authors = 'AUTHORS'
if (not os.getenv('SKIP_GENERATE_AUTHORS')):
if os.path.isdir('.git'):
git_log_cmd = (("git log --format='%aN <%aE>' | sort -u | egrep -v '" + jenkins_email) + "'")
changelog = _run_shell_command(git_log_cmd)
mailmap = parse_mailmap()
with open(new_authors, 'w') as new_authors_fh:
new_authors_fh.write(canonicalize_emails(changelog, mailmap))
if os.path.exists(old_authors):
with open(old_authors, 'r') as old_authors_fh:
new_authors_fh.write(('\n' + old_authors_fh.read()))
else:
open(new_authors, 'w').close()
| null | null | null | using git commits
| codeqa | def generate authors jenkins email 'jenkins@review openstack stackforge org'old authors 'AUTHORS in'new authors 'AUTHORS'if not os getenv 'SKIP GENERATE AUTHORS' if os path isdir ' git' git log cmd "gitlog--format '%a N<%a E>' sort-u egrep-v'" + jenkins email + "'" changelog run shell command git log cmd mailmap parse mailmap with open new authors 'w' as new authors fh new authors fh write canonicalize emails changelog mailmap if os path exists old authors with open old authors 'r' as old authors fh new authors fh write '\n' + old authors fh read else open new authors 'w' close
| null | null | null | null | Question:
How do authors create ?
Code:
def generate_authors():
jenkins_email = 'jenkins@review.(openstack|stackforge).org'
old_authors = 'AUTHORS.in'
new_authors = 'AUTHORS'
if (not os.getenv('SKIP_GENERATE_AUTHORS')):
if os.path.isdir('.git'):
git_log_cmd = (("git log --format='%aN <%aE>' | sort -u | egrep -v '" + jenkins_email) + "'")
changelog = _run_shell_command(git_log_cmd)
mailmap = parse_mailmap()
with open(new_authors, 'w') as new_authors_fh:
new_authors_fh.write(canonicalize_emails(changelog, mailmap))
if os.path.exists(old_authors):
with open(old_authors, 'r') as old_authors_fh:
new_authors_fh.write(('\n' + old_authors_fh.read()))
else:
open(new_authors, 'w').close()
|
null | null | null | What does the code return ?
| def avail_locations(call=None):
if (call == 'action'):
raise SaltCloudSystemExit('The avail_locations function must be called with -f or --function, or with the --list-locations option')
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = str(region[item])
return ret
| null | null | null | a dict of all available vm locations on the cloud provider with relevant data
| codeqa | def avail locations call None if call 'action' raise Salt Cloud System Exit ' Theavail locationsfunctionmustbecalledwith-for--function orwiththe--list-locationsoption' params {' Action' ' Describe Regions'}items query params params ret {}for region in items[' Regions'][' Region'] ret[region[' Region Id']] {}for item in region ret[region[' Region Id']][item] str region[item] return ret
| null | null | null | null | Question:
What does the code return ?
Code:
def avail_locations(call=None):
if (call == 'action'):
raise SaltCloudSystemExit('The avail_locations function must be called with -f or --function, or with the --list-locations option')
params = {'Action': 'DescribeRegions'}
items = query(params=params)
ret = {}
for region in items['Regions']['Region']:
ret[region['RegionId']] = {}
for item in region:
ret[region['RegionId']][item] = str(region[item])
return ret
|
null | null | null | What does the code take ?
| def _split_multiline_prompt(get_prompt_tokens):
def has_before_tokens(cli):
for (token, char) in get_prompt_tokens(cli):
if (u'\n' in char):
return True
return False
def before(cli):
result = []
found_nl = False
for (token, char) in reversed(explode_tokens(get_prompt_tokens(cli))):
if found_nl:
result.insert(0, (token, char))
elif (char == u'\n'):
found_nl = True
return result
def first_input_line(cli):
result = []
for (token, char) in reversed(explode_tokens(get_prompt_tokens(cli))):
if (char == u'\n'):
break
else:
result.insert(0, (token, char))
return result
return (has_before_tokens, before, first_input_line)
| null | null | null | a get_prompt_tokens function
| codeqa | def split multiline prompt get prompt tokens def has before tokens cli for token char in get prompt tokens cli if u'\n' in char return Truereturn Falsedef before cli result []found nl Falsefor token char in reversed explode tokens get prompt tokens cli if found nl result insert 0 token char elif char u'\n' found nl Truereturn resultdef first input line cli result []for token char in reversed explode tokens get prompt tokens cli if char u'\n' breakelse result insert 0 token char return resultreturn has before tokens before first input line
| null | null | null | null | Question:
What does the code take ?
Code:
def _split_multiline_prompt(get_prompt_tokens):
def has_before_tokens(cli):
for (token, char) in get_prompt_tokens(cli):
if (u'\n' in char):
return True
return False
def before(cli):
result = []
found_nl = False
for (token, char) in reversed(explode_tokens(get_prompt_tokens(cli))):
if found_nl:
result.insert(0, (token, char))
elif (char == u'\n'):
found_nl = True
return result
def first_input_line(cli):
result = []
for (token, char) in reversed(explode_tokens(get_prompt_tokens(cli))):
if (char == u'\n'):
break
else:
result.insert(0, (token, char))
return result
return (has_before_tokens, before, first_input_line)
|
null | null | null | What does the code return instead ?
| def _split_multiline_prompt(get_prompt_tokens):
def has_before_tokens(cli):
for (token, char) in get_prompt_tokens(cli):
if (u'\n' in char):
return True
return False
def before(cli):
result = []
found_nl = False
for (token, char) in reversed(explode_tokens(get_prompt_tokens(cli))):
if found_nl:
result.insert(0, (token, char))
elif (char == u'\n'):
found_nl = True
return result
def first_input_line(cli):
result = []
for (token, char) in reversed(explode_tokens(get_prompt_tokens(cli))):
if (char == u'\n'):
break
else:
result.insert(0, (token, char))
return result
return (has_before_tokens, before, first_input_line)
| null | null | null | three new functions
| codeqa | def split multiline prompt get prompt tokens def has before tokens cli for token char in get prompt tokens cli if u'\n' in char return Truereturn Falsedef before cli result []found nl Falsefor token char in reversed explode tokens get prompt tokens cli if found nl result insert 0 token char elif char u'\n' found nl Truereturn resultdef first input line cli result []for token char in reversed explode tokens get prompt tokens cli if char u'\n' breakelse result insert 0 token char return resultreturn has before tokens before first input line
| null | null | null | null | Question:
What does the code return instead ?
Code:
def _split_multiline_prompt(get_prompt_tokens):
def has_before_tokens(cli):
for (token, char) in get_prompt_tokens(cli):
if (u'\n' in char):
return True
return False
def before(cli):
result = []
found_nl = False
for (token, char) in reversed(explode_tokens(get_prompt_tokens(cli))):
if found_nl:
result.insert(0, (token, char))
elif (char == u'\n'):
found_nl = True
return result
def first_input_line(cli):
result = []
for (token, char) in reversed(explode_tokens(get_prompt_tokens(cli))):
if (char == u'\n'):
break
else:
result.insert(0, (token, char))
return result
return (has_before_tokens, before, first_input_line)
|
null | null | null | What does the code get ?
| def getCarvingFromParser(xmlParser):
booleanGeometry = boolean_geometry.BooleanGeometry()
artOfIllusionElement = xmlParser.getRoot()
artOfIllusionElement.object = booleanGeometry
euclidean.removeListFromDictionary(artOfIllusionElement.attributeDictionary, ['fileversion', 'xmlns:bf'])
sceneElement = artOfIllusionElement.getFirstChildWithClassName('Scene')
xmlElements = sceneElement.getFirstChildWithClassName('objects').getChildrenWithClassName('bf:Elem')
for xmlElement in xmlElements:
processXMLElement(booleanGeometry.archivableObjects, artOfIllusionElement, xmlElement)
return booleanGeometry
| null | null | null | the carving for the parser
| codeqa | def get Carving From Parser xml Parser boolean Geometry boolean geometry Boolean Geometry art Of Illusion Element xml Parser get Root art Of Illusion Element object boolean Geometryeuclidean remove List From Dictionary art Of Illusion Element attribute Dictionary ['fileversion' 'xmlns bf'] scene Element art Of Illusion Element get First Child With Class Name ' Scene' xml Elements scene Element get First Child With Class Name 'objects' get Children With Class Name 'bf Elem' for xml Element in xml Elements process XML Element boolean Geometry archivable Objects art Of Illusion Element xml Element return boolean Geometry
| null | null | null | null | Question:
What does the code get ?
Code:
def getCarvingFromParser(xmlParser):
booleanGeometry = boolean_geometry.BooleanGeometry()
artOfIllusionElement = xmlParser.getRoot()
artOfIllusionElement.object = booleanGeometry
euclidean.removeListFromDictionary(artOfIllusionElement.attributeDictionary, ['fileversion', 'xmlns:bf'])
sceneElement = artOfIllusionElement.getFirstChildWithClassName('Scene')
xmlElements = sceneElement.getFirstChildWithClassName('objects').getChildrenWithClassName('bf:Elem')
for xmlElement in xmlElements:
processXMLElement(booleanGeometry.archivableObjects, artOfIllusionElement, xmlElement)
return booleanGeometry
|
null | null | null | For what purpose does a compiled template object return ?
| def get_template(template_name):
(source, origin) = find_template_source(template_name)
template = get_template_from_string(source, origin, template_name)
return template
| null | null | null | for the given template name
| codeqa | def get template template name source origin find template source template name template get template from string source origin template name return template
| null | null | null | null | Question:
For what purpose does a compiled template object return ?
Code:
def get_template(template_name):
(source, origin) = find_template_source(template_name)
template = get_template_from_string(source, origin, template_name)
return template
|
null | null | null | What does the code get ?
| def forecast(location, params=None):
url = '{}/{}'.format(api, location)
headers = {'Accept-Encoding': 'gzip'}
r = requests.get(url, params=params, headers=headers)
if (r.status_code != 200):
raise WeatherException('Your key is invalid or forecast.io is down')
r = r.json()
if ('error' in r):
raise WeatherException('Error getting weather: {}'.format(r['error']), r['error'])
return r
| null | null | null | a forecast for a location
| codeqa | def forecast location params None url '{}/{}' format api location headers {' Accept- Encoding' 'gzip'}r requests get url params params headers headers if r status code 200 raise Weather Exception ' Yourkeyisinvalidorforecast ioisdown' r r json if 'error' in r raise Weather Exception ' Errorgettingweather {}' format r['error'] r['error'] return r
| null | null | null | null | Question:
What does the code get ?
Code:
def forecast(location, params=None):
url = '{}/{}'.format(api, location)
headers = {'Accept-Encoding': 'gzip'}
r = requests.get(url, params=params, headers=headers)
if (r.status_code != 200):
raise WeatherException('Your key is invalid or forecast.io is down')
r = r.json()
if ('error' in r):
raise WeatherException('Error getting weather: {}'.format(r['error']), r['error'])
return r
|
null | null | null | What do candidate convert ?
| def try_int(candidate, default_value=0):
try:
return int(candidate)
except (ValueError, TypeError):
return default_value
| null | null | null | to int
| codeqa | def try int candidate default value 0 try return int candidate except Value Error Type Error return default value
| null | null | null | null | Question:
What do candidate convert ?
Code:
def try_int(candidate, default_value=0):
try:
return int(candidate)
except (ValueError, TypeError):
return default_value
|
null | null | null | What converts to int ?
| def try_int(candidate, default_value=0):
try:
return int(candidate)
except (ValueError, TypeError):
return default_value
| null | null | null | candidate
| codeqa | def try int candidate default value 0 try return int candidate except Value Error Type Error return default value
| null | null | null | null | Question:
What converts to int ?
Code:
def try_int(candidate, default_value=0):
try:
return int(candidate)
except (ValueError, TypeError):
return default_value
|
null | null | null | What does the code take ?
| def returner(ret):
options = _get_options(ret)
_response = _request('GET', (options['url'] + '_all_dbs'))
if (options['db'] not in _response):
_response = _request('PUT', (options['url'] + options['db']))
if (('ok' not in _response) or (_response['ok'] is not True)):
log.error('Unable to create database "{0}"'.format(options['db']))
log.error('Nothing logged! Lost data.')
return
log.info('Created database "{0}"'.format(options['db']))
doc = _generate_doc(ret)
_response = _request('PUT', (((options['url'] + options['db']) + '/') + doc['_id']), 'application/json', json.dumps(doc))
if (('ok' not in _response) or (_response['ok'] is not True)):
log.error('Unable to create document: "{0}"'.format(_response))
log.error('Nothing logged! Lost data.')
| null | null | null | the return
| codeqa | def returner ret options get options ret response request 'GET' options['url'] + ' all dbs' if options['db'] not in response response request 'PUT' options['url'] + options['db'] if 'ok' not in response or response['ok'] is not True log error ' Unabletocreatedatabase"{ 0 }"' format options['db'] log error ' Nothinglogged Lostdata ' returnlog info ' Createddatabase"{ 0 }"' format options['db'] doc generate doc ret response request 'PUT' options['url'] + options['db'] + '/' + doc[' id'] 'application/json' json dumps doc if 'ok' not in response or response['ok'] is not True log error ' Unabletocreatedocument "{ 0 }"' format response log error ' Nothinglogged Lostdata '
| null | null | null | null | Question:
What does the code take ?
Code:
def returner(ret):
options = _get_options(ret)
_response = _request('GET', (options['url'] + '_all_dbs'))
if (options['db'] not in _response):
_response = _request('PUT', (options['url'] + options['db']))
if (('ok' not in _response) or (_response['ok'] is not True)):
log.error('Unable to create database "{0}"'.format(options['db']))
log.error('Nothing logged! Lost data.')
return
log.info('Created database "{0}"'.format(options['db']))
doc = _generate_doc(ret)
_response = _request('PUT', (((options['url'] + options['db']) + '/') + doc['_id']), 'application/json', json.dumps(doc))
if (('ok' not in _response) or (_response['ok'] is not True)):
log.error('Unable to create document: "{0}"'.format(_response))
log.error('Nothing logged! Lost data.')
|
null | null | null | What does the code make ?
| def plugin():
return SwapBrackets
| null | null | null | plugin available
| codeqa | def plugin return Swap Brackets
| null | null | null | null | Question:
What does the code make ?
Code:
def plugin():
return SwapBrackets
|
null | null | null | What does the code drop ?
| def drop_database(manager):
manager.execute(('DROP DATABASE `%s`' % manager.get_db_name()))
| null | null | null | the database that the specified manager controls
| codeqa | def drop database manager manager execute 'DROPDATABASE`%s`' % manager get db name
| null | null | null | null | Question:
What does the code drop ?
Code:
def drop_database(manager):
manager.execute(('DROP DATABASE `%s`' % manager.get_db_name()))
|
null | null | null | What does the code make ?
| def user_media_path(what):
default = os.path.join(settings.MEDIA_ROOT, what)
key = '{0}_PATH'.format(what.upper())
return getattr(settings, key, default)
| null | null | null | it possible to override storage paths in settings
| codeqa | def user media path what default os path join settings MEDIA ROOT what key '{ 0 } PATH' format what upper return getattr settings key default
| null | null | null | null | Question:
What does the code make ?
Code:
def user_media_path(what):
default = os.path.join(settings.MEDIA_ROOT, what)
key = '{0}_PATH'.format(what.upper())
return getattr(settings, key, default)
|
null | null | null | What overrides in settings ?
| def user_media_path(what):
default = os.path.join(settings.MEDIA_ROOT, what)
key = '{0}_PATH'.format(what.upper())
return getattr(settings, key, default)
| null | null | null | storage paths
| codeqa | def user media path what default os path join settings MEDIA ROOT what key '{ 0 } PATH' format what upper return getattr settings key default
| null | null | null | null | Question:
What overrides in settings ?
Code:
def user_media_path(what):
default = os.path.join(settings.MEDIA_ROOT, what)
key = '{0}_PATH'.format(what.upper())
return getattr(settings, key, default)
|
null | null | null | Where do storage paths override ?
| def user_media_path(what):
default = os.path.join(settings.MEDIA_ROOT, what)
key = '{0}_PATH'.format(what.upper())
return getattr(settings, key, default)
| null | null | null | in settings
| codeqa | def user media path what default os path join settings MEDIA ROOT what key '{ 0 } PATH' format what upper return getattr settings key default
| null | null | null | null | Question:
Where do storage paths override ?
Code:
def user_media_path(what):
default = os.path.join(settings.MEDIA_ROOT, what)
key = '{0}_PATH'.format(what.upper())
return getattr(settings, key, default)
|
null | null | null | Where did the string contain ?
| def admin_media_prefix():
try:
from django.conf import settings
except ImportError:
return ''
return settings.ADMIN_MEDIA_PREFIX
| null | null | null | in the setting admin_media_prefix
| codeqa | def admin media prefix try from django conf import settingsexcept Import Error return ''return settings ADMIN MEDIA PREFIX
| null | null | null | null | Question:
Where did the string contain ?
Code:
def admin_media_prefix():
try:
from django.conf import settings
except ImportError:
return ''
return settings.ADMIN_MEDIA_PREFIX
|
null | null | null | What contained in the setting admin_media_prefix ?
| def admin_media_prefix():
try:
from django.conf import settings
except ImportError:
return ''
return settings.ADMIN_MEDIA_PREFIX
| null | null | null | the string
| codeqa | def admin media prefix try from django conf import settingsexcept Import Error return ''return settings ADMIN MEDIA PREFIX
| null | null | null | null | Question:
What contained in the setting admin_media_prefix ?
Code:
def admin_media_prefix():
try:
from django.conf import settings
except ImportError:
return ''
return settings.ADMIN_MEDIA_PREFIX
|
null | null | null | How do a string listing hex return ?
| def hexWithoutQuotes(l):
return str([hex(i) for i in l]).replace("'", '')
| null | null | null | without all the single quotes
| codeqa | def hex Without Quotes l return str [hex i for i in l] replace "'" ''
| null | null | null | null | Question:
How do a string listing hex return ?
Code:
def hexWithoutQuotes(l):
return str([hex(i) for i in l]).replace("'", '')
|
null | null | null | What does the code count ?
| def count_lines(filename, non_empty=False):
try:
if non_empty:
out = subprocess.Popen(['grep', '-cve', '^\\s*$', filename], stdout=subprocess.PIPE)
else:
out = subprocess.Popen(['wc', '-l', filename], stdout=subprocess.PIPE)
return int(out.communicate()[0].split()[0])
except:
pass
return 0
| null | null | null | the number of lines from the filename file
| codeqa | def count lines filename non empty False try if non empty out subprocess Popen ['grep' '-cve' '^\\s*$' filename] stdout subprocess PIPE else out subprocess Popen ['wc' '-l' filename] stdout subprocess PIPE return int out communicate [0 ] split [0 ] except passreturn 0
| null | null | null | null | Question:
What does the code count ?
Code:
def count_lines(filename, non_empty=False):
try:
if non_empty:
out = subprocess.Popen(['grep', '-cve', '^\\s*$', filename], stdout=subprocess.PIPE)
else:
out = subprocess.Popen(['wc', '-l', filename], stdout=subprocess.PIPE)
return int(out.communicate()[0].split()[0])
except:
pass
return 0
|
null | null | null | What does the code get ?
| def getFundamentalsPath(subName=''):
return getJoinedPath(getGeometryUtilitiesPath('evaluate_fundamentals'), subName)
| null | null | null | the evaluate_fundamentals directory path
| codeqa | def get Fundamentals Path sub Name '' return get Joined Path get Geometry Utilities Path 'evaluate fundamentals' sub Name
| null | null | null | null | Question:
What does the code get ?
Code:
def getFundamentalsPath(subName=''):
return getJoinedPath(getGeometryUtilitiesPath('evaluate_fundamentals'), subName)
|
null | null | null | What does the code convert into a dictionary ?
| def conn_from_flowtuple(ft):
(sip, sport, dip, dport, offset, relts) = ft
return {'src': sip, 'sport': sport, 'dst': dip, 'dport': dport, 'offset': offset, 'time': relts}
| null | null | null | the flow tuple
| codeqa | def conn from flowtuple ft sip sport dip dport offset relts ftreturn {'src' sip 'sport' sport 'dst' dip 'dport' dport 'offset' offset 'time' relts}
| null | null | null | null | Question:
What does the code convert into a dictionary ?
Code:
def conn_from_flowtuple(ft):
(sip, sport, dip, dport, offset, relts) = ft
return {'src': sip, 'sport': sport, 'dst': dip, 'dport': dport, 'offset': offset, 'time': relts}
|
null | null | null | What does the code compute ?
| @public
def gff_list(f, *gens, **args):
options.allowed_flags(args, ['polys'])
try:
(F, opt) = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('gff_list', 1, exc)
factors = F.gff_list()
if (not opt.polys):
return [(g.as_expr(), k) for (g, k) in factors]
else:
return factors
| null | null | null | a list of greatest factorial factors of f
| codeqa | @publicdef gff list f *gens **args options allowed flags args ['polys'] try F opt poly from expr f *gens **args except Polification Failed as exc raise Computation Failed 'gff list' 1 exc factors F gff list if not opt polys return [ g as expr k for g k in factors]else return factors
| null | null | null | null | Question:
What does the code compute ?
Code:
@public
def gff_list(f, *gens, **args):
options.allowed_flags(args, ['polys'])
try:
(F, opt) = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('gff_list', 1, exc)
factors = F.gff_list()
if (not opt.polys):
return [(g.as_expr(), k) for (g, k) in factors]
else:
return factors
|
null | null | null | What does the code get from secured file ?
| def get_navigator_auth_password():
return NAVIGATOR.AUTH_PASSWORD_SCRIPT.get()
| null | null | null | default password
| codeqa | def get navigator auth password return NAVIGATOR AUTH PASSWORD SCRIPT get
| null | null | null | null | Question:
What does the code get from secured file ?
Code:
def get_navigator_auth_password():
return NAVIGATOR.AUTH_PASSWORD_SCRIPT.get()
|
null | null | null | What does the code get by paths ?
| def getFloatListListsByPaths(paths):
floatListLists = []
for path in paths:
floatListList = []
for point in path:
floatListList.append(point.getFloatList())
return floatListLists
| null | null | null | float lists
| codeqa | def get Float List Lists By Paths paths float List Lists []for path in paths float List List []for point in path float List List append point get Float List return float List Lists
| null | null | null | null | Question:
What does the code get by paths ?
Code:
def getFloatListListsByPaths(paths):
floatListLists = []
for path in paths:
floatListList = []
for point in path:
floatListList.append(point.getFloatList())
return floatListLists
|
null | null | null | How does the code get float lists ?
| def getFloatListListsByPaths(paths):
floatListLists = []
for path in paths:
floatListList = []
for point in path:
floatListList.append(point.getFloatList())
return floatListLists
| null | null | null | by paths
| codeqa | def get Float List Lists By Paths paths float List Lists []for path in paths float List List []for point in path float List List append point get Float List return float List Lists
| null | null | null | null | Question:
How does the code get float lists ?
Code:
def getFloatListListsByPaths(paths):
floatListLists = []
for path in paths:
floatListList = []
for point in path:
floatListList.append(point.getFloatList())
return floatListLists
|
null | null | null | How will the wrapped function execute only actually ?
| def sampled(live_config_var):
def sampled_decorator(fn):
@functools.wraps(fn)
def sampled_fn(*a, **kw):
if (random.random() > g.live_config[live_config_var]):
return None
else:
return fn(*a, **kw)
return sampled_fn
return sampled_decorator
| null | null | null | at the rate specified by the live_config sample rate given
| codeqa | def sampled live config var def sampled decorator fn @functools wraps fn def sampled fn *a **kw if random random > g live config[live config var] return Noneelse return fn *a **kw return sampled fnreturn sampled decorator
| null | null | null | null | Question:
How will the wrapped function execute only actually ?
Code:
def sampled(live_config_var):
def sampled_decorator(fn):
@functools.wraps(fn)
def sampled_fn(*a, **kw):
if (random.random() > g.live_config[live_config_var]):
return None
else:
return fn(*a, **kw)
return sampled_fn
return sampled_decorator
|
null | null | null | What does the code display ?
| def main():
if (len(sys.argv) > 1):
writeOutput(' '.join(sys.argv[1:]))
else:
settings.startMainLoopFromConstructor(getNewRepository())
| null | null | null | the carve dialog
| codeqa | def main if len sys argv > 1 write Output '' join sys argv[ 1 ] else settings start Main Loop From Constructor get New Repository
| null | null | null | null | Question:
What does the code display ?
Code:
def main():
if (len(sys.argv) > 1):
writeOutput(' '.join(sys.argv[1:]))
else:
settings.startMainLoopFromConstructor(getNewRepository())
|
null | null | null | How did error handle ?
| def report_error(error, exc_info, request=None, extra_data=None, level=None):
if (HAS_ROLLBAR and hasattr(settings, u'ROLLBAR')):
rollbar.report_exc_info(exc_info, request, extra_data=extra_data, level=level)
LOGGER.error(u'Handled exception %s: %s', error.__class__.__name__, force_text(error).encode(u'utf-8'))
if (sys.argv[1:2] == [u'test']):
traceback.print_exc()
| null | null | null | gracefully
| codeqa | def report error error exc info request None extra data None level None if HAS ROLLBAR and hasattr settings u'ROLLBAR' rollbar report exc info exc info request extra data extra data level level LOGGER error u' Handledexception%s %s' error class name force text error encode u'utf- 8 ' if sys argv[ 1 2] [u'test'] traceback print exc
| null | null | null | null | Question:
How did error handle ?
Code:
def report_error(error, exc_info, request=None, extra_data=None, level=None):
if (HAS_ROLLBAR and hasattr(settings, u'ROLLBAR')):
rollbar.report_exc_info(exc_info, request, extra_data=extra_data, level=level)
LOGGER.error(u'Handled exception %s: %s', error.__class__.__name__, force_text(error).encode(u'utf-8'))
if (sys.argv[1:2] == [u'test']):
traceback.print_exc()
|
null | null | null | How is the coordination service configured ?
| def configured():
backend_configured = (cfg.CONF.coordination.url is not None)
mock_backend = (backend_configured and (cfg.CONF.coordination.url.startswith('zake') or cfg.CONF.coordination.url.startswith('file')))
return (backend_configured and (not mock_backend))
| null | null | null | properly
| codeqa | def configured backend configured cfg CONF coordination url is not None mock backend backend configured and cfg CONF coordination url startswith 'zake' or cfg CONF coordination url startswith 'file' return backend configured and not mock backend
| null | null | null | null | Question:
How is the coordination service configured ?
Code:
def configured():
backend_configured = (cfg.CONF.coordination.url is not None)
mock_backend = (backend_configured and (cfg.CONF.coordination.url.startswith('zake') or cfg.CONF.coordination.url.startswith('file')))
return (backend_configured and (not mock_backend))
|
null | null | null | When do a safe filter decorator raise errors only ?
| def safe_filter(error_output=u''):
def inner(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as err:
if sorl_settings.THUMBNAIL_DEBUG:
raise
logger.error((u'Thumbnail filter failed: %s' % err.message), exc_info=sys.exc_info())
return error_output
return wrapper
return inner
| null | null | null | when thumbnail_debug is true otherwise returning error_output
| codeqa | def safe filter error output u'' def inner f @wraps f def wrapper *args **kwargs try return f *args **kwargs except Exception as err if sorl settings THUMBNAIL DEBUG raiselogger error u' Thumbnailfilterfailed %s' % err message exc info sys exc info return error outputreturn wrapperreturn inner
| null | null | null | null | Question:
When do a safe filter decorator raise errors only ?
Code:
def safe_filter(error_output=u''):
def inner(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as err:
if sorl_settings.THUMBNAIL_DEBUG:
raise
logger.error((u'Thumbnail filter failed: %s' % err.message), exc_info=sys.exc_info())
return error_output
return wrapper
return inner
|
null | null | null | What does the code remove from the specified service ?
| def remove_service_port(service, port):
if (service not in get_services(permanent=True)):
raise CommandExecutionError('The service does not exist.')
cmd = '--permanent --service={0} --remove-port={1}'.format(service, port)
return __firewall_cmd(cmd)
| null | null | null | a port
| codeqa | def remove service port service port if service not in get services permanent True raise Command Execution Error ' Theservicedoesnotexist ' cmd '--permanent--service {0 }--remove-port {1 }' format service port return firewall cmd cmd
| null | null | null | null | Question:
What does the code remove from the specified service ?
Code:
def remove_service_port(service, port):
if (service not in get_services(permanent=True)):
raise CommandExecutionError('The service does not exist.')
cmd = '--permanent --service={0} --remove-port={1}'.format(service, port)
return __firewall_cmd(cmd)
|
null | null | null | What does the code provide ?
| def blend(*cols, **kwargs):
return Blend(*cols, **kwargs)
| null | null | null | a simple function for specifying a blend data operation
| codeqa | def blend *cols **kwargs return Blend *cols **kwargs
| null | null | null | null | Question:
What does the code provide ?
Code:
def blend(*cols, **kwargs):
return Blend(*cols, **kwargs)
|
null | null | null | How does the code find a user ?
| def find_user(name, api_url=None, api_key=None, api_version=None):
users = list_users(api_url=api_url, api_key=api_key, api_version=api_version)
if users:
for x in range(0, len(users)):
if (users[x]['name'] == name):
return users[x]
return False
| null | null | null | by name
| codeqa | def find user name api url None api key None api version None users list users api url api url api key api key api version api version if users for x in range 0 len users if users[x]['name'] name return users[x]return False
| null | null | null | null | Question:
How does the code find a user ?
Code:
def find_user(name, api_url=None, api_key=None, api_version=None):
users = list_users(api_url=api_url, api_key=api_key, api_version=api_version)
if users:
for x in range(0, len(users)):
if (users[x]['name'] == name):
return users[x]
return False
|
null | null | null | What does the code find by name ?
| def find_user(name, api_url=None, api_key=None, api_version=None):
users = list_users(api_url=api_url, api_key=api_key, api_version=api_version)
if users:
for x in range(0, len(users)):
if (users[x]['name'] == name):
return users[x]
return False
| null | null | null | a user
| codeqa | def find user name api url None api key None api version None users list users api url api url api key api key api version api version if users for x in range 0 len users if users[x]['name'] name return users[x]return False
| null | null | null | null | Question:
What does the code find by name ?
Code:
def find_user(name, api_url=None, api_key=None, api_version=None):
users = list_users(api_url=api_url, api_key=api_key, api_version=api_version)
if users:
for x in range(0, len(users)):
if (users[x]['name'] == name):
return users[x]
return False
|
null | null | null | What does the code calculate ?
| def maximum(input, labels=None, index=None):
return _select(input, labels, index, find_max=True)[0]
| null | null | null | the maximum of the values of an array over labeled regions
| codeqa | def maximum input labels None index None return select input labels index find max True [0 ]
| null | null | null | null | Question:
What does the code calculate ?
Code:
def maximum(input, labels=None, index=None):
return _select(input, labels, index, find_max=True)[0]
|
null | null | null | What does the resource definition be ?
| def resolve_embedded_fields(resource, req):
embedded_fields = []
non_embedded_fields = []
if req.embedded:
try:
client_embedding = json.loads(req.embedded)
except ValueError:
abort(400, description='Unable to parse `embedded` clause')
try:
embedded_fields = [k for (k, v) in client_embedding.items() if (v == 1)]
non_embedded_fields = [k for (k, v) in client_embedding.items() if (v == 0)]
except AttributeError:
abort(400, description='Unable to parse `embedded` clause')
embedded_fields = list(((set(config.DOMAIN[resource]['embedded_fields']) | set(embedded_fields)) - set(non_embedded_fields)))
enabled_embedded_fields = []
for field in sorted(embedded_fields, key=(lambda a: a.count('.'))):
field_def = field_definition(resource, field)
if field_def:
if (field_def.get('type') == 'list'):
field_def = field_def['schema']
if (('data_relation' in field_def) and field_def['data_relation'].get('embeddable')):
enabled_embedded_fields.append(field)
return enabled_embedded_fields
| null | null | null | the request does not specify
| codeqa | def resolve embedded fields resource req embedded fields []non embedded fields []if req embedded try client embedding json loads req embedded except Value Error abort 400 description ' Unabletoparse`embedded`clause' try embedded fields [k for k v in client embedding items if v 1 ]non embedded fields [k for k v in client embedding items if v 0 ]except Attribute Error abort 400 description ' Unabletoparse`embedded`clause' embedded fields list set config DOMAIN[resource]['embedded fields'] set embedded fields - set non embedded fields enabled embedded fields []for field in sorted embedded fields key lambda a a count ' ' field def field definition resource field if field def if field def get 'type' 'list' field def field def['schema']if 'data relation' in field def and field def['data relation'] get 'embeddable' enabled embedded fields append field return enabled embedded fields
| null | null | null | null | Question:
What does the resource definition be ?
Code:
def resolve_embedded_fields(resource, req):
embedded_fields = []
non_embedded_fields = []
if req.embedded:
try:
client_embedding = json.loads(req.embedded)
except ValueError:
abort(400, description='Unable to parse `embedded` clause')
try:
embedded_fields = [k for (k, v) in client_embedding.items() if (v == 1)]
non_embedded_fields = [k for (k, v) in client_embedding.items() if (v == 0)]
except AttributeError:
abort(400, description='Unable to parse `embedded` clause')
embedded_fields = list(((set(config.DOMAIN[resource]['embedded_fields']) | set(embedded_fields)) - set(non_embedded_fields)))
enabled_embedded_fields = []
for field in sorted(embedded_fields, key=(lambda a: a.count('.'))):
field_def = field_definition(resource, field)
if field_def:
if (field_def.get('type') == 'list'):
field_def = field_def['schema']
if (('data_relation' in field_def) and field_def['data_relation'].get('embeddable')):
enabled_embedded_fields.append(field)
return enabled_embedded_fields
|
null | null | null | What is the request does not specify ?
| def resolve_embedded_fields(resource, req):
embedded_fields = []
non_embedded_fields = []
if req.embedded:
try:
client_embedding = json.loads(req.embedded)
except ValueError:
abort(400, description='Unable to parse `embedded` clause')
try:
embedded_fields = [k for (k, v) in client_embedding.items() if (v == 1)]
non_embedded_fields = [k for (k, v) in client_embedding.items() if (v == 0)]
except AttributeError:
abort(400, description='Unable to parse `embedded` clause')
embedded_fields = list(((set(config.DOMAIN[resource]['embedded_fields']) | set(embedded_fields)) - set(non_embedded_fields)))
enabled_embedded_fields = []
for field in sorted(embedded_fields, key=(lambda a: a.count('.'))):
field_def = field_definition(resource, field)
if field_def:
if (field_def.get('type') == 'list'):
field_def = field_def['schema']
if (('data_relation' in field_def) and field_def['data_relation'].get('embeddable')):
enabled_embedded_fields.append(field)
return enabled_embedded_fields
| null | null | null | the resource definition
| codeqa | def resolve embedded fields resource req embedded fields []non embedded fields []if req embedded try client embedding json loads req embedded except Value Error abort 400 description ' Unabletoparse`embedded`clause' try embedded fields [k for k v in client embedding items if v 1 ]non embedded fields [k for k v in client embedding items if v 0 ]except Attribute Error abort 400 description ' Unabletoparse`embedded`clause' embedded fields list set config DOMAIN[resource]['embedded fields'] set embedded fields - set non embedded fields enabled embedded fields []for field in sorted embedded fields key lambda a a count ' ' field def field definition resource field if field def if field def get 'type' 'list' field def field def['schema']if 'data relation' in field def and field def['data relation'] get 'embeddable' enabled embedded fields append field return enabled embedded fields
| null | null | null | null | Question:
What is the request does not specify ?
Code:
def resolve_embedded_fields(resource, req):
embedded_fields = []
non_embedded_fields = []
if req.embedded:
try:
client_embedding = json.loads(req.embedded)
except ValueError:
abort(400, description='Unable to parse `embedded` clause')
try:
embedded_fields = [k for (k, v) in client_embedding.items() if (v == 1)]
non_embedded_fields = [k for (k, v) in client_embedding.items() if (v == 0)]
except AttributeError:
abort(400, description='Unable to parse `embedded` clause')
embedded_fields = list(((set(config.DOMAIN[resource]['embedded_fields']) | set(embedded_fields)) - set(non_embedded_fields)))
enabled_embedded_fields = []
for field in sorted(embedded_fields, key=(lambda a: a.count('.'))):
field_def = field_definition(resource, field)
if field_def:
if (field_def.get('type') == 'list'):
field_def = field_def['schema']
if (('data_relation' in field_def) and field_def['data_relation'].get('embeddable')):
enabled_embedded_fields.append(field)
return enabled_embedded_fields
|
null | null | null | What fails on empty string ?
| def test_issue309(en_tokenizer):
tokens = en_tokenizer(u' ')
doc = get_doc(tokens.vocab, [t.text for t in tokens], heads=[0], deps=[u'ROOT'])
doc.is_parsed = True
assert (len(doc) == 1)
sents = list(doc.sents)
assert (len(sents) == 1)
| null | null | null | sbd
| codeqa | def test issue 309 en tokenizer tokens en tokenizer u'' doc get doc tokens vocab [t text for t in tokens] heads [0 ] deps [u'ROOT'] doc is parsed Trueassert len doc 1 sents list doc sents assert len sents 1
| null | null | null | null | Question:
What fails on empty string ?
Code:
def test_issue309(en_tokenizer):
tokens = en_tokenizer(u' ')
doc = get_doc(tokens.vocab, [t.text for t in tokens], heads=[0], deps=[u'ROOT'])
doc.is_parsed = True
assert (len(doc) == 1)
sents = list(doc.sents)
assert (len(sents) == 1)
|
null | null | null | What does the code create ?
| def define_delta(name, description, manager=counters):
counter = _DeltaCounter(name, description)
manager.register(counter)
return counter
| null | null | null | a performance counter which tracks the accumulation of a value since the previous sample of the counter
| codeqa | def define delta name description manager counters counter Delta Counter name description manager register counter return counter
| null | null | null | null | Question:
What does the code create ?
Code:
def define_delta(name, description, manager=counters):
counter = _DeltaCounter(name, description)
manager.register(counter)
return counter
|
null | null | null | What tracks the accumulation of a value since the previous sample of the counter ?
| def define_delta(name, description, manager=counters):
counter = _DeltaCounter(name, description)
manager.register(counter)
return counter
| null | null | null | a performance counter
| codeqa | def define delta name description manager counters counter Delta Counter name description manager register counter return counter
| null | null | null | null | Question:
What tracks the accumulation of a value since the previous sample of the counter ?
Code:
def define_delta(name, description, manager=counters):
counter = _DeltaCounter(name, description)
manager.register(counter)
return counter
|
null | null | null | What does a performance counter track since the previous sample of the counter ?
| def define_delta(name, description, manager=counters):
counter = _DeltaCounter(name, description)
manager.register(counter)
return counter
| null | null | null | the accumulation of a value
| codeqa | def define delta name description manager counters counter Delta Counter name description manager register counter return counter
| null | null | null | null | Question:
What does a performance counter track since the previous sample of the counter ?
Code:
def define_delta(name, description, manager=counters):
counter = _DeltaCounter(name, description)
manager.register(counter)
return counter
|
null | null | null | When does a performance counter track the accumulation of a value ?
| def define_delta(name, description, manager=counters):
counter = _DeltaCounter(name, description)
manager.register(counter)
return counter
| null | null | null | since the previous sample of the counter
| codeqa | def define delta name description manager counters counter Delta Counter name description manager register counter return counter
| null | null | null | null | Question:
When does a performance counter track the accumulation of a value ?
Code:
def define_delta(name, description, manager=counters):
counter = _DeltaCounter(name, description)
manager.register(counter)
return counter
|
null | null | null | What should abort raise ?
| @aborts
def test_abort():
abort('Test')
| null | null | null | systemexit
| codeqa | @abortsdef test abort abort ' Test'
| null | null | null | null | Question:
What should abort raise ?
Code:
@aborts
def test_abort():
abort('Test')
|
null | null | null | What does the code stop ?
| def stop():
global __SCHED
if __SCHED:
logging.debug('Stopping scheduler')
try:
__SCHED.stop()
except IndexError:
pass
del __SCHED
__SCHED = None
| null | null | null | the scheduler
| codeqa | def stop global SCHE Dif SCHED logging debug ' Stoppingscheduler' try SCHED stop except Index Error passdel SCHED SCHED None
| null | null | null | null | Question:
What does the code stop ?
Code:
def stop():
global __SCHED
if __SCHED:
logging.debug('Stopping scheduler')
try:
__SCHED.stop()
except IndexError:
pass
del __SCHED
__SCHED = None
|
null | null | null | What does the code instantiate ?
| def make_region(*arg, **kw):
return CacheRegion(*arg, **kw)
| null | null | null | a new : class
| codeqa | def make region *arg **kw return Cache Region *arg **kw
| null | null | null | null | Question:
What does the code instantiate ?
Code:
def make_region(*arg, **kw):
return CacheRegion(*arg, **kw)
|
null | null | null | What is indicating abstract methods ?
| def abstractmethod(funcobj):
funcobj.__isabstractmethod__ = True
return funcobj
| null | null | null | a decorator
| codeqa | def abstractmethod funcobj funcobj isabstractmethod Truereturn funcobj
| null | null | null | null | Question:
What is indicating abstract methods ?
Code:
def abstractmethod(funcobj):
funcobj.__isabstractmethod__ = True
return funcobj
|
null | null | null | What does the code create ?
| @pytest.fixture
def progress_widget(qtbot, monkeypatch, config_stub):
config_stub.data = {'colors': {'statusbar.progress.bg': 'black'}, 'fonts': {}}
monkeypatch.setattr('qutebrowser.mainwindow.statusbar.progress.style.config', config_stub)
widget = Progress()
qtbot.add_widget(widget)
assert (not widget.isVisible())
assert (not widget.isTextVisible())
return widget
| null | null | null | a progress widget
| codeqa | @pytest fixturedef progress widget qtbot monkeypatch config stub config stub data {'colors' {'statusbar progress bg' 'black'} 'fonts' {}}monkeypatch setattr 'qutebrowser mainwindow statusbar progress style config' config stub widget Progress qtbot add widget widget assert not widget is Visible assert not widget is Text Visible return widget
| null | null | null | null | Question:
What does the code create ?
Code:
@pytest.fixture
def progress_widget(qtbot, monkeypatch, config_stub):
config_stub.data = {'colors': {'statusbar.progress.bg': 'black'}, 'fonts': {}}
monkeypatch.setattr('qutebrowser.mainwindow.statusbar.progress.style.config', config_stub)
widget = Progress()
qtbot.add_widget(widget)
assert (not widget.isVisible())
assert (not widget.isTextVisible())
return widget
|
null | null | null | What does the code check ?
| @pytest.fixture
def progress_widget(qtbot, monkeypatch, config_stub):
config_stub.data = {'colors': {'statusbar.progress.bg': 'black'}, 'fonts': {}}
monkeypatch.setattr('qutebrowser.mainwindow.statusbar.progress.style.config', config_stub)
widget = Progress()
qtbot.add_widget(widget)
assert (not widget.isVisible())
assert (not widget.isTextVisible())
return widget
| null | null | null | its initial state
| codeqa | @pytest fixturedef progress widget qtbot monkeypatch config stub config stub data {'colors' {'statusbar progress bg' 'black'} 'fonts' {}}monkeypatch setattr 'qutebrowser mainwindow statusbar progress style config' config stub widget Progress qtbot add widget widget assert not widget is Visible assert not widget is Text Visible return widget
| null | null | null | null | Question:
What does the code check ?
Code:
@pytest.fixture
def progress_widget(qtbot, monkeypatch, config_stub):
config_stub.data = {'colors': {'statusbar.progress.bg': 'black'}, 'fonts': {}}
monkeypatch.setattr('qutebrowser.mainwindow.statusbar.progress.style.config', config_stub)
widget = Progress()
qtbot.add_widget(widget)
assert (not widget.isVisible())
assert (not widget.isTextVisible())
return widget
|
null | null | null | How does the code render it ?
| @register.tag('include')
def do_include(parser, token):
bits = token.split_contents()
if (len(bits) < 2):
raise TemplateSyntaxError(('%r tag takes at least one argument: the name of the template to be included.' % bits[0]))
options = {}
remaining_bits = bits[2:]
while remaining_bits:
option = remaining_bits.pop(0)
if (option in options):
raise TemplateSyntaxError(('The %r option was specified more than once.' % option))
if (option == 'with'):
value = token_kwargs(remaining_bits, parser, support_legacy=False)
if (not value):
raise TemplateSyntaxError(('"with" in %r tag needs at least one keyword argument.' % bits[0]))
elif (option == 'only'):
value = True
else:
raise TemplateSyntaxError(('Unknown argument for %r tag: %r.' % (bits[0], option)))
options[option] = value
isolated_context = options.get('only', False)
namemap = options.get('with', {})
bits[1] = construct_relative_path(parser.origin.template_name, bits[1])
return IncludeNode(parser.compile_filter(bits[1]), extra_context=namemap, isolated_context=isolated_context)
| null | null | null | with the current context
| codeqa | @register tag 'include' def do include parser token bits token split contents if len bits < 2 raise Template Syntax Error '%rtagtakesatleastoneargument thenameofthetemplatetobeincluded ' % bits[ 0 ] options {}remaining bits bits[ 2 ]while remaining bits option remaining bits pop 0 if option in options raise Template Syntax Error ' The%roptionwasspecifiedmorethanonce ' % option if option 'with' value token kwargs remaining bits parser support legacy False if not value raise Template Syntax Error '"with"in%rtagneedsatleastonekeywordargument ' % bits[ 0 ] elif option 'only' value Trueelse raise Template Syntax Error ' Unknownargumentfor%rtag %r ' % bits[ 0 ] option options[option] valueisolated context options get 'only' False namemap options get 'with' {} bits[ 1 ] construct relative path parser origin template name bits[ 1 ] return Include Node parser compile filter bits[ 1 ] extra context namemap isolated context isolated context
| null | null | null | null | Question:
How does the code render it ?
Code:
@register.tag('include')
def do_include(parser, token):
bits = token.split_contents()
if (len(bits) < 2):
raise TemplateSyntaxError(('%r tag takes at least one argument: the name of the template to be included.' % bits[0]))
options = {}
remaining_bits = bits[2:]
while remaining_bits:
option = remaining_bits.pop(0)
if (option in options):
raise TemplateSyntaxError(('The %r option was specified more than once.' % option))
if (option == 'with'):
value = token_kwargs(remaining_bits, parser, support_legacy=False)
if (not value):
raise TemplateSyntaxError(('"with" in %r tag needs at least one keyword argument.' % bits[0]))
elif (option == 'only'):
value = True
else:
raise TemplateSyntaxError(('Unknown argument for %r tag: %r.' % (bits[0], option)))
options[option] = value
isolated_context = options.get('only', False)
namemap = options.get('with', {})
bits[1] = construct_relative_path(parser.origin.template_name, bits[1])
return IncludeNode(parser.compile_filter(bits[1]), extra_context=namemap, isolated_context=isolated_context)
|
null | null | null | What does the code load ?
| @register.tag('include')
def do_include(parser, token):
bits = token.split_contents()
if (len(bits) < 2):
raise TemplateSyntaxError(('%r tag takes at least one argument: the name of the template to be included.' % bits[0]))
options = {}
remaining_bits = bits[2:]
while remaining_bits:
option = remaining_bits.pop(0)
if (option in options):
raise TemplateSyntaxError(('The %r option was specified more than once.' % option))
if (option == 'with'):
value = token_kwargs(remaining_bits, parser, support_legacy=False)
if (not value):
raise TemplateSyntaxError(('"with" in %r tag needs at least one keyword argument.' % bits[0]))
elif (option == 'only'):
value = True
else:
raise TemplateSyntaxError(('Unknown argument for %r tag: %r.' % (bits[0], option)))
options[option] = value
isolated_context = options.get('only', False)
namemap = options.get('with', {})
bits[1] = construct_relative_path(parser.origin.template_name, bits[1])
return IncludeNode(parser.compile_filter(bits[1]), extra_context=namemap, isolated_context=isolated_context)
| null | null | null | a template
| codeqa | @register tag 'include' def do include parser token bits token split contents if len bits < 2 raise Template Syntax Error '%rtagtakesatleastoneargument thenameofthetemplatetobeincluded ' % bits[ 0 ] options {}remaining bits bits[ 2 ]while remaining bits option remaining bits pop 0 if option in options raise Template Syntax Error ' The%roptionwasspecifiedmorethanonce ' % option if option 'with' value token kwargs remaining bits parser support legacy False if not value raise Template Syntax Error '"with"in%rtagneedsatleastonekeywordargument ' % bits[ 0 ] elif option 'only' value Trueelse raise Template Syntax Error ' Unknownargumentfor%rtag %r ' % bits[ 0 ] option options[option] valueisolated context options get 'only' False namemap options get 'with' {} bits[ 1 ] construct relative path parser origin template name bits[ 1 ] return Include Node parser compile filter bits[ 1 ] extra context namemap isolated context isolated context
| null | null | null | null | Question:
What does the code load ?
Code:
@register.tag('include')
def do_include(parser, token):
bits = token.split_contents()
if (len(bits) < 2):
raise TemplateSyntaxError(('%r tag takes at least one argument: the name of the template to be included.' % bits[0]))
options = {}
remaining_bits = bits[2:]
while remaining_bits:
option = remaining_bits.pop(0)
if (option in options):
raise TemplateSyntaxError(('The %r option was specified more than once.' % option))
if (option == 'with'):
value = token_kwargs(remaining_bits, parser, support_legacy=False)
if (not value):
raise TemplateSyntaxError(('"with" in %r tag needs at least one keyword argument.' % bits[0]))
elif (option == 'only'):
value = True
else:
raise TemplateSyntaxError(('Unknown argument for %r tag: %r.' % (bits[0], option)))
options[option] = value
isolated_context = options.get('only', False)
namemap = options.get('with', {})
bits[1] = construct_relative_path(parser.origin.template_name, bits[1])
return IncludeNode(parser.compile_filter(bits[1]), extra_context=namemap, isolated_context=isolated_context)
|
null | null | null | When do the multipart minimum part size small make ?
| def reduced_min_part_size(f):
import moto.s3.models as s3model
orig_size = s3model.UPLOAD_PART_MIN_SIZE
@wraps(f)
def wrapped(*args, **kwargs):
try:
s3model.UPLOAD_PART_MIN_SIZE = REDUCED_PART_SIZE
return f(*args, **kwargs)
finally:
s3model.UPLOAD_PART_MIN_SIZE = orig_size
return wrapped
| null | null | null | temporarily
| codeqa | def reduced min part size f import moto s3 models as s3 modelorig size s3 model UPLOAD PART MIN SIZE@wraps f def wrapped *args **kwargs try s3 model UPLOAD PART MIN SIZE REDUCED PART SIZ Ereturn f *args **kwargs finally s3 model UPLOAD PART MIN SIZE orig sizereturn wrapped
| null | null | null | null | Question:
When do the multipart minimum part size small make ?
Code:
def reduced_min_part_size(f):
import moto.s3.models as s3model
orig_size = s3model.UPLOAD_PART_MIN_SIZE
@wraps(f)
def wrapped(*args, **kwargs):
try:
s3model.UPLOAD_PART_MIN_SIZE = REDUCED_PART_SIZE
return f(*args, **kwargs)
finally:
s3model.UPLOAD_PART_MIN_SIZE = orig_size
return wrapped
|
null | null | null | How do tests speed ?
| def reduced_min_part_size(f):
import moto.s3.models as s3model
orig_size = s3model.UPLOAD_PART_MIN_SIZE
@wraps(f)
def wrapped(*args, **kwargs):
try:
s3model.UPLOAD_PART_MIN_SIZE = REDUCED_PART_SIZE
return f(*args, **kwargs)
finally:
s3model.UPLOAD_PART_MIN_SIZE = orig_size
return wrapped
| null | null | null | by temporarily making the multipart minimum part size small
| codeqa | def reduced min part size f import moto s3 models as s3 modelorig size s3 model UPLOAD PART MIN SIZE@wraps f def wrapped *args **kwargs try s3 model UPLOAD PART MIN SIZE REDUCED PART SIZ Ereturn f *args **kwargs finally s3 model UPLOAD PART MIN SIZE orig sizereturn wrapped
| null | null | null | null | Question:
How do tests speed ?
Code:
def reduced_min_part_size(f):
import moto.s3.models as s3model
orig_size = s3model.UPLOAD_PART_MIN_SIZE
@wraps(f)
def wrapped(*args, **kwargs):
try:
s3model.UPLOAD_PART_MIN_SIZE = REDUCED_PART_SIZE
return f(*args, **kwargs)
finally:
s3model.UPLOAD_PART_MIN_SIZE = orig_size
return wrapped
|
null | null | null | What does the user press when ?
| @require_POST
@csrf_protect
def sync(request):
if (not test_user_authenticated(request)):
return login(request, next='/cobbler_web/sync', expired=True)
remote.background_sync({'verbose': 'True'}, request.session['token'])
return HttpResponseRedirect('/cobbler_web/task_created')
| null | null | null | the sync button
| codeqa | @require POST@csrf protectdef sync request if not test user authenticated request return login request next '/cobbler web/sync' expired True remote background sync {'verbose' ' True'} request session['token'] return Http Response Redirect '/cobbler web/task created'
| null | null | null | null | Question:
What does the user press when ?
Code:
@require_POST
@csrf_protect
def sync(request):
if (not test_user_authenticated(request)):
return login(request, next='/cobbler_web/sync', expired=True)
remote.background_sync({'verbose': 'True'}, request.session['token'])
return HttpResponseRedirect('/cobbler_web/task_created')
|
null | null | null | What presses the sync button when ?
| @require_POST
@csrf_protect
def sync(request):
if (not test_user_authenticated(request)):
return login(request, next='/cobbler_web/sync', expired=True)
remote.background_sync({'verbose': 'True'}, request.session['token'])
return HttpResponseRedirect('/cobbler_web/task_created')
| null | null | null | the user
| codeqa | @require POST@csrf protectdef sync request if not test user authenticated request return login request next '/cobbler web/sync' expired True remote background sync {'verbose' ' True'} request session['token'] return Http Response Redirect '/cobbler web/task created'
| null | null | null | null | Question:
What presses the sync button when ?
Code:
@require_POST
@csrf_protect
def sync(request):
if (not test_user_authenticated(request)):
return login(request, next='/cobbler_web/sync', expired=True)
remote.background_sync({'verbose': 'True'}, request.session['token'])
return HttpResponseRedirect('/cobbler_web/task_created')
|
null | null | null | What does the code return as a dictionary ?
| def run_job(job, raw_input=''):
job.sandbox(stdin=BytesIO(raw_input))
with job.make_runner() as runner:
runner.run()
return dict((job.parse_output_line(line) for line in runner.stream_output()))
| null | null | null | its output
| codeqa | def run job job raw input '' job sandbox stdin Bytes IO raw input with job make runner as runner runner run return dict job parse output line line for line in runner stream output
| null | null | null | null | Question:
What does the code return as a dictionary ?
Code:
def run_job(job, raw_input=''):
job.sandbox(stdin=BytesIO(raw_input))
with job.make_runner() as runner:
runner.run()
return dict((job.parse_output_line(line) for line in runner.stream_output()))
|
null | null | null | How does the code return its output ?
| def run_job(job, raw_input=''):
job.sandbox(stdin=BytesIO(raw_input))
with job.make_runner() as runner:
runner.run()
return dict((job.parse_output_line(line) for line in runner.stream_output()))
| null | null | null | as a dictionary
| codeqa | def run job job raw input '' job sandbox stdin Bytes IO raw input with job make runner as runner runner run return dict job parse output line line for line in runner stream output
| null | null | null | null | Question:
How does the code return its output ?
Code:
def run_job(job, raw_input=''):
job.sandbox(stdin=BytesIO(raw_input))
with job.make_runner() as runner:
runner.run()
return dict((job.parse_output_line(line) for line in runner.stream_output()))
|
null | null | null | What does non - view helper function validate ?
| def validate_campaign(campaign):
return (campaign and (campaign in campaigns.get_campaigns()))
| null | null | null | campaign
| codeqa | def validate campaign campaign return campaign and campaign in campaigns get campaigns
| null | null | null | null | Question:
What does non - view helper function validate ?
Code:
def validate_campaign(campaign):
return (campaign and (campaign in campaigns.get_campaigns()))
|
null | null | null | What did vertex give ?
| def getVertexGivenBinary(byteIndex, stlData):
return Vector3(getFloatGivenBinary(byteIndex, stlData), getFloatGivenBinary((byteIndex + 4), stlData), getFloatGivenBinary((byteIndex + 8), stlData))
| null | null | null | stl vertex line
| codeqa | def get Vertex Given Binary byte Index stl Data return Vector 3 get Float Given Binary byte Index stl Data get Float Given Binary byte Index + 4 stl Data get Float Given Binary byte Index + 8 stl Data
| null | null | null | null | Question:
What did vertex give ?
Code:
def getVertexGivenBinary(byteIndex, stlData):
return Vector3(getFloatGivenBinary(byteIndex, stlData), getFloatGivenBinary((byteIndex + 4), stlData), getFloatGivenBinary((byteIndex + 8), stlData))
|
null | null | null | What finds below a package ?
| def find_modules(import_path, include_packages=False, recursive=False):
module = import_string(import_path)
path = getattr(module, '__path__', None)
if (path is None):
raise ValueError(('%r is not a package' % import_path))
basename = (module.__name__ + '.')
for (importer, modname, ispkg) in pkgutil.iter_modules(path):
modname = (basename + modname)
if ispkg:
if include_packages:
(yield modname)
if recursive:
for item in find_modules(modname, include_packages, True):
(yield item)
else:
(yield modname)
| null | null | null | all the modules
| codeqa | def find modules import path include packages False recursive False module import string import path path getattr module ' path ' None if path is None raise Value Error '%risnotapackage' % import path basename module name + ' ' for importer modname ispkg in pkgutil iter modules path modname basename + modname if ispkg if include packages yield modname if recursive for item in find modules modname include packages True yield item else yield modname
| null | null | null | null | Question:
What finds below a package ?
Code:
def find_modules(import_path, include_packages=False, recursive=False):
module = import_string(import_path)
path = getattr(module, '__path__', None)
if (path is None):
raise ValueError(('%r is not a package' % import_path))
basename = (module.__name__ + '.')
for (importer, modname, ispkg) in pkgutil.iter_modules(path):
modname = (basename + modname)
if ispkg:
if include_packages:
(yield modname)
if recursive:
for item in find_modules(modname, include_packages, True):
(yield item)
else:
(yield modname)
|
null | null | null | Where does all the modules find ?
| def find_modules(import_path, include_packages=False, recursive=False):
module = import_string(import_path)
path = getattr(module, '__path__', None)
if (path is None):
raise ValueError(('%r is not a package' % import_path))
basename = (module.__name__ + '.')
for (importer, modname, ispkg) in pkgutil.iter_modules(path):
modname = (basename + modname)
if ispkg:
if include_packages:
(yield modname)
if recursive:
for item in find_modules(modname, include_packages, True):
(yield item)
else:
(yield modname)
| null | null | null | below a package
| codeqa | def find modules import path include packages False recursive False module import string import path path getattr module ' path ' None if path is None raise Value Error '%risnotapackage' % import path basename module name + ' ' for importer modname ispkg in pkgutil iter modules path modname basename + modname if ispkg if include packages yield modname if recursive for item in find modules modname include packages True yield item else yield modname
| null | null | null | null | Question:
Where does all the modules find ?
Code:
def find_modules(import_path, include_packages=False, recursive=False):
module = import_string(import_path)
path = getattr(module, '__path__', None)
if (path is None):
raise ValueError(('%r is not a package' % import_path))
basename = (module.__name__ + '.')
for (importer, modname, ispkg) in pkgutil.iter_modules(path):
modname = (basename + modname)
if ispkg:
if include_packages:
(yield modname)
if recursive:
for item in find_modules(modname, include_packages, True):
(yield item)
else:
(yield modname)
|
null | null | null | What does the code evaluate ?
| def getEvaluatedExpressionValue(value, xmlElement):
try:
return getEvaluatedExpressionValueBySplitLine(getEvaluatorSplitWords(value), xmlElement)
except:
print 'Warning, in getEvaluatedExpressionValue in evaluate could not get a value for:'
print value
traceback.print_exc(file=sys.stdout)
return None
| null | null | null | the expression value
| codeqa | def get Evaluated Expression Value value xml Element try return get Evaluated Expression Value By Split Line get Evaluator Split Words value xml Element except print ' Warning inget Evaluated Expression Valueinevaluatecouldnotgetavaluefor 'print valuetraceback print exc file sys stdout return None
| null | null | null | null | Question:
What does the code evaluate ?
Code:
def getEvaluatedExpressionValue(value, xmlElement):
try:
return getEvaluatedExpressionValueBySplitLine(getEvaluatorSplitWords(value), xmlElement)
except:
print 'Warning, in getEvaluatedExpressionValue in evaluate could not get a value for:'
print value
traceback.print_exc(file=sys.stdout)
return None
|
null | null | null | What does the code get ?
| def getComplexPathByMultiplier(multiplier, path):
complexPath = []
for point in path:
complexPath.append((multiplier * point))
return complexPath
| null | null | null | the multiplied complex path
| codeqa | def get Complex Path By Multiplier multiplier path complex Path []for point in path complex Path append multiplier * point return complex Path
| null | null | null | null | Question:
What does the code get ?
Code:
def getComplexPathByMultiplier(multiplier, path):
complexPath = []
for point in path:
complexPath.append((multiplier * point))
return complexPath
|
null | null | null | What does the code declare ?
| def DeclareKeyFlags(flag_values=FLAGS):
for flag_name in DECLARED_KEY_FLAGS:
gflags.DECLARE_key_flag(flag_name, flag_values=flag_values)
| null | null | null | a few key flags
| codeqa | def Declare Key Flags flag values FLAGS for flag name in DECLARED KEY FLAGS gflags DECLARE key flag flag name flag values flag values
| null | null | null | null | Question:
What does the code declare ?
Code:
def DeclareKeyFlags(flag_values=FLAGS):
for flag_name in DECLARED_KEY_FLAGS:
gflags.DECLARE_key_flag(flag_name, flag_values=flag_values)
|
null | null | null | What precess their equinoxes ?
| def test_array_precession():
j2000 = Time(u'J2000', scale=u'utc')
j1975 = Time(u'J1975', scale=u'utc')
fk5 = FK5(([1, 1.1] * u.radian), ([0.5, 0.6] * u.radian))
assert (fk5.equinox.jyear == j2000.jyear)
fk5_2 = fk5.transform_to(FK5(equinox=j1975))
assert (fk5_2.equinox.jyear == j1975.jyear)
npt.assert_array_less(0.05, np.abs((fk5.ra.degree - fk5_2.ra.degree)))
npt.assert_array_less(0.05, np.abs((fk5.dec.degree - fk5_2.dec.degree)))
| null | null | null | arrays
| codeqa | def test array precession j2000 Time u'J 2000 ' scale u'utc' j1975 Time u'J 1975 ' scale u'utc' fk 5 FK 5 [1 1 1] * u radian [0 5 0 6] * u radian assert fk 5 equinox jyear j2000 jyear fk 5 2 fk 5 transform to FK 5 equinox j1975 assert fk 5 2 equinox jyear j1975 jyear npt assert array less 0 05 np abs fk 5 ra degree - fk 5 2 ra degree npt assert array less 0 05 np abs fk 5 dec degree - fk 5 2 dec degree
| null | null | null | null | Question:
What precess their equinoxes ?
Code:
def test_array_precession():
j2000 = Time(u'J2000', scale=u'utc')
j1975 = Time(u'J1975', scale=u'utc')
fk5 = FK5(([1, 1.1] * u.radian), ([0.5, 0.6] * u.radian))
assert (fk5.equinox.jyear == j2000.jyear)
fk5_2 = fk5.transform_to(FK5(equinox=j1975))
assert (fk5_2.equinox.jyear == j1975.jyear)
npt.assert_array_less(0.05, np.abs((fk5.ra.degree - fk5_2.ra.degree)))
npt.assert_array_less(0.05, np.abs((fk5.dec.degree - fk5_2.dec.degree)))
|
null | null | null | What do decorator assure ?
| def default_index(func):
@wraps(func)
def check_default_index(self, *args, **kwargs):
if (self._file_path != self._index_path()):
raise AssertionError(('Cannot call %r on indices that do not represent the default git index' % func.__name__))
return func(self, *args, **kwargs)
return check_default_index
| null | null | null | the wrapped method may only run if we are the default repository index
| codeqa | def default index func @wraps func def check default index self *args **kwargs if self file path self index path raise Assertion Error ' Cannotcall%ronindicesthatdonotrepresentthedefaultgitindex' % func name return func self *args **kwargs return check default index
| null | null | null | null | Question:
What do decorator assure ?
Code:
def default_index(func):
@wraps(func)
def check_default_index(self, *args, **kwargs):
if (self._file_path != self._index_path()):
raise AssertionError(('Cannot call %r on indices that do not represent the default git index' % func.__name__))
return func(self, *args, **kwargs)
return check_default_index
|
null | null | null | What is assuring the wrapped method may only run if we are the default repository index ?
| def default_index(func):
@wraps(func)
def check_default_index(self, *args, **kwargs):
if (self._file_path != self._index_path()):
raise AssertionError(('Cannot call %r on indices that do not represent the default git index' % func.__name__))
return func(self, *args, **kwargs)
return check_default_index
| null | null | null | decorator
| codeqa | def default index func @wraps func def check default index self *args **kwargs if self file path self index path raise Assertion Error ' Cannotcall%ronindicesthatdonotrepresentthedefaultgitindex' % func name return func self *args **kwargs return check default index
| null | null | null | null | Question:
What is assuring the wrapped method may only run if we are the default repository index ?
Code:
def default_index(func):
@wraps(func)
def check_default_index(self, *args, **kwargs):
if (self._file_path != self._index_path()):
raise AssertionError(('Cannot call %r on indices that do not represent the default git index' % func.__name__))
return func(self, *args, **kwargs)
return check_default_index
|
null | null | null | What does the code parse to a group ?
| def parse_call_group(source, info, ch, pos):
if (ch == 'R'):
group = '0'
else:
group = (ch + source.get_while(DIGITS))
source.expect(')')
return CallGroup(info, group, pos)
| null | null | null | a call
| codeqa | def parse call group source info ch pos if ch 'R' group '0 'else group ch + source get while DIGITS source expect ' ' return Call Group info group pos
| null | null | null | null | Question:
What does the code parse to a group ?
Code:
def parse_call_group(source, info, ch, pos):
if (ch == 'R'):
group = '0'
else:
group = (ch + source.get_while(DIGITS))
source.expect(')')
return CallGroup(info, group, pos)
|
null | null | null | What contains one or more space - delimited values ?
| def __space_delimited_list(value):
(valid, _value, errmsg) = (False, value, 'space-delimited string')
try:
if hasattr(value, '__iter__'):
valid = True
else:
_value = value.split()
if (_value == []):
raise ValueError
valid = True
except AttributeError:
pass
except ValueError:
pass
return (valid, _value, errmsg)
| null | null | null | a value
| codeqa | def space delimited list value valid value errmsg False value 'space-delimitedstring' try if hasattr value ' iter ' valid Trueelse value value split if value [] raise Value Errorvalid Trueexcept Attribute Error passexcept Value Error passreturn valid value errmsg
| null | null | null | null | Question:
What contains one or more space - delimited values ?
Code:
def __space_delimited_list(value):
(valid, _value, errmsg) = (False, value, 'space-delimited string')
try:
if hasattr(value, '__iter__'):
valid = True
else:
_value = value.split()
if (_value == []):
raise ValueError
valid = True
except AttributeError:
pass
except ValueError:
pass
return (valid, _value, errmsg)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.