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 append the header / data if filename exists ?
def append(filename, data, header=None, checksum=False, verify=True, **kwargs): (name, closed, noexist_or_empty) = _stat_filename_or_fileobj(filename) if noexist_or_empty: writeto(filename, data, header, checksum=checksum, **kwargs) else: hdu = _makehdu(data, header) if isinstance(hdu, PrimaryHDU): hdu = ImageHDU(data, header) if (verify or (not closed)): f = fitsopen(filename, mode='append') try: f.append(hdu) hdu._output_checksum = checksum finally: f._close(closed=closed) else: f = _File(filename, mode='append') try: hdu._output_checksum = checksum hdu._writeto(f) finally: f._close()
null
null
null
to fits file
codeqa
def append filename data header None checksum False verify True **kwargs name closed noexist or empty stat filename or fileobj filename if noexist or empty writeto filename data header checksum checksum **kwargs else hdu makehdu data header if isinstance hdu Primary HDU hdu Image HDU data header if verify or not closed f fitsopen filename mode 'append' try f append hdu hdu output checksum checksumfinally f close closed closed else f File filename mode 'append' try hdu output checksum checksumhdu writeto f finally f close
null
null
null
null
Question: What does the code append the header / data if filename exists ? Code: def append(filename, data, header=None, checksum=False, verify=True, **kwargs): (name, closed, noexist_or_empty) = _stat_filename_or_fileobj(filename) if noexist_or_empty: writeto(filename, data, header, checksum=checksum, **kwargs) else: hdu = _makehdu(data, header) if isinstance(hdu, PrimaryHDU): hdu = ImageHDU(data, header) if (verify or (not closed)): f = fitsopen(filename, mode='append') try: f.append(hdu) hdu._output_checksum = checksum finally: f._close(closed=closed) else: f = _File(filename, mode='append') try: hdu._output_checksum = checksum hdu._writeto(f) finally: f._close()
null
null
null
What did the code require ?
def register(linter): linter.register_checker(MisdesignChecker(linter))
null
null
null
method to auto register this checker
codeqa
def register linter linter register checker Misdesign Checker linter
null
null
null
null
Question: What did the code require ? Code: def register(linter): linter.register_checker(MisdesignChecker(linter))
null
null
null
What sets the current session as fresh ?
def confirm_login(): session['_fresh'] = True session['_id'] = _create_identifier() user_login_confirmed.send(current_app._get_current_object())
null
null
null
this
codeqa
def confirm login session[' fresh'] Truesession[' id'] create identifier user login confirmed send current app get current object
null
null
null
null
Question: What sets the current session as fresh ? Code: def confirm_login(): session['_fresh'] = True session['_id'] = _create_identifier() user_login_confirmed.send(current_app._get_current_object())
null
null
null
What does this set as fresh ?
def confirm_login(): session['_fresh'] = True session['_id'] = _create_identifier() user_login_confirmed.send(current_app._get_current_object())
null
null
null
the current session
codeqa
def confirm login session[' fresh'] Truesession[' id'] create identifier user login confirmed send current app get current object
null
null
null
null
Question: What does this set as fresh ? Code: def confirm_login(): session['_fresh'] = True session['_id'] = _create_identifier() user_login_confirmed.send(current_app._get_current_object())
null
null
null
What does the code get ?
def get_package_data(): package_data = {} package_data['jupyterhub'] = ['alembic.ini', 'alembic/*', 'alembic/versions/*'] return package_data
null
null
null
package data
codeqa
def get package data package data {}package data['jupyterhub'] ['alembic ini' 'alembic/*' 'alembic/versions/*']return package data
null
null
null
null
Question: What does the code get ? Code: def get_package_data(): package_data = {} package_data['jupyterhub'] = ['alembic.ini', 'alembic/*', 'alembic/versions/*'] return package_data
null
null
null
What does the code get ?
def get_minion_data(minion, opts): grains = None pillar = None if opts.get('minion_data_cache', False): cache = salt.cache.Cache(opts) if (minion is None): for id_ in cache.list('minions'): data = cache.fetch('minions/{0}'.format(id_), 'data') if (data is None): continue else: data = cache.fetch('minions/{0}'.format(minion), 'data') if (data is not None): grains = data['grains'] pillar = data['pillar'] return ((minion if minion else None), grains, pillar)
null
null
null
the grains / pillar
codeqa
def get minion data minion opts grains Nonepillar Noneif opts get 'minion data cache' False cache salt cache Cache opts if minion is None for id in cache list 'minions' data cache fetch 'minions/{ 0 }' format id 'data' if data is None continueelse data cache fetch 'minions/{ 0 }' format minion 'data' if data is not None grains data['grains']pillar data['pillar']return minion if minion else None grains pillar
null
null
null
null
Question: What does the code get ? Code: def get_minion_data(minion, opts): grains = None pillar = None if opts.get('minion_data_cache', False): cache = salt.cache.Cache(opts) if (minion is None): for id_ in cache.list('minions'): data = cache.fetch('minions/{0}'.format(id_), 'data') if (data is None): continue else: data = cache.fetch('minions/{0}'.format(minion), 'data') if (data is not None): grains = data['grains'] pillar = data['pillar'] return ((minion if minion else None), grains, pillar)
null
null
null
What does the code execute from a working directory ?
def run_script(script_path, cwd='.'): run_thru_shell = sys.platform.startswith('win') if script_path.endswith('.py'): script_command = [sys.executable, script_path] else: script_command = [script_path] utils.make_executable(script_path) try: proc = subprocess.Popen(script_command, shell=run_thru_shell, cwd=cwd) exit_status = proc.wait() if (exit_status != EXIT_SUCCESS): raise FailedHookException('Hook script failed (exit status: {})'.format(exit_status)) except OSError as os_error: if (os_error.errno == errno.ENOEXEC): raise FailedHookException('Hook script failed, might be an empty file or missing a shebang') raise FailedHookException('Hook script failed (error: {})'.format(os_error))
null
null
null
a script
codeqa
def run script script path cwd ' ' run thru shell sys platform startswith 'win' if script path endswith ' py' script command [sys executable script path]else script command [script path]utils make executable script path try proc subprocess Popen script command shell run thru shell cwd cwd exit status proc wait if exit status EXIT SUCCESS raise Failed Hook Exception ' Hookscriptfailed exitstatus {} ' format exit status except OS Error as os error if os error errno errno ENOEXEC raise Failed Hook Exception ' Hookscriptfailed mightbeanemptyfileormissingashebang' raise Failed Hook Exception ' Hookscriptfailed error {} ' format os error
null
null
null
null
Question: What does the code execute from a working directory ? Code: def run_script(script_path, cwd='.'): run_thru_shell = sys.platform.startswith('win') if script_path.endswith('.py'): script_command = [sys.executable, script_path] else: script_command = [script_path] utils.make_executable(script_path) try: proc = subprocess.Popen(script_command, shell=run_thru_shell, cwd=cwd) exit_status = proc.wait() if (exit_status != EXIT_SUCCESS): raise FailedHookException('Hook script failed (exit status: {})'.format(exit_status)) except OSError as os_error: if (os_error.errno == errno.ENOEXEC): raise FailedHookException('Hook script failed, might be an empty file or missing a shebang') raise FailedHookException('Hook script failed (error: {})'.format(os_error))
null
null
null
What d accepts i d values only ?
@pytest.mark.django_db def test_plugin_image_id_field(): image = File.objects.create() image_id = ImageIDField() assert (image_id.clean('1') == 1) with pytest.raises(ValidationError): image_id.clean('something malicious')
null
null
null
imageidfield
codeqa
@pytest mark django dbdef test plugin image id field image File objects create image id Image ID Field assert image id clean '1 ' 1 with pytest raises Validation Error image id clean 'somethingmalicious'
null
null
null
null
Question: What d accepts i d values only ? Code: @pytest.mark.django_db def test_plugin_image_id_field(): image = File.objects.create() image_id = ImageIDField() assert (image_id.clean('1') == 1) with pytest.raises(ValidationError): image_id.clean('something malicious')
null
null
null
What does the code get ?
def user_info(name, **client_args): matching_users = (user for user in list_users(**client_args) if (user.get('user') == name)) try: return next(matching_users) except StopIteration: pass
null
null
null
information about given user
codeqa
def user info name **client args matching users user for user in list users **client args if user get 'user' name try return next matching users except Stop Iteration pass
null
null
null
null
Question: What does the code get ? Code: def user_info(name, **client_args): matching_users = (user for user in list_users(**client_args) if (user.get('user') == name)) try: return next(matching_users) except StopIteration: pass
null
null
null
Ca we support editing ?
def check_module_metadata_editability(module): allowed = allowed_metadata_by_category(module.location.category) if ('*' in allowed): return 0 allowed = (allowed + ['xml_attributes', 'display_name']) err_cnt = 0 illegal_keys = (set(own_metadata(module).keys()) - set(allowed)) if (len(illegal_keys) > 0): err_cnt = (err_cnt + 1) print ': found non-editable metadata on {url}. These metadata keys are not supported = {keys}'.format(url=unicode(module.location), keys=illegal_keys) return err_cnt
null
null
null
No
codeqa
def check module metadata editability module allowed allowed metadata by category module location category if '*' in allowed return 0allowed allowed + ['xml attributes' 'display name'] err cnt 0illegal keys set own metadata module keys - set allowed if len illegal keys > 0 err cnt err cnt + 1 print ' foundnon-editablemetadataon{url} Thesemetadatakeysarenotsupported {keys}' format url unicode module location keys illegal keys return err cnt
null
null
null
null
Question: Ca we support editing ? Code: def check_module_metadata_editability(module): allowed = allowed_metadata_by_category(module.location.category) if ('*' in allowed): return 0 allowed = (allowed + ['xml_attributes', 'display_name']) err_cnt = 0 illegal_keys = (set(own_metadata(module).keys()) - set(allowed)) if (len(illegal_keys) > 0): err_cnt = (err_cnt + 1) print ': found non-editable metadata on {url}. These metadata keys are not supported = {keys}'.format(url=unicode(module.location), keys=illegal_keys) return err_cnt
null
null
null
What will function write to the given stream writing ?
def get_unicode_writer(stream=sys.stdout, encoding=None, errors=u'replace'): encoding = (encoding or get_preferred_output_encoding()) if ((sys.version_info < (3,)) or (not hasattr(stream, u'buffer'))): return (lambda s: stream.write(s.encode(encoding, errors))) else: return (lambda s: stream.buffer.write(s.encode(encoding, errors)))
null
null
null
unicode string
codeqa
def get unicode writer stream sys stdout encoding None errors u'replace' encoding encoding or get preferred output encoding if sys version info < 3 or not hasattr stream u'buffer' return lambda s stream write s encode encoding errors else return lambda s stream buffer write s encode encoding errors
null
null
null
null
Question: What will function write to the given stream writing ? Code: def get_unicode_writer(stream=sys.stdout, encoding=None, errors=u'replace'): encoding = (encoding or get_preferred_output_encoding()) if ((sys.version_info < (3,)) or (not hasattr(stream, u'buffer'))): return (lambda s: stream.write(s.encode(encoding, errors))) else: return (lambda s: stream.buffer.write(s.encode(encoding, errors)))
null
null
null
What does the code send to the managers ?
def mail_managers(subject, message, fail_silently=False, connection=None): if (not settings.MANAGERS): return EmailMessage((u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)), message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], connection=connection).send(fail_silently=fail_silently)
null
null
null
a message
codeqa
def mail managers subject message fail silently False connection None if not settings MANAGERS return Email Message u'%s%s' % settings EMAIL SUBJECT PREFIX subject message settings SERVER EMAIL [a[ 1 ] for a in settings MANAGERS] connection connection send fail silently fail silently
null
null
null
null
Question: What does the code send to the managers ? Code: def mail_managers(subject, message, fail_silently=False, connection=None): if (not settings.MANAGERS): return EmailMessage((u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)), message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], connection=connection).send(fail_silently=fail_silently)
null
null
null
What does the code get ?
def getResolver(): global theResolver if (theResolver is None): try: theResolver = createResolver() except ValueError: theResolver = createResolver(servers=[('127.0.0.1', 53)]) return theResolver
null
null
null
a resolver instance
codeqa
def get Resolver global the Resolverif the Resolver is None try the Resolver create Resolver except Value Error the Resolver create Resolver servers [ '127 0 0 1' 53 ] return the Resolver
null
null
null
null
Question: What does the code get ? Code: def getResolver(): global theResolver if (theResolver is None): try: theResolver = createResolver() except ValueError: theResolver = createResolver(servers=[('127.0.0.1', 53)]) return theResolver
null
null
null
What does the code return ?
def create_vdi(session, sr_ref, instance, name_label, disk_type, virtual_size, read_only=False): otherconf = {'nova_disk_type': disk_type} if instance: otherconf['nova_instance_uuid'] = instance['uuid'] vdi_ref = session.call_xenapi('VDI.create', {'name_label': name_label, 'name_description': disk_type, 'SR': sr_ref, 'virtual_size': str(virtual_size), 'type': 'User', 'sharable': False, 'read_only': read_only, 'xenstore_data': {}, 'other_config': otherconf, 'sm_config': {}, 'tags': []}) LOG.debug(_('Created VDI %(vdi_ref)s (%(name_label)s, %(virtual_size)s, %(read_only)s) on %(sr_ref)s.'), locals()) return vdi_ref
null
null
null
its reference
codeqa
def create vdi session sr ref instance name label disk type virtual size read only False otherconf {'nova disk type' disk type}if instance otherconf['nova instance uuid'] instance['uuid']vdi ref session call xenapi 'VDI create' {'name label' name label 'name description' disk type 'SR' sr ref 'virtual size' str virtual size 'type' ' User' 'sharable' False 'read only' read only 'xenstore data' {} 'other config' otherconf 'sm config' {} 'tags' []} LOG debug ' Created VDI% vdi ref s % name label s % virtual size s % read only s on% sr ref s ' locals return vdi ref
null
null
null
null
Question: What does the code return ? Code: def create_vdi(session, sr_ref, instance, name_label, disk_type, virtual_size, read_only=False): otherconf = {'nova_disk_type': disk_type} if instance: otherconf['nova_instance_uuid'] = instance['uuid'] vdi_ref = session.call_xenapi('VDI.create', {'name_label': name_label, 'name_description': disk_type, 'SR': sr_ref, 'virtual_size': str(virtual_size), 'type': 'User', 'sharable': False, 'read_only': read_only, 'xenstore_data': {}, 'other_config': otherconf, 'sm_config': {}, 'tags': []}) LOG.debug(_('Created VDI %(vdi_ref)s (%(name_label)s, %(virtual_size)s, %(read_only)s) on %(sr_ref)s.'), locals()) return vdi_ref
null
null
null
What did the code set ?
def set_mode(path, mode): func_name = '{0}.set_mode'.format(__virtualname__) if (__opts__.get('fun', '') == func_name): log.info('The function {0} should not be used on Windows systems; see function docs for details. The value returned is always None. Use set_perms instead.'.format(func_name)) return get_mode(path)
null
null
null
the mode of a file this just calls get_mode
codeqa
def set mode path mode func name '{ 0 } set mode' format virtualname if opts get 'fun' '' func name log info ' Thefunction{ 0 }shouldnotbeusedon Windowssystems seefunctiondocsfordetails Thevaluereturnedisalways None Useset permsinstead ' format func name return get mode path
null
null
null
null
Question: What did the code set ? Code: def set_mode(path, mode): func_name = '{0}.set_mode'.format(__virtualname__) if (__opts__.get('fun', '') == func_name): log.info('The function {0} should not be used on Windows systems; see function docs for details. The value returned is always None. Use set_perms instead.'.format(func_name)) return get_mode(path)
null
null
null
What do a context manager capture ?
@contextmanager def capture(command, *args, **kwargs): (out, sys.stdout) = (sys.stdout, StringIO()) command(*args, **kwargs) sys.stdout.seek(0) (yield sys.stdout.read()) sys.stdout = out
null
null
null
std out
codeqa
@contextmanagerdef capture command *args **kwargs out sys stdout sys stdout String IO command *args **kwargs sys stdout seek 0 yield sys stdout read sys stdout out
null
null
null
null
Question: What do a context manager capture ? Code: @contextmanager def capture(command, *args, **kwargs): (out, sys.stdout) = (sys.stdout, StringIO()) command(*args, **kwargs) sys.stdout.seek(0) (yield sys.stdout.read()) sys.stdout = out
null
null
null
What captures std out ?
@contextmanager def capture(command, *args, **kwargs): (out, sys.stdout) = (sys.stdout, StringIO()) command(*args, **kwargs) sys.stdout.seek(0) (yield sys.stdout.read()) sys.stdout = out
null
null
null
a context manager
codeqa
@contextmanagerdef capture command *args **kwargs out sys stdout sys stdout String IO command *args **kwargs sys stdout seek 0 yield sys stdout read sys stdout out
null
null
null
null
Question: What captures std out ? Code: @contextmanager def capture(command, *args, **kwargs): (out, sys.stdout) = (sys.stdout, StringIO()) command(*args, **kwargs) sys.stdout.seek(0) (yield sys.stdout.read()) sys.stdout = out
null
null
null
How did paragraph generate ?
def paragraph(): return ' '.join((sentence() for i in range(random.randint(1, 4))))
null
null
null
randomly
codeqa
def paragraph return '' join sentence for i in range random randint 1 4
null
null
null
null
Question: How did paragraph generate ? Code: def paragraph(): return ' '.join((sentence() for i in range(random.randint(1, 4))))
null
null
null
What does the code get with some testing data ?
def create_order_source(prices_include_tax, line_data, tax_rates): lines = [Line.from_text(x) for x in line_data] shop = get_shop(prices_include_tax, currency=u'USD') tax_classes = create_assigned_tax_classes(tax_rates) products = create_products(shop, lines, tax_classes) services = create_services(shop, lines, tax_classes) source = OrderSource(shop) fill_order_source(source, lines, products, services) return source
null
null
null
order source
codeqa
def create order source prices include tax line data tax rates lines [ Line from text x for x in line data]shop get shop prices include tax currency u'USD' tax classes create assigned tax classes tax rates products create products shop lines tax classes services create services shop lines tax classes source Order Source shop fill order source source lines products services return source
null
null
null
null
Question: What does the code get with some testing data ? Code: def create_order_source(prices_include_tax, line_data, tax_rates): lines = [Line.from_text(x) for x in line_data] shop = get_shop(prices_include_tax, currency=u'USD') tax_classes = create_assigned_tax_classes(tax_rates) products = create_products(shop, lines, tax_classes) services = create_services(shop, lines, tax_classes) source = OrderSource(shop) fill_order_source(source, lines, products, services) return source
null
null
null
How does the code get order source ?
def create_order_source(prices_include_tax, line_data, tax_rates): lines = [Line.from_text(x) for x in line_data] shop = get_shop(prices_include_tax, currency=u'USD') tax_classes = create_assigned_tax_classes(tax_rates) products = create_products(shop, lines, tax_classes) services = create_services(shop, lines, tax_classes) source = OrderSource(shop) fill_order_source(source, lines, products, services) return source
null
null
null
with some testing data
codeqa
def create order source prices include tax line data tax rates lines [ Line from text x for x in line data]shop get shop prices include tax currency u'USD' tax classes create assigned tax classes tax rates products create products shop lines tax classes services create services shop lines tax classes source Order Source shop fill order source source lines products services return source
null
null
null
null
Question: How does the code get order source ? Code: def create_order_source(prices_include_tax, line_data, tax_rates): lines = [Line.from_text(x) for x in line_data] shop = get_shop(prices_include_tax, currency=u'USD') tax_classes = create_assigned_tax_classes(tax_rates) products = create_products(shop, lines, tax_classes) services = create_services(shop, lines, tax_classes) source = OrderSource(shop) fill_order_source(source, lines, products, services) return source
null
null
null
How is replay_dump called ?
def test_replay_dump_template_name(monkeypatch, mocker, user_config_data, user_config_file): monkeypatch.chdir('tests/fake-repo-tmpl') mock_replay_dump = mocker.patch('cookiecutter.main.dump') mocker.patch('cookiecutter.main.generate_files') cookiecutter('.', no_input=True, replay=False, config_file=user_config_file) mock_replay_dump.assert_called_once_with(user_config_data['replay_dir'], 'fake-repo-tmpl', mocker.ANY)
null
null
null
with a valid template_name
codeqa
def test replay dump template name monkeypatch mocker user config data user config file monkeypatch chdir 'tests/fake-repo-tmpl' mock replay dump mocker patch 'cookiecutter main dump' mocker patch 'cookiecutter main generate files' cookiecutter ' ' no input True replay False config file user config file mock replay dump assert called once with user config data['replay dir'] 'fake-repo-tmpl' mocker ANY
null
null
null
null
Question: How is replay_dump called ? Code: def test_replay_dump_template_name(monkeypatch, mocker, user_config_data, user_config_file): monkeypatch.chdir('tests/fake-repo-tmpl') mock_replay_dump = mocker.patch('cookiecutter.main.dump') mocker.patch('cookiecutter.main.generate_files') cookiecutter('.', no_input=True, replay=False, config_file=user_config_file) mock_replay_dump.assert_called_once_with(user_config_data['replay_dir'], 'fake-repo-tmpl', mocker.ANY)
null
null
null
What is playing the current clip ?
def speedx(clip, factor=None, final_duration=None): if final_duration: factor = ((1.0 * clip.duration) / final_duration) newclip = clip.fl_time((lambda t: (factor * t)), apply_to=['mask', 'audio']) if (clip.duration is not None): newclip = newclip.set_duration(((1.0 * clip.duration) / factor)) return newclip
null
null
null
a clip
codeqa
def speedx clip factor None final duration None if final duration factor 1 0 * clip duration / final duration newclip clip fl time lambda t factor * t apply to ['mask' 'audio'] if clip duration is not None newclip newclip set duration 1 0 * clip duration / factor return newclip
null
null
null
null
Question: What is playing the current clip ? Code: def speedx(clip, factor=None, final_duration=None): if final_duration: factor = ((1.0 * clip.duration) / final_duration) newclip = clip.fl_time((lambda t: (factor * t)), apply_to=['mask', 'audio']) if (clip.duration is not None): newclip = newclip.set_duration(((1.0 * clip.duration) / factor)) return newclip
null
null
null
What does a clip play ?
def speedx(clip, factor=None, final_duration=None): if final_duration: factor = ((1.0 * clip.duration) / final_duration) newclip = clip.fl_time((lambda t: (factor * t)), apply_to=['mask', 'audio']) if (clip.duration is not None): newclip = newclip.set_duration(((1.0 * clip.duration) / factor)) return newclip
null
null
null
the current clip
codeqa
def speedx clip factor None final duration None if final duration factor 1 0 * clip duration / final duration newclip clip fl time lambda t factor * t apply to ['mask' 'audio'] if clip duration is not None newclip newclip set duration 1 0 * clip duration / factor return newclip
null
null
null
null
Question: What does a clip play ? Code: def speedx(clip, factor=None, final_duration=None): if final_duration: factor = ((1.0 * clip.duration) / final_duration) newclip = clip.fl_time((lambda t: (factor * t)), apply_to=['mask', 'audio']) if (clip.duration is not None): newclip = newclip.set_duration(((1.0 * clip.duration) / factor)) return newclip
null
null
null
What does the code find ?
def get_tau_cov(mu, tau=None, cov=None): if (tau is None): if (cov is None): cov = np.eye(len(mu)) tau = np.eye(len(mu)) else: tau = tt.nlinalg.matrix_inverse(cov) elif (cov is not None): raise ValueError("Can't pass both tau and sd") else: cov = tt.nlinalg.matrix_inverse(tau) return (tau, cov)
null
null
null
precision and standard deviation
codeqa
def get tau cov mu tau None cov None if tau is None if cov is None cov np eye len mu tau np eye len mu else tau tt nlinalg matrix inverse cov elif cov is not None raise Value Error " Can'tpassbothtauandsd" else cov tt nlinalg matrix inverse tau return tau cov
null
null
null
null
Question: What does the code find ? Code: def get_tau_cov(mu, tau=None, cov=None): if (tau is None): if (cov is None): cov = np.eye(len(mu)) tau = np.eye(len(mu)) else: tau = tt.nlinalg.matrix_inverse(cov) elif (cov is not None): raise ValueError("Can't pass both tau and sd") else: cov = tt.nlinalg.matrix_inverse(tau) return (tau, cov)
null
null
null
Where does a temporary test file live ?
def create_tmp_test(code, prefix='tmp', delete=True, **kwargs): py = tempfile.NamedTemporaryFile(prefix=prefix, delete=delete) code = code.format(**kwargs) if IS_PY3: code = code.encode('UTF-8') py.write(code) py.flush() st = os.stat(py.name) os.chmod(py.name, (st.st_mode | stat.S_IEXEC)) return py
null
null
null
on disk
codeqa
def create tmp test code prefix 'tmp' delete True **kwargs py tempfile Named Temporary File prefix prefix delete delete code code format **kwargs if IS PY 3 code code encode 'UTF- 8 ' py write code py flush st os stat py name os chmod py name st st mode stat S IEXEC return py
null
null
null
null
Question: Where does a temporary test file live ? Code: def create_tmp_test(code, prefix='tmp', delete=True, **kwargs): py = tempfile.NamedTemporaryFile(prefix=prefix, delete=delete) code = code.format(**kwargs) if IS_PY3: code = code.encode('UTF-8') py.write(code) py.flush() st = os.stat(py.name) os.chmod(py.name, (st.st_mode | stat.S_IEXEC)) return py
null
null
null
What does the code create ?
def create_tmp_test(code, prefix='tmp', delete=True, **kwargs): py = tempfile.NamedTemporaryFile(prefix=prefix, delete=delete) code = code.format(**kwargs) if IS_PY3: code = code.encode('UTF-8') py.write(code) py.flush() st = os.stat(py.name) os.chmod(py.name, (st.st_mode | stat.S_IEXEC)) return py
null
null
null
a temporary test file that lives on disk
codeqa
def create tmp test code prefix 'tmp' delete True **kwargs py tempfile Named Temporary File prefix prefix delete delete code code format **kwargs if IS PY 3 code code encode 'UTF- 8 ' py write code py flush st os stat py name os chmod py name st st mode stat S IEXEC return py
null
null
null
null
Question: What does the code create ? Code: def create_tmp_test(code, prefix='tmp', delete=True, **kwargs): py = tempfile.NamedTemporaryFile(prefix=prefix, delete=delete) code = code.format(**kwargs) if IS_PY3: code = code.encode('UTF-8') py.write(code) py.flush() st = os.stat(py.name) os.chmod(py.name, (st.st_mode | stat.S_IEXEC)) return py
null
null
null
What lives on disk ?
def create_tmp_test(code, prefix='tmp', delete=True, **kwargs): py = tempfile.NamedTemporaryFile(prefix=prefix, delete=delete) code = code.format(**kwargs) if IS_PY3: code = code.encode('UTF-8') py.write(code) py.flush() st = os.stat(py.name) os.chmod(py.name, (st.st_mode | stat.S_IEXEC)) return py
null
null
null
a temporary test file
codeqa
def create tmp test code prefix 'tmp' delete True **kwargs py tempfile Named Temporary File prefix prefix delete delete code code format **kwargs if IS PY 3 code code encode 'UTF- 8 ' py write code py flush st os stat py name os chmod py name st st mode stat S IEXEC return py
null
null
null
null
Question: What lives on disk ? Code: def create_tmp_test(code, prefix='tmp', delete=True, **kwargs): py = tempfile.NamedTemporaryFile(prefix=prefix, delete=delete) code = code.format(**kwargs) if IS_PY3: code = code.encode('UTF-8') py.write(code) py.flush() st = os.stat(py.name) os.chmod(py.name, (st.st_mode | stat.S_IEXEC)) return py
null
null
null
What does the code add to the given input ?
def addNoise(input, noise=0.1, doForeground=True, doBackground=True): if (doForeground and doBackground): return numpy.abs((input - (numpy.random.random(input.shape) < noise))) else: if doForeground: return numpy.logical_and(input, (numpy.random.random(input.shape) > noise)) if doBackground: return numpy.logical_or(input, (numpy.random.random(input.shape) < noise)) return input
null
null
null
noise
codeqa
def add Noise input noise 0 1 do Foreground True do Background True if do Foreground and do Background return numpy abs input - numpy random random input shape < noise else if do Foreground return numpy logical and input numpy random random input shape > noise if do Background return numpy logical or input numpy random random input shape < noise return input
null
null
null
null
Question: What does the code add to the given input ? Code: def addNoise(input, noise=0.1, doForeground=True, doBackground=True): if (doForeground and doBackground): return numpy.abs((input - (numpy.random.random(input.shape) < noise))) else: if doForeground: return numpy.logical_and(input, (numpy.random.random(input.shape) > noise)) if doBackground: return numpy.logical_or(input, (numpy.random.random(input.shape) < noise)) return input
null
null
null
What does the code extract from an entity key ?
def get_root_key_from_entity_key(key): tokens = key.split(KIND_SEPARATOR) return (tokens[0] + KIND_SEPARATOR)
null
null
null
the root key
codeqa
def get root key from entity key key tokens key split KIND SEPARATOR return tokens[ 0 ] + KIND SEPARATOR
null
null
null
null
Question: What does the code extract from an entity key ? Code: def get_root_key_from_entity_key(key): tokens = key.split(KIND_SEPARATOR) return (tokens[0] + KIND_SEPARATOR)
null
null
null
What tells which distribution are compatible with which version of python by adding a data - python - require to the anchor links ?
def test_finder_only_installs_data_require(data): finder = PackageFinder([], [data.index_url('datarequire')], session=PipSession()) links = finder.find_all_candidates('fakepackage') expected = ['1.0.0', '9.9.9'] if (sys.version_info < (2, 7)): expected.append('2.6.0') elif ((2, 7) < sys.version_info < (3,)): expected.append('2.7.0') elif (sys.version_info > (3, 3)): expected.append('3.3.0') assert (set([str(v.version) for v in links]) == set(expected))
null
null
null
a simple - repository
codeqa
def test finder only installs data require data finder Package Finder [] [data index url 'datarequire' ] session Pip Session links finder find all candidates 'fakepackage' expected [' 1 0 0' '9 9 9']if sys version info < 2 7 expected append '2 6 0' elif 2 7 < sys version info < 3 expected append '2 7 0' elif sys version info > 3 3 expected append '3 3 0' assert set [str v version for v in links] set expected
null
null
null
null
Question: What tells which distribution are compatible with which version of python by adding a data - python - require to the anchor links ? Code: def test_finder_only_installs_data_require(data): finder = PackageFinder([], [data.index_url('datarequire')], session=PipSession()) links = finder.find_all_candidates('fakepackage') expected = ['1.0.0', '9.9.9'] if (sys.version_info < (2, 7)): expected.append('2.6.0') elif ((2, 7) < sys.version_info < (3,)): expected.append('2.7.0') elif (sys.version_info > (3, 3)): expected.append('3.3.0') assert (set([str(v.version) for v in links]) == set(expected))
null
null
null
What do data write ?
def writeToFD(fd, data): try: return os.write(fd, data) except (OSError, IOError) as io: if (io.errno in (errno.EAGAIN, errno.EINTR)): return 0 return CONNECTION_LOST
null
null
null
to file descriptor
codeqa
def write To FD fd data try return os write fd data except OS Error IO Error as io if io errno in errno EAGAIN errno EINTR return 0return CONNECTION LOST
null
null
null
null
Question: What do data write ? Code: def writeToFD(fd, data): try: return os.write(fd, data) except (OSError, IOError) as io: if (io.errno in (errno.EAGAIN, errno.EINTR)): return 0 return CONNECTION_LOST
null
null
null
How does the code sort them ?
def sort(seq): build_heap(seq) heap_size = (len(seq) - 1) for x in range(heap_size, 0, (-1)): (seq[0], seq[x]) = (seq[x], seq[0]) heap_size = (heap_size - 1) max_heapify(seq, 0, heap_size) return seq
null
null
null
in ascending order
codeqa
def sort seq build heap seq heap size len seq - 1 for x in range heap size 0 -1 seq[ 0 ] seq[x] seq[x] seq[ 0 ] heap size heap size - 1 max heapify seq 0 heap size return seq
null
null
null
null
Question: How does the code sort them ? Code: def sort(seq): build_heap(seq) heap_size = (len(seq) - 1) for x in range(heap_size, 0, (-1)): (seq[0], seq[x]) = (seq[x], seq[0]) heap_size = (heap_size - 1) max_heapify(seq, 0, heap_size) return seq
null
null
null
What does the code take ?
def sort(seq): build_heap(seq) heap_size = (len(seq) - 1) for x in range(heap_size, 0, (-1)): (seq[0], seq[x]) = (seq[x], seq[0]) heap_size = (heap_size - 1) max_heapify(seq, 0, heap_size) return seq
null
null
null
a list of integers
codeqa
def sort seq build heap seq heap size len seq - 1 for x in range heap size 0 -1 seq[ 0 ] seq[x] seq[x] seq[ 0 ] heap size heap size - 1 max heapify seq 0 heap size return seq
null
null
null
null
Question: What does the code take ? Code: def sort(seq): build_heap(seq) heap_size = (len(seq) - 1) for x in range(heap_size, 0, (-1)): (seq[0], seq[x]) = (seq[x], seq[0]) heap_size = (heap_size - 1) max_heapify(seq, 0, heap_size) return seq
null
null
null
What does the code write ?
def write_libraries(dir, libraries): files = [open(os.path.join(dir, k), 'w') for (k, _) in libraries] for (f, (_, v)) in zip(files, libraries): v.write_markdown_to_file(f) for (f, (_, v)) in zip(files, libraries): v.write_other_members(f) f.close()
null
null
null
a list of libraries to disk
codeqa
def write libraries dir libraries files [open os path join dir k 'w' for k in libraries]for f v in zip files libraries v write markdown to file f for f v in zip files libraries v write other members f f close
null
null
null
null
Question: What does the code write ? Code: def write_libraries(dir, libraries): files = [open(os.path.join(dir, k), 'w') for (k, _) in libraries] for (f, (_, v)) in zip(files, libraries): v.write_markdown_to_file(f) for (f, (_, v)) in zip(files, libraries): v.write_other_members(f) f.close()
null
null
null
What does user try ?
def test_summary_without_shipping_method(request_cart_with_item, client, monkeypatch): monkeypatch.setattr('saleor.checkout.core.Checkout.email', True) response = client.get(reverse('checkout:summary')) assert (response.status_code == 302) assert (get_redirect_location(response) == reverse('checkout:shipping-method'))
null
null
null
to get summary step without saved shipping method - if is redirected to shipping method step
codeqa
def test summary without shipping method request cart with item client monkeypatch monkeypatch setattr 'saleor checkout core Checkout email' True response client get reverse 'checkout summary' assert response status code 302 assert get redirect location response reverse 'checkout shipping-method'
null
null
null
null
Question: What does user try ? Code: def test_summary_without_shipping_method(request_cart_with_item, client, monkeypatch): monkeypatch.setattr('saleor.checkout.core.Checkout.email', True) response = client.get(reverse('checkout:summary')) assert (response.status_code == 302) assert (get_redirect_location(response) == reverse('checkout:shipping-method'))
null
null
null
When do @overload raise ?
def _overload_dummy(*args, **kwds): raise NotImplementedError(u'You should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed.')
null
null
null
when called
codeqa
def overload dummy *args **kwds raise Not Implemented Error u' Youshouldnotcallanoverloadedfunction Aseriesof@overload-decoratedfunctionsoutsideastubmoduleshouldalwaysbefollowedbyanimplementationthatisnot@overload-ed '
null
null
null
null
Question: When do @overload raise ? Code: def _overload_dummy(*args, **kwds): raise NotImplementedError(u'You should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed.')
null
null
null
How d matrix reconstruct ?
def idz_reconid(B, idx, proj): B = np.asfortranarray(B) if (proj.size > 0): return _id.idz_reconid(B, idx, proj) else: return B[:, np.argsort(idx)]
null
null
null
from complex i d
codeqa
def idz reconid B idx proj B np asfortranarray B if proj size > 0 return id idz reconid B idx proj else return B[ np argsort idx ]
null
null
null
null
Question: How d matrix reconstruct ? Code: def idz_reconid(B, idx, proj): B = np.asfortranarray(B) if (proj.size > 0): return _id.idz_reconid(B, idx, proj) else: return B[:, np.argsort(idx)]
null
null
null
What matches the supplied certificate ?
def assert_fingerprint(cert, fingerprint): fingerprint = fingerprint.replace(':', '').lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if (not hashfunc): raise SSLError('Fingerprint of invalid length: {0}'.format(fingerprint)) fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if (cert_digest != fingerprint_bytes): raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'.format(fingerprint, hexlify(cert_digest)))
null
null
null
given fingerprint
codeqa
def assert fingerprint cert fingerprint fingerprint fingerprint replace ' ' '' lower digest length len fingerprint hashfunc HASHFUNC MAP get digest length if not hashfunc raise SSL Error ' Fingerprintofinvalidlength {0 }' format fingerprint fingerprint bytes unhexlify fingerprint encode cert digest hashfunc cert digest if cert digest fingerprint bytes raise SSL Error ' Fingerprintsdidnotmatch Expected"{ 0 }" got"{ 1 }" ' format fingerprint hexlify cert digest
null
null
null
null
Question: What matches the supplied certificate ? Code: def assert_fingerprint(cert, fingerprint): fingerprint = fingerprint.replace(':', '').lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if (not hashfunc): raise SSLError('Fingerprint of invalid length: {0}'.format(fingerprint)) fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if (cert_digest != fingerprint_bytes): raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'.format(fingerprint, hexlify(cert_digest)))
null
null
null
What does which column hold ?
def _intercept_idx(design_info): from patsy.desc import INTERCEPT from numpy import array return array([(INTERCEPT == i) for i in design_info.terms])
null
null
null
the intercept
codeqa
def intercept idx design info from patsy desc import INTERCEP Tfrom numpy import arrayreturn array [ INTERCEPT i for i in design info terms]
null
null
null
null
Question: What does which column hold ? Code: def _intercept_idx(design_info): from patsy.desc import INTERCEPT from numpy import array return array([(INTERCEPT == i) for i in design_info.terms])
null
null
null
What holds the intercept ?
def _intercept_idx(design_info): from patsy.desc import INTERCEPT from numpy import array return array([(INTERCEPT == i) for i in design_info.terms])
null
null
null
which column
codeqa
def intercept idx design info from patsy desc import INTERCEP Tfrom numpy import arrayreturn array [ INTERCEPT i for i in design info terms]
null
null
null
null
Question: What holds the intercept ? Code: def _intercept_idx(design_info): from patsy.desc import INTERCEPT from numpy import array return array([(INTERCEPT == i) for i in design_info.terms])
null
null
null
What does the code get ?
def getClosestPointOnSegment(segmentBegin, segmentEnd, point): segmentDifference = (segmentEnd - segmentBegin) if (abs(segmentDifference) <= 0.0): return segmentBegin pointMinusSegmentBegin = (point - segmentBegin) beginPlaneDot = getDotProduct(pointMinusSegmentBegin, segmentDifference) differencePlaneDot = getDotProduct(segmentDifference, segmentDifference) intercept = (beginPlaneDot / differencePlaneDot) intercept = max(intercept, 0.0) intercept = min(intercept, 1.0) return (segmentBegin + (segmentDifference * intercept))
null
null
null
the closest point on the segment
codeqa
def get Closest Point On Segment segment Begin segment End point segment Difference segment End - segment Begin if abs segment Difference < 0 0 return segment Beginpoint Minus Segment Begin point - segment Begin begin Plane Dot get Dot Product point Minus Segment Begin segment Difference difference Plane Dot get Dot Product segment Difference segment Difference intercept begin Plane Dot / difference Plane Dot intercept max intercept 0 0 intercept min intercept 1 0 return segment Begin + segment Difference * intercept
null
null
null
null
Question: What does the code get ? Code: def getClosestPointOnSegment(segmentBegin, segmentEnd, point): segmentDifference = (segmentEnd - segmentBegin) if (abs(segmentDifference) <= 0.0): return segmentBegin pointMinusSegmentBegin = (point - segmentBegin) beginPlaneDot = getDotProduct(pointMinusSegmentBegin, segmentDifference) differencePlaneDot = getDotProduct(segmentDifference, segmentDifference) intercept = (beginPlaneDot / differencePlaneDot) intercept = max(intercept, 0.0) intercept = min(intercept, 1.0) return (segmentBegin + (segmentDifference * intercept))
null
null
null
What does the code provide ?
def _section_analytics(course, access): section_data = {'section_key': 'instructor_analytics', 'section_display_name': _('Analytics'), 'access': access, 'course_id': unicode(course.id)} return section_data
null
null
null
data for the corresponding dashboard section
codeqa
def section analytics course access section data {'section key' 'instructor analytics' 'section display name' ' Analytics' 'access' access 'course id' unicode course id }return section data
null
null
null
null
Question: What does the code provide ? Code: def _section_analytics(course, access): section_data = {'section_key': 'instructor_analytics', 'section_display_name': _('Analytics'), 'access': access, 'course_id': unicode(course.id)} return section_data
null
null
null
What does the code verify ?
def verify_plaintext(request, client_secret=None, resource_owner_secret=None): signature = sign_plaintext(client_secret, resource_owner_secret) return safe_string_equals(signature, request.signature)
null
null
null
a plaintext signature
codeqa
def verify plaintext request client secret None resource owner secret None signature sign plaintext client secret resource owner secret return safe string equals signature request signature
null
null
null
null
Question: What does the code verify ? Code: def verify_plaintext(request, client_secret=None, resource_owner_secret=None): signature = sign_plaintext(client_secret, resource_owner_secret) return safe_string_equals(signature, request.signature)
null
null
null
What does the code rotate a given number of degrees clockwise ?
def rotate(image_data, degrees, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None): rpc = rotate_async(image_data, degrees, output_encoding=output_encoding, quality=quality, correct_orientation=correct_orientation, rpc=rpc, transparent_substitution_rgb=transparent_substitution_rgb) return rpc.get_result()
null
null
null
a given image
codeqa
def rotate image data degrees output encoding PNG quality None correct orientation UNCHANGED ORIENTATION rpc None transparent substitution rgb None rpc rotate async image data degrees output encoding output encoding quality quality correct orientation correct orientation rpc rpc transparent substitution rgb transparent substitution rgb return rpc get result
null
null
null
null
Question: What does the code rotate a given number of degrees clockwise ? Code: def rotate(image_data, degrees, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None): rpc = rotate_async(image_data, degrees, output_encoding=output_encoding, quality=quality, correct_orientation=correct_orientation, rpc=rpc, transparent_substitution_rgb=transparent_substitution_rgb) return rpc.get_result()
null
null
null
What does the code rotate a given image ?
def rotate(image_data, degrees, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None): rpc = rotate_async(image_data, degrees, output_encoding=output_encoding, quality=quality, correct_orientation=correct_orientation, rpc=rpc, transparent_substitution_rgb=transparent_substitution_rgb) return rpc.get_result()
null
null
null
a given number of degrees clockwise
codeqa
def rotate image data degrees output encoding PNG quality None correct orientation UNCHANGED ORIENTATION rpc None transparent substitution rgb None rpc rotate async image data degrees output encoding output encoding quality quality correct orientation correct orientation rpc rpc transparent substitution rgb transparent substitution rgb return rpc get result
null
null
null
null
Question: What does the code rotate a given image ? Code: def rotate(image_data, degrees, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None): rpc = rotate_async(image_data, degrees, output_encoding=output_encoding, quality=quality, correct_orientation=correct_orientation, rpc=rpc, transparent_substitution_rgb=transparent_substitution_rgb) return rpc.get_result()
null
null
null
What does the code retrieve ?
def _GetBlobMetadata(blob_key): (size, content_type, open_key) = _GetGoogleStorageFileMetadata(blob_key) if (size is None): (size, content_type, open_key) = _GetBlobstoreMetadata(blob_key) return (size, content_type, open_key)
null
null
null
the metadata about a blob from the blob_key
codeqa
def Get Blob Metadata blob key size content type open key Get Google Storage File Metadata blob key if size is None size content type open key Get Blobstore Metadata blob key return size content type open key
null
null
null
null
Question: What does the code retrieve ? Code: def _GetBlobMetadata(blob_key): (size, content_type, open_key) = _GetGoogleStorageFileMetadata(blob_key) if (size is None): (size, content_type, open_key) = _GetBlobstoreMetadata(blob_key) return (size, content_type, open_key)
null
null
null
What will read the first line from the next file ?
def nextfile(): if (not _state): raise RuntimeError('no active input()') return _state.nextfile()
null
null
null
the next iteration
codeqa
def nextfile if not state raise Runtime Error 'noactiveinput 'return state nextfile
null
null
null
null
Question: What will read the first line from the next file ? Code: def nextfile(): if (not _state): raise RuntimeError('no active input()') return _state.nextfile()
null
null
null
For what purpose do the current file close ?
def nextfile(): if (not _state): raise RuntimeError('no active input()') return _state.nextfile()
null
null
null
so that the next iteration will read the first line from the next file
codeqa
def nextfile if not state raise Runtime Error 'noactiveinput 'return state nextfile
null
null
null
null
Question: For what purpose do the current file close ? Code: def nextfile(): if (not _state): raise RuntimeError('no active input()') return _state.nextfile()
null
null
null
What will the next iteration read ?
def nextfile(): if (not _state): raise RuntimeError('no active input()') return _state.nextfile()
null
null
null
the first line from the next file
codeqa
def nextfile if not state raise Runtime Error 'noactiveinput 'return state nextfile
null
null
null
null
Question: What will the next iteration read ? Code: def nextfile(): if (not _state): raise RuntimeError('no active input()') return _state.nextfile()
null
null
null
How will lines not read from the file not count ?
def nextfile(): if (not _state): raise RuntimeError('no active input()') return _state.nextfile()
null
null
null
towards the cumulative line count
codeqa
def nextfile if not state raise Runtime Error 'noactiveinput 'return state nextfile
null
null
null
null
Question: How will lines not read from the file not count ? Code: def nextfile(): if (not _state): raise RuntimeError('no active input()') return _state.nextfile()
null
null
null
When do old modules use ec2_connect method ?
def get_ec2_creds(module): (region, ec2_url, boto_params) = get_aws_connection_info(module) return (ec2_url, boto_params['aws_access_key_id'], boto_params['aws_secret_access_key'], region)
null
null
null
yet
codeqa
def get ec 2 creds module region ec 2 url boto params get aws connection info module return ec 2 url boto params['aws access key id'] boto params['aws secret access key'] region
null
null
null
null
Question: When do old modules use ec2_connect method ? Code: def get_ec2_creds(module): (region, ec2_url, boto_params) = get_aws_connection_info(module) return (ec2_url, boto_params['aws_access_key_id'], boto_params['aws_secret_access_key'], region)
null
null
null
What do old modules use yet ?
def get_ec2_creds(module): (region, ec2_url, boto_params) = get_aws_connection_info(module) return (ec2_url, boto_params['aws_access_key_id'], boto_params['aws_secret_access_key'], region)
null
null
null
ec2_connect method
codeqa
def get ec 2 creds module region ec 2 url boto params get aws connection info module return ec 2 url boto params['aws access key id'] boto params['aws secret access key'] region
null
null
null
null
Question: What do old modules use yet ? Code: def get_ec2_creds(module): (region, ec2_url, boto_params) = get_aws_connection_info(module) return (ec2_url, boto_params['aws_access_key_id'], boto_params['aws_secret_access_key'], region)
null
null
null
What use ec2_connect method yet ?
def get_ec2_creds(module): (region, ec2_url, boto_params) = get_aws_connection_info(module) return (ec2_url, boto_params['aws_access_key_id'], boto_params['aws_secret_access_key'], region)
null
null
null
old modules
codeqa
def get ec 2 creds module region ec 2 url boto params get aws connection info module return ec 2 url boto params['aws access key id'] boto params['aws secret access key'] region
null
null
null
null
Question: What use ec2_connect method yet ? Code: def get_ec2_creds(module): (region, ec2_url, boto_params) = get_aws_connection_info(module) return (ec2_url, boto_params['aws_access_key_id'], boto_params['aws_secret_access_key'], region)
null
null
null
What does the code instantiate ?
def _make_dipoles(times, poss, oris, sol, gof): amplitude = (sol * 1000000000.0) oris = np.array(oris) dipoles = [] for i_dip in range(poss.shape[0]): i_pos = poss[i_dip][np.newaxis, :].repeat(len(times), axis=0) i_ori = oris[i_dip][np.newaxis, :].repeat(len(times), axis=0) dipoles.append(Dipole(times, i_pos, amplitude[i_dip], i_ori, gof)) return dipoles
null
null
null
a list of dipoles
codeqa
def make dipoles times poss oris sol gof amplitude sol * 1000000000 0 oris np array oris dipoles []for i dip in range poss shape[ 0 ] i pos poss[i dip][np newaxis ] repeat len times axis 0 i ori oris[i dip][np newaxis ] repeat len times axis 0 dipoles append Dipole times i pos amplitude[i dip] i ori gof return dipoles
null
null
null
null
Question: What does the code instantiate ? Code: def _make_dipoles(times, poss, oris, sol, gof): amplitude = (sol * 1000000000.0) oris = np.array(oris) dipoles = [] for i_dip in range(poss.shape[0]): i_pos = poss[i_dip][np.newaxis, :].repeat(len(times), axis=0) i_ori = oris[i_dip][np.newaxis, :].repeat(len(times), axis=0) dipoles.append(Dipole(times, i_pos, amplitude[i_dip], i_ori, gof)) return dipoles
null
null
null
What does the code get from class ?
def _check_subject(class_subject, input_subject, raise_error=True): if (input_subject is not None): if (not isinstance(input_subject, string_types)): raise ValueError('subject input must be a string') else: return input_subject elif (class_subject is not None): if (not isinstance(class_subject, string_types)): raise ValueError('Neither subject input nor class subject attribute was a string') else: return class_subject else: if (raise_error is True): raise ValueError('Neither subject input nor class subject attribute was a string') return None
null
null
null
subject name
codeqa
def check subject class subject input subject raise error True if input subject is not None if not isinstance input subject string types raise Value Error 'subjectinputmustbeastring' else return input subjectelif class subject is not None if not isinstance class subject string types raise Value Error ' Neithersubjectinputnorclasssubjectattributewasastring' else return class subjectelse if raise error is True raise Value Error ' Neithersubjectinputnorclasssubjectattributewasastring' return None
null
null
null
null
Question: What does the code get from class ? Code: def _check_subject(class_subject, input_subject, raise_error=True): if (input_subject is not None): if (not isinstance(input_subject, string_types)): raise ValueError('subject input must be a string') else: return input_subject elif (class_subject is not None): if (not isinstance(class_subject, string_types)): raise ValueError('Neither subject input nor class subject attribute was a string') else: return class_subject else: if (raise_error is True): raise ValueError('Neither subject input nor class subject attribute was a string') return None
null
null
null
What does the code create ?
def _mk_client(): if ('cp.fileclient_{0}'.format(id(__opts__)) not in __context__): __context__['cp.fileclient_{0}'.format(id(__opts__))] = salt.fileclient.get_file_client(__opts__)
null
null
null
a file client
codeqa
def mk client if 'cp fileclient {0 }' format id opts not in context context ['cp fileclient {0 }' format id opts ] salt fileclient get file client opts
null
null
null
null
Question: What does the code create ? Code: def _mk_client(): if ('cp.fileclient_{0}'.format(id(__opts__)) not in __context__): __context__['cp.fileclient_{0}'.format(id(__opts__))] = salt.fileclient.get_file_client(__opts__)
null
null
null
What does the code leave ?
def StripWhitespace(stream): last_type = None has_space = False ignore_group = frozenset((Comparison, Punctuation)) for (token_type, value) in stream: if last_type: if (token_type in Whitespace): has_space = True continue elif (token_type in (Whitespace, Whitespace.Newline, ignore_group)): continue if has_space: if (not ignore_group.intersection((last_type, token_type))): (yield (Whitespace, ' ')) has_space = False (yield (token_type, value)) last_type = token_type
null
null
null
only the minimal ones
codeqa
def Strip Whitespace stream last type Nonehas space Falseignore group frozenset Comparison Punctuation for token type value in stream if last type if token type in Whitespace has space Truecontinueelif token type in Whitespace Whitespace Newline ignore group continueif has space if not ignore group intersection last type token type yield Whitespace '' has space False yield token type value last type token type
null
null
null
null
Question: What does the code leave ? Code: def StripWhitespace(stream): last_type = None has_space = False ignore_group = frozenset((Comparison, Punctuation)) for (token_type, value) in stream: if last_type: if (token_type in Whitespace): has_space = True continue elif (token_type in (Whitespace, Whitespace.Newline, ignore_group)): continue if has_space: if (not ignore_group.intersection((last_type, token_type))): (yield (Whitespace, ' ')) has_space = False (yield (token_type, value)) last_type = token_type
null
null
null
What do we have ?
def parse_trees(filename): data = open('test_file', 'r').read() for tree_str in data.split(';\n'): if tree_str: (yield Trees.Tree((tree_str + ';')))
null
null
null
bio
codeqa
def parse trees filename data open 'test file' 'r' read for tree str in data split ' \n' if tree str yield Trees Tree tree str + ' '
null
null
null
null
Question: What do we have ? Code: def parse_trees(filename): data = open('test_file', 'r').read() for tree_str in data.split(';\n'): if tree_str: (yield Trees.Tree((tree_str + ';')))
null
null
null
When is the product key installed ?
def installed(product_key): cmd = 'cscript C:\\Windows\\System32\\slmgr.vbs /dli' out = __salt__['cmd.run'](cmd) return (product_key[(-5):] in out)
null
null
null
already
codeqa
def installed product key cmd 'cscript C \\ Windows\\ System 32 \\slmgr vbs/dli'out salt ['cmd run'] cmd return product key[ -5 ] in out
null
null
null
null
Question: When is the product key installed ? Code: def installed(product_key): cmd = 'cscript C:\\Windows\\System32\\slmgr.vbs /dli' out = __salt__['cmd.run'](cmd) return (product_key[(-5):] in out)
null
null
null
By how much did import task skip ?
@pipeline.mutator_stage def plugin_stage(session, func, task): if task.skip: return func(session, task) task.reload()
null
null
null
non
codeqa
@pipeline mutator stagedef plugin stage session func task if task skip returnfunc session task task reload
null
null
null
null
Question: By how much did import task skip ? Code: @pipeline.mutator_stage def plugin_stage(session, func, task): if task.skip: return func(session, task) task.reload()
null
null
null
What is preserving the original aspect ratio ?
def _aspect_preserving_resize(image, smallest_side): smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32) shape = tf.shape(image) height = shape[0] width = shape[1] (new_height, new_width) = _smallest_size_at_least(height, width, smallest_side) image = tf.expand_dims(image, 0) resized_image = tf.image.resize_bilinear(image, [new_height, new_width], align_corners=False) resized_image = tf.squeeze(resized_image) resized_image.set_shape([None, None, 3]) return resized_image
null
null
null
images
codeqa
def aspect preserving resize image smallest side smallest side tf convert to tensor smallest side dtype tf int 32 shape tf shape image height shape[ 0 ]width shape[ 1 ] new height new width smallest size at least height width smallest side image tf expand dims image 0 resized image tf image resize bilinear image [new height new width] align corners False resized image tf squeeze resized image resized image set shape [ None None 3] return resized image
null
null
null
null
Question: What is preserving the original aspect ratio ? Code: def _aspect_preserving_resize(image, smallest_side): smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32) shape = tf.shape(image) height = shape[0] width = shape[1] (new_height, new_width) = _smallest_size_at_least(height, width, smallest_side) image = tf.expand_dims(image, 0) resized_image = tf.image.resize_bilinear(image, [new_height, new_width], align_corners=False) resized_image = tf.squeeze(resized_image) resized_image.set_shape([None, None, 3]) return resized_image
null
null
null
What do images preserve ?
def _aspect_preserving_resize(image, smallest_side): smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32) shape = tf.shape(image) height = shape[0] width = shape[1] (new_height, new_width) = _smallest_size_at_least(height, width, smallest_side) image = tf.expand_dims(image, 0) resized_image = tf.image.resize_bilinear(image, [new_height, new_width], align_corners=False) resized_image = tf.squeeze(resized_image) resized_image.set_shape([None, None, 3]) return resized_image
null
null
null
the original aspect ratio
codeqa
def aspect preserving resize image smallest side smallest side tf convert to tensor smallest side dtype tf int 32 shape tf shape image height shape[ 0 ]width shape[ 1 ] new height new width smallest size at least height width smallest side image tf expand dims image 0 resized image tf image resize bilinear image [new height new width] align corners False resized image tf squeeze resized image resized image set shape [ None None 3] return resized image
null
null
null
null
Question: What do images preserve ? Code: def _aspect_preserving_resize(image, smallest_side): smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32) shape = tf.shape(image) height = shape[0] width = shape[1] (new_height, new_width) = _smallest_size_at_least(height, width, smallest_side) image = tf.expand_dims(image, 0) resized_image = tf.image.resize_bilinear(image, [new_height, new_width], align_corners=False) resized_image = tf.squeeze(resized_image) resized_image.set_shape([None, None, 3]) return resized_image
null
null
null
What does the code convert into a network input ?
def im_list_to_blob(ims): max_shape = np.array([im.shape for im in ims]).max(axis=0) num_images = len(ims) blob = np.zeros((num_images, max_shape[0], max_shape[1], 3), dtype=np.float32) for i in xrange(num_images): im = ims[i] blob[i, 0:im.shape[0], 0:im.shape[1], :] = im channel_swap = (0, 3, 1, 2) blob = blob.transpose(channel_swap) return blob
null
null
null
a list of images
codeqa
def im list to blob ims max shape np array [im shape for im in ims] max axis 0 num images len ims blob np zeros num images max shape[ 0 ] max shape[ 1 ] 3 dtype np float 32 for i in xrange num images im ims[i]blob[i 0 im shape[ 0 ] 0 im shape[ 1 ] ] imchannel swap 0 3 1 2 blob blob transpose channel swap return blob
null
null
null
null
Question: What does the code convert into a network input ? Code: def im_list_to_blob(ims): max_shape = np.array([im.shape for im in ims]).max(axis=0) num_images = len(ims) blob = np.zeros((num_images, max_shape[0], max_shape[1], 3), dtype=np.float32) for i in xrange(num_images): im = ims[i] blob[i, 0:im.shape[0], 0:im.shape[1], :] = im channel_swap = (0, 3, 1, 2) blob = blob.transpose(channel_swap) return blob
null
null
null
What does the code create ?
def create_connection(conf, new=True): return Connection()
null
null
null
a connection
codeqa
def create connection conf new True return Connection
null
null
null
null
Question: What does the code create ? Code: def create_connection(conf, new=True): return Connection()
null
null
null
What does the code get ?
def get_history_items(): return [readline.get_history_item(i) for i in xrange(1, (readline.get_current_history_length() + 1))]
null
null
null
all history item
codeqa
def get history items return [readline get history item i for i in xrange 1 readline get current history length + 1 ]
null
null
null
null
Question: What does the code get ? Code: def get_history_items(): return [readline.get_history_item(i) for i in xrange(1, (readline.get_current_history_length() + 1))]
null
null
null
When will the computer start ?
def get_restart_delay(): ret = salt.utils.mac_utils.execute_return_result('systemsetup -getwaitforstartupafterpowerfailure') return salt.utils.mac_utils.parse_return(ret)
null
null
null
after which
codeqa
def get restart delay ret salt utils mac utils execute return result 'systemsetup-getwaitforstartupafterpowerfailure' return salt utils mac utils parse return ret
null
null
null
null
Question: When will the computer start ? Code: def get_restart_delay(): ret = salt.utils.mac_utils.execute_return_result('systemsetup -getwaitforstartupafterpowerfailure') return salt.utils.mac_utils.parse_return(ret)
null
null
null
What does the code get ?
def get_restart_delay(): ret = salt.utils.mac_utils.execute_return_result('systemsetup -getwaitforstartupafterpowerfailure') return salt.utils.mac_utils.parse_return(ret)
null
null
null
the number of seconds after which the computer will start up after a power failure
codeqa
def get restart delay ret salt utils mac utils execute return result 'systemsetup-getwaitforstartupafterpowerfailure' return salt utils mac utils parse return ret
null
null
null
null
Question: What does the code get ? Code: def get_restart_delay(): ret = salt.utils.mac_utils.execute_return_result('systemsetup -getwaitforstartupafterpowerfailure') return salt.utils.mac_utils.parse_return(ret)
null
null
null
What does the code get ?
def bytes(num_bytes): if (not isinstance(num_bytes, _integer_types)): raise TypeError('num_bytes must be an integer') if (num_bytes < 0): raise ValueError('num_bytes must not be negative') result_buffer = _ffi.new('char[]', num_bytes) result_code = _lib.RAND_bytes(result_buffer, num_bytes) if (result_code == (-1)): _raise_current_error() return _ffi.buffer(result_buffer)[:]
null
null
null
some random bytes
codeqa
def bytes num bytes if not isinstance num bytes integer types raise Type Error 'num bytesmustbeaninteger' if num bytes < 0 raise Value Error 'num bytesmustnotbenegative' result buffer ffi new 'char[]' num bytes result code lib RAND bytes result buffer num bytes if result code -1 raise current error return ffi buffer result buffer [ ]
null
null
null
null
Question: What does the code get ? Code: def bytes(num_bytes): if (not isinstance(num_bytes, _integer_types)): raise TypeError('num_bytes must be an integer') if (num_bytes < 0): raise ValueError('num_bytes must not be negative') result_buffer = _ffi.new('char[]', num_bytes) result_code = _lib.RAND_bytes(result_buffer, num_bytes) if (result_code == (-1)): _raise_current_error() return _ffi.buffer(result_buffer)[:]
null
null
null
What did the code stub ?
def get_course_enrollment(student_id, course_id): return _get_fake_enrollment(student_id, course_id)
null
null
null
enrollment data request
codeqa
def get course enrollment student id course id return get fake enrollment student id course id
null
null
null
null
Question: What did the code stub ? Code: def get_course_enrollment(student_id, course_id): return _get_fake_enrollment(student_id, course_id)
null
null
null
What does the code annotate with child_indent annotations ?
def _AnnotateIndents(tree): if (tree.parent is None): pytree_utils.SetNodeAnnotation(tree, pytree_utils.Annotation.CHILD_INDENT, '') for child in tree.children: if (child.type == token.INDENT): child_indent = pytree_utils.GetNodeAnnotation(tree, pytree_utils.Annotation.CHILD_INDENT) if ((child_indent is not None) and (child_indent != child.value)): raise RuntimeError('inconsistent indentation for child', (tree, child)) pytree_utils.SetNodeAnnotation(tree, pytree_utils.Annotation.CHILD_INDENT, child.value) _AnnotateIndents(child)
null
null
null
the tree
codeqa
def Annotate Indents tree if tree parent is None pytree utils Set Node Annotation tree pytree utils Annotation CHILD INDENT '' for child in tree children if child type token INDENT child indent pytree utils Get Node Annotation tree pytree utils Annotation CHILD INDENT if child indent is not None and child indent child value raise Runtime Error 'inconsistentindentationforchild' tree child pytree utils Set Node Annotation tree pytree utils Annotation CHILD INDENT child value Annotate Indents child
null
null
null
null
Question: What does the code annotate with child_indent annotations ? Code: def _AnnotateIndents(tree): if (tree.parent is None): pytree_utils.SetNodeAnnotation(tree, pytree_utils.Annotation.CHILD_INDENT, '') for child in tree.children: if (child.type == token.INDENT): child_indent = pytree_utils.GetNodeAnnotation(tree, pytree_utils.Annotation.CHILD_INDENT) if ((child_indent is not None) and (child_indent != child.value)): raise RuntimeError('inconsistent indentation for child', (tree, child)) pytree_utils.SetNodeAnnotation(tree, pytree_utils.Annotation.CHILD_INDENT, child.value) _AnnotateIndents(child)
null
null
null
What does the code take ?
def search(seq, key): lo = 0 hi = (len(seq) - 1) while (hi >= lo): mid = (lo + ((hi - lo) // 2)) if (seq[mid] < key): lo = (mid + 1) elif (seq[mid] > key): hi = (mid - 1) else: return mid return False
null
null
null
a list of integers
codeqa
def search seq key lo 0hi len seq - 1 while hi > lo mid lo + hi - lo // 2 if seq[mid] < key lo mid + 1 elif seq[mid] > key hi mid - 1 else return midreturn False
null
null
null
null
Question: What does the code take ? Code: def search(seq, key): lo = 0 hi = (len(seq) - 1) while (hi >= lo): mid = (lo + ((hi - lo) // 2)) if (seq[mid] < key): lo = (mid + 1) elif (seq[mid] > key): hi = (mid - 1) else: return mid return False
null
null
null
What does the code decorate ?
def reconstructor(fn): fn.__sa_reconstructor__ = True return fn
null
null
null
a method
codeqa
def reconstructor fn fn sa reconstructor Truereturn fn
null
null
null
null
Question: What does the code decorate ? Code: def reconstructor(fn): fn.__sa_reconstructor__ = True return fn
null
null
null
Where does implementation total_second ?
def total_seconds(td): if hasattr(td, 'total_seconds'): return td.total_seconds() else: return (((((td.days * 86400) + td.seconds) * (10 ** 6)) + td.microseconds) / (10.0 ** 6))
null
null
null
local
codeqa
def total seconds td if hasattr td 'total seconds' return td total seconds else return td days * 86400 + td seconds * 10 ** 6 + td microseconds / 10 0 ** 6
null
null
null
null
Question: Where does implementation total_second ? Code: def total_seconds(td): if hasattr(td, 'total_seconds'): return td.total_seconds() else: return (((((td.days * 86400) + td.seconds) * (10 ** 6)) + td.microseconds) / (10.0 ** 6))
null
null
null
What total_seconds local ?
def total_seconds(td): if hasattr(td, 'total_seconds'): return td.total_seconds() else: return (((((td.days * 86400) + td.seconds) * (10 ** 6)) + td.microseconds) / (10.0 ** 6))
null
null
null
implementation
codeqa
def total seconds td if hasattr td 'total seconds' return td total seconds else return td days * 86400 + td seconds * 10 ** 6 + td microseconds / 10 0 ** 6
null
null
null
null
Question: What total_seconds local ? Code: def total_seconds(td): if hasattr(td, 'total_seconds'): return td.total_seconds() else: return (((((td.days * 86400) + td.seconds) * (10 ** 6)) + td.microseconds) / (10.0 ** 6))
null
null
null
For what purpose be that downloaded ?
def get_vmdk_size_and_properties(context, image, instance): LOG.debug((_('Getting image size for the image %s') % image), instance=instance) (image_service, image_id) = glance.get_remote_image_service(context, image) meta_data = image_service.show(context, image_id) (size, properties) = (meta_data['size'], meta_data['properties']) LOG.debug((_('Got image size of %(size)s for the image %(image)s') % locals()), instance=instance) return (size, properties)
null
null
null
for attach in spawn
codeqa
def get vmdk size and properties context image instance LOG debug ' Gettingimagesizefortheimage%s' % image instance instance image service image id glance get remote image service context image meta data image service show context image id size properties meta data['size'] meta data['properties'] LOG debug ' Gotimagesizeof% size sfortheimage% image s' % locals instance instance return size properties
null
null
null
null
Question: For what purpose be that downloaded ? Code: def get_vmdk_size_and_properties(context, image, instance): LOG.debug((_('Getting image size for the image %s') % image), instance=instance) (image_service, image_id) = glance.get_remote_image_service(context, image) meta_data = image_service.show(context, image_id) (size, properties) = (meta_data['size'], meta_data['properties']) LOG.debug((_('Got image size of %(size)s for the image %(image)s') % locals()), instance=instance) return (size, properties)
null
null
null
For what purpose does the tournament matrix return ?
@not_implemented_for('undirected') @not_implemented_for('multigraph') def tournament_matrix(G): A = nx.adjacency_matrix(G) return (A - A.T)
null
null
null
for the given tournament graph
codeqa
@not implemented for 'undirected' @not implemented for 'multigraph' def tournament matrix G A nx adjacency matrix G return A - A T
null
null
null
null
Question: For what purpose does the tournament matrix return ? Code: @not_implemented_for('undirected') @not_implemented_for('multigraph') def tournament_matrix(G): A = nx.adjacency_matrix(G) return (A - A.T)
null
null
null
What does the code raise ?
def get_user(username='testuser'): User = get_user_model() try: return User.objects.get(username=username) except User.DoesNotExist: raise FixtureMissingError(('Username "%s" not found. You probably forgot to import a users fixture.' % username))
null
null
null
fixturemissingerror
codeqa
def get user username 'testuser' User get user model try return User objects get username username except User Does Not Exist raise Fixture Missing Error ' Username"%s"notfound Youprobablyforgottoimportausersfixture ' % username
null
null
null
null
Question: What does the code raise ? Code: def get_user(username='testuser'): User = get_user_model() try: return User.objects.get(username=username) except User.DoesNotExist: raise FixtureMissingError(('Username "%s" not found. You probably forgot to import a users fixture.' % username))
null
null
null
For what purpose does the code preprocess the given image ?
def preprocess_for_eval(image, output_height, output_width): tf.image_summary('image', tf.expand_dims(image, 0)) image = tf.to_float(image) resized_image = tf.image.resize_image_with_crop_or_pad(image, output_width, output_height) tf.image_summary('resized_image', tf.expand_dims(resized_image, 0)) return tf.image.per_image_whitening(resized_image)
null
null
null
for evaluation
codeqa
def preprocess for eval image output height output width tf image summary 'image' tf expand dims image 0 image tf to float image resized image tf image resize image with crop or pad image output width output height tf image summary 'resized image' tf expand dims resized image 0 return tf image per image whitening resized image
null
null
null
null
Question: For what purpose does the code preprocess the given image ? Code: def preprocess_for_eval(image, output_height, output_width): tf.image_summary('image', tf.expand_dims(image, 0)) image = tf.to_float(image) resized_image = tf.image.resize_image_with_crop_or_pad(image, output_width, output_height) tf.image_summary('resized_image', tf.expand_dims(resized_image, 0)) return tf.image.per_image_whitening(resized_image)
null
null
null
What does the code preprocess for evaluation ?
def preprocess_for_eval(image, output_height, output_width): tf.image_summary('image', tf.expand_dims(image, 0)) image = tf.to_float(image) resized_image = tf.image.resize_image_with_crop_or_pad(image, output_width, output_height) tf.image_summary('resized_image', tf.expand_dims(resized_image, 0)) return tf.image.per_image_whitening(resized_image)
null
null
null
the given image
codeqa
def preprocess for eval image output height output width tf image summary 'image' tf expand dims image 0 image tf to float image resized image tf image resize image with crop or pad image output width output height tf image summary 'resized image' tf expand dims resized image 0 return tf image per image whitening resized image
null
null
null
null
Question: What does the code preprocess for evaluation ? Code: def preprocess_for_eval(image, output_height, output_width): tf.image_summary('image', tf.expand_dims(image, 0)) image = tf.to_float(image) resized_image = tf.image.resize_image_with_crop_or_pad(image, output_width, output_height) tf.image_summary('resized_image', tf.expand_dims(resized_image, 0)) return tf.image.per_image_whitening(resized_image)
null
null
null
What does the code establish ?
def _kde_support(data, bw, gridsize, cut, clip): support_min = max((data.min() - (bw * cut)), clip[0]) support_max = min((data.max() + (bw * cut)), clip[1]) return np.linspace(support_min, support_max, gridsize)
null
null
null
support for a kernel density estimate
codeqa
def kde support data bw gridsize cut clip support min max data min - bw * cut clip[ 0 ] support max min data max + bw * cut clip[ 1 ] return np linspace support min support max gridsize
null
null
null
null
Question: What does the code establish ? Code: def _kde_support(data, bw, gridsize, cut, clip): support_min = max((data.min() - (bw * cut)), clip[0]) support_max = min((data.max() + (bw * cut)), clip[1]) return np.linspace(support_min, support_max, gridsize)
null
null
null
How does the roles return ?
def get_roles_with_permission(permission): roles = [] for role in ROLE_PERMISSIONS: permissions = ROLE_PERMISSIONS[role] if ((permission in permissions) or ('admin' in permissions)): roles.append(role) return roles
null
null
null
with the permission requested
codeqa
def get roles with permission permission roles []for role in ROLE PERMISSIONS permissions ROLE PERMISSIONS[role]if permission in permissions or 'admin' in permissions roles append role return roles
null
null
null
null
Question: How does the roles return ? Code: def get_roles_with_permission(permission): roles = [] for role in ROLE_PERMISSIONS: permissions = ROLE_PERMISSIONS[role] if ((permission in permissions) or ('admin' in permissions)): roles.append(role) return roles
null
null
null
What does the code get ?
@register.tag def get_blog_categories(parser, token): try: (tag_name, arg) = token.contents.split(None, 1) except ValueError: raise template.TemplateSyntaxError, ('%s tag requires arguments' % token.contents.split()[0]) m = re.search('as (\\w+)', arg) if (not m): raise template.TemplateSyntaxError, ('%s tag had invalid arguments' % tag_name) var_name = m.groups()[0] return BlogCategories(var_name)
null
null
null
all blog categories
codeqa
@register tagdef get blog categories parser token try tag name arg token contents split None 1 except Value Error raise template Template Syntax Error '%stagrequiresarguments' % token contents split [0 ] m re search 'as \\w+ ' arg if not m raise template Template Syntax Error '%staghadinvalidarguments' % tag name var name m groups [0 ]return Blog Categories var name
null
null
null
null
Question: What does the code get ? Code: @register.tag def get_blog_categories(parser, token): try: (tag_name, arg) = token.contents.split(None, 1) except ValueError: raise template.TemplateSyntaxError, ('%s tag requires arguments' % token.contents.split()[0]) m = re.search('as (\\w+)', arg) if (not m): raise template.TemplateSyntaxError, ('%s tag had invalid arguments' % tag_name) var_name = m.groups()[0] return BlogCategories(var_name)
null
null
null
For what purpose must napalm library be installed ?
def __virtual__(): if (HAS_NAPALM and ('proxy' in __opts__)): return __virtualname__ else: return (False, 'The module NTP cannot be loaded: napalm or proxy could not be loaded.')
null
null
null
for this module to work
codeqa
def virtual if HAS NAPALM and 'proxy' in opts return virtualname else return False ' Themodule NT Pcannotbeloaded napalmorproxycouldnotbeloaded '
null
null
null
null
Question: For what purpose must napalm library be installed ? Code: def __virtual__(): if (HAS_NAPALM and ('proxy' in __opts__)): return __virtualname__ else: return (False, 'The module NTP cannot be loaded: napalm or proxy could not be loaded.')
null
null
null
How do items print ?
def list_items(lib, query, album, fmt=u''): if album: for album in lib.albums(query): ui.print_(format(album, fmt)) else: for item in lib.items(query): ui.print_(format(item, fmt))
null
null
null
in lib matching query
codeqa
def list items lib query album fmt u'' if album for album in lib albums query ui print format album fmt else for item in lib items query ui print format item fmt
null
null
null
null
Question: How do items print ? Code: def list_items(lib, query, album, fmt=u''): if album: for album in lib.albums(query): ui.print_(format(album, fmt)) else: for item in lib.items(query): ui.print_(format(item, fmt))
null
null
null
What is containing a host and possibly a port ?
def to_host_port_tuple(host_port_str, default_port=80): uri = URIReference(scheme=None, authority=host_port_str, path=None, query=None, fragment=None) host = uri.host.strip('[]') if (not uri.port): port = default_port else: port = int(uri.port) return (host, port)
null
null
null
the given string
codeqa
def to host port tuple host port str default port 80 uri URI Reference scheme None authority host port str path None query None fragment None host uri host strip '[]' if not uri port port default portelse port int uri port return host port
null
null
null
null
Question: What is containing a host and possibly a port ? Code: def to_host_port_tuple(host_port_str, default_port=80): uri = URIReference(scheme=None, authority=host_port_str, path=None, query=None, fragment=None) host = uri.host.strip('[]') if (not uri.port): port = default_port else: port = int(uri.port) return (host, port)
null
null
null
What does the code create ?
def hardlinkFile(srcFile, destFile): try: link(srcFile, destFile) fixSetGroupID(destFile) except Exception as e: sickrage.srCore.srLogger.warning((u'Failed to create hardlink of %s at %s. Error: %r. Copying instead' % (srcFile, destFile, e))) copyFile(srcFile, destFile)
null
null
null
a hard - link between source and destination
codeqa
def hardlink File src File dest File try link src File dest File fix Set Group ID dest File except Exception as e sickrage sr Core sr Logger warning u' Failedtocreatehardlinkof%sat%s Error %r Copyinginstead' % src File dest File e copy File src File dest File
null
null
null
null
Question: What does the code create ? Code: def hardlinkFile(srcFile, destFile): try: link(srcFile, destFile) fixSetGroupID(destFile) except Exception as e: sickrage.srCore.srLogger.warning((u'Failed to create hardlink of %s at %s. Error: %r. Copying instead' % (srcFile, destFile, e))) copyFile(srcFile, destFile)
null
null
null
What does the code compute ?
def _winding_number(T, field): return int((sum([field(*_values[t][i]) for (t, i) in T]) / field(2)))
null
null
null
the winding number of the input polynomial
codeqa
def winding number T field return int sum [field * values[t][i] for t i in T] / field 2
null
null
null
null
Question: What does the code compute ? Code: def _winding_number(T, field): return int((sum([field(*_values[t][i]) for (t, i) in T]) / field(2)))
null
null
null
How does the code get cycle class ?
def cycle_by_name(name): return symbol_by_name(name, CYCLE_ALIASES)
null
null
null
by name
codeqa
def cycle by name name return symbol by name name CYCLE ALIASES
null
null
null
null
Question: How does the code get cycle class ? Code: def cycle_by_name(name): return symbol_by_name(name, CYCLE_ALIASES)
null
null
null
What does the code get by name ?
def cycle_by_name(name): return symbol_by_name(name, CYCLE_ALIASES)
null
null
null
cycle class
codeqa
def cycle by name name return symbol by name name CYCLE ALIASES
null
null
null
null
Question: What does the code get by name ? Code: def cycle_by_name(name): return symbol_by_name(name, CYCLE_ALIASES)
null
null
null
When does the code get holidays ?
def get_holidays(employee, from_date, to_date): holiday_list = get_holiday_list_for_employee(employee) holidays = frappe.db.sql(u'select count(distinct holiday_date) from `tabHoliday` h1, `tabHoliday List` h2\n DCTB DCTB where h1.parent = h2.name and h1.holiday_date between %s and %s\n DCTB DCTB and h2.name = %s', (from_date, to_date, holiday_list))[0][0] return holidays
null
null
null
between two
codeqa
def get holidays employee from date to date holiday list get holiday list for employee employee holidays frappe db sql u'selectcount distinctholiday date from`tab Holiday`h 1 `tab Holiday List`h 2 \n DCTB DCTB whereh 1 parent h2 nameandh 1 holiday datebetween%sand%s\n DCTB DCTB andh 2 name %s' from date to date holiday list [0 ][ 0 ]return holidays
null
null
null
null
Question: When does the code get holidays ? Code: def get_holidays(employee, from_date, to_date): holiday_list = get_holiday_list_for_employee(employee) holidays = frappe.db.sql(u'select count(distinct holiday_date) from `tabHoliday` h1, `tabHoliday List` h2\n DCTB DCTB where h1.parent = h2.name and h1.holiday_date between %s and %s\n DCTB DCTB and h2.name = %s', (from_date, to_date, holiday_list))[0][0] return holidays
null
null
null
What does the code get between two ?
def get_holidays(employee, from_date, to_date): holiday_list = get_holiday_list_for_employee(employee) holidays = frappe.db.sql(u'select count(distinct holiday_date) from `tabHoliday` h1, `tabHoliday List` h2\n DCTB DCTB where h1.parent = h2.name and h1.holiday_date between %s and %s\n DCTB DCTB and h2.name = %s', (from_date, to_date, holiday_list))[0][0] return holidays
null
null
null
holidays
codeqa
def get holidays employee from date to date holiday list get holiday list for employee employee holidays frappe db sql u'selectcount distinctholiday date from`tab Holiday`h 1 `tab Holiday List`h 2 \n DCTB DCTB whereh 1 parent h2 nameandh 1 holiday datebetween%sand%s\n DCTB DCTB andh 2 name %s' from date to date holiday list [0 ][ 0 ]return holidays
null
null
null
null
Question: What does the code get between two ? Code: def get_holidays(employee, from_date, to_date): holiday_list = get_holiday_list_for_employee(employee) holidays = frappe.db.sql(u'select count(distinct holiday_date) from `tabHoliday` h1, `tabHoliday List` h2\n DCTB DCTB where h1.parent = h2.name and h1.holiday_date between %s and %s\n DCTB DCTB and h2.name = %s', (from_date, to_date, holiday_list))[0][0] return holidays
null
null
null
What does someone cause ?
def test_fast_wait(): gevent.sleep(300)
null
null
null
fast - sleep test patching to regress
codeqa
def test fast wait gevent sleep 300
null
null
null
null
Question: What does someone cause ? Code: def test_fast_wait(): gevent.sleep(300)
null
null
null
What causes fast - sleep test patching to regress ?
def test_fast_wait(): gevent.sleep(300)
null
null
null
someone
codeqa
def test fast wait gevent sleep 300
null
null
null
null
Question: What causes fast - sleep test patching to regress ? Code: def test_fast_wait(): gevent.sleep(300)
null
null
null
Where did the code set pixel color ?
def set_color(img, coords, color, alpha=1): (rr, cc) = coords if (img.ndim == 2): img = img[..., np.newaxis] color = np.array(color, ndmin=1, copy=False) if (img.shape[(-1)] != color.shape[(-1)]): raise ValueError('Color shape ({}) must match last image dimension ({}).'.format(color.shape[0], img.shape[(-1)])) if np.isscalar(alpha): alpha = (np.ones_like(rr) * alpha) (rr, cc, alpha) = _coords_inside_image(rr, cc, img.shape, val=alpha) alpha = alpha[..., np.newaxis] color = (color * alpha) vals = (img[(rr, cc)] * (1 - alpha)) img[(rr, cc)] = (vals + color)
null
null
null
in the image
codeqa
def set color img coords color alpha 1 rr cc coordsif img ndim 2 img img[ np newaxis]color np array color ndmin 1 copy False if img shape[ -1 ] color shape[ -1 ] raise Value Error ' Colorshape {} mustmatchlastimagedimension {} ' format color shape[ 0 ] img shape[ -1 ] if np isscalar alpha alpha np ones like rr * alpha rr cc alpha coords inside image rr cc img shape val alpha alpha alpha[ np newaxis]color color * alpha vals img[ rr cc ] * 1 - alpha img[ rr cc ] vals + color
null
null
null
null
Question: Where did the code set pixel color ? Code: def set_color(img, coords, color, alpha=1): (rr, cc) = coords if (img.ndim == 2): img = img[..., np.newaxis] color = np.array(color, ndmin=1, copy=False) if (img.shape[(-1)] != color.shape[(-1)]): raise ValueError('Color shape ({}) must match last image dimension ({}).'.format(color.shape[0], img.shape[(-1)])) if np.isscalar(alpha): alpha = (np.ones_like(rr) * alpha) (rr, cc, alpha) = _coords_inside_image(rr, cc, img.shape, val=alpha) alpha = alpha[..., np.newaxis] color = (color * alpha) vals = (img[(rr, cc)] * (1 - alpha)) img[(rr, cc)] = (vals + color)
null
null
null
What did the code set in the image in the image ?
def set_color(img, coords, color, alpha=1): (rr, cc) = coords if (img.ndim == 2): img = img[..., np.newaxis] color = np.array(color, ndmin=1, copy=False) if (img.shape[(-1)] != color.shape[(-1)]): raise ValueError('Color shape ({}) must match last image dimension ({}).'.format(color.shape[0], img.shape[(-1)])) if np.isscalar(alpha): alpha = (np.ones_like(rr) * alpha) (rr, cc, alpha) = _coords_inside_image(rr, cc, img.shape, val=alpha) alpha = alpha[..., np.newaxis] color = (color * alpha) vals = (img[(rr, cc)] * (1 - alpha)) img[(rr, cc)] = (vals + color)
null
null
null
pixel color
codeqa
def set color img coords color alpha 1 rr cc coordsif img ndim 2 img img[ np newaxis]color np array color ndmin 1 copy False if img shape[ -1 ] color shape[ -1 ] raise Value Error ' Colorshape {} mustmatchlastimagedimension {} ' format color shape[ 0 ] img shape[ -1 ] if np isscalar alpha alpha np ones like rr * alpha rr cc alpha coords inside image rr cc img shape val alpha alpha alpha[ np newaxis]color color * alpha vals img[ rr cc ] * 1 - alpha img[ rr cc ] vals + color
null
null
null
null
Question: What did the code set in the image in the image ? Code: def set_color(img, coords, color, alpha=1): (rr, cc) = coords if (img.ndim == 2): img = img[..., np.newaxis] color = np.array(color, ndmin=1, copy=False) if (img.shape[(-1)] != color.shape[(-1)]): raise ValueError('Color shape ({}) must match last image dimension ({}).'.format(color.shape[0], img.shape[(-1)])) if np.isscalar(alpha): alpha = (np.ones_like(rr) * alpha) (rr, cc, alpha) = _coords_inside_image(rr, cc, img.shape, val=alpha) alpha = alpha[..., np.newaxis] color = (color * alpha) vals = (img[(rr, cc)] * (1 - alpha)) img[(rr, cc)] = (vals + color)
null
null
null
How does the code get normal ?
def getNormalByPath(path): totalNormal = Vector3() for (pointIndex, point) in enumerate(path): center = path[((pointIndex + 1) % len(path))] end = path[((pointIndex + 2) % len(path))] totalNormal += getNormalWeighted(point, center, end) return totalNormal.getNormalized()
null
null
null
by path
codeqa
def get Normal By Path path total Normal Vector 3 for point Index point in enumerate path center path[ point Index + 1 % len path ]end path[ point Index + 2 % len path ]total Normal + get Normal Weighted point center end return total Normal get Normalized
null
null
null
null
Question: How does the code get normal ? Code: def getNormalByPath(path): totalNormal = Vector3() for (pointIndex, point) in enumerate(path): center = path[((pointIndex + 1) % len(path))] end = path[((pointIndex + 2) % len(path))] totalNormal += getNormalWeighted(point, center, end) return totalNormal.getNormalized()
null
null
null
What does the code generate ?
def generate_unit_summary(namespace): docstring = io.StringIO() docstring.write(u'\n.. list-table:: Available Units\n :header-rows: 1\n :widths: 10 20 20 20 1\n\n * - Unit\n - Description\n - Represents\n - Aliases\n - SI Prefixes\n') for unit_summary in _iter_unit_summary(namespace): docstring.write(u'\n * - ``{0}``\n - {1}\n - {2}\n - {3}\n - {4!s:.1}\n'.format(*unit_summary)) return docstring.getvalue()
null
null
null
a summary of units from a given namespace
codeqa
def generate unit summary namespace docstring io String IO docstring write u'\n list-table Available Units\n header-rows 1\n widths 102020201 \n\n*- Unit\n- Description\n- Represents\n- Aliases\n-SI Prefixes\n' for unit summary in iter unit summary namespace docstring write u'\n*-``{ 0 }``\n-{ 1 }\n-{ 2 }\n-{ 3 }\n-{ 4 s 1}\n' format *unit summary return docstring getvalue
null
null
null
null
Question: What does the code generate ? Code: def generate_unit_summary(namespace): docstring = io.StringIO() docstring.write(u'\n.. list-table:: Available Units\n :header-rows: 1\n :widths: 10 20 20 20 1\n\n * - Unit\n - Description\n - Represents\n - Aliases\n - SI Prefixes\n') for unit_summary in _iter_unit_summary(namespace): docstring.write(u'\n * - ``{0}``\n - {1}\n - {2}\n - {3}\n - {4!s:.1}\n'.format(*unit_summary)) return docstring.getvalue()
null
null
null
What makes testing update_blogs management command easier ?
def _render_blog_supernav(entry): return render_to_string('blogs/supernav.html', {'entry': entry})
null
null
null
utility
codeqa
def render blog supernav entry return render to string 'blogs/supernav html' {'entry' entry}
null
null
null
null
Question: What makes testing update_blogs management command easier ? Code: def _render_blog_supernav(entry): return render_to_string('blogs/supernav.html', {'entry': entry})
null
null
null
What do utility make ?
def _render_blog_supernav(entry): return render_to_string('blogs/supernav.html', {'entry': entry})
null
null
null
testing update_blogs management command easier
codeqa
def render blog supernav entry return render to string 'blogs/supernav html' {'entry' entry}
null
null
null
null
Question: What do utility make ? Code: def _render_blog_supernav(entry): return render_to_string('blogs/supernav.html', {'entry': entry})
null
null
null
What can override the runner parameter ?
def validate_runner_parameter_attribute_override(action_ref, param_name, attr_name, runner_param_attr_value, action_param_attr_value): param_values_are_the_same = (action_param_attr_value == runner_param_attr_value) if ((attr_name not in RUNNER_PARAM_OVERRIDABLE_ATTRS) and (not param_values_are_the_same)): raise InvalidActionParameterException(('The attribute "%s" for the runner parameter "%s" in action "%s" cannot be overridden.' % (attr_name, param_name, action_ref))) return True
null
null
null
the provided parameter from the action schema
codeqa
def validate runner parameter attribute override action ref param name attr name runner param attr value action param attr value param values are the same action param attr value runner param attr value if attr name not in RUNNER PARAM OVERRIDABLE ATTRS and not param values are the same raise Invalid Action Parameter Exception ' Theattribute"%s"fortherunnerparameter"%s"inaction"%s"cannotbeoverridden ' % attr name param name action ref return True
null
null
null
null
Question: What can override the runner parameter ? Code: def validate_runner_parameter_attribute_override(action_ref, param_name, attr_name, runner_param_attr_value, action_param_attr_value): param_values_are_the_same = (action_param_attr_value == runner_param_attr_value) if ((attr_name not in RUNNER_PARAM_OVERRIDABLE_ATTRS) and (not param_values_are_the_same)): raise InvalidActionParameterException(('The attribute "%s" for the runner parameter "%s" in action "%s" cannot be overridden.' % (attr_name, param_name, action_ref))) return True