id
stringlengths
11
16
language
stringclasses
2 values
question
stringlengths
13
844
answer
stringlengths
1
900
code
stringlengths
162
27.4k
code_original
stringlengths
162
26k
code_word_count
int64
51
5.96k
python-test-1722
python
What do signed url provide to a resource ?
query - string authn
def generate signed url credentials resource expiration api access endpoint '' method 'GET' content md 5 None content type None response type None response disposition None generation None expiration get expiration seconds expiration string to sign '\n' join [method content md 5 or '' content type or '' str expiration ...
def generate_signed_url credentials resource expiration api_access_endpoint '' method 'GET' content_md5 None content_type None response_type None response_disposition None generation None expiration _get_expiration_seconds expiration string_to_sign '\n' join [method content_md5 or '' content_type or '' str expiration r...
100
python-test-1723
python
What does this function turn into serializable objects ?
assorted types
def to serializables obj if isinstance obj P Record result dict obj result[ CLASS MARKER] obj class name return resultelif isinstance obj P Class result obj to dict result[ CLASS MARKER] obj class name return resultelif isinstance obj P Map return { CLASS MARKER u'P Map' u'values' dict obj items }elif isinstance obj P ...
def _to_serializables obj if isinstance obj PRecord result dict obj result[_CLASS_MARKER] obj __class__ __name__return resultelif isinstance obj PClass result obj _to_dict result[_CLASS_MARKER] obj __class__ __name__return resultelif isinstance obj PMap return {_CLASS_MARKER u'PMap' u'values' dict obj items }elif isins...
120
python-test-1727
python
What does the code return ?
a list with all the pids of a process tree
def get processtree pids pid include parent True parents get all processes pids all pids parents keys pids set [pid] while True pids new pids copy for pid in all pids if parents[ pid] in pids pids new add pid if pids new pids breakpids pids new copy if not include parent pids remove pid return list pids
def get_processtree_pids pid include_parent True parents get_all_processes_pids all_pids parents keys pids set [pid] while True pids_new pids copy for _pid in all_pids if parents[_pid] in pids pids_new add _pid if pids_new pids breakpids pids_new copy if not include_parent pids remove pid return list pids
58
python-test-1728
python
What does the auth api trigger ?
the email of a viewfinder access token
def Test Generate Access Token action tester device dict auth info dict user cookie None use short token True response dict Generate Access Token action tester device dict auth info dict user cookie use short token use short token identity type value Identity Split Key auth info dict['identity'] expected digits 4 if us...
def _TestGenerateAccessToken action tester device_dict auth_info_dict user_cookie None use_short_token True response_dict _GenerateAccessToken action tester device_dict auth_info_dict user_cookie use_short_token use_short_token identity_type value Identity SplitKey auth_info_dict['identity'] expected_digits 4 if use_sh...
111
python-test-1729
python
What triggers the email of a viewfinder access token ?
the auth api
def Test Generate Access Token action tester device dict auth info dict user cookie None use short token True response dict Generate Access Token action tester device dict auth info dict user cookie use short token use short token identity type value Identity Split Key auth info dict['identity'] expected digits 4 if us...
def _TestGenerateAccessToken action tester device_dict auth_info_dict user_cookie None use_short_token True response_dict _GenerateAccessToken action tester device_dict auth_info_dict user_cookie use_short_token use_short_token identity_type value Identity SplitKey auth_info_dict['identity'] expected_digits 4 if use_sh...
111
python-test-1730
python
What uses to expand archs for the installed version of xcode ?
the |xcodearchsdefault| object
def Get Xcode Archs Default global XCODE ARCHS DEFAULT CACH Eif XCODE ARCHS DEFAULT CACHE return XCODE ARCHS DEFAULT CACHE xcode version Xcode Version if xcode version < '0500 ' XCODE ARCHS DEFAULT CACHE Xcode Archs Default '$ ARCHS STANDARD ' Xcode Archs Variable Mapping ['i 386 '] Xcode Archs Variable Mapping ['i 386...
def GetXcodeArchsDefault global XCODE_ARCHS_DEFAULT_CACHEif XCODE_ARCHS_DEFAULT_CACHE return XCODE_ARCHS_DEFAULT_CACHE xcode_version _ XcodeVersion if xcode_version < '0500' XCODE_ARCHS_DEFAULT_CACHE XcodeArchsDefault '$ ARCHS_STANDARD ' XcodeArchsVariableMapping ['i386'] XcodeArchsVariableMapping ['i386'] XcodeArchsVa...
196
python-test-1731
python
What does the |xcodearchsdefault| object use ?
to expand archs for the installed version of xcode
def Get Xcode Archs Default global XCODE ARCHS DEFAULT CACH Eif XCODE ARCHS DEFAULT CACHE return XCODE ARCHS DEFAULT CACHE xcode version Xcode Version if xcode version < '0500 ' XCODE ARCHS DEFAULT CACHE Xcode Archs Default '$ ARCHS STANDARD ' Xcode Archs Variable Mapping ['i 386 '] Xcode Archs Variable Mapping ['i 386...
def GetXcodeArchsDefault global XCODE_ARCHS_DEFAULT_CACHEif XCODE_ARCHS_DEFAULT_CACHE return XCODE_ARCHS_DEFAULT_CACHE xcode_version _ XcodeVersion if xcode_version < '0500' XCODE_ARCHS_DEFAULT_CACHE XcodeArchsDefault '$ ARCHS_STANDARD ' XcodeArchsVariableMapping ['i386'] XcodeArchsVariableMapping ['i386'] XcodeArchsVa...
196
python-test-1732
python
What do target_bucket yum repository with packages update ?
from source_repo repository
@dodef update repo package directory target bucket target key source repo packages flocker version distribution package directory create Directory package type distribution package type yield Effect Download S 3 Key Recursively source bucket target bucket source prefix target key target path package directory filter ex...
@dodef update_repo package_directory target_bucket target_key source_repo packages flocker_version distribution package_directory createDirectory package_type distribution package_type yield Effect DownloadS3KeyRecursively source_bucket target_bucket source_prefix target_key target_path package_directory filter_extensi...
111
python-test-1733
python
What updates from source_repo repository ?
target_bucket yum repository with packages
@dodef update repo package directory target bucket target key source repo packages flocker version distribution package directory create Directory package type distribution package type yield Effect Download S 3 Key Recursively source bucket target bucket source prefix target key target path package directory filter ex...
@dodef update_repo package_directory target_bucket target_key source_repo packages flocker_version distribution package_directory createDirectory package_type distribution package_type yield Effect DownloadS3KeyRecursively source_bucket target_bucket source_prefix target_key target_path package_directory filter_extensi...
111
python-test-1734
python
How do a package instal ?
using pip install --prefix
def test install package with prefix script data prefix path script scratch path / 'prefix' result script pip 'install' '--prefix' prefix path '-f' data find links '--no-binary' 'simple' '--no-index' 'simple 1 0' if hasattr sys 'pypy version info' path script scratch / 'prefix' else path script scratch / 'prefix' / 'li...
def test_install_package_with_prefix script data prefix_path script scratch_path / 'prefix' result script pip 'install' '--prefix' prefix_path '-f' data find_links '--no-binary' 'simple' '--no-index' 'simple 1 0' if hasattr sys 'pypy_version_info' path script scratch / 'prefix' else path script scratch / 'prefix' / 'li...
80
python-test-1735
python
What does fixture simulate ?
a clean system with no config / cloned cookiecutters
@pytest fixture scope 'function' def clean system request user config path os path expanduser '~/ cookiecutterrc' user config path backup os path expanduser '~/ cookiecutterrc backup' if os path exists user config path user config found Trueshutil copy user config path user config path backup os remove user config path...
@pytest fixture scope 'function' def clean_system request user_config_path os path expanduser '~/ cookiecutterrc' user_config_path_backup os path expanduser '~/ cookiecutterrc backup' if os path exists user_config_path user_config_found Trueshutil copy user_config_path user_config_path_backup os remove user_config_path...
172
python-test-1736
python
What does the code delete ?
all files older than * time_old * in * path *
def s3 cleanup glob path time old dry run False **runner kwargs runner EMR Job Runner **runner kwargs log info ' Deletingallfilesin%sthatareolderthan%s' % glob path time old for path in runner fs ls glob path bucket name key name parse s3 uri path bucket runner fs get bucket bucket name for key in bucket list key name ...
def _s3_cleanup glob_path time_old dry_run False **runner_kwargs runner EMRJobRunner **runner_kwargs log info 'Deletingallfilesin%sthatareolderthan%s' % glob_path time_old for path in runner fs ls glob_path bucket_name key_name parse_s3_uri path bucket runner fs get_bucket bucket_name for key in bucket list key_name la...
92
python-test-1737
python
What does the code check in the last four seconds ?
the average amount of data in megabytes written to the databases datafiles
def check write to datafiles con warning critical perf data warning warning or 20 critical critical or 40 try data get server status con writes data['dur']['write To Data Files MB']message ' Writetodatafiles % 2f MB' % writes message + performance data perf data [ '% 2f' % writes 'write to data files' warning critical ...
def check_write_to_datafiles con warning critical perf_data warning warning or 20 critical critical or 40 try data get_server_status con writes data['dur']['writeToDataFilesMB']message 'Writetodatafiles % 2fMB' % writes message + performance_data perf_data [ '% 2f' % writes 'write_to_data_files' warning critical ] retu...
72
python-test-1742
python
What does the code launch with the provided title and message ?
a qmessagebox question
def question title msg default True yes Qt Widgets Q Message Box Yesno Qt Widgets Q Message Box Nobuttons yes no if default default yeselse default noparent active window Message Box Qt Widgets Q Message Boxresult Message Box question parent title msg buttons default return result Qt Widgets Q Message Box Yes
def question title msg default True yes QtWidgets QMessageBox Yesno QtWidgets QMessageBox Nobuttons yes no if default default yeselse default noparent active_window MessageBox QtWidgets QMessageBoxresult MessageBox question parent title msg buttons default return result QtWidgets QMessageBox Yes
52
python-test-1743
python
What did the code read ?
a profile file
def load Profile filename all Machines False global settings Listprofile Parser Config Parser Config Parser try profile Parser read filename except Config Parser Parsing Error returnif all Machines n 0while profile Parser has section 'profile %d' % n for set in settings List if set is Preference continuesection 'profil...
def loadProfile filename allMachines False global settingsListprofileParser ConfigParser ConfigParser try profileParser read filename except ConfigParser ParsingError returnif allMachines n 0while profileParser has_section 'profile_%d' % n for set in settingsList if set isPreference continuesection 'profile_%d' % n if ...
143
python-test-1744
python
What do nt start at boot returns true ?
service name
def disable name stop False **kwargs if not enabled name return Falsesvc realpath get svc path name [0 ]down file os path join svc realpath 'down' if stop stop name if not os path exists down file try salt utils fopen down file 'w' close except IO Error log error ' Unabletocreatefile{ 0 }' format down file return False...
def disable name stop False **kwargs if not enabled name return Falsesvc_realpath _get_svc_path name [0]down_file os path join svc_realpath 'down' if stop stop name if not os path exists down_file try salt utils fopen down_file 'w' close except IOError log error 'Unabletocreatefile{0}' format down_file return Falseretu...
60
python-test-1745
python
Where do service name nt start if operation is successfull name the services name stop if true ?
at boot returns true
def disable name stop False **kwargs if not enabled name return Falsesvc realpath get svc path name [0 ]down file os path join svc realpath 'down' if stop stop name if not os path exists down file try salt utils fopen down file 'w' close except IO Error log error ' Unabletocreatefile{ 0 }' format down file return False...
def disable name stop False **kwargs if not enabled name return Falsesvc_realpath _get_svc_path name [0]down_file os path join svc_realpath 'down' if stop stop name if not os path exists down_file try salt utils fopen down_file 'w' close except IOError log error 'Unabletocreatefile{0}' format down_file return Falseretu...
60
python-test-1746
python
Do service name start at boot returns true if operation is successfull name the services name stop if true ?
No
def disable name stop False **kwargs if not enabled name return Falsesvc realpath get svc path name [0 ]down file os path join svc realpath 'down' if stop stop name if not os path exists down file try salt utils fopen down file 'w' close except IO Error log error ' Unabletocreatefile{ 0 }' format down file return False...
def disable name stop False **kwargs if not enabled name return Falsesvc_realpath _get_svc_path name [0]down_file os path join svc_realpath 'down' if stop stop name if not os path exists down_file try salt utils fopen down_file 'w' close except IOError log error 'Unabletocreatefile{0}' format down_file return Falseretu...
60
python-test-1752
python
What does the code get ?
the preferred channels safe for work status
@commands u'getsafeforwork' u'getsfw' @example u' getsfw[channel]' def get channel sfw bot trigger channel trigger group 2 if not channel channel trigger senderif channel is nick return bot say u' getsfwwithnochannelparamisonlypermittedinchannels' channel channel strip sfw bot db get channel value channel u'sfw' if sfw...
@commands u'getsafeforwork' u'getsfw' @example u' getsfw[channel]' def get_channel_sfw bot trigger channel trigger group 2 if not channel channel trigger senderif channel is_nick return bot say u' getsfwwithnochannelparamisonlypermittedinchannels' channel channel strip sfw bot db get_channel_value channel u'sfw' if sfw...
56
python-test-1753
python
What does the code retrieve from the minion ?
the master status
def get master status **connection args mod sys getframe f code co namelog debug '{ 0 }<--' format mod conn connect **connection args if conn is None return []rtnv do query into hash conn 'SHOWMASTERSTATUS' conn close if len rtnv 0 rtnv append [] log debug '{ 0 }-->{ 1 }' format mod len rtnv[ 0 ] return rtnv[ 0 ]
def get_master_status **connection_args mod sys _getframe f_code co_namelog debug '{0}<--' format mod conn _connect **connection_args if conn is None return []rtnv __do_query_into_hash conn 'SHOWMASTERSTATUS' conn close if len rtnv 0 rtnv append [] log debug '{0}-->{1}' format mod len rtnv[0] return rtnv[0]
61
python-test-1761
python
Where do a random integer sample ?
between low and high
def random integers random state size None low 0 high 1 ndim None dtype 'int 64 ' low tensor as tensor variable low high tensor as tensor variable high ndim size bcast infer ndim bcast ndim size low high op Random Function random integers helper tensor Tensor Type dtype dtype broadcastable bcast return op random state ...
def random_integers random_state size None low 0 high 1 ndim None dtype 'int64' low tensor as_tensor_variable low high tensor as_tensor_variable high ndim size bcast _infer_ndim_bcast ndim size low high op RandomFunction random_integers_helper tensor TensorType dtype dtype broadcastable bcast return op random_state siz...
59
python-test-1762
python
What samples between low and high ?
a random integer
def random integers random state size None low 0 high 1 ndim None dtype 'int 64 ' low tensor as tensor variable low high tensor as tensor variable high ndim size bcast infer ndim bcast ndim size low high op Random Function random integers helper tensor Tensor Type dtype dtype broadcastable bcast return op random state ...
def random_integers random_state size None low 0 high 1 ndim None dtype 'int64' low tensor as_tensor_variable low high tensor as_tensor_variable high ndim size bcast _infer_ndim_bcast ndim size low high op RandomFunction random_integers_helper tensor TensorType dtype dtype broadcastable bcast return op random_state siz...
59
python-test-1767
python
What does the code establish ?
a default - setting listener
def default listener col attr default @event listens for col attr 'init scalar' retval True propagate True def init scalar target value dict if default is callable value default arg None elif default is scalar value default argelse raise Not Implemented Error " Can'tinvokepre-defaultfora SQL-levelcolumndefault" dict [c...
def default_listener col_attr default @event listens_for col_attr 'init_scalar' retval True propagate True def init_scalar target value dict_ if default is_callable value default arg None elif default is_scalar value default argelse raise NotImplementedError "Can'tinvokepre-defaultforaSQL-levelcolumndefault" dict_[col_...
51
python-test-1771
python
What does a step definition call when ?
two subordinate step definitions
def test multiple subordinate steps are run @step ' Iruntwosubordinatesteps' def two subordinate steps step step behave as '\n When Irunthefirstsub-step\n And Irunthesecondsub-step\n' global first ranglobal second ranfirst ran Falsesecond ran False@step ' Irunthefirstsub-step$' def increment step global first ranfirst ...
def test_multiple_subordinate_steps_are_run @step 'Iruntwosubordinatesteps' def two_subordinate_steps step step behave_as '\nWhenIrunthefirstsub-step\nAndIrunthesecondsub-step\n' global first_ranglobal second_ranfirst_ran Falsesecond_ran False@step 'Irunthefirstsub-step$' def increment step global first_ranfirst_ran Tr...
77
python-test-1773
python
What does the code generate ?
the " friedman # 1 " regression problem
def make friedman 1 n samples 100 n features 10 noise 0 0 random state None if n features < 5 raise Value Error 'n featuresmustbeatleastfive ' generator check random state random state X generator rand n samples n features y 10 * np sin np pi * X[ 0] * X[ 1] + 20 * X[ 2] - 0 5 ** 2 + 10 * X[ 3] + 5 * X[ 4] + noise * ge...
def make_friedman1 n_samples 100 n_features 10 noise 0 0 random_state None if n_features < 5 raise ValueError 'n_featuresmustbeatleastfive ' generator check_random_state random_state X generator rand n_samples n_features y 10 * np sin np pi * X[ 0] * X[ 1] + 20 * X[ 2] - 0 5 ** 2 + 10 * X[ 3] + 5 * X[ 4] + noise * gene...
83
python-test-1777
python
What uses to construct a lazy list - like object that is analogous to map ?
the lazymap class
def apply features feature func toks labeled None if labeled is None labeled toks and isinstance toks[ 0 ] tuple list if labeled def lazy func labeled token return feature func labeled token[ 0 ] labeled token[ 1 ] return Lazy Map lazy func toks else return Lazy Map feature func toks
def apply_features feature_func toks labeled None if labeled is None labeled toks and isinstance toks[0] tuple list if labeled def lazy_func labeled_token return feature_func labeled_token[0] labeled_token[1] return LazyMap lazy_func toks else return LazyMap feature_func toks
52
python-test-1778
python
What do the lazymap class use ?
to construct a lazy list - like object that is analogous to map
def apply features feature func toks labeled None if labeled is None labeled toks and isinstance toks[ 0 ] tuple list if labeled def lazy func labeled token return feature func labeled token[ 0 ] labeled token[ 1 ] return Lazy Map lazy func toks else return Lazy Map feature func toks
def apply_features feature_func toks labeled None if labeled is None labeled toks and isinstance toks[0] tuple list if labeled def lazy_func labeled_token return feature_func labeled_token[0] labeled_token[1] return LazyMap lazy_func toks else return LazyMap feature_func toks
52
python-test-1779
python
What does the code remove ?
an installed feature
def remove feature remove payload False restart False mgmt tools ''if salt utils version cmp grains ['osversion'] '6 2' > 0 mgmt tools '- Include Management Tools'rmv ''if remove payload rmv '- Remove'rst ''if restart rst '- Restart'cmd ' Remove- Windows Feature- Name{ 0 }{ 1 }{ 2 }{ 3 }- Error Action Silently Continue...
def remove feature remove_payload False restart False mgmt_tools ''if salt utils version_cmp __grains__['osversion'] '6 2' > 0 mgmt_tools '-IncludeManagementTools'rmv ''if remove_payload rmv '-Remove'rst ''if restart rst '-Restart'cmd 'Remove-WindowsFeature-Name{0}{1}{2}{3}-ErrorActionSilentlyContinue-WarningActionSile...
131
python-test-1780
python
What does the code generate ?
an obfuscated version of pwnstallers utils
def pwnstaller Generate Utils H method Subs code '#include"launch h"\n'code + 'voidinit launcher void \n'code + 'intget thisfile char*%s constchar*%s \n' % helpers random String helpers random String code + 'int Create Act Context char*%s char*%s \n' % helpers random String helpers random String code + 'void Release Ac...
def pwnstallerGenerateUtilsH methodSubs code '#include"launch h"\n'code + 'voidinit_launcher void \n'code + 'intget_thisfile char*%s constchar*%s \n' % helpers randomString helpers randomString code + 'intCreateActContext char*%s char*%s \n' % helpers randomString helpers randomString code + 'voidReleaseActContext void...
126
python-test-1781
python
What does the code expand into a list of strings ?
an ip address pattern
def expand ipaddress pattern string family if family not in [4 6] raise Exception ' Invalid I Paddressfamily {}' format family if family 4 regex IP 4 EXPANSION PATTER Nbase 10 else regex IP 6 EXPANSION PATTER Nbase 16 lead pattern remnant re split regex string maxsplit 1 x y pattern split '-' for i in range int x base ...
def expand_ipaddress_pattern string family if family not in [4 6] raise Exception 'InvalidIPaddressfamily {}' format family if family 4 regex IP4_EXPANSION_PATTERNbase 10else regex IP6_EXPANSION_PATTERNbase 16 lead pattern remnant re split regex string maxsplit 1 x y pattern split '-' for i in range int x base int y ba...
105
python-test-1785
python
What do class decorator allow ?
the decorated class to be serialized by the migrations subsystem
def deconstructible *args **kwargs path kwargs pop 'path' None def decorator klass def new cls *args **kwargs obj super klass cls new cls obj constructor args args kwargs return objdef deconstruct obj '\n Returnsa 3 -tupleofclassimportpath positionalarguments \nandkeywordarguments \n'if path module name name path rpart...
def deconstructible *args **kwargs path kwargs pop 'path' None def decorator klass def __new__ cls *args **kwargs obj super klass cls __new__ cls obj _constructor_args args kwargs return objdef deconstruct obj '\nReturnsa3-tupleofclassimportpath positionalarguments \nandkeywordarguments \n'if path module_name _ name pa...
122
python-test-1786
python
What do internet gateway fail ?
to detach w/ wrong vpc
@mock ec 2 def test igw detach wrong vpc conn boto connect vpc u'the key' u'the secret' igw conn create internet gateway vpc 1 conn create vpc VPC CIDR vpc 2 conn create vpc VPC CIDR conn attach internet gateway igw id vpc 1 id with assert raises EC 2 Response Error as cm conn detach internet gateway igw id vpc 2 id cm...
@mock_ec2def test_igw_detach_wrong_vpc conn boto connect_vpc u'the_key' u'the_secret' igw conn create_internet_gateway vpc1 conn create_vpc VPC_CIDR vpc2 conn create_vpc VPC_CIDR conn attach_internet_gateway igw id vpc1 id with assert_raises EC2ResponseError as cm conn detach_internet_gateway igw id vpc2 id cm exceptio...
86
python-test-1787
python
What does the code prepare ?
the connection to the django authentication framework
def django auth setup global DJANGO AUTH CLAS Sif DJANGO AUTH CLASS is not None returnif '^model' in opts ['external auth']['django'] django model fullname opts ['external auth']['django']['^model']django model name django model fullname split ' ' [ -1 ]django module name ' ' join django model fullname split ' ' [0 -1 ...
def django_auth_setup global DJANGO_AUTH_CLASSif DJANGO_AUTH_CLASS is not None returnif '^model' in __opts__['external_auth']['django'] django_model_fullname __opts__['external_auth']['django']['^model']django_model_name django_model_fullname split ' ' [ -1 ]django_module_name ' ' join django_model_fullname split ' ' [...
92
python-test-1788
python
What does the code build ?
a navigation item used for example breadcrumbs outputs < li><a href=
def make menu item menu item title **kw menu items config['routes named routes']if menu item not in menu items raise Exception 'menuitem`%s`cannotbefound' % menu item item copy copy menu items[menu item] item update kw active link active item needed item pop 'needed' for need in needed if need not in kw raise Exception...
def _make_menu_item menu_item title **kw _menu_items config['routes named_routes']if menu_item not in _menu_items raise Exception 'menuitem`%s`cannotbefound' % menu_item item copy copy _menu_items[menu_item] item update kw active _link_active item needed item pop 'needed' for need in needed if need not in kw raise Exce...
88
python-test-1790
python
How do an mri coregister ?
with a subjects head shape
def coregistration tabbed False split True scene width 500 inst None subject None subjects dir None guess mri subject None check mayavi version from backend import check backend check backend from coreg gui import Coreg Frame make viewview make view tabbed split scene width gui Coreg Frame inst subject subjects dir gue...
def coregistration tabbed False split True scene_width 500 inst None subject None subjects_dir None guess_mri_subject None _check_mayavi_version from _backend import _check_backend_check_backend from _coreg_gui import CoregFrame _make_viewview _make_view tabbed split scene_width gui CoregFrame inst subject subjects_dir...
61
python-test-1796
python
What sets a fresh default context ?
a sync tasklet
def toplevel func synctaskletfunc synctasklet func @utils wrapping func def add context wrapper *args **kwds ndb debug utils func info func state clear all pending ctx make default context try set context ctx return synctaskletfunc *args **kwds finally set context None ctx flush check success eventloop run return add c...
def toplevel func synctaskletfunc synctasklet func @utils wrapping func def add_context_wrapper *args **kwds __ndb_debug__ utils func_info func _state clear_all_pending ctx make_default_context try set_context ctx return synctaskletfunc *args **kwds finally set_context None ctx flush check_success eventloop run return ...
51
python-test-1797
python
What does a sync tasklet set ?
a fresh default context
def toplevel func synctaskletfunc synctasklet func @utils wrapping func def add context wrapper *args **kwds ndb debug utils func info func state clear all pending ctx make default context try set context ctx return synctaskletfunc *args **kwds finally set context None ctx flush check success eventloop run return add c...
def toplevel func synctaskletfunc synctasklet func @utils wrapping func def add_context_wrapper *args **kwds __ndb_debug__ utils func_info func _state clear_all_pending ctx make_default_context try set_context ctx return synctaskletfunc *args **kwds finally set_context None ctx flush check_success eventloop run return ...
51
python-test-1820
python
What does the code delete ?
a dataset relationship
def package relationship delete context data dict model context['model']user context['user'] id id 2 rel get or bust data dict ['subject' 'object' 'type'] pkg 1 model Package get id pkg 2 model Package get id 2 if not pkg 1 raise Not Found ' Subjectpackage%rwasnotfound ' % id if not pkg 2 return Not Found ' Objectpacka...
def package_relationship_delete context data_dict model context['model']user context['user'] id id2 rel _get_or_bust data_dict ['subject' 'object' 'type'] pkg1 model Package get id pkg2 model Package get id2 if not pkg1 raise NotFound 'Subjectpackage%rwasnotfound ' % id if not pkg2 return NotFound 'Objectpackage%rwasno...
120
python-test-1823
python
What extracts all consistent phrase pairs from a word - aligned sentence pair ?
phrase extraction algorithm
def phrase extraction srctext trgtext alignment max phrase length 0 srctext srctext split trgtext trgtext split srclen len srctext trglen len trgtext f aligned [j for j in alignment]max phrase length max phrase length or max srclen trglen bp set for e start in range srclen max idx min srclen e start + max phrase length...
def phrase_extraction srctext trgtext alignment max_phrase_length 0 srctext srctext split trgtext trgtext split srclen len srctext trglen len trgtext f_aligned [j for _ j in alignment]max_phrase_length max_phrase_length or max srclen trglen bp set for e_start in range srclen max_idx min srclen e_start + max_phrase_leng...
125
python-test-1824
python
What does phrase extraction algorithm extract from a word - aligned sentence pair ?
all consistent phrase pairs
def phrase extraction srctext trgtext alignment max phrase length 0 srctext srctext split trgtext trgtext split srclen len srctext trglen len trgtext f aligned [j for j in alignment]max phrase length max phrase length or max srclen trglen bp set for e start in range srclen max idx min srclen e start + max phrase length...
def phrase_extraction srctext trgtext alignment max_phrase_length 0 srctext srctext split trgtext trgtext split srclen len srctext trglen len trgtext f_aligned [j for _ j in alignment]max_phrase_length max_phrase_length or max srclen trglen bp set for e_start in range srclen max_idx min srclen e_start + max_phrase_leng...
125
python-test-1825
python
What does the code setup ?
the flic platform
def setup platform hass config add entities discovery info None import pyflichost config get CONF HOST port config get CONF PORT discovery config get CONF DISCOVERY try client pyflic Flic Client host port except Connection Refused Error LOGGER error ' Failedtoconnecttoflicserver ' returndef new button callback address ...
def setup_platform hass config add_entities discovery_info None import pyflichost config get CONF_HOST port config get CONF_PORT discovery config get CONF_DISCOVERY try client pyflic FlicClient host port except ConnectionRefusedError _LOGGER error 'Failedtoconnecttoflicserver ' returndef new_button_callback address 'Se...
123
python-test-1826
python
Where does decorator replace custom skip test markup ?
in doctests
def doctest skip parser func lines func doc split '\n' new lines []for line in lines match SKIP RE match line if match is None new lines append line continue code space expr match groups try if eval expr func globals code code + space + '#doctest +SKIP' except Attribute Error if eval expr func init globals code code + ...
def doctest_skip_parser func lines func __doc__ split '\n' new_lines []for line in lines match SKIP_RE match line if match is None new_lines append line continue code space expr match groups try if eval expr func __globals__ code code + space + '#doctest +SKIP' except AttributeError if eval expr func __init__ __globals...
76
python-test-1827
python
What does decorator replace in doctests ?
custom skip test markup
def doctest skip parser func lines func doc split '\n' new lines []for line in lines match SKIP RE match line if match is None new lines append line continue code space expr match groups try if eval expr func globals code code + space + '#doctest +SKIP' except Attribute Error if eval expr func init globals code code + ...
def doctest_skip_parser func lines func __doc__ split '\n' new_lines []for line in lines match SKIP_RE match line if match is None new_lines append line continue code space expr match groups try if eval expr func __globals__ code code + space + '#doctest +SKIP' except AttributeError if eval expr func __init__ __globals...
76
python-test-1828
python
What formats into a more manageable and useful dictionary for issue information ?
api return information
def format issue issue ret {'id' issue get 'id' 'issue number' issue get 'number' 'state' issue get 'state' 'title' issue get 'title' 'user' issue get 'user' get 'login' 'html url' issue get 'html url' }assignee issue get 'assignee' if assignee assignee assignee get 'login' labels issue get 'labels' label names []for l...
def _format_issue issue ret {'id' issue get 'id' 'issue_number' issue get 'number' 'state' issue get 'state' 'title' issue get 'title' 'user' issue get 'user' get 'login' 'html_url' issue get 'html_url' }assignee issue get 'assignee' if assignee assignee assignee get 'login' labels issue get 'labels' label_names []for ...
76
python-test-1829
python
What do api return information format ?
into a more manageable and useful dictionary for issue information
def format issue issue ret {'id' issue get 'id' 'issue number' issue get 'number' 'state' issue get 'state' 'title' issue get 'title' 'user' issue get 'user' get 'login' 'html url' issue get 'html url' }assignee issue get 'assignee' if assignee assignee assignee get 'login' labels issue get 'labels' label names []for l...
def _format_issue issue ret {'id' issue get 'id' 'issue_number' issue get 'number' 'state' issue get 'state' 'title' issue get 'title' 'user' issue get 'user' get 'login' 'html_url' issue get 'html_url' }assignee issue get 'assignee' if assignee assignee assignee get 'login' labels issue get 'labels' label_names []for ...
76
python-test-1830
python
What does this decorator apply ?
a testtools attr for each service that gets exercised by a test case
def services *args def decorator f services ['compute' 'image' 'baremetal' 'volume' 'network' 'identity' 'object storage']for service in args if service not in services raise exceptions Invalid Service Tag '%sisnotavalidservice' % service attr type list args f @functools wraps f def wrapper self *func args **func kwarg...
def services *args def decorator f services ['compute' 'image' 'baremetal' 'volume' 'network' 'identity' 'object_storage']for service in args if service not in services raise exceptions InvalidServiceTag '%sisnotavalidservice' % service attr type list args f @functools wraps f def wrapper self *func_args **func_kwargs ...
81
python-test-1831
python
What did a decorator set for each service used in a test case ?
an attr
def services *args def decorator f services ['compute' 'image' 'baremetal' 'volume' 'network' 'identity' 'object storage']for service in args if service not in services raise exceptions Invalid Service Tag '%sisnotavalidservice' % service attr type list args f @functools wraps f def wrapper self *func args **func kwarg...
def services *args def decorator f services ['compute' 'image' 'baremetal' 'volume' 'network' 'identity' 'object_storage']for service in args if service not in services raise exceptions InvalidServiceTag '%sisnotavalidservice' % service attr type list args f @functools wraps f def wrapper self *func_args **func_kwargs ...
81
python-test-1838
python
When does race condition test ?
when downloading items
@with sitldef test 227 connpath vehicle connect connpath wait ready True def assert commands count vehicle commands download vehicle commands wait ready assert equals len vehicle commands count assert commands 0 vehicle commands add Command 0 0 0 mavutil mavlink MAV FRAME GLOBAL RELATIVE ALT mavutil mavlink MAV CMD NAV...
@with_sitldef test_227 connpath vehicle connect connpath wait_ready True def assert_commands count vehicle commands download vehicle commands wait_ready assert_equals len vehicle commands count assert_commands 0 vehicle commands add Command 0 0 0 mavutil mavlink MAV_FRAME_GLOBAL_RELATIVE_ALT mavutil mavlink MAV_CMD_NAV...
65
python-test-1842
python
What does the code ensure ?
event source mapping with passed properties is absent
def event source mapping absent name Event Source Arn Function Name region None key None keyid None profile None ret {'name' None 'result' True 'comment' '' 'changes' {}}desc salt ['boto lambda describe event source mapping'] Event Source Arn Event Source Arn Function Name Function Name region region key key keyid keyi...
def event_source_mapping_absent name EventSourceArn FunctionName region None key None keyid None profile None ret {'name' None 'result' True 'comment' '' 'changes' {}}desc __salt__['boto_lambda describe_event_source_mapping'] EventSourceArn EventSourceArn FunctionName FunctionName region region key key keyid keyid prof...
138
python-test-1846
python
What does the code create ?
a new : class : sslobject instance
def wrap socket sock keyfile None certfile None server side None cert reqs None ssl version None ca certs None do handshake on connect None suppress ragged eofs None for arg in ['cert reqs' 'ssl version' 'ca certs' 'do handshake on connect' 'suppress ragged eofs'] if locals [arg] is not None raise Type Error ' Tousearg...
def wrap_socket sock keyfile None certfile None server_side None cert_reqs None ssl_version None ca_certs None do_handshake_on_connect None suppress_ragged_eofs None for arg in ['cert_reqs' 'ssl_version' 'ca_certs' 'do_handshake_on_connect' 'suppress_ragged_eofs'] if locals [arg] is not None raise TypeError 'Touseargum...
69
python-test-1848
python
When does the code extract the contents of a tar or zip file into the directory * dest * ?
at * archive_path *
def unarchive archive path dest if tarfile is tarfile archive path with contextlib closing tarfile open archive path 'r' as archive archive extractall dest elif is zipfile archive path with contextlib closing Zip File archive path 'r' as archive for name in archive namelist dest path os path join dest *name split '/' d...
def unarchive archive_path dest if tarfile is_tarfile archive_path with contextlib closing tarfile open archive_path 'r' as archive archive extractall dest elif is_zipfile archive_path with contextlib closing ZipFile archive_path 'r' as archive for name in archive namelist dest_path os path join dest *name split '/' di...
97
python-test-1849
python
What does the code extract into the directory * dest * at * archive_path * ?
the contents of a tar or zip file
def unarchive archive path dest if tarfile is tarfile archive path with contextlib closing tarfile open archive path 'r' as archive archive extractall dest elif is zipfile archive path with contextlib closing Zip File archive path 'r' as archive for name in archive namelist dest path os path join dest *name split '/' d...
def unarchive archive_path dest if tarfile is_tarfile archive_path with contextlib closing tarfile open archive_path 'r' as archive archive extractall dest elif is_zipfile archive_path with contextlib closing ZipFile archive_path 'r' as archive for name in archive namelist dest_path os path join dest *name split '/' di...
97
python-test-1851
python
What does a decorator assert ?
that the decorated validator does nt modify its data dict param
def does not modify data dict validator def call and assert key data errors context None if context is None context {}original data copy deepcopy data original errors copy deepcopy errors original context copy deepcopy context result validator key data errors context context assert data original data ' Shouldnotmodifyd...
def does_not_modify_data_dict validator def call_and_assert key data errors context None if context is None context {}original_data copy deepcopy data original_errors copy deepcopy errors original_context copy deepcopy context result validator key data errors context context assert data original_data 'Shouldnotmodifyda...
73
python-test-1852
python
How is cache deactivated ?
in private - browsing mode
def test cache deactivated private browsing config stub tmpdir config stub data {'storage' {'cache-size' 1024 } 'general' {'private-browsing' True}}disk cache cache Disk Cache str tmpdir metadata Q Network Cache Meta Data metadata set Url Q Url 'http //www example com/' assert metadata is Valid assert disk cache prepar...
def test_cache_deactivated_private_browsing config_stub tmpdir config_stub data {'storage' {'cache-size' 1024} 'general' {'private-browsing' True}}disk_cache cache DiskCache str tmpdir metadata QNetworkCacheMetaData metadata setUrl QUrl 'http //www example com/' assert metadata isValid assert disk_cache prepare metadat...
51
python-test-1853
python
What does the code draw ?
a rounded rectangle
def round rectangle size radius fill width height sizerectangle Image new u'L' size 255 corner round corner radius 255 rectangle paste corner 0 0 rectangle paste corner rotate 90 0 height - radius rectangle paste corner rotate 180 width - radius height - radius rectangle paste corner rotate 270 width - radius 0 return ...
def round_rectangle size radius fill width height sizerectangle Image new u'L' size 255 corner round_corner radius 255 rectangle paste corner 0 0 rectangle paste corner rotate 90 0 height - radius rectangle paste corner rotate 180 width - radius height - radius rectangle paste corner rotate 270 width - radius 0 return ...
55
python-test-1854
python
What do user have ?
access to this descriptor
def has access descriptor user action descriptor course key None def can load "\n NOTE Thisdoesnotcheckthatthestudentisenrolledinthecourse\nthatcontainsthismodule Wemayormaynotwanttoallownon-enrolled\nstudentstoseemodules Ifnot viewsshouldcheckthecourse sowe\ndon'thavetohittheenrollmentstableoneverymoduleload \n"if not...
def _has_access_descriptor user action descriptor course_key None def can_load "\nNOTE Thisdoesnotcheckthatthestudentisenrolledinthecourse\nthatcontainsthismodule Wemayormaynotwanttoallownon-enrolled\nstudentstoseemodules Ifnot viewsshouldcheckthecourse sowe\ndon'thavetohittheenrollmentstableoneverymoduleload \n"if not...
110
python-test-1855
python
When does func evaluate to true ?
before timeout expires
def wait for func timeout first 0 0 step 1 0 text None start time time time end time time time + timeout time sleep first while time time < end time if text logging debug '%s %fsecs ' text time time - start time output func if output return outputtime sleep step return None
def wait_for func timeout first 0 0 step 1 0 text None start_time time time end_time time time + timeout time sleep first while time time < end_time if text logging debug '%s %fsecs ' text time time - start_time output func if output return outputtime sleep step return None
55
python-test-1858
python
What does the code compute ?
an wamp - cra authentication signature from an authentication challenge and a key
def compute wcs key challenge assert type key in [six text type six binary type] assert type challenge in [six text type six binary type] if type key six text type key key encode 'utf 8 ' if type challenge six text type challenge challenge encode 'utf 8 ' sig hmac new key challenge hashlib sha 256 digest return binasci...
def compute_wcs key challenge assert type key in [six text_type six binary_type] assert type challenge in [six text_type six binary_type] if type key six text_type key key encode 'utf8' if type challenge six text_type challenge challenge encode 'utf8' sig hmac new key challenge hashlib sha256 digest return binascii b2a...
66
python-test-1860
python
What does the code extract ?
a set of unique identifiers from the request
def get unique content type object pk name None request None ip None user agent None user None if request if request user is authenticated user request userip user agent Noneelse user Noneip request META get 'REMOTE ADDR' '' user agent request META get 'HTTP USER AGENT' '' [ 255 ]hash text '\n' join unicode x encode 'u...
def get_unique content_type object_pk name None request None ip None user_agent None user None if request if request user is_authenticated user request userip user_agent Noneelse user Noneip request META get 'REMOTE_ADDR' '' user_agent request META get 'HTTP_USER_AGENT' '' [ 255]hash_text '\n' join unicode x encode 'ut...
96
python-test-1861
python
What does the code ensure ?
that the named schema is present in the database
def present dbname name owner None db user None db password None db host None db port None ret {'dbname' dbname 'name' name 'changes' {} 'result' True 'comment' ' Schema{ 0 }isalreadypresentindatabase{ 1 }' format name dbname }db args {'db user' db user 'db password' db password 'db host' db host 'db port' db port}sche...
def present dbname name owner None db_user None db_password None db_host None db_port None ret {'dbname' dbname 'name' name 'changes' {} 'result' True 'comment' 'Schema{0}isalreadypresentindatabase{1}' format name dbname }db_args {'db_user' db_user 'db_password' db_password 'db_host' db_host 'db_port' db_port}schema_at...
127
python-test-1862
python
What do the check if you require more information about payload URL ?
the url below
def get Changes request options None payload json loads request args['payload'][ 0 ] repo url '%s%s' % payload['canon url'] payload['repository']['absolute url'] project request args get 'project' [''] [0 ]changes []for commit in payload['commits'] changes append {'author' commit['raw author'] 'files' [f['file'] for f ...
def getChanges request options None payload json loads request args['payload'][0] repo_url '%s%s' % payload['canon_url'] payload['repository']['absolute_url'] project request args get 'project' [''] [0]changes []for commit in payload['commits'] changes append {'author' commit['raw_author'] 'files' [f['file'] for f in c...
84
python-test-1863
python
What does the code catch if you require more information about payload URL ?
a post request from bitbucket
def get Changes request options None payload json loads request args['payload'][ 0 ] repo url '%s%s' % payload['canon url'] payload['repository']['absolute url'] project request args get 'project' [''] [0 ]changes []for commit in payload['commits'] changes append {'author' commit['raw author'] 'files' [f['file'] for f ...
def getChanges request options None payload json loads request args['payload'][0] repo_url '%s%s' % payload['canon_url'] payload['repository']['absolute_url'] project request args get 'project' [''] [0]changes []for commit in payload['commits'] changes append {'author' commit['raw_author'] 'files' [f['file'] for f in c...
84
python-test-1864
python
What do you require ?
more information about payload URL
def get Changes request options None payload json loads request args['payload'][ 0 ] repo url '%s%s' % payload['canon url'] payload['repository']['absolute url'] project request args get 'project' [''] [0 ]changes []for commit in payload['commits'] changes append {'author' commit['raw author'] 'files' [f['file'] for f ...
def getChanges request options None payload json loads request args['payload'][0] repo_url '%s%s' % payload['canon_url'] payload['repository']['absolute_url'] project request args get 'project' [''] [0]changes []for commit in payload['commits'] changes append {'author' commit['raw_author'] 'files' [f['file'] for f in c...
84
python-test-1866
python
What do the user have ?
the permissions to modify a dataset
def check dataset edition permission authorize get False def inner view func def decorate request *args **kwargs dataset kwargs get 'dataset' if dataset is not None and not authorize get and request method 'GET' Job objects can edit or exception request dataset coordinator return view func request *args **kwargs return...
def check_dataset_edition_permission authorize_get False def inner view_func def decorate request *args **kwargs dataset kwargs get 'dataset' if dataset is not None and not authorize_get and request method 'GET' Job objects can_edit_or_exception request dataset coordinator return view_func request *args **kwargs return...
56
python-test-1867
python
What has decorator ensuring ?
that the user has the permissions to modify a dataset
def check dataset edition permission authorize get False def inner view func def decorate request *args **kwargs dataset kwargs get 'dataset' if dataset is not None and not authorize get and request method 'GET' Job objects can edit or exception request dataset coordinator return view func request *args **kwargs return...
def check_dataset_edition_permission authorize_get False def inner view_func def decorate request *args **kwargs dataset kwargs get 'dataset' if dataset is not None and not authorize_get and request method 'GET' Job objects can_edit_or_exception request dataset coordinator return view_func request *args **kwargs return...
56
python-test-1872
python
When did from accountbroker copy the code ?
before the sstoage_policy_index column was added
def prespi create container table self conn conn executescript "\n CREATETABL Econtainer \n ROWIDINTEGERPRIMARYKEYAUTOINCREMENT \nname TEXT \nput timestamp TEXT \ndelete timestamp TEXT \nobject count INTEGER \nbytes used INTEGER \ndeleted INTEGERDEFAULT 0 \n \n\n CREATEINDE Xix container deleted name ON\ncontainer dele...
def prespi_create_container_table self conn conn executescript "\nCREATETABLEcontainer \nROWIDINTEGERPRIMARYKEYAUTOINCREMENT \nnameTEXT \nput_timestampTEXT \ndelete_timestampTEXT \nobject_countINTEGER \nbytes_usedINTEGER \ndeletedINTEGERDEFAULT0\n \n\nCREATEINDEXix_container_deleted_nameON\ncontainer deleted name \n\nC...
160
python-test-1873
python
What does this policy merge ?
small segments
def MERGE SMALL writer segments from whoosh filedb filereading import Segment Readernewsegments []sorted segment list sorted s doc count all s for s in segments total docs 0for i count seg in enumerate sorted segment list if count > 0 total docs + countif total docs < fib i + 5 reader Segment Reader writer storage writ...
def MERGE_SMALL writer segments from whoosh filedb filereading import SegmentReadernewsegments []sorted_segment_list sorted s doc_count_all s for s in segments total_docs 0for i count seg in enumerate sorted_segment_list if count > 0 total_docs + countif total_docs < fib i + 5 reader SegmentReader writer storage writer...
71
python-test-1874
python
What does the code build ?
standard module data from doctypes
def build standard config module doctype info if not frappe db get value u' Module Def' module frappe throw u' Module Not Found' data []add section data u' Documents' u'fafa-star' [d for d in doctype info if d document type in u' Document' u' Transaction' ] add section data u' Setup' u'fafa-cog' [d for d in doctype inf...
def build_standard_config module doctype_info if not frappe db get_value u'ModuleDef' module frappe throw _ u'ModuleNotFound' data []add_section data _ u'Documents' u'fafa-star' [d for d in doctype_info if d document_type in u'Document' u'Transaction' ] add_section data _ u'Setup' u'fafa-cog' [d for d in doctype_info i...
86
python-test-1876
python
What does the code generate ?
the rest long_description
def make long description readme path README PAT Hreadme md strip html comments read readme path history md strip html comments read HISTORY PATH license md ' License\n \n\n' + read LICENSE PATH sections [readme md history md license md]md description '\n\n' join sections md ext os path splitext readme path [1 ]md desc...
def make_long_description readme_path README_PATHreadme_md strip_html_comments read readme_path history_md strip_html_comments read HISTORY_PATH license_md 'License\n \n\n' + read LICENSE_PATH sections [readme_md history_md license_md]md_description '\n\n' join sections md_ext os path splitext readme_path [1]md_descrip...
106
python-test-1878
python
What does the code replace with a single string of up to size bytes ?
the first entries in a deque of strings
def merge prefix deque size if len deque 1 and len deque[ 0 ] < size returnprefix []remaining sizewhile deque and remaining > 0 chunk deque popleft if len chunk > remaining deque appendleft chunk[remaining ] chunk chunk[ remaining]prefix append chunk remaining - len chunk if prefix deque appendleft type prefix[ 0 ] joi...
def _merge_prefix deque size if len deque 1 and len deque[0] < size returnprefix []remaining sizewhile deque and remaining > 0 chunk deque popleft if len chunk > remaining deque appendleft chunk[remaining ] chunk chunk[ remaining]prefix append chunk remaining - len chunk if prefix deque appendleft type prefix[0] join p...
61
python-test-1888
python
What does the code generate ?
a return dtrace probe
def return probe from definition df types args df['args']retval type df['retval type']printf specifier type description retval type types ['printf specifier']template Template RETURN PROBE TEMPLATE mapping {' LIBRARY ' df get 'library' '' ' NAME ' df['api'] ' ARGS FORMAT STRING ' arguments format string args types ' RE...
def return_probe_from_definition df types args df['args']retval_type df['retval_type']printf_specifier type_description retval_type types ['printf_specifier']template Template RETURN_PROBE_TEMPLATE mapping {'__LIBRARY__' df get 'library' '' '__NAME__' df['api'] '__ARGS_FORMAT_STRING__' arguments_format_string args type...
83
python-test-1892
python
For what purpose does sampleid return ?
to write to output fasta / qual files ids_bcs_added_field
def get output ids ids bcs added field corrected bc num errors added field max bc errors 1 5 enum val 1 bc corrected flag Noneif added field is None curr added field ''else curr added field added fieldif corrected bc is None curr bc ''else curr bc corrected bclog id ''if num errors > max bc errors sample id ' Unassigne...
def get_output_ids ids_bcs_added_field corrected_bc num_errors added_field max_bc_errors 1 5 enum_val 1 bc_corrected_flag Noneif added_field is None curr_added_field ''else curr_added_field added_fieldif corrected_bc is None curr_bc ''else curr_bc corrected_bclog_id ''if num_errors > max_bc_errors sample_id 'Unassigned...
166
python-test-1895
python
What use the " posix_local " install scheme ?
platforms
def fix local scheme home dir symlink True try import sysconfigexcept Import Error passelse if sysconfig get default scheme 'posix local' local path os path join home dir 'local' if not os path exists local path os mkdir local path for subdir name in os listdir home dir if subdir name 'local' continuecopyfile os path a...
def fix_local_scheme home_dir symlink True try import sysconfigexcept ImportError passelse if sysconfig _get_default_scheme 'posix_local' local_path os path join home_dir 'local' if not os path exists local_path os mkdir local_path for subdir_name in os listdir home_dir if subdir_name 'local' continuecopyfile os path a...
71
python-test-1896
python
What need to be given an additional " local " location ?
platforms that use the " posix_local " install scheme
def fix local scheme home dir symlink True try import sysconfigexcept Import Error passelse if sysconfig get default scheme 'posix local' local path os path join home dir 'local' if not os path exists local path os mkdir local path for subdir name in os listdir home dir if subdir name 'local' continuecopyfile os path a...
def fix_local_scheme home_dir symlink True try import sysconfigexcept ImportError passelse if sysconfig _get_default_scheme 'posix_local' local_path os path join home_dir 'local' if not os path exists local_path os mkdir local_path for subdir_name in os listdir home_dir if subdir_name 'local' continuecopyfile os path a...
71
python-test-1897
python
What do platforms use ?
the " posix_local " install scheme
def fix local scheme home dir symlink True try import sysconfigexcept Import Error passelse if sysconfig get default scheme 'posix local' local path os path join home dir 'local' if not os path exists local path os mkdir local path for subdir name in os listdir home dir if subdir name 'local' continuecopyfile os path a...
def fix_local_scheme home_dir symlink True try import sysconfigexcept ImportError passelse if sysconfig _get_default_scheme 'posix_local' local_path os path join home_dir 'local' if not os path exists local_path os mkdir local_path for subdir_name in os listdir home_dir if subdir_name 'local' continuecopyfile os path a...
71
python-test-1898
python
What do platforms that use the " posix_local " install scheme need ?
to be given an additional " local " location
def fix local scheme home dir symlink True try import sysconfigexcept Import Error passelse if sysconfig get default scheme 'posix local' local path os path join home dir 'local' if not os path exists local path os mkdir local path for subdir name in os listdir home dir if subdir name 'local' continuecopyfile os path a...
def fix_local_scheme home_dir symlink True try import sysconfigexcept ImportError passelse if sysconfig _get_default_scheme 'posix_local' local_path os path join home_dir 'local' if not os path exists local_path os mkdir local_path for subdir_name in os listdir home_dir if subdir_name 'local' continuecopyfile os path a...
71
python-test-1900
python
What does the code perform ?
post - indexing tasks
@taskdef post index new index old index alias index name settings print ' Optimizing updatingsettingsandaliases ' alias ES indices optimize index new index ES indices put settings index new index body settings actions [{'add' {'index' new index 'alias' alias}}]if old index actions append {'remove' {'index' old index 'a...
@taskdef post_index new_index old_index alias index_name settings _print 'Optimizing updatingsettingsandaliases ' alias ES indices optimize index new_index ES indices put_settings index new_index body settings actions [{'add' {'index' new_index 'alias' alias}}]if old_index actions append {'remove' {'index' old_index 'a...
127
python-test-1903
python
What does this function return ?
a persistent l{key }
def get Persistent RSA Key location key Size 4096 location parent makedirs ignore Existing Directory True if not location exists private Key rsa generate private key public exponent 65537 key size key Size backend default backend pem private Key private bytes encoding serialization Encoding PEM format serialization Pri...
def _getPersistentRSAKey location keySize 4096 location parent makedirs ignoreExistingDirectory True if not location exists privateKey rsa generate_private_key public_exponent 65537 key_size keySize backend default_backend pem privateKey private_bytes encoding serialization Encoding PEM format serialization PrivateForm...
87
python-test-1908
python
What does the code expand into proper html usable in either templates or the rich text editor ?
database - representation html
def expand db html html for editor False def replace a tag m attrs extract attrs m group 1 if u'linktype' not in attrs return m group 0 handler get link handler attrs[u'linktype'] return handler expand db attributes attrs for editor def replace embed tag m attrs extract attrs m group 1 handler get embed handler attrs[u...
def expand_db_html html for_editor False def replace_a_tag m attrs extract_attrs m group 1 if u'linktype' not in attrs return m group 0 handler get_link_handler attrs[u'linktype'] return handler expand_db_attributes attrs for_editor def replace_embed_tag m attrs extract_attrs m group 1 handler get_embed_handler attrs[u...
85
python-test-1909
python
Where did the application host ?
on this machine
def wait on app port retries math ceil START APP TIMEOUT / BACKOFF TIME private ip appscale info get private ip url 'http //' + private ip + ' ' + str port + FETCH PATH while retries > 0 try opener urllib 2 build opener No Redirection response opener open url if response code HTTP OK logging warning '{}returned{} Heade...
def wait_on_app port retries math ceil START_APP_TIMEOUT / BACKOFF_TIME private_ip appscale_info get_private_ip url 'http //' + private_ip + ' ' + str port + FETCH_PATH while retries > 0 try opener urllib2 build_opener NoRedirection response opener open url if response code HTTP_OK logging warning '{}returned{} Headers...
90
python-test-1911
python
What will the code construct ?
a tracecomponentdb
def to trace component db component if not isinstance component basestring dict print type component raise Value Error ' Expectedcomponenttobestrordict' object id component if isinstance component basestring else component['id'] ref component get 'ref' '' if isinstance component dict else '' caused by component get 'ca...
def _to_trace_component_db component if not isinstance component basestring dict print type component raise ValueError 'Expectedcomponenttobestrordict' object_id component if isinstance component basestring else component['id'] ref component get 'ref' '' if isinstance component dict else '' caused_by component get 'cau...
67
python-test-1915
python
What does the code show ?
the settings as parsed from the config file
def vhosts cmd '{ 0 }-S' format detect os ret {}namevhost ''out salt ['cmd run'] cmd for line in out splitlines if not line continuecomps line split if 'isa Name Virtual Host' in line namevhost comps[ 0 ]ret[namevhost] {}else if comps[ 0 ] 'default' ret[namevhost]['default'] {}ret[namevhost]['default']['vhost'] comps[ ...
def vhosts cmd '{0}-S' format _detect_os ret {}namevhost ''out __salt__['cmd run'] cmd for line in out splitlines if not line continuecomps line split if 'isaNameVirtualHost' in line namevhost comps[0]ret[namevhost] {}else if comps[0] 'default' ret[namevhost]['default'] {}ret[namevhost]['default']['vhost'] comps[2]ret[...
90
python-test-1916
python
How do query execute to interpolate it ?
sql_query
def query sql query vars None processed False if vars is None vars {}db cursor ctx db cursor if not processed sql query vars reparam sql query vars ctx db execute db cursor sql query vars if db cursor description names [x[ 0 ] for x in db cursor description]def iterwrapper row db cursor fetchone while row yield Storage...
def query sql_query vars None processed False if vars is None vars {}db_cursor ctx db cursor if not processed sql_query vars reparam sql_query vars ctx db_execute db_cursor sql_query vars if db_cursor description names [x[0] for x in db_cursor description]def iterwrapper row db_cursor fetchone while row yield Storage d...
107
python-test-1919
python
What does the code determine ?
the average number of steps to reach a certain value
def avg Found After decreasing Target Values lists Of Actual Values batch Size 1 use Median False from scipy import sumnum Lists len lists Of Actual Values longest max list map len lists Of Actual Values res [[ 0 ] for in range num Lists ]for tval in decreasing Target Values for li l in enumerate lists Of Actual Values...
def avgFoundAfter decreasingTargetValues listsOfActualValues batchSize 1 useMedian False from scipy import sumnumLists len listsOfActualValues longest max list map len listsOfActualValues res [[0] for _ in range numLists ]for tval in decreasingTargetValues for li l in enumerate listsOfActualValues lres res[li]found Fal...
114
python-test-1926
python
What does the code show ?
the log for a given event
def eventlog request event 0 if not test user authenticated request return login request next '/cobbler web/eventlog/%s' % str event expired True event info remote get events if event not in event info return Http Response 'eventnotfound' data event info[event]eventname data[ 0 ]eventtime data[ 1 ]eventstate data[ 2 ]e...
def eventlog request event 0 if not test_user_authenticated request return login request next '/cobbler_web/eventlog/%s' % str event expired True event_info remote get_events if event not in event_info return HttpResponse 'eventnotfound' data event_info[event]eventname data[0]eventtime data[1]eventstate data[2]eventlog...
89
python-test-1927
python
When does hmac1 and hmac2 compare ?
after hmacing them again using key
def is Valid HMAC hmac 1 hmac 2 key assert len hmac 1 len hmac 2 double Hmac 1 mycrypto HMAC SHA 256 128 key hmac 1 double Hmac 2 mycrypto HMAC SHA 256 128 key hmac 2 if double Hmac 1 double Hmac 2 return Falselog debug ' Thecomputed HMA Cisvalid ' return True
def isValidHMAC hmac1 hmac2 key assert len hmac1 len hmac2 doubleHmac1 mycrypto HMAC_SHA256_128 key hmac1 doubleHmac2 mycrypto HMAC_SHA256_128 key hmac2 if doubleHmac1 doubleHmac2 return Falselog debug 'ThecomputedHMACisvalid ' return True
55
python-test-1928
python
What yields bytes chunks ?
a chain of iterators over the request - response exchange
def build output stream args env request response output options req h OUT REQ HEAD in output options req b OUT REQ BODY in output options resp h OUT RESP HEAD in output options resp b OUT RESP BODY in output options req req h or req b resp resp h or resp b output [] Stream get stream type env args if req output append...
def build_output_stream args env request response output_options req_h OUT_REQ_HEAD in output_options req_b OUT_REQ_BODY in output_options resp_h OUT_RESP_HEAD in output_options resp_b OUT_RESP_BODY in output_options req req_h or req_b resp resp_h or resp_b output []Stream get_stream_type env args if req output append ...
117
python-test-1929
python
What does a chain of iterators over the request - response exchange yield ?
bytes chunks
def build output stream args env request response output options req h OUT REQ HEAD in output options req b OUT REQ BODY in output options resp h OUT RESP HEAD in output options resp b OUT RESP BODY in output options req req h or req b resp resp h or resp b output [] Stream get stream type env args if req output append...
def build_output_stream args env request response output_options req_h OUT_REQ_HEAD in output_options req_b OUT_REQ_BODY in output_options resp_h OUT_RESP_HEAD in output_options resp_b OUT_RESP_BODY in output_options req req_h or req_b resp resp_h or resp_b output []Stream get_stream_type env args if req output append ...
117
python-test-1930
python
What converts to sql wildcard ?
classic wildcard
def convert search search if not search search ''else search search replace '*' '%' replace '' '%' if search and search startswith '^' search search replace '^' '' search + '%'elif search and search endswith '$' search search replace '$' '' search '%' + search else search '%' + search + '%' return search
def convert_search search if not search search ''else search search replace '*' '%' replace '' '%' if search and search startswith '^' search search replace '^' '' search + '%'elif search and search endswith '$' search search replace '$' '' search '%' + search else search '%' + search + '%' return search
54
python-test-1931
python
What do classic wildcard convert ?
to sql wildcard
def convert search search if not search search ''else search search replace '*' '%' replace '' '%' if search and search startswith '^' search search replace '^' '' search + '%'elif search and search endswith '$' search search replace '$' '' search '%' + search else search '%' + search + '%' return search
def convert_search search if not search search ''else search search replace '*' '%' replace '' '%' if search and search startswith '^' search search replace '^' '' search + '%'elif search and search endswith '$' search search replace '$' '' search '%' + search else search '%' + search + '%' return search
54
python-test-1932
python
How does the code apply the filter to the given data ?
in reverse
def inverse data impulse response None filter params {} max gain 2 predefined filter None assert nD data 2 'data' if predefined filter is None filt LPI Filter 2 D impulse response **filter params else filt predefined filter F G filt prepare data min limit F F 1 / F mask np abs F > max gain F[mask] np sign F[mask] * max...
def inverse data impulse_response None filter_params {} max_gain 2 predefined_filter None assert_nD data 2 'data' if predefined_filter is None filt LPIFilter2D impulse_response **filter_params else filt predefined_filter F G filt _prepare data _min_limit F F 1 / F mask np abs F > max_gain F[mask] np sign F[mask] * max_...
77
python-test-1933
python
What does the code apply to the given data in reverse ?
the filter
def inverse data impulse response None filter params {} max gain 2 predefined filter None assert nD data 2 'data' if predefined filter is None filt LPI Filter 2 D impulse response **filter params else filt predefined filter F G filt prepare data min limit F F 1 / F mask np abs F > max gain F[mask] np sign F[mask] * max...
def inverse data impulse_response None filter_params {} max_gain 2 predefined_filter None assert_nD data 2 'data' if predefined_filter is None filt LPIFilter2D impulse_response **filter_params else filt predefined_filter F G filt _prepare data _min_limit F F 1 / F mask np abs F > max_gain F[mask] np sign F[mask] * max_...
77
python-test-1935
python
What d the code find by i d or name ?
a cloud server
def rax find server module rax module server cs rax module cloudserverstry UUID server server cs servers get server except Value Error servers cs servers list search opts dict name '^%s$' % server if not servers module fail json msg ' No Serverwasmatchedbyname tryusingthe Server I Dinstead' if len servers > 1 module fa...
def rax_find_server module rax_module server cs rax_module cloudserverstry UUID server server cs servers get server except ValueError servers cs servers list search_opts dict name '^%s$' % server if not servers module fail_json msg 'NoServerwasmatchedbyname tryusingtheServerIDinstead' if len servers > 1 module fail_jso...
67
python-test-1943
python
What does the code generate ?
a single line of the graph g in adjacency list format
def generate adjlist G delimiter '' directed G is directed seen set for s nbrs in G adjacency line make str s + delimiter for t data in nbrs items if not directed and t in seen continueif G is multigraph for d in data values line + make str t + delimiter else line + make str t + delimiter if not directed seen add s yie...
def generate_adjlist G delimiter '' directed G is_directed seen set for s nbrs in G adjacency line make_str s + delimiter for t data in nbrs items if not directed and t in seen continueif G is_multigraph for d in data values line + make_str t + delimiter else line + make_str t + delimiter if not directed seen add s yie...
73
python-test-1944
python
For what purpose do the signed archive download ?
for a given public extension / version
def download signed request uuid **kwargs extension get object or 404 Extension objects without deleted public uuid uuid version get object or 404 extension versions without deleted public pk kwargs['version id'] log info ' Downloadingpublicadd-on %sversion%sfrom%s' % extension pk version pk version signed file path re...
def download_signed request uuid **kwargs extension get_object_or_404 Extension objects without_deleted public uuid uuid version get_object_or_404 extension versions without_deleted public pk kwargs['version_id'] log info 'Downloadingpublicadd-on %sversion%sfrom%s' % extension pk version pk version signed_file_path ret...
54
python-test-1946
python
What does the code get from image metadata ?
a value of a specified type
def get value from system metadata instance key type default value instance system metadata get key default try return type value except Value Error LOG warning LW ' Metadatavalue% value sfor% key sisnotoftype% type s Usingdefaultvalue% default s ' {'value' value 'key' key 'type' type 'default' default} instance instan...
def get_value_from_system_metadata instance key type default value instance system_metadata get key default try return type value except ValueError LOG warning _LW 'Metadatavalue% value sfor% key sisnotoftype% type s Usingdefaultvalue% default s ' {'value' value 'key' key 'type' type 'default' default} instance instanc...
51
python-test-1947
python
What does the code remove ?
all files that match the sample pattern
def remove samples path RE SAMPLE re compile sample match re I for root dirs files in os walk path for file in files if RE SAMPLE search file path os path join root file try logging info ' Removingunwantedsamplefile%s' path os remove path except logging error T ' Removing%sfailed' clip path path logging info ' Tracebac...
def remove_samples path RE_SAMPLE re compile sample_match re I for root _dirs files in os walk path for file_ in files if RE_SAMPLE search file_ path os path join root file_ try logging info 'Removingunwantedsamplefile%s' path os remove path except logging error T 'Removing%sfailed' clip_path path logging info 'Traceba...
61
python-test-1949
python
For what purpose did shapes and strides broadcast ?
to target_shape
def bc adjust shape strides context builder shapes strides target shape bc shapes []bc strides []zero context get constant types uintp 0 one context get constant types uintp 1 mismatch [builder icmp signed ' ' tar old for tar old in zip target shape shapes ]src is one [builder icmp signed ' ' old one for old in shapes]...
def _bc_adjust_shape_strides context builder shapes strides target_shape bc_shapes []bc_strides []zero context get_constant types uintp 0 one context get_constant types uintp 1 mismatch [builder icmp_signed ' ' tar old for tar old in zip target_shape shapes ]src_is_one [builder icmp_signed ' ' old one for old in shapes...
108
python-test-1950
python
What does the code create ?
a cpuset container
def create container with mbytes and specific cpus name mbytes cpus None root SUPER ROOT io {} move in True timeout 0 need mem containers if not container exists root raise error Autotest Error ' Parentcontainer"%s"doesnotexist' % root if cpus is None cpus get cpus root else cpus set cpus if not cpus raise error Autote...
def create_container_with_mbytes_and_specific_cpus name mbytes cpus None root SUPER_ROOT io {} move_in True timeout 0 need_mem_containers if not container_exists root raise error AutotestError 'Parentcontainer"%s"doesnotexist' % root if cpus is None cpus get_cpus root else cpus set cpus if not cpus raise error Autotest...
101
python-test-1951
python
What does the code move into it ?
jobs current pid
def create container with mbytes and specific cpus name mbytes cpus None root SUPER ROOT io {} move in True timeout 0 need mem containers if not container exists root raise error Autotest Error ' Parentcontainer"%s"doesnotexist' % root if cpus is None cpus get cpus root else cpus set cpus if not cpus raise error Autote...
def create_container_with_mbytes_and_specific_cpus name mbytes cpus None root SUPER_ROOT io {} move_in True timeout 0 need_mem_containers if not container_exists root raise error AutotestError 'Parentcontainer"%s"doesnotexist' % root if cpus is None cpus get_cpus root else cpus set cpus if not cpus raise error Autotest...
101