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 did the code read ?
| def read(name, *args):
with open(os.path.join(THIS_DIR, name)) as f:
return f.read(*args)
| null | null | null | a file path relative to this file
| codeqa | def read name *args with open os path join THIS DIR name as f return f read *args
| null | null | null | null | Question:
What did the code read ?
Code:
def read(name, *args):
with open(os.path.join(THIS_DIR, name)) as f:
return f.read(*args)
|
null | null | null | What does the code get ?
| def template(*args, **kwargs):
tpl = (args[0] if args else None)
template_adapter = kwargs.pop('template_adapter', SimpleTemplate)
if ((tpl not in TEMPLATES) or DEBUG):
settings = kwargs.pop('template_settings', {})
lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
if isinstance(tpl, template_adapter):
TEMPLATES[tpl] = tpl
if settings:
TEMPLATES[tpl].prepare(**settings)
elif (('\n' in tpl) or ('{' in tpl) or ('%' in tpl) or ('$' in tpl)):
TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
else:
TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
if (not TEMPLATES[tpl]):
abort(500, ('Template (%s) not found' % tpl))
for dictarg in args[1:]:
kwargs.update(dictarg)
return TEMPLATES[tpl].render(kwargs)
| null | null | null | a rendered template as a string iterator
| codeqa | def template *args **kwargs tpl args[ 0 ] if args else None template adapter kwargs pop 'template adapter' Simple Template if tpl not in TEMPLATES or DEBUG settings kwargs pop 'template settings' {} lookup kwargs pop 'template lookup' TEMPLATE PATH if isinstance tpl template adapter TEMPLATES[tpl] tplif settings TEMPLATES[tpl] prepare **settings elif '\n' in tpl or '{' in tpl or '%' in tpl or '$' in tpl TEMPLATES[tpl] template adapter source tpl lookup lookup **settings else TEMPLATES[tpl] template adapter name tpl lookup lookup **settings if not TEMPLATES[tpl] abort 500 ' Template %s notfound' % tpl for dictarg in args[ 1 ] kwargs update dictarg return TEMPLATES[tpl] render kwargs
| null | null | null | null | Question:
What does the code get ?
Code:
def template(*args, **kwargs):
tpl = (args[0] if args else None)
template_adapter = kwargs.pop('template_adapter', SimpleTemplate)
if ((tpl not in TEMPLATES) or DEBUG):
settings = kwargs.pop('template_settings', {})
lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
if isinstance(tpl, template_adapter):
TEMPLATES[tpl] = tpl
if settings:
TEMPLATES[tpl].prepare(**settings)
elif (('\n' in tpl) or ('{' in tpl) or ('%' in tpl) or ('$' in tpl)):
TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
else:
TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
if (not TEMPLATES[tpl]):
abort(500, ('Template (%s) not found' % tpl))
for dictarg in args[1:]:
kwargs.update(dictarg)
return TEMPLATES[tpl].render(kwargs)
|
null | null | null | Till when do a cinder volume detach from a nova host ?
| def _nova_detach(nova_volume_manager, cinder_volume_manager, server_id, cinder_volume):
try:
nova_volume_manager.delete_server_volume(server_id=server_id, attachment_id=cinder_volume.id)
except NovaNotFound:
raise UnattachedVolume(cinder_volume.id)
wait_for_volume_state(volume_manager=cinder_volume_manager, expected_volume=cinder_volume, desired_state=u'available', transient_states=(u'in-use', u'detaching'))
| null | null | null | until the volume has detached
| codeqa | def nova detach nova volume manager cinder volume manager server id cinder volume try nova volume manager delete server volume server id server id attachment id cinder volume id except Nova Not Found raise Unattached Volume cinder volume id wait for volume state volume manager cinder volume manager expected volume cinder volume desired state u'available' transient states u'in-use' u'detaching'
| null | null | null | null | Question:
Till when do a cinder volume detach from a nova host ?
Code:
def _nova_detach(nova_volume_manager, cinder_volume_manager, server_id, cinder_volume):
try:
nova_volume_manager.delete_server_volume(server_id=server_id, attachment_id=cinder_volume.id)
except NovaNotFound:
raise UnattachedVolume(cinder_volume.id)
wait_for_volume_state(volume_manager=cinder_volume_manager, expected_volume=cinder_volume, desired_state=u'available', transient_states=(u'in-use', u'detaching'))
|
null | null | null | What does the code get ?
| def getAxialMargin(circleRadius, numberOfSides, polygonRadius):
return ((polygonRadius * math.sin((math.pi / float(numberOfSides)))) - circleRadius)
| null | null | null | axial margin
| codeqa | def get Axial Margin circle Radius number Of Sides polygon Radius return polygon Radius * math sin math pi / float number Of Sides - circle Radius
| null | null | null | null | Question:
What does the code get ?
Code:
def getAxialMargin(circleRadius, numberOfSides, polygonRadius):
return ((polygonRadius * math.sin((math.pi / float(numberOfSides)))) - circleRadius)
|
null | null | null | How do link function second derivatives check ?
| def test_deriv2():
np.random.seed(24235)
for link in Links:
if (type(link) == type(probit)):
continue
for k in range(10):
p = np.random.uniform(0, 1)
p = np.clip(p, 0.01, 0.99)
if (type(link) == type(cauchy)):
p = np.clip(p, 0.03, 0.97)
d = link.deriv2(p)
da = nd.approx_fprime(np.r_[p], link.deriv)
assert_allclose(d, da, rtol=1e-06, atol=1e-06, err_msg=str(link))
| null | null | null | using numeric differentiation
| codeqa | def test deriv 2 np random seed 24235 for link in Links if type link type probit continuefor k in range 10 p np random uniform 0 1 p np clip p 0 01 0 99 if type link type cauchy p np clip p 0 03 0 97 d link deriv 2 p da nd approx fprime np r [p] link deriv assert allclose d da rtol 1e- 06 atol 1e- 06 err msg str link
| null | null | null | null | Question:
How do link function second derivatives check ?
Code:
def test_deriv2():
np.random.seed(24235)
for link in Links:
if (type(link) == type(probit)):
continue
for k in range(10):
p = np.random.uniform(0, 1)
p = np.clip(p, 0.01, 0.99)
if (type(link) == type(cauchy)):
p = np.clip(p, 0.03, 0.97)
d = link.deriv2(p)
da = nd.approx_fprime(np.r_[p], link.deriv)
assert_allclose(d, da, rtol=1e-06, atol=1e-06, err_msg=str(link))
|
null | null | null | What give admins the ability to unban a user ?
| @require_chanmsg
@require_privilege(OP, u'You are not a channel operator.')
@commands(u'unban')
def unban(bot, trigger):
if (bot.privileges[trigger.sender][bot.nick] < HALFOP):
return bot.reply(u"I'm not a channel operator!")
text = trigger.group().split()
argc = len(text)
if (argc < 2):
return
opt = Identifier(text[1])
banmask = opt
channel = trigger.sender
if (not opt.is_nick()):
if (argc < 3):
return
channel = opt
banmask = text[2]
banmask = configureHostMask(banmask)
if (banmask == u''):
return
bot.write([u'MODE', channel, u'-b', banmask])
| null | null | null | this
| codeqa | @require chanmsg@require privilege OP u' Youarenotachanneloperator ' @commands u'unban' def unban bot trigger if bot privileges[trigger sender][bot nick] < HALFOP return bot reply u"I'mnotachanneloperator " text trigger group split argc len text if argc < 2 returnopt Identifier text[ 1 ] banmask optchannel trigger senderif not opt is nick if argc < 3 returnchannel optbanmask text[ 2 ]banmask configure Host Mask banmask if banmask u'' returnbot write [u'MODE' channel u'-b' banmask]
| null | null | null | null | Question:
What give admins the ability to unban a user ?
Code:
@require_chanmsg
@require_privilege(OP, u'You are not a channel operator.')
@commands(u'unban')
def unban(bot, trigger):
if (bot.privileges[trigger.sender][bot.nick] < HALFOP):
return bot.reply(u"I'm not a channel operator!")
text = trigger.group().split()
argc = len(text)
if (argc < 2):
return
opt = Identifier(text[1])
banmask = opt
channel = trigger.sender
if (not opt.is_nick()):
if (argc < 3):
return
channel = opt
banmask = text[2]
banmask = configureHostMask(banmask)
if (banmask == u''):
return
bot.write([u'MODE', channel, u'-b', banmask])
|
null | null | null | What give the ability to unban a user admins ?
| @require_chanmsg
@require_privilege(OP, u'You are not a channel operator.')
@commands(u'unban')
def unban(bot, trigger):
if (bot.privileges[trigger.sender][bot.nick] < HALFOP):
return bot.reply(u"I'm not a channel operator!")
text = trigger.group().split()
argc = len(text)
if (argc < 2):
return
opt = Identifier(text[1])
banmask = opt
channel = trigger.sender
if (not opt.is_nick()):
if (argc < 3):
return
channel = opt
banmask = text[2]
banmask = configureHostMask(banmask)
if (banmask == u''):
return
bot.write([u'MODE', channel, u'-b', banmask])
| null | null | null | this
| codeqa | @require chanmsg@require privilege OP u' Youarenotachanneloperator ' @commands u'unban' def unban bot trigger if bot privileges[trigger sender][bot nick] < HALFOP return bot reply u"I'mnotachanneloperator " text trigger group split argc len text if argc < 2 returnopt Identifier text[ 1 ] banmask optchannel trigger senderif not opt is nick if argc < 3 returnchannel optbanmask text[ 2 ]banmask configure Host Mask banmask if banmask u'' returnbot write [u'MODE' channel u'-b' banmask]
| null | null | null | null | Question:
What give the ability to unban a user admins ?
Code:
@require_chanmsg
@require_privilege(OP, u'You are not a channel operator.')
@commands(u'unban')
def unban(bot, trigger):
if (bot.privileges[trigger.sender][bot.nick] < HALFOP):
return bot.reply(u"I'm not a channel operator!")
text = trigger.group().split()
argc = len(text)
if (argc < 2):
return
opt = Identifier(text[1])
banmask = opt
channel = trigger.sender
if (not opt.is_nick()):
if (argc < 3):
return
channel = opt
banmask = text[2]
banmask = configureHostMask(banmask)
if (banmask == u''):
return
bot.write([u'MODE', channel, u'-b', banmask])
|
null | null | null | What did the code set ?
| def s3_set_default_filter(selector, value, tablename=None):
s3 = current.response.s3
filter_defaults = s3
for level in ('filter_defaults', tablename):
if (level not in filter_defaults):
filter_defaults[level] = {}
filter_defaults = filter_defaults[level]
filter_defaults[selector] = value
| null | null | null | a default filter for selector
| codeqa | def s3 set default filter selector value tablename None s3 current response s3 filter defaults s3 for level in 'filter defaults' tablename if level not in filter defaults filter defaults[level] {}filter defaults filter defaults[level]filter defaults[selector] value
| null | null | null | null | Question:
What did the code set ?
Code:
def s3_set_default_filter(selector, value, tablename=None):
s3 = current.response.s3
filter_defaults = s3
for level in ('filter_defaults', tablename):
if (level not in filter_defaults):
filter_defaults[level] = {}
filter_defaults = filter_defaults[level]
filter_defaults[selector] = value
|
null | null | null | What does the code run ?
| def InitAndRun(run_callback, shutdown_callback=None, scan_ops=False, server_logging=True):
main.InitAndRun(run_callback=partial(_StartWWW, run_callback, scan_ops), shutdown_callback=shutdown_callback, server_logging=server_logging)
| null | null | null | the main initialization routine
| codeqa | def Init And Run run callback shutdown callback None scan ops False server logging True main Init And Run run callback partial Start WWW run callback scan ops shutdown callback shutdown callback server logging server logging
| null | null | null | null | Question:
What does the code run ?
Code:
def InitAndRun(run_callback, shutdown_callback=None, scan_ops=False, server_logging=True):
main.InitAndRun(run_callback=partial(_StartWWW, run_callback, scan_ops), shutdown_callback=shutdown_callback, server_logging=server_logging)
|
null | null | null | What does the code make ?
| def ensure_tables():
global tables
if (tables is None):
import tables
| null | null | null | sure tables module has been imported
| codeqa | def ensure tables global tablesif tables is None import tables
| null | null | null | null | Question:
What does the code make ?
Code:
def ensure_tables():
global tables
if (tables is None):
import tables
|
null | null | null | What does the code take ?
| def iso_time_string(val, show_tzinfo=False):
if (not val):
return ''
if isinstance(val, six.string_types):
dt = _parse_datetime_string(val)
else:
dt = val
if (not isinstance(dt, datetime.datetime)):
dt = datetime.datetime.fromordinal(dt.toordinal())
has_tz = (dt.tzinfo is not None)
if (show_tzinfo and has_tz):
ret = ''.join(dt.isoformat().rsplit(':', 1))
elif (show_tzinfo and (not has_tz)):
ret = ('%s+0000' % dt.isoformat().split('.')[0])
elif ((not show_tzinfo) and has_tz):
ret = dt.isoformat()[:(-6)]
elif ((not show_tzinfo) and (not has_tz)):
ret = dt.isoformat().split('.')[0]
return ret
| null | null | null | either a date
| codeqa | def iso time string val show tzinfo False if not val return ''if isinstance val six string types dt parse datetime string val else dt valif not isinstance dt datetime datetime dt datetime datetime fromordinal dt toordinal has tz dt tzinfo is not None if show tzinfo and has tz ret '' join dt isoformat rsplit ' ' 1 elif show tzinfo and not has tz ret '%s+ 0000 ' % dt isoformat split ' ' [0 ] elif not show tzinfo and has tz ret dt isoformat [ -6 ]elif not show tzinfo and not has tz ret dt isoformat split ' ' [0 ]return ret
| null | null | null | null | Question:
What does the code take ?
Code:
def iso_time_string(val, show_tzinfo=False):
if (not val):
return ''
if isinstance(val, six.string_types):
dt = _parse_datetime_string(val)
else:
dt = val
if (not isinstance(dt, datetime.datetime)):
dt = datetime.datetime.fromordinal(dt.toordinal())
has_tz = (dt.tzinfo is not None)
if (show_tzinfo and has_tz):
ret = ''.join(dt.isoformat().rsplit(':', 1))
elif (show_tzinfo and (not has_tz)):
ret = ('%s+0000' % dt.isoformat().split('.')[0])
elif ((not show_tzinfo) and has_tz):
ret = dt.isoformat()[:(-6)]
elif ((not show_tzinfo) and (not has_tz)):
ret = dt.isoformat().split('.')[0]
return ret
|
null | null | null | What provided in train_indexes and test_indexes ?
| def split(train_indexes, test_indexes, *args):
ret = []
for arg in args:
arg = np.asanyarray(arg)
arg_train = arg[train_indexes]
arg_test = arg[test_indexes]
ret.append(arg_train)
ret.append(arg_test)
return ret
| null | null | null | indexes
| codeqa | def split train indexes test indexes *args ret []for arg in args arg np asanyarray arg arg train arg[train indexes]arg test arg[test indexes]ret append arg train ret append arg test return ret
| null | null | null | null | Question:
What provided in train_indexes and test_indexes ?
Code:
def split(train_indexes, test_indexes, *args):
ret = []
for arg in args:
arg = np.asanyarray(arg)
arg_train = arg[train_indexes]
arg_test = arg[test_indexes]
ret.append(arg_train)
ret.append(arg_test)
return ret
|
null | null | null | Where did indexes provide ?
| def split(train_indexes, test_indexes, *args):
ret = []
for arg in args:
arg = np.asanyarray(arg)
arg_train = arg[train_indexes]
arg_test = arg[test_indexes]
ret.append(arg_train)
ret.append(arg_test)
return ret
| null | null | null | in train_indexes and test_indexes
| codeqa | def split train indexes test indexes *args ret []for arg in args arg np asanyarray arg arg train arg[train indexes]arg test arg[test indexes]ret append arg train ret append arg test return ret
| null | null | null | null | Question:
Where did indexes provide ?
Code:
def split(train_indexes, test_indexes, *args):
ret = []
for arg in args:
arg = np.asanyarray(arg)
arg_train = arg[train_indexes]
arg_test = arg[test_indexes]
ret.append(arg_train)
ret.append(arg_test)
return ret
|
null | null | null | Where do something be ?
| def addVector3Loop(loop, loops, vertexes, z):
vector3Loop = []
for point in loop:
vector3Index = Vector3Index(len(vertexes), point.real, point.imag, z)
vector3Loop.append(vector3Index)
vertexes.append(vector3Index)
if (len(vector3Loop) > 0):
loops.append(vector3Loop)
| null | null | null | in it
| codeqa | def add Vector 3 Loop loop loops vertexes z vector 3 Loop []for point in loop vector 3 Index Vector 3 Index len vertexes point real point imag z vector 3 Loop append vector 3 Index vertexes append vector 3 Index if len vector 3 Loop > 0 loops append vector 3 Loop
| null | null | null | null | Question:
Where do something be ?
Code:
def addVector3Loop(loop, loops, vertexes, z):
vector3Loop = []
for point in loop:
vector3Index = Vector3Index(len(vertexes), point.real, point.imag, z)
vector3Loop.append(vector3Index)
vertexes.append(vector3Index)
if (len(vector3Loop) > 0):
loops.append(vector3Loop)
|
null | null | null | What is in it ?
| def addVector3Loop(loop, loops, vertexes, z):
vector3Loop = []
for point in loop:
vector3Index = Vector3Index(len(vertexes), point.real, point.imag, z)
vector3Loop.append(vector3Index)
vertexes.append(vector3Index)
if (len(vector3Loop) > 0):
loops.append(vector3Loop)
| null | null | null | something
| codeqa | def add Vector 3 Loop loop loops vertexes z vector 3 Loop []for point in loop vector 3 Index Vector 3 Index len vertexes point real point imag z vector 3 Loop append vector 3 Index vertexes append vector 3 Index if len vector 3 Loop > 0 loops append vector 3 Loop
| null | null | null | null | Question:
What is in it ?
Code:
def addVector3Loop(loop, loops, vertexes, z):
vector3Loop = []
for point in loop:
vector3Index = Vector3Index(len(vertexes), point.real, point.imag, z)
vector3Loop.append(vector3Index)
vertexes.append(vector3Index)
if (len(vector3Loop) > 0):
loops.append(vector3Loop)
|
null | null | null | How do salts renderer ?
| def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
if ((not path) and (not string)):
raise salt.exceptions.SaltInvocationError('Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = path
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
return salt.template.compile_template(path_or_string, renderers, default_renderer, __opts__['renderer_blacklist'], __opts__['renderer_whitelist'], **kwargs)
| null | null | null | through
| codeqa | def renderer path None string None default renderer 'jinja yaml' **kwargs if not path and not string raise salt exceptions Salt Invocation Error ' Mustpasseitherpathorstring' renderers salt loader render opts salt if path path or string pathelif string path or string ' string 'kwargs['input data'] stringreturn salt template compile template path or string renderers default renderer opts ['renderer blacklist'] opts ['renderer whitelist'] **kwargs
| null | null | null | null | Question:
How do salts renderer ?
Code:
def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
if ((not path) and (not string)):
raise salt.exceptions.SaltInvocationError('Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = path
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
return salt.template.compile_template(path_or_string, renderers, default_renderer, __opts__['renderer_blacklist'], __opts__['renderer_whitelist'], **kwargs)
|
null | null | null | What does standard deviation 1 ignore ?
| def rescale(data_matrix):
(means, stdevs) = scale(data_matrix)
def rescaled(i, j):
if (stdevs[j] > 0):
return ((data_matrix[i][j] - means[j]) / stdevs[j])
else:
return data_matrix[i][j]
(num_rows, num_cols) = shape(data_matrix)
return make_matrix(num_rows, num_cols, rescaled)
| null | null | null | columns with no deviation
| codeqa | def rescale data matrix means stdevs scale data matrix def rescaled i j if stdevs[j] > 0 return data matrix[i][j] - means[j] / stdevs[j] else return data matrix[i][j] num rows num cols shape data matrix return make matrix num rows num cols rescaled
| null | null | null | null | Question:
What does standard deviation 1 ignore ?
Code:
def rescale(data_matrix):
(means, stdevs) = scale(data_matrix)
def rescaled(i, j):
if (stdevs[j] > 0):
return ((data_matrix[i][j] - means[j]) / stdevs[j])
else:
return data_matrix[i][j]
(num_rows, num_cols) = shape(data_matrix)
return make_matrix(num_rows, num_cols, rescaled)
|
null | null | null | For what purpose does the code rescale the input data ?
| def rescale(data_matrix):
(means, stdevs) = scale(data_matrix)
def rescaled(i, j):
if (stdevs[j] > 0):
return ((data_matrix[i][j] - means[j]) / stdevs[j])
else:
return data_matrix[i][j]
(num_rows, num_cols) = shape(data_matrix)
return make_matrix(num_rows, num_cols, rescaled)
| null | null | null | so that each column has mean 0 and standard deviation 1 ignores columns with no deviation
| codeqa | def rescale data matrix means stdevs scale data matrix def rescaled i j if stdevs[j] > 0 return data matrix[i][j] - means[j] / stdevs[j] else return data matrix[i][j] num rows num cols shape data matrix return make matrix num rows num cols rescaled
| null | null | null | null | Question:
For what purpose does the code rescale the input data ?
Code:
def rescale(data_matrix):
(means, stdevs) = scale(data_matrix)
def rescaled(i, j):
if (stdevs[j] > 0):
return ((data_matrix[i][j] - means[j]) / stdevs[j])
else:
return data_matrix[i][j]
(num_rows, num_cols) = shape(data_matrix)
return make_matrix(num_rows, num_cols, rescaled)
|
null | null | null | What ignores columns with no deviation ?
| def rescale(data_matrix):
(means, stdevs) = scale(data_matrix)
def rescaled(i, j):
if (stdevs[j] > 0):
return ((data_matrix[i][j] - means[j]) / stdevs[j])
else:
return data_matrix[i][j]
(num_rows, num_cols) = shape(data_matrix)
return make_matrix(num_rows, num_cols, rescaled)
| null | null | null | standard deviation 1
| codeqa | def rescale data matrix means stdevs scale data matrix def rescaled i j if stdevs[j] > 0 return data matrix[i][j] - means[j] / stdevs[j] else return data matrix[i][j] num rows num cols shape data matrix return make matrix num rows num cols rescaled
| null | null | null | null | Question:
What ignores columns with no deviation ?
Code:
def rescale(data_matrix):
(means, stdevs) = scale(data_matrix)
def rescaled(i, j):
if (stdevs[j] > 0):
return ((data_matrix[i][j] - means[j]) / stdevs[j])
else:
return data_matrix[i][j]
(num_rows, num_cols) = shape(data_matrix)
return make_matrix(num_rows, num_cols, rescaled)
|
null | null | null | What does the code rescale so that each column has mean 0 and standard deviation 1 ignores columns with no deviation ?
| def rescale(data_matrix):
(means, stdevs) = scale(data_matrix)
def rescaled(i, j):
if (stdevs[j] > 0):
return ((data_matrix[i][j] - means[j]) / stdevs[j])
else:
return data_matrix[i][j]
(num_rows, num_cols) = shape(data_matrix)
return make_matrix(num_rows, num_cols, rescaled)
| null | null | null | the input data
| codeqa | def rescale data matrix means stdevs scale data matrix def rescaled i j if stdevs[j] > 0 return data matrix[i][j] - means[j] / stdevs[j] else return data matrix[i][j] num rows num cols shape data matrix return make matrix num rows num cols rescaled
| null | null | null | null | Question:
What does the code rescale so that each column has mean 0 and standard deviation 1 ignores columns with no deviation ?
Code:
def rescale(data_matrix):
(means, stdevs) = scale(data_matrix)
def rescaled(i, j):
if (stdevs[j] > 0):
return ((data_matrix[i][j] - means[j]) / stdevs[j])
else:
return data_matrix[i][j]
(num_rows, num_cols) = shape(data_matrix)
return make_matrix(num_rows, num_cols, rescaled)
|
null | null | null | What does the code destroy ?
| def destroy(name, stop=False, path=None):
_ensure_exists(name, path=path)
if ((not stop) and (state(name, path=path) != 'stopped')):
raise CommandExecutionError("Container '{0}' is not stopped".format(name))
return _change_state('lxc-destroy', name, None, path=path)
| null | null | null | the named container
| codeqa | def destroy name stop False path None ensure exists name path path if not stop and state name path path 'stopped' raise Command Execution Error " Container'{ 0 }'isnotstopped" format name return change state 'lxc-destroy' name None path path
| null | null | null | null | Question:
What does the code destroy ?
Code:
def destroy(name, stop=False, path=None):
_ensure_exists(name, path=path)
if ((not stop) and (state(name, path=path) != 'stopped')):
raise CommandExecutionError("Container '{0}' is not stopped".format(name))
return _change_state('lxc-destroy', name, None, path=path)
|
null | null | null | What does the code create ?
| def create_relationship(model, instance, relation):
result = {}
pk_value = primary_key_value(instance)
self_link = url_for(model, pk_value, relation, relationship=True)
related_link = url_for(model, pk_value, relation)
result['links'] = {'self': self_link}
try:
related_model = get_related_model(model, relation)
url_for(related_model)
except ValueError:
pass
else:
result['links']['related'] = related_link
related_value = getattr(instance, relation)
if is_like_list(instance, relation):
result['data'] = list(map(simple_relationship_dump, related_value))
elif (related_value is not None):
result['data'] = simple_relationship_dump(related_value)
else:
result['data'] = None
return result
| null | null | null | a relationship from the given relation name
| codeqa | def create relationship model instance relation result {}pk value primary key value instance self link url for model pk value relation relationship True related link url for model pk value relation result['links'] {'self' self link}try related model get related model model relation url for related model except Value Error passelse result['links']['related'] related linkrelated value getattr instance relation if is like list instance relation result['data'] list map simple relationship dump related value elif related value is not None result['data'] simple relationship dump related value else result['data'] Nonereturn result
| null | null | null | null | Question:
What does the code create ?
Code:
def create_relationship(model, instance, relation):
result = {}
pk_value = primary_key_value(instance)
self_link = url_for(model, pk_value, relation, relationship=True)
related_link = url_for(model, pk_value, relation)
result['links'] = {'self': self_link}
try:
related_model = get_related_model(model, relation)
url_for(related_model)
except ValueError:
pass
else:
result['links']['related'] = related_link
related_value = getattr(instance, relation)
if is_like_list(instance, relation):
result['data'] = list(map(simple_relationship_dump, related_value))
elif (related_value is not None):
result['data'] = simple_relationship_dump(related_value)
else:
result['data'] = None
return result
|
null | null | null | What installs a package via pythons ?
| def install_python(name, version=None, install_args=None, override_args=False):
return install(name, version=version, source='python', install_args=install_args, override_args=override_args)
| null | null | null | chocolatey
| codeqa | def install python name version None install args None override args False return install name version version source 'python' install args install args override args override args
| null | null | null | null | Question:
What installs a package via pythons ?
Code:
def install_python(name, version=None, install_args=None, override_args=False):
return install(name, version=version, source='python', install_args=install_args, override_args=override_args)
|
null | null | null | What does the code take ?
| def sanitizeSceneName(name, anime=False):
if (not name):
return u''
bad_chars = u',:()!?\u2019'
if (not anime):
bad_chars += u"'"
for x in bad_chars:
name = name.replace(x, u'')
name = name.replace(u'&', u'and')
name = re.sub(u'[- /]+', u'.', name)
name = re.sub(u'[.]+', u'.', name)
if name.endswith(u'.'):
name = name[:(-1)]
return name
| null | null | null | a show name
| codeqa | def sanitize Scene Name name anime False if not name return u''bad chars u' ?\u 2019 'if not anime bad chars + u"'"for x in bad chars name name replace x u'' name name replace u'&' u'and' name re sub u'[-/]+' u' ' name name re sub u'[ ]+' u' ' name if name endswith u' ' name name[ -1 ]return name
| null | null | null | null | Question:
What does the code take ?
Code:
def sanitizeSceneName(name, anime=False):
if (not name):
return u''
bad_chars = u',:()!?\u2019'
if (not anime):
bad_chars += u"'"
for x in bad_chars:
name = name.replace(x, u'')
name = name.replace(u'&', u'and')
name = re.sub(u'[- /]+', u'.', name)
name = re.sub(u'[.]+', u'.', name)
if name.endswith(u'.'):
name = name[:(-1)]
return name
|
null | null | null | What does the code get from the intersection loops ?
| def getCentersFromIntersectionLoops(circleIntersectionLoops, radius):
centers = []
for circleIntersectionLoop in circleIntersectionLoops:
centers.append(getCentersFromIntersectionLoop(circleIntersectionLoop, radius))
return centers
| null | null | null | the centers
| codeqa | def get Centers From Intersection Loops circle Intersection Loops radius centers []for circle Intersection Loop in circle Intersection Loops centers append get Centers From Intersection Loop circle Intersection Loop radius return centers
| null | null | null | null | Question:
What does the code get from the intersection loops ?
Code:
def getCentersFromIntersectionLoops(circleIntersectionLoops, radius):
centers = []
for circleIntersectionLoop in circleIntersectionLoops:
centers.append(getCentersFromIntersectionLoop(circleIntersectionLoop, radius))
return centers
|
null | null | null | What will this submit to the provided connection ?
| def submit_and_wait_for_completion(unit_test, connection, start, end, increment, precision, split_range=False):
pending_callbacks = []
completed_callbacks = []
for gross_time in range(start, end, increment):
timeout = get_timeout(gross_time, start, end, precision, split_range)
callback = TimerCallback(timeout)
connection.create_timer(timeout, callback.invoke)
pending_callbacks.append(callback)
while (len(pending_callbacks) is not 0):
for callback in pending_callbacks:
if callback.was_invoked():
pending_callbacks.remove(callback)
completed_callbacks.append(callback)
time.sleep(0.1)
for callback in completed_callbacks:
unit_test.assertAlmostEqual(callback.expected_wait, callback.get_wait_time(), delta=0.15)
| null | null | null | a number of timers
| codeqa | def submit and wait for completion unit test connection start end increment precision split range False pending callbacks []completed callbacks []for gross time in range start end increment timeout get timeout gross time start end precision split range callback Timer Callback timeout connection create timer timeout callback invoke pending callbacks append callback while len pending callbacks is not 0 for callback in pending callbacks if callback was invoked pending callbacks remove callback completed callbacks append callback time sleep 0 1 for callback in completed callbacks unit test assert Almost Equal callback expected wait callback get wait time delta 0 15
| null | null | null | null | Question:
What will this submit to the provided connection ?
Code:
def submit_and_wait_for_completion(unit_test, connection, start, end, increment, precision, split_range=False):
pending_callbacks = []
completed_callbacks = []
for gross_time in range(start, end, increment):
timeout = get_timeout(gross_time, start, end, precision, split_range)
callback = TimerCallback(timeout)
connection.create_timer(timeout, callback.invoke)
pending_callbacks.append(callback)
while (len(pending_callbacks) is not 0):
for callback in pending_callbacks:
if callback.was_invoked():
pending_callbacks.remove(callback)
completed_callbacks.append(callback)
time.sleep(0.1)
for callback in completed_callbacks:
unit_test.assertAlmostEqual(callback.expected_wait, callback.get_wait_time(), delta=0.15)
|
null | null | null | What will submit a number of timers to the provided connection ?
| def submit_and_wait_for_completion(unit_test, connection, start, end, increment, precision, split_range=False):
pending_callbacks = []
completed_callbacks = []
for gross_time in range(start, end, increment):
timeout = get_timeout(gross_time, start, end, precision, split_range)
callback = TimerCallback(timeout)
connection.create_timer(timeout, callback.invoke)
pending_callbacks.append(callback)
while (len(pending_callbacks) is not 0):
for callback in pending_callbacks:
if callback.was_invoked():
pending_callbacks.remove(callback)
completed_callbacks.append(callback)
time.sleep(0.1)
for callback in completed_callbacks:
unit_test.assertAlmostEqual(callback.expected_wait, callback.get_wait_time(), delta=0.15)
| null | null | null | this
| codeqa | def submit and wait for completion unit test connection start end increment precision split range False pending callbacks []completed callbacks []for gross time in range start end increment timeout get timeout gross time start end precision split range callback Timer Callback timeout connection create timer timeout callback invoke pending callbacks append callback while len pending callbacks is not 0 for callback in pending callbacks if callback was invoked pending callbacks remove callback completed callbacks append callback time sleep 0 1 for callback in completed callbacks unit test assert Almost Equal callback expected wait callback get wait time delta 0 15
| null | null | null | null | Question:
What will submit a number of timers to the provided connection ?
Code:
def submit_and_wait_for_completion(unit_test, connection, start, end, increment, precision, split_range=False):
pending_callbacks = []
completed_callbacks = []
for gross_time in range(start, end, increment):
timeout = get_timeout(gross_time, start, end, precision, split_range)
callback = TimerCallback(timeout)
connection.create_timer(timeout, callback.invoke)
pending_callbacks.append(callback)
while (len(pending_callbacks) is not 0):
for callback in pending_callbacks:
if callback.was_invoked():
pending_callbacks.remove(callback)
completed_callbacks.append(callback)
time.sleep(0.1)
for callback in completed_callbacks:
unit_test.assertAlmostEqual(callback.expected_wait, callback.get_wait_time(), delta=0.15)
|
null | null | null | What differ first position ?
| def diff_pos(string1, string2):
for (count, c) in enumerate(string1):
if (len(string2) <= count):
return count
if (string2[count] != c):
return count
| null | null | null | string1 and string2
| codeqa | def diff pos string 1 string 2 for count c in enumerate string 1 if len string 2 < count return countif string 2 [count] c return count
| null | null | null | null | Question:
What differ first position ?
Code:
def diff_pos(string1, string2):
for (count, c) in enumerate(string1):
if (len(string2) <= count):
return count
if (string2[count] != c):
return count
|
null | null | null | Where do string1 and string2 differ ?
| def diff_pos(string1, string2):
for (count, c) in enumerate(string1):
if (len(string2) <= count):
return count
if (string2[count] != c):
return count
| null | null | null | first position
| codeqa | def diff pos string 1 string 2 for count c in enumerate string 1 if len string 2 < count return countif string 2 [count] c return count
| null | null | null | null | Question:
Where do string1 and string2 differ ?
Code:
def diff_pos(string1, string2):
for (count, c) in enumerate(string1):
if (len(string2) <= count):
return count
if (string2[count] != c):
return count
|
null | null | null | What does the code create from dictionary mapping ?
| def storify(mapping, *requireds, **defaults):
stor = Storage()
for key in (requireds + tuple(mapping.keys())):
value = mapping[key]
if isinstance(value, list):
value = value[(-1)]
if hasattr(value, 'value'):
value = value.value
setattr(stor, key, value)
for (key, value) in defaults.iteritems():
result = value
if hasattr(stor, key):
result = stor[key]
if ((value == ()) and (not isinstance(result, tuple))):
result = (result,)
setattr(stor, key, result)
return stor
| null | null | null | a storage object
| codeqa | def storify mapping *requireds **defaults stor Storage for key in requireds + tuple mapping keys value mapping[key]if isinstance value list value value[ -1 ]if hasattr value 'value' value value valuesetattr stor key value for key value in defaults iteritems result valueif hasattr stor key result stor[key]if value and not isinstance result tuple result result setattr stor key result return stor
| null | null | null | null | Question:
What does the code create from dictionary mapping ?
Code:
def storify(mapping, *requireds, **defaults):
stor = Storage()
for key in (requireds + tuple(mapping.keys())):
value = mapping[key]
if isinstance(value, list):
value = value[(-1)]
if hasattr(value, 'value'):
value = value.value
setattr(stor, key, value)
for (key, value) in defaults.iteritems():
result = value
if hasattr(stor, key):
result = stor[key]
if ((value == ()) and (not isinstance(result, tuple))):
result = (result,)
setattr(stor, key, result)
return stor
|
null | null | null | What does the code run ?
| def _runMultiple(tupleList):
for (f, args, kwargs) in tupleList:
f(*args, **kwargs)
| null | null | null | a list of functions
| codeqa | def run Multiple tuple List for f args kwargs in tuple List f *args **kwargs
| null | null | null | null | Question:
What does the code run ?
Code:
def _runMultiple(tupleList):
for (f, args, kwargs) in tupleList:
f(*args, **kwargs)
|
null | null | null | What does the code get ?
| def getNewDerivation(elementNode, prefix, sideLength):
return TransformDerivation(elementNode, prefix)
| null | null | null | new derivation
| codeqa | def get New Derivation element Node prefix side Length return Transform Derivation element Node prefix
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewDerivation(elementNode, prefix, sideLength):
return TransformDerivation(elementNode, prefix)
|
null | null | null | By how much do mode exist ?
| def test_extract_array_wrong_mode():
with pytest.raises(ValueError) as e:
extract_array(np.arange(4), (2,), (0,), mode=u'full')
assert (u"Valid modes are 'partial', 'trim', and 'strict'." == str(e.value))
| null | null | null | non
| codeqa | def test extract array wrong mode with pytest raises Value Error as e extract array np arange 4 2 0 mode u'full' assert u" Validmodesare'partial' 'trim' and'strict' " str e value
| null | null | null | null | Question:
By how much do mode exist ?
Code:
def test_extract_array_wrong_mode():
with pytest.raises(ValueError) as e:
extract_array(np.arange(4), (2,), (0,), mode=u'full')
assert (u"Valid modes are 'partial', 'trim', and 'strict'." == str(e.value))
|
null | null | null | What is defining test cases ?
| def pyUnitTests():
s = unittest.TestSuite()
for (filename, test_num, expected, case) in getCases():
s.addTest(_TestCase(filename, str(test_num), expected, case))
return s
| null | null | null | a file
| codeqa | def py Unit Tests s unittest Test Suite for filename test num expected case in get Cases s add Test Test Case filename str test num expected case return s
| null | null | null | null | Question:
What is defining test cases ?
Code:
def pyUnitTests():
s = unittest.TestSuite()
for (filename, test_num, expected, case) in getCases():
s.addTest(_TestCase(filename, str(test_num), expected, case))
return s
|
null | null | null | What does the code generate ?
| def get_config_file(paths=None):
if (paths is None):
paths = [os.path.join(path, 'ivre.conf') for path in ['/etc', '/etc/ivre', '/usr/local/etc', '/usr/local/etc/ivre']]
paths.append(os.path.join(os.path.expanduser('~'), '.ivre.conf'))
for path in paths:
if os.path.isfile(path):
(yield path)
| null | null | null | the available config files
| codeqa | def get config file paths None if paths is None paths [os path join path 'ivre conf' for path in ['/etc' '/etc/ivre' '/usr/local/etc' '/usr/local/etc/ivre']]paths append os path join os path expanduser '~' ' ivre conf' for path in paths if os path isfile path yield path
| null | null | null | null | Question:
What does the code generate ?
Code:
def get_config_file(paths=None):
if (paths is None):
paths = [os.path.join(path, 'ivre.conf') for path in ['/etc', '/etc/ivre', '/usr/local/etc', '/usr/local/etc/ivre']]
paths.append(os.path.join(os.path.expanduser('~'), '.ivre.conf'))
for path in paths:
if os.path.isfile(path):
(yield path)
|
null | null | null | What does the code add from grid ?
| def addFacesByGrid(faces, grid):
cellTopLoops = getIndexedCellLoopsFromIndexedGrid(grid)
for cellTopLoop in cellTopLoops:
addFacesByConvex(faces, cellTopLoop)
| null | null | null | faces
| codeqa | def add Faces By Grid faces grid cell Top Loops get Indexed Cell Loops From Indexed Grid grid for cell Top Loop in cell Top Loops add Faces By Convex faces cell Top Loop
| null | null | null | null | Question:
What does the code add from grid ?
Code:
def addFacesByGrid(faces, grid):
cellTopLoops = getIndexedCellLoopsFromIndexedGrid(grid)
for cellTopLoop in cellTopLoops:
addFacesByConvex(faces, cellTopLoop)
|
null | null | null | In which direction does the code add faces ?
| def addFacesByGrid(faces, grid):
cellTopLoops = getIndexedCellLoopsFromIndexedGrid(grid)
for cellTopLoop in cellTopLoops:
addFacesByConvex(faces, cellTopLoop)
| null | null | null | from grid
| codeqa | def add Faces By Grid faces grid cell Top Loops get Indexed Cell Loops From Indexed Grid grid for cell Top Loop in cell Top Loops add Faces By Convex faces cell Top Loop
| null | null | null | null | Question:
In which direction does the code add faces ?
Code:
def addFacesByGrid(faces, grid):
cellTopLoops = getIndexedCellLoopsFromIndexedGrid(grid)
for cellTopLoop in cellTopLoops:
addFacesByConvex(faces, cellTopLoop)
|
null | null | null | How do windows find ?
| def find(callable, desktop=None):
return root(desktop).find(callable)
| null | null | null | using the given callable for the current desktop
| codeqa | def find callable desktop None return root desktop find callable
| null | null | null | null | Question:
How do windows find ?
Code:
def find(callable, desktop=None):
return root(desktop).find(callable)
|
null | null | null | What do windows use ?
| def find(callable, desktop=None):
return root(desktop).find(callable)
| null | null | null | the given callable for the current desktop
| codeqa | def find callable desktop None return root desktop find callable
| null | null | null | null | Question:
What do windows use ?
Code:
def find(callable, desktop=None):
return root(desktop).find(callable)
|
null | null | null | How do windows return ?
| def find(callable, desktop=None):
return root(desktop).find(callable)
| null | null | null | using the given callable for the current desktop
| codeqa | def find callable desktop None return root desktop find callable
| null | null | null | null | Question:
How do windows return ?
Code:
def find(callable, desktop=None):
return root(desktop).find(callable)
|
null | null | null | What is using the given callable for the current desktop ?
| def find(callable, desktop=None):
return root(desktop).find(callable)
| null | null | null | windows
| codeqa | def find callable desktop None return root desktop find callable
| null | null | null | null | Question:
What is using the given callable for the current desktop ?
Code:
def find(callable, desktop=None):
return root(desktop).find(callable)
|
null | null | null | What does the code prepend ?
| def rel_posix_to_abs_local(host, path, environ=None):
if (environ is None):
environ = os.environ
if path.startswith('/'):
path = path[1:]
root = path_for_host(host, environ)
return os.path.join(root, *path.split('/'))
| null | null | null | the tmp directory the hosts files are in
| codeqa | def rel posix to abs local host path environ None if environ is None environ os environif path startswith '/' path path[ 1 ]root path for host host environ return os path join root *path split '/'
| null | null | null | null | Question:
What does the code prepend ?
Code:
def rel_posix_to_abs_local(host, path, environ=None):
if (environ is None):
environ = os.environ
if path.startswith('/'):
path = path[1:]
root = path_for_host(host, environ)
return os.path.join(root, *path.split('/'))
|
null | null | null | How did preference options read ?
| def _parse_read_preference(options):
if ('read_preference' in options):
return options['read_preference']
mode = options.get('readpreference', 0)
tags = options.get('readpreferencetags')
max_staleness = options.get('maxstalenessseconds', (-1))
return make_read_preference(mode, tags, max_staleness)
| null | null | null | parse
| codeqa | def parse read preference options if 'read preference' in options return options['read preference']mode options get 'readpreference' 0 tags options get 'readpreferencetags' max staleness options get 'maxstalenessseconds' -1 return make read preference mode tags max staleness
| null | null | null | null | Question:
How did preference options read ?
Code:
def _parse_read_preference(options):
if ('read_preference' in options):
return options['read_preference']
mode = options.get('readpreference', 0)
tags = options.get('readpreferencetags')
max_staleness = options.get('maxstalenessseconds', (-1))
return make_read_preference(mode, tags, max_staleness)
|
null | null | null | What does the code get ?
| def supported_locales():
family = distrib_family()
if (family == 'debian'):
return _parse_locales('/usr/share/i18n/SUPPORTED')
elif (family == 'arch'):
return _parse_locales('/etc/locale.gen')
elif (family == 'redhat'):
return _supported_locales_redhat()
else:
raise UnsupportedFamily(supported=['debian', 'arch', 'redhat'])
| null | null | null | the list of supported locales
| codeqa | def supported locales family distrib family if family 'debian' return parse locales '/usr/share/i 18 n/SUPPORTED' elif family 'arch' return parse locales '/etc/locale gen' elif family 'redhat' return supported locales redhat else raise Unsupported Family supported ['debian' 'arch' 'redhat']
| null | null | null | null | Question:
What does the code get ?
Code:
def supported_locales():
family = distrib_family()
if (family == 'debian'):
return _parse_locales('/usr/share/i18n/SUPPORTED')
elif (family == 'arch'):
return _parse_locales('/etc/locale.gen')
elif (family == 'redhat'):
return _supported_locales_redhat()
else:
raise UnsupportedFamily(supported=['debian', 'arch', 'redhat'])
|
null | null | null | How do spectral norm of a real matrix estimate ?
| def idd_snorm(m, n, matvect, matvec, its=20):
(snorm, v) = _id.idd_snorm(m, n, matvect, matvec, its)
return snorm
| null | null | null | by the randomized power method
| codeqa | def idd snorm m n matvect matvec its 20 snorm v id idd snorm m n matvect matvec its return snorm
| null | null | null | null | Question:
How do spectral norm of a real matrix estimate ?
Code:
def idd_snorm(m, n, matvect, matvec, its=20):
(snorm, v) = _id.idd_snorm(m, n, matvect, matvec, its)
return snorm
|
null | null | null | What does the code get ?
| def libvlc_audio_equalizer_get_preamp(p_equalizer):
f = (_Cfunctions.get('libvlc_audio_equalizer_get_preamp', None) or _Cfunction('libvlc_audio_equalizer_get_preamp', ((1,),), None, ctypes.c_float, ctypes.c_void_p))
return f(p_equalizer)
| null | null | null | the current pre - amplification value from an equalizer
| codeqa | def libvlc audio equalizer get preamp p equalizer f Cfunctions get 'libvlc audio equalizer get preamp' None or Cfunction 'libvlc audio equalizer get preamp' 1 None ctypes c float ctypes c void p return f p equalizer
| null | null | null | null | Question:
What does the code get ?
Code:
def libvlc_audio_equalizer_get_preamp(p_equalizer):
f = (_Cfunctions.get('libvlc_audio_equalizer_get_preamp', None) or _Cfunction('libvlc_audio_equalizer_get_preamp', ((1,),), None, ctypes.c_float, ctypes.c_void_p))
return f(p_equalizer)
|
null | null | null | What does context help ?
| def disambig_string(info):
disambig = []
if (info.data_source and (info.data_source != 'MusicBrainz')):
disambig.append(info.data_source)
if isinstance(info, hooks.AlbumInfo):
if info.media:
if (info.mediums > 1):
disambig.append(u'{0}x{1}'.format(info.mediums, info.media))
else:
disambig.append(info.media)
if info.year:
disambig.append(unicode(info.year))
if info.country:
disambig.append(info.country)
if info.label:
disambig.append(info.label)
if info.albumdisambig:
disambig.append(info.albumdisambig)
if disambig:
return u', '.join(disambig)
| null | null | null | disambiguate similar - looking albums and tracks
| codeqa | def disambig string info disambig []if info data source and info data source ' Music Brainz' disambig append info data source if isinstance info hooks Album Info if info media if info mediums > 1 disambig append u'{ 0 }x{ 1 }' format info mediums info media else disambig append info media if info year disambig append unicode info year if info country disambig append info country if info label disambig append info label if info albumdisambig disambig append info albumdisambig if disambig return u' ' join disambig
| null | null | null | null | Question:
What does context help ?
Code:
def disambig_string(info):
disambig = []
if (info.data_source and (info.data_source != 'MusicBrainz')):
disambig.append(info.data_source)
if isinstance(info, hooks.AlbumInfo):
if info.media:
if (info.mediums > 1):
disambig.append(u'{0}x{1}'.format(info.mediums, info.media))
else:
disambig.append(info.media)
if info.year:
disambig.append(unicode(info.year))
if info.country:
disambig.append(info.country)
if info.label:
disambig.append(info.label)
if info.albumdisambig:
disambig.append(info.albumdisambig)
if disambig:
return u', '.join(disambig)
|
null | null | null | What helps disambiguate similar - looking albums and tracks ?
| def disambig_string(info):
disambig = []
if (info.data_source and (info.data_source != 'MusicBrainz')):
disambig.append(info.data_source)
if isinstance(info, hooks.AlbumInfo):
if info.media:
if (info.mediums > 1):
disambig.append(u'{0}x{1}'.format(info.mediums, info.media))
else:
disambig.append(info.media)
if info.year:
disambig.append(unicode(info.year))
if info.country:
disambig.append(info.country)
if info.label:
disambig.append(info.label)
if info.albumdisambig:
disambig.append(info.albumdisambig)
if disambig:
return u', '.join(disambig)
| null | null | null | context
| codeqa | def disambig string info disambig []if info data source and info data source ' Music Brainz' disambig append info data source if isinstance info hooks Album Info if info media if info mediums > 1 disambig append u'{ 0 }x{ 1 }' format info mediums info media else disambig append info media if info year disambig append unicode info year if info country disambig append info country if info label disambig append info label if info albumdisambig disambig append info albumdisambig if disambig return u' ' join disambig
| null | null | null | null | Question:
What helps disambiguate similar - looking albums and tracks ?
Code:
def disambig_string(info):
disambig = []
if (info.data_source and (info.data_source != 'MusicBrainz')):
disambig.append(info.data_source)
if isinstance(info, hooks.AlbumInfo):
if info.media:
if (info.mediums > 1):
disambig.append(u'{0}x{1}'.format(info.mediums, info.media))
else:
disambig.append(info.media)
if info.year:
disambig.append(unicode(info.year))
if info.country:
disambig.append(info.country)
if info.label:
disambig.append(info.label)
if info.albumdisambig:
disambig.append(info.albumdisambig)
if disambig:
return u', '.join(disambig)
|
null | null | null | What does the code get ?
| def _get_spec(tree_base, spec, template, saltenv='base'):
spec_tgt = os.path.basename(spec)
dest = os.path.join(tree_base, spec_tgt)
return __salt__['cp.get_url'](spec, dest, saltenv=saltenv)
| null | null | null | the spec file
| codeqa | def get spec tree base spec template saltenv 'base' spec tgt os path basename spec dest os path join tree base spec tgt return salt ['cp get url'] spec dest saltenv saltenv
| null | null | null | null | Question:
What does the code get ?
Code:
def _get_spec(tree_base, spec, template, saltenv='base'):
spec_tgt = os.path.basename(spec)
dest = os.path.join(tree_base, spec_tgt)
return __salt__['cp.get_url'](spec, dest, saltenv=saltenv)
|
null | null | null | What does the code apply ?
| def get_catalog_discover_hack(service_type, url):
return _VERSION_HACKS.get_discover_hack(service_type, url)
| null | null | null | the catalog hacks
| codeqa | def get catalog discover hack service type url return VERSION HACKS get discover hack service type url
| null | null | null | null | Question:
What does the code apply ?
Code:
def get_catalog_discover_hack(service_type, url):
return _VERSION_HACKS.get_discover_hack(service_type, url)
|
null | null | null | What does the code delete ?
| def instance_group_delete(context, group_uuid):
return IMPL.instance_group_delete(context, group_uuid)
| null | null | null | an group
| codeqa | def instance group delete context group uuid return IMPL instance group delete context group uuid
| null | null | null | null | Question:
What does the code delete ?
Code:
def instance_group_delete(context, group_uuid):
return IMPL.instance_group_delete(context, group_uuid)
|
null | null | null | How do code run ?
| @contextmanager
def temporary_locale(temp_locale=None):
orig_locale = locale.setlocale(locale.LC_ALL)
if (temp_locale is not None):
locale.setlocale(locale.LC_ALL, temp_locale)
(yield)
locale.setlocale(locale.LC_ALL, orig_locale)
| null | null | null | in a context with a temporary locale
| codeqa | @contextmanagerdef temporary locale temp locale None orig locale locale setlocale locale LC ALL if temp locale is not None locale setlocale locale LC ALL temp locale yield locale setlocale locale LC ALL orig locale
| null | null | null | null | Question:
How do code run ?
Code:
@contextmanager
def temporary_locale(temp_locale=None):
orig_locale = locale.setlocale(locale.LC_ALL)
if (temp_locale is not None):
locale.setlocale(locale.LC_ALL, temp_locale)
(yield)
locale.setlocale(locale.LC_ALL, orig_locale)
|
null | null | null | In which direction does the locale reset when exiting context ?
| @contextmanager
def temporary_locale(temp_locale=None):
orig_locale = locale.setlocale(locale.LC_ALL)
if (temp_locale is not None):
locale.setlocale(locale.LC_ALL, temp_locale)
(yield)
locale.setlocale(locale.LC_ALL, orig_locale)
| null | null | null | back
| codeqa | @contextmanagerdef temporary locale temp locale None orig locale locale setlocale locale LC ALL if temp locale is not None locale setlocale locale LC ALL temp locale yield locale setlocale locale LC ALL orig locale
| null | null | null | null | Question:
In which direction does the locale reset when exiting context ?
Code:
@contextmanager
def temporary_locale(temp_locale=None):
orig_locale = locale.setlocale(locale.LC_ALL)
if (temp_locale is not None):
locale.setlocale(locale.LC_ALL, temp_locale)
(yield)
locale.setlocale(locale.LC_ALL, orig_locale)
|
null | null | null | When does the locale reset back ?
| @contextmanager
def temporary_locale(temp_locale=None):
orig_locale = locale.setlocale(locale.LC_ALL)
if (temp_locale is not None):
locale.setlocale(locale.LC_ALL, temp_locale)
(yield)
locale.setlocale(locale.LC_ALL, orig_locale)
| null | null | null | when exiting context
| codeqa | @contextmanagerdef temporary locale temp locale None orig locale locale setlocale locale LC ALL if temp locale is not None locale setlocale locale LC ALL temp locale yield locale setlocale locale LC ALL orig locale
| null | null | null | null | Question:
When does the locale reset back ?
Code:
@contextmanager
def temporary_locale(temp_locale=None):
orig_locale = locale.setlocale(locale.LC_ALL)
if (temp_locale is not None):
locale.setlocale(locale.LC_ALL, temp_locale)
(yield)
locale.setlocale(locale.LC_ALL, orig_locale)
|
null | null | null | For what purpose do a string escape ?
| def quote_escape(value, lf='&mjf-lf;', quot='&mjf-quot;'):
if ('\n' in value):
value = value.replace('\n', lf)
if (("'" in value) and ('"' in value)):
value = value.replace('"', quot)
return value
| null | null | null | so that it can safely be quoted
| codeqa | def quote escape value lf '&mjf-lf ' quot '&mjf-quot ' if '\n' in value value value replace '\n' lf if "'" in value and '"' in value value value replace '"' quot return value
| null | null | null | null | Question:
For what purpose do a string escape ?
Code:
def quote_escape(value, lf='&mjf-lf;', quot='&mjf-quot;'):
if ('\n' in value):
value = value.replace('\n', lf)
if (("'" in value) and ('"' in value)):
value = value.replace('"', quot)
return value
|
null | null | null | How can it be quoted ?
| def quote_escape(value, lf='&mjf-lf;', quot='&mjf-quot;'):
if ('\n' in value):
value = value.replace('\n', lf)
if (("'" in value) and ('"' in value)):
value = value.replace('"', quot)
return value
| null | null | null | safely
| codeqa | def quote escape value lf '&mjf-lf ' quot '&mjf-quot ' if '\n' in value value value replace '\n' lf if "'" in value and '"' in value value value replace '"' quot return value
| null | null | null | null | Question:
How can it be quoted ?
Code:
def quote_escape(value, lf='&mjf-lf;', quot='&mjf-quot;'):
if ('\n' in value):
value = value.replace('\n', lf)
if (("'" in value) and ('"' in value)):
value = value.replace('"', quot)
return value
|
null | null | null | How can a number be expressed ?
| def factoring_visitor(state, primes):
(f, lpart, pstack) = state
factoring = []
for i in range((lpart + 1)):
factor = 1
for ps in pstack[f[i]:f[(i + 1)]]:
if (ps.v > 0):
factor *= (primes[ps.c] ** ps.v)
factoring.append(factor)
return factoring
| null | null | null | the ways
| codeqa | def factoring visitor state primes f lpart pstack statefactoring []for i in range lpart + 1 factor 1for ps in pstack[f[i] f[ i + 1 ]] if ps v > 0 factor * primes[ps c] ** ps v factoring append factor return factoring
| null | null | null | null | Question:
How can a number be expressed ?
Code:
def factoring_visitor(state, primes):
(f, lpart, pstack) = state
factoring = []
for i in range((lpart + 1)):
factor = 1
for ps in pstack[f[i]:f[(i + 1)]]:
if (ps.v > 0):
factor *= (primes[ps.c] ** ps.v)
factoring.append(factor)
return factoring
|
null | null | null | How do the legacy graph parse ?
| def create_legacy_graph_tasks(symbol_table_cls):
symbol_table_constraint = symbol_table_cls.constraint()
return [(HydratedTargets, [SelectDependencies(HydratedTarget, Addresses, field_types=(Address,), transitive=True)], HydratedTargets), (HydratedTarget, [Select(symbol_table_constraint), SelectDependencies(HydratedField, symbol_table_constraint, u'field_adaptors', field_types=(SourcesField, BundlesField))], hydrate_target), (HydratedField, [Select(SourcesField), SelectProjection(FilesDigest, PathGlobs, (u'path_globs',), SourcesField), SelectProjection(Files, PathGlobs, (u'excluded_path_globs',), SourcesField)], hydrate_sources), (HydratedField, [Select(BundlesField), SelectDependencies(FilesDigest, BundlesField, u'path_globs_list', field_types=(PathGlobs,)), SelectDependencies(Files, BundlesField, u'excluded_path_globs_list', field_types=(PathGlobs,))], hydrate_bundles)]
| null | null | null | recursively
| codeqa | def create legacy graph tasks symbol table cls symbol table constraint symbol table cls constraint return [ Hydrated Targets [ Select Dependencies Hydrated Target Addresses field types Address transitive True ] Hydrated Targets Hydrated Target [ Select symbol table constraint Select Dependencies Hydrated Field symbol table constraint u'field adaptors' field types Sources Field Bundles Field ] hydrate target Hydrated Field [ Select Sources Field Select Projection Files Digest Path Globs u'path globs' Sources Field Select Projection Files Path Globs u'excluded path globs' Sources Field ] hydrate sources Hydrated Field [ Select Bundles Field Select Dependencies Files Digest Bundles Field u'path globs list' field types Path Globs Select Dependencies Files Bundles Field u'excluded path globs list' field types Path Globs ] hydrate bundles ]
| null | null | null | null | Question:
How do the legacy graph parse ?
Code:
def create_legacy_graph_tasks(symbol_table_cls):
symbol_table_constraint = symbol_table_cls.constraint()
return [(HydratedTargets, [SelectDependencies(HydratedTarget, Addresses, field_types=(Address,), transitive=True)], HydratedTargets), (HydratedTarget, [Select(symbol_table_constraint), SelectDependencies(HydratedField, symbol_table_constraint, u'field_adaptors', field_types=(SourcesField, BundlesField))], hydrate_target), (HydratedField, [Select(SourcesField), SelectProjection(FilesDigest, PathGlobs, (u'path_globs',), SourcesField), SelectProjection(Files, PathGlobs, (u'excluded_path_globs',), SourcesField)], hydrate_sources), (HydratedField, [Select(BundlesField), SelectDependencies(FilesDigest, BundlesField, u'path_globs_list', field_types=(PathGlobs,)), SelectDependencies(Files, BundlesField, u'excluded_path_globs_list', field_types=(PathGlobs,))], hydrate_bundles)]
|
null | null | null | What does the code setup ?
| def setup(hass, config):
import nest
if ('nest' in _CONFIGURING):
return
conf = config[DOMAIN]
client_id = conf[CONF_CLIENT_ID]
client_secret = conf[CONF_CLIENT_SECRET]
filename = config.get(CONF_FILENAME, NEST_CONFIG_FILE)
access_token_cache_file = hass.config.path(filename)
nest = nest.Nest(access_token_cache_file=access_token_cache_file, client_id=client_id, client_secret=client_secret)
setup_nest(hass, nest, config)
return True
| null | null | null | the nest thermostat component
| codeqa | def setup hass config import nestif 'nest' in CONFIGURING returnconf config[DOMAIN]client id conf[CONF CLIENT ID]client secret conf[CONF CLIENT SECRET]filename config get CONF FILENAME NEST CONFIG FILE access token cache file hass config path filename nest nest Nest access token cache file access token cache file client id client id client secret client secret setup nest hass nest config return True
| null | null | null | null | Question:
What does the code setup ?
Code:
def setup(hass, config):
import nest
if ('nest' in _CONFIGURING):
return
conf = config[DOMAIN]
client_id = conf[CONF_CLIENT_ID]
client_secret = conf[CONF_CLIENT_SECRET]
filename = config.get(CONF_FILENAME, NEST_CONFIG_FILE)
access_token_cache_file = hass.config.path(filename)
nest = nest.Nest(access_token_cache_file=access_token_cache_file, client_id=client_id, client_secret=client_secret)
setup_nest(hass, nest, config)
return True
|
null | null | null | What has the given permission for any organization ?
| def has_user_permission_for_some_org(user_name, permission):
user_id = get_user_id_for_username(user_name, allow_none=True)
if (not user_id):
return False
roles = get_roles_with_permission(permission)
if (not roles):
return False
q = model.Session.query(model.Member).filter((model.Member.table_name == 'user')).filter((model.Member.state == 'active')).filter(model.Member.capacity.in_(roles)).filter((model.Member.table_id == user_id))
group_ids = []
for row in q.all():
group_ids.append(row.group_id)
if (not group_ids):
return False
q = model.Session.query(model.Group).filter((model.Group.is_organization == True)).filter((model.Group.state == 'active')).filter(model.Group.id.in_(group_ids))
return bool(q.count())
| null | null | null | the user
| codeqa | def has user permission for some org user name permission user id get user id for username user name allow none True if not user id return Falseroles get roles with permission permission if not roles return Falseq model Session query model Member filter model Member table name 'user' filter model Member state 'active' filter model Member capacity in roles filter model Member table id user id group ids []for row in q all group ids append row group id if not group ids return Falseq model Session query model Group filter model Group is organization True filter model Group state 'active' filter model Group id in group ids return bool q count
| null | null | null | null | Question:
What has the given permission for any organization ?
Code:
def has_user_permission_for_some_org(user_name, permission):
user_id = get_user_id_for_username(user_name, allow_none=True)
if (not user_id):
return False
roles = get_roles_with_permission(permission)
if (not roles):
return False
q = model.Session.query(model.Member).filter((model.Member.table_name == 'user')).filter((model.Member.state == 'active')).filter(model.Member.capacity.in_(roles)).filter((model.Member.table_id == user_id))
group_ids = []
for row in q.all():
group_ids.append(row.group_id)
if (not group_ids):
return False
q = model.Session.query(model.Group).filter((model.Group.is_organization == True)).filter((model.Group.state == 'active')).filter(model.Group.id.in_(group_ids))
return bool(q.count())
|
null | null | null | What does the code get ?
| def get_profilers(**filter_data):
return rpc_utils.prepare_for_serialization(models.Profiler.list_objects(filter_data))
| null | null | null | all profilers
| codeqa | def get profilers **filter data return rpc utils prepare for serialization models Profiler list objects filter data
| null | null | null | null | Question:
What does the code get ?
Code:
def get_profilers(**filter_data):
return rpc_utils.prepare_for_serialization(models.Profiler.list_objects(filter_data))
|
null | null | null | How do contents of the mail queue show ?
| def show_queue():
cmd = 'mailq'
out = __salt__['cmd.run'](cmd).splitlines()
queue = []
queue_pattern = re.compile('(?P<queue_id>^[A-Z0-9]+)\\s+(?P<size>\\d+)\\s(?P<timestamp>\\w{3}\\s\\w{3}\\s\\d{1,2}\\s\\d{2}\\:\\d{2}\\:\\d{2})\\s+(?P<sender>.+)')
recipient_pattern = re.compile('^\\s+(?P<recipient>.+)')
for line in out:
if re.match('^[-|postqueue:|Mail]', line):
continue
if re.match(queue_pattern, line):
m = re.match(queue_pattern, line)
queue_id = m.group('queue_id')
size = m.group('size')
timestamp = m.group('timestamp')
sender = m.group('sender')
elif re.match(recipient_pattern, line):
m = re.match(recipient_pattern, line)
recipient = m.group('recipient')
elif (not line):
queue.append({'queue_id': queue_id, 'size': size, 'timestamp': timestamp, 'sender': sender, 'recipient': recipient})
return queue
| null | null | null | cli example
| codeqa | def show queue cmd 'mailq'out salt ['cmd run'] cmd splitlines queue []queue pattern re compile ' ?P<queue id>^[A-Z 0 - 9 ]+ \\s+ ?P<size>\\d+ \\s ?P<timestamp>\\w{ 3 }\\s\\w{ 3 }\\s\\d{ 1 2}\\s\\d{ 2 }\\ \\d{ 2 }\\ \\d{ 2 } \\s+ ?P<sender> + ' recipient pattern re compile '^\\s+ ?P<recipient> + ' for line in out if re match '^[- postqueue Mail]' line continueif re match queue pattern line m re match queue pattern line queue id m group 'queue id' size m group 'size' timestamp m group 'timestamp' sender m group 'sender' elif re match recipient pattern line m re match recipient pattern line recipient m group 'recipient' elif not line queue append {'queue id' queue id 'size' size 'timestamp' timestamp 'sender' sender 'recipient' recipient} return queue
| null | null | null | null | Question:
How do contents of the mail queue show ?
Code:
def show_queue():
cmd = 'mailq'
out = __salt__['cmd.run'](cmd).splitlines()
queue = []
queue_pattern = re.compile('(?P<queue_id>^[A-Z0-9]+)\\s+(?P<size>\\d+)\\s(?P<timestamp>\\w{3}\\s\\w{3}\\s\\d{1,2}\\s\\d{2}\\:\\d{2}\\:\\d{2})\\s+(?P<sender>.+)')
recipient_pattern = re.compile('^\\s+(?P<recipient>.+)')
for line in out:
if re.match('^[-|postqueue:|Mail]', line):
continue
if re.match(queue_pattern, line):
m = re.match(queue_pattern, line)
queue_id = m.group('queue_id')
size = m.group('size')
timestamp = m.group('timestamp')
sender = m.group('sender')
elif re.match(recipient_pattern, line):
m = re.match(recipient_pattern, line)
recipient = m.group('recipient')
elif (not line):
queue.append({'queue_id': queue_id, 'size': size, 'timestamp': timestamp, 'sender': sender, 'recipient': recipient})
return queue
|
null | null | null | By how much did old - style compatibility classes pickle ?
| def _convertToNewStyle(newClass, oldInstance):
if (oldInstance.__class__.__name__ == 'ExperimentHandler'):
newHandler = psychopy.data.ExperimentHandler()
else:
newHandler = newClass([], 0)
for thisAttrib in dir(oldInstance):
if ('instancemethod' in str(type(getattr(oldInstance, thisAttrib)))):
continue
elif (thisAttrib == '__weakref__'):
continue
else:
value = getattr(oldInstance, thisAttrib)
setattr(newHandler, thisAttrib, value)
return newHandler
| null | null | null | un
| codeqa | def convert To New Style new Class old Instance if old Instance class name ' Experiment Handler' new Handler psychopy data Experiment Handler else new Handler new Class [] 0 for this Attrib in dir old Instance if 'instancemethod' in str type getattr old Instance this Attrib continueelif this Attrib ' weakref ' continueelse value getattr old Instance this Attrib setattr new Handler this Attrib value return new Handler
| null | null | null | null | Question:
By how much did old - style compatibility classes pickle ?
Code:
def _convertToNewStyle(newClass, oldInstance):
if (oldInstance.__class__.__name__ == 'ExperimentHandler'):
newHandler = psychopy.data.ExperimentHandler()
else:
newHandler = newClass([], 0)
for thisAttrib in dir(oldInstance):
if ('instancemethod' in str(type(getattr(oldInstance, thisAttrib)))):
continue
elif (thisAttrib == '__weakref__'):
continue
else:
value = getattr(oldInstance, thisAttrib)
setattr(newHandler, thisAttrib, value)
return newHandler
|
null | null | null | What does the code write here ?
| def remove_dark_lang_config(apps, schema_editor):
raise RuntimeError(u'Cannot reverse this migration.')
| null | null | null | your backwards methods
| codeqa | def remove dark lang config apps schema editor raise Runtime Error u' Cannotreversethismigration '
| null | null | null | null | Question:
What does the code write here ?
Code:
def remove_dark_lang_config(apps, schema_editor):
raise RuntimeError(u'Cannot reverse this migration.')
|
null | null | null | What does the code get ?
| def getEvaluatedString(key, xmlElement=None):
if (xmlElement == None):
return None
if (key in xmlElement.attributeDictionary):
return str(getEvaluatedValueObliviously(key, xmlElement))
return None
| null | null | null | the evaluated value as a string
| codeqa | def get Evaluated String key xml Element None if xml Element None return Noneif key in xml Element attribute Dictionary return str get Evaluated Value Obliviously key xml Element return None
| null | null | null | null | Question:
What does the code get ?
Code:
def getEvaluatedString(key, xmlElement=None):
if (xmlElement == None):
return None
if (key in xmlElement.attributeDictionary):
return str(getEvaluatedValueObliviously(key, xmlElement))
return None
|
null | null | null | What does the code update ?
| def organization_update(context, data_dict):
return _group_or_org_update(context, data_dict, is_org=True)
| null | null | null | a organization
| codeqa | def organization update context data dict return group or org update context data dict is org True
| null | null | null | null | Question:
What does the code update ?
Code:
def organization_update(context, data_dict):
return _group_or_org_update(context, data_dict, is_org=True)
|
null | null | null | What does the code retrieve ?
| def get_index_trap(*args, **kwargs):
from conda.core.index import get_index
kwargs.pop(u'json', None)
return get_index(*args, **kwargs)
| null | null | null | the package index
| codeqa | def get index trap *args **kwargs from conda core index import get indexkwargs pop u'json' None return get index *args **kwargs
| null | null | null | null | Question:
What does the code retrieve ?
Code:
def get_index_trap(*args, **kwargs):
from conda.core.index import get_index
kwargs.pop(u'json', None)
return get_index(*args, **kwargs)
|
null | null | null | How do the right compressor file object return ?
| def _write_fileobject(filename, compress=('zlib', 3)):
compressmethod = compress[0]
compresslevel = compress[1]
if (compressmethod == 'gzip'):
return _buffered_write_file(BinaryGzipFile(filename, 'wb', compresslevel=compresslevel))
elif (compressmethod == 'bz2'):
return _buffered_write_file(bz2.BZ2File(filename, 'wb', compresslevel=compresslevel))
elif ((lzma is not None) and (compressmethod == 'xz')):
return _buffered_write_file(lzma.LZMAFile(filename, 'wb', check=lzma.CHECK_NONE, preset=compresslevel))
elif ((lzma is not None) and (compressmethod == 'lzma')):
return _buffered_write_file(lzma.LZMAFile(filename, 'wb', preset=compresslevel, format=lzma.FORMAT_ALONE))
else:
return _buffered_write_file(BinaryZlibFile(filename, 'wb', compresslevel=compresslevel))
| null | null | null | in write mode
| codeqa | def write fileobject filename compress 'zlib' 3 compressmethod compress[ 0 ]compresslevel compress[ 1 ]if compressmethod 'gzip' return buffered write file Binary Gzip File filename 'wb' compresslevel compresslevel elif compressmethod 'bz 2 ' return buffered write file bz 2 BZ 2 File filename 'wb' compresslevel compresslevel elif lzma is not None and compressmethod 'xz' return buffered write file lzma LZMA File filename 'wb' check lzma CHECK NONE preset compresslevel elif lzma is not None and compressmethod 'lzma' return buffered write file lzma LZMA File filename 'wb' preset compresslevel format lzma FORMAT ALONE else return buffered write file Binary Zlib File filename 'wb' compresslevel compresslevel
| null | null | null | null | Question:
How do the right compressor file object return ?
Code:
def _write_fileobject(filename, compress=('zlib', 3)):
compressmethod = compress[0]
compresslevel = compress[1]
if (compressmethod == 'gzip'):
return _buffered_write_file(BinaryGzipFile(filename, 'wb', compresslevel=compresslevel))
elif (compressmethod == 'bz2'):
return _buffered_write_file(bz2.BZ2File(filename, 'wb', compresslevel=compresslevel))
elif ((lzma is not None) and (compressmethod == 'xz')):
return _buffered_write_file(lzma.LZMAFile(filename, 'wb', check=lzma.CHECK_NONE, preset=compresslevel))
elif ((lzma is not None) and (compressmethod == 'lzma')):
return _buffered_write_file(lzma.LZMAFile(filename, 'wb', preset=compresslevel, format=lzma.FORMAT_ALONE))
else:
return _buffered_write_file(BinaryZlibFile(filename, 'wb', compresslevel=compresslevel))
|
null | null | null | What does the code initialize ?
| def init_logger():
logger = logging.getLogger('south')
logger.addHandler(NullHandler())
return logger
| null | null | null | the south logger
| codeqa | def init logger logger logging get Logger 'south' logger add Handler Null Handler return logger
| null | null | null | null | Question:
What does the code initialize ?
Code:
def init_logger():
logger = logging.getLogger('south')
logger.addHandler(NullHandler())
return logger
|
null | null | null | How does the code render it as context ?
| def render_to_string(template_name, dictionary=None, context_instance=None):
dictionary = (dictionary or {})
if isinstance(template_name, (list, tuple)):
t = select_template(template_name)
else:
t = get_template(template_name)
if context_instance:
context_instance.update(dictionary)
else:
context_instance = Context(dictionary)
return t.render(context_instance)
| null | null | null | with the given dictionary
| codeqa | def render to string template name dictionary None context instance None dictionary dictionary or {} if isinstance template name list tuple t select template template name else t get template template name if context instance context instance update dictionary else context instance Context dictionary return t render context instance
| null | null | null | null | Question:
How does the code render it as context ?
Code:
def render_to_string(template_name, dictionary=None, context_instance=None):
dictionary = (dictionary or {})
if isinstance(template_name, (list, tuple)):
t = select_template(template_name)
else:
t = get_template(template_name)
if context_instance:
context_instance.update(dictionary)
else:
context_instance = Context(dictionary)
return t.render(context_instance)
|
null | null | null | What does the code load ?
| def render_to_string(template_name, dictionary=None, context_instance=None):
dictionary = (dictionary or {})
if isinstance(template_name, (list, tuple)):
t = select_template(template_name)
else:
t = get_template(template_name)
if context_instance:
context_instance.update(dictionary)
else:
context_instance = Context(dictionary)
return t.render(context_instance)
| null | null | null | the given template_name
| codeqa | def render to string template name dictionary None context instance None dictionary dictionary or {} if isinstance template name list tuple t select template template name else t get template template name if context instance context instance update dictionary else context instance Context dictionary return t render context instance
| null | null | null | null | Question:
What does the code load ?
Code:
def render_to_string(template_name, dictionary=None, context_instance=None):
dictionary = (dictionary or {})
if isinstance(template_name, (list, tuple)):
t = select_template(template_name)
else:
t = get_template(template_name)
if context_instance:
context_instance.update(dictionary)
else:
context_instance = Context(dictionary)
return t.render(context_instance)
|
null | null | null | Where does tests run ?
| def runner(window, test_classes):
output = StringQueue()
panel = window.get_output_panel('package_control_tests')
panel.settings().set('word_wrap', True)
window.run_command('show_panel', {'panel': 'output.package_control_tests'})
threading.Thread(target=show_results, args=(panel, output)).start()
threading.Thread(target=do_run, args=(test_classes, output)).start()
| null | null | null | in a thread
| codeqa | def runner window test classes output String Queue panel window get output panel 'package control tests' panel settings set 'word wrap' True window run command 'show panel' {'panel' 'output package control tests'} threading Thread target show results args panel output start threading Thread target do run args test classes output start
| null | null | null | null | Question:
Where does tests run ?
Code:
def runner(window, test_classes):
output = StringQueue()
panel = window.get_output_panel('package_control_tests')
panel.settings().set('word_wrap', True)
window.run_command('show_panel', {'panel': 'output.package_control_tests'})
threading.Thread(target=show_results, args=(panel, output)).start()
threading.Thread(target=do_run, args=(test_classes, output)).start()
|
null | null | null | What runs in a thread ?
| def runner(window, test_classes):
output = StringQueue()
panel = window.get_output_panel('package_control_tests')
panel.settings().set('word_wrap', True)
window.run_command('show_panel', {'panel': 'output.package_control_tests'})
threading.Thread(target=show_results, args=(panel, output)).start()
threading.Thread(target=do_run, args=(test_classes, output)).start()
| null | null | null | tests
| codeqa | def runner window test classes output String Queue panel window get output panel 'package control tests' panel settings set 'word wrap' True window run command 'show panel' {'panel' 'output package control tests'} threading Thread target show results args panel output start threading Thread target do run args test classes output start
| null | null | null | null | Question:
What runs in a thread ?
Code:
def runner(window, test_classes):
output = StringQueue()
panel = window.get_output_panel('package_control_tests')
panel.settings().set('word_wrap', True)
window.run_command('show_panel', {'panel': 'output.package_control_tests'})
threading.Thread(target=show_results, args=(panel, output)).start()
threading.Thread(target=do_run, args=(test_classes, output)).start()
|
null | null | null | When do constructions from plugins by these types allow ?
| def plugins_dict(module, plugin_type_identifier):
plugin_dict = {}
for plugin_module in submodules(module):
for clazz in getattr(plugin_module, '__all__', []):
try:
clazz = getattr(plugin_module, clazz)
except TypeError:
clazz = clazz
plugin_type = getattr(clazz, plugin_type_identifier, None)
if plugin_type:
plugin_dict[plugin_type] = clazz
return plugin_dict
| null | null | null | later on
| codeqa | def plugins dict module plugin type identifier plugin dict {}for plugin module in submodules module for clazz in getattr plugin module ' all ' [] try clazz getattr plugin module clazz except Type Error clazz clazzplugin type getattr clazz plugin type identifier None if plugin type plugin dict[plugin type] clazzreturn plugin dict
| null | null | null | null | Question:
When do constructions from plugins by these types allow ?
Code:
def plugins_dict(module, plugin_type_identifier):
plugin_dict = {}
for plugin_module in submodules(module):
for clazz in getattr(plugin_module, '__all__', []):
try:
clazz = getattr(plugin_module, clazz)
except TypeError:
clazz = clazz
plugin_type = getattr(clazz, plugin_type_identifier, None)
if plugin_type:
plugin_dict[plugin_type] = clazz
return plugin_dict
|
null | null | null | For what purpose do a dictionary throw in ?
| def plugins_dict(module, plugin_type_identifier):
plugin_dict = {}
for plugin_module in submodules(module):
for clazz in getattr(plugin_module, '__all__', []):
try:
clazz = getattr(plugin_module, clazz)
except TypeError:
clazz = clazz
plugin_type = getattr(clazz, plugin_type_identifier, None)
if plugin_type:
plugin_dict[plugin_type] = clazz
return plugin_dict
| null | null | null | to allow constructions from plugins by these types later on
| codeqa | def plugins dict module plugin type identifier plugin dict {}for plugin module in submodules module for clazz in getattr plugin module ' all ' [] try clazz getattr plugin module clazz except Type Error clazz clazzplugin type getattr clazz plugin type identifier None if plugin type plugin dict[plugin type] clazzreturn plugin dict
| null | null | null | null | Question:
For what purpose do a dictionary throw in ?
Code:
def plugins_dict(module, plugin_type_identifier):
plugin_dict = {}
for plugin_module in submodules(module):
for clazz in getattr(plugin_module, '__all__', []):
try:
clazz = getattr(plugin_module, clazz)
except TypeError:
clazz = clazz
plugin_type = getattr(clazz, plugin_type_identifier, None)
if plugin_type:
plugin_dict[plugin_type] = clazz
return plugin_dict
|
null | null | null | In which direction do in submodules of module walk ?
| def plugins_dict(module, plugin_type_identifier):
plugin_dict = {}
for plugin_module in submodules(module):
for clazz in getattr(plugin_module, '__all__', []):
try:
clazz = getattr(plugin_module, clazz)
except TypeError:
clazz = clazz
plugin_type = getattr(clazz, plugin_type_identifier, None)
if plugin_type:
plugin_dict[plugin_type] = clazz
return plugin_dict
| null | null | null | through all classes
| codeqa | def plugins dict module plugin type identifier plugin dict {}for plugin module in submodules module for clazz in getattr plugin module ' all ' [] try clazz getattr plugin module clazz except Type Error clazz clazzplugin type getattr clazz plugin type identifier None if plugin type plugin dict[plugin type] clazzreturn plugin dict
| null | null | null | null | Question:
In which direction do in submodules of module walk ?
Code:
def plugins_dict(module, plugin_type_identifier):
plugin_dict = {}
for plugin_module in submodules(module):
for clazz in getattr(plugin_module, '__all__', []):
try:
clazz = getattr(plugin_module, clazz)
except TypeError:
clazz = clazz
plugin_type = getattr(clazz, plugin_type_identifier, None)
if plugin_type:
plugin_dict[plugin_type] = clazz
return plugin_dict
|
null | null | null | What returns on the path_info ?
| def peek_path_info(environ, charset='utf-8', errors='replace'):
segments = environ.get('PATH_INFO', '').lstrip('/').split('/', 1)
if segments:
return to_unicode(wsgi_get_bytes(segments[0]), charset, errors, allow_none_charset=True)
| null | null | null | the next segment
| codeqa | def peek path info environ charset 'utf- 8 ' errors 'replace' segments environ get 'PATH INFO' '' lstrip '/' split '/' 1 if segments return to unicode wsgi get bytes segments[ 0 ] charset errors allow none charset True
| null | null | null | null | Question:
What returns on the path_info ?
Code:
def peek_path_info(environ, charset='utf-8', errors='replace'):
segments = environ.get('PATH_INFO', '').lstrip('/').split('/', 1)
if segments:
return to_unicode(wsgi_get_bytes(segments[0]), charset, errors, allow_none_charset=True)
|
null | null | null | Where does the next segment return ?
| def peek_path_info(environ, charset='utf-8', errors='replace'):
segments = environ.get('PATH_INFO', '').lstrip('/').split('/', 1)
if segments:
return to_unicode(wsgi_get_bytes(segments[0]), charset, errors, allow_none_charset=True)
| null | null | null | on the path_info
| codeqa | def peek path info environ charset 'utf- 8 ' errors 'replace' segments environ get 'PATH INFO' '' lstrip '/' split '/' 1 if segments return to unicode wsgi get bytes segments[ 0 ] charset errors allow none charset True
| null | null | null | null | Question:
Where does the next segment return ?
Code:
def peek_path_info(environ, charset='utf-8', errors='replace'):
segments = environ.get('PATH_INFO', '').lstrip('/').split('/', 1)
if segments:
return to_unicode(wsgi_get_bytes(segments[0]), charset, errors, allow_none_charset=True)
|
null | null | null | When do a bs4 tag clone ?
| def clone_bs4_elem(el):
if isinstance(el, NavigableString):
return type(el)(el)
copy = Tag(None, el.builder, el.name, el.namespace, el.nsprefix)
copy.attrs = dict(el.attrs)
for attr in ('can_be_empty_element', 'hidden'):
setattr(copy, attr, getattr(el, attr))
for child in el.contents:
copy.append(clone_bs4_elem(child))
return copy
| null | null | null | before modifying it
| codeqa | def clone bs 4 elem el if isinstance el Navigable String return type el el copy Tag None el builder el name el namespace el nsprefix copy attrs dict el attrs for attr in 'can be empty element' 'hidden' setattr copy attr getattr el attr for child in el contents copy append clone bs 4 elem child return copy
| null | null | null | null | Question:
When do a bs4 tag clone ?
Code:
def clone_bs4_elem(el):
if isinstance(el, NavigableString):
return type(el)(el)
copy = Tag(None, el.builder, el.name, el.namespace, el.nsprefix)
copy.attrs = dict(el.attrs)
for attr in ('can_be_empty_element', 'hidden'):
setattr(copy, attr, getattr(el, attr))
for child in el.contents:
copy.append(clone_bs4_elem(child))
return copy
|
null | null | null | What did the code put over a common denominator ?
| def ratsimp(expr):
(f, g) = cancel(expr).as_numer_denom()
try:
(Q, r) = reduced(f, [g], field=True, expand=False)
except ComputationFailed:
return (f / g)
return (Add(*Q) + cancel((r / g)))
| null | null | null | an expression
| codeqa | def ratsimp expr f g cancel expr as numer denom try Q r reduced f [g] field True expand False except Computation Failed return f / g return Add *Q + cancel r / g
| null | null | null | null | Question:
What did the code put over a common denominator ?
Code:
def ratsimp(expr):
(f, g) = cancel(expr).as_numer_denom()
try:
(Q, r) = reduced(f, [g], field=True, expand=False)
except ComputationFailed:
return (f / g)
return (Add(*Q) + cancel((r / g)))
|
null | null | null | What does the code send ?
| def webhook_notification(version, build, hook_url):
project = version.project
data = json.dumps({'name': project.name, 'slug': project.slug, 'build': {'id': build.id, 'success': build.success, 'date': build.date.strftime('%Y-%m-%d %H:%M:%S')}})
log.debug(LOG_TEMPLATE.format(project=project.slug, version='', msg=('sending notification to: %s' % hook_url)))
requests.post(hook_url, data=data)
| null | null | null | webhook notification for project webhook
| codeqa | def webhook notification version build hook url project version projectdata json dumps {'name' project name 'slug' project slug 'build' {'id' build id 'success' build success 'date' build date strftime '%Y-%m-%d%H %M %S' }} log debug LOG TEMPLATE format project project slug version '' msg 'sendingnotificationto %s' % hook url requests post hook url data data
| null | null | null | null | Question:
What does the code send ?
Code:
def webhook_notification(version, build, hook_url):
project = version.project
data = json.dumps({'name': project.name, 'slug': project.slug, 'build': {'id': build.id, 'success': build.success, 'date': build.date.strftime('%Y-%m-%d %H:%M:%S')}})
log.debug(LOG_TEMPLATE.format(project=project.slug, version='', msg=('sending notification to: %s' % hook_url)))
requests.post(hook_url, data=data)
|
null | null | null | What does the code evaluate ?
| def setFunctionLocalDictionary(arguments, function):
function.localDictionary = {'_arguments': arguments}
if (len(arguments) > 0):
firstArgument = arguments[0]
if (firstArgument.__class__ == dict):
function.localDictionary = firstArgument
return
if ('parameters' not in function.elementNode.attributes):
return
parameters = function.elementNode.attributes['parameters'].strip()
if (parameters == ''):
return
parameterWords = parameters.split(',')
for (parameterWordIndex, parameterWord) in enumerate(parameterWords):
strippedWord = parameterWord.strip()
keyValue = KeyValue().getByEqual(strippedWord)
if (parameterWordIndex < len(arguments)):
function.localDictionary[keyValue.key] = arguments[parameterWordIndex]
else:
strippedValue = keyValue.value
if (strippedValue == None):
print 'Warning there is no default parameter in getParameterValue for:'
print strippedWord
print parameterWords
print arguments
print function.elementNode.attributes
else:
strippedValue = strippedValue.strip()
function.localDictionary[keyValue.key.strip()] = strippedValue
if (len(arguments) > len(parameterWords)):
print 'Warning there are too many initializeFunction parameters for:'
print function.elementNode.attributes
print parameterWords
print arguments
| null | null | null | the function statement
| codeqa | def set Function Local Dictionary arguments function function local Dictionary {' arguments' arguments}if len arguments > 0 first Argument arguments[ 0 ]if first Argument class dict function local Dictionary first Argumentreturnif 'parameters' not in function element Node attributes returnparameters function element Node attributes['parameters'] strip if parameters '' returnparameter Words parameters split ' ' for parameter Word Index parameter Word in enumerate parameter Words stripped Word parameter Word strip key Value Key Value get By Equal stripped Word if parameter Word Index < len arguments function local Dictionary[key Value key] arguments[parameter Word Index]else stripped Value key Value valueif stripped Value None print ' Warningthereisnodefaultparameteringet Parameter Valuefor 'print stripped Wordprint parameter Wordsprint argumentsprint function element Node attributeselse stripped Value stripped Value strip function local Dictionary[key Value key strip ] stripped Valueif len arguments > len parameter Words print ' Warningtherearetoomanyinitialize Functionparametersfor 'print function element Node attributesprint parameter Wordsprint arguments
| null | null | null | null | Question:
What does the code evaluate ?
Code:
def setFunctionLocalDictionary(arguments, function):
function.localDictionary = {'_arguments': arguments}
if (len(arguments) > 0):
firstArgument = arguments[0]
if (firstArgument.__class__ == dict):
function.localDictionary = firstArgument
return
if ('parameters' not in function.elementNode.attributes):
return
parameters = function.elementNode.attributes['parameters'].strip()
if (parameters == ''):
return
parameterWords = parameters.split(',')
for (parameterWordIndex, parameterWord) in enumerate(parameterWords):
strippedWord = parameterWord.strip()
keyValue = KeyValue().getByEqual(strippedWord)
if (parameterWordIndex < len(arguments)):
function.localDictionary[keyValue.key] = arguments[parameterWordIndex]
else:
strippedValue = keyValue.value
if (strippedValue == None):
print 'Warning there is no default parameter in getParameterValue for:'
print strippedWord
print parameterWords
print arguments
print function.elementNode.attributes
else:
strippedValue = strippedValue.strip()
function.localDictionary[keyValue.key.strip()] = strippedValue
if (len(arguments) > len(parameterWords)):
print 'Warning there are too many initializeFunction parameters for:'
print function.elementNode.attributes
print parameterWords
print arguments
|
null | null | null | What does the code delete ?
| def setFunctionLocalDictionary(arguments, function):
function.localDictionary = {'_arguments': arguments}
if (len(arguments) > 0):
firstArgument = arguments[0]
if (firstArgument.__class__ == dict):
function.localDictionary = firstArgument
return
if ('parameters' not in function.elementNode.attributes):
return
parameters = function.elementNode.attributes['parameters'].strip()
if (parameters == ''):
return
parameterWords = parameters.split(',')
for (parameterWordIndex, parameterWord) in enumerate(parameterWords):
strippedWord = parameterWord.strip()
keyValue = KeyValue().getByEqual(strippedWord)
if (parameterWordIndex < len(arguments)):
function.localDictionary[keyValue.key] = arguments[parameterWordIndex]
else:
strippedValue = keyValue.value
if (strippedValue == None):
print 'Warning there is no default parameter in getParameterValue for:'
print strippedWord
print parameterWords
print arguments
print function.elementNode.attributes
else:
strippedValue = strippedValue.strip()
function.localDictionary[keyValue.key.strip()] = strippedValue
if (len(arguments) > len(parameterWords)):
print 'Warning there are too many initializeFunction parameters for:'
print function.elementNode.attributes
print parameterWords
print arguments
| null | null | null | the evaluators
| codeqa | def set Function Local Dictionary arguments function function local Dictionary {' arguments' arguments}if len arguments > 0 first Argument arguments[ 0 ]if first Argument class dict function local Dictionary first Argumentreturnif 'parameters' not in function element Node attributes returnparameters function element Node attributes['parameters'] strip if parameters '' returnparameter Words parameters split ' ' for parameter Word Index parameter Word in enumerate parameter Words stripped Word parameter Word strip key Value Key Value get By Equal stripped Word if parameter Word Index < len arguments function local Dictionary[key Value key] arguments[parameter Word Index]else stripped Value key Value valueif stripped Value None print ' Warningthereisnodefaultparameteringet Parameter Valuefor 'print stripped Wordprint parameter Wordsprint argumentsprint function element Node attributeselse stripped Value stripped Value strip function local Dictionary[key Value key strip ] stripped Valueif len arguments > len parameter Words print ' Warningtherearetoomanyinitialize Functionparametersfor 'print function element Node attributesprint parameter Wordsprint arguments
| null | null | null | null | Question:
What does the code delete ?
Code:
def setFunctionLocalDictionary(arguments, function):
function.localDictionary = {'_arguments': arguments}
if (len(arguments) > 0):
firstArgument = arguments[0]
if (firstArgument.__class__ == dict):
function.localDictionary = firstArgument
return
if ('parameters' not in function.elementNode.attributes):
return
parameters = function.elementNode.attributes['parameters'].strip()
if (parameters == ''):
return
parameterWords = parameters.split(',')
for (parameterWordIndex, parameterWord) in enumerate(parameterWords):
strippedWord = parameterWord.strip()
keyValue = KeyValue().getByEqual(strippedWord)
if (parameterWordIndex < len(arguments)):
function.localDictionary[keyValue.key] = arguments[parameterWordIndex]
else:
strippedValue = keyValue.value
if (strippedValue == None):
print 'Warning there is no default parameter in getParameterValue for:'
print strippedWord
print parameterWords
print arguments
print function.elementNode.attributes
else:
strippedValue = strippedValue.strip()
function.localDictionary[keyValue.key.strip()] = strippedValue
if (len(arguments) > len(parameterWords)):
print 'Warning there are too many initializeFunction parameters for:'
print function.elementNode.attributes
print parameterWords
print arguments
|
null | null | null | What does a view redirect to the get view ?
| def login_protected_redirect_view(request):
return HttpResponseRedirect('/test_client_regress/get_view/')
| null | null | null | all requests
| codeqa | def login protected redirect view request return Http Response Redirect '/test client regress/get view/'
| null | null | null | null | Question:
What does a view redirect to the get view ?
Code:
def login_protected_redirect_view(request):
return HttpResponseRedirect('/test_client_regress/get_view/')
|
null | null | null | What redirects all requests to the get view ?
| def login_protected_redirect_view(request):
return HttpResponseRedirect('/test_client_regress/get_view/')
| null | null | null | a view
| codeqa | def login protected redirect view request return Http Response Redirect '/test client regress/get view/'
| null | null | null | null | Question:
What redirects all requests to the get view ?
Code:
def login_protected_redirect_view(request):
return HttpResponseRedirect('/test_client_regress/get_view/')
|
null | null | null | When does time return ?
| def http2time(text):
m = STRICT_DATE_RE.search(text)
if m:
g = m.groups()
mon = (MONTHS_LOWER.index(g[1].lower()) + 1)
tt = (int(g[2]), mon, int(g[0]), int(g[3]), int(g[4]), float(g[5]))
return _timegm(tt)
text = text.lstrip()
text = WEEKDAY_RE.sub('', text, 1)
(day, mon, yr, hr, min, sec, tz) = ([None] * 7)
m = LOOSE_HTTP_DATE_RE.search(text)
if (m is not None):
(day, mon, yr, hr, min, sec, tz) = m.groups()
else:
return None
return _str2time(day, mon, yr, hr, min, sec, tz)
| null | null | null | in seconds
| codeqa | def http 2 time text m STRICT DATE RE search text if m g m groups mon MONTHS LOWER index g[ 1 ] lower + 1 tt int g[ 2 ] mon int g[ 0 ] int g[ 3 ] int g[ 4 ] float g[ 5 ] return timegm tt text text lstrip text WEEKDAY RE sub '' text 1 day mon yr hr min sec tz [ None] * 7 m LOOSE HTTP DATE RE search text if m is not None day mon yr hr min sec tz m groups else return Nonereturn str 2 time day mon yr hr min sec tz
| null | null | null | null | Question:
When does time return ?
Code:
def http2time(text):
m = STRICT_DATE_RE.search(text)
if m:
g = m.groups()
mon = (MONTHS_LOWER.index(g[1].lower()) + 1)
tt = (int(g[2]), mon, int(g[0]), int(g[3]), int(g[4]), float(g[5]))
return _timegm(tt)
text = text.lstrip()
text = WEEKDAY_RE.sub('', text, 1)
(day, mon, yr, hr, min, sec, tz) = ([None] * 7)
m = LOOSE_HTTP_DATE_RE.search(text)
if (m is not None):
(day, mon, yr, hr, min, sec, tz) = m.groups()
else:
return None
return _str2time(day, mon, yr, hr, min, sec, tz)
|
null | null | null | When did the code call ?
| def postDeploy(site):
pass
| null | null | null | after deploying the site
| codeqa | def post Deploy site pass
| null | null | null | null | Question:
When did the code call ?
Code:
def postDeploy(site):
pass
|
null | null | null | Where is substring sub found ?
| def find(s, *args):
return _apply(s.find, args)
| null | null | null | in s
| codeqa | def find s *args return apply s find args
| null | null | null | null | Question:
Where is substring sub found ?
Code:
def find(s, *args):
return _apply(s.find, args)
|
null | null | null | What is found in s ?
| def find(s, *args):
return _apply(s.find, args)
| null | null | null | substring sub
| codeqa | def find s *args return apply s find args
| null | null | null | null | Question:
What is found in s ?
Code:
def find(s, *args):
return _apply(s.find, args)
|
null | null | null | What will be updated here ?
| def update_info_dict(oldInfoDict, newInfoDict):
for (k, v) in newInfoDict.items():
if any((isinstance(v, t) for t in (tuple, list, dict))):
pass
elif ((oldInfoDict.get(k) is None) or (v not in (None, '', '0', 0))):
oldInfoDict[k] = v
| null | null | null | only normal values
| codeqa | def update info dict old Info Dict new Info Dict for k v in new Info Dict items if any isinstance v t for t in tuple list dict passelif old Info Dict get k is None or v not in None '' '0 ' 0 old Info Dict[k] v
| null | null | null | null | Question:
What will be updated here ?
Code:
def update_info_dict(oldInfoDict, newInfoDict):
for (k, v) in newInfoDict.items():
if any((isinstance(v, t) for t in (tuple, list, dict))):
pass
elif ((oldInfoDict.get(k) is None) or (v not in (None, '', '0', 0))):
oldInfoDict[k] = v
|
null | null | null | What do a string contain every three digits ?
| def intcomma(value):
orig = str(value)
new = re.sub('^(-?\\d+)(\\d{3})', '\\g<1>,\\g<2>', str(value))
if (orig == new):
return new
else:
return intcomma(new)
| null | null | null | commas
| codeqa | def intcomma value orig str value new re sub '^ -?\\d+ \\d{ 3 } ' '\\g< 1 > \\g< 2 >' str value if orig new return newelse return intcomma new
| null | null | null | null | Question:
What do a string contain every three digits ?
Code:
def intcomma(value):
orig = str(value)
new = re.sub('^(-?\\d+)(\\d{3})', '\\g<1>,\\g<2>', str(value))
if (orig == new):
return new
else:
return intcomma(new)
|
null | null | null | When do a string contain commas ?
| def intcomma(value):
orig = str(value)
new = re.sub('^(-?\\d+)(\\d{3})', '\\g<1>,\\g<2>', str(value))
if (orig == new):
return new
else:
return intcomma(new)
| null | null | null | every three digits
| codeqa | def intcomma value orig str value new re sub '^ -?\\d+ \\d{ 3 } ' '\\g< 1 > \\g< 2 >' str value if orig new return newelse return intcomma new
| null | null | null | null | Question:
When do a string contain commas ?
Code:
def intcomma(value):
orig = str(value)
new = re.sub('^(-?\\d+)(\\d{3})', '\\g<1>,\\g<2>', str(value))
if (orig == new):
return new
else:
return intcomma(new)
|
null | null | null | How does the image_data values dictionary convert it into the location_data format ?
| def _normalize_image_location_for_db(image_data):
if (('locations' not in image_data) and ('location_data' not in image_data)):
image_data['locations'] = None
return image_data
locations = image_data.pop('locations', [])
location_data = image_data.pop('location_data', [])
location_data_dict = {}
for l in locations:
location_data_dict[l] = {}
for l in location_data:
location_data_dict[l['url']] = {'metadata': l['metadata'], 'status': l['status'], 'id': (l['id'] if ('id' in l) else None)}
ordered_keys = locations[:]
for ld in location_data:
if (ld['url'] not in ordered_keys):
ordered_keys.append(ld['url'])
location_data = []
for loc in ordered_keys:
data = location_data_dict[loc]
if data:
location_data.append({'url': loc, 'metadata': data['metadata'], 'status': data['status'], 'id': data['id']})
else:
location_data.append({'url': loc, 'metadata': {}, 'status': 'active', 'id': None})
image_data['locations'] = location_data
return image_data
| null | null | null | only which is then consumable by the image object
| codeqa | def normalize image location for db image data if 'locations' not in image data and 'location data' not in image data image data['locations'] Nonereturn image datalocations image data pop 'locations' [] location data image data pop 'location data' [] location data dict {}for l in locations location data dict[l] {}for l in location data location data dict[l['url']] {'metadata' l['metadata'] 'status' l['status'] 'id' l['id'] if 'id' in l else None }ordered keys locations[ ]for ld in location data if ld['url'] not in ordered keys ordered keys append ld['url'] location data []for loc in ordered keys data location data dict[loc]if data location data append {'url' loc 'metadata' data['metadata'] 'status' data['status'] 'id' data['id']} else location data append {'url' loc 'metadata' {} 'status' 'active' 'id' None} image data['locations'] location datareturn image data
| null | null | null | null | Question:
How does the image_data values dictionary convert it into the location_data format ?
Code:
def _normalize_image_location_for_db(image_data):
if (('locations' not in image_data) and ('location_data' not in image_data)):
image_data['locations'] = None
return image_data
locations = image_data.pop('locations', [])
location_data = image_data.pop('location_data', [])
location_data_dict = {}
for l in locations:
location_data_dict[l] = {}
for l in location_data:
location_data_dict[l['url']] = {'metadata': l['metadata'], 'status': l['status'], 'id': (l['id'] if ('id' in l) else None)}
ordered_keys = locations[:]
for ld in location_data:
if (ld['url'] not in ordered_keys):
ordered_keys.append(ld['url'])
location_data = []
for loc in ordered_keys:
data = location_data_dict[loc]
if data:
location_data.append({'url': loc, 'metadata': data['metadata'], 'status': data['status'], 'id': data['id']})
else:
location_data.append({'url': loc, 'metadata': {}, 'status': 'active', 'id': None})
image_data['locations'] = location_data
return image_data
|
null | null | null | When did location_data field add ?
| def _normalize_image_location_for_db(image_data):
if (('locations' not in image_data) and ('location_data' not in image_data)):
image_data['locations'] = None
return image_data
locations = image_data.pop('locations', [])
location_data = image_data.pop('location_data', [])
location_data_dict = {}
for l in locations:
location_data_dict[l] = {}
for l in location_data:
location_data_dict[l['url']] = {'metadata': l['metadata'], 'status': l['status'], 'id': (l['id'] if ('id' in l) else None)}
ordered_keys = locations[:]
for ld in location_data:
if (ld['url'] not in ordered_keys):
ordered_keys.append(ld['url'])
location_data = []
for loc in ordered_keys:
data = location_data_dict[loc]
if data:
location_data.append({'url': loc, 'metadata': data['metadata'], 'status': data['status'], 'id': data['id']})
else:
location_data.append({'url': loc, 'metadata': {}, 'status': 'active', 'id': None})
image_data['locations'] = location_data
return image_data
| null | null | null | newly
| codeqa | def normalize image location for db image data if 'locations' not in image data and 'location data' not in image data image data['locations'] Nonereturn image datalocations image data pop 'locations' [] location data image data pop 'location data' [] location data dict {}for l in locations location data dict[l] {}for l in location data location data dict[l['url']] {'metadata' l['metadata'] 'status' l['status'] 'id' l['id'] if 'id' in l else None }ordered keys locations[ ]for ld in location data if ld['url'] not in ordered keys ordered keys append ld['url'] location data []for loc in ordered keys data location data dict[loc]if data location data append {'url' loc 'metadata' data['metadata'] 'status' data['status'] 'id' data['id']} else location data append {'url' loc 'metadata' {} 'status' 'active' 'id' None} image data['locations'] location datareturn image data
| null | null | null | null | Question:
When did location_data field add ?
Code:
def _normalize_image_location_for_db(image_data):
if (('locations' not in image_data) and ('location_data' not in image_data)):
image_data['locations'] = None
return image_data
locations = image_data.pop('locations', [])
location_data = image_data.pop('location_data', [])
location_data_dict = {}
for l in locations:
location_data_dict[l] = {}
for l in location_data:
location_data_dict[l['url']] = {'metadata': l['metadata'], 'status': l['status'], 'id': (l['id'] if ('id' in l) else None)}
ordered_keys = locations[:]
for ld in location_data:
if (ld['url'] not in ordered_keys):
ordered_keys.append(ld['url'])
location_data = []
for loc in ordered_keys:
data = location_data_dict[loc]
if data:
location_data.append({'url': loc, 'metadata': data['metadata'], 'status': data['status'], 'id': data['id']})
else:
location_data.append({'url': loc, 'metadata': {}, 'status': 'active', 'id': None})
image_data['locations'] = location_data
return image_data
|
null | null | null | Where is the location_data format consumable then ?
| def _normalize_image_location_for_db(image_data):
if (('locations' not in image_data) and ('location_data' not in image_data)):
image_data['locations'] = None
return image_data
locations = image_data.pop('locations', [])
location_data = image_data.pop('location_data', [])
location_data_dict = {}
for l in locations:
location_data_dict[l] = {}
for l in location_data:
location_data_dict[l['url']] = {'metadata': l['metadata'], 'status': l['status'], 'id': (l['id'] if ('id' in l) else None)}
ordered_keys = locations[:]
for ld in location_data:
if (ld['url'] not in ordered_keys):
ordered_keys.append(ld['url'])
location_data = []
for loc in ordered_keys:
data = location_data_dict[loc]
if data:
location_data.append({'url': loc, 'metadata': data['metadata'], 'status': data['status'], 'id': data['id']})
else:
location_data.append({'url': loc, 'metadata': {}, 'status': 'active', 'id': None})
image_data['locations'] = location_data
return image_data
| null | null | null | by the image object
| codeqa | def normalize image location for db image data if 'locations' not in image data and 'location data' not in image data image data['locations'] Nonereturn image datalocations image data pop 'locations' [] location data image data pop 'location data' [] location data dict {}for l in locations location data dict[l] {}for l in location data location data dict[l['url']] {'metadata' l['metadata'] 'status' l['status'] 'id' l['id'] if 'id' in l else None }ordered keys locations[ ]for ld in location data if ld['url'] not in ordered keys ordered keys append ld['url'] location data []for loc in ordered keys data location data dict[loc]if data location data append {'url' loc 'metadata' data['metadata'] 'status' data['status'] 'id' data['id']} else location data append {'url' loc 'metadata' {} 'status' 'active' 'id' None} image data['locations'] location datareturn image data
| null | null | null | null | Question:
Where is the location_data format consumable then ?
Code:
def _normalize_image_location_for_db(image_data):
if (('locations' not in image_data) and ('location_data' not in image_data)):
image_data['locations'] = None
return image_data
locations = image_data.pop('locations', [])
location_data = image_data.pop('location_data', [])
location_data_dict = {}
for l in locations:
location_data_dict[l] = {}
for l in location_data:
location_data_dict[l['url']] = {'metadata': l['metadata'], 'status': l['status'], 'id': (l['id'] if ('id' in l) else None)}
ordered_keys = locations[:]
for ld in location_data:
if (ld['url'] not in ordered_keys):
ordered_keys.append(ld['url'])
location_data = []
for loc in ordered_keys:
data = location_data_dict[loc]
if data:
location_data.append({'url': loc, 'metadata': data['metadata'], 'status': data['status'], 'id': data['id']})
else:
location_data.append({'url': loc, 'metadata': {}, 'status': 'active', 'id': None})
image_data['locations'] = location_data
return image_data
|
null | null | null | What is consumable by the image object ?
| def _normalize_image_location_for_db(image_data):
if (('locations' not in image_data) and ('location_data' not in image_data)):
image_data['locations'] = None
return image_data
locations = image_data.pop('locations', [])
location_data = image_data.pop('location_data', [])
location_data_dict = {}
for l in locations:
location_data_dict[l] = {}
for l in location_data:
location_data_dict[l['url']] = {'metadata': l['metadata'], 'status': l['status'], 'id': (l['id'] if ('id' in l) else None)}
ordered_keys = locations[:]
for ld in location_data:
if (ld['url'] not in ordered_keys):
ordered_keys.append(ld['url'])
location_data = []
for loc in ordered_keys:
data = location_data_dict[loc]
if data:
location_data.append({'url': loc, 'metadata': data['metadata'], 'status': data['status'], 'id': data['id']})
else:
location_data.append({'url': loc, 'metadata': {}, 'status': 'active', 'id': None})
image_data['locations'] = location_data
return image_data
| null | null | null | the location_data format
| codeqa | def normalize image location for db image data if 'locations' not in image data and 'location data' not in image data image data['locations'] Nonereturn image datalocations image data pop 'locations' [] location data image data pop 'location data' [] location data dict {}for l in locations location data dict[l] {}for l in location data location data dict[l['url']] {'metadata' l['metadata'] 'status' l['status'] 'id' l['id'] if 'id' in l else None }ordered keys locations[ ]for ld in location data if ld['url'] not in ordered keys ordered keys append ld['url'] location data []for loc in ordered keys data location data dict[loc]if data location data append {'url' loc 'metadata' data['metadata'] 'status' data['status'] 'id' data['id']} else location data append {'url' loc 'metadata' {} 'status' 'active' 'id' None} image data['locations'] location datareturn image data
| null | null | null | null | Question:
What is consumable by the image object ?
Code:
def _normalize_image_location_for_db(image_data):
if (('locations' not in image_data) and ('location_data' not in image_data)):
image_data['locations'] = None
return image_data
locations = image_data.pop('locations', [])
location_data = image_data.pop('location_data', [])
location_data_dict = {}
for l in locations:
location_data_dict[l] = {}
for l in location_data:
location_data_dict[l['url']] = {'metadata': l['metadata'], 'status': l['status'], 'id': (l['id'] if ('id' in l) else None)}
ordered_keys = locations[:]
for ld in location_data:
if (ld['url'] not in ordered_keys):
ordered_keys.append(ld['url'])
location_data = []
for loc in ordered_keys:
data = location_data_dict[loc]
if data:
location_data.append({'url': loc, 'metadata': data['metadata'], 'status': data['status'], 'id': data['id']})
else:
location_data.append({'url': loc, 'metadata': {}, 'status': 'active', 'id': None})
image_data['locations'] = location_data
return image_data
|
null | null | null | What do we create ?
| def test_oldstyle_getattr():
class C:
def __getattr__(self, name):
return globals()[name]
a = C()
| null | null | null | an old style class
| codeqa | def test oldstyle getattr class C def getattr self name return globals [name]a C
| null | null | null | null | Question:
What do we create ?
Code:
def test_oldstyle_getattr():
class C:
def __getattr__(self, name):
return globals()[name]
a = C()
|
null | null | null | What does the code get if it does not exist ?
| def worker_get(context, **filters):
query = _worker_query(context, **filters)
worker = (query.first() if query else None)
if (not worker):
raise exception.WorkerNotFound(**filters)
return worker
| null | null | null | a worker
| codeqa | def worker get context **filters query worker query context **filters worker query first if query else None if not worker raise exception Worker Not Found **filters return worker
| null | null | null | null | Question:
What does the code get if it does not exist ?
Code:
def worker_get(context, **filters):
query = _worker_query(context, **filters)
worker = (query.first() if query else None)
if (not worker):
raise exception.WorkerNotFound(**filters)
return worker
|
null | null | null | What did the code split by the occurrences of the pattern ?
| def split(pattern, string, maxsplit=0):
return _compile(pattern, 0).split(string, maxsplit)
| null | null | null | the source string
| codeqa | def split pattern string maxsplit 0 return compile pattern 0 split string maxsplit
| null | null | null | null | Question:
What did the code split by the occurrences of the pattern ?
Code:
def split(pattern, string, maxsplit=0):
return _compile(pattern, 0).split(string, maxsplit)
|
null | null | null | How did the code split the source string ?
| def split(pattern, string, maxsplit=0):
return _compile(pattern, 0).split(string, maxsplit)
| null | null | null | by the occurrences of the pattern
| codeqa | def split pattern string maxsplit 0 return compile pattern 0 split string maxsplit
| null | null | null | null | Question:
How did the code split the source string ?
Code:
def split(pattern, string, maxsplit=0):
return _compile(pattern, 0).split(string, maxsplit)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.