labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2
values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4
values | answer stringlengths 2 905 | src stringclasses 3
values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What does the code create ?
| @log_call
@utils.no_4byte_params
def metadef_namespace_create(context, values):
global DATA
namespace_values = copy.deepcopy(values)
namespace_name = namespace_values.get('namespace')
required_attributes = ['namespace', 'owner']
allowed_attributes = ['namespace', 'owner', 'display_name', 'description', 'visibility... | null | null | null | a namespace object
| codeqa | @log call@utils no 4byte paramsdef metadef namespace create context values global DAT Anamespace values copy deepcopy values namespace name namespace values get 'namespace' required attributes ['namespace' 'owner']allowed attributes ['namespace' 'owner' 'display name' 'description' 'visibility' 'protected']for namespac... | null | null | null | null | Question:
What does the code create ?
Code:
@log_call
@utils.no_4byte_params
def metadef_namespace_create(context, values):
global DATA
namespace_values = copy.deepcopy(values)
namespace_name = namespace_values.get('namespace')
required_attributes = ['namespace', 'owner']
allowed_attributes = ['namespace', 'ow... |
null | null | null | For what purpose do subplot parameters adjust ?
| def tight_layout(pad=1.2, h_pad=None, w_pad=None, fig=None):
import matplotlib.pyplot as plt
fig = (plt.gcf() if (fig is None) else fig)
fig.canvas.draw()
try:
fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad)
except Exception:
try:
fig.set_tight_layout(dict(pad=pad, h_pad=h_pad, w_pad=w_pad))
except Ex... | null | null | null | to give specified padding
| codeqa | def tight layout pad 1 2 h pad None w pad None fig None import matplotlib pyplot as pltfig plt gcf if fig is None else fig fig canvas draw try fig tight layout pad pad h pad h pad w pad w pad except Exception try fig set tight layout dict pad pad h pad h pad w pad w pad except Exception warn ' Matplotlibfunction"tight ... | null | null | null | null | Question:
For what purpose do subplot parameters adjust ?
Code:
def tight_layout(pad=1.2, h_pad=None, w_pad=None, fig=None):
import matplotlib.pyplot as plt
fig = (plt.gcf() if (fig is None) else fig)
fig.canvas.draw()
try:
fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad)
except Exception:
try:
fig.s... |
null | null | null | How did handler deny ?
| @requires_csrf_token
def permission_denied(request, template_name='403.html'):
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseForbidden('<h1>403 Forbidden</h1>')
return http.HttpResponseForbidden(template.render(RequestContext(request)))
| null | null | null | permission
| codeqa | @requires csrf tokendef permission denied request template name '403 html' try template loader get template template name except Template Does Not Exist return http Http Response Forbidden '<h 1 > 403 Forbidden</h 1 >' return http Http Response Forbidden template render Request Context request
| null | null | null | null | Question:
How did handler deny ?
Code:
@requires_csrf_token
def permission_denied(request, template_name='403.html'):
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseForbidden('<h1>403 Forbidden</h1>')
return http.HttpResponseForbidden(template.render(... |
null | null | null | What does the code remove ?
| @pytest.fixture(scope=u'function')
def remove_additional_folders(request):
def fin_remove_additional_folders():
if os.path.exists(u'tests/test-pyhooks/inputpyhooks'):
utils.rmtree(u'tests/test-pyhooks/inputpyhooks')
if os.path.exists(u'inputpyhooks'):
utils.rmtree(u'inputpyhooks')
if os.path.exists(u'tests... | null | null | null | some special folders which are created by the tests
| codeqa | @pytest fixture scope u'function' def remove additional folders request def fin remove additional folders if os path exists u'tests/test-pyhooks/inputpyhooks' utils rmtree u'tests/test-pyhooks/inputpyhooks' if os path exists u'inputpyhooks' utils rmtree u'inputpyhooks' if os path exists u'tests/test-shellhooks' utils r... | null | null | null | null | Question:
What does the code remove ?
Code:
@pytest.fixture(scope=u'function')
def remove_additional_folders(request):
def fin_remove_additional_folders():
if os.path.exists(u'tests/test-pyhooks/inputpyhooks'):
utils.rmtree(u'tests/test-pyhooks/inputpyhooks')
if os.path.exists(u'inputpyhooks'):
utils.rmt... |
null | null | null | What have the code puts into a manual state ?
| def managed(flag=True, using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
connection = connections[using]
thread_ident = thread.get_ident()
top = state.get(thread_ident, {}).get(using, None)
if top:
top[(-1)] = flag
if ((not flag) and is_dirty(using=using)):
connection._commit()
set_clean(using=... | null | null | null | the transaction manager
| codeqa | def managed flag True using None if using is None using DEFAULT DB ALIA Sconnection connections[using]thread ident thread get ident top state get thread ident {} get using None if top top[ -1 ] flagif not flag and is dirty using using connection commit set clean using using else raise Transaction Management Error " Thi... | null | null | null | null | Question:
What have the code puts into a manual state ?
Code:
def managed(flag=True, using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
connection = connections[using]
thread_ident = thread.get_ident()
top = state.get(thread_ident, {}).get(using, None)
if top:
top[(-1)] = flag
if ((not flag) and i... |
null | null | null | How be by the user committed managed transactions ?
| def managed(flag=True, using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
connection = connections[using]
thread_ident = thread.get_ident()
top = state.get(thread_ident, {}).get(using, None)
if top:
top[(-1)] = flag
if ((not flag) and is_dirty(using=using)):
connection._commit()
set_clean(using=... | null | null | null | explicitly
| codeqa | def managed flag True using None if using is None using DEFAULT DB ALIA Sconnection connections[using]thread ident thread get ident top state get thread ident {} get using None if top top[ -1 ] flagif not flag and is dirty using using connection commit set clean using using else raise Transaction Management Error " Thi... | null | null | null | null | Question:
How be by the user committed managed transactions ?
Code:
def managed(flag=True, using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
connection = connections[using]
thread_ident = thread.get_ident()
top = state.get(thread_ident, {}).get(using, None)
if top:
top[(-1)] = flag
if ((not flag)... |
null | null | null | What saves in a file ?
| def process_image(imagename, resultname, params='--edge-thresh 10 --peak-thresh 5'):
if (imagename[(-3):] != 'pgm'):
im = Image.open(imagename).convert('L')
im.save('tmp.pgm')
imagename = 'tmp.pgm'
cmmd = str(((((('sift ' + imagename) + ' --output=') + resultname) + ' ') + params))
os.system(cmmd)
print... | null | null | null | the results
| codeqa | def process image imagename resultname params '--edge-thresh 10 --peak-thresh 5 ' if imagename[ -3 ] 'pgm' im Image open imagename convert 'L' im save 'tmp pgm' imagename 'tmp pgm'cmmd str 'sift' + imagename + '--output ' + resultname + '' + params os system cmmd print 'processed' imagename 'to' resultname
| null | null | null | null | Question:
What saves in a file ?
Code:
def process_image(imagename, resultname, params='--edge-thresh 10 --peak-thresh 5'):
if (imagename[(-3):] != 'pgm'):
im = Image.open(imagename).convert('L')
im.save('tmp.pgm')
imagename = 'tmp.pgm'
cmmd = str(((((('sift ' + imagename) + ' --output=') + resultname)... |
null | null | null | Where do the results save ?
| def process_image(imagename, resultname, params='--edge-thresh 10 --peak-thresh 5'):
if (imagename[(-3):] != 'pgm'):
im = Image.open(imagename).convert('L')
im.save('tmp.pgm')
imagename = 'tmp.pgm'
cmmd = str(((((('sift ' + imagename) + ' --output=') + resultname) + ' ') + params))
os.system(cmmd)
print... | null | null | null | in a file
| codeqa | def process image imagename resultname params '--edge-thresh 10 --peak-thresh 5 ' if imagename[ -3 ] 'pgm' im Image open imagename convert 'L' im save 'tmp pgm' imagename 'tmp pgm'cmmd str 'sift' + imagename + '--output ' + resultname + '' + params os system cmmd print 'processed' imagename 'to' resultname
| null | null | null | null | Question:
Where do the results save ?
Code:
def process_image(imagename, resultname, params='--edge-thresh 10 --peak-thresh 5'):
if (imagename[(-3):] != 'pgm'):
im = Image.open(imagename).convert('L')
im.save('tmp.pgm')
imagename = 'tmp.pgm'
cmmd = str(((((('sift ' + imagename) + ' --output=') + result... |
null | null | null | What does the code get from the remote server ?
| def _GetRemoteAppId(url, throttle, email, passin, raw_input_fn=raw_input, password_input_fn=getpass.getpass, throttle_class=None):
(scheme, host_port, url_path, _, _) = urlparse.urlsplit(url)
secure = (scheme == 'https')
throttled_rpc_server_factory = remote_api_throttle.ThrottledHttpRpcServerFactory(throttle, throt... | null | null | null | the app i d
| codeqa | def Get Remote App Id url throttle email passin raw input fn raw input password input fn getpass getpass throttle class None scheme host port url path urlparse urlsplit url secure scheme 'https' throttled rpc server factory remote api throttle Throttled Http Rpc Server Factory throttle throttle class throttle class def... | null | null | null | null | Question:
What does the code get from the remote server ?
Code:
def _GetRemoteAppId(url, throttle, email, passin, raw_input_fn=raw_input, password_input_fn=getpass.getpass, throttle_class=None):
(scheme, host_port, url_path, _, _) = urlparse.urlsplit(url)
secure = (scheme == 'https')
throttled_rpc_server_factory... |
null | null | null | How do all volumes transfers see a special search option ?
| @profiler.trace
def transfer_list(request, detailed=True, search_opts=None):
c_client = cinderclient(request)
try:
return [VolumeTransfer(v) for v in c_client.transfers.list(detailed=detailed, search_opts=search_opts)]
except cinder_exception.Forbidden as error:
LOG.error(error)
return []
| null | null | null | in
| codeqa | @profiler tracedef transfer list request detailed True search opts None c client cinderclient request try return [ Volume Transfer v for v in c client transfers list detailed detailed search opts search opts ]except cinder exception Forbidden as error LOG error error return []
| null | null | null | null | Question:
How do all volumes transfers see a special search option ?
Code:
@profiler.trace
def transfer_list(request, detailed=True, search_opts=None):
c_client = cinderclient(request)
try:
return [VolumeTransfer(v) for v in c_client.transfers.list(detailed=detailed, search_opts=search_opts)]
except cinder_exc... |
null | null | null | How do the given expression structure visit ?
| def traverse_depthfirst(obj, opts, visitors):
return traverse_using(iterate_depthfirst(obj, opts), obj, visitors)
| null | null | null | using the depth - first iterator
| codeqa | def traverse depthfirst obj opts visitors return traverse using iterate depthfirst obj opts obj visitors
| null | null | null | null | Question:
How do the given expression structure visit ?
Code:
def traverse_depthfirst(obj, opts, visitors):
return traverse_using(iterate_depthfirst(obj, opts), obj, visitors)
|
null | null | null | How do the given expression structure traverse ?
| def traverse_depthfirst(obj, opts, visitors):
return traverse_using(iterate_depthfirst(obj, opts), obj, visitors)
| null | null | null | using the depth - first iterator
| codeqa | def traverse depthfirst obj opts visitors return traverse using iterate depthfirst obj opts obj visitors
| null | null | null | null | Question:
How do the given expression structure traverse ?
Code:
def traverse_depthfirst(obj, opts, visitors):
return traverse_using(iterate_depthfirst(obj, opts), obj, visitors)
|
null | null | null | What does the code get ?
| def backup_get_all_by_project(context, project_id, filters=None, marker=None, limit=None, offset=None, sort_keys=None, sort_dirs=None):
return IMPL.backup_get_all_by_project(context, project_id, filters=filters, marker=marker, limit=limit, offset=offset, sort_keys=sort_keys, sort_dirs=sort_dirs)
| null | null | null | all backups belonging to a project
| codeqa | def backup get all by project context project id filters None marker None limit None offset None sort keys None sort dirs None return IMPL backup get all by project context project id filters filters marker marker limit limit offset offset sort keys sort keys sort dirs sort dirs
| null | null | null | null | Question:
What does the code get ?
Code:
def backup_get_all_by_project(context, project_id, filters=None, marker=None, limit=None, offset=None, sort_keys=None, sort_dirs=None):
return IMPL.backup_get_all_by_project(context, project_id, filters=filters, marker=marker, limit=limit, offset=offset, sort_keys=sort_keys... |
null | null | null | What does the code return ?
| def mask_hash(hash, show=6, char='*'):
masked = hash[:show]
masked += (char * len(hash[show:]))
return masked
| null | null | null | the given hash
| codeqa | def mask hash hash show 6 char '*' masked hash[ show]masked + char * len hash[show ] return masked
| null | null | null | null | Question:
What does the code return ?
Code:
def mask_hash(hash, show=6, char='*'):
masked = hash[:show]
masked += (char * len(hash[show:]))
return masked
|
null | null | null | What does the code initialize ?
| def init_source():
codename = crypto_util.genrandomid()
filesystem_id = crypto_util.hash_codename(codename)
journalist_filename = crypto_util.display_id()
source = db.Source(filesystem_id, journalist_filename)
db.db_session.add(source)
db.db_session.commit()
os.mkdir(store.path(source.filesystem_id))
crypto_uti... | null | null | null | a source
| codeqa | def init source codename crypto util genrandomid filesystem id crypto util hash codename codename journalist filename crypto util display id source db Source filesystem id journalist filename db db session add source db db session commit os mkdir store path source filesystem id crypto util genkeypair source filesystem ... | null | null | null | null | Question:
What does the code initialize ?
Code:
def init_source():
codename = crypto_util.genrandomid()
filesystem_id = crypto_util.hash_codename(codename)
journalist_filename = crypto_util.display_id()
source = db.Source(filesystem_id, journalist_filename)
db.db_session.add(source)
db.db_session.commit()
os... |
null | null | null | How do a regex compile ?
| def _lazy_re_compile(regex, flags=0):
def _compile():
if isinstance(regex, str):
return re.compile(regex, flags)
else:
assert (not flags), 'flags must be empty if regex is passed pre-compiled'
return regex
return SimpleLazyObject(_compile)
| null | null | null | lazily
| codeqa | def lazy re compile regex flags 0 def compile if isinstance regex str return re compile regex flags else assert not flags 'flagsmustbeemptyifregexispassedpre-compiled'return regexreturn Simple Lazy Object compile
| null | null | null | null | Question:
How do a regex compile ?
Code:
def _lazy_re_compile(regex, flags=0):
def _compile():
if isinstance(regex, str):
return re.compile(regex, flags)
else:
assert (not flags), 'flags must be empty if regex is passed pre-compiled'
return regex
return SimpleLazyObject(_compile)
|
null | null | null | What does the code create ?
| def _build_match_rule(action, target):
match_rule = policy.RuleCheck('rule', action)
(resource, is_write) = get_resource_and_action(action)
if is_write:
res_map = attributes.RESOURCE_ATTRIBUTE_MAP
if (resource in res_map):
for attribute_name in res_map[resource]:
if _is_attribute_explicitly_set(attribute_... | null | null | null | the rule to match for a given action
| codeqa | def build match rule action target match rule policy Rule Check 'rule' action resource is write get resource and action action if is write res map attributes RESOURCE ATTRIBUTE MA Pif resource in res map for attribute name in res map[resource] if is attribute explicitly set attribute name res map[resource] target attri... | null | null | null | null | Question:
What does the code create ?
Code:
def _build_match_rule(action, target):
match_rule = policy.RuleCheck('rule', action)
(resource, is_write) = get_resource_and_action(action)
if is_write:
res_map = attributes.RESOURCE_ATTRIBUTE_MAP
if (resource in res_map):
for attribute_name in res_map[resource]... |
null | null | null | How do arguments build ?
| def build_info():
ret = {'info': []}
out = __salt__['cmd.run']('{0} -V'.format(__detect_os()))
for i in out.splitlines():
if i.startswith('configure argument'):
ret['build arguments'] = re.findall("(?:[^\\s]*'.*')|(?:[^\\s]+)", i)[2:]
continue
ret['info'].append(i)
return ret
| null | null | null | cli example
| codeqa | def build info ret {'info' []}out salt ['cmd run'] '{ 0 }-V' format detect os for i in out splitlines if i startswith 'configureargument' ret['buildarguments'] re findall " ? [^\\s]*' *' ? [^\\s]+ " i [2 ]continueret['info'] append i return ret
| null | null | null | null | Question:
How do arguments build ?
Code:
def build_info():
ret = {'info': []}
out = __salt__['cmd.run']('{0} -V'.format(__detect_os()))
for i in out.splitlines():
if i.startswith('configure argument'):
ret['build arguments'] = re.findall("(?:[^\\s]*'.*')|(?:[^\\s]+)", i)[2:]
continue
ret['info'].app... |
null | null | null | What does the code find ?
| def negotiate_locale(preferred, available, sep='_', aliases=LOCALE_ALIASES):
available = [a.lower() for a in available if a]
for locale in preferred:
ll = locale.lower()
if (ll in available):
return locale
if aliases:
alias = aliases.get(ll)
if alias:
alias = alias.replace('_', sep)
if (alias.l... | null | null | null | the best match between available and requested locale strings
| codeqa | def negotiate locale preferred available sep ' ' aliases LOCALE ALIASES available [a lower for a in available if a]for locale in preferred ll locale lower if ll in available return localeif aliases alias aliases get ll if alias alias alias replace ' ' sep if alias lower in available return aliasparts locale split sep i... | null | null | null | null | Question:
What does the code find ?
Code:
def negotiate_locale(preferred, available, sep='_', aliases=LOCALE_ALIASES):
available = [a.lower() for a in available if a]
for locale in preferred:
ll = locale.lower()
if (ll in available):
return locale
if aliases:
alias = aliases.get(ll)
if alias:
a... |
null | null | null | What will check adding the file to the database preserve ?
| def file_upload_filename_case_view(request):
file = request.FILES[u'file_field']
obj = FileModel()
obj.testfile.save(file.name, file)
return HttpResponse((u'%d' % obj.pk))
| null | null | null | the filename case
| codeqa | def file upload filename case view request file request FILES[u'file field']obj File Model obj testfile save file name file return Http Response u'%d' % obj pk
| null | null | null | null | Question:
What will check adding the file to the database preserve ?
Code:
def file_upload_filename_case_view(request):
file = request.FILES[u'file_field']
obj = FileModel()
obj.testfile.save(file.name, file)
return HttpResponse((u'%d' % obj.pk))
|
null | null | null | What will preserve the filename case ?
| def file_upload_filename_case_view(request):
file = request.FILES[u'file_field']
obj = FileModel()
obj.testfile.save(file.name, file)
return HttpResponse((u'%d' % obj.pk))
| null | null | null | check adding the file to the database
| codeqa | def file upload filename case view request file request FILES[u'file field']obj File Model obj testfile save file name file return Http Response u'%d' % obj pk
| null | null | null | null | Question:
What will preserve the filename case ?
Code:
def file_upload_filename_case_view(request):
file = request.FILES[u'file_field']
obj = FileModel()
obj.testfile.save(file.name, file)
return HttpResponse((u'%d' % obj.pk))
|
null | null | null | What do code block ?
| def ginput(*args, **kwargs):
return gcf().ginput(*args, **kwargs)
| null | null | null | call
| codeqa | def ginput *args **kwargs return gcf ginput *args **kwargs
| null | null | null | null | Question:
What do code block ?
Code:
def ginput(*args, **kwargs):
return gcf().ginput(*args, **kwargs)
|
null | null | null | What does the country call for a specific region ?
| def country_code_for_valid_region(region_code):
metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None)
if (metadata is None):
raise Exception(('Invalid region code %s' % region_code))
return metadata.country_code
| null | null | null | code
| codeqa | def country code for valid region region code metadata Phone Metadata metadata for region region code upper None if metadata is None raise Exception ' Invalidregioncode%s' % region code return metadata country code
| null | null | null | null | Question:
What does the country call for a specific region ?
Code:
def country_code_for_valid_region(region_code):
metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None)
if (metadata is None):
raise Exception(('Invalid region code %s' % region_code))
return metadata.country_code
|
null | null | null | What is calling code for a specific region ?
| def country_code_for_valid_region(region_code):
metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None)
if (metadata is None):
raise Exception(('Invalid region code %s' % region_code))
return metadata.country_code
| null | null | null | the country
| codeqa | def country code for valid region region code metadata Phone Metadata metadata for region region code upper None if metadata is None raise Exception ' Invalidregioncode%s' % region code return metadata country code
| null | null | null | null | Question:
What is calling code for a specific region ?
Code:
def country_code_for_valid_region(region_code):
metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None)
if (metadata is None):
raise Exception(('Invalid region code %s' % region_code))
return metadata.country_code
|
null | null | null | What does the code turn into a 2d tensor where the first dimension is conserved ?
| def batch_flatten(x):
x = tf.reshape(x, stack([(-1), prod(shape(x)[1:])]))
return x
| null | null | null | a n - d tensor
| codeqa | def batch flatten x x tf reshape x stack [ -1 prod shape x [1 ] ] return x
| null | null | null | null | Question:
What does the code turn into a 2d tensor where the first dimension is conserved ?
Code:
def batch_flatten(x):
x = tf.reshape(x, stack([(-1), prod(shape(x)[1:])]))
return x
|
null | null | null | Where is the first dimension conserved ?
| def batch_flatten(x):
x = tf.reshape(x, stack([(-1), prod(shape(x)[1:])]))
return x
| null | null | null | a 2d tensor
| codeqa | def batch flatten x x tf reshape x stack [ -1 prod shape x [1 ] ] return x
| null | null | null | null | Question:
Where is the first dimension conserved ?
Code:
def batch_flatten(x):
x = tf.reshape(x, stack([(-1), prod(shape(x)[1:])]))
return x
|
null | null | null | What does the code normalize ?
| def normalize_encoding(encoding):
if (hasattr(types, 'UnicodeType') and (type(encoding) is types.UnicodeType)):
encoding = encoding.encode('latin-1')
return '_'.join(encoding.translate(_norm_encoding_map).split())
| null | null | null | an encoding name
| codeqa | def normalize encoding encoding if hasattr types ' Unicode Type' and type encoding is types Unicode Type encoding encoding encode 'latin- 1 ' return ' ' join encoding translate norm encoding map split
| null | null | null | null | Question:
What does the code normalize ?
Code:
def normalize_encoding(encoding):
if (hasattr(types, 'UnicodeType') and (type(encoding) is types.UnicodeType)):
encoding = encoding.encode('latin-1')
return '_'.join(encoding.translate(_norm_encoding_map).split())
|
null | null | null | What does the code create ?
| def create_instance(context, user_id='fake', project_id='fake', params=None):
flavor = flavors.get_flavor_by_name('m1.tiny')
net_info = model.NetworkInfo([])
info_cache = objects.InstanceInfoCache(network_info=net_info)
inst = objects.Instance(context=context, image_ref=uuids.fake_image_ref, reservation_id='r-faker... | null | null | null | a test instance
| codeqa | def create instance context user id 'fake' project id 'fake' params None flavor flavors get flavor by name 'm 1 tiny' net info model Network Info [] info cache objects Instance Info Cache network info net info inst objects Instance context context image ref uuids fake image ref reservation id 'r-fakeres' user id user i... | null | null | null | null | Question:
What does the code create ?
Code:
def create_instance(context, user_id='fake', project_id='fake', params=None):
flavor = flavors.get_flavor_by_name('m1.tiny')
net_info = model.NetworkInfo([])
info_cache = objects.InstanceInfoCache(network_info=net_info)
inst = objects.Instance(context=context, image_r... |
null | null | null | What does this decorator activate ?
| def commit_on_success(func):
def _commit_on_success(*args, **kw):
try:
enter_transaction_management()
managed(True)
try:
res = func(*args, **kw)
except Exception as e:
if is_dirty():
rollback()
raise
else:
if is_dirty():
commit()
return res
finally:
leave_transaction_... | null | null | null | commit on response
| codeqa | def commit on success func def commit on success *args **kw try enter transaction management managed True try res func *args **kw except Exception as e if is dirty rollback raiseelse if is dirty commit return resfinally leave transaction management return commit on success
| null | null | null | null | Question:
What does this decorator activate ?
Code:
def commit_on_success(func):
def _commit_on_success(*args, **kw):
try:
enter_transaction_management()
managed(True)
try:
res = func(*args, **kw)
except Exception as e:
if is_dirty():
rollback()
raise
else:
if is_dirty():
... |
null | null | null | What activates commit on response ?
| def commit_on_success(func):
def _commit_on_success(*args, **kw):
try:
enter_transaction_management()
managed(True)
try:
res = func(*args, **kw)
except Exception as e:
if is_dirty():
rollback()
raise
else:
if is_dirty():
commit()
return res
finally:
leave_transaction_... | null | null | null | this decorator
| codeqa | def commit on success func def commit on success *args **kw try enter transaction management managed True try res func *args **kw except Exception as e if is dirty rollback raiseelse if is dirty commit return resfinally leave transaction management return commit on success
| null | null | null | null | Question:
What activates commit on response ?
Code:
def commit_on_success(func):
def _commit_on_success(*args, **kw):
try:
enter_transaction_management()
managed(True)
try:
res = func(*args, **kw)
except Exception as e:
if is_dirty():
rollback()
raise
else:
if is_dirty():
... |
null | null | null | What do the endpoint segments overhang ?
| def getOverhangDirection(belowOutsetLoops, segmentBegin, segmentEnd):
segment = (segmentEnd - segmentBegin)
normalizedSegment = euclidean.getNormalized(complex(segment.real, segment.imag))
segmentYMirror = complex(normalizedSegment.real, (- normalizedSegment.imag))
segmentBegin = (segmentYMirror * segmentBegin)
se... | null | null | null | the layer below
| codeqa | def get Overhang Direction below Outset Loops segment Begin segment End segment segment End - segment Begin normalized Segment euclidean get Normalized complex segment real segment imag segment Y Mirror complex normalized Segment real - normalized Segment imag segment Begin segment Y Mirror * segment Begin segment End ... | null | null | null | null | Question:
What do the endpoint segments overhang ?
Code:
def getOverhangDirection(belowOutsetLoops, segmentBegin, segmentEnd):
segment = (segmentEnd - segmentBegin)
normalizedSegment = euclidean.getNormalized(complex(segment.real, segment.imag))
segmentYMirror = complex(normalizedSegment.real, (- normalizedSegme... |
null | null | null | What overhang the layer below ?
| def getOverhangDirection(belowOutsetLoops, segmentBegin, segmentEnd):
segment = (segmentEnd - segmentBegin)
normalizedSegment = euclidean.getNormalized(complex(segment.real, segment.imag))
segmentYMirror = complex(normalizedSegment.real, (- normalizedSegment.imag))
segmentBegin = (segmentYMirror * segmentBegin)
se... | null | null | null | the endpoint segments
| codeqa | def get Overhang Direction below Outset Loops segment Begin segment End segment segment End - segment Begin normalized Segment euclidean get Normalized complex segment real segment imag segment Y Mirror complex normalized Segment real - normalized Segment imag segment Begin segment Y Mirror * segment Begin segment End ... | null | null | null | null | Question:
What overhang the layer below ?
Code:
def getOverhangDirection(belowOutsetLoops, segmentBegin, segmentEnd):
segment = (segmentEnd - segmentBegin)
normalizedSegment = euclidean.getNormalized(complex(segment.real, segment.imag))
segmentYMirror = complex(normalizedSegment.real, (- normalizedSegment.imag))... |
null | null | null | When do we have a user object ?
| def start_user_as_anon():
return {'user': ANON}
| null | null | null | always
| codeqa | def start user as anon return {'user' ANON}
| null | null | null | null | Question:
When do we have a user object ?
Code:
def start_user_as_anon():
return {'user': ANON}
|
null | null | null | What does the code create ?
| def create_container(reactor, control_service, node_uuid, name, image, volumes=None, timeout=DEFAULT_TIMEOUT):
d = control_service.create_container(node_uuid, name, image, volumes)
def wait_until_running(container):
def container_matches(container, state):
return ((container.name == state.name) and (container.no... | null | null | null | a container
| codeqa | def create container reactor control service node uuid name image volumes None timeout DEFAULT TIMEOUT d control service create container node uuid name image volumes def wait until running container def container matches container state return container name state name and container node uuid state node uuid and state... | null | null | null | null | Question:
What does the code create ?
Code:
def create_container(reactor, control_service, node_uuid, name, image, volumes=None, timeout=DEFAULT_TIMEOUT):
d = control_service.create_container(node_uuid, name, image, volumes)
def wait_until_running(container):
def container_matches(container, state):
return (... |
null | null | null | What does the code add to negatives ?
| def addNegativesByRadius(end, negatives, radius, start, xmlElement):
extrudeDerivation = extrude.ExtrudeDerivation()
addNegativesByDerivation(end, extrudeDerivation, negatives, radius, start, xmlElement)
| null | null | null | teardrop drill hole
| codeqa | def add Negatives By Radius end negatives radius start xml Element extrude Derivation extrude Extrude Derivation add Negatives By Derivation end extrude Derivation negatives radius start xml Element
| null | null | null | null | Question:
What does the code add to negatives ?
Code:
def addNegativesByRadius(end, negatives, radius, start, xmlElement):
extrudeDerivation = extrude.ExtrudeDerivation()
addNegativesByDerivation(end, extrudeDerivation, negatives, radius, start, xmlElement)
|
null | null | null | What does the code give ?
| def get_email_preferences_for_exploration(user_id, exploration_id):
exploration_user_model = user_models.ExplorationUserDataModel.get(user_id, exploration_id)
if (exploration_user_model is None):
return user_domain.UserExplorationPrefs.create_default_prefs()
else:
return user_domain.UserExplorationPrefs(explorat... | null | null | null | mute preferences for exploration with given exploration_id of user with given user_id
| codeqa | def get email preferences for exploration user id exploration id exploration user model user models Exploration User Data Model get user id exploration id if exploration user model is None return user domain User Exploration Prefs create default prefs else return user domain User Exploration Prefs exploration user mode... | null | null | null | null | Question:
What does the code give ?
Code:
def get_email_preferences_for_exploration(user_id, exploration_id):
exploration_user_model = user_models.ExplorationUserDataModel.get(user_id, exploration_id)
if (exploration_user_model is None):
return user_domain.UserExplorationPrefs.create_default_prefs()
else:
re... |
null | null | null | What does the code validate ?
| def __validate__(config):
if (not isinstance(config, dict)):
return (False, 'Configuration for btmp beacon must be a list of dictionaries.')
return (True, 'Valid beacon configuration')
| null | null | null | the beacon configuration
| codeqa | def validate config if not isinstance config dict return False ' Configurationforbtmpbeaconmustbealistofdictionaries ' return True ' Validbeaconconfiguration'
| null | null | null | null | Question:
What does the code validate ?
Code:
def __validate__(config):
if (not isinstance(config, dict)):
return (False, 'Configuration for btmp beacon must be a list of dictionaries.')
return (True, 'Valid beacon configuration')
|
null | null | null | What does the code delete if appropriate ?
| def check_resource_cleanup(rsrc, template_id, resource_data, engine_id, timeout, msg_queue):
check_message = functools.partial(_check_for_message, msg_queue)
rsrc.delete_convergence(template_id, resource_data, engine_id, timeout, check_message)
| null | null | null | the resource
| codeqa | def check resource cleanup rsrc template id resource data engine id timeout msg queue check message functools partial check for message msg queue rsrc delete convergence template id resource data engine id timeout check message
| null | null | null | null | Question:
What does the code delete if appropriate ?
Code:
def check_resource_cleanup(rsrc, template_id, resource_data, engine_id, timeout, msg_queue):
check_message = functools.partial(_check_for_message, msg_queue)
rsrc.delete_convergence(template_id, resource_data, engine_id, timeout, check_message)
|
null | null | null | When do all the text parts concatenate ?
| def token_list_to_text(tokenlist):
ZeroWidthEscape = Token.ZeroWidthEscape
return u''.join((item[1] for item in tokenlist if (item[0] != ZeroWidthEscape)))
| null | null | null | again
| codeqa | def token list to text tokenlist Zero Width Escape Token Zero Width Escapereturn u'' join item[ 1 ] for item in tokenlist if item[ 0 ] Zero Width Escape
| null | null | null | null | Question:
When do all the text parts concatenate ?
Code:
def token_list_to_text(tokenlist):
ZeroWidthEscape = Token.ZeroWidthEscape
return u''.join((item[1] for item in tokenlist if (item[0] != ZeroWidthEscape)))
|
null | null | null | What does the code create ?
| def link(src, dst):
if (platform.system() == u'Windows'):
if (ctypes.windll.kernel32.CreateHardLinkW(ctypes.c_wchar_p(unicode(dst)), ctypes.c_wchar_p(unicode(src)), None) == 0):
raise ctypes.WinError()
else:
ek(os.link, src, dst)
| null | null | null | a file link from source to destination
| codeqa | def link src dst if platform system u' Windows' if ctypes windll kernel 32 Create Hard Link W ctypes c wchar p unicode dst ctypes c wchar p unicode src None 0 raise ctypes Win Error else ek os link src dst
| null | null | null | null | Question:
What does the code create ?
Code:
def link(src, dst):
if (platform.system() == u'Windows'):
if (ctypes.windll.kernel32.CreateHardLinkW(ctypes.c_wchar_p(unicode(dst)), ctypes.c_wchar_p(unicode(src)), None) == 0):
raise ctypes.WinError()
else:
ek(os.link, src, dst)
|
null | null | null | When is output being redirected to a stream ?
| def get_capture_stream():
return getattr(local_context, u'output', None)
| null | null | null | currently
| codeqa | def get capture stream return getattr local context u'output' None
| null | null | null | null | Question:
When is output being redirected to a stream ?
Code:
def get_capture_stream():
return getattr(local_context, u'output', None)
|
null | null | null | What does the code get ?
| def getNewRepository():
return FillRepository()
| null | null | null | new repository
| codeqa | def get New Repository return Fill Repository
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewRepository():
return FillRepository()
|
null | null | null | How does the code convert a text string to a byte string ?
| def t2b(t):
clean = b(rws(t))
if ((len(clean) % 2) == 1):
print clean
raise ValueError('Even number of characters expected')
return a2b_hex(clean)
| null | null | null | with bytes in hex form
| codeqa | def t2 b t clean b rws t if len clean % 2 1 print cleanraise Value Error ' Evennumberofcharactersexpected' return a2 b hex clean
| null | null | null | null | Question:
How does the code convert a text string to a byte string ?
Code:
def t2b(t):
clean = b(rws(t))
if ((len(clean) % 2) == 1):
print clean
raise ValueError('Even number of characters expected')
return a2b_hex(clean)
|
null | null | null | What does the code convert to a byte string with bytes in hex form ?
| def t2b(t):
clean = b(rws(t))
if ((len(clean) % 2) == 1):
print clean
raise ValueError('Even number of characters expected')
return a2b_hex(clean)
| null | null | null | a text string
| codeqa | def t2 b t clean b rws t if len clean % 2 1 print cleanraise Value Error ' Evennumberofcharactersexpected' return a2 b hex clean
| null | null | null | null | Question:
What does the code convert to a byte string with bytes in hex form ?
Code:
def t2b(t):
clean = b(rws(t))
if ((len(clean) % 2) == 1):
print clean
raise ValueError('Even number of characters expected')
return a2b_hex(clean)
|
null | null | null | When did more than one delay ?
| def compute(*args, **kwargs):
args = [delayed(a) for a in args]
return base.compute(*args, **kwargs)
| null | null | null | at once
| codeqa | def compute *args **kwargs args [delayed a for a in args]return base compute *args **kwargs
| null | null | null | null | Question:
When did more than one delay ?
Code:
def compute(*args, **kwargs):
args = [delayed(a) for a in args]
return base.compute(*args, **kwargs)
|
null | null | null | What does the code create ?
| def backref(name, **kwargs):
return (name, kwargs)
| null | null | null | a back reference with explicit keyword arguments
| codeqa | def backref name **kwargs return name kwargs
| null | null | null | null | Question:
What does the code create ?
Code:
def backref(name, **kwargs):
return (name, kwargs)
|
null | null | null | What did the code set only if the field does not exist ?
| def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
| null | null | null | the value of a hash field
| codeqa | def hsetnx key field value host None port None db None password None server connect host port db password return server hsetnx key field value
| null | null | null | null | Question:
What did the code set only if the field does not exist ?
Code:
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
|
null | null | null | What does the code take ?
| @register.filter
def can_moderate(obj, user):
return obj.can_moderate(user)
| null | null | null | article or related to article model
| codeqa | @register filterdef can moderate obj user return obj can moderate user
| null | null | null | null | Question:
What does the code take ?
Code:
@register.filter
def can_moderate(obj, user):
return obj.can_moderate(user)
|
null | null | null | What does the code parse to a named group ?
| def parse_call_named_group(source, info, pos):
group = parse_name(source)
source.expect(')')
return CallGroup(info, group, pos)
| null | null | null | a call
| codeqa | def parse call named group source info pos group parse name source source expect ' ' return Call Group info group pos
| null | null | null | null | Question:
What does the code parse to a named group ?
Code:
def parse_call_named_group(source, info, pos):
group = parse_name(source)
source.expect(')')
return CallGroup(info, group, pos)
|
null | null | null | What does the code install ?
| def install(packages, update=False, options=None, version=None):
manager = MANAGER
if update:
update_index()
if (options is None):
options = []
if (version is None):
version = ''
if (version and (not isinstance(packages, list))):
version = ('=' + version)
if (not isinstance(packages, basestring)):
packa... | null | null | null | one or more packages
| codeqa | def install packages update False options None version None manager MANAGE Rif update update index if options is None options []if version is None version ''if version and not isinstance packages list version ' ' + version if not isinstance packages basestring packages '' join packages options append '--quiet' options ... | null | null | null | null | Question:
What does the code install ?
Code:
def install(packages, update=False, options=None, version=None):
manager = MANAGER
if update:
update_index()
if (options is None):
options = []
if (version is None):
version = ''
if (version and (not isinstance(packages, list))):
version = ('=' + version)
i... |
null | null | null | What does the code create ?
| def new_figure_manager(num, *args, **kwargs):
if __debug__:
verbose.report('backend_agg.new_figure_manager', 'debug-annoying')
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
canvas = FigureCanvasAgg(thisFig)
manager = FigureManagerBase(canvas, num)
return manager
| null | null | null | a new figure manager instance
| codeqa | def new figure manager num *args **kwargs if debug verbose report 'backend agg new figure manager' 'debug-annoying' Figure Class kwargs pop ' Figure Class' Figure this Fig Figure Class *args **kwargs canvas Figure Canvas Agg this Fig manager Figure Manager Base canvas num return manager
| null | null | null | null | Question:
What does the code create ?
Code:
def new_figure_manager(num, *args, **kwargs):
if __debug__:
verbose.report('backend_agg.new_figure_manager', 'debug-annoying')
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
canvas = FigureCanvasAgg(thisFig)
manager = FigureM... |
null | null | null | How do style dictionaries merge ?
| def styleof(expr, styles=default_styles):
style = dict()
for (typ, sty) in styles:
if isinstance(expr, typ):
style.update(sty)
return style
| null | null | null | in order
| codeqa | def styleof expr styles default styles style dict for typ sty in styles if isinstance expr typ style update sty return style
| null | null | null | null | Question:
How do style dictionaries merge ?
Code:
def styleof(expr, styles=default_styles):
style = dict()
for (typ, sty) in styles:
if isinstance(expr, typ):
style.update(sty)
return style
|
null | null | null | What does the code get from the segment table ?
| def getPointsFromSegmentTable(segmentTable):
points = []
segmentTableKeys = segmentTable.keys()
segmentTableKeys.sort()
for segmentTableKey in segmentTableKeys:
for segment in segmentTable[segmentTableKey]:
for endpoint in segment:
points.append(endpoint.point)
return points
| null | null | null | the points
| codeqa | def get Points From Segment Table segment Table points []segment Table Keys segment Table keys segment Table Keys sort for segment Table Key in segment Table Keys for segment in segment Table[segment Table Key] for endpoint in segment points append endpoint point return points
| null | null | null | null | Question:
What does the code get from the segment table ?
Code:
def getPointsFromSegmentTable(segmentTable):
points = []
segmentTableKeys = segmentTable.keys()
segmentTableKeys.sort()
for segmentTableKey in segmentTableKeys:
for segment in segmentTable[segmentTableKey]:
for endpoint in segment:
points.... |
null | null | null | How are the admins dependencies installed ?
| def check_dependencies(**kwargs):
errors = []
if (not apps.is_installed('django.contrib.contenttypes')):
missing_app = checks.Error("'django.contrib.contenttypes' must be in INSTALLED_APPS in order to use the admin application.", id='admin.E401')
errors.append(missing_app)
try:
default_template_engi... | null | null | null | correctly
| codeqa | def check dependencies **kwargs errors []if not apps is installed 'django contrib contenttypes' missing app checks Error "'django contrib contenttypes'mustbein INSTALLED APP Sinordertousetheadminapplication " id 'admin E401 ' errors append missing app try default template engine Engine get default except Exception pass... | null | null | null | null | Question:
How are the admins dependencies installed ?
Code:
def check_dependencies(**kwargs):
errors = []
if (not apps.is_installed('django.contrib.contenttypes')):
missing_app = checks.Error("'django.contrib.contenttypes' must be in INSTALLED_APPS in order to use the admin application.", id='admin.E... |
null | null | null | What does a traditional - style method take ?
| def cr_uid_ids(method):
method._api = 'cr_uid_ids'
return method
| null | null | null | cr
| codeqa | def cr uid ids method method api 'cr uid ids'return method
| null | null | null | null | Question:
What does a traditional - style method take ?
Code:
def cr_uid_ids(method):
method._api = 'cr_uid_ids'
return method
|
null | null | null | For what purpose do full path return to the user - specific cache ?
| def user_cache_dir(appname, appauthor=None, version=None, opinion=True):
if sys.platform.startswith('win'):
if (appauthor is None):
raise AppDirsError("must specify 'appauthor' on Windows")
path = os.path.join(_get_win_folder('CSIDL_LOCAL_APPDATA'), appauthor, appname)
if opinion:
path = os.path.join(p... | null | null | null | for this application
| codeqa | def user cache dir appname appauthor None version None opinion True if sys platform startswith 'win' if appauthor is None raise App Dirs Error "mustspecify'appauthor'on Windows" path os path join get win folder 'CSIDL LOCAL APPDATA' appauthor appname if opinion path os path join path ' Cache' elif sys platform 'darwin'... | null | null | null | null | Question:
For what purpose do full path return to the user - specific cache ?
Code:
def user_cache_dir(appname, appauthor=None, version=None, opinion=True):
if sys.platform.startswith('win'):
if (appauthor is None):
raise AppDirsError("must specify 'appauthor' on Windows")
path = os.path.join(_get_win_f... |
null | null | null | What does the code prompt which option to choose from the given ?
| def prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input):
rendered_options = [render_variable(env, raw, cookiecutter_dict) for raw in options]
if no_input:
return rendered_options[0]
return read_user_choice(key, rendered_options)
| null | null | null | the user
| codeqa | def prompt choice for config cookiecutter dict env key options no input rendered options [render variable env raw cookiecutter dict for raw in options]if no input return rendered options[ 0 ]return read user choice key rendered options
| null | null | null | null | Question:
What does the code prompt which option to choose from the given ?
Code:
def prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input):
rendered_options = [render_variable(env, raw, cookiecutter_dict) for raw in options]
if no_input:
return rendered_options[0]
return read_user_choice(ke... |
null | null | null | What does the code retrieve ?
| def _get_deployment_config_file():
path = CONF.paste_deploy.config_file
if (not path):
path = _get_paste_config_path()
if (not path):
msg = (_('Unable to locate paste config file for %s.') % CONF.prog)
raise RuntimeError(msg)
return os.path.abspath(path)
| null | null | null | the deployment_config_file config item
| codeqa | def get deployment config file path CONF paste deploy config fileif not path path get paste config path if not path msg ' Unabletolocatepasteconfigfilefor%s ' % CONF prog raise Runtime Error msg return os path abspath path
| null | null | null | null | Question:
What does the code retrieve ?
Code:
def _get_deployment_config_file():
path = CONF.paste_deploy.config_file
if (not path):
path = _get_paste_config_path()
if (not path):
msg = (_('Unable to locate paste config file for %s.') % CONF.prog)
raise RuntimeError(msg)
return os.path.abspath(path... |
null | null | null | What did the code set ?
| def hset(key, field, value, host=None, port=None, db=None, password=None):
server = _connect(host, port, db, password)
return server.hset(key, field, value)
| null | null | null | the value of a hash field
| codeqa | def hset key field value host None port None db None password None server connect host port db password return server hset key field value
| null | null | null | null | Question:
What did the code set ?
Code:
def hset(key, field, value, host=None, port=None, db=None, password=None):
server = _connect(host, port, db, password)
return server.hset(key, field, value)
|
null | null | null | Where did the bug report ?
| def fix_IE_for_vary(request, response):
useragent = request.META.get('HTTP_USER_AGENT', '').upper()
if (('MSIE' not in useragent) and ('CHROMEFRAME' not in useragent)):
return response
safe_mime_types = ('text/html', 'text/plain', 'text/sgml')
if (response['Content-Type'].split(';')[0] not in safe_mime_types):
... | null | null | null | at URL
| codeqa | def fix IE for vary request response useragent request META get 'HTTP USER AGENT' '' upper if 'MSIE' not in useragent and 'CHROMEFRAME' not in useragent return responsesafe mime types 'text/html' 'text/plain' 'text/sgml' if response[' Content- Type'] split ' ' [0 ] not in safe mime types try del response[' Vary']except... | null | null | null | null | Question:
Where did the bug report ?
Code:
def fix_IE_for_vary(request, response):
useragent = request.META.get('HTTP_USER_AGENT', '').upper()
if (('MSIE' not in useragent) and ('CHROMEFRAME' not in useragent)):
return response
safe_mime_types = ('text/html', 'text/plain', 'text/sgml')
if (response['Content-T... |
null | null | null | What reported at URL ?
| def fix_IE_for_vary(request, response):
useragent = request.META.get('HTTP_USER_AGENT', '').upper()
if (('MSIE' not in useragent) and ('CHROMEFRAME' not in useragent)):
return response
safe_mime_types = ('text/html', 'text/plain', 'text/sgml')
if (response['Content-Type'].split(';')[0] not in safe_mime_types):
... | null | null | null | the bug
| codeqa | def fix IE for vary request response useragent request META get 'HTTP USER AGENT' '' upper if 'MSIE' not in useragent and 'CHROMEFRAME' not in useragent return responsesafe mime types 'text/html' 'text/plain' 'text/sgml' if response[' Content- Type'] split ' ' [0 ] not in safe mime types try del response[' Vary']except... | null | null | null | null | Question:
What reported at URL ?
Code:
def fix_IE_for_vary(request, response):
useragent = request.META.get('HTTP_USER_AGENT', '').upper()
if (('MSIE' not in useragent) and ('CHROMEFRAME' not in useragent)):
return response
safe_mime_types = ('text/html', 'text/plain', 'text/sgml')
if (response['Content-Type'... |
null | null | null | How does a cookie unset ?
| def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
clearables = []
for cookie in cookiejar:
if (cookie.name == name):
if ((domain is None) or (domain == cookie.domain)):
if ((path is None) or (path == cookie.path)):
clearables.append((cookie.domain, cookie.path, cookie.name))
for (doma... | null | null | null | by name
| codeqa | def remove cookie by name cookiejar name domain None path None clearables []for cookie in cookiejar if cookie name name if domain is None or domain cookie domain if path is None or path cookie path clearables append cookie domain cookie path cookie name for domain path name in clearables cookiejar clear domain path nam... | null | null | null | null | Question:
How does a cookie unset ?
Code:
def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
clearables = []
for cookie in cookiejar:
if (cookie.name == name):
if ((domain is None) or (domain == cookie.domain)):
if ((path is None) or (path == cookie.path)):
clearables.append((cookie... |
null | null | null | What does the code get from multiplier ?
| def getVector3ByMultiplierPrefixes(multiplier, prefixes, vector3, xmlElement):
for prefix in prefixes:
vector3 = getVector3ByMultiplierPrefix(multiplier, prefix, vector3, xmlElement)
return vector3
| null | null | null | vector3
| codeqa | def get Vector 3 By Multiplier Prefixes multiplier prefixes vector 3 xml Element for prefix in prefixes vector 3 get Vector 3 By Multiplier Prefix multiplier prefix vector 3 xml Element return vector 3
| null | null | null | null | Question:
What does the code get from multiplier ?
Code:
def getVector3ByMultiplierPrefixes(multiplier, prefixes, vector3, xmlElement):
for prefix in prefixes:
vector3 = getVector3ByMultiplierPrefix(multiplier, prefix, vector3, xmlElement)
return vector3
|
null | null | null | What do generic z - test save ?
| def _zstat_generic(value1, value2, std_diff, alternative, diff=0):
zstat = (((value1 - value2) - diff) / std_diff)
if (alternative in ['two-sided', '2-sided', '2s']):
pvalue = (stats.norm.sf(np.abs(zstat)) * 2)
elif (alternative in ['larger', 'l']):
pvalue = stats.norm.sf(zstat)
elif (alternative in ['smaller',... | null | null | null | typing
| codeqa | def zstat generic value 1 value 2 std diff alternative diff 0 zstat value 1 - value 2 - diff / std diff if alternative in ['two-sided' '2 -sided' '2 s'] pvalue stats norm sf np abs zstat * 2 elif alternative in ['larger' 'l'] pvalue stats norm sf zstat elif alternative in ['smaller' 's'] pvalue stats norm cdf zstat els... | null | null | null | null | Question:
What do generic z - test save ?
Code:
def _zstat_generic(value1, value2, std_diff, alternative, diff=0):
zstat = (((value1 - value2) - diff) / std_diff)
if (alternative in ['two-sided', '2-sided', '2s']):
pvalue = (stats.norm.sf(np.abs(zstat)) * 2)
elif (alternative in ['larger', 'l']):
pvalue = st... |
null | null | null | What saves typing ?
| def _zstat_generic(value1, value2, std_diff, alternative, diff=0):
zstat = (((value1 - value2) - diff) / std_diff)
if (alternative in ['two-sided', '2-sided', '2s']):
pvalue = (stats.norm.sf(np.abs(zstat)) * 2)
elif (alternative in ['larger', 'l']):
pvalue = stats.norm.sf(zstat)
elif (alternative in ['smaller',... | null | null | null | generic z - test
| codeqa | def zstat generic value 1 value 2 std diff alternative diff 0 zstat value 1 - value 2 - diff / std diff if alternative in ['two-sided' '2 -sided' '2 s'] pvalue stats norm sf np abs zstat * 2 elif alternative in ['larger' 'l'] pvalue stats norm sf zstat elif alternative in ['smaller' 's'] pvalue stats norm cdf zstat els... | null | null | null | null | Question:
What saves typing ?
Code:
def _zstat_generic(value1, value2, std_diff, alternative, diff=0):
zstat = (((value1 - value2) - diff) / std_diff)
if (alternative in ['two-sided', '2-sided', '2s']):
pvalue = (stats.norm.sf(np.abs(zstat)) * 2)
elif (alternative in ['larger', 'l']):
pvalue = stats.norm.sf(... |
null | null | null | What does the code return according to pep 263 ?
| def coding_spec(data):
if isinstance(data, bytes):
lines = data.decode('iso-8859-1')
else:
lines = data
if ('\n' in lines):
lst = lines.split('\n', 2)[:2]
elif ('\r' in lines):
lst = lines.split('\r', 2)[:2]
else:
lst = [lines]
for line in lst:
match = coding_re.match(line)
if (match is not None):
... | null | null | null | the encoding declaration
| codeqa | def coding spec data if isinstance data bytes lines data decode 'iso- 8859 - 1 ' else lines dataif '\n' in lines lst lines split '\n' 2 [ 2]elif '\r' in lines lst lines split '\r' 2 [ 2]else lst [lines]for line in lst match coding re match line if match is not None breakif not blank re match line return Noneelse return... | null | null | null | null | Question:
What does the code return according to pep 263 ?
Code:
def coding_spec(data):
if isinstance(data, bytes):
lines = data.decode('iso-8859-1')
else:
lines = data
if ('\n' in lines):
lst = lines.split('\n', 2)[:2]
elif ('\r' in lines):
lst = lines.split('\r', 2)[:2]
else:
lst = [lines]
for lin... |
null | null | null | How does the code return the encoding declaration ?
| def coding_spec(data):
if isinstance(data, bytes):
lines = data.decode('iso-8859-1')
else:
lines = data
if ('\n' in lines):
lst = lines.split('\n', 2)[:2]
elif ('\r' in lines):
lst = lines.split('\r', 2)[:2]
else:
lst = [lines]
for line in lst:
match = coding_re.match(line)
if (match is not None):
... | null | null | null | according to pep 263
| codeqa | def coding spec data if isinstance data bytes lines data decode 'iso- 8859 - 1 ' else lines dataif '\n' in lines lst lines split '\n' 2 [ 2]elif '\r' in lines lst lines split '\r' 2 [ 2]else lst [lines]for line in lst match coding re match line if match is not None breakif not blank re match line return Noneelse return... | null | null | null | null | Question:
How does the code return the encoding declaration ?
Code:
def coding_spec(data):
if isinstance(data, bytes):
lines = data.decode('iso-8859-1')
else:
lines = data
if ('\n' in lines):
lst = lines.split('\n', 2)[:2]
elif ('\r' in lines):
lst = lines.split('\r', 2)[:2]
else:
lst = [lines]
for ... |
null | null | null | What did the code set ?
| def libvlc_media_set_meta(p_md, e_meta, psz_value):
f = (_Cfunctions.get('libvlc_media_set_meta', None) or _Cfunction('libvlc_media_set_meta', ((1,), (1,), (1,)), None, None, Media, Meta, ctypes.c_char_p))
return f(p_md, e_meta, psz_value)
| null | null | null | the meta of the media
| codeqa | def libvlc media set meta p md e meta psz value f Cfunctions get 'libvlc media set meta' None or Cfunction 'libvlc media set meta' 1 1 1 None None Media Meta ctypes c char p return f p md e meta psz value
| null | null | null | null | Question:
What did the code set ?
Code:
def libvlc_media_set_meta(p_md, e_meta, psz_value):
f = (_Cfunctions.get('libvlc_media_set_meta', None) or _Cfunction('libvlc_media_set_meta', ((1,), (1,), (1,)), None, None, Media, Meta, ctypes.c_char_p))
return f(p_md, e_meta, psz_value)
|
null | null | null | What does the code instantiate ?
| def variable(value, dtype=None, name=None):
if (dtype is None):
dtype = floatx()
if hasattr(value, 'tocoo'):
_assert_sparse_module()
variable = th_sparse_module.as_sparse_variable(value)
else:
value = np.asarray(value, dtype=dtype)
variable = theano.shared(value=value, name=name, strict=False)
variable._k... | null | null | null | a variable
| codeqa | def variable value dtype None name None if dtype is None dtype floatx if hasattr value 'tocoo' assert sparse module variable th sparse module as sparse variable value else value np asarray value dtype dtype variable theano shared value value name name strict False variable keras shape value shapevariable uses learning ... | null | null | null | null | Question:
What does the code instantiate ?
Code:
def variable(value, dtype=None, name=None):
if (dtype is None):
dtype = floatx()
if hasattr(value, 'tocoo'):
_assert_sparse_module()
variable = th_sparse_module.as_sparse_variable(value)
else:
value = np.asarray(value, dtype=dtype)
variable = theano.shar... |
null | null | null | In which direction is the user logged ?
| def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorator(function)
return actual_decorator
| null | null | null | in
| codeqa | def login required function None redirect field name REDIRECT FIELD NAME login url None actual decorator user passes test lambda u u is authenticated login url login url redirect field name redirect field name if function return actual decorator function return actual decorator
| null | null | null | null | Question:
In which direction is the user logged ?
Code:
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decor... |
null | null | null | What does decorator for views check ?
| def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorator(function)
return actual_decorator
| null | null | null | that the user is logged in
| codeqa | def login required function None redirect field name REDIRECT FIELD NAME login url None actual decorator user passes test lambda u u is authenticated login url login url redirect field name redirect field name if function return actual decorator function return actual decorator
| null | null | null | null | Question:
What does decorator for views check ?
Code:
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorat... |
null | null | null | What checks that the user is logged in ?
| def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorator(function)
return actual_decorator
| null | null | null | decorator for views
| codeqa | def login required function None redirect field name REDIRECT FIELD NAME login url None actual decorator user passes test lambda u u is authenticated login url login url redirect field name redirect field name if function return actual decorator function return actual decorator
| null | null | null | null | Question:
What checks that the user is logged in ?
Code:
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated()), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_deco... |
null | null | null | What does the code return ?
| def timedelta_to_days(delta):
return (delta.days + (delta.seconds / (3600 * 24)))
| null | null | null | the time delta
| codeqa | def timedelta to days delta return delta days + delta seconds / 3600 * 24
| null | null | null | null | Question:
What does the code return ?
Code:
def timedelta_to_days(delta):
return (delta.days + (delta.seconds / (3600 * 24)))
|
null | null | null | What does the code get ?
| def getNewRepository():
return CoolRepository()
| null | null | null | the repository constructor
| codeqa | def get New Repository return Cool Repository
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewRepository():
return CoolRepository()
|
null | null | null | What does the code create ?
| def _mk_fileclient():
if ('cp.fileclient' not in __context__):
__context__['cp.fileclient'] = salt.fileclient.get_file_client(__opts__)
| null | null | null | a file client
| codeqa | def mk fileclient if 'cp fileclient' not in context context ['cp fileclient'] salt fileclient get file client opts
| null | null | null | null | Question:
What does the code create ?
Code:
def _mk_fileclient():
if ('cp.fileclient' not in __context__):
__context__['cp.fileclient'] = salt.fileclient.get_file_client(__opts__)
|
null | null | null | What does the code write ?
| def write_git_changelog():
new_changelog = 'ChangeLog'
git_dir = _get_git_directory()
if (not os.getenv('SKIP_WRITE_GIT_CHANGELOG')):
if git_dir:
git_log_cmd = ('git --git-dir=%s log' % git_dir)
changelog = _run_shell_command(git_log_cmd)
mailmap = _parse_git_mailmap(git_dir)
with open(new_changelog,... | null | null | null | a changelog based on the git changelog
| codeqa | def write git changelog new changelog ' Change Log'git dir get git directory if not os getenv 'SKIP WRITE GIT CHANGELOG' if git dir git log cmd 'git--git-dir %slog' % git dir changelog run shell command git log cmd mailmap parse git mailmap git dir with open new changelog 'w' as changelog file changelog file write cano... | null | null | null | null | Question:
What does the code write ?
Code:
def write_git_changelog():
new_changelog = 'ChangeLog'
git_dir = _get_git_directory()
if (not os.getenv('SKIP_WRITE_GIT_CHANGELOG')):
if git_dir:
git_log_cmd = ('git --git-dir=%s log' % git_dir)
changelog = _run_shell_command(git_log_cmd)
mailmap = _parse_g... |
null | null | null | What does the code display ?
| def getDisplayedDialogFromConstructor(repository):
try:
getReadRepository(repository)
return RepositoryDialog(repository, Tkinter.Tk())
except:
print 'this should never happen, getDisplayedDialogFromConstructor in settings could not open'
print repository
traceback.print_exc(file=sys.stdout)
retu... | null | null | null | the repository dialog
| codeqa | def get Displayed Dialog From Constructor repository try get Read Repository repository return Repository Dialog repository Tkinter Tk except print 'thisshouldneverhappen get Displayed Dialog From Constructorinsettingscouldnotopen'print repositorytraceback print exc file sys stdout return None
| null | null | null | null | Question:
What does the code display ?
Code:
def getDisplayedDialogFromConstructor(repository):
try:
getReadRepository(repository)
return RepositoryDialog(repository, Tkinter.Tk())
except:
print 'this should never happen, getDisplayedDialogFromConstructor in settings could not open'
print reposit... |
null | null | null | What does the code get from the rest interface ?
| def get(key, profile=None):
data = _get_values(profile)
return salt.utils.traverse_dict_and_list(data, key, None)
| null | null | null | a value
| codeqa | def get key profile None data get values profile return salt utils traverse dict and list data key None
| null | null | null | null | Question:
What does the code get from the rest interface ?
Code:
def get(key, profile=None):
data = _get_values(profile)
return salt.utils.traverse_dict_and_list(data, key, None)
|
null | null | null | What does the code convert into a numerical index ?
| def column_index_from_string(str_col):
try:
return _COL_STRING_CACHE[str_col.upper()]
except KeyError:
raise ValueError('{0} is not a valid column name'.format(str_col))
| null | null | null | a column name
| codeqa | def column index from string str col try return COL STRING CACHE[str col upper ]except Key Error raise Value Error '{ 0 }isnotavalidcolumnname' format str col
| null | null | null | null | Question:
What does the code convert into a numerical index ?
Code:
def column_index_from_string(str_col):
try:
return _COL_STRING_CACHE[str_col.upper()]
except KeyError:
raise ValueError('{0} is not a valid column name'.format(str_col))
|
null | null | null | What does the code load ?
| @sopel.module.nickname_commands(u'load')
@sopel.module.priority(u'low')
@sopel.module.thread(False)
def f_load(bot, trigger):
if (not trigger.admin):
return
name = trigger.group(2)
path = u''
if (not name):
return bot.reply(u'Load what?')
if (name in sys.modules):
return bot.reply(u'Module already loaded,... | null | null | null | a module
| codeqa | @sopel module nickname commands u'load' @sopel module priority u'low' @sopel module thread False def f load bot trigger if not trigger admin returnname trigger group 2 path u''if not name return bot reply u' Loadwhat?' if name in sys modules return bot reply u' Modulealreadyloaded usereload' mods sopel loader enumerate... | null | null | null | null | Question:
What does the code load ?
Code:
@sopel.module.nickname_commands(u'load')
@sopel.module.priority(u'low')
@sopel.module.thread(False)
def f_load(bot, trigger):
if (not trigger.admin):
return
name = trigger.group(2)
path = u''
if (not name):
return bot.reply(u'Load what?')
if (name in sys.modules):... |
null | null | null | Who have the test case still ?
| def mc2cum(mc):
return mnc2cum(mc2mnc(mc))
| null | null | null | i
| codeqa | def mc 2 cum mc return mnc 2 cum mc 2 mnc mc
| null | null | null | null | Question:
Who have the test case still ?
Code:
def mc2cum(mc):
return mnc2cum(mc2mnc(mc))
|
null | null | null | What is deriving generators ?
| @public
def sfield(exprs, *symbols, **options):
single = False
if (not is_sequence(exprs)):
(exprs, single) = ([exprs], True)
exprs = list(map(sympify, exprs))
opt = build_options(symbols, options)
numdens = []
for expr in exprs:
numdens.extend(expr.as_numer_denom())
(reps, opt) = _parallel_dict_from_expr(nu... | null | null | null | a field
| codeqa | @publicdef sfield exprs *symbols **options single Falseif not is sequence exprs exprs single [exprs] True exprs list map sympify exprs opt build options symbols options numdens []for expr in exprs numdens extend expr as numer denom reps opt parallel dict from expr numdens opt if opt domain is None coeffs sum [list rep ... | null | null | null | null | Question:
What is deriving generators ?
Code:
@public
def sfield(exprs, *symbols, **options):
single = False
if (not is_sequence(exprs)):
(exprs, single) = ([exprs], True)
exprs = list(map(sympify, exprs))
opt = build_options(symbols, options)
numdens = []
for expr in exprs:
numdens.extend(expr.as_numer_d... |
null | null | null | How did explorations rat ?
| def get_top_rated_exploration_summary_dicts(language_codes, limit):
filtered_exp_summaries = [exp_summary for exp_summary in exp_services.get_top_rated_exploration_summaries(limit).values() if ((exp_summary.language_code in language_codes) and (sum(exp_summary.ratings.values()) > 0))]
sorted_exp_summaries = sorted(fi... | null | null | null | top
| codeqa | def get top rated exploration summary dicts language codes limit filtered exp summaries [exp summary for exp summary in exp services get top rated exploration summaries limit values if exp summary language code in language codes and sum exp summary ratings values > 0 ]sorted exp summaries sorted filtered exp summaries ... | null | null | null | null | Question:
How did explorations rat ?
Code:
def get_top_rated_exploration_summary_dicts(language_codes, limit):
filtered_exp_summaries = [exp_summary for exp_summary in exp_services.get_top_rated_exploration_summaries(limit).values() if ((exp_summary.language_code in language_codes) and (sum(exp_summary.ratings.val... |
null | null | null | When does the recursion limit change ?
| @contextlib.contextmanager
def change_recursion_limit(limit):
old_limit = sys.getrecursionlimit()
if (old_limit < limit):
sys.setrecursionlimit(limit)
(yield)
sys.setrecursionlimit(old_limit)
| null | null | null | temporarily
| codeqa | @contextlib contextmanagerdef change recursion limit limit old limit sys getrecursionlimit if old limit < limit sys setrecursionlimit limit yield sys setrecursionlimit old limit
| null | null | null | null | Question:
When does the recursion limit change ?
Code:
@contextlib.contextmanager
def change_recursion_limit(limit):
old_limit = sys.getrecursionlimit()
if (old_limit < limit):
sys.setrecursionlimit(limit)
(yield)
sys.setrecursionlimit(old_limit)
|
null | null | null | How does a binary digest return for the pbkdf2 hash algorithm of data ?
| def pbkdf2(data, salt, iterations=1000, keylen=32, hashfunc=None):
assert (type(data) == bytes)
assert (type(salt) == bytes)
assert (type(iterations) in six.integer_types)
assert (type(keylen) in six.integer_types)
return _pbkdf2(data, salt, iterations, keylen, (hashfunc or hashlib.sha256))
| null | null | null | with the given salt
| codeqa | def pbkdf 2 data salt iterations 1000 keylen 32 hashfunc None assert type data bytes assert type salt bytes assert type iterations in six integer types assert type keylen in six integer types return pbkdf 2 data salt iterations keylen hashfunc or hashlib sha 256
| null | null | null | null | Question:
How does a binary digest return for the pbkdf2 hash algorithm of data ?
Code:
def pbkdf2(data, salt, iterations=1000, keylen=32, hashfunc=None):
assert (type(data) == bytes)
assert (type(salt) == bytes)
assert (type(iterations) in six.integer_types)
assert (type(keylen) in six.integer_types)
return _... |
null | null | null | What do we need ?
| def setup_module():
if (PROTOCOL_VERSION >= 4):
use_singledc(start=False)
ccm_cluster = get_cluster()
ccm_cluster.stop()
config_options = {'tombstone_failure_threshold': 2000, 'tombstone_warn_threshold': 1000}
ccm_cluster.set_configuration_options(config_options)
ccm_cluster.start(wait_for_binary_proto=Tru... | null | null | null | some custom setup for this module
| codeqa | def setup module if PROTOCOL VERSION > 4 use singledc start False ccm cluster get cluster ccm cluster stop config options {'tombstone failure threshold' 2000 'tombstone warn threshold' 1000 }ccm cluster set configuration options config options ccm cluster start wait for binary proto True wait other notice True setup ke... | null | null | null | null | Question:
What do we need ?
Code:
def setup_module():
if (PROTOCOL_VERSION >= 4):
use_singledc(start=False)
ccm_cluster = get_cluster()
ccm_cluster.stop()
config_options = {'tombstone_failure_threshold': 2000, 'tombstone_warn_threshold': 1000}
ccm_cluster.set_configuration_options(config_options)
ccm_c... |
null | null | null | How did parameter split ?
| def _parse_params(term):
keys = ['key', 'type', 'section', 'file', 're', 'default']
params = {}
for k in keys:
params[k] = ''
thiskey = 'key'
for (idp, phrase) in enumerate(term.split()):
for k in keys:
if (('%s=' % k) in phrase):
thiskey = k
if ((idp == 0) or (not params[thiskey])):
params[thiskey... | null | null | null | safely
| codeqa | def parse params term keys ['key' 'type' 'section' 'file' 're' 'default']params {}for k in keys params[k] ''thiskey 'key'for idp phrase in enumerate term split for k in keys if '%s ' % k in phrase thiskey kif idp 0 or not params[thiskey] params[thiskey] phraseelse params[thiskey] + '' + phrase rparams [params[x] for x ... | null | null | null | null | Question:
How did parameter split ?
Code:
def _parse_params(term):
keys = ['key', 'type', 'section', 'file', 're', 'default']
params = {}
for k in keys:
params[k] = ''
thiskey = 'key'
for (idp, phrase) in enumerate(term.split()):
for k in keys:
if (('%s=' % k) in phrase):
thiskey = k
if ((idp == 0... |
null | null | null | What means its data probably ?
| def isdata(object):
return (not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object)))
| null | null | null | a type
| codeqa | def isdata object return not inspect ismodule object or inspect isclass object or inspect isroutine object or inspect isframe object or inspect istraceback object or inspect iscode object
| null | null | null | null | Question:
What means its data probably ?
Code:
def isdata(object):
return (not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object)))
|
null | null | null | What does a type mean probably ?
| def isdata(object):
return (not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object)))
| null | null | null | its data
| codeqa | def isdata object return not inspect ismodule object or inspect isclass object or inspect isroutine object or inspect isframe object or inspect istraceback object or inspect iscode object
| null | null | null | null | Question:
What does a type mean probably ?
Code:
def isdata(object):
return (not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object)))
|
null | null | null | What does the code receive ?
| def ms_attacks(exploit):
return {'1': 'dll_hijacking', '2': 'unc_embed', '3': 'exploit/windows/fileformat/ms15_100_mcl_exe', '4': 'exploit/windows/fileformat/ms14_017_rtf', '5': 'exploit/windows/fileformat/ms11_006_createsizeddibsection', '6': 'exploit/windows/fileformat/ms10_087_rtf_pfragments_bof', '7': 'exploit/win... | null | null | null | the input given by the user from create_payload
| codeqa | def ms attacks exploit return {' 1 ' 'dll hijacking' '2 ' 'unc embed' '3 ' 'exploit/windows/fileformat/ms 15 100 mcl exe' '4 ' 'exploit/windows/fileformat/ms 14 017 rtf' '5 ' 'exploit/windows/fileformat/ms 11 006 createsizeddibsection' '6 ' 'exploit/windows/fileformat/ms 10 087 rtf pfragments bof' '7 ' 'exploit/windows... | null | null | null | null | Question:
What does the code receive ?
Code:
def ms_attacks(exploit):
return {'1': 'dll_hijacking', '2': 'unc_embed', '3': 'exploit/windows/fileformat/ms15_100_mcl_exe', '4': 'exploit/windows/fileformat/ms14_017_rtf', '5': 'exploit/windows/fileformat/ms11_006_createsizeddibsection', '6': 'exploit/windows/fileforma... |
null | null | null | What does the code get by name / alias ?
| def get_loader_cls(loader):
return get_cls_by_name(loader, LOADER_ALIASES)
| null | null | null | loader class
| codeqa | def get loader cls loader return get cls by name loader LOADER ALIASES
| null | null | null | null | Question:
What does the code get by name / alias ?
Code:
def get_loader_cls(loader):
return get_cls_by_name(loader, LOADER_ALIASES)
|
null | null | null | How does the code get loader class ?
| def get_loader_cls(loader):
return get_cls_by_name(loader, LOADER_ALIASES)
| null | null | null | by name / alias
| codeqa | def get loader cls loader return get cls by name loader LOADER ALIASES
| null | null | null | null | Question:
How does the code get loader class ?
Code:
def get_loader_cls(loader):
return get_cls_by_name(loader, LOADER_ALIASES)
|
null | null | null | What can a decorator be used ?
| def deprecated(func):
def newFunc(*args, **kwargs):
warnings.warn(('Call to deprecated function %s.' % func.__name__), category=DeprecationWarning)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
| null | null | null | to mark functions as deprecated
| codeqa | def deprecated func def new Func *args **kwargs warnings warn ' Calltodeprecatedfunction%s ' % func name category Deprecation Warning return func *args **kwargs new Func name func name new Func doc func doc new Func dict update func dict return new Func
| null | null | null | null | Question:
What can a decorator be used ?
Code:
def deprecated(func):
def newFunc(*args, **kwargs):
warnings.warn(('Call to deprecated function %s.' % func.__name__), category=DeprecationWarning)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__... |
null | null | null | What can be used to mark functions as deprecated ?
| def deprecated(func):
def newFunc(*args, **kwargs):
warnings.warn(('Call to deprecated function %s.' % func.__name__), category=DeprecationWarning)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
| null | null | null | a decorator
| codeqa | def deprecated func def new Func *args **kwargs warnings warn ' Calltodeprecatedfunction%s ' % func name category Deprecation Warning return func *args **kwargs new Func name func name new Func doc func doc new Func dict update func dict return new Func
| null | null | null | null | Question:
What can be used to mark functions as deprecated ?
Code:
def deprecated(func):
def newFunc(*args, **kwargs):
warnings.warn(('Call to deprecated function %s.' % func.__name__), category=DeprecationWarning)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc... |
null | null | null | How did elements fill ?
| def get_sparse_matrix(M, N, frac=0.1):
data = (np.zeros((M, N)) * 0.0)
for i in range(int(((M * N) * frac))):
x = np.random.randint(0, (M - 1))
y = np.random.randint(0, (N - 1))
data[(x, y)] = np.random.rand()
return data
| null | null | null | randomly
| codeqa | def get sparse matrix M N frac 0 1 data np zeros M N * 0 0 for i in range int M * N * frac x np random randint 0 M - 1 y np random randint 0 N - 1 data[ x y ] np random rand return data
| null | null | null | null | Question:
How did elements fill ?
Code:
def get_sparse_matrix(M, N, frac=0.1):
data = (np.zeros((M, N)) * 0.0)
for i in range(int(((M * N) * frac))):
x = np.random.randint(0, (M - 1))
y = np.random.randint(0, (N - 1))
data[(x, y)] = np.random.rand()
return data
|
null | null | null | What does the code provide ?
| def __virtual__():
return ('ethtool' if ('ethtool.show_driver' in __salt__) else False)
| null | null | null | state
| codeqa | def virtual return 'ethtool' if 'ethtool show driver' in salt else False
| null | null | null | null | Question:
What does the code provide ?
Code:
def __virtual__():
return ('ethtool' if ('ethtool.show_driver' in __salt__) else False)
|
null | null | null | What does the code return as tuple ?
| def _parse_localename(localename):
code = normalize(localename)
if ('@' in code):
(code, modifier) = code.split('@', 1)
if ((modifier == 'euro') and ('.' not in code)):
return (code, 'iso-8859-15')
if ('.' in code):
return tuple(code.split('.')[:2])
elif (code == 'C'):
return (None, None)
raise ValueErr... | null | null | null | the result
| codeqa | def parse localename localename code normalize localename if '@' in code code modifier code split '@' 1 if modifier 'euro' and ' ' not in code return code 'iso- 8859 - 15 ' if ' ' in code return tuple code split ' ' [ 2] elif code 'C' return None None raise Value Error 'unknownlocale %s' % localename
| null | null | null | null | Question:
What does the code return as tuple ?
Code:
def _parse_localename(localename):
code = normalize(localename)
if ('@' in code):
(code, modifier) = code.split('@', 1)
if ((modifier == 'euro') and ('.' not in code)):
return (code, 'iso-8859-15')
if ('.' in code):
return tuple(code.split('.')[:2])
... |
null | null | null | What does the code setup ?
| def setup_platform(hass, config, add_devices, discovery_info=None):
if (not int(hub.config.get(CONF_SMARTCAM, 1))):
return False
directory_path = hass.config.config_dir
if (not os.access(directory_path, os.R_OK)):
_LOGGER.error('file path %s is not readable', directory_path)
return False
hub.update_smart... | null | null | null | the camera
| codeqa | def setup platform hass config add devices discovery info None if not int hub config get CONF SMARTCAM 1 return Falsedirectory path hass config config dirif not os access directory path os R OK LOGGER error 'filepath%sisnotreadable' directory path return Falsehub update smartcam smartcams []smartcams extend [ Verisure ... | null | null | null | null | Question:
What does the code setup ?
Code:
def setup_platform(hass, config, add_devices, discovery_info=None):
if (not int(hub.config.get(CONF_SMARTCAM, 1))):
return False
directory_path = hass.config.config_dir
if (not os.access(directory_path, os.R_OK)):
_LOGGER.error('file path %s is not readable', d... |
null | null | null | How do path tokens join ?
| def join_path(a, *p):
path = a
for b in p:
if (len(b) == 0):
continue
if b.startswith('/'):
path += b[1:]
elif ((path == '') or path.endswith('/')):
path += b
else:
path += ('/' + b)
return path
| null | null | null | together
| codeqa | def join path a *p path afor b in p if len b 0 continueif b startswith '/' path + b[ 1 ]elif path '' or path endswith '/' path + belse path + '/' + b return path
| null | null | null | null | Question:
How do path tokens join ?
Code:
def join_path(a, *p):
path = a
for b in p:
if (len(b) == 0):
continue
if b.startswith('/'):
path += b[1:]
elif ((path == '') or path.endswith('/')):
path += b
else:
path += ('/' + b)
return path
|
null | null | null | What does the code validate ?
| def __validate__(config):
VALID_ITEMS = ['type', 'bytes_sent', 'bytes_recv', 'packets_sent', 'packets_recv', 'errin', 'errout', 'dropin', 'dropout']
if (not isinstance(config, dict)):
return (False, 'Configuration for load beacon must be a dictionary.')
else:
for item in config:
if (not isinstance(conf... | null | null | null | the beacon configuration
| codeqa | def validate config VALID ITEMS ['type' 'bytes sent' 'bytes recv' 'packets sent' 'packets recv' 'errin' 'errout' 'dropin' 'dropout']if not isinstance config dict return False ' Configurationforloadbeaconmustbeadictionary ' else for item in config if not isinstance config[item] dict return False ' Configurationforloadbe... | null | null | null | null | Question:
What does the code validate ?
Code:
def __validate__(config):
VALID_ITEMS = ['type', 'bytes_sent', 'bytes_recv', 'packets_sent', 'packets_recv', 'errin', 'errout', 'dropin', 'dropout']
if (not isinstance(config, dict)):
return (False, 'Configuration for load beacon must be a dictionary.')
else... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.