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-5606 | python | How do incoming requests for notifications handle ? | in a restful way | @login requireddef course notifications handler request course key string None action state id None if not course key string or not action state id return Http Response Bad Request response format request GET get 'format' or request POST get 'format' or 'html' course key Course Key from string course key string if resp... | @login_requireddef course_notifications_handler request course_key_string None action_state_id None if not course_key_string or not action_state_id return HttpResponseBadRequest response_format request GET get 'format' or request POST get 'format' or 'html' course_key CourseKey from_string course_key_string if response... | 128 |
python-test-5608 | python | What does the code create ? | a theme with the given name | def create theme name **extra kwargs kwargs {'status' STATUS PUBLIC 'name' name 'slug' slugify name 'bayesian rating' random uniform 1 5 'average daily users' random randint 200 2000 'weekly downloads' random randint 200 2000 'created' datetime now 'last updated' datetime now }kwargs update extra kwargs theme Addon obj... | def create_theme name **extra_kwargs kwargs {'status' STATUS_PUBLIC 'name' name 'slug' slugify name 'bayesian_rating' random uniform 1 5 'average_daily_users' random randint 200 2000 'weekly_downloads' random randint 200 2000 'created' datetime now 'last_updated' datetime now }kwargs update extra_kwargs theme Addon obj... | 84 |
python-test-5610 | python | What do a sound use ? | the harmonic plus stochastic model hfreq | def hps Model Synth hfreq hmag hphase stoc Env N H fs yh SM sine Model Synth hfreq hmag hphase N H fs yst STM stochastic Model Synth stoc Env H H * 2 y yh[ min yh size yst size ] + yst[ min yh size yst size ] return y yh yst | def hpsModelSynth hfreq hmag hphase stocEnv N H fs yh SM sineModelSynth hfreq hmag hphase N H fs yst STM stochasticModelSynth stocEnv H H * 2 y yh[ min yh size yst size ] + yst[ min yh size yst size ] return y yh yst | 54 |
python-test-5613 | python | When is refresh called ? | a second time | def test refresh called twice refresher callbacks Mock pgexecute Mock special Mock def dummy bg refresh *args time sleep 3 refresher bg refresh dummy bg refreshactual 1 refresher refresh pgexecute special callbacks time sleep 1 assert len actual 1 1 assert len actual 1 [ 0 ] 4 assert actual 1 [ 0 ][ 3 ] ' Auto-completi... | def test_refresh_called_twice refresher callbacks Mock pgexecute Mock special Mock def dummy_bg_refresh *args time sleep 3 refresher _bg_refresh dummy_bg_refreshactual1 refresher refresh pgexecute special callbacks time sleep 1 assert len actual1 1 assert len actual1[0] 4 assert actual1[0][3] 'Auto-completionrefreshsta... | 93 |
python-test-5618 | python | What does the code create ? | a random personcontact from the given locale | def create random person locale None minimum name comp len 0 fake get faker [u'person' u'internet' u'address'] locale locale while True first name fake first name last name fake last name name u'%s%s' % first name last name if len first name > minimum name comp len and len last name > minimum name comp len breakemail g... | def create_random_person locale None minimum_name_comp_len 0 fake get_faker [u'person' u'internet' u'address'] locale locale while True first_name fake first_name last_name fake last_name name u'%s%s' % first_name last_name if len first_name > minimum_name_comp_len and len last_name > minimum_name_comp_len breakemail g... | 121 |
python-test-5620 | python | What may a list contains ? | nested lists | def register arguments func args None if args is None args func args argsif func args vararg func set local func args vararg func args if func args kwarg func set local func args kwarg func args for arg in args if isinstance arg Name func set local arg name arg else register arguments func arg elts | def register_arguments func args None if args is None args func args argsif func args vararg func set_local func args vararg func args if func args kwarg func set_local func args kwarg func args for arg in args if isinstance arg Name func set_local arg name arg else register_arguments func arg elts | 57 |
python-test-5621 | python | What does the code add to local args ? | given arguments | def register arguments func args None if args is None args func args argsif func args vararg func set local func args vararg func args if func args kwarg func set local func args kwarg func args for arg in args if isinstance arg Name func set local arg name arg else register arguments func arg elts | def register_arguments func args None if args is None args func args argsif func args vararg func set_local func args vararg func args if func args kwarg func set_local func args kwarg func args for arg in args if isinstance arg Name func set_local arg name arg else register_arguments func arg elts | 57 |
python-test-5623 | python | For what purpose does the code check ? | to make sure that output is quiet | def test output quiet with Assert Not Prints '2 ' ip run cell '1 + 1 ' store history True with Assert Not Prints '2 ' ip run cell '1 + 1 #commentwithasemicolon' store history True with Assert Not Prints '2 ' ip run cell '1 + 1 \n#commented out function ' store history True | def test_output_quiet with AssertNotPrints '2' ip run_cell '1+1 ' store_history True with AssertNotPrints '2' ip run_cell '1+1 #commentwithasemicolon' store_history True with AssertNotPrints '2' ip run_cell '1+1 \n#commented_out_function ' store_history True | 55 |
python-test-5626 | python | What does the code start ? | the main event loop | def application start context view context app set view view view show view raise runtask qtutils Run Task parent view init update task view runtask context model fsmonitor current start msg timer Qt Core Q Timer msg timer set Single Shot True msg timer timeout connect send msg msg timer start 0 result context app exec... | def application_start context view context app set_view view view show view raise_ runtask qtutils RunTask parent view init_update_task view runtask context model fsmonitor current start msg_timer QtCore QTimer msg_timer setSingleShot True msg_timer timeout connect _send_msg msg_timer start 0 result context app exec_ f... | 71 |
python-test-5629 | python | What does the code represent ? | a list of integers as a sequence of ranges | def intranges from list list sorted list sorted list ranges []last write -1 for i in range len sorted list if i + 1 < len sorted list if sorted list[i] sorted list[ i + 1 ] - 1 continuecurrent range sorted list[ last write + 1 i + 1 ]range tuple current range[ 0 ] current range[ -1 ] + 1 ranges append range tuple last ... | def intranges_from_list list_ sorted_list sorted list_ ranges []last_write -1 for i in range len sorted_list if i + 1 < len sorted_list if sorted_list[i] sorted_list[ i + 1 ] - 1 continuecurrent_range sorted_list[ last_write + 1 i + 1 ]range_tuple current_range[0] current_range[ -1 ] + 1 ranges append range_tuple last_... | 71 |
python-test-5630 | python | For what purpose do the input data scale ? | so that the range old_min - old_max maps to new_min - new_max | def Scale Data data old min old max new min new max def Scale Point x if x is None return Nonereturn scale * x + translate if old min old max scale 1else scale new max - new min / float old max - old min translate new min - scale * old min return map Scale Point data | def ScaleData data old_min old_max new_min new_max def ScalePoint x if x is None return Nonereturn scale * x + translate if old_min old_max scale 1else scale new_max - new_min / float old_max - old_min translate new_min - scale * old_min return map ScalePoint data | 60 |
python-test-5631 | python | How do it process ? | through their ruleset | def tamper payload **kwargs ret Val payloadif payload ret Val ''i 0while i < len payload if payload[i] '%' and i < len payload - 2 and payload[ i + 1 i + 2 ] in string hexdigits and payload[ i + 2 i + 3 ] in string hexdigits ret Val + '%% 25 %s' % payload[ i + 1 i + 3 ] i + 3else ret Val + '%% 25 % 2X' % ord payload[i]... | def tamper payload **kwargs retVal payloadif payload retVal ''i 0while i < len payload if payload[i] '%' and i < len payload - 2 and payload[ i + 1 i + 2 ] in string hexdigits and payload[ i + 2 i + 3 ] in string hexdigits retVal + '%%25%s' % payload[ i + 1 i + 3 ] i + 3else retVal + '%%25% 2X' % ord payload[i] i + 1re... | 83 |
python-test-5632 | python | When do some weak web application firewalls not double ? | before processing it through their ruleset | def tamper payload **kwargs ret Val payloadif payload ret Val ''i 0while i < len payload if payload[i] '%' and i < len payload - 2 and payload[ i + 1 i + 2 ] in string hexdigits and payload[ i + 2 i + 3 ] in string hexdigits ret Val + '%% 25 %s' % payload[ i + 1 i + 3 ] i + 3else ret Val + '%% 25 % 2X' % ord payload[i]... | def tamper payload **kwargs retVal payloadif payload retVal ''i 0while i < len payload if payload[i] '%' and i < len payload - 2 and payload[ i + 1 i + 2 ] in string hexdigits and payload[ i + 2 i + 3 ] in string hexdigits retVal + '%%25%s' % payload[ i + 1 i + 3 ] i + 3else retVal + '%%25% 2X' % ord payload[i] i + 1re... | 83 |
python-test-5635 | python | What did not require admin role ? | geoserver rest | def data upload progress req if 'id' in req GET upload id str req GET['id'] if upload id in req session upload obj get object or 404 Upload import id upload id user req user upload session upload obj get session else upload session req session[upload id]import session upload session import sessionprogress import sessio... | def data_upload_progress req if 'id' in req GET upload_id str req GET['id'] if upload_id in req session upload_obj get_object_or_404 Upload import_id upload_id user req user upload_session upload_obj get_session else upload_session req session[upload_id]import_session upload_session import_sessionprogress import_sessio... | 69 |
python-test-5636 | python | What did geoserver rest not require ? | admin role | def data upload progress req if 'id' in req GET upload id str req GET['id'] if upload id in req session upload obj get object or 404 Upload import id upload id user req user upload session upload obj get session else upload session req session[upload id]import session upload session import sessionprogress import sessio... | def data_upload_progress req if 'id' in req GET upload_id str req GET['id'] if upload_id in req session upload_obj get_object_or_404 Upload import_id upload_id user req user upload_session upload_obj get_session else upload_session req session[upload_id]import_session upload_session import_sessionprogress import_sessio... | 69 |
python-test-5637 | python | Did geoserver rest require admin role ? | No | def data upload progress req if 'id' in req GET upload id str req GET['id'] if upload id in req session upload obj get object or 404 Upload import id upload id user req user upload session upload obj get session else upload session req session[upload id]import session upload session import sessionprogress import sessio... | def data_upload_progress req if 'id' in req GET upload_id str req GET['id'] if upload_id in req session upload_obj get_object_or_404 Upload import_id upload_id user req user upload_session upload_obj get_session else upload_session req session[upload_id]import_session upload_session import_sessionprogress import_sessio... | 69 |
python-test-5642 | python | What does the code calculate using the provided coefficients ? | the transformed points value | def get transformed points tps new points source points coefficients num points batch size to transform new points dimshuffle 0 'x' 1 2 stacked transform T tile to transform 1 num points 1 1 r 2 T sum stacked transform - source points dimshuffle 'x' 1 0 'x' ** 2 axis 2 log r 2 T log r 2 distances T switch T isnan log r... | def _get_transformed_points_tps new_points source_points coefficients num_points batch_size to_transform new_points dimshuffle 0 'x' 1 2 stacked_transform T tile to_transform 1 num_points 1 1 r_2 T sum stacked_transform - source_points dimshuffle 'x' 1 0 'x' ** 2 axis 2 log_r_2 T log r_2 distances T switch T isnan log_... | 118 |
python-test-5643 | python | What does the code use ? | the provided coefficients | def get transformed points tps new points source points coefficients num points batch size to transform new points dimshuffle 0 'x' 1 2 stacked transform T tile to transform 1 num points 1 1 r 2 T sum stacked transform - source points dimshuffle 'x' 1 0 'x' ** 2 axis 2 log r 2 T log r 2 distances T switch T isnan log r... | def _get_transformed_points_tps new_points source_points coefficients num_points batch_size to_transform new_points dimshuffle 0 'x' 1 2 stacked_transform T tile to_transform 1 num_points 1 1 r_2 T sum stacked_transform - source_points dimshuffle 'x' 1 0 'x' ** 2 axis 2 log_r_2 T log r_2 distances T switch T isnan log_... | 118 |
python-test-5644 | python | How does the code calculate the transformed points value ? | using the provided coefficients | def get transformed points tps new points source points coefficients num points batch size to transform new points dimshuffle 0 'x' 1 2 stacked transform T tile to transform 1 num points 1 1 r 2 T sum stacked transform - source points dimshuffle 'x' 1 0 'x' ** 2 axis 2 log r 2 T log r 2 distances T switch T isnan log r... | def _get_transformed_points_tps new_points source_points coefficients num_points batch_size to_transform new_points dimshuffle 0 'x' 1 2 stacked_transform T tile to_transform 1 num_points 1 1 r_2 T sum stacked_transform - source_points dimshuffle 'x' 1 0 'x' ** 2 axis 2 log_r_2 T log r_2 distances T switch T isnan log_... | 118 |
python-test-5645 | python | What does the code make ? | dict of lib | def get ids lines field bad ids None debug False result defaultdict list for line in lines if line startswith '>' fields map strip line[ 1 ] split label fields[ 0 ]if not ' ' in label continue lib id label rsplit ' ' 1 if bad ids and label in bad ids if debug print ' Excludedbadid %s' % label else result[lib] append fi... | def get_ids lines field bad_ids None debug False result defaultdict list for line in lines if line startswith '>' fields map strip line[1 ] split label fields[0]if not '_' in label continue lib id_ label rsplit '_' 1 if bad_ids and label in bad_ids if debug print 'Excludedbadid %s' % label else result[lib] append field... | 67 |
python-test-5650 | python | What does the code find ? | a zone by name or zone_id | def get zone by name conn module zone name want private zone id want vpc id for zone in conn get zones private zone module boolean zone config get ' Private Zone' False if private zone want private and zone name zone name and zone id None or zone id replace '/hostedzone/' '' zone id if want vpc id zone details conn get... | def get_zone_by_name conn module zone_name want_private zone_id want_vpc_id for zone in conn get_zones private_zone module boolean zone config get 'PrivateZone' False if private_zone want_private and zone name zone_name and zone_id None or zone id replace '/hostedzone/' '' zone_id if want_vpc_id zone_details conn get_h... | 104 |
python-test-5659 | python | What does the code compute ? | the composed sum prod(p2 for beta root of p1 ) | def rs compose add p1 p2 R p1 ringx R gens[ 0 ]prec p1 degree * p2 degree + 1 np 1 rs newton p1 x prec np 1 e rs hadamard exp np 1 np 2 rs newton p2 x prec np 2 e rs hadamard exp np 2 np 3 e rs mul np 1 e np 2 e x prec np 3 rs hadamard exp np 3 e True np 3 a np 3 [ 0 ] - np 3 / x q rs integrate np 3 a x q rs exp q x pr... | def rs_compose_add p1 p2 R p1 ringx R gens[0]prec p1 degree * p2 degree + 1 np1 rs_newton p1 x prec np1e rs_hadamard_exp np1 np2 rs_newton p2 x prec np2e rs_hadamard_exp np2 np3e rs_mul np1e np2e x prec np3 rs_hadamard_exp np3e True np3a np3[ 0 ] - np3 / x q rs_integrate np3a x q rs_exp q x prec q _invert_monoms q q q ... | 125 |
python-test-5660 | python | What does the code update ? | the quotas for a quota class | @utils arg 'class name' metavar '<class>' help ' Nameofquotaclasstosetthequotasfor ' @utils arg '--monitors' metavar '<monitors>' type int default None help ' Newvalueforthe"monitors"quota ' @utils arg '--snapshots' metavar '<snapshots>' type int default None help ' Newvalueforthe"snapshots"quota ' @utils arg '--gigaby... | @utils arg 'class_name' metavar '<class>' help 'Nameofquotaclasstosetthequotasfor ' @utils arg '--monitors' metavar '<monitors>' type int default None help 'Newvalueforthe"monitors"quota ' @utils arg '--snapshots' metavar '<snapshots>' type int default None help 'Newvalueforthe"snapshots"quota ' @utils arg '--gigabytes... | 69 |
python-test-5663 | python | What does the code check ? | all python source files in this directory and all subdirectories | def input dir dirname dirname dirname rstrip '/' if excluded dirname returnfor root dirs files in os walk dirname if options verbose message 'directory' + root options counters['directories'] options counters get 'directories' 0 + 1 dirs sort for subdir in dirs if excluded subdir dirs remove subdir files sort for filen... | def input_dir dirname dirname dirname rstrip '/' if excluded dirname returnfor root dirs files in os walk dirname if options verbose message 'directory' + root options counters['directories'] options counters get 'directories' 0 + 1 dirs sort for subdir in dirs if excluded subdir dirs remove subdir files sort for filen... | 60 |
python-test-5666 | python | What does the code get ? | definition location of a pattern or a match | def defined at if DEBUG frame inspect currentframe while frame try if frame f globals[' package '] package breakexcept Key Error breakframe frame f backret Frame frame f lineno frame f globals get ' package ' frame f globals get ' name ' frame f code co filename del framereturn ret | def defined_at if DEBUG frame inspect currentframe while frame try if frame f_globals['__package__'] __package__ breakexcept KeyError breakframe frame f_backret Frame frame f_lineno frame f_globals get '__package__' frame f_globals get '__name__' frame f_code co_filename del framereturn ret | 51 |
python-test-5667 | python | What disassembles a file ? | simple test program | def test if sys argv[ 1 ] if sys argv[ 2 ] sys stderr write 'usage pythondis py[- file]\n' sys exit 2 fn sys argv[ 1 ]if not fn or fn '-' fn Noneelse fn Noneif fn is None f sys stdinelse f open fn source f read if fn is not None f close else fn '<stdin>'code compile source fn 'exec' dis code | def _test if sys argv[1 ] if sys argv[2 ] sys stderr write 'usage pythondis py[- file]\n' sys exit 2 fn sys argv[1]if not fn or fn '-' fn Noneelse fn Noneif fn is None f sys stdinelse f open fn source f read if fn is not None f close else fn '<stdin>'code compile source fn 'exec' dis code | 64 |
python-test-5669 | python | What does the code execute if it starts with import ? | sitedir | def addpackage sitedir name known paths if known paths is None init pathinfo reset 1else reset 0fullname os path join sitedir name try f open fullname 'r U' except IO Error returntry for line in f if line startswith '#' continueif line startswith 'import' exec linecontinueline line rstrip dir dircase makepath sitedir l... | def addpackage sitedir name known_paths if known_paths is None _init_pathinfo reset 1else reset 0fullname os path join sitedir name try f open fullname 'rU' except IOError returntry for line in f if line startswith '#' continueif line startswith 'import' exec linecontinueline line rstrip dir dircase makepath sitedir li... | 82 |
python-test-5670 | python | How does the code add a new path to known_paths if it starts with import ? | by combining sitedir and name or execute sitedir | def addpackage sitedir name known paths if known paths is None init pathinfo reset 1else reset 0fullname os path join sitedir name try f open fullname 'r U' except IO Error returntry for line in f if line startswith '#' continueif line startswith 'import' exec linecontinueline line rstrip dir dircase makepath sitedir l... | def addpackage sitedir name known_paths if known_paths is None _init_pathinfo reset 1else reset 0fullname os path join sitedir name try f open fullname 'rU' except IOError returntry for line in f if line startswith '#' continueif line startswith 'import' exec linecontinueline line rstrip dir dircase makepath sitedir li... | 82 |
python-test-5671 | python | What does the code add if it starts with import by combining sitedir and name or execute sitedir ? | a new path to known_paths | def addpackage sitedir name known paths if known paths is None init pathinfo reset 1else reset 0fullname os path join sitedir name try f open fullname 'r U' except IO Error returntry for line in f if line startswith '#' continueif line startswith 'import' exec linecontinueline line rstrip dir dircase makepath sitedir l... | def addpackage sitedir name known_paths if known_paths is None _init_pathinfo reset 1else reset 0fullname os path join sitedir name try f open fullname 'rU' except IOError returntry for line in f if line startswith '#' continueif line startswith 'import' exec linecontinueline line rstrip dir dircase makepath sitedir li... | 82 |
python-test-5672 | python | What does this method create ? | a folder structure of the specified depth | def create folder structure depth 2 sibling 2 parent None if depth > 0 and sibling > 0 depth range list range 1 depth + 1 depth range reverse for d in depth range for s in range 1 sibling + 1 name 'folder %s--%s' % str d str s folder Folder name name parent parent folder save create folder structure depth d - 1 sibling... | def create_folder_structure depth 2 sibling 2 parent None if depth > 0 and sibling > 0 depth_range list range 1 depth + 1 depth_range reverse for d in depth_range for s in range 1 sibling + 1 name 'folder %s--%s' % str d str s folder Folder name name parent parent folder save create_folder_structure depth d - 1 sibling... | 69 |
python-test-5673 | python | What does the code retrieve ? | all nat gateways for a subnet | def gateway in subnet exists client subnet id allocation id None check mode False allocation id exists Falsegateways []states ['available' 'pending'] gws retrieved gws get nat gateways client subnet id states states check mode check mode if not gws retrieved return gateways allocation id exists for gw in gws for addres... | def gateway_in_subnet_exists client subnet_id allocation_id None check_mode False allocation_id_exists Falsegateways []states ['available' 'pending'] gws_retrieved _ gws get_nat_gateways client subnet_id states states check_mode check_mode if not gws_retrieved return gateways allocation_id_exists for gw in gws for addr... | 80 |
python-test-5682 | python | What were we trying for a while ? | to maintain * exact * stderr compatibility with cpython | def canonicalize stderr stderr stderr stderr strip split '\n' [ -1 ]substitutions [ " Name Error globalname'" " Name Error name'" " Attribute Error ' \\w+ 'objectattribute' \\w+ 'isread-only" ' Attribute Error \\ 2 ' ' Type Error object new \\ \\ takesnoparameters' ' Type Error object takesnoparameters' ' Index Error l... | def canonicalize_stderr stderr stderr stderr strip split '\n' [ -1 ]substitutions [ "NameError globalname'" "NameError name'" "AttributeError ' \\w+ 'objectattribute' \\w+ 'isread-only" 'AttributeError \\2' 'TypeError object __new__\\ \\ takesnoparameters' 'TypeError object takesnoparameters' 'IndexError listassignment... | 81 |
python-test-5683 | python | When were we trying to maintain * exact * stderr compatibility with cpython ? | for a while | def canonicalize stderr stderr stderr stderr strip split '\n' [ -1 ]substitutions [ " Name Error globalname'" " Name Error name'" " Attribute Error ' \\w+ 'objectattribute' \\w+ 'isread-only" ' Attribute Error \\ 2 ' ' Type Error object new \\ \\ takesnoparameters' ' Type Error object takesnoparameters' ' Index Error l... | def canonicalize_stderr stderr stderr stderr strip split '\n' [ -1 ]substitutions [ "NameError globalname'" "NameError name'" "AttributeError ' \\w+ 'objectattribute' \\w+ 'isread-only" 'AttributeError \\2' 'TypeError object __new__\\ \\ takesnoparameters' 'TypeError object takesnoparameters' 'IndexError listassignment... | 81 |
python-test-5685 | python | What does the code call ? | a last | def request lastfm method **kwargs kwargs['method'] methodkwargs setdefault 'api key' API KEY kwargs setdefault 'format' 'json' logger debug ' Calling Last F Mmethod %s' method logger debug ' Last F Mcallparameters %s' kwargs data request request json ENTRY POINT timeout TIMEOUT params kwargs lock lastfm lock if not da... | def request_lastfm method **kwargs kwargs['method'] methodkwargs setdefault 'api_key' API_KEY kwargs setdefault 'format' 'json' logger debug 'CallingLast FMmethod %s' method logger debug 'Last FMcallparameters %s' kwargs data request request_json ENTRY_POINT timeout TIMEOUT params kwargs lock lastfm_lock if not data lo... | 72 |
python-test-5686 | python | What does the code create ? | a testcase for ifilesystemsnapshots | def make ifilesystemsnapshots tests fixture class I Filesystem Snapshots Tests Async Test Case '\n Testsfor class `I Filesystem Snapshots`implementors \n\n Thesearefunctionaltestsifrunagainstrealfilesystems \n'def test interface self '\n Thetestedobjectprovides class `I Filesystem Snapshots` \n'fs snapshots fixture sel... | def make_ifilesystemsnapshots_tests fixture class IFilesystemSnapshotsTests AsyncTestCase '\nTestsfor class `IFilesystemSnapshots`implementors \n\nThesearefunctionaltestsifrunagainstrealfilesystems \n'def test_interface self '\nThetestedobjectprovides class `IFilesystemSnapshots` \n'fs_snapshots fixture self self asser... | 91 |
python-test-5687 | python | What did the code set ? | the zabbix component | def setup hass config from pyzabbix import Zabbix API Zabbix API Exceptionconf config[DOMAIN]if conf[CONF SSL] schema 'https'else schema 'http'url urljoin '{} //{}' format schema conf[CONF HOST] conf[CONF PATH] username conf get CONF USERNAME None password conf get CONF PASSWORD None zapi Zabbix API url try zapi login ... | def setup hass config from pyzabbix import ZabbixAPI ZabbixAPIExceptionconf config[DOMAIN]if conf[CONF_SSL] schema 'https'else schema 'http'url urljoin '{} //{}' format schema conf[CONF_HOST] conf[CONF_PATH] username conf get CONF_USERNAME None password conf get CONF_PASSWORD None zapi ZabbixAPI url try zapi login user... | 74 |
python-test-5688 | python | What does the code perform ? | a swirl transformation | def swirl image center None strength 1 radius 100 rotation 0 output shape None order 1 mode None cval 0 clip True preserve range False if mode is None warn ' Thedefaultof`mode`in`skimage transform swirl`willchangeto`reflect`inversion 0 15 ' mode 'constant'if center is None center np array image shape [ 2] / 2 warp args... | def swirl image center None strength 1 radius 100 rotation 0 output_shape None order 1 mode None cval 0 clip True preserve_range False if mode is None warn 'Thedefaultof`mode`in`skimage transform swirl`willchangeto`reflect`inversion0 15 ' mode 'constant'if center is None center np array image shape [ 2] / 2 warp_args {... | 85 |
python-test-5689 | python | What does the code get ? | the location of a cached requirements file ; caching if necessary | def get cached requirements requirements saltenv req file senv salt utils url parse requirements if senv saltenv senvif req file not in salt ['cp list master'] saltenv return Falsecached requirements salt ['cp is cached'] requirements saltenv if not cached requirements cached requirements salt ['cp cache file'] require... | def _get_cached_requirements requirements saltenv req_file senv salt utils url parse requirements if senv saltenv senvif req_file not in __salt__['cp list_master'] saltenv return Falsecached_requirements __salt__['cp is_cached'] requirements saltenv if not cached_requirements cached_requirements __salt__['cp cache_file... | 73 |
python-test-5690 | python | How d client i d and client secret initializes ? | based on the settings | def get oauth 2 client id and secret settings instance secret json getattr settings instance 'GOOGLE OAUTH 2 CLIENT SECRETS JSON' None if secret json is not None return load client secrets secret json else client id getattr settings instance 'GOOGLE OAUTH 2 CLIENT ID' None client secret getattr settings instance 'GOOGL... | def _get_oauth2_client_id_and_secret settings_instance secret_json getattr settings_instance 'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON' None if secret_json is not None return _load_client_secrets secret_json else client_id getattr settings_instance 'GOOGLE_OAUTH2_CLIENT_ID' None client_secret getattr settings_instance 'GOOGLE... | 101 |
python-test-5693 | python | What does the code find ? | all ccx derived from this course | @CELERY APP taskdef send ccx course published course key course key Course Locator from string course key for ccx in Custom Course For Ed X objects filter course id course key try ccx key CCX Locator from course locator course key unicode ccx id except Invalid Key Error log info ' Attempttopublishcoursewithdeprecatedid... | @CELERY_APP taskdef send_ccx_course_published course_key course_key CourseLocator from_string course_key for ccx in CustomCourseForEdX objects filter course_id course_key try ccx_key CCXLocator from_course_locator course_key unicode ccx id except InvalidKeyError log info 'Attempttopublishcoursewithdeprecatedid Course %... | 87 |
python-test-5694 | python | What does the code find ? | a suitable hardlink target | def hardlink if possible fullname node meta global targets writtentarget meta hardlink targettarget versions targets written get target if target versions for target path target vfs path target meta in target versions if hardlink compatible target path target vfs path target meta node meta try os link target path fulln... | def hardlink_if_possible fullname node meta global targets_writtentarget meta hardlink_targettarget_versions targets_written get target if target_versions for target_path target_vfs_path target_meta in target_versions if hardlink_compatible target_path target_vfs_path target_meta node meta try os link target_path fulln... | 82 |
python-test-5695 | python | What does the code solve ? | a standard eigenvalue problem | def eigenhproblem standard desc dim dtype overwrite lower turbo eigenvalues if iscomplex empty 1 dtype dtype a complex symrand dim dtype else a symrand dim astype dtype if overwrite a c a copy else a c a w z eigh a overwrite a overwrite lower lower eigvals eigenvalues assert dtype equal z dtype dtype w w astype dtype d... | def eigenhproblem_standard desc dim dtype overwrite lower turbo eigenvalues if iscomplex empty 1 dtype dtype a _complex_symrand dim dtype else a symrand dim astype dtype if overwrite a_c a copy else a_c a w z eigh a overwrite_a overwrite lower lower eigvals eigenvalues assert_dtype_equal z dtype dtype w w astype dtype ... | 75 |
python-test-5698 | python | What does the code subdivide ? | a cubic bezier curve defined by the control points cp | def bezier subdivide cp t c00 c01 c02 c03 cpc 10 c00 * 1 - t + c01 * t c11 c01 * 1 - t + c02 * t c12 c02 * 1 - t + c03 * t c20 c10 * 1 - t + c11 * t c21 c11 * 1 - t + c12 * t c30 c20 * 1 - t + c21 * t first [c 00 c10 c20 c30 ]second [c 30 c21 c12 c03 ]return first second | def bezier_subdivide cp t c00 c01 c02 c03 cpc10 c00 * 1 - t + c01 * t c11 c01 * 1 - t + c02 * t c12 c02 * 1 - t + c03 * t c20 c10 * 1 - t + c11 * t c21 c11 * 1 - t + c12 * t c30 c20 * 1 - t + c21 * t first [c00 c10 c20 c30]second [c30 c21 c12 c03]return first second | 85 |
python-test-5702 | python | What used in computation ? | the singular values | def pinv extended X rcond 1e- 15 X np asarray X X X conjugate u s vt np linalg svd X 0 s orig np copy s m u shape[ 0 ]n vt shape[ 1 ]cutoff rcond * np maximum reduce s for i in range min n m if s[i] > cutoff s[i] 1 0 / s[i] else s[i] 0 0res np dot np transpose vt np multiply s[ np core newaxis] np transpose u return re... | def pinv_extended X rcond 1e-15 X np asarray X X X conjugate u s vt np linalg svd X 0 s_orig np copy s m u shape[0]n vt shape[1]cutoff rcond * np maximum reduce s for i in range min n m if s[i] > cutoff s[i] 1 0 / s[i] else s[i] 0 0res np dot np transpose vt np multiply s[ np core newaxis] np transpose u return res s_o... | 80 |
python-test-5703 | python | Where did the singular values use ? | in computation | def pinv extended X rcond 1e- 15 X np asarray X X X conjugate u s vt np linalg svd X 0 s orig np copy s m u shape[ 0 ]n vt shape[ 1 ]cutoff rcond * np maximum reduce s for i in range min n m if s[i] > cutoff s[i] 1 0 / s[i] else s[i] 0 0res np dot np transpose vt np multiply s[ np core newaxis] np transpose u return re... | def pinv_extended X rcond 1e-15 X np asarray X X X conjugate u s vt np linalg svd X 0 s_orig np copy s m u shape[0]n vt shape[1]cutoff rcond * np maximum reduce s for i in range min n m if s[i] > cutoff s[i] 1 0 / s[i] else s[i] 0 0res np dot np transpose vt np multiply s[ np core newaxis] np transpose u return res s_o... | 80 |
python-test-5705 | python | What has the code move if it has no content before it ? | the split point up its ancestor chain | def adjust split point split point log sp split pointwhile True parent sp getparent if parent is None or barename parent tag in {u'body' u'html'} or parent text and parent text strip or parent index sp > 0 breaksp parentif sp is not split point log debug u' Adjustedsplitpointtoancestor' return sp | def adjust_split_point split_point log sp split_pointwhile True parent sp getparent if parent is None or barename parent tag in {u'body' u'html'} or parent text and parent text strip or parent index sp > 0 breaksp parentif sp is not split_point log debug u'Adjustedsplitpointtoancestor' return sp | 51 |
python-test-5706 | python | What do it have before it ? | no content | def adjust split point split point log sp split pointwhile True parent sp getparent if parent is None or barename parent tag in {u'body' u'html'} or parent text and parent text strip or parent index sp > 0 breaksp parentif sp is not split point log debug u' Adjustedsplitpointtoancestor' return sp | def adjust_split_point split_point log sp split_pointwhile True parent sp getparent if parent is None or barename parent tag in {u'body' u'html'} or parent text and parent text strip or parent index sp > 0 breaksp parentif sp is not split_point log debug u'Adjustedsplitpointtoancestor' return sp | 51 |
python-test-5707 | python | What is defining a convex polygon ? | 2-tuples | def contains point poly point n len poly c Falsei 0j n - 1 while i < n if poly[i][ 0 ] > point[ 0 ] poly[j][ 0 ] > point[ 0 ] and point[ 1 ] < poly[j][ 1 ] - poly[i][ 1 ] * point[ 0 ] - poly[i][ 0 ] / poly[j][ 0 ] - poly[i][ 0 ] + poly[i][ 1 ] c not c j ii + 1return c | def contains_point poly point n len poly c Falsei 0j n - 1 while i < n if poly[i][0] > point[0] poly[j][0] > point[0] and point[1] < poly[j][1] - poly[i][1] * point[0] - poly[i][0] / poly[j][0] - poly[i][0] + poly[i][1] c not c j ii + 1return c | 73 |
python-test-5708 | python | What do 2-tuples define ? | a convex polygon | def contains point poly point n len poly c Falsei 0j n - 1 while i < n if poly[i][ 0 ] > point[ 0 ] poly[j][ 0 ] > point[ 0 ] and point[ 1 ] < poly[j][ 1 ] - poly[i][ 1 ] * point[ 0 ] - poly[i][ 0 ] / poly[j][ 0 ] - poly[i][ 0 ] + poly[i][ 1 ] c not c j ii + 1return c | def contains_point poly point n len poly c Falsei 0j n - 1 while i < n if poly[i][0] > point[0] poly[j][0] > point[0] and point[1] < poly[j][1] - poly[i][1] * point[0] - poly[i][0] / poly[j][0] - poly[i][0] + poly[i][1] c not c j ii + 1return c | 73 |
python-test-5710 | python | What do function raise ? | skiptest exception | def skipif skip condition msg None def skip decorator f import noseif callable skip condition skip val lambda skip condition else skip val lambda skip condition def get msg func msg None ' Skipmessagewithinformationaboutfunctionbeingskipped 'if msg is None out ' Testskippedduetotestcondition'else out '\n' + msg return ... | def skipif skip_condition msg None def skip_decorator f import noseif callable skip_condition skip_val lambda skip_condition else skip_val lambda skip_condition def get_msg func msg None 'Skipmessagewithinformationaboutfunctionbeingskipped 'if msg is None out 'Testskippedduetotestcondition'else out '\n' + msg return 'S... | 123 |
python-test-5711 | python | What do a folder use ? | pip install | def test install folder using dot slash script script scratch path join 'mock' mkdir pkg path script scratch path / 'mock' pkg path join 'setup py' write mock 100 setup py result script pip 'install' ' /mock' egg folder script site packages / 'mock- 100 1-py%s egg-info' % pyversion assert egg folder in result files cre... | def test_install_folder_using_dot_slash script script scratch_path join 'mock' mkdir pkg_path script scratch_path / 'mock' pkg_path join 'setup py' write mock100_setup_py result script pip 'install' ' /mock' egg_folder script site_packages / 'mock-100 1-py%s egg-info' % pyversion assert egg_folder in result files_creat... | 58 |
python-test-5712 | python | What did the code customize for profile widgets and more popups ? | org_resource fields | def org customise org resource fields method s3 db current s3 dbtable s3 db org resourcetable location id represent s3 db gis Location Represent sep ' ' list fields ['organisation id' 'location id' 'parameter id' 'value' 'comments']if method in 'datalist' 'profile' table modified by represent s3 auth user represent nam... | def org_customise_org_resource_fields method s3db current s3dbtable s3db org_resourcetable location_id represent s3db gis_LocationRepresent sep ' ' list_fields ['organisation_id' 'location_id' 'parameter_id' 'value' 'comments']if method in 'datalist' 'profile' table modified_by represent s3_auth_user_represent_nametabl... | 81 |
python-test-5713 | python | What does the code get between inside and outside loops ? | extra loops | def get Extra Fill Loops loops radius greater Than Radius 1 4 * radius extra Fill Loops []centers intercircle get Centers From Points intercircle get Points From Loops loops greater Than Radius greater Than Radius for center in centers inset intercircle get Simplified Inset From Clockwise Loop center radius if intercir... | def getExtraFillLoops loops radius greaterThanRadius 1 4 * radius extraFillLoops []centers intercircle getCentersFromPoints intercircle getPointsFromLoops loops greaterThanRadius greaterThanRadius for center in centers inset intercircle getSimplifiedInsetFromClockwiseLoop center radius if intercircle isLargeSameDirecti... | 82 |
python-test-5714 | python | Where does the code get extra loops ? | between inside and outside loops | def get Extra Fill Loops loops radius greater Than Radius 1 4 * radius extra Fill Loops []centers intercircle get Centers From Points intercircle get Points From Loops loops greater Than Radius greater Than Radius for center in centers inset intercircle get Simplified Inset From Clockwise Loop center radius if intercir... | def getExtraFillLoops loops radius greaterThanRadius 1 4 * radius extraFillLoops []centers intercircle getCentersFromPoints intercircle getPointsFromLoops loops greaterThanRadius greaterThanRadius for center in centers inset intercircle getSimplifiedInsetFromClockwiseLoop center radius if intercircle isLargeSameDirecti... | 82 |
python-test-5721 | python | What does instances implement ? | pre / post stack operation methods | def get plug point class instances global pp class instancesif pp class instances is None pp class instances []pp classes []try slps resources global env get stack lifecycle plugins pp classes [cls for name cls in slps]except Exception LOG exception LE 'failedtogetlifecycleplugpointclasses' for ppc in pp classes try pp... | def get_plug_point_class_instances global pp_class_instancesif pp_class_instances is None pp_class_instances []pp_classes []try slps resources global_env get_stack_lifecycle_plugins pp_classes [cls for name cls in slps]except Exception LOG exception _LE 'failedtogetlifecycleplugpointclasses' for ppc in pp_classes try p... | 84 |
python-test-5723 | python | How does the code send numpy arrays ? | using the buffer interface and some metadata | def send arrays socket arrays stop False if arrays arrays [numpy ascontiguousarray array for array in arrays]if stop headers {'stop' True}socket send json headers else headers [header data from array 1 0 array for array in arrays]socket send json headers zmq SNDMORE for array in arrays[ -1 ] socket send array zmq SNDMO... | def send_arrays socket arrays stop False if arrays arrays [numpy ascontiguousarray array for array in arrays]if stop headers {'stop' True}socket send_json headers else headers [header_data_from_array_1_0 array for array in arrays]socket send_json headers zmq SNDMORE for array in arrays[ -1 ] socket send array zmq SNDMO... | 58 |
python-test-5730 | python | What does a redis client instance return ? | from given scrapy settings object | def get redis from settings settings params defaults REDIS PARAMS copy params update settings getdict 'REDIS PARAMS' for source dest in SETTINGS PARAMS MAP items val settings get source if val params[dest] valif isinstance params get 'redis cls' six string types params['redis cls'] load object params['redis cls'] retur... | def get_redis_from_settings settings params defaults REDIS_PARAMS copy params update settings getdict 'REDIS_PARAMS' for source dest in SETTINGS_PARAMS_MAP items val settings get source if val params[dest] valif isinstance params get 'redis_cls' six string_types params['redis_cls'] load_object params['redis_cls'] retur... | 51 |
python-test-5731 | python | What returns from given scrapy settings object ? | a redis client instance | def get redis from settings settings params defaults REDIS PARAMS copy params update settings getdict 'REDIS PARAMS' for source dest in SETTINGS PARAMS MAP items val settings get source if val params[dest] valif isinstance params get 'redis cls' six string types params['redis cls'] load object params['redis cls'] retur... | def get_redis_from_settings settings params defaults REDIS_PARAMS copy params update settings getdict 'REDIS_PARAMS' for source dest in SETTINGS_PARAMS_MAP items val settings get source if val params[dest] valif isinstance params get 'redis_cls' six string_types params['redis_cls'] load_object params['redis_cls'] retur... | 51 |
python-test-5754 | python | What does the code delete ? | the prefixed attributes | def get Cumulative Vector 3 Remove default Vector 3 element Node prefix if prefix '' default Vector 3 x evaluate get Evaluated Float default Vector 3 x element Node 'x' default Vector 3 y evaluate get Evaluated Float default Vector 3 y element Node 'y' default Vector 3 z evaluate get Evaluated Float default Vector 3 z ... | def getCumulativeVector3Remove defaultVector3 elementNode prefix if prefix '' defaultVector3 x evaluate getEvaluatedFloat defaultVector3 x elementNode 'x' defaultVector3 y evaluate getEvaluatedFloat defaultVector3 y elementNode 'y' defaultVector3 z evaluate getEvaluatedFloat defaultVector3 z elementNode 'z' euclidean r... | 100 |
python-test-5755 | python | What does the code get ? | cumulative vector3 | def get Cumulative Vector 3 Remove default Vector 3 element Node prefix if prefix '' default Vector 3 x evaluate get Evaluated Float default Vector 3 x element Node 'x' default Vector 3 y evaluate get Evaluated Float default Vector 3 y element Node 'y' default Vector 3 z evaluate get Evaluated Float default Vector 3 z ... | def getCumulativeVector3Remove defaultVector3 elementNode prefix if prefix '' defaultVector3 x evaluate getEvaluatedFloat defaultVector3 x elementNode 'x' defaultVector3 y evaluate getEvaluatedFloat defaultVector3 y elementNode 'y' defaultVector3 z evaluate getEvaluatedFloat defaultVector3 z elementNode 'z' euclidean r... | 100 |
python-test-5756 | python | For what purpose does the code send a request to the tool shed ? | to retrieve the current metadata for a repository of type tool_dependency_definition defined by the combination of a name and owner | def get tool dependency definition metadata from tool shed app tool shed url name owner tool shed url common util get tool shed url from tool shed registry app tool shed url params dict name name owner owner pathspec ['repository' 'get tool dependency definition metadata']metadata util url get tool shed url password mg... | def get_tool_dependency_definition_metadata_from_tool_shed app tool_shed_url name owner tool_shed_url common_util get_tool_shed_url_from_tool_shed_registry app tool_shed_url params dict name name owner owner pathspec ['repository' 'get_tool_dependency_definition_metadata']metadata util url_get tool_shed_url password_mg... | 68 |
python-test-5757 | python | For what purpose do the arn return ? | for a scaling policy in a specific autoscale group or none | def get scaling policy arn as group scaling policy name region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile policies conn get all policies as group as group for policy in policies if policy name scaling policy name return policy policy arnlog error ' Couldnotconv... | def get_scaling_policy_arn as_group scaling_policy_name region None key None keyid None profile None conn _get_conn region region key key keyid keyid profile profile policies conn get_all_policies as_group as_group for policy in policies if policy name scaling_policy_name return policy policy_arnlog error 'Couldnotconv... | 62 |
python-test-5758 | python | How do each string split in the series ? | by sep | def str get dummies arr sep ' ' arr arr fillna '' try arr sep + arr + sep except Type Error arr sep + arr astype str + sep tags set for ts in arr str split sep tags update ts tags sorted tags - set [''] dummies np empty len arr len tags dtype np int 64 for i t in enumerate tags pat sep + t + sep dummies[ i] lib map inf... | def str_get_dummies arr sep ' ' arr arr fillna '' try arr sep + arr + sep except TypeError arr sep + arr astype str + sep tags set for ts in arr str split sep tags update ts tags sorted tags - set [''] dummies np empty len arr len tags dtype np int64 for i t in enumerate tags pat sep + t + sep dummies[ i] lib map_infer... | 86 |
python-test-5765 | python | What does the code start ? | the intro | @given "I'vestartedtheintro" def step impl context go to manage page context start intro context modal context modal find css class with wait context MODAL CLASS wait time 30 context skip button modal find element by class name SKIP BUTTON CLASS context next button modal find element by class name NEXT BUTTON CLASS con... | @given "I'vestartedtheintro" def step_impl context go_to_manage_page context start_intro context modal context modal find_css_class_with_wait context MODAL_CLASS wait_time 30 context skip_button modal find_element_by_class_name SKIP_BUTTON_CLASS context next_button modal find_element_by_class_name NEXT_BUTTON_CLASS con... | 64 |
python-test-5767 | python | What does the code get ? | vlm_media instance position by name or instance i d | def libvlc vlm get media instance position p instance psz name i instance f Cfunctions get 'libvlc vlm get media instance position' None or Cfunction 'libvlc vlm get media instance position' 1 1 1 None ctypes c float Instance ctypes c char p ctypes c int return f p instance psz name i instance | def libvlc_vlm_get_media_instance_position p_instance psz_name i_instance f _Cfunctions get 'libvlc_vlm_get_media_instance_position' None or _Cfunction 'libvlc_vlm_get_media_instance_position' 1 1 1 None ctypes c_float Instance ctypes c_char_p ctypes c_int return f p_instance psz_name i_instance | 54 |
python-test-5769 | python | What does the code add dynamically ? | a querymanager for each | def add status query managers sender **kwargs if not issubclass sender Status Model returnfor value display in getattr sender u'STATUS' try sender meta get field value raise Improperly Configured u" Status Model Model'%s'hasafieldnamed'%s'whichconflictswithastatusofthesamename " % sender name value except Field Does No... | def add_status_query_managers sender **kwargs if not issubclass sender StatusModel returnfor value display in getattr sender u'STATUS' try sender _meta get_field value raise ImproperlyConfigured u"StatusModel Model'%s'hasafieldnamed'%s'whichconflictswithastatusofthesamename " % sender __name__ value except FieldDoesNot... | 52 |
python-test-5770 | python | What does a possible_string_format_functions ( ) method override ? | the standard pprint | def test possible string format functions t Q Table [ [1 2] * u m ] t['col 0 '] info format '% 3f'assert t pformat ['col 0 ' 'm' '-----' '1 000 ' '2 000 '] t['col 0 '] info format 'hi{ 3f}'assert t pformat ['col 0 ' 'm' '--------' 'hi 1 000 ' 'hi 2 000 '] t['col 0 '] info format ' 4f'assert t pformat ['col 0 ' 'm' '---... | def test_possible_string_format_functions t QTable [ [1 2] * u m ] t['col0'] info format '% 3f'assert t pformat ['col0' 'm' '-----' '1 000' '2 000'] t['col0'] info format 'hi{ 3f}'assert t pformat ['col0' 'm' '--------' 'hi1 000' 'hi2 000'] t['col0'] info format ' 4f'assert t pformat ['col0' 'm' '------' '1 0000' '2 00... | 78 |
python-test-5771 | python | What overrides the standard pprint ? | a possible_string_format_functions ( ) method | def test possible string format functions t Q Table [ [1 2] * u m ] t['col 0 '] info format '% 3f'assert t pformat ['col 0 ' 'm' '-----' '1 000 ' '2 000 '] t['col 0 '] info format 'hi{ 3f}'assert t pformat ['col 0 ' 'm' '--------' 'hi 1 000 ' 'hi 2 000 '] t['col 0 '] info format ' 4f'assert t pformat ['col 0 ' 'm' '---... | def test_possible_string_format_functions t QTable [ [1 2] * u m ] t['col0'] info format '% 3f'assert t pformat ['col0' 'm' '-----' '1 000' '2 000'] t['col0'] info format 'hi{ 3f}'assert t pformat ['col0' 'm' '--------' 'hi1 000' 'hi2 000'] t['col0'] info format ' 4f'assert t pformat ['col0' 'm' '------' '1 0000' '2 00... | 78 |
python-test-5773 | python | For what purpose does the code provide a session - like object called " channel_session " to consumers ? | as a message attribute that will auto - persist across consumers with the same incoming " reply_channel " value | def channel session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel session' try return func message *args **kwargs finally if message channel session modified message channel session save if not message reply channel raise Value Error ' Noreply channelsenttoconsumer @channel ses... | def channel_session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel_session' try return func message *args **kwargs finally if message channel_session modified message channel_session save if not message reply_channel raise ValueError 'Noreply_channelsenttoconsumer @channel_sessi... | 99 |
python-test-5774 | python | What will auto across consumers ? | a message attribute | def channel session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel session' try return func message *args **kwargs finally if message channel session modified message channel session save if not message reply channel raise Value Error ' Noreply channelsenttoconsumer @channel ses... | def channel_session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel_session' try return func message *args **kwargs finally if message channel_session modified message channel_session save if not message reply_channel raise ValueError 'Noreply_channelsenttoconsumer @channel_sessi... | 99 |
python-test-5775 | python | How will a message attribute auto across consumers ? | with the same incoming " reply_channel " value | def channel session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel session' try return func message *args **kwargs finally if message channel session modified message channel session save if not message reply channel raise Value Error ' Noreply channelsenttoconsumer @channel ses... | def channel_session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel_session' try return func message *args **kwargs finally if message channel_session modified message channel_session save if not message reply_channel raise ValueError 'Noreply_channelsenttoconsumer @channel_sessi... | 99 |
python-test-5776 | python | Where will a message attribute auto with the same incoming " reply_channel " value ? | across consumers | def channel session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel session' try return func message *args **kwargs finally if message channel session modified message channel session save if not message reply channel raise Value Error ' Noreply channelsenttoconsumer @channel ses... | def channel_session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel_session' try return func message *args **kwargs finally if message channel_session modified message channel_session save if not message reply_channel raise ValueError 'Noreply_channelsenttoconsumer @channel_sessi... | 99 |
python-test-5777 | python | What does the code provide to consumers as a message attribute that will auto - persist across consumers with the same incoming " reply_channel " value ? | a session - like object called " channel_session " | def channel session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel session' try return func message *args **kwargs finally if message channel session modified message channel session save if not message reply channel raise Value Error ' Noreply channelsenttoconsumer @channel ses... | def channel_session func @functools wraps func def inner message *args **kwargs if hasattr message 'channel_session' try return func message *args **kwargs finally if message channel_session modified message channel_session save if not message reply_channel raise ValueError 'Noreply_channelsenttoconsumer @channel_sessi... | 99 |
python-test-5781 | python | What does the code add ? | subparsers for all the registered export plugins | def Add Plugins Subparsers classes sorted export plugins plugin Export Plugin classes itervalues key lambda cls cls name subparsers flags PARSER add subparsers title ' Subcommands' for cls in classes if not cls name continuesubparser subparsers add parser cls name help cls description plugin obj cls plugin obj Configur... | def AddPluginsSubparsers classes sorted export_plugins plugin ExportPlugin classes itervalues key lambda cls cls name subparsers flags PARSER add_subparsers title 'Subcommands' for cls in classes if not cls name continuesubparser subparsers add_parser cls name help cls description plugin_obj cls plugin_obj ConfigureArg... | 59 |
python-test-5786 | python | What does the code create for the given instant ? | a time only timestamp | def time hour None min None sec None micro None offset None obj False now dt datetime utcnow if hour is None hour now hourif min is None min now minuteif sec is None sec now secondif micro is None micro now microsecondif offset is None offset tzutc elif not isinstance offset dt tzinfo offset tzoffset None offset value ... | def time hour None min None sec None micro None offset None obj False now dt datetime utcnow if hour is None hour now hourif min is None min now minuteif sec is None sec now secondif micro is None micro now microsecondif offset is None offset tzutc elif not isinstance offset dt tzinfo offset tzoffset None offset value ... | 73 |
python-test-5787 | python | When does the code create a time only timestamp ? | for the given instant | def time hour None min None sec None micro None offset None obj False now dt datetime utcnow if hour is None hour now hourif min is None min now minuteif sec is None sec now secondif micro is None micro now microsecondif offset is None offset tzutc elif not isinstance offset dt tzinfo offset tzoffset None offset value ... | def time hour None min None sec None micro None offset None obj False now dt datetime utcnow if hour is None hour now hourif min is None min now minuteif sec is None sec now secondif micro is None micro now microsecondif offset is None offset tzutc elif not isinstance offset dt tzinfo offset tzoffset None offset value ... | 73 |
python-test-5789 | python | What will a generator return to sync with parent cells ? | a list of active and deleted instances | def get instances to sync context updated since None project id None deleted True shuffle False uuids only False filters {}if updated since is not None filters['changes-since'] updated sinceif project id is not None filters['project id'] project idif not deleted filters['deleted'] Falseinstances db instance get all by ... | def get_instances_to_sync context updated_since None project_id None deleted True shuffle False uuids_only False filters {}if updated_since is not None filters['changes-since'] updated_sinceif project_id is not None filters['project_id'] project_idif not deleted filters['deleted'] Falseinstances db instance_get_all_by_... | 69 |
python-test-5790 | python | For what purpose will a generator return a list of active and deleted instances ? | to sync with parent cells | def get instances to sync context updated since None project id None deleted True shuffle False uuids only False filters {}if updated since is not None filters['changes-since'] updated sinceif project id is not None filters['project id'] project idif not deleted filters['deleted'] Falseinstances db instance get all by ... | def get_instances_to_sync context updated_since None project_id None deleted True shuffle False uuids_only False filters {}if updated_since is not None filters['changes-since'] updated_sinceif project_id is not None filters['project_id'] project_idif not deleted filters['deleted'] Falseinstances db instance_get_all_by_... | 69 |
python-test-5791 | python | What does the code identify ? | all listening processes within the given namespace | def kill listen processes namespace force False pids find listen pids namespace namespace pids to kill {utils find fork top parent pid for pid in pids}kill signal signal SIGTER Mif force kill signal signal SIGKIL Lchildren [utils find child pids pid True for pid in pids to kill]pids to kill update itertools chain from ... | def _kill_listen_processes namespace force False pids find_listen_pids_namespace namespace pids_to_kill {utils find_fork_top_parent pid for pid in pids}kill_signal signal SIGTERMif force kill_signal signal SIGKILLchildren [utils find_child_pids pid True for pid in pids_to_kill]pids_to_kill update itertools chain from_i... | 124 |
python-test-5795 | python | What saves from dict to file ? | tweets | def save tweets filename tweets if len tweets 0 returntry archive open filename 'w' except IO Error as e err ' Cannotsavetweets %s' % str e returnfor k in sorted tweets keys try archive write '%i%s\n' % k tweets[k] encode 'utf- 8 ' except Exception as ex err 'archivingtweet%sfaileddueto%s' % k unicode ex archive close | def save_tweets filename tweets if len tweets 0 returntry archive open filename 'w' except IOError as e err 'Cannotsavetweets %s' % str e returnfor k in sorted tweets keys try archive write '%i%s\n' % k tweets[k] encode 'utf-8' except Exception as ex err 'archivingtweet%sfaileddueto%s' % k unicode ex archive close | 55 |
python-test-5796 | python | What do tweets save ? | from dict to file | def save tweets filename tweets if len tweets 0 returntry archive open filename 'w' except IO Error as e err ' Cannotsavetweets %s' % str e returnfor k in sorted tweets keys try archive write '%i%s\n' % k tweets[k] encode 'utf- 8 ' except Exception as ex err 'archivingtweet%sfaileddueto%s' % k unicode ex archive close | def save_tweets filename tweets if len tweets 0 returntry archive open filename 'w' except IOError as e err 'Cannotsavetweets %s' % str e returnfor k in sorted tweets keys try archive write '%i%s\n' % k tweets[k] encode 'utf-8' except Exception as ex err 'archivingtweet%sfaileddueto%s' % k unicode ex archive close | 55 |
python-test-5797 | python | What handles the given request ? | a spider class | def spidercls for request spider loader request default spidercls None log none False log multiple False snames spider loader find by request request if len snames 1 return spider loader load snames[ 0 ] if len snames > 1 and log multiple logger error ' Morethanonespidercanhandle % request s-% snames s' {'request' requ... | def spidercls_for_request spider_loader request default_spidercls None log_none False log_multiple False snames spider_loader find_by_request request if len snames 1 return spider_loader load snames[0] if len snames > 1 and log_multiple logger error 'Morethanonespidercanhandle % request s-% snames s' {'request' request... | 78 |
python-test-5800 | python | What do all classes use to set the appropriate fonts ? | pdf | def set fonts self font set current deployment settings get pdf export font if font set try font name font set[ 0 ]font name bold font set[ 1 ]folder current request folderpdfmetrics register Font TT Font font name os path join folder 'static' 'fonts' '%s ttf' % font name pdfmetrics register Font TT Font font name bold... | def set_fonts self font_set current deployment_settings get_pdf_export_font if font_set try font_name font_set[0]font_name_bold font_set[1]folder current request folderpdfmetrics registerFont TTFont font_name os path join folder 'static' 'fonts' '%s ttf' % font_name pdfmetrics registerFont TTFont font_name_bold os path... | 116 |
python-test-5801 | python | What do all classes set ? | the appropriate fonts | def set fonts self font set current deployment settings get pdf export font if font set try font name font set[ 0 ]font name bold font set[ 1 ]folder current request folderpdfmetrics register Font TT Font font name os path join folder 'static' 'fonts' '%s ttf' % font name pdfmetrics register Font TT Font font name bold... | def set_fonts self font_set current deployment_settings get_pdf_export_font if font_set try font_name font_set[0]font_name_bold font_set[1]folder current request folderpdfmetrics registerFont TTFont font_name os path join folder 'static' 'fonts' '%s ttf' % font_name pdfmetrics registerFont TTFont font_name_bold os path... | 116 |
python-test-5802 | python | What do all classes use pdf ? | to set the appropriate fonts | def set fonts self font set current deployment settings get pdf export font if font set try font name font set[ 0 ]font name bold font set[ 1 ]folder current request folderpdfmetrics register Font TT Font font name os path join folder 'static' 'fonts' '%s ttf' % font name pdfmetrics register Font TT Font font name bold... | def set_fonts self font_set current deployment_settings get_pdf_export_font if font_set try font_name font_set[0]font_name_bold font_set[1]folder current request folderpdfmetrics registerFont TTFont font_name os path join folder 'static' 'fonts' '%s ttf' % font_name pdfmetrics registerFont TTFont font_name_bold os path... | 116 |
python-test-5805 | python | What does the code create ? | a list of : class :~ subliminal | def create download tasks subtitles by video languages multi tasks []for video subtitles in subtitles by video iteritems if not subtitles continueif not multi task Download Task video list subtitles logger debug u' Createdtask%r' % task tasks append task continuefor by language in groupby subtitles lambda s languages i... | def create_download_tasks subtitles_by_video languages multi tasks []for video subtitles in subtitles_by_video iteritems if not subtitles continueif not multi task DownloadTask video list subtitles logger debug u'Createdtask%r' % task tasks append task continuefor _ by_language in groupby subtitles lambda s languages i... | 69 |
python-test-5808 | python | What do the user do ? | action action | def hue permission required action app def decorator view func @wraps view func def decorated request *args **kwargs if not request user has hue permission action app raise Popup Exception ' Permissiondenied % action s/% app s ' % {'action' action 'app' app} return view func request *args **kwargs return decoratedretur... | def hue_permission_required action app def decorator view_func @wraps view_func def decorated request *args **kwargs if not request user has_hue_permission action app raise PopupException _ 'Permissiondenied % action s/% app s ' % {'action' action 'app' app} return view_func request *args **kwargs return decoratedretur... | 52 |
python-test-5809 | python | What does the user have ? | permissions to do action action on app app | def hue permission required action app def decorator view func @wraps view func def decorated request *args **kwargs if not request user has hue permission action app raise Popup Exception ' Permissiondenied % action s/% app s ' % {'action' action 'app' app} return view func request *args **kwargs return decoratedretur... | def hue_permission_required action app def decorator view_func @wraps view_func def decorated request *args **kwargs if not request user has_hue_permission action app raise PopupException _ 'Permissiondenied % action s/% app s ' % {'action' action 'app' app} return view_func request *args **kwargs return decoratedretur... | 52 |
python-test-5815 | python | What does the code generate ? | the response for a hybi-00 challenge | def complete hybi 00 headers challenge key 1 headers[' Sec- Web Socket- Key 1 ']key 2 headers[' Sec- Web Socket- Key 2 ']first int '' join i for i in key 1 if i in digits // key 1 count '' second int '' join i for i in key 2 if i in digits // key 2 count '' nonce pack '>II 8 s' first second challenge return md 5 nonce ... | def complete_hybi00 headers challenge key1 headers['Sec-WebSocket-Key1']key2 headers['Sec-WebSocket-Key2']first int '' join i for i in key1 if i in digits // key1 count '' second int '' join i for i in key2 if i in digits // key2 count '' nonce pack '>II8s' first second challenge return md5 nonce digest | 73 |
python-test-5818 | python | What writes the bytes to the specified stream ? | the code given a set of images | def write Gif To File fp images durations loops frames 0previous Nonefor im in images if not previous palette getheader im [1 ]data getdata im imdes data data[ 0 ] data[ 1 ] header getheader Anim im appext get App Ext loops graphext get Graphics Control Ext durations[ 0 ] fp write header fp write palette fp write appex... | def _writeGifToFile fp images durations loops frames 0previous Nonefor im in images if not previous palette getheader im [1]data getdata im imdes data data[0] data[1 ] header getheaderAnim im appext getAppExt loops graphext getGraphicsControlExt durations[0] fp write header fp write palette fp write appext fp write gra... | 116 |
python-test-5821 | python | For what purpose do template_html html template send ? | to send as new message part context a dictionary to pass into the template calls | @task queue 'web' time limit EMAIL TIME LIMIT def send email task recipient subject template template html context None msg Email Multi Alternatives subject get template template render context settings DEFAULT FROM EMAIL [recipient] try msg attach alternative get template template html render context 'text/html' excep... | @task queue 'web' time_limit EMAIL_TIME_LIMIT def send_email_task recipient subject template template_html context None msg EmailMultiAlternatives subject get_template template render context settings DEFAULT_FROM_EMAIL [recipient] try msg attach_alternative get_template template_html render context 'text/html' except ... | 58 |
python-test-5822 | python | For what purpose does the code send email recipient email recipient address subject email subject header template plain text template ? | to send template_html html template to send as new message part context a dictionary to pass into the template calls | @task queue 'web' time limit EMAIL TIME LIMIT def send email task recipient subject template template html context None msg Email Multi Alternatives subject get template template render context settings DEFAULT FROM EMAIL [recipient] try msg attach alternative get template template html render context 'text/html' excep... | @task queue 'web' time_limit EMAIL_TIME_LIMIT def send_email_task recipient subject template template_html context None msg EmailMultiAlternatives subject get_template template render context settings DEFAULT_FROM_EMAIL [recipient] try msg attach_alternative get_template template_html render context 'text/html' except ... | 58 |
python-test-5823 | python | What does the code send to send template_html html template to send as new message part context a dictionary to pass into the template calls ? | email recipient email recipient address subject email subject header template plain text template | @task queue 'web' time limit EMAIL TIME LIMIT def send email task recipient subject template template html context None msg Email Multi Alternatives subject get template template render context settings DEFAULT FROM EMAIL [recipient] try msg attach alternative get template template html render context 'text/html' excep... | @task queue 'web' time_limit EMAIL_TIME_LIMIT def send_email_task recipient subject template template_html context None msg EmailMultiAlternatives subject get_template template render context settings DEFAULT_FROM_EMAIL [recipient] try msg attach_alternative get_template template_html render context 'text/html' except ... | 58 |
python-test-5825 | python | What does the code get ? | qiime version and the git sha + current branch | def get qiime library version qiime dir get qiime project dir qiime version qiime library versionsha cmd 'git--git-dir%s/ gitrev-parse HEAD' % qiime dir sha o sha e sha r qiime system call sha cmd git sha sha o strip branch cmd 'git--git-dir%s/ gitrev-parse--abbrev-ref HEAD' % qiime dir branch o branch e branch r qiime... | def get_qiime_library_version qiime_dir get_qiime_project_dir qiime_version qiime_library_versionsha_cmd 'git--git-dir%s/ gitrev-parseHEAD' % qiime_dir sha_o sha_e sha_r qiime_system_call sha_cmd git_sha sha_o strip branch_cmd 'git--git-dir%s/ gitrev-parse--abbrev-refHEAD' % qiime_dir branch_o branch_e branch_r qiime_s... | 94 |
python-test-5833 | python | What did the code give ? | data from an illumina qseq file | def illumina data to fastq record data number of bases None seq index 8qual index 9pass filter index 10 try pass filter int record data[pass filter index] except Index Error pass filter 2if number of bases is None seq record data[seq index] replace ' ' 'N' qual record data[qual index]else seq record data[seq index][ nu... | def illumina_data_to_fastq record_data number_of_bases None seq_index 8qual_index 9pass_filter_index 10try pass_filter int record_data[pass_filter_index] except IndexError pass_filter 2if number_of_bases is None seq record_data[seq_index] replace ' ' 'N' qual record_data[qual_index]else seq record_data[seq_index][ numb... | 115 |
python-test-5835 | python | What does the code setup ? | the miflora sensor | def setup platform hass config add devices discovery info None from miflora import miflora pollercache config get CONF CACHE poller miflora poller Mi Flora Poller config get CONF MAC cache timeout cache force update config get CONF FORCE UPDATE median config get CONF MEDIAN poller ble timeout config get CONF TIMEOUT po... | def setup_platform hass config add_devices discovery_info None from miflora import miflora_pollercache config get CONF_CACHE poller miflora_poller MiFloraPoller config get CONF_MAC cache_timeout cache force_update config get CONF_FORCE_UPDATE median config get CONF_MEDIAN poller ble_timeout config get CONF_TIMEOUT poll... | 102 |
python-test-5839 | python | What does the code see ? | URL for more | @pytest mark skipif 'not HAS YAML' def test regression 5604 t Table t meta {'foo' 5 * u km 'foo 2 ' u s}t['bar'] [7 ] * u km out String IO t write out format 'ascii ecsv' assert ' astropy units Unit' in out getvalue assert ' astropy units Quantity' in out getvalue | @pytest mark skipif 'notHAS_YAML' def test_regression_5604 t Table t meta {'foo' 5 * u km 'foo2' u s}t['bar'] [7] * u km out StringIO t write out format 'ascii ecsv' assert ' astropy units Unit' in out getvalue assert ' astropy units Quantity' in out getvalue | 54 |
python-test-5841 | python | What has that inverse applied when the inverse of another model ? | a compound model with a custom inverse | def test compound custom inverse poly Polynomial 1 D 1 c0 1 c1 2 scale Scale 1 shift Shift 1 model 1 poly scale model 1 inverse polymodel 2 shift model 1 assert allclose model 2 inverse 1 poly shift inverse 1 with pytest raises Not Implemented Error shift + model 1 inversewith pytest raises Not Implemented Error model ... | def test_compound_custom_inverse poly Polynomial1D 1 c0 1 c1 2 scale Scale 1 shift Shift 1 model1 poly scale model1 inverse polymodel2 shift model1 assert_allclose model2 inverse 1 poly shift inverse 1 with pytest raises NotImplementedError shift + model1 inversewith pytest raises NotImplementedError model1 & poly inve... | 63 |
python-test-5842 | python | When did that inverse apply ? | when the inverse of another model | def test compound custom inverse poly Polynomial 1 D 1 c0 1 c1 2 scale Scale 1 shift Shift 1 model 1 poly scale model 1 inverse polymodel 2 shift model 1 assert allclose model 2 inverse 1 poly shift inverse 1 with pytest raises Not Implemented Error shift + model 1 inversewith pytest raises Not Implemented Error model ... | def test_compound_custom_inverse poly Polynomial1D 1 c0 1 c1 2 scale Scale 1 shift Shift 1 model1 poly scale model1 inverse polymodel2 shift model1 assert_allclose model2 inverse 1 poly shift inverse 1 with pytest raises NotImplementedError shift + model1 inversewith pytest raises NotImplementedError model1 & poly inve... | 63 |
python-test-5843 | python | What do a compound model with a custom inverse have ? | that inverse applied when the inverse of another model | def test compound custom inverse poly Polynomial 1 D 1 c0 1 c1 2 scale Scale 1 shift Shift 1 model 1 poly scale model 1 inverse polymodel 2 shift model 1 assert allclose model 2 inverse 1 poly shift inverse 1 with pytest raises Not Implemented Error shift + model 1 inversewith pytest raises Not Implemented Error model ... | def test_compound_custom_inverse poly Polynomial1D 1 c0 1 c1 2 scale Scale 1 shift Shift 1 model1 poly scale model1 inverse polymodel2 shift model1 assert_allclose model2 inverse 1 poly shift inverse 1 with pytest raises NotImplementedError shift + model1 inversewith pytest raises NotImplementedError model1 & poly inve... | 63 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.