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-5190
python
What does the code perform ?
a ring migration between the * populations
def mig Ring populations k selection replacement None migarray None nbr demes len populations if migarray is None migarray range 1 nbr demes + [0 ] immigrants [[] for i in xrange nbr demes ]emigrants [[] for i in xrange nbr demes ]for from deme in xrange nbr demes emigrants[from deme] extend selection populations[from ...
def migRing populations k selection replacement None migarray None nbr_demes len populations if migarray is None migarray range 1 nbr_demes + [0] immigrants [[] for i in xrange nbr_demes ]emigrants [[] for i in xrange nbr_demes ]for from_deme in xrange nbr_demes emigrants[from_deme] extend selection populations[from_de...
95
python-test-5196
python
What does the code get ?
the image that matches the required image type
def pr image represent image name format None size table current s3 db pr image libraryquery table original name image name if format query query & table format format if size query query & table width size[ 0 ] & table height size[ 1 ] image current db query select table new name limitby 0 1 first if image return imag...
def pr_image_represent image_name format None size table current s3db pr_image_libraryquery table original_name image_name if format query query & table format format if size query query & table width size[0] & table height size[1] image current db query select table new_name limitby 0 1 first if image return image new...
66
python-test-5197
python
What tests directory ?
biopythons
def find test dir start dir None if not start dir start dir ' 'target os path abspath start dir while True if os path isdir os path join target ' Bio' and os path isdir os path join target ' Tests' return os path abspath os path join target ' Tests' new tmp os path split target if target new breaktarget newraise Value ...
def find_test_dir start_dir None if not start_dir start_dir ' 'target os path abspath start_dir while True if os path isdir os path join target 'Bio' and os path isdir os path join target 'Tests' return os path abspath os path join target 'Tests' new tmp os path split target if target new breaktarget newraise ValueErro...
75
python-test-5198
python
What does the code find ?
the absolute path of biopythons tests directory
def find test dir start dir None if not start dir start dir ' 'target os path abspath start dir while True if os path isdir os path join target ' Bio' and os path isdir os path join target ' Tests' return os path abspath os path join target ' Tests' new tmp os path split target if target new breaktarget newraise Value ...
def find_test_dir start_dir None if not start_dir start_dir ' 'target os path abspath start_dir while True if os path isdir os path join target 'Bio' and os path isdir os path join target 'Tests' return os path abspath os path join target 'Tests' new tmp os path split target if target new breaktarget newraise ValueErro...
75
python-test-5212
python
Do we load arbitrary modules from modules ?
No
def test constructed module Module Type type sys Top Module Module Type ' Top Module' sys modules[' Top Module'] Top Module Sub Module Module Type ' Sub Module' Sub Module Object object Top Module Sub Module Sub Moduletry import Top Module Sub Module Assert Unreachable except Import Error passdel sys modules[' Top Modu...
def test_constructed_module ModuleType type sys TopModule ModuleType 'TopModule' sys modules['TopModule'] TopModuleSubModule ModuleType 'SubModule' SubModule Object object TopModule SubModule SubModuletry import TopModule SubModuleAssertUnreachable except ImportError passdel sys modules['TopModule']
53
python-test-5213
python
What do we nt load from modules ?
arbitrary modules
def test constructed module Module Type type sys Top Module Module Type ' Top Module' sys modules[' Top Module'] Top Module Sub Module Module Type ' Sub Module' Sub Module Object object Top Module Sub Module Sub Moduletry import Top Module Sub Module Assert Unreachable except Import Error passdel sys modules[' Top Modu...
def test_constructed_module ModuleType type sys TopModule ModuleType 'TopModule' sys modules['TopModule'] TopModuleSubModule ModuleType 'SubModule' SubModule Object object TopModule SubModule SubModuletry import TopModule SubModuleAssertUnreachable except ImportError passdel sys modules['TopModule']
53
python-test-5215
python
What read counting ?
readparsers
@pytest mark multithreaddef test num reads threads import threadingdef count reads rparser for in rparser passn threads 4threads []rparser Read Parser utils get test data '100 -reads fq gz' for in range n threads thr threading Thread target count reads args [rparser] threads append thr thr start for thr in threads thr ...
@pytest mark multithreaddef test_num_reads_threads import threadingdef count_reads rparser for _ in rparser passn_threads 4threads []rparser ReadParser utils get_test_data '100-reads fq gz' for _ in range n_threads thr threading Thread target count_reads args [rparser] threads append thr thr start for thr in threads th...
58
python-test-5216
python
What do readparsers read ?
counting
@pytest mark multithreaddef test num reads threads import threadingdef count reads rparser for in rparser passn threads 4threads []rparser Read Parser utils get test data '100 -reads fq gz' for in range n threads thr threading Thread target count reads args [rparser] threads append thr thr start for thr in threads thr ...
@pytest mark multithreaddef test_num_reads_threads import threadingdef count_reads rparser for _ in rparser passn_threads 4threads []rparser ReadParser utils get_test_data '100-reads fq gz' for _ in range n_threads thr threading Thread target count_reads args [rparser] threads append thr thr start for thr in threads th...
58
python-test-5219
python
What does the code add to an existing deferred ?
a timeout
def timeout reactor deferred timeout sec reason None def timeout deferred cancel delayed timeout reactor call Later timeout sec timeout if reason is not None def maybe replace reason passthrough if delayed timeout active return passthroughreturn Failure reason deferred add Errback maybe replace reason def abort timeout...
def timeout reactor deferred timeout_sec reason None def _timeout deferred cancel delayed_timeout reactor callLater timeout_sec _timeout if reason is not None def maybe_replace_reason passthrough if delayed_timeout active return passthroughreturn Failure reason deferred addErrback maybe_replace_reason def abort_timeout...
63
python-test-5220
python
What does the code fix ?
the makefile
def fix makefile do apply fixed Falselines open makefile readlines for old new in CHANGES i findline lines new if i > 0 continuei findline lines old if i < 0 print 'fixapplepython 23 Pythoninstallationnotfixed appearsbroken 'print 'fixapplepython 23 missingline ' oldreturn 2lines[i] newfixed Trueif fixed if do apply pr...
def fix makefile do_apply fixed Falselines open makefile readlines for old new in CHANGES i findline lines new if i > 0 continuei findline lines old if i < 0 print 'fixapplepython23 Pythoninstallationnotfixed appearsbroken 'print 'fixapplepython23 missingline ' oldreturn 2lines[i] newfixed Trueif fixed if do_apply prin...
84
python-test-5221
python
What does this parse in the form username : password@hostname : port ?
a host connection string
def parse host connect string hcs if '@' in hcs p re compile ' ?P<username>[^@ ]* ? ?P<password> * ? \\\\ @ ?P<hostname>[^ ]* ? ?P<port>[ 0 - 9 ]* ' else p re compile ' ?P<username> ?P<password> ?P<hostname>[^ ]* ? ?P<port>[ 0 - 9 ]* ' m p search hcs d m groupdict d['password'] d['password'] replace '\\@' '@' return d
def parse_host_connect_string hcs if '@' in hcs p re compile ' ?P<username>[^@ ]* ? ?P<password> * ? \\\\ @ ?P<hostname>[^ ]* ? ?P<port>[0-9]* ' else p re compile ' ?P<username> ?P<password> ?P<hostname>[^ ]* ? ?P<port>[0-9]* ' m p search hcs d m groupdict d['password'] d['password'] replace '\\@' '@' return d
61
python-test-5222
python
How does this parse a host connection string ?
in the form username : password@hostname : port
def parse host connect string hcs if '@' in hcs p re compile ' ?P<username>[^@ ]* ? ?P<password> * ? \\\\ @ ?P<hostname>[^ ]* ? ?P<port>[ 0 - 9 ]* ' else p re compile ' ?P<username> ?P<password> ?P<hostname>[^ ]* ? ?P<port>[ 0 - 9 ]* ' m p search hcs d m groupdict d['password'] d['password'] replace '\\@' '@' return d
def parse_host_connect_string hcs if '@' in hcs p re compile ' ?P<username>[^@ ]* ? ?P<password> * ? \\\\ @ ?P<hostname>[^ ]* ? ?P<port>[0-9]* ' else p re compile ' ?P<username> ?P<password> ?P<hostname>[^ ]* ? ?P<port>[0-9]* ' m p search hcs d m groupdict d['password'] d['password'] replace '\\@' '@' return d
61
python-test-5223
python
What does the code get ?
the presence for a jid
def get presence jid from jid None get show False if not jid raise Invalid Jid Error request xmpp service pb Presence Request response xmpp service pb Presence Response request set jid to str jid if from jid request set from jid to str from jid try apiproxy stub map Make Sync Call 'xmpp' ' Get Presence' request respons...
def get_presence jid from_jid None get_show False if not jid raise InvalidJidError request xmpp_service_pb PresenceRequest response xmpp_service_pb PresenceResponse request set_jid _to_str jid if from_jid request set_from_jid _to_str from_jid try apiproxy_stub_map MakeSyncCall 'xmpp' 'GetPresence' request response exce...
171
python-test-5225
python
What allow you to specify arguments in constructor without having to manipulate the err tuple directly ?
libvirterror exceptions
def make libvirt Error error class msg error code None error domain None error message None error level None str 1 None str 2 None str 3 None int 1 None int 2 None exc error class msg exc err error code error domain error message error level str 1 str 2 str 3 int 1 int 2 return exc
def make_libvirtError error_class msg error_code None error_domain None error_message None error_level None str1 None str2 None str3 None int1 None int2 None exc error_class msg exc err error_code error_domain error_message error_level str1 str2 str3 int1 int2 return exc
60
python-test-5226
python
What do you manipulate directly ?
the err tuple
def make libvirt Error error class msg error code None error domain None error message None error level None str 1 None str 2 None str 3 None int 1 None int 2 None exc error class msg exc err error code error domain error message error level str 1 str 2 str 3 int 1 int 2 return exc
def make_libvirtError error_class msg error_code None error_domain None error_message None error_level None str1 None str2 None str3 None int1 None int2 None exc error_class msg exc err error_code error_domain error_message error_level str1 str2 str3 int1 int2 return exc
60
python-test-5227
python
What do you specify without having to manipulate the err tuple directly ?
arguments in constructor
def make libvirt Error error class msg error code None error domain None error message None error level None str 1 None str 2 None str 3 None int 1 None int 2 None exc error class msg exc err error code error domain error message error level str 1 str 2 str 3 int 1 int 2 return exc
def make_libvirtError error_class msg error_code None error_domain None error_message None error_level None str1 None str2 None str3 None int1 None int2 None exc error_class msg exc err error_code error_domain error_message error_level str1 str2 str3 int1 int2 return exc
60
python-test-5228
python
What do libvirterror exceptions allow ?
you to specify arguments in constructor without having to manipulate the err tuple directly
def make libvirt Error error class msg error code None error domain None error message None error level None str 1 None str 2 None str 3 None int 1 None int 2 None exc error class msg exc err error code error domain error message error level str 1 str 2 str 3 int 1 int 2 return exc
def make_libvirtError error_class msg error_code None error_domain None error_message None error_level None str1 None str2 None str3 None int1 None int2 None exc error_class msg exc err error_code error_domain error_message error_level str1 str2 str3 int1 int2 return exc
60
python-test-5229
python
How do you specify arguments in constructor ?
without having to manipulate the err tuple directly
def make libvirt Error error class msg error code None error domain None error message None error level None str 1 None str 2 None str 3 None int 1 None int 2 None exc error class msg exc err error code error domain error message error level str 1 str 2 str 3 int 1 int 2 return exc
def make_libvirtError error_class msg error_code None error_domain None error_message None error_level None str1 None str2 None str3 None int1 None int2 None exc error_class msg exc err error_code error_domain error_message error_level str1 str2 str3 int1 int2 return exc
60
python-test-5230
python
What does the code get ?
list of states of provider - user combinations
def get provider user states user states []found user auths list models Django Storage user get social auth for user user for enabled provider in provider Registry enabled association Nonefor auth in found user auths if enabled provider match social auth auth association authbreakif enabled provider accepts logins or a...
def get_provider_user_states user states []found_user_auths list models DjangoStorage user get_social_auth_for_user user for enabled_provider in provider Registry enabled association Nonefor auth in found_user_auths if enabled_provider match_social_auth auth association authbreakif enabled_provider accepts_logins or as...
61
python-test-5232
python
What does the code create ?
a vim - friendly string from a group of dicts
def escape inp def conv obj ' Convertobj 'if isinstance obj list rv as unicode '[' + ' ' join conv o for o in obj + ']' elif isinstance obj dict rv as unicode '{' + ' ' join [ '%s %s' % conv key conv value for key value in obj iteritems ] + '}' else rv as unicode '"%s"' % as unicode obj replace '"' '\\"' return rvretur...
def escape inp def conv obj 'Convertobj 'if isinstance obj list rv as_unicode '[' + ' ' join conv o for o in obj + ']' elif isinstance obj dict rv as_unicode '{' + ' ' join [ '%s %s' % conv key conv value for key value in obj iteritems ] + '}' else rv as_unicode '"%s"' % as_unicode obj replace '"' '\\"' return rvreturn...
73
python-test-5235
python
What does the code add to an array parameters data ?
a column of ones
def add constant data prepend True has constant 'skip' if is using pandas data None or is recarray data from statsmodels tsa tsatools import add trendreturn add trend data trend 'c' prepend prepend has constant has constant x np asanyarray data if x ndim 1 x x[ None]elif x ndim > 2 raise Value Error ' Onlyimplementd 2 ...
def add_constant data prepend True has_constant 'skip' if _is_using_pandas data None or _is_recarray data from statsmodels tsa tsatools import add_trendreturn add_trend data trend 'c' prepend prepend has_constant has_constant x np asanyarray data if x ndim 1 x x[ None]elif x ndim > 2 raise ValueError 'Onlyimplementd2-d...
117
python-test-5236
python
What does this return ?
a dict of violations from the safelint report
def get safelint counts filename report contents get report contents filename rule count regex re compile '^ ?P<rule id>[a-z-]+ \\s+ ?P<count>\\d+ violations' re MULTILINE total count regex re compile '^ ?P<count>\\d+ violationstotal' re MULTILINE violations {'rules' {}}for violation match in rule count regex finditer ...
def _get_safelint_counts filename report_contents _get_report_contents filename rule_count_regex re compile '^ ?P<rule_id>[a-z-]+ \\s+ ?P<count>\\d+ violations' re MULTILINE total_count_regex re compile '^ ?P<count>\\d+ violationstotal' re MULTILINE violations {'rules' {}}for violation_match in rule_count_regex findite...
86
python-test-5239
python
What do str->str choose ?
the best one
def select url from video api html c json loads html video dic {}for i in c['mp 4 '] video dic[i['code']] i['http']quality preference list ['sdvd' 'hd' 'dvd' 'sd']url [video dic[quality] for quality in quality preference list if quality in video dic ][ 0 ]html get html url c json loads html return [i['urls'][ 0 ] for i...
def select_url_from_video_api html c json loads html video_dic {}for i in c['mp4'] video_dic[i['code']] i['http']quality_preference_list ['sdvd' 'hd' 'dvd' 'sd']url [video_dic[quality] for quality in quality_preference_list if quality in video_dic ][0]html get_html url c json loads html return [i['urls'][0] for i in c[...
59
python-test-5240
python
What choose the best one ?
str->str
def select url from video api html c json loads html video dic {}for i in c['mp 4 '] video dic[i['code']] i['http']quality preference list ['sdvd' 'hd' 'dvd' 'sd']url [video dic[quality] for quality in quality preference list if quality in video dic ][ 0 ]html get html url c json loads html return [i['urls'][ 0 ] for i...
def select_url_from_video_api html c json loads html video_dic {}for i in c['mp4'] video_dic[i['code']] i['http']quality_preference_list ['sdvd' 'hd' 'dvd' 'sd']url [video_dic[quality] for quality in quality_preference_list if quality in video_dic ][0]html get_html url c json loads html return [i['urls'][0] for i in c[...
59
python-test-5247
python
What does the code generate ?
a buffer lookup function for the right number of dimensions
def buf lookup strided code proto defin name nd args ' ' join [ 'i%d s%d' % i i for i in range nd ] offset '+' join [ 'i%d*s%d' % i i for i in range nd ] proto putln '#define%s type buf %s type char* buf+%s ' % name args offset
def buf_lookup_strided_code proto defin name nd args ' ' join [ 'i%d s%d' % i i for i in range nd ] offset '+' join [ 'i%d*s%d' % i i for i in range nd ] proto putln '#define%s type buf %s type char* buf+%s ' % name args offset
53
python-test-5248
python
What do you want ?
to store its old monitor under a different name and start a new monitor
def push monitor model name transfer experience False save records False assert hasattr model 'monitor' old monitor model monitorsetattr model name old monitor del model monitorif transfer experience monitor Monitor get monitor model assert monitor is not old monitor monitor num batches seen old monitor num batches see...
def push_monitor model name transfer_experience False save_records False assert hasattr model 'monitor' old_monitor model monitorsetattr model name old_monitor del model monitorif transfer_experience monitor Monitor get_monitor model assert monitor is not old_monitor monitor _num_batches_seen old_monitor _num_batches_s...
86
python-test-5249
python
What do you store under a different name ?
its old monitor
def push monitor model name transfer experience False save records False assert hasattr model 'monitor' old monitor model monitorsetattr model name old monitor del model monitorif transfer experience monitor Monitor get monitor model assert monitor is not old monitor monitor num batches seen old monitor num batches see...
def push_monitor model name transfer_experience False save_records False assert hasattr model 'monitor' old_monitor model monitorsetattr model name old_monitor del model monitorif transfer_experience monitor Monitor get_monitor model assert monitor is not old_monitor monitor _num_batches_seen old_monitor _num_batches_s...
86
python-test-5250
python
What do you start ?
a new monitor
def push monitor model name transfer experience False save records False assert hasattr model 'monitor' old monitor model monitorsetattr model name old monitor del model monitorif transfer experience monitor Monitor get monitor model assert monitor is not old monitor monitor num batches seen old monitor num batches see...
def push_monitor model name transfer_experience False save_records False assert hasattr model 'monitor' old_monitor model monitorsetattr model name old_monitor del model monitorif transfer_experience monitor Monitor get_monitor model assert monitor is not old_monitor monitor _num_batches_seen old_monitor _num_batches_s...
86
python-test-5251
python
How do you store its old monitor ?
under a different name
def push monitor model name transfer experience False save records False assert hasattr model 'monitor' old monitor model monitorsetattr model name old monitor del model monitorif transfer experience monitor Monitor get monitor model assert monitor is not old monitor monitor num batches seen old monitor num batches see...
def push_monitor model name transfer_experience False save_records False assert hasattr model 'monitor' old_monitor model monitorsetattr model name old_monitor del model monitorif transfer_experience monitor Monitor get_monitor model assert monitor is not old_monitor monitor _num_batches_seen old_monitor _num_batches_s...
86
python-test-5253
python
What does the code execute ?
the equivalent of get_sql_reset in the current database
def reset app interactive True from django db import connection transactionfrom django conf import settingsapp name app name split ' ' [ -2 ]disable termcolors check for validation errors app sql list get sql reset app if interactive confirm raw input '\n Youhaverequestedadatabasereset \n Thiswill IRREVERSIBLYDESTRO Ya...
def reset app interactive True from django db import connection transactionfrom django conf import settingsapp_name app __name__ split ' ' [ -2 ]disable_termcolors _check_for_validation_errors app sql_list get_sql_reset app if interactive confirm raw_input '\nYouhaverequestedadatabasereset \nThiswillIRREVERSIBLYDESTROY...
135
python-test-5254
python
What does the code create ?
a new blockdevicedeployer
def create blockdevicedeployer test case hostname u' 192 0 2 1' node uuid uuid 4 eventually consistent False api loopbackblockdeviceapi for test test case if eventually consistent api Eventually Consistent Block Device API api async api Sync To Threaded Async API Adapter sync api reactor Non Reactor threadpool Non Thre...
def create_blockdevicedeployer test_case hostname u'192 0 2 1' node_uuid uuid4 eventually_consistent False api loopbackblockdeviceapi_for_test test_case if eventually_consistent api EventuallyConsistentBlockDeviceAPI api async_api _SyncToThreadedAsyncAPIAdapter _sync api _reactor NonReactor _threadpool NonThreadPool re...
77
python-test-5259
python
What does the code return ?
the results of a call to system_profiler -xml -detail full spapplicationsdatatype as a dictionary
def applications apps call system profiler 'SP Applications Data Type' appdict {}for a in apps details dict a details pop ' name' if 'last Modified' in details details['last Modified'] details['last Modified'] strftime '%Y-%m-%d%H %M %S' if 'info' in details try details['info'] '{ 0 } {1 }' format details['info'][ 0 ] ...
def applications apps _call_system_profiler 'SPApplicationsDataType' appdict {}for a in apps details dict a details pop '_name' if 'lastModified' in details details['lastModified'] details['lastModified'] strftime '%Y-%m-%d%H %M %S' if 'info' in details try details['info'] '{0} {1}' format details['info'][0] details['i...
76
python-test-5260
python
What does the code create ?
an issue and along with its dependencies
def create issue **kwargs owner kwargs pop 'owner' None if owner is None owner User Factory create project kwargs pop 'project' None if project is None project Project Factory create owner owner defaults {'project' project 'owner' owner 'status' Issue Status Factory create project project 'milestone' Milestone Factory ...
def create_issue **kwargs owner kwargs pop 'owner' None if owner is None owner UserFactory create project kwargs pop 'project' None if project is None project ProjectFactory create owner owner defaults {'project' project 'owner' owner 'status' IssueStatusFactory create project project 'milestone' MilestoneFactory creat...
77
python-test-5266
python
In which direction did the code set the current startup disk ?
to the indicated path
def set startup disk path if path not in list startup disks msg ' Invalidvaluepassedforpath \n Mustbeavalidstartupdiskasfoundinsystem list startup disks \n Passed {0 }' format path raise Salt Invocation Error msg cmd 'systemsetup-setstartupdisk{ 0 }' format path salt utils mac utils execute return result cmd return sal...
def set_startup_disk path if path not in list_startup_disks msg 'Invalidvaluepassedforpath \nMustbeavalidstartupdiskasfoundinsystem list_startup_disks \nPassed {0}' format path raise SaltInvocationError msg cmd 'systemsetup-setstartupdisk{0}' format path salt utils mac_utils execute_return_result cmd return salt utils ...
56
python-test-5267
python
What did the code set to the indicated path ?
the current startup disk
def set startup disk path if path not in list startup disks msg ' Invalidvaluepassedforpath \n Mustbeavalidstartupdiskasfoundinsystem list startup disks \n Passed {0 }' format path raise Salt Invocation Error msg cmd 'systemsetup-setstartupdisk{ 0 }' format path salt utils mac utils execute return result cmd return sal...
def set_startup_disk path if path not in list_startup_disks msg 'Invalidvaluepassedforpath \nMustbeavalidstartupdiskasfoundinsystem list_startup_disks \nPassed {0}' format path raise SaltInvocationError msg cmd 'systemsetup-setstartupdisk{0}' format path salt utils mac_utils execute_return_result cmd return salt utils ...
56
python-test-5268
python
What does the code remove if post processed and finished seeding ?
torrent + data
def check Torrent Finished logger info ' Checkingifanytorrentshavefinishedseedingandcanberemoved' with postprocessor lock my DB db DB Connection results my DB select 'SELECT*fromsnatched WHERE Status " Seed Processed"' for album in results hash album[' Folder Name']albumid album[' Album ID']torrent removed Falseif head...
def checkTorrentFinished logger info 'Checkingifanytorrentshavefinishedseedingandcanberemoved' with postprocessor_lock myDB db DBConnection results myDB select 'SELECT*fromsnatchedWHEREStatus "Seed_Processed"' for album in results hash album['FolderName']albumid album['AlbumID']torrent_removed Falseif headphones CONFIG...
80
python-test-5269
python
What do a function define on monomials ?
admissible order
def monomial key order None gens None if order is None order lexif isinstance order Symbol order str order if isinstance order str try order monomial key[order]except Key Error raise Value Error "supportedmonomialorderingsare'lex' 'grlex'and'grevlex' got%r" % order if hasattr order ' call ' if gens is not None def orde...
def monomial_key order None gens None if order is None order lexif isinstance order Symbol order str order if isinstance order str try order _monomial_key[order]except KeyError raise ValueError "supportedmonomialorderingsare'lex' 'grlex'and'grevlex' got%r" % order if hasattr order '__call__' if gens is not None def _or...
69
python-test-5270
python
What do views have ?
argument usage_key_string
def ensure valid usage key view func @wraps view func def inner request *args **kwargs usage key kwargs get 'usage key string' if usage key is not None try Usage Key from string usage key except Invalid Key Error raise Http 404 response view func request *args **kwargs return responsereturn inner
def ensure_valid_usage_key view_func @wraps view_func def inner request *args **kwargs usage_key kwargs get 'usage_key_string' if usage_key is not None try UsageKey from_string usage_key except InvalidKeyError raise Http404response view_func request *args **kwargs return responsereturn inner
51
python-test-5271
python
How should this decorator be used only ?
with views which have argument usage_key_string
def ensure valid usage key view func @wraps view func def inner request *args **kwargs usage key kwargs get 'usage key string' if usage key is not None try Usage Key from string usage key except Invalid Key Error raise Http 404 response view func request *args **kwargs return responsereturn inner
def ensure_valid_usage_key view_func @wraps view_func def inner request *args **kwargs usage_key kwargs get 'usage_key_string' if usage_key is not None try UsageKey from_string usage_key except InvalidKeyError raise Http404response view_func request *args **kwargs return responsereturn inner
51
python-test-5272
python
What does the code remove from the console output ?
the linux console escape and control sequences
def strip console codes output if '\x 1 b' not in output return outputold word ''return str ''index 0output '\x 1 b[m%s' % output console codes '%G \\[m \\[[\\d ]+[H Jnrm]'while index < len output tmp index 0tmp word ''while len re findall '\x 1 b' tmp word < 2 and index + tmp index < len output tmp word + output[ inde...
def strip_console_codes output if '\x1b' not in output return outputold_word ''return_str ''index 0output '\x1b[m%s' % output console_codes '%G \\[m \\[[\\d ]+[HJnrm]'while index < len output tmp_index 0tmp_word ''while len re findall '\x1b' tmp_word < 2 and index + tmp_index < len output tmp_word + output[ index + tmp...
139
python-test-5274
python
Where do we evaluate kroneckerdelta symbols ?
in the expression assuming einstein summation
def evaluate deltas e accepted functions Add if isinstance e accepted functions return e func *[evaluate deltas arg for arg in e args] elif isinstance e Mul deltas []indices {}for i in e args for s in i free symbols if s in indices indices[s] + 1else indices[s] 0if isinstance i Kronecker Delta deltas append i for d in ...
def evaluate_deltas e accepted_functions Add if isinstance e accepted_functions return e func *[evaluate_deltas arg for arg in e args] elif isinstance e Mul deltas []indices {}for i in e args for s in i free_symbols if s in indices indices[s] + 1else indices[s] 0if isinstance i KroneckerDelta deltas append i for d in d...
115
python-test-5275
python
What is assuming einstein summation ?
kroneckerdelta symbols in the expression
def evaluate deltas e accepted functions Add if isinstance e accepted functions return e func *[evaluate deltas arg for arg in e args] elif isinstance e Mul deltas []indices {}for i in e args for s in i free symbols if s in indices indices[s] + 1else indices[s] 0if isinstance i Kronecker Delta deltas append i for d in ...
def evaluate_deltas e accepted_functions Add if isinstance e accepted_functions return e func *[evaluate_deltas arg for arg in e args] elif isinstance e Mul deltas []indices {}for i in e args for s in i free_symbols if s in indices indices[s] + 1else indices[s] 0if isinstance i KroneckerDelta deltas append i for d in d...
115
python-test-5276
python
What do kroneckerdelta symbols in the expression assume ?
einstein summation
def evaluate deltas e accepted functions Add if isinstance e accepted functions return e func *[evaluate deltas arg for arg in e args] elif isinstance e Mul deltas []indices {}for i in e args for s in i free symbols if s in indices indices[s] + 1else indices[s] 0if isinstance i Kronecker Delta deltas append i for d in ...
def evaluate_deltas e accepted_functions Add if isinstance e accepted_functions return e func *[evaluate_deltas arg for arg in e args] elif isinstance e Mul deltas []indices {}for i in e args for s in i free_symbols if s in indices indices[s] + 1else indices[s] 0if isinstance i KroneckerDelta deltas append i for d in d...
115
python-test-5277
python
What do we evaluate in the expression assuming einstein summation ?
kroneckerdelta symbols
def evaluate deltas e accepted functions Add if isinstance e accepted functions return e func *[evaluate deltas arg for arg in e args] elif isinstance e Mul deltas []indices {}for i in e args for s in i free symbols if s in indices indices[s] + 1else indices[s] 0if isinstance i Kronecker Delta deltas append i for d in ...
def evaluate_deltas e accepted_functions Add if isinstance e accepted_functions return e func *[evaluate_deltas arg for arg in e args] elif isinstance e Mul deltas []indices {}for i in e args for s in i free_symbols if s in indices indices[s] + 1else indices[s] 0if isinstance i KroneckerDelta deltas append i for d in d...
115
python-test-5280
python
What does the code create ?
a checked pmap field
def pmap field key type value type optional False invariant valid initial UNDEFINED factory None input factory factoryclass The Map Checked P Map key type key type value type value type The Map name key type name capitalize + value type name capitalize + 'P Map' if optional def mapping factory argument if argument is N...
def pmap_field key_type value_type optional False invariant _valid initial _UNDEFINED factory None input_factory factoryclass TheMap CheckedPMap __key_type__ key_type__value_type__ value_typeTheMap __name__ key_type __name__ capitalize + value_type __name__ capitalize + 'PMap' if optional def mapping_factory argument i...
111
python-test-5281
python
What does the code create ?
a new httpserver for an application
def Create Server root path login url port template dir None serve address '' allow skipped files False static caching True python path list sys path sdk dir SDK ROOT default partition None frontend port None interactive console True secret hash 'xxx' absolute root path os path realpath root path Fake File Set Allowed ...
def CreateServer root_path login_url port template_dir None serve_address '' allow_skipped_files False static_caching True python_path_list sys path sdk_dir SDK_ROOT default_partition None frontend_port None interactive_console True secret_hash 'xxx' absolute_root_path os path realpath root_path FakeFile SetAllowedPath...
181
python-test-5282
python
What do the index file correspond ?
to _ pos _
def get Index form pos 'noun' def try Substitutions try Substitutions form substitutions lookup 1 dictionary dictionary For pos if lookup and dictionary has key form return dictionary[form]elif substitutions old new substitutions[ 0 ]substitute string replace form old new and substitute form if substitute and dictionar...
def getIndex form pos 'noun' def trySubstitutions trySubstitutions form substitutions lookup 1 dictionary dictionaryFor pos if lookup and dictionary has_key form return dictionary[form]elif substitutions old new substitutions[0]substitute string replace form old new and substitute form if substitute and dictionary has_...
81
python-test-5283
python
What is corresponding to _ pos _ ?
the index file
def get Index form pos 'noun' def try Substitutions try Substitutions form substitutions lookup 1 dictionary dictionary For pos if lookup and dictionary has key form return dictionary[form]elif substitutions old new substitutions[ 0 ]substitute string replace form old new and substitute form if substitute and dictionar...
def getIndex form pos 'noun' def trySubstitutions trySubstitutions form substitutions lookup 1 dictionary dictionaryFor pos if lookup and dictionary has_key form return dictionary[form]elif substitutions old new substitutions[0]substitute string replace form old new and substitute form if substitute and dictionary has_...
81
python-test-5286
python
For what purpose does the code update the password ?
for a given host
@depends HAS PYVMOMI def update host password host username password new password protocol None port None service instance salt utils vmware get service instance host host username username password password protocol protocol port port account manager salt utils vmware get inventory service instance account Manageruser...
@depends HAS_PYVMOMI def update_host_password host username password new_password protocol None port None service_instance salt utils vmware get_service_instance host host username username password password protocol protocol port port account_manager salt utils vmware get_inventory service_instance accountManageruser_...
107
python-test-5287
python
How do data integrity verify ?
by ensuring mac is valid
def verify signed data token data if data startswith MAC MARKER try data data[len MAC MARKER ]mac data json loads base 64 b64 decode data mac compute mac token mac data['serialized data'] if mac mac data['mac'] raise Invalid Mac Error 'invalid MAC expect %s actual %s' % mac data['mac'] mac return json loads mac data['s...
def verify_signed_data token data if data startswith MAC_MARKER try data data[len MAC_MARKER ]mac_data json loads base64 b64decode data mac compute_mac token mac_data['serialized_data'] if mac mac_data['mac'] raise InvalidMacError 'invalidMAC expect %s actual %s' % mac_data['mac'] mac return json loads mac_data['serial...
67
python-test-5288
python
What does the code add ?
documentation annotations to the decorated function
def api doc section uses site False **kwargs def add metadata api function doc api function api doc getattr api function ' api doc' {} if 'extends' in kwargs kwargs['extends'] kwargs['extends'] api docdoc update kwargs doc['uses site'] uses sitedoc['section'] sectiondoc['lineno'] api function func code co firstlinenofi...
def api_doc section uses_site False **kwargs def add_metadata api_function doc api_function _api_doc getattr api_function '_api_doc' {} if 'extends' in kwargs kwargs['extends'] kwargs['extends'] _api_docdoc update kwargs doc['uses_site'] uses_sitedoc['section'] sectiondoc['lineno'] api_function func_code co_firstlineno...
115
python-test-5293
python
What does the code run immediately ?
a scheduled job on the minion
def run job name force False ret {'comment' [] 'result' True}if not name ret['comment'] ' Jobnameisrequired 'ret['result'] Falseschedule list show all True return yaml False if name in schedule data schedule[name]if 'enabled' in data and not data['enabled'] and not force ret['comment'] ' Job{ 0 }isdisabled ' format nam...
def run_job name force False ret {'comment' [] 'result' True}if not name ret['comment'] 'Jobnameisrequired 'ret['result'] Falseschedule list_ show_all True return_yaml False if name in schedule data schedule[name]if 'enabled' in data and not data['enabled'] and not force ret['comment'] 'Job{0}isdisabled ' format name e...
93
python-test-5294
python
How does the texpath setting return ?
with any environment variables
def get texpath def get texpath try texpath get setting sublime platform {} get 'texpath' except Attribute Error exc info sys exc infotry reload sys modules[get texpath module ] texpath get setting sublime platform {} get 'texpath' except reraise *exc info return expand vars texpath if texpath is not None else None ret...
def get_texpath def _get_texpath try texpath get_setting sublime platform {} get 'texpath' except AttributeError exc_info sys exc_infotry reload sys modules[get_texpath __module__] texpath get_setting sublime platform {} get 'texpath' except reraise *exc_info return expand_vars texpath if texpath is not None else None ...
62
python-test-5295
python
What does the code get ?
the amplification value for a particular equalizer frequency band
def libvlc audio equalizer get amp at index p equalizer u band f Cfunctions get 'libvlc audio equalizer get amp at index' None or Cfunction 'libvlc audio equalizer get amp at index' 1 1 None ctypes c float ctypes c void p ctypes c uint return f p equalizer u band
def libvlc_audio_equalizer_get_amp_at_index p_equalizer u_band f _Cfunctions get 'libvlc_audio_equalizer_get_amp_at_index' None or _Cfunction 'libvlc_audio_equalizer_get_amp_at_index' 1 1 None ctypes c_float ctypes c_void_p ctypes c_uint return f p_equalizer u_band
51
python-test-5296
python
What does the code evaluate ?
the residual sum of squares fit for one set of mu values
def one step mu u if np abs mu max > 1 0 return 1 0 compose linear fitting data mu u u['uu'] u['sing'] u['vv'] linalg svd u['M'] u['resi'][ ] u['y'][ ]for p in range u['nfit'] - 1 dot np dot u['uu'][p] u['y'] for k in range u['nterms'] - 1 u['resi'][k] u['resi'][k] - u['uu'][ p k ] * dot return np dot u['resi'] u['resi...
def _one_step mu u if np abs mu max > 1 0 return 1 0_compose_linear_fitting_data mu u u['uu'] u['sing'] u['vv'] linalg svd u['M'] u['resi'][ ] u['y'][ ]for p in range u['nfit'] - 1 dot np dot u['uu'][p] u['y'] for k in range u['nterms'] - 1 u['resi'][k] u['resi'][k] - u['uu'][ p k ] * dot return np dot u['resi'] u['res...
64
python-test-5299
python
What does the code do to find better alphas ?
one iteration of hill climbing
def train iis xs classes features f sharp alphas e empirical max newton iterations newton converge p yx calc p class given x xs classes features alphas N len xs newalphas alphas[ ]for i in range len alphas delta iis solve delta N features[i] f sharp e empirical[i] p yx max newton iterations newton converge newalphas[i]...
def _train_iis xs classes features f_sharp alphas e_empirical max_newton_iterations newton_converge p_yx _calc_p_class_given_x xs classes features alphas N len xs newalphas alphas[ ]for i in range len alphas delta _iis_solve_delta N features[i] f_sharp e_empirical[i] p_yx max_newton_iterations newton_converge newalphas...
59
python-test-5300
python
For what purpose does the code do one iteration of hill climbing ?
to find better alphas
def train iis xs classes features f sharp alphas e empirical max newton iterations newton converge p yx calc p class given x xs classes features alphas N len xs newalphas alphas[ ]for i in range len alphas delta iis solve delta N features[i] f sharp e empirical[i] p yx max newton iterations newton converge newalphas[i]...
def _train_iis xs classes features f_sharp alphas e_empirical max_newton_iterations newton_converge p_yx _calc_p_class_given_x xs classes features alphas N len xs newalphas alphas[ ]for i in range len alphas delta _iis_solve_delta N features[i] f_sharp e_empirical[i] p_yx max_newton_iterations newton_converge newalphas...
59
python-test-5301
python
What is using to insert a newline in emacs mode when ?
control - o
def newline with copy margin event b event current buffercursor start pos b document cursor position colb newline copy margin True b cursor up count 1 cursor end pos b document cursor position colif cursor start pos cursor end pos pos diff cursor start pos - cursor end pos b cursor right count pos diff
def newline_with_copy_margin event b event current_buffercursor_start_pos b document cursor_position_colb newline copy_margin True b cursor_up count 1 cursor_end_pos b document cursor_position_colif cursor_start_pos cursor_end_pos pos_diff cursor_start_pos - cursor_end_pos b cursor_right count pos_diff
55
python-test-5302
python
What do control - o use when ?
to insert a newline in emacs mode
def newline with copy margin event b event current buffercursor start pos b document cursor position colb newline copy margin True b cursor up count 1 cursor end pos b document cursor position colif cursor start pos cursor end pos pos diff cursor start pos - cursor end pos b cursor right count pos diff
def newline_with_copy_margin event b event current_buffercursor_start_pos b document cursor_position_colb newline copy_margin True b cursor_up count 1 cursor_end_pos b document cursor_position_colif cursor_start_pos cursor_end_pos pos_diff cursor_start_pos - cursor_end_pos b cursor_right count pos_diff
55
python-test-5304
python
What does the code provide ?
the number of seconds corresponding to the formatting used for the cputime and etime fields of ps : [ [ dd-]hh:]mm : ss or mm : ss
def parse short time label label days hours minutes seconds '0 ' '0 ' '0 ' '0 ' if '-' in label days label label split '-' 1 time comp label split ' ' if len time comp 3 hours minutes seconds time compelif len time comp 2 minutes seconds time compelse raise Value Error " Invalidtimeformat weexpected'[[dd-]hh ]mm ss'or'...
def parse_short_time_label label days hours minutes seconds '0' '0' '0' '0' if '-' in label days label label split '-' 1 time_comp label split ' ' if len time_comp 3 hours minutes seconds time_compelif len time_comp 2 minutes seconds time_compelse raise ValueError "Invalidtimeformat weexpected'[[dd-]hh ]mm ss'or'mm ss ...
105
python-test-5305
python
Does a fitter support fixed or tied parameters natively ?
No
def model to fit params model fitparam indices list range len model param names if any model fixed values or any model tied values params list model parameters param metrics model param metricsfor idx name in list enumerate model param names [ -1 ] if model fixed[name] or model tied[name] slice param metrics[name][u'sl...
def _model_to_fit_params model fitparam_indices list range len model param_names if any model fixed values or any model tied values params list model parameters param_metrics model _param_metricsfor idx name in list enumerate model param_names [ -1 ] if model fixed[name] or model tied[name] slice_ param_metrics[name][u...
68
python-test-5306
python
What does a fitter nt support natively ?
fixed or tied parameters
def model to fit params model fitparam indices list range len model param names if any model fixed values or any model tied values params list model parameters param metrics model param metricsfor idx name in list enumerate model param names [ -1 ] if model fixed[name] or model tied[name] slice param metrics[name][u'sl...
def _model_to_fit_params model fitparam_indices list range len model param_names if any model fixed values or any model tied values params list model parameters param_metrics model _param_metricsfor idx name in list enumerate model param_names [ -1 ] if model fixed[name] or model tied[name] slice_ param_metrics[name][u...
68
python-test-5307
python
What does the code convert to an array that can be used with a fitter that does nt natively support fixed or tied parameters ?
a model instances parameter array
def model to fit params model fitparam indices list range len model param names if any model fixed values or any model tied values params list model parameters param metrics model param metricsfor idx name in list enumerate model param names [ -1 ] if model fixed[name] or model tied[name] slice param metrics[name][u'sl...
def _model_to_fit_params model fitparam_indices list range len model param_names if any model fixed values or any model tied values params list model parameters param_metrics model _param_metricsfor idx name in list enumerate model param_names [ -1 ] if model fixed[name] or model tied[name] slice_ param_metrics[name][u...
68
python-test-5308
python
How can that be used ?
with a fitter that does nt natively support fixed or tied parameters
def model to fit params model fitparam indices list range len model param names if any model fixed values or any model tied values params list model parameters param metrics model param metricsfor idx name in list enumerate model param names [ -1 ] if model fixed[name] or model tied[name] slice param metrics[name][u'sl...
def _model_to_fit_params model fitparam_indices list range len model param_names if any model fixed values or any model tied values params list model parameters param_metrics model _param_metricsfor idx name in list enumerate model param_names [ -1 ] if model fixed[name] or model tied[name] slice_ param_metrics[name][u...
68
python-test-5309
python
What does nt support fixed or tied parameters natively ?
a fitter
def model to fit params model fitparam indices list range len model param names if any model fixed values or any model tied values params list model parameters param metrics model param metricsfor idx name in list enumerate model param names [ -1 ] if model fixed[name] or model tied[name] slice param metrics[name][u'sl...
def _model_to_fit_params model fitparam_indices list range len model param_names if any model fixed values or any model tied values params list model parameters param_metrics model _param_metricsfor idx name in list enumerate model param_names [ -1 ] if model fixed[name] or model tied[name] slice_ param_metrics[name][u...
68
python-test-5310
python
How does a fitter nt support fixed or tied parameters ?
natively
def model to fit params model fitparam indices list range len model param names if any model fixed values or any model tied values params list model parameters param metrics model param metricsfor idx name in list enumerate model param names [ -1 ] if model fixed[name] or model tied[name] slice param metrics[name][u'sl...
def _model_to_fit_params model fitparam_indices list range len model param_names if any model fixed values or any model tied values params list model parameters param_metrics model _param_metricsfor idx name in list enumerate model param_names [ -1 ] if model fixed[name] or model tied[name] slice_ param_metrics[name][u...
68
python-test-5311
python
What do the file contain ?
the edge list data
def generate graphs with gzip open ATLAS FILE 'rb' as f line f readline while line and line startswith 'GRAPH' graph index int line[ 6 ] rstrip line f readline num nodes int line[ 6 ] rstrip edgelist []line f readline while line and not line startswith 'GRAPH' edgelist append line rstrip line f readline G nx Graph G na...
def _generate_graphs with gzip open ATLAS_FILE 'rb' as f line f readline while line and line startswith 'GRAPH' graph_index int line[6 ] rstrip line f readline num_nodes int line[6 ] rstrip edgelist []line f readline while line and not line startswith 'GRAPH' edgelist append line rstrip line f readline G nx Graph G nam...
86
python-test-5312
python
What runs a basic sanity check on the normal method of a curand_randomstreams object ?
check_normal_basic
def check normal basic shape as symbolic dim as symbolic False rng CURAND Random Streams 234 if shape as symbolic shape constant 10 10 elif dim as symbolic shape 10 constant 10 else shape 10 10 u0 rng normal shape u1 rng normal shape f0 theano function [] u0 mode mode with gpu f1 theano function [] u1 mode mode with gp...
def check_normal_basic shape_as_symbolic dim_as_symbolic False rng CURAND_RandomStreams 234 if shape_as_symbolic shape constant 10 10 elif dim_as_symbolic shape 10 constant 10 else shape 10 10 u0 rng normal shape u1 rng normal shape f0 theano function [] u0 mode mode_with_gpu f1 theano function [] u1 mode mode_with_gpu...
139
python-test-5313
python
What does check_normal_basic run ?
a basic sanity check on the normal method of a curand_randomstreams object
def check normal basic shape as symbolic dim as symbolic False rng CURAND Random Streams 234 if shape as symbolic shape constant 10 10 elif dim as symbolic shape 10 constant 10 else shape 10 10 u0 rng normal shape u1 rng normal shape f0 theano function [] u0 mode mode with gpu f1 theano function [] u1 mode mode with gp...
def check_normal_basic shape_as_symbolic dim_as_symbolic False rng CURAND_RandomStreams 234 if shape_as_symbolic shape constant 10 10 elif dim_as_symbolic shape 10 constant 10 else shape 10 10 u0 rng normal shape u1 rng normal shape f0 theano function [] u0 mode mode_with_gpu f1 theano function [] u1 mode mode_with_gpu...
139
python-test-5316
python
What does this give ops ?
the ability to change the topic
@require chanmsg@require privilege OP u' Youarenotachanneloperator ' @commands u'topic' def topic bot trigger if bot privileges[trigger sender][bot nick] < HALFOP return bot reply u"I'mnotachanneloperator " if not trigger group 2 returnchannel trigger sender lower narg 1mask Nonemask bot db get channel value channel u'...
@require_chanmsg@require_privilege OP u'Youarenotachanneloperator ' @commands u'topic' def topic bot trigger if bot privileges[trigger sender][bot nick] < HALFOP return bot reply u"I'mnotachanneloperator " if not trigger group 2 returnchannel trigger sender lower narg 1mask Nonemask bot db get_channel_value channel u't...
105
python-test-5321
python
What does the code perform ?
a full site build
def build config live server False dump json False dirty False if not dirty log info u' Cleaningsitedirectory' utils clean directory config[u'site dir'] else log warning u"A'dirty'buildisbeingperformed thiswilllikelyleadtoinaccuratenavigationandotherlinkswithinyoursite Thisoptionisdesignedforsitedevelopmentpurposesonly...
def build config live_server False dump_json False dirty False if not dirty log info u'Cleaningsitedirectory' utils clean_directory config[u'site_dir'] else log warning u"A'dirty'buildisbeingperformed thiswilllikelyleadtoinaccuratenavigationandotherlinkswithinyoursite Thisoptionisdesignedforsitedevelopmentpurposesonly ...
124
python-test-5322
python
How did the code read a png file to rgb8 or rgba8 ?
unlike imread
def read png filename x Reader filename try alpha x as Direct [3 ]['alpha']if alpha y x as RGBA 8 [2 ]n 4else y x as RGB 8 [2 ]n 3y np array [yy for yy in y] np uint 8 finally x file close y shape y shape[ 0 ] y shape[ 1 ] // n n return y
def read_png filename x Reader filename try alpha x asDirect [3]['alpha']if alpha y x asRGBA8 [2]n 4else y x asRGB8 [2]n 3y np array [yy for yy in y] np uint8 finally x file close y shape y shape[0] y shape[1] // n n return y
60
python-test-5323
python
By how much did the code read a png file unlike imread ?
to rgb8 or rgba8
def read png filename x Reader filename try alpha x as Direct [3 ]['alpha']if alpha y x as RGBA 8 [2 ]n 4else y x as RGB 8 [2 ]n 3y np array [yy for yy in y] np uint 8 finally x file close y shape y shape[ 0 ] y shape[ 1 ] // n n return y
def read_png filename x Reader filename try alpha x asDirect [3]['alpha']if alpha y x asRGBA8 [2]n 4else y x asRGB8 [2]n 3y np array [yy for yy in y] np uint8 finally x file close y shape y shape[0] y shape[1] // n n return y
60
python-test-5326
python
What does the code validate ?
the name of the bucket against s3 criteria
def validate bucket name name if ' ' in name or len name < 3 or len name > 63 or not name[ -1 ] isalnum return Falseelif ' -' in name or '- ' in name or ' ' in name or not name[ 0 ] isalnum return Falseelif re match '^ [0 - 9 ] [1 - 9 ][ 0 - 9 ] 1[ 0 - 9 ]{ 2 } 2[ 0 - 4 ][ 0 - 9 ] 25 [ 0 - 5 ] \\ {3 } [0 - 9 ] [1 - 9 ]...
def validate_bucket_name name if '_' in name or len name < 3 or len name > 63 or not name[ -1 ] isalnum return Falseelif ' -' in name or '- ' in name or ' ' in name or not name[0] isalnum return Falseelif re match '^ [0-9] [1-9][0-9] 1[0-9]{2} 2[0-4][0-9] 25[0-5] \\ {3} [0-9] [1-9][0-9] 1[0-9]{2} 2[0-4][0-9] 25[0-5] $'...
130
python-test-5328
python
What did the code set ?
a version for the namespace to be loaded
def require version namespace version global versionsrepo GI Repository namespaces repo get loaded namespaces if namespace in namespaces loaded version repo get version namespace if loaded version version raise Value Error ' Namespace%sisalreadyloadedwithversion%s' % namespace loaded version if namespace in versions an...
def require_version namespace version global _versionsrepo GIRepository namespaces repo get_loaded_namespaces if namespace in namespaces loaded_version repo get_version namespace if loaded_version version raise ValueError 'Namespace%sisalreadyloadedwithversion%s' % namespace loaded_version if namespace in _versions and...
85
python-test-5331
python
What does the code add ?
y groove
def add Y Groove derivation negatives x if derivation top Bevel < 0 0 returnbottom derivation height - derivation top Bevel top derivation heightgroove [complex x bottom complex x - derivation top Bevel top complex x + derivation top Bevel top ]triangle mesh add Symmetric Y Path negatives groove 1 0001 * derivation top...
def addYGroove derivation negatives x if derivation topBevel < 0 0 returnbottom derivation height - derivation topBevel top derivation heightgroove [complex x bottom complex x - derivation topBevel top complex x + derivation topBevel top ]triangle_mesh addSymmetricYPath negatives groove 1 0001 * derivation topRight ima...
56
python-test-5334
python
What does the code validate ?
the format of the given bucket_name
def validate gs bucket name bucket name if len bucket name > MAX BUCKET LEN raise Backup Validation Exception ' Bucketnamelengthshouldnotbelongerthan%d' % MAX BUCKET LEN if len bucket name < MIN BUCKET LEN raise Backup Validation Exception ' Bucketnamelengthshouldbelongerthan%d' % MIN BUCKET LEN if bucket name lower st...
def validate_gs_bucket_name bucket_name if len bucket_name > MAX_BUCKET_LEN raise BackupValidationException 'Bucketnamelengthshouldnotbelongerthan%d' % MAX_BUCKET_LEN if len bucket_name < MIN_BUCKET_LEN raise BackupValidationException 'Bucketnamelengthshouldbelongerthan%d' % MIN_BUCKET_LEN if bucket_name lower startswi...
105
python-test-5338
python
Where does a dict fill the blanks ?
in kb notification templates
def context dict revision ready for l10 n False revision approved False diff ''l 10 n revision document revisions filter is ready for localization True approved revision document revisions filter is approved True if ready for l10 n and l10 n count > 1 old rev l10 n order by '-created' [1 ]diff get diff for revision doc...
def context_dict revision ready_for_l10n False revision_approved False diff ''l10n revision document revisions filter is_ready_for_localization True approved revision document revisions filter is_approved True if ready_for_l10n and l10n count > 1 old_rev l10n order_by '-created' [1]diff get_diff_for revision document o...
141
python-test-5341
python
What assumes that matplotlib is executed in a pycrust shell ?
current implementation
def show DEBUG MSG 'show ' 3 None for figwin in Gcf get all fig managers figwin frame Show if show needmain and not matplotlib is interactive wxapp wx Get App if wxapp is not None imlr getattr wxapp ' Is Main Loop Running' lambda False if not imlr wxapp Main Loop show needmain False
def show DEBUG_MSG 'show ' 3 None for figwin in Gcf get_all_fig_managers figwin frame Show if show _needmain and not matplotlib is_interactive wxapp wx GetApp if wxapp is not None imlr getattr wxapp 'IsMainLoopRunning' lambda False if not imlr wxapp MainLoop show _needmain False
55
python-test-5342
python
How is matplotlib executed ?
in a pycrust shell
def show DEBUG MSG 'show ' 3 None for figwin in Gcf get all fig managers figwin frame Show if show needmain and not matplotlib is interactive wxapp wx Get App if wxapp is not None imlr getattr wxapp ' Is Main Loop Running' lambda False if not imlr wxapp Main Loop show needmain False
def show DEBUG_MSG 'show ' 3 None for figwin in Gcf get_all_fig_managers figwin frame Show if show _needmain and not matplotlib is_interactive wxapp wx GetApp if wxapp is not None imlr getattr wxapp 'IsMainLoopRunning' lambda False if not imlr wxapp MainLoop show _needmain False
55
python-test-5343
python
What does current implementation assume ?
that matplotlib is executed in a pycrust shell
def show DEBUG MSG 'show ' 3 None for figwin in Gcf get all fig managers figwin frame Show if show needmain and not matplotlib is interactive wxapp wx Get App if wxapp is not None imlr getattr wxapp ' Is Main Loop Running' lambda False if not imlr wxapp Main Loop show needmain False
def show DEBUG_MSG 'show ' 3 None for figwin in Gcf get_all_fig_managers figwin frame Show if show _needmain and not matplotlib is_interactive wxapp wx GetApp if wxapp is not None imlr getattr wxapp 'IsMainLoopRunning' lambda False if not imlr wxapp MainLoop show _needmain False
55
python-test-5344
python
What will decorator do before remoting ?
the arguments serialization
def serialize args fn def wrapper obj *args **kwargs args [ utils strtime arg if isinstance arg datetime datetime else arg for arg in args]for k v in kwargs items if k 'exc val' and v kwargs[k] six text type v elif k 'exc tb' and v and not isinstance v six string types kwargs[k] '' join traceback format tb v elif isins...
def serialize_args fn def wrapper obj *args **kwargs args [ utils strtime arg if isinstance arg datetime datetime else arg for arg in args]for k v in kwargs items if k 'exc_val' and v kwargs[k] six text_type v elif k 'exc_tb' and v and not isinstance v six string_types kwargs[k] '' join traceback format_tb v elif isins...
111
python-test-5345
python
When will decorator do the arguments serialization ?
before remoting
def serialize args fn def wrapper obj *args **kwargs args [ utils strtime arg if isinstance arg datetime datetime else arg for arg in args]for k v in kwargs items if k 'exc val' and v kwargs[k] six text type v elif k 'exc tb' and v and not isinstance v six string types kwargs[k] '' join traceback format tb v elif isins...
def serialize_args fn def wrapper obj *args **kwargs args [ utils strtime arg if isinstance arg datetime datetime else arg for arg in args]for k v in kwargs items if k 'exc_val' and v kwargs[k] six text_type v elif k 'exc_tb' and v and not isinstance v six string_types kwargs[k] '' join traceback format_tb v elif isins...
111
python-test-5346
python
What does the code create ?
an instance of securityrule from a dict
def create rule instance rule return Security Rule rule['protocol'] rule['source address prefix'] rule['destination address prefix'] rule['access'] rule['direction'] id rule get 'id' None description rule get 'description' None source port range rule get 'source port range' None destination port range rule get 'destina...
def create_rule_instance rule return SecurityRule rule['protocol'] rule['source_address_prefix'] rule['destination_address_prefix'] rule['access'] rule['direction'] id rule get 'id' None description rule get 'description' None source_port_range rule get 'source_port_range' None destination_port_range rule get 'destinat...
67
python-test-5347
python
What does the code setup ?
the limitlessled lights
def setup platform hass config add devices discovery info None from limitlessled bridge import Bridgeconfig rewrite legacy config lights []for bridge conf in config get CONF BRIDGES bridge Bridge bridge conf get CONF HOST port bridge conf get CONF PORT DEFAULT PORT version bridge conf get CONF VERSION DEFAULT VERSION f...
def setup_platform hass config add_devices discovery_info None from limitlessled bridge import Bridgeconfig rewrite_legacy config lights []for bridge_conf in config get CONF_BRIDGES bridge Bridge bridge_conf get CONF_HOST port bridge_conf get CONF_PORT DEFAULT_PORT version bridge_conf get CONF_VERSION DEFAULT_VERSION f...
91
python-test-5350
python
What does the code get ?
a dictionary of resource provider usage by resource class
@webob dec wsgify@util check accept 'application/json' def list usages req context req environ['placement context']uuid util wsgi path item req environ 'uuid' try resource provider objects Resource Provider get by uuid context uuid except exception Not Found as exc raise webob exc HTTP Not Found ' Noresourceproviderwit...
@webob dec wsgify@util check_accept 'application/json' def list_usages req context req environ['placement context']uuid util wsgi_path_item req environ 'uuid' try resource_provider objects ResourceProvider get_by_uuid context uuid except exception NotFound as exc raise webob exc HTTPNotFound _ 'Noresourceproviderwithuu...
96
python-test-5351
python
What does the code get from a cloud - init dict ?
a mime multipart encoded string
def get cloud init mime cloud init if isinstance cloud init six string types cloud init json loads cloud init cloud init email mime multipart MIME Multipart if 'boothooks' in cloud init for script name script in six iteritems cloud init['boothooks'] script email mime text MIME Text script 'cloud-boothook' cloud init at...
def get_cloud_init_mime cloud_init if isinstance cloud_init six string_types cloud_init json loads cloud_init _cloud_init email mime multipart MIMEMultipart if 'boothooks' in cloud_init for script_name script in six iteritems cloud_init['boothooks'] _script email mime text MIMEText script 'cloud-boothook' _cloud_init a...
110
python-test-5354
python
What does the code return ?
a list of subplotspec from the given list of axes
def get subplotspec list axes list grid spec None subplotspec list []for ax in axes list axes or locator ax get axes locator if axes or locator is None axes or locator axif hasattr axes or locator 'get subplotspec' subplotspec axes or locator get subplotspec subplotspec subplotspec get topmost subplotspec gs subplotspe...
def get_subplotspec_list axes_list grid_spec None subplotspec_list []for ax in axes_list axes_or_locator ax get_axes_locator if axes_or_locator is None axes_or_locator axif hasattr axes_or_locator 'get_subplotspec' subplotspec axes_or_locator get_subplotspec subplotspec subplotspec get_topmost_subplotspec gs subplotspe...
81
python-test-5355
python
How does the code stop the flask web server ?
by loading /shutdown
def stop port global client cancelclient cancel Truetry if transparent torification s socket socket s connect '127 0 0 1' port s sendall 'GET/{ 0 s}/shutdown HTTP/ 1 1\r\n\r\n' format shutdown slug else urlopen 'http // 127 0 0 1 {0 d}/{ 1 s}/shutdown' format port shutdown slug read except pass
def stop port global client_cancelclient_cancel Truetry if transparent_torification s socket socket s connect '127 0 0 1' port s sendall 'GET/{0 s}/shutdownHTTP/1 1\r\n\r\n' format shutdown_slug else urlopen 'http //127 0 0 1 {0 d}/{1 s}/shutdown' format port shutdown_slug read except pass
51
python-test-5356
python
What does the code create ?
a new adcustomizerfeed
def Create Customizer Feed client feed name ad customizer feed service client Get Service ' Ad Customizer Feed Service' customizer feed {'feed Name' feed name 'feed Attributes' [{'type' 'STRING' 'name' ' Name'} {'type' 'STRING' 'name' ' Price'} {'type' 'DATE TIME' 'name' ' Date'}]}feed service operation {'operator' 'AD...
def CreateCustomizerFeed client feed_name ad_customizer_feed_service client GetService 'AdCustomizerFeedService' customizer_feed {'feedName' feed_name 'feedAttributes' [{'type' 'STRING' 'name' 'Name'} {'type' 'STRING' 'name' 'Price'} {'type' 'DATE_TIME' 'name' 'Date'}]}feed_service_operation {'operator' 'ADD' 'operand'...
123
python-test-5364
python
What did the code read ?
a run - length encoded run from the given fo with the given header and bit_width
def read rle file obj header bit width debug logging count header >> 1 zero data '\x 00 \x 00 \x 00 \x 00 'width bit width + 7 // 8 data file obj read width data data + zero data[len data ] value struct unpack '<i' data [0 ]if debug logging logger debug u' Read RL Egroupwithvalue%sofbyte-width%sandcount%s' value width ...
def read_rle file_obj header bit_width debug_logging count header >> 1 zero_data '\x00\x00\x00\x00'width bit_width + 7 // 8 data file_obj read width data data + zero_data[len data ] value struct unpack '<i' data [0]if debug_logging logger debug u'ReadRLEgroupwithvalue%sofbyte-width%sandcount%s' value width count for _ ...
67
python-test-5365
python
In which direction do probability calculate ?
from normal distribution paramaters z : float value of z statistic direction : str one of low
def normprob z direction 'two-sided' mean 0 std 1 if direction 'two-sided' if z > 0 return 2 * 1 0 - norm cdf z mean std else return 2 * norm cdf z mean std elif direction 'high' return 1 - norm cdf z mean std elif direction 'low' return norm cdf z mean std else raise Value Error ' Unknowndirection '
def normprob z direction 'two-sided' mean 0 std 1 if direction 'two-sided' if z > 0 return 2 * 1 0 - norm cdf z mean std else return 2 * norm cdf z mean std elif direction 'high' return 1 - norm cdf z mean std elif direction 'low' return norm cdf z mean std else raise ValueError 'Unknowndirection '
63
python-test-5366
python
What does a replacement for internalerror present for the programmer ?
a nice page with lots of debug information
def debugerror if has Templating out str djangoerror else out '<p> You\'vesetweb pytousethefancierdebugerrorerrormessages \nbutthesemessagesrequireyouinstallthe Cheetahtemplate\nsystem Formoreinformation see\n<ahref "http //webpy org/">theweb pywebsite</a> </p>\n\n<p> Inthemeantime here\'saplainolderrormessage </p>\n\n...
def debugerror if _hasTemplating out str djangoerror else out '<p>You\'vesetweb pytousethefancierdebugerrorerrormessages \nbutthesemessagesrequireyouinstalltheCheetahtemplate\nsystem Formoreinformation see\n<ahref "http //webpy org/">theweb pywebsite</a> </p>\n\n<p>Inthemeantime here\'saplainolderrormessage </p>\n\n<pr...
51
python-test-5367
python
What do lists contain ?
the entire spreadsheet
def export spreadsheet client spreadsheet key worksheet id headers cleaned headers get cleaned headers headers spreadsheet lines [headers]rows feed client Get List Feed spreadsheet key worksheet id visibility 'public' projection 'values' while True found data Falsefor row in rows feed entry line []for header idx header...
def _export_spreadsheet client spreadsheet_key worksheet_id headers cleaned_headers _get_cleaned_headers headers spreadsheet_lines [headers]rows_feed client GetListFeed spreadsheet_key worksheet_id visibility 'public' projection 'values' while True found_data Falsefor row in rows_feed entry line []for header_idx header...
138
python-test-5369
python
What are the code ensure ?
there are split points for converting to epub
def split txt txt epub split size kb 0 if epub split size kb > 0 if isinstance txt unicode txt txt encode 'utf- 8 ' length byte len txt chunk size long length byte / int length byte / epub split size kb * 1024 + 2 if len filter lambda x len x > chunk size txt split '\n\n' txt '\n\n' join [split string separator line ch...
def split_txt txt epub_split_size_kb 0 if epub_split_size_kb > 0 if isinstance txt unicode txt txt encode 'utf-8' length_byte len txt chunk_size long length_byte / int length_byte / epub_split_size_kb * 1024 + 2 if len filter lambda x len x > chunk_size txt split '\n\n' txt '\n\n' join [split_string_separator line chun...
88
python-test-5370
python
What does the code expand ?
the authorizedkeysfile expression
def expand authorized keys path path user home converted path ''had escape Falsefor char in path if had escape had escape Falseif char '%' converted path + '%'elif char 'u' converted path + userelif char 'h' converted path + homeelse error ' Authorized Keys Filepath unknowntokencharacter"%{ 0 }"' format char raise Comm...
def _expand_authorized_keys_path path user home converted_path ''had_escape Falsefor char in path if had_escape had_escape Falseif char '%' converted_path + '%'elif char 'u' converted_path + userelif char 'h' converted_path + homeelse error 'AuthorizedKeysFilepath unknowntokencharacter"%{0}"' format char raise CommandE...
80
python-test-5376
python
When do directs for the link follow ?
as long as the redirects are on the given sites
def follow redirects link sites None def follow url return sites None or urlparse urlparse url hostname in sites class Redirect Handler urllib 2 HTTP Redirect Handler def init self self last url Nonedef redirect request self req fp code msg hdrs newurl self last url newurlif not follow newurl return Noner urllib 2 HTTP...
def follow_redirects link sites None def follow url return sites None or urlparse urlparse url hostname in sites class RedirectHandler urllib2 HTTPRedirectHandler def __init__ self self last_url Nonedef redirect_request self req fp code msg hdrs newurl self last_url newurlif not follow newurl return Noner urllib2 HTTPR...
124
python-test-5378
python
What does the code find ?
the highest numbered file in a given directory that matches a given pattern
def find highest files directory unversioned regex files find matching files directory regex get numbers re compile ' \\d+ \\d+ \\d+ ' def max 2 a b ' Returnsthelargerofthetwovalues'av get numbers search os path basename a groups bv get numbers search os path basename b groups ret cmp av[ 0 ] bv[ 0 ] or cmp av[ 1 ] bv[...
def find_highest_files directory unversioned regex files find_matching_files directory regex get_numbers re compile ' \\d+ \\d+ \\d+ ' def max2 a b 'Returnsthelargerofthetwovalues'av get_numbers search os path basename a groups bv get_numbers search os path basename b groups ret cmp av[0] bv[0] or cmp av[1] bv[1] or cm...
103
python-test-5379
python
What does a minimum degree return ?
from the given average degree
def generate min degree gamma average degree max degree tolerance max iters min deg top max degreemin deg bot 1min deg mid min deg top - min deg bot / 2 + min deg bot itrs 0mid avg deg 0while abs mid avg deg - average degree > tolerance if itrs > max iters raise nx Exceeded Max Iterations ' Couldnotmatchaverage degree'...
def _generate_min_degree gamma average_degree max_degree tolerance max_iters min_deg_top max_degreemin_deg_bot 1min_deg_mid min_deg_top - min_deg_bot / 2 + min_deg_bot itrs 0mid_avg_deg 0while abs mid_avg_deg - average_degree > tolerance if itrs > max_iters raise nx ExceededMaxIterations 'Couldnotmatchaverage_degree' m...
151
python-test-5380
python
What returns from the given average degree ?
a minimum degree
def generate min degree gamma average degree max degree tolerance max iters min deg top max degreemin deg bot 1min deg mid min deg top - min deg bot / 2 + min deg bot itrs 0mid avg deg 0while abs mid avg deg - average degree > tolerance if itrs > max iters raise nx Exceeded Max Iterations ' Couldnotmatchaverage degree'...
def _generate_min_degree gamma average_degree max_degree tolerance max_iters min_deg_top max_degreemin_deg_bot 1min_deg_mid min_deg_top - min_deg_bot / 2 + min_deg_bot itrs 0mid_avg_deg 0while abs mid_avg_deg - average_degree > tolerance if itrs > max_iters raise nx ExceededMaxIterations 'Couldnotmatchaverage_degree' m...
151