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-1500
python
What does the code get ?
unique vertexes
def get Unique Vertexes loops vertex Dictionary {}unique Vertexes []for loop in loops for vertex Index vertex in enumerate loop vertex Tuple vertex x vertex y vertex z if vertex Tuple in vertex Dictionary loop[vertex Index] vertex Dictionary[vertex Tuple]else if vertex class Vector 3 Index loop[vertex Index] index len ...
def getUniqueVertexes loops vertexDictionary {}uniqueVertexes []for loop in loops for vertexIndex vertex in enumerate loop vertexTuple vertex x vertex y vertex z if vertexTuple in vertexDictionary loop[vertexIndex] vertexDictionary[vertexTuple]else if vertex __class__ Vector3Index loop[vertexIndex] index len vertexDict...
78
python-test-1510
python
What does the code render ?
a stats series in csv
@allow cross site request@non atomic requestsdef render csv request addon stats fields title None show disclaimer None ts time strftime '%c%z' context {'addon' addon 'timestamp' ts 'title' title 'show disclaimer' show disclaimer}response render request 'stats/csv header txt' context writer Unicode CSV Dict Writer respo...
@allow_cross_site_request@non_atomic_requestsdef render_csv request addon stats fields title None show_disclaimer None ts time strftime '%c%z' context {'addon' addon 'timestamp' ts 'title' title 'show_disclaimer' show_disclaimer}response render request 'stats/csv_header txt' context writer UnicodeCSVDictWriter response...
67
python-test-1514
python
What does the code build ?
the global network script
def build network settings **settings current network settings parse rh config RH NETWORK FILE opts parse network settings settings current network settings try template JINJA get template 'network jinja' except jinja 2 exceptions Template Not Found log error ' Couldnotloadtemplatenetwork jinja' return ''network templa...
def build_network_settings **settings current_network_settings _parse_rh_config _RH_NETWORK_FILE opts _parse_network_settings settings current_network_settings try template JINJA get_template 'network jinja' except jinja2 exceptions TemplateNotFound log error 'Couldnotloadtemplatenetwork jinja' return ''network templat...
65
python-test-1515
python
When do our appropriate resampler return ?
when grouping as well
def get resampler for grouping groupby rule how None fill method None limit None kind None **kwargs tg Time Grouper freq rule **kwargs resampler tg get resampler groupby obj kind kind r resampler get resampler for grouping groupby groupby return maybe process deprecations r how how fill method fill method limit limit
def get_resampler_for_grouping groupby rule how None fill_method None limit None kind None **kwargs tg TimeGrouper freq rule **kwargs resampler tg _get_resampler groupby obj kind kind r resampler _get_resampler_for_grouping groupby groupby return _maybe_process_deprecations r how how fill_method fill_method limit limit
52
python-test-1516
python
What does the code execute on the input individuals ?
a uniform partially matched crossover
def cx Uniform Partialy Matched ind 1 ind 2 indpb size min len ind 1 len ind 2 p1 p2 [0 ] * size [0 ] * size for i in xrange size p1 [ind 1 [i]] ip 2 [ind 2 [i]] ifor i in xrange size if random random < indpb temp 1 ind 1 [i]temp 2 ind 2 [i] ind 1 [i] ind 1 [p 1 [temp 2 ]] temp 2 temp 1 ind 2 [i] ind 2 [p 2 [temp 1 ]] ...
def cxUniformPartialyMatched ind1 ind2 indpb size min len ind1 len ind2 p1 p2 [0] * size [0] * size for i in xrange size p1[ind1[i]] ip2[ind2[i]] ifor i in xrange size if random random < indpb temp1 ind1[i]temp2 ind2[i] ind1[i] ind1[p1[temp2]] temp2 temp1 ind2[i] ind2[p2[temp1]] temp1 temp2 p1[temp1] p1[temp2] p1[temp2...
126
python-test-1521
python
How does the code convert an ipv4 address to network form ?
in text form
def inet aton text parts text split ' ' if len parts 4 raise dns exception Syntax Errorfor part in parts if not part isdigit raise dns exception Syntax Errorif len part > 1 and part[ 0 ] '0 ' raise dns exception Syntax Errortry bytes [int part for part in parts]return struct pack 'BBBB' *bytes except raise dns exceptio...
def inet_aton text parts text split ' ' if len parts 4 raise dns exception SyntaxErrorfor part in parts if not part isdigit raise dns exception SyntaxErrorif len part > 1 and part[0] '0' raise dns exception SyntaxErrortry bytes [int part for part in parts]return struct pack 'BBBB' *bytes except raise dns exception Synt...
62
python-test-1522
python
What does the code remove lease ?
from semaphore path the path in zookeeper where the lock is zk_hosts
def unlock path zk hosts None identifier None max concurrency 1 ephemeral lease False if zk hosts is not None and path not in SEMAPHORE MAP zk get zk conn zk hosts SEMAPHORE MAP[path] Semaphore zk path identifier max leases max concurrency ephemeral lease ephemeral lease if path in SEMAPHORE MAP SEMAPHORE MAP[path] rel...
def unlock path zk_hosts None identifier None max_concurrency 1 ephemeral_lease False if zk_hosts is not None and path not in SEMAPHORE_MAP zk _get_zk_conn zk_hosts SEMAPHORE_MAP[path] _Semaphore zk path identifier max_leases max_concurrency ephemeral_lease ephemeral_lease if path in SEMAPHORE_MAP SEMAPHORE_MAP[path] r...
68
python-test-1523
python
What does the code extend ?
a list of simpletables
def table extend tables keep headers True from copy import deepcopyfor ii t in enumerate tables[ ] t deepcopy t if t[ 0 ] datatype 'header' t[ 0 ][ 0 ] data t titlet[ 0 ][ 0 ] datatype Nonet[ 0 ][ 0 ] row t[ 0 ][ 1 ] rowif not keep headers and ii > 0 for c in t[ 0 ][ 1 ] c data ''if ii 0 table all telse r1 table all[ -...
def table_extend tables keep_headers True from copy import deepcopyfor ii t in enumerate tables[ ] t deepcopy t if t[0] datatype 'header' t[0][0] data t titlet[0][0] _datatype Nonet[0][0] row t[0][1] rowif not keep_headers and ii > 0 for c in t[0][1 ] c data ''if ii 0 table_all telse r1 table_all[ -1 ]r1 add_format 'tx...
97
python-test-1534
python
What manifests in the os ?
new ebs block device
def wait for new device base expected size time limit 60 start time time time elapsed time time time - start time while elapsed time < time limit for device in list set File Path '/sys/block' children - set base device name device basename if device name startswith 'sd' 'xvd' and get device size device name expected si...
def _wait_for_new_device base expected_size time_limit 60 start_time time time elapsed_time time time - start_time while elapsed_time < time_limit for device in list set FilePath '/sys/block' children - set base device_name device basename if device_name startswith 'sd' 'xvd' and _get_device_size device_name expected_s...
133
python-test-1535
python
Where do new ebs block device manifest ?
in the os
def wait for new device base expected size time limit 60 start time time time elapsed time time time - start time while elapsed time < time limit for device in list set File Path '/sys/block' children - set base device name device basename if device name startswith 'sd' 'xvd' and get device size device name expected si...
def _wait_for_new_device base expected_size time_limit 60 start_time time time elapsed_time time time - start_time while elapsed_time < time_limit for device in list set FilePath '/sys/block' children - set base device_name device basename if device_name startswith 'sd' 'xvd' and _get_device_size device_name expected_s...
133
python-test-1536
python
What does a hostname use ?
to contact the server
def get hostname server None version None instance None req servers service pb Get Hostname Request if server req set server server if version req set version version if instance if not isinstance instance basestring long int raise Type Error "'instance'argmustbeoftypebasestring longorint " req set instance '%s' % inst...
def get_hostname server None version None instance None req servers_service_pb GetHostnameRequest if server req set_server server if version req set_version version if instance if not isinstance instance basestring long int raise TypeError "'instance'argmustbeoftypebasestring longorint " req set_instance '%s' % instanc...
114
python-test-1537
python
What does the code take ?
a list of lines
def write incron lines user lines if user 'system' ret {}ret['retcode'] write file INCRON SYSTEM TAB 'salt' '' join lines return retelse path salt utils files mkstemp with salt utils fopen path 'w+' as fp fp writelines lines if grains ['os family'] ' Solaris' and user 'root' salt ['cmd run'] 'chown{ 0 }{ 1 }' format us...
def _write_incron_lines user lines if user 'system' ret {}ret['retcode'] _write_file _INCRON_SYSTEM_TAB 'salt' '' join lines return retelse path salt utils files mkstemp with salt utils fopen path 'w+' as fp_ fp_ writelines lines if __grains__['os_family'] 'Solaris' and user 'root' __salt__['cmd run'] 'chown{0}{1}' for...
80
python-test-1540
python
What does the code create ?
a dummy virtualmachine with 1 vcpu
def create dummy vm name service instance vm folder resource pool datastore vm name 'MARVEL-' + name datastore path '[' + datastore + ']' + vm name vmx file vim vm File Info log Directory None snapshot Directory None suspend Directory None vm Path Name datastore path config vim vm Config Spec name vm name memory MB 128...
def create_dummy_vm name service_instance vm_folder resource_pool datastore vm_name 'MARVEL-' + name datastore_path '[' + datastore + ']' + vm_name vmx_file vim vm FileInfo logDirectory None snapshotDirectory None suspendDirectory None vmPathName datastore_path config vim vm ConfigSpec name vm_name memoryMB 128 numCPUs...
99
python-test-1541
python
What does the code create ?
a native code function
def llvm jit code args expr signature callback type if callback type is None jit LLVM Jit Code signature else jit LLVM Jit Code Callback signature jit create args args jit create function base jit create param dict args strmod jit create function expr if False print 'LLVMIR' print strmod fptr jit compile function strmo...
def _llvm_jit_code args expr signature callback_type if callback_type is None jit LLVMJitCode signature else jit LLVMJitCodeCallback signature jit _create_args args jit _create_function_base jit _create_param_dict args strmod jit _create_function expr if False print 'LLVMIR' print strmod fptr jit _compile_function strm...
57
python-test-1545
python
What does the code delete ?
an entry from the cachedir index
def cachedir index del minion id base None base init cachedir base index file os path join base 'index p' lock file index file if os path exists index file with salt utils fopen index file 'r' as fh index msgpack load fh else returnif minion id in index del index[minion id]with salt utils fopen index file 'w' as fh msg...
def cachedir_index_del minion_id base None base init_cachedir base index_file os path join base 'index p' lock_file index_file if os path exists index_file with salt utils fopen index_file 'r' as fh_ index msgpack load fh_ else returnif minion_id in index del index[minion_id]with salt utils fopen index_file 'w' as fh_ ...
68
python-test-1546
python
What does the code create ?
a plugindummy package
def create Plugin Dummy entrypath plugin Content real plugin Module entrypath create Directory pkg entrypath child 'plugindummy' pkg create Directory if real pkg child ' init py' set Content '' plugs pkg child 'plugins' plugs create Directory if real plugs child ' init py' set Content plugin Init File plugs child plugi...
def _createPluginDummy entrypath pluginContent real pluginModule entrypath createDirectory pkg entrypath child 'plugindummy' pkg createDirectory if real pkg child '__init__ py' setContent '' plugs pkg child 'plugins' plugs createDirectory if real plugs child '__init__ py' setContent pluginInitFile plugs child pluginMod...
62
python-test-1547
python
What does the code ensure ?
empty directories in the base backup are created particularly in the case when postgresql empties the files in those directories in parallel
def test dynamically emptied directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some file bdir join 'afile' some file write '1234567890 ' base dir adir strpath spec parts tar partition partition base dir tar paths []for part in parts for tar info in part rel path os path re...
def test_dynamically_emptied_directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some_file bdir join 'afile' some_file write '1234567890' base_dir adir strpath spec parts tar_partition partition base_dir tar_paths []for part in parts for tar_info in part rel_path os path rel...
73
python-test-1548
python
What empties the files in those directories in parallel when ?
postgresql
def test dynamically emptied directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some file bdir join 'afile' some file write '1234567890 ' base dir adir strpath spec parts tar partition partition base dir tar paths []for part in parts for tar info in part rel path os path re...
def test_dynamically_emptied_directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some_file bdir join 'afile' some_file write '1234567890' base_dir adir strpath spec parts tar_partition partition base_dir tar_paths []for part in parts for tar_info in part rel_path os path rel...
73
python-test-1549
python
What are created in the case when postgresql empties the files in those directories in parallel ?
empty directories in the base backup
def test dynamically emptied directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some file bdir join 'afile' some file write '1234567890 ' base dir adir strpath spec parts tar partition partition base dir tar paths []for part in parts for tar info in part rel path os path re...
def test_dynamically_emptied_directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some_file bdir join 'afile' some_file write '1234567890' base_dir adir strpath spec parts tar_partition partition base_dir tar_paths []for part in parts for tar_info in part rel_path os path rel...
73
python-test-1550
python
Where are empty directories in the base backup created particularly ?
in the case when postgresql empties the files in those directories in parallel
def test dynamically emptied directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some file bdir join 'afile' some file write '1234567890 ' base dir adir strpath spec parts tar partition partition base dir tar paths []for part in parts for tar info in part rel path os path re...
def test_dynamically_emptied_directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some_file bdir join 'afile' some_file write '1234567890' base_dir adir strpath spec parts tar_partition partition base_dir tar_paths []for part in parts for tar_info in part rel_path os path rel...
73
python-test-1551
python
What did postgresql empty in parallel when ?
the files in those directories
def test dynamically emptied directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some file bdir join 'afile' some file write '1234567890 ' base dir adir strpath spec parts tar partition partition base dir tar paths []for part in parts for tar info in part rel path os path re...
def test_dynamically_emptied_directories tmpdir adir tmpdir join 'adir' ensure dir True bdir adir join 'bdir' ensure dir True some_file bdir join 'afile' some_file write '1234567890' base_dir adir strpath spec parts tar_partition partition base_dir tar_paths []for part in parts for tar_info in part rel_path os path rel...
73
python-test-1554
python
What should override a non - redirect one ?
a redirect update added
def test add item redirect update qtbot tmpdir url 'http //www example com/'hist file tmpdir / 'filled-history' hist file write '12345 {}\n' format url hist history Web History hist dir str tmpdir hist name 'filled-history' list hist async read with qtbot assert Not Emitted hist add completion item with qtbot wait Sign...
def test_add_item_redirect_update qtbot tmpdir url 'http //www example com/'hist_file tmpdir / 'filled-history' hist_file write '12345{}\n' format url hist history WebHistory hist_dir str tmpdir hist_name 'filled-history' list hist async_read with qtbot assertNotEmitted hist add_completion_item with qtbot waitSignal hi...
83
python-test-1555
python
What should a redirect update added override ?
a non - redirect one
def test add item redirect update qtbot tmpdir url 'http //www example com/'hist file tmpdir / 'filled-history' hist file write '12345 {}\n' format url hist history Web History hist dir str tmpdir hist name 'filled-history' list hist async read with qtbot assert Not Emitted hist add completion item with qtbot wait Sign...
def test_add_item_redirect_update qtbot tmpdir url 'http //www example com/'hist_file tmpdir / 'filled-history' hist_file write '12345{}\n' format url hist history WebHistory hist_dir str tmpdir hist_name 'filled-history' list hist async_read with qtbot assertNotEmitted hist add_completion_item with qtbot waitSignal hi...
83
python-test-1557
python
What does the code remove ?
followers of an existing viewpoint
@gen coroutinedef Remove Followers client obj store user id device id request request['user id'] user id yield Activity Verify Activity Id client user id device id request['activity']['activity id'] yield gen Task Operation Create And Execute client user id device id ' Remove Followers Operation Execute' request loggin...
@gen coroutinedef RemoveFollowers client obj_store user_id device_id request request['user_id'] user_id yield Activity VerifyActivityId client user_id device_id request['activity']['activity_id'] yield gen Task Operation CreateAndExecute client user_id device_id 'RemoveFollowersOperation Execute' request logging info '...
66
python-test-1563
python
What do file support ?
a high enough version of firefox
def supports firefox file obj apps file obj version apps all if not file obj binary components and not file obj strict compatibility return apps filter max application in SIGN FOR APPS max version int gte version int settings MIN D2 C VERSION else return apps filter max application in [amo FIREFOX id amo ANDROID id] ma...
def supports_firefox file_obj apps file_obj version apps all if not file_obj binary_components and not file_obj strict_compatibility return apps filter max__application__in SIGN_FOR_APPS max__version_int__gte version_int settings MIN_D2C_VERSION else return apps filter max__application__in [amo FIREFOX id amo ANDROID i...
68
python-test-1564
python
What does the code build out of it ?
a transitively closed map
def get redirects redirects filename redirects {}print ' Parsingthe N Tredirectfile' for l line in enumerate BZ 2 File redirects filename split line split if len split 4 print 'ignoringmalformedline ' + line continueredirects[short name split[ 0 ] ] short name split[ 2 ] if l % 1000000 0 print '[%s]line %08 d' % dateti...
def get_redirects redirects_filename redirects {}print 'ParsingtheNTredirectfile' for l line in enumerate BZ2File redirects_filename split line split if len split 4 print 'ignoringmalformedline ' + line continueredirects[short_name split[0] ] short_name split[2] if l % 1000000 0 print '[%s]line %08d' % datetime now iso...
111
python-test-1565
python
How did map close ?
transitively
def get redirects redirects filename redirects {}print ' Parsingthe N Tredirectfile' for l line in enumerate BZ 2 File redirects filename split line split if len split 4 print 'ignoringmalformedline ' + line continueredirects[short name split[ 0 ] ] short name split[ 2 ] if l % 1000000 0 print '[%s]line %08 d' % dateti...
def get_redirects redirects_filename redirects {}print 'ParsingtheNTredirectfile' for l line in enumerate BZ2File redirects_filename split line split if len split 4 print 'ignoringmalformedline ' + line continueredirects[short_name split[0] ] short_name split[2] if l % 1000000 0 print '[%s]line %08d' % datetime now iso...
111
python-test-1567
python
What do the object have ?
a permission args
def has permission obj name principal permission access mode 'grant' obj type 'file' exact True if access mode lower not in ['grant' 'deny'] raise Salt Invocation Error ' Invalid"access mode"passed {0 }' format access mode access mode access mode lower dacl Dacl obj name obj type obj type obj type lower sid get sid pri...
def has_permission obj_name principal permission access_mode 'grant' obj_type 'file' exact True if access_mode lower not in ['grant' 'deny'] raise SaltInvocationError 'Invalid"access_mode"passed {0}' format access_mode access_mode access_mode lower dacl Dacl obj_name obj_type obj_type obj_type lower sid get_sid princip...
143
python-test-1568
python
What does the code render ?
an openid authentication request
def render openid request request openid request return to trust root None if trust root is None trust root getattr settings 'OPENID TRUST ROOT' request build absolute uri '/' if openid request should Send Redirect redirect url openid request redirect URL trust root return to return Http Response Redirect redirect url ...
def render_openid_request request openid_request return_to trust_root None if trust_root is None trust_root getattr settings 'OPENID_TRUST_ROOT' request build_absolute_uri '/' if openid_request shouldSendRedirect redirect_url openid_request redirectURL trust_root return_to return HttpResponseRedirect redirect_url else ...
80
python-test-1569
python
What does the code update ?
a user preference for the given username
@intercept errors User API Internal Error ignore errors [ User API Request Error] def set user preference requesting user preference key preference value username None existing user get authorized user requesting user username serializer create user preference serializer existing user preference key preference value va...
@intercept_errors UserAPIInternalError ignore_errors [UserAPIRequestError] def set_user_preference requesting_user preference_key preference_value username None existing_user _get_authorized_user requesting_user username serializer create_user_preference_serializer existing_user preference_key preference_value validate...
70
python-test-1570
python
What makes sense at least more or less ?
the ecliptic transformations for heliocentric and barycentric
def test ecliptic heliobary icrs ICRS 1 * u deg 2 * u deg distance 1 5 * R sun bary icrs transform to Barycentric True Ecliptic helio icrs transform to Heliocentric True Ecliptic assert np abs bary distance - helio distance > 1 * u km helio in bary frame bary realize frame helio cartesian assert bary separation helio i...
def test_ecliptic_heliobary icrs ICRS 1 * u deg 2 * u deg distance 1 5 * R_sun bary icrs transform_to BarycentricTrueEcliptic helio icrs transform_to HeliocentricTrueEcliptic assert np abs bary distance - helio distance > 1 * u km helio_in_bary_frame bary realize_frame helio cartesian assert bary separation helio_in_ba...
68
python-test-1571
python
What does the code get ?
all balance sheet accounts for opening entry
@frappe whitelist def get opening accounts company accounts frappe db sql list u"select\n DCTB DCTB DCTB namefromtab Account\n DCTB DCTB where\n DCTB DCTB DCTB is group 0and\n DCTB DCTB DCTB report type ' Balance Sheet'and\n DCTB DCTB DCTB ifnull warehouse '' ''and\n DCTB DCTB DCTB company %s\n DCTB DCTB orderbynameasc...
@frappe whitelist def get_opening_accounts company accounts frappe db sql_list u"select\n DCTB DCTB DCTB namefromtabAccount\n DCTB DCTB where\n DCTB DCTB DCTB is_group 0and\n DCTB DCTB DCTB report_type 'BalanceSheet'and\n DCTB DCTB DCTB ifnull warehouse '' ''and\n DCTB DCTB DCTB company %s\n DCTB DCTB orderbynameasc" c...
64
python-test-1576
python
What does the code get ?
the vm profile spec configured for storage policy
def get storage profile spec session storage policy profile id pbm get profile id by name session storage policy if profile id client factory session vim client factorystorage profile spec client factory create 'ns 0 Virtual Machine Defined Profile Spec' storage profile spec profile Id profile id unique Idreturn storag...
def get_storage_profile_spec session storage_policy profile_id pbm get_profile_id_by_name session storage_policy if profile_id client_factory session vim client factorystorage_profile_spec client_factory create 'ns0 VirtualMachineDefinedProfileSpec' storage_profile_spec profileId profile_id uniqueIdreturn storage_profi...
52
python-test-1584
python
What does the code get ?
an iterator of names and bound methods
def nose tools functions module BUILDER string build textwrap dedent '\nimportunittest\n\nclass Test unittest Test Case \npass\na Test \n' try case next module['a'] infer except astroid Inference Error returnfor method in case methods if method name startswith 'assert' and ' ' not in method name pep 8 name pep 8 method...
def _nose_tools_functions module _BUILDER string_build textwrap dedent '\nimportunittest\n\nclassTest unittest TestCase \npass\na Test \n' try case next module['a'] infer except astroid InferenceError returnfor method in case methods if method name startswith 'assert' and '_' not in method name pep8_name _pep8 method n...
60
python-test-1591
python
What does the code get ?
the correct compensator for ctf coils
def make ctf comp coils info coils logger info ' Settingupcompensationdata ' comp num get current comp info if comp num is None or comp num 0 logger info ' Nocompensationset Nothingmoretodo ' return Nonen comp ch sum [ c['kind'] FIFF FIFFV MEG CH for c in info['chs']] logger info '%doutof%dchannelshavethecompensationse...
def _make_ctf_comp_coils info coils logger info 'Settingupcompensationdata ' comp_num get_current_comp info if comp_num is None or comp_num 0 logger info 'Nocompensationset Nothingmoretodo ' return Nonen_comp_ch sum [ c['kind'] FIFF FIFFV_MEG_CH for c in info['chs']] logger info '%doutof%dchannelshavethecompensationset...
98
python-test-1592
python
What does it contain ?
only the folder metadata caches from different oses
def remove dir if empty path ignore metadata caches False try os rmdir path except OS Error as e if e errno errno ENOTEMPTY or len os listdir path > 0 if ignore metadata caches try found Falsefor x in os listdir path if x lower in {' ds store' 'thumbs db'} found Truex os path join path x if os path isdir x import shuti...
def remove_dir_if_empty path ignore_metadata_caches False try os rmdir path except OSError as e if e errno errno ENOTEMPTY or len os listdir path > 0 if ignore_metadata_caches try found Falsefor x in os listdir path if x lower in {' ds_store' 'thumbs db'} found Truex os path join path x if os path isdir x import shutil...
83
python-test-1597
python
For what purpose can you supply a data folder or any folder ?
in order to make a visualization
def get recording dirs data dir filtered recording dirs []if is pupil rec dir data dir filtered recording dirs append data dir for root dirs files in os walk data dir filtered recording dirs + [os path join root d for d in dirs if not d startswith ' ' and is pupil rec dir os path join root d ]logger debug ' Filtered Re...
def get_recording_dirs data_dir filtered_recording_dirs []if is_pupil_rec_dir data_dir filtered_recording_dirs append data_dir for root dirs files in os walk data_dir filtered_recording_dirs + [os path join root d for d in dirs if not d startswith ' ' and is_pupil_rec_dir os path join root d ]logger debug 'FilteredReco...
75
python-test-1598
python
What can you supply in order to make a visualization ?
a data folder or any folder
def get recording dirs data dir filtered recording dirs []if is pupil rec dir data dir filtered recording dirs append data dir for root dirs files in os walk data dir filtered recording dirs + [os path join root d for d in dirs if not d startswith ' ' and is pupil rec dir os path join root d ]logger debug ' Filtered Re...
def get_recording_dirs data_dir filtered_recording_dirs []if is_pupil_rec_dir data_dir filtered_recording_dirs append data_dir for root dirs files in os walk data_dir filtered_recording_dirs + [os path join root d for d in dirs if not d startswith ' ' and is_pupil_rec_dir os path join root d ]logger debug 'FilteredReco...
75
python-test-1599
python
What did you make ?
a visualization
def get recording dirs data dir filtered recording dirs []if is pupil rec dir data dir filtered recording dirs append data dir for root dirs files in os walk data dir filtered recording dirs + [os path join root d for d in dirs if not d startswith ' ' and is pupil rec dir os path join root d ]logger debug ' Filtered Re...
def get_recording_dirs data_dir filtered_recording_dirs []if is_pupil_rec_dir data_dir filtered_recording_dirs append data_dir for root dirs files in os walk data_dir filtered_recording_dirs + [os path join root d for d in dirs if not d startswith ' ' and is_pupil_rec_dir os path join root d ]logger debug 'FilteredReco...
75
python-test-1600
python
Where does we allow those c++11 features only ?
in certain places
def Flag Cxx 11 Features filename clean lines linenum error line clean lines elided[linenum]include Match '\\s*#\\s*include\\s+[<"] [^<"]+ [">]' line if include and include group 1 startswith 'tr 1 /' error filename linenum 'build/c++tr 1 ' 5 'C++TR 1 headerssuchas<%s>areunapproved ' % include group 1 if include and in...
def FlagCxx11Features filename clean_lines linenum error line clean_lines elided[linenum]include Match '\\s*#\\s*include\\s+[<"] [^<"]+ [">]' line if include and include group 1 startswith 'tr1/' error filename linenum 'build/c++tr1' 5 'C++TR1headerssuchas<%s>areunapproved ' % include group 1 if include and include gro...
123
python-test-1601
python
What does the code add to gradients ?
histogram summaries
def add gradients summaries grads and vars summaries []for grad var in grads and vars if grad is not None if isinstance grad tf Indexed Slices grad values grad valueselse grad values gradsummaries append tf histogram summary var op name + ' gradient' grad values summaries append tf histogram summary var op name + ' gra...
def _add_gradients_summaries grads_and_vars summaries []for grad var in grads_and_vars if grad is not None if isinstance grad tf IndexedSlices grad_values grad valueselse grad_values gradsummaries append tf histogram_summary var op name + ' gradient' grad_values summaries append tf histogram_summary var op name + ' gra...
73
python-test-1602
python
What does the code create in a region ?
a static address
def create address kwargs None call None if call 'function' raise Salt Cloud System Exit ' Thecreate addressfunctionmustbecalledwith-for--function ' if not kwargs or 'name' not in kwargs log error ' Anamemustbespecifiedwhencreatinganaddress ' return Falseif 'region' not in kwargs log error ' Aregionmustbespecifiedforth...
def create_address kwargs None call None if call 'function' raise SaltCloudSystemExit 'Thecreate_addressfunctionmustbecalledwith-for--function ' if not kwargs or 'name' not in kwargs log error 'Anamemustbespecifiedwhencreatinganaddress ' return Falseif 'region' not in kwargs log error 'Aregionmustbespecifiedfortheaddre...
112
python-test-1603
python
When should the meta path be consulted ?
before builtins are loaded
def test meta path before builtins class My Exception Exception passclass K def find module self name path if name 'time' return selfreturn Nonedef load module self name raise My Exceptionif 'time' in sys modules del sys modules['time']loader K sys meta path append loader try import time Assert Unreachable except My Ex...
def test_meta_path_before_builtins class MyException Exception passclass K def find_module self name path if name 'time' return selfreturn Nonedef load_module self name raise MyExceptionif 'time' in sys modules del sys modules['time']loader K sys meta_path append loader try import timeAssertUnreachable except MyExcepti...
59
python-test-1605
python
What does the code retrieve from the minion ?
the show variables
def showvariables **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 'SHOWVARIABLES' conn close if len rtnv 0 rtnv append [] log debug '{ 0 }-->{ 1 }' format mod len rtnv[ 0 ] return rtnv
def showvariables **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 'SHOWVARIABLES' conn close if len rtnv 0 rtnv append [] log debug '{0}-->{1}' format mod len rtnv[0] return rtnv
57
python-test-1606
python
Where does the code add the milestone for given entrance_exam ?
in course args
def add entrance exam milestone course entrance exam namespace choices get namespace choices milestone relationship types get milestone relationship types milestone namespace generate milestone namespace namespace choices get 'ENTRANCE EXAM' course id milestone add milestone {'name' ' Test Milestone' 'namespace' milest...
def add_entrance_exam_milestone course entrance_exam namespace_choices get_namespace_choices milestone_relationship_types get_milestone_relationship_types milestone_namespace generate_milestone_namespace namespace_choices get 'ENTRANCE_EXAM' course id milestone add_milestone {'name' 'TestMilestone' 'namespace' mileston...
74
python-test-1607
python
What does the code add in course args in course args ?
the milestone for given entrance_exam
def add entrance exam milestone course entrance exam namespace choices get namespace choices milestone relationship types get milestone relationship types milestone namespace generate milestone namespace namespace choices get 'ENTRANCE EXAM' course id milestone add milestone {'name' ' Test Milestone' 'namespace' milest...
def add_entrance_exam_milestone course entrance_exam namespace_choices get_namespace_choices milestone_relationship_types get_milestone_relationship_types milestone_namespace generate_milestone_namespace namespace_choices get 'ENTRANCE_EXAM' course id milestone add_milestone {'name' 'TestMilestone' 'namespace' mileston...
74
python-test-1608
python
What does the code generate ?
a course structure dictionary for the specified course
def get credit course requirement xblocks course key requirements []for category in CREDIT REQUIREMENT XBLOCK CATEGORIES requirements extend [{'namespace' block get credit requirement namespace 'name' block get credit requirement name 'display name' block get credit requirement display name 'start date' block start 'cr...
def _get_credit_course_requirement_xblocks course_key requirements []for category in CREDIT_REQUIREMENT_XBLOCK_CATEGORIES requirements extend [{'namespace' block get_credit_requirement_namespace 'name' block get_credit_requirement_name 'display_name' block get_credit_requirement_display_name 'start_date' block start 'c...
60
python-test-1610
python
What does the code update ?
a postgres group cli examples
def group update groupname user None host None port None maintenance db None password None createdb None createroles None createuser None encrypted None inherit None login None superuser None replication None rolepassword None groups None runas None return role update groupname user user host host port port maintenance...
def group_update groupname user None host None port None maintenance_db None password None createdb None createroles None createuser None encrypted None inherit None login None superuser None replication None rolepassword None groups None runas None return _role_update groupname user user host host port port maintenanc...
77
python-test-1611
python
What does the code ensure ?
that all array arguments are contiguous
@contextlib contextmanagerdef make contiguous context builder sig args newtys []newargs []copies []for ty val in zip sig args args if not isinstance ty types Array or ty layout in 'CF' newty newval ty val else newty ty copy layout 'C' copysig signature newty ty newval array copy context builder copysig val copies appen...
@contextlib contextmanagerdef make_contiguous context builder sig args newtys []newargs []copies []for ty val in zip sig args args if not isinstance ty types Array or ty layout in 'CF' newty newval ty val else newty ty copy layout 'C' copysig signature newty ty newval array_copy context builder copysig val copies appen...
80
python-test-1613
python
Do the find and find_all methods of beautifulsoup handle the text parameter combined with other parameters ?
No
def find all soup name None attrs None recursive True text None limit None **kwargs if text is None return soup find all name attrs or {} recursive text limit **kwargs if isinstance text string types text re compile re escape text re I tags soup find all name attrs or {} recursive **kwargs rv []for tag in tags if match...
def find_all soup name None attrs None recursive True text None limit None **kwargs if text is None return soup find_all name attrs or {} recursive text limit **kwargs if isinstance text string_types text re compile re escape text re I tags soup find_all name attrs or {} recursive **kwargs rv []for tag in tags if match...
79
python-test-1614
python
What do nt handle the text parameter combined with other parameters ?
the find and find_all methods of beautifulsoup
def find all soup name None attrs None recursive True text None limit None **kwargs if text is None return soup find all name attrs or {} recursive text limit **kwargs if isinstance text string types text re compile re escape text re I tags soup find all name attrs or {} recursive **kwargs rv []for tag in tags if match...
def find_all soup name None attrs None recursive True text None limit None **kwargs if text is None return soup find_all name attrs or {} recursive text limit **kwargs if isinstance text string_types text re compile re escape text re I tags soup find_all name attrs or {} recursive **kwargs rv []for tag in tags if match...
79
python-test-1615
python
What do the find and find_all methods of beautifulsoup nt handle ?
the text parameter combined with other parameters
def find all soup name None attrs None recursive True text None limit None **kwargs if text is None return soup find all name attrs or {} recursive text limit **kwargs if isinstance text string types text re compile re escape text re I tags soup find all name attrs or {} recursive **kwargs rv []for tag in tags if match...
def find_all soup name None attrs None recursive True text None limit None **kwargs if text is None return soup find_all name attrs or {} recursive text limit **kwargs if isinstance text string_types text re compile re escape text re I tags soup find_all name attrs or {} recursive **kwargs rv []for tag in tags if match...
79
python-test-1617
python
How do edx content embed ?
via the lti protocol
@csrf exempt@add p3 p headerdef lti launch request course id usage id if not settings FEATURES['ENABLE LTI PROVIDER'] return Http Response Forbidden params get required parameters request POST if not params return Http Response Bad Request params update get optional parameters request POST try lti consumer Lti Consumer...
@csrf_exempt@add_p3p_headerdef lti_launch request course_id usage_id if not settings FEATURES['ENABLE_LTI_PROVIDER'] return HttpResponseForbidden params get_required_parameters request POST if not params return HttpResponseBadRequest params update get_optional_parameters request POST try lti_consumer LtiConsumer get_or...
141
python-test-1621
python
What does the code ensure ?
a sysrc variable is absent
def absent name **kwargs ret {'name' name 'changes' {} 'result' False 'comment' ''}current state salt ['sysrc get'] name name **kwargs if current state is None ret['result'] Trueret['comment'] '"{ 0 }"isalreadyabsent ' format name return retif opts ['test'] is True ret['comment'] '"{ 0 }"willberemoved ' format name ret...
def absent name **kwargs ret {'name' name 'changes' {} 'result' False 'comment' ''}current_state __salt__['sysrc get'] name name **kwargs if current_state is None ret['result'] Trueret['comment'] '"{0}"isalreadyabsent ' format name return retif __opts__['test'] is True ret['comment'] '"{0}"willberemoved ' format name r...
83
python-test-1623
python
What does the code adapt ?
a post response to a message
def http Response To Message response server url response message Message from KV Form response body if response status 400 raise Server Error from Message response message elif response status not in 200 206 fmt 'badstatuscodefromserver%s %s'error message fmt % server url response status raise fetchers HTTP Fetching E...
def _httpResponseToMessage response server_url response_message Message fromKVForm response body if response status 400 raise ServerError fromMessage response_message elif response status not in 200 206 fmt 'badstatuscodefromserver%s %s'error_message fmt % server_url response status raise fetchers HTTPFetchingError err...
54
python-test-1628
python
What does the code run ?
the oauthauthorizetoken cgi
def O Auth Authorize Token CGI method parameters outfile oauth callback Get First parameters OAUTH CALLBACK PARAM '' if method 'GET' outfile write ' Status 200 \r\n' outfile write ' Content- Type text/html\r\n' outfile write '\r\n' outfile write Render Token Approval Template oauth callback elif method 'POST' if oauth ...
def OAuthAuthorizeTokenCGI method parameters outfile oauth_callback GetFirst parameters _OAUTH_CALLBACK_PARAM '' if method 'GET' outfile write 'Status 200\r\n' outfile write 'Content-Type text/html\r\n' outfile write '\r\n' outfile write RenderTokenApprovalTemplate oauth_callback elif method 'POST' if oauth_callback ou...
97
python-test-1631
python
What does the code rewrite in its simplest form ?
a kroneckerdeltas indices
@cacheitdef simplify delta expr from sympy solvers import solveif isinstance expr Kronecker Delta try slns solve expr args[ 0 ] - expr args[ 1 ] dict True if slns and len slns 1 return Mul *[ Kronecker Delta * key value for key value in slns[ 0 ] items ] except Not Implemented Error passreturn expr
@cacheitdef _simplify_delta expr from sympy solvers import solveif isinstance expr KroneckerDelta try slns solve expr args[0] - expr args[1] dict True if slns and len slns 1 return Mul *[KroneckerDelta * key value for key value in slns[0] items ] except NotImplementedError passreturn expr
56
python-test-1632
python
How does the code rewrite a kroneckerdeltas indices ?
in its simplest form
@cacheitdef simplify delta expr from sympy solvers import solveif isinstance expr Kronecker Delta try slns solve expr args[ 0 ] - expr args[ 1 ] dict True if slns and len slns 1 return Mul *[ Kronecker Delta * key value for key value in slns[ 0 ] items ] except Not Implemented Error passreturn expr
@cacheitdef _simplify_delta expr from sympy solvers import solveif isinstance expr KroneckerDelta try slns solve expr args[0] - expr args[1] dict True if slns and len slns 1 return Mul *[KroneckerDelta * key value for key value in slns[0] items ] except NotImplementedError passreturn expr
56
python-test-1634
python
What does the code convert to a string ?
a zero indexed column cell reference
def xl col to name col num col abs False col num + 1col str ''col abs '$' if col abs else '' while col num remainder col num % 26 if remainder 0 remainder 26 col letter chr ord 'A' + remainder - 1 col str col letter + col str col num int col num - 1 / 26 return col abs + col str
def xl_col_to_name col_num col_abs False col_num + 1col_str ''col_abs '$' if col_abs else '' while col_num remainder col_num % 26 if remainder 0 remainder 26col_letter chr ord 'A' + remainder - 1 col_str col_letter + col_str col_num int col_num - 1 / 26 return col_abs + col_str
67
python-test-1650
python
What does the code setup ?
the mysensors platform for covers
def setup platform hass config add devices discovery info None if discovery info is None returngateways hass data get mysensors MYSENSORS GATEWAYS if not gateways returnfor gateway in gateways pres gateway const Presentationset req gateway const Set Reqmap sv types {pres S COVER [set req V DIMMER set req V LIGHT]}if fl...
def setup_platform hass config add_devices discovery_info None if discovery_info is None returngateways hass data get mysensors MYSENSORS_GATEWAYS if not gateways returnfor gateway in gateways pres gateway const Presentationset_req gateway const SetReqmap_sv_types {pres S_COVER [set_req V_DIMMER set_req V_LIGHT]}if flo...
91
python-test-1651
python
What does the code give ?
email preferences of user with given user_id
def get email preferences user id email preferences model user models User Email Preferences Model get user id strict False if email preferences model is None return user domain User Global Prefs create default prefs else return user domain User Global Prefs email preferences model site updates email preferences model ...
def get_email_preferences user_id email_preferences_model user_models UserEmailPreferencesModel get user_id strict False if email_preferences_model is None return user_domain UserGlobalPrefs create_default_prefs else return user_domain UserGlobalPrefs email_preferences_model site_updates email_preferences_model editor_...
64
python-test-1652
python
What does the code find ?
the period
def find audio period aclip t min 0 1 t max 2 t res 0 01 chunksize int t res * aclip fps chunk duration 1 0 * chunksize / aclip fps v np array [ c ** 2 sum for c in aclip iter chunks chunksize ] v v - v mean corrs np correlate v v mode 'full' [ - len v ]corrs[ int t min / chunk duration ] 0corrs[int t max / chunk durat...
def find_audio_period aclip t_min 0 1 t_max 2 t_res 0 01 chunksize int t_res * aclip fps chunk_duration 1 0 * chunksize / aclip fps v np array [ c ** 2 sum for c in aclip iter_chunks chunksize ] v v - v mean corrs np correlate v v mode 'full' [ - len v ]corrs[ int t_min / chunk_duration ] 0corrs[int t_max / chunk_durat...
86
python-test-1653
python
What should raise invaliddataerror if given invalid data ?
upsert_data
@mock patch 'ckanext datastore db get fields' def test upsert with insert method and invalid data mock get fields function mock connection mock Mock mock connection execute side effect sqlalchemy exc Data Error 'statement' 'params' 'orig' connection invalidated False context {'connection' mock connection}data dict {'fi...
@mock patch 'ckanext datastore db _get_fields' def test_upsert_with_insert_method_and_invalid_data mock_get_fields_function mock_connection mock Mock mock_connection execute side_effect sqlalchemy exc DataError 'statement' 'params' 'orig' connection_invalidated False context {'connection' mock_connection}data_dict {'fi...
91
python-test-1654
python
What should upsert_data raise if given invalid data ?
invaliddataerror
@mock patch 'ckanext datastore db get fields' def test upsert with insert method and invalid data mock get fields function mock connection mock Mock mock connection execute side effect sqlalchemy exc Data Error 'statement' 'params' 'orig' connection invalidated False context {'connection' mock connection}data dict {'fi...
@mock patch 'ckanext datastore db _get_fields' def test_upsert_with_insert_method_and_invalid_data mock_get_fields_function mock_connection mock Mock mock_connection execute side_effect sqlalchemy exc DataError 'statement' 'params' 'orig' connection_invalidated False context {'connection' mock_connection}data_dict {'fi...
91
python-test-1661
python
How does the code find all of the failing tests ?
by looking for files with -failed - diff at the end of the basename
def find failing tests result images source entries []for root dirs files in os walk result images for fname in files basename ext os path splitext fname if basename endswith u'-failed-diff' path os path join root fname entry Entry path result images source entries append entry entries sort key lambda x x name return e...
def find_failing_tests result_images source entries []for root dirs files in os walk result_images for fname in files basename ext os path splitext fname if basename endswith u'-failed-diff' path os path join root fname entry Entry path result_images source entries append entry entries sort key lambda x x name return e...
55
python-test-1662
python
What does the code find by looking for files with -failed - diff at the end of the basename ?
all of the failing tests
def find failing tests result images source entries []for root dirs files in os walk result images for fname in files basename ext os path splitext fname if basename endswith u'-failed-diff' path os path join root fname entry Entry path result images source entries append entry entries sort key lambda x x name return e...
def find_failing_tests result_images source entries []for root dirs files in os walk result_images for fname in files basename ext os path splitext fname if basename endswith u'-failed-diff' path os path join root fname entry Entry path result_images source entries append entry entries sort key lambda x x name return e...
55
python-test-1665
python
What does the code get ?
lifecycle information about an extension
def create metadata name ext version None schema None user None host None port None maintenance db None password None runas None installed ext get installed extension name user user host host port port maintenance db maintenance db password password runas runas ret [ EXTENSION NOT INSTALLED]if installed ext ret [ EXTEN...
def create_metadata name ext_version None schema None user None host None port None maintenance_db None password None runas None installed_ext get_installed_extension name user user host host port port maintenance_db maintenance_db password password runas runas ret [_EXTENSION_NOT_INSTALLED]if installed_ext ret [_EXTEN...
104
python-test-1666
python
How does a list of featured activities return ?
with the given language codes
def get featured activity summary dicts language codes activity references activity services get featured activity references exploration ids collection ids activity services split by type activity references exp summary dicts get displayable exp summary dicts matching ids exploration ids col summary dicts get displaya...
def get_featured_activity_summary_dicts language_codes activity_references activity_services get_featured_activity_references exploration_ids collection_ids activity_services split_by_type activity_references exp_summary_dicts get_displayable_exp_summary_dicts_matching_ids exploration_ids col_summary_dicts get_displaya...
128
python-test-1667
python
What does the code ensure ?
that all associated messages are deleted when a thread is deleted
def test thread delete db gmail account generic thread add fake thread db session gmail account namespace id generic message add fake message db session gmail account namespace id generic thread assert db session query Thread filter Thread id generic thread id all [generic thread] assert db session query Message filter...
def test_thread_delete db gmail_account generic_thread add_fake_thread db session gmail_account namespace id generic_message add_fake_message db session gmail_account namespace id generic_thread assert db session query Thread filter Thread id generic_thread id all [generic_thread] assert db session query Message filter...
93
python-test-1668
python
When are all associated messages deleted ?
when a thread is deleted
def test thread delete db gmail account generic thread add fake thread db session gmail account namespace id generic message add fake message db session gmail account namespace id generic thread assert db session query Thread filter Thread id generic thread id all [generic thread] assert db session query Message filter...
def test_thread_delete db gmail_account generic_thread add_fake_thread db session gmail_account namespace id generic_message add_fake_message db session gmail_account namespace id generic_thread assert db session query Thread filter Thread id generic_thread id all [generic_thread] assert db session query Message filter...
93
python-test-1669
python
What performs a chisquare test for proportions for pairwise comparisons with a control ?
chisquare test of proportions for pairs of k samples compared to control
def proportions chisquare pairscontrol count nobs value None multitest method 'hs' alternative 'two-sided' if value is not None or not alternative in ['two-sided' '2 s'] raise Not Implemented Errorall pairs [ 0 k for k in range 1 len count ]pvals [proportions chisquare count[list pair ] nobs[list pair ] [1 ] for pair i...
def proportions_chisquare_pairscontrol count nobs value None multitest_method 'hs' alternative 'two-sided' if value is not None or not alternative in ['two-sided' '2s'] raise NotImplementedErrorall_pairs [ 0 k for k in range 1 len count ]pvals [proportions_chisquare count[list pair ] nobs[list pair ] [1] for pair in al...
66
python-test-1670
python
What do chisquare test of proportions for pairs of k samples compared to control perform ?
a chisquare test for proportions for pairwise comparisons with a control
def proportions chisquare pairscontrol count nobs value None multitest method 'hs' alternative 'two-sided' if value is not None or not alternative in ['two-sided' '2 s'] raise Not Implemented Errorall pairs [ 0 k for k in range 1 len count ]pvals [proportions chisquare count[list pair ] nobs[list pair ] [1 ] for pair i...
def proportions_chisquare_pairscontrol count nobs value None multitest_method 'hs' alternative 'two-sided' if value is not None or not alternative in ['two-sided' '2s'] raise NotImplementedErrorall_pairs [ 0 k for k in range 1 len count ]pvals [proportions_chisquare count[list pair ] nobs[list pair ] [1] for pair in al...
66
python-test-1675
python
What does the code get ?
the list of top contributors with the contribution count
def get creator counts query count page creator counts query facet counts ['creator id']['terms']total len creator counts creator counts creator counts[ page - 1 * count page * count ]user ids [x['term'] for x in creator counts]results User Mapping Type search filter id in user ids values dict 'id' 'username' 'display ...
def _get_creator_counts query count page creator_counts query facet_counts ['creator_id']['terms']total len creator_counts creator_counts creator_counts[ page - 1 * count page * count ]user_ids [x['term'] for x in creator_counts]results UserMappingType search filter id__in user_ids values_dict 'id' 'username' 'display_...
122
python-test-1676
python
What do test make from python ?
m - eeg forward solution
@slow test@testing requires testing datadef test make forward solution fwd py make forward solution fname raw fname trans fname src fname bem mindist 5 0 eeg True meg True assert true isinstance fwd py Forward fwd read forward solution fname meeg assert true isinstance fwd Forward compare forwards fwd fwd py 366 1494 m...
@slow_test@testing requires_testing_datadef test_make_forward_solution fwd_py make_forward_solution fname_raw fname_trans fname_src fname_bem mindist 5 0 eeg True meg True assert_true isinstance fwd_py Forward fwd read_forward_solution fname_meeg assert_true isinstance fwd Forward _compare_forwards fwd fwd_py 366 1494 ...
57
python-test-1677
python
For what purpose do supported_locales update ?
for an individual app
@task@use masterdef update supported locales single id latest False **kw from mkt webapps models import Webapptry app Webapp objects get pk id except Webapp Does Not Exist log info u'[ Webapp %s] Didnotfindwebapptoupdatesupportedlocales ' % id returntry if app update supported locales latest latest log info u'[ Webapp ...
@task@use_masterdef update_supported_locales_single id latest False **kw from mkt webapps models import Webapptry app Webapp objects get pk id except Webapp DoesNotExist log info u'[Webapp %s]Didnotfindwebapptoupdatesupportedlocales ' % id returntry if app update_supported_locales latest latest log info u'[Webapp %s]Up...
68
python-test-1678
python
What does the code send for the specified user ?
the login instructions email
def send login instructions user token generate login token user login link url for security 'token login' token token external True send mail config value 'EMAIL SUBJECT PASSWORDLESS' user email 'login instructions' user user login link login link login instructions sent send app get current object user user login tok...
def send_login_instructions user token generate_login_token user login_link url_for_security 'token_login' token token _external True send_mail config_value 'EMAIL_SUBJECT_PASSWORDLESS' user email 'login_instructions' user user login_link login_link login_instructions_sent send app _get_current_object user user login_t...
51
python-test-1681
python
What are the crypto maps not using ?
aes
def main cisco file 'cisco ipsec txt'cisco cfg Cisco Conf Parse cisco file crypto maps cisco cfg find objects wo child parentspec 'cryptomap CRYPTO' childspec 'AES' print '\n Cryptomapsnotusing AES 'for entry in crypto maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' ...
def main cisco_file 'cisco_ipsec txt'cisco_cfg CiscoConfParse cisco_file crypto_maps cisco_cfg find_objects_wo_child parentspec 'cryptomapCRYPTO' childspec 'AES' print '\nCryptomapsnotusingAES 'for entry in crypto_maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' child...
69
python-test-1682
python
What are not using aes ?
the crypto maps
def main cisco file 'cisco ipsec txt'cisco cfg Cisco Conf Parse cisco file crypto maps cisco cfg find objects wo child parentspec 'cryptomap CRYPTO' childspec 'AES' print '\n Cryptomapsnotusing AES 'for entry in crypto maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' ...
def main cisco_file 'cisco_ipsec txt'cisco_cfg CiscoConfParse cisco_file crypto_maps cisco_cfg find_objects_wo_child parentspec 'cryptomapCRYPTO' childspec 'AES' print '\nCryptomapsnotusingAES 'for entry in crypto_maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' child...
69
python-test-1683
python
What does the code using ciscoconfparse find ?
the crypto maps that are not using aes
def main cisco file 'cisco ipsec txt'cisco cfg Cisco Conf Parse cisco file crypto maps cisco cfg find objects wo child parentspec 'cryptomap CRYPTO' childspec 'AES' print '\n Cryptomapsnotusing AES 'for entry in crypto maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' ...
def main cisco_file 'cisco_ipsec txt'cisco_cfg CiscoConfParse cisco_file crypto_maps cisco_cfg find_objects_wo_child parentspec 'cryptomapCRYPTO' childspec 'AES' print '\nCryptomapsnotusingAES 'for entry in crypto_maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' child...
69
python-test-1684
python
What does the code use ?
ciscoconfparse
def main cisco file 'cisco ipsec txt'cisco cfg Cisco Conf Parse cisco file crypto maps cisco cfg find objects wo child parentspec 'cryptomap CRYPTO' childspec 'AES' print '\n Cryptomapsnotusing AES 'for entry in crypto maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' ...
def main cisco_file 'cisco_ipsec txt'cisco_cfg CiscoConfParse cisco_file crypto_maps cisco_cfg find_objects_wo_child parentspec 'cryptomapCRYPTO' childspec 'AES' print '\nCryptomapsnotusingAES 'for entry in crypto_maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' child...
69
python-test-1685
python
What finds the crypto maps that are not using aes ?
the code using ciscoconfparse
def main cisco file 'cisco ipsec txt'cisco cfg Cisco Conf Parse cisco file crypto maps cisco cfg find objects wo child parentspec 'cryptomap CRYPTO' childspec 'AES' print '\n Cryptomapsnotusing AES 'for entry in crypto maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' ...
def main cisco_file 'cisco_ipsec txt'cisco_cfg CiscoConfParse cisco_file crypto_maps cisco_cfg find_objects_wo_child parentspec 'cryptomapCRYPTO' childspec 'AES' print '\nCryptomapsnotusingAES 'for entry in crypto_maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' child...
69
python-test-1686
python
Are the crypto maps using aes ?
No
def main cisco file 'cisco ipsec txt'cisco cfg Cisco Conf Parse cisco file crypto maps cisco cfg find objects wo child parentspec 'cryptomap CRYPTO' childspec 'AES' print '\n Cryptomapsnotusing AES 'for entry in crypto maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' ...
def main cisco_file 'cisco_ipsec txt'cisco_cfg CiscoConfParse cisco_file crypto_maps cisco_cfg find_objects_wo_child parentspec 'cryptomapCRYPTO' childspec 'AES' print '\nCryptomapsnotusingAES 'for entry in crypto_maps for child in entry children if 'transform' in child text match re search 'settransform-set * $' child...
69
python-test-1687
python
Where does values set ?
in the org
def desktop lockdown name user None disable application handlers None disable command line None disable lock screen None disable log out None disable print setup None disable printing None disable save to disk None disable user switching None user administration disabled None **kwargs gnome kwargs {'user' user 'schema'...
def desktop_lockdown name user None disable_application_handlers None disable_command_line None disable_lock_screen None disable_log_out None disable_print_setup None disable_printing None disable_save_to_disk None disable_user_switching None user_administration_disabled None **kwargs gnome_kwargs {'user' user 'schema'...
111
python-test-1689
python
What does the code convert to string ?
a number in hex format
def hex 2 str hexnum intsize 4 if not isinstance hexnum six string types nbits intsize * 8 hexnum '0 x%x' % hexnum + 1 << nbits % 1 << nbits s hexnum[ 2 ]if len s % 2 0 s '0 ' + s result codecs decode s 'hex' [ -1 ]return result
def hex2str hexnum intsize 4 if not isinstance hexnum six string_types nbits intsize * 8 hexnum '0x%x' % hexnum + 1 << nbits % 1 << nbits s hexnum[2 ]if len s % 2 0 s '0' + s result codecs decode s 'hex' [ -1 ]return result
54
python-test-1690
python
For what purpose does pygpu nt be there when ?
for unpickle
def test unpickle gpuarray as numpy ndarray flag 0 oldflag config experimental unpickle gpu on cpuconfig experimental unpickle gpu on cpu Falsetry testfile dir os path dirname os path realpath file fname ' Gpu Array pkl'with open os path join testfile dir fname 'rb' as fp if PY 3 u Compat Unpickler fp encoding 'latin 1...
def test_unpickle_gpuarray_as_numpy_ndarray_flag0 oldflag config experimental unpickle_gpu_on_cpuconfig experimental unpickle_gpu_on_cpu Falsetry testfile_dir os path dirname os path realpath __file__ fname 'GpuArray pkl'with open os path join testfile_dir fname 'rb' as fp if PY3 u CompatUnpickler fp encoding 'latin1' ...
88
python-test-1695
python
What does the code scan ?
a video from a path
def scan video path if not os path exists path raise Value Error ' Pathdoesnotexist' if not path endswith VIDEO EXTENSIONS raise Value Error '%risnotavalidvideoextension' % os path splitext path [1 ] dirpath filename os path split path logger info ' Scanningvideo%rin%r' filename dirpath video Video fromguess path guess...
def scan_video path if not os path exists path raise ValueError 'Pathdoesnotexist' if not path endswith VIDEO_EXTENSIONS raise ValueError '%risnotavalidvideoextension' % os path splitext path [1] dirpath filename os path split path logger info 'Scanningvideo%rin%r' filename dirpath video Video fromguess path guessit pa...
103
python-test-1698
python
How are returns url prefixed with the skin name of the first skin that contains the file directories searched ?
in this order : settings
def find media source url while url[ 0 ] '/' url url[ 1 ]d os path dirnamen os path normpathj os path joinf os path isfileskins n j d d file 'skins' try media os path join skins settings OSQA DEFAULT SKIN url assert f media use skin settings OSQA DEFAULT SKI Nexcept try media j skins 'default' url assert f media use sk...
def find_media_source url while url[0] '/' url url[1 ]d os path dirnamen os path normpathj os path joinf os path isfileskins n j d d __file__ 'skins' try media os path join skins settings OSQA_DEFAULT_SKIN url assert f media use_skin settings OSQA_DEFAULT_SKINexcept try media j skins 'default' url assert f media use_sk...
92
python-test-1699
python
What contains the file directories ?
the first skin
def find media source url while url[ 0 ] '/' url url[ 1 ]d os path dirnamen os path normpathj os path joinf os path isfileskins n j d d file 'skins' try media os path join skins settings OSQA DEFAULT SKIN url assert f media use skin settings OSQA DEFAULT SKI Nexcept try media j skins 'default' url assert f media use sk...
def find_media_source url while url[0] '/' url url[1 ]d os path dirnamen os path normpathj os path joinf os path isfileskins n j d d __file__ 'skins' try media os path join skins settings OSQA_DEFAULT_SKIN url assert f media use_skin settings OSQA_DEFAULT_SKINexcept try media j skins 'default' url assert f media use_sk...
92
python-test-1700
python
What does the first skin contain ?
the file directories
def find media source url while url[ 0 ] '/' url url[ 1 ]d os path dirnamen os path normpathj os path joinf os path isfileskins n j d d file 'skins' try media os path join skins settings OSQA DEFAULT SKIN url assert f media use skin settings OSQA DEFAULT SKI Nexcept try media j skins 'default' url assert f media use sk...
def find_media_source url while url[0] '/' url url[1 ]d os path dirnamen os path normpathj os path joinf os path isfileskins n j d d __file__ 'skins' try media os path join skins settings OSQA_DEFAULT_SKIN url assert f media use_skin settings OSQA_DEFAULT_SKINexcept try media j skins 'default' url assert f media use_sk...
92
python-test-1703
python
What do sequencematcher use ?
to return list of the best " good enough " matches
def get close matches word possibilities n 3 cutoff 0 6 if not n > 0 raise Value Error 'nmustbe> 0 %r' % n if not 0 0 < cutoff < 1 0 raise Value Error 'cutoffmustbein[ 0 0 1 0] %r' % cutoff result []s Sequence Matcher s set seq 2 word for x in possibilities s set seq 1 x if s real quick ratio > cutoff and s quick ratio...
def get_close_matches word possibilities n 3 cutoff 0 6 if not n > 0 raise ValueError 'nmustbe>0 %r' % n if not 0 0 < cutoff < 1 0 raise ValueError 'cutoffmustbein[0 0 1 0] %r' % cutoff result []s SequenceMatcher s set_seq2 word for x in possibilities s set_seq1 x if s real_quick_ratio > cutoff and s quick_ratio > cuto...
97
python-test-1704
python
What use to return list of the best " good enough " matches ?
sequencematcher
def get close matches word possibilities n 3 cutoff 0 6 if not n > 0 raise Value Error 'nmustbe> 0 %r' % n if not 0 0 < cutoff < 1 0 raise Value Error 'cutoffmustbein[ 0 0 1 0] %r' % cutoff result []s Sequence Matcher s set seq 2 word for x in possibilities s set seq 1 x if s real quick ratio > cutoff and s quick ratio...
def get_close_matches word possibilities n 3 cutoff 0 6 if not n > 0 raise ValueError 'nmustbe>0 %r' % n if not 0 0 < cutoff < 1 0 raise ValueError 'cutoffmustbein[0 0 1 0] %r' % cutoff result []s SequenceMatcher s set_seq2 word for x in possibilities s set_seq1 x if s real_quick_ratio > cutoff and s quick_ratio > cuto...
97
python-test-1705
python
What did the code read data none if something went wrong ?
from socket * sock *
def read packet sock timeout None sock settimeout timeout dlen data None None try if os name 'nt' datalen sock recv SZ dlen struct unpack 'l' datalen data ''while len data < dlen data + sock recv dlen else datalen temp fail retry socket error sock recv SZ socket MSG WAITALL if len datalen SZ dlen struct unpack 'l' data...
def read_packet sock timeout None sock settimeout timeout dlen data None None try if os name 'nt' datalen sock recv SZ dlen struct unpack 'l' datalen data ''while len data < dlen data + sock recv dlen else datalen temp_fail_retry socket error sock recv SZ socket MSG_WAITALL if len datalen SZ dlen struct unpack 'l' data...
104
python-test-1706
python
What do the win32 api extracticon use ?
to load the icon
def simple load icon module index as data False size ICON SIZE try large icons small icons win 32 gui Extract Icon Ex module index 10 except pywintypes error as err if err winerror winerror ERROR FILE NOT FOUND raiseprints u' File%rdoesnotexist cannotloadicon' % module returnicons large icons + small icons try if icons...
def simple_load_icon module index as_data False size ICON_SIZE try large_icons small_icons win32gui ExtractIconEx module index 10 except pywintypes error as err if err winerror winerror ERROR_FILE_NOT_FOUND raiseprints u'File%rdoesnotexist cannotloadicon' % module returnicons large_icons + small_icons try if icons must...
91
python-test-1707
python
What uses to load the icon ?
the win32 api extracticon
def simple load icon module index as data False size ICON SIZE try large icons small icons win 32 gui Extract Icon Ex module index 10 except pywintypes error as err if err winerror winerror ERROR FILE NOT FOUND raiseprints u' File%rdoesnotexist cannotloadicon' % module returnicons large icons + small icons try if icons...
def simple_load_icon module index as_data False size ICON_SIZE try large_icons small_icons win32gui ExtractIconEx module index 10 except pywintypes error as err if err winerror winerror ERROR_FILE_NOT_FOUND raiseprints u'File%rdoesnotexist cannotloadicon' % module returnicons large_icons + small_icons try if icons must...
91
python-test-1708
python
When did by pyyaml use callback ?
when a " ! pkl : " tag is encountered
def multi constructor pkl loader tag suffix node global additional environif tag suffix '' and tag suffix u'' raise Assertion Error ' Expectedtag suffixtobe""butitis"' + tag suffix + '" Putspacebetween pkl andthefilename ' mapping loader construct yaml str node obj serial load preprocess mapping additional environ prox...
def multi_constructor_pkl loader tag_suffix node global additional_environif tag_suffix '' and tag_suffix u'' raise AssertionError 'Expectedtag_suffixtobe""butitis"' + tag_suffix + '" Putspacebetween pkl andthefilename ' mapping loader construct_yaml_str node obj serial load preprocess mapping additional_environ proxy ...
63
python-test-1712
python
What does the code find ?
all ancestor entities of a person entity in the ou hierarchy
def pr get ancestors pe id s3 db current s3 dbatable s3 db pr affiliationrtable s3 db pr rolequery atable deleted True & atable role id rtable id & atable pe id pe id & rtable deleted True & rtable role type OU roles current db query select rtable id rtable pe id rtable path rtable role type paths []append paths append...
def pr_get_ancestors pe_id s3db current s3dbatable s3db pr_affiliationrtable s3db pr_rolequery atable deleted True & atable role_id rtable id & atable pe_id pe_id & rtable deleted True & rtable role_type OU roles current db query select rtable id rtable pe_id rtable path rtable role_type paths []append paths appendfor ...
110
python-test-1713
python
What does the code find ?
a rule in the group that matches the module parameters
def find matching rule module secgroup remotegroup protocol module params['protocol']remote ip prefix module params['remote ip prefix']ethertype module params['ethertype']direction module params['direction']remote group id remotegroup['id']for rule in secgroup['security group rules'] if protocol rule['protocol'] and re...
def _find_matching_rule module secgroup remotegroup protocol module params['protocol']remote_ip_prefix module params['remote_ip_prefix']ethertype module params['ethertype']direction module params['direction']remote_group_id remotegroup['id']for rule in secgroup['security_group_rules'] if protocol rule['protocol'] and r...
72
python-test-1716
python
What does the code remove from the your locally installed overlays ?
the given overlay
def delete overlay ret list old overlays list local cmd 'layman--quietness 0--delete{ 0 }' format overlay delete attempt salt ['cmd run all'] cmd python shell False if delete attempt['retcode'] 0 raise salt exceptions Command Execution Error delete attempt['stdout'] new overlays list local if len new overlays 0 srcline...
def delete overlay ret list old_overlays list_local cmd 'layman--quietness 0--delete{0}' format overlay delete_attempt __salt__['cmd run_all'] cmd python_shell False if delete_attempt['retcode'] 0 raise salt exceptions CommandExecutionError delete_attempt['stdout'] new_overlays list_local if len new_overlays 0 srcline ...
79
python-test-1720
python
What does the code build ?
an expected frequency matrix
def build exp freq mat exp freq table exp freq mat Expected Frequency Matrix alphabet exp freq table alphabet build later 1 for i in exp freq mat if i[ 0 ] i[ 1 ] exp freq mat[i] exp freq table[i[ 0 ]] ** 2 else exp freq mat[i] 2 0 * exp freq table[i[ 0 ]] * exp freq table[i[ 1 ]] return exp freq mat
def _build_exp_freq_mat exp_freq_table exp_freq_mat ExpectedFrequencyMatrix alphabet exp_freq_table alphabet build_later 1 for i in exp_freq_mat if i[0] i[1] exp_freq_mat[i] exp_freq_table[i[0]] ** 2 else exp_freq_mat[i] 2 0 * exp_freq_table[i[0]] * exp_freq_table[i[1]] return exp_freq_mat
67
python-test-1721
python
What provides query - string authn to a resource ?
signed url
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