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-4701 | python | What is providing on win_id 0 and 1 ? | a fake tabbed - browser object | @pytest fixturedef tabbed browser stubs stubs win registry win registry add window 1 stubs [stubs Tabbed Browser Stub stubs Tabbed Browser Stub ]objreg register 'tabbed-browser' stubs[ 0 ] scope 'window' window 0 objreg register 'tabbed-browser' stubs[ 1 ] scope 'window' window 1 yield stubs objreg delete 'tabbed-brows... | @pytest fixturedef tabbed_browser_stubs stubs win_registry win_registry add_window 1 stubs [stubs TabbedBrowserStub stubs TabbedBrowserStub ]objreg register 'tabbed-browser' stubs[0] scope 'window' window 0 objreg register 'tabbed-browser' stubs[1] scope 'window' window 1 yield stubs objreg delete 'tabbed-browser' scop... | 58 |
python-test-4702 | python | Where do a fake tabbed - browser object provide ? | on win_id 0 and 1 | @pytest fixturedef tabbed browser stubs stubs win registry win registry add window 1 stubs [stubs Tabbed Browser Stub stubs Tabbed Browser Stub ]objreg register 'tabbed-browser' stubs[ 0 ] scope 'window' window 0 objreg register 'tabbed-browser' stubs[ 1 ] scope 'window' window 1 yield stubs objreg delete 'tabbed-brows... | @pytest fixturedef tabbed_browser_stubs stubs win_registry win_registry add_window 1 stubs [stubs TabbedBrowserStub stubs TabbedBrowserStub ]objreg register 'tabbed-browser' stubs[0] scope 'window' window 0 objreg register 'tabbed-browser' stubs[1] scope 'window' window 1 yield stubs objreg delete 'tabbed-browser' scop... | 58 |
python-test-4718 | python | What does the code strip from the req ? | the additional properties | def strip additional query parameters schema req additional properties schema get 'addtional Properties' True pattern regexes []patterns schema get 'pattern Properties' None if patterns for regex in patterns pattern regexes append re compile regex if additional properties for param in set req GET keys if param not in s... | def _strip_additional_query_parameters schema req additional_properties schema get 'addtionalProperties' True pattern_regexes []patterns schema get 'patternProperties' None if patterns for regex in patterns pattern_regexes append re compile regex if additional_properties for param in set req GET keys if param not in sc... | 66 |
python-test-4719 | python | What does yaml parse as floats ? | scientific notation | def test scientific notation loaded load 'a {a 1e 3 b 1 E4 c -1 e- 3 d 2 3e+ 4 e 2e 4 f 23 53 e 1 g 32284 2e+ 9 h 2 333993939 e- 3 }' assert isinstance loaded['a']['a'] float assert isinstance loaded['a']['b'] float assert isinstance loaded['a']['c'] float assert isinstance loaded['a']['d'] float assert isinstance load... | def test_scientific_notation loaded load 'a {a 1e3 b 1 E4 c -1e-3 d 2 3e+4 e 2e4 f 23 53e1 g 32284 2e+9 h 2 333993939e-3}' assert isinstance loaded['a']['a'] float assert isinstance loaded['a']['b'] float assert isinstance loaded['a']['c'] float assert isinstance loaded['a']['d'] float assert isinstance loaded['a']['e'... | 71 |
python-test-4720 | python | What parses scientific notation as floats ? | yaml | def test scientific notation loaded load 'a {a 1e 3 b 1 E4 c -1 e- 3 d 2 3e+ 4 e 2e 4 f 23 53 e 1 g 32284 2e+ 9 h 2 333993939 e- 3 }' assert isinstance loaded['a']['a'] float assert isinstance loaded['a']['b'] float assert isinstance loaded['a']['c'] float assert isinstance loaded['a']['d'] float assert isinstance load... | def test_scientific_notation loaded load 'a {a 1e3 b 1 E4 c -1e-3 d 2 3e+4 e 2e4 f 23 53e1 g 32284 2e+9 h 2 333993939e-3}' assert isinstance loaded['a']['a'] float assert isinstance loaded['a']['b'] float assert isinstance loaded['a']['c'] float assert isinstance loaded['a']['d'] float assert isinstance loaded['a']['e'... | 71 |
python-test-4721 | python | How does yaml parse scientific notation ? | as floats | def test scientific notation loaded load 'a {a 1e 3 b 1 E4 c -1 e- 3 d 2 3e+ 4 e 2e 4 f 23 53 e 1 g 32284 2e+ 9 h 2 333993939 e- 3 }' assert isinstance loaded['a']['a'] float assert isinstance loaded['a']['b'] float assert isinstance loaded['a']['c'] float assert isinstance loaded['a']['d'] float assert isinstance load... | def test_scientific_notation loaded load 'a {a 1e3 b 1 E4 c -1e-3 d 2 3e+4 e 2e4 f 23 53e1 g 32284 2e+9 h 2 333993939e-3}' assert isinstance loaded['a']['a'] float assert isinstance loaded['a']['b'] float assert isinstance loaded['a']['c'] float assert isinstance loaded['a']['d'] float assert isinstance loaded['a']['e'... | 71 |
python-test-4726 | python | What does the code create ? | a new plugin based on the cookiecutter plugin template | @plugins command 'new' @click argument 'plugin identifier' callback check cookiecutter @click option '--template' '-t' type click STRING default 'https //github com/sh 4 nks/cookiecutter-flaskbb-plugin' help ' Pathtoacookiecuttertemplateortoavalidgitrepo ' def new plugin plugin identifier template out dir os path join ... | @plugins command 'new' @click argument 'plugin_identifier' callback check_cookiecutter @click option '--template' '-t' type click STRING default 'https //github com/sh4nks/cookiecutter-flaskbb-plugin' help 'Pathtoacookiecuttertemplateortoavalidgitrepo ' def new_plugin plugin_identifier template out_dir os path join cur... | 72 |
python-test-4735 | python | What do grid parameters get if true ? | from a frequency array parameters frequency : array_like or quantity input frequency grid assume_regular_frequency : bool | def get frequency grid frequency assume regular frequency False frequency np asarray frequency if frequency ndim 1 raise Value Error 'frequencygridmustbe 1 dimensional' elif len frequency 1 return frequency[ 0 ] frequency[ 0 ] 1 elif not assume regular frequency or is regular frequency raise Value Error 'frequencymustb... | def _get_frequency_grid frequency assume_regular_frequency False frequency np asarray frequency if frequency ndim 1 raise ValueError 'frequencygridmustbe1dimensional' elif len frequency 1 return frequency[0] frequency[0] 1 elif not assume_regular_frequency or _is_regular frequency raise ValueError 'frequencymustbearegu... | 61 |
python-test-4736 | python | What gets from a frequency array parameters frequency : array_like or quantity input frequency grid assume_regular_frequency : bool if true ? | grid parameters | def get frequency grid frequency assume regular frequency False frequency np asarray frequency if frequency ndim 1 raise Value Error 'frequencygridmustbe 1 dimensional' elif len frequency 1 return frequency[ 0 ] frequency[ 0 ] 1 elif not assume regular frequency or is regular frequency raise Value Error 'frequencymustb... | def _get_frequency_grid frequency assume_regular_frequency False frequency np asarray frequency if frequency ndim 1 raise ValueError 'frequencygridmustbe1dimensional' elif len frequency 1 return frequency[0] frequency[0] 1 elif not assume_regular_frequency or _is_regular frequency raise ValueError 'frequencymustbearegu... | 61 |
python-test-4737 | python | What does the code kill ? | the salt minion | def kill timeout 15 ret {'killed' None 'retcode' 1}comment []pid grains get 'pid' if not pid comment append ' Unabletofind"pid"ingrains' ret['retcode'] salt defaults exitcodes EX SOFTWAR Eelif 'ps kill pid' not in salt comment append ' Missingcommand ps kill pid' ret['retcode'] salt defaults exitcodes EX SOFTWAR Eelse ... | def kill timeout 15 ret {'killed' None 'retcode' 1}comment []pid __grains__ get 'pid' if not pid comment append 'Unabletofind"pid"ingrains' ret['retcode'] salt defaults exitcodes EX_SOFTWAREelif 'ps kill_pid' not in __salt__ comment append 'Missingcommand ps kill_pid' ret['retcode'] salt defaults exitcodes EX_SOFTWAREe... | 96 |
python-test-4738 | python | What does the code open ? | a fif file for writing | def start file fname id None if isinstance fname string types if op splitext fname [1 ] lower ' gz' logger debug ' Writingusinggzip' fid Gzip File fname 'wb' compresslevel 2 else logger debug ' Writingusingnormal I/O' fid open fname 'wb' else logger debug ' Writingusing%s I/O' % type fname fid fnamefid seek 0 write id ... | def start_file fname id_ None if isinstance fname string_types if op splitext fname [1] lower ' gz' logger debug 'Writingusinggzip' fid GzipFile fname 'wb' compresslevel 2 else logger debug 'WritingusingnormalI/O' fid open fname 'wb' else logger debug 'Writingusing%sI/O' % type fname fid fnamefid seek 0 write_id fid FI... | 80 |
python-test-4739 | python | What does the code write ? | the compulsory header tags | def start file fname id None if isinstance fname string types if op splitext fname [1 ] lower ' gz' logger debug ' Writingusinggzip' fid Gzip File fname 'wb' compresslevel 2 else logger debug ' Writingusingnormal I/O' fid open fname 'wb' else logger debug ' Writingusing%s I/O' % type fname fid fnamefid seek 0 write id ... | def start_file fname id_ None if isinstance fname string_types if op splitext fname [1] lower ' gz' logger debug 'Writingusinggzip' fid GzipFile fname 'wb' compresslevel 2 else logger debug 'WritingusingnormalI/O' fid open fname 'wb' else logger debug 'Writingusing%sI/O' % type fname fid fnamefid seek 0 write_id fid FI... | 80 |
python-test-4742 | python | What does the code restore ? | a previous backup into the cassandra directory structure | def untar backup files source logging info " Untarringbackupfile'{ 0 }' " format source try tar tarfile open source 'r gz' tar extractall path '/' tar close except tarfile Tar Error as tar error logging exception tar error raise backup exceptions BR Exception " Exceptionwhileuntarringbackupfile'{ 0 }' " format source l... | def untar_backup_files source logging info "Untarringbackupfile'{0}' " format source try tar tarfile open source 'r gz' tar extractall path '/' tar close except tarfile TarError as tar_error logging exception tar_error raise backup_exceptions BRException "Exceptionwhileuntarringbackupfile'{0}' " format source logging i... | 59 |
python-test-4748 | python | What does the code delete ? | a snapshot from the image | def image snapshot delete call None kwargs None if call 'function' raise Salt Cloud System Exit ' Theimage snapshot deletefunctionmustbecalledwith-for--function ' if kwargs is None kwargs {}image id kwargs get 'image id' None image name kwargs get 'image name' None snapshot id kwargs get 'snapshot id' None if snapshot ... | def image_snapshot_delete call None kwargs None if call 'function' raise SaltCloudSystemExit 'Theimage_snapshot_deletefunctionmustbecalledwith-for--function ' if kwargs is None kwargs {}image_id kwargs get 'image_id' None image_name kwargs get 'image_name' None snapshot_id kwargs get 'snapshot_id' None if snapshot_id i... | 146 |
python-test-4752 | python | What does the code get ? | provider document | def get saml provider name region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile try provider conn get saml provider name return provider['get saml provider response']['get saml provider result']['saml metadata document']except boto exception Boto Server Error as e... | def get_saml_provider name region None key None keyid None profile None conn _get_conn region region key key keyid keyid profile profile try provider conn get_saml_provider name return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document']except boto exception BotoServerError as e ... | 67 |
python-test-4753 | python | Where did an domains list ? | in a certificate | def cert get domains cert domains []try ext cert extensions get extension for oid x509 OID SUBJECT ALTERNATIVE NAME entries ext value get values for type x509 DNS Name for entry in entries domains append entry except Exception as e app logger warning ' Failedtoget Subject Alt Name {0 }' format e return domains | def cert_get_domains cert domains []try ext cert extensions get_extension_for_oid x509 OID_SUBJECT_ALTERNATIVE_NAME entries ext value get_values_for_type x509 DNSName for entry in entries domains append entry except Exception as e app logger warning 'FailedtogetSubjectAltName {0}' format e return domains | 54 |
python-test-4754 | python | What listed in a certificate ? | an domains | def cert get domains cert domains []try ext cert extensions get extension for oid x509 OID SUBJECT ALTERNATIVE NAME entries ext value get values for type x509 DNS Name for entry in entries domains append entry except Exception as e app logger warning ' Failedtoget Subject Alt Name {0 }' format e return domains | def cert_get_domains cert domains []try ext cert extensions get_extension_for_oid x509 OID_SUBJECT_ALTERNATIVE_NAME entries ext value get_values_for_type x509 DNSName for entry in entries domains append entry except Exception as e app logger warning 'FailedtogetSubjectAltName {0}' format e return domains | 54 |
python-test-4756 | python | What does the discount amount exceed ? | the minimium total price set by minimum_price constraint in shopproduct | def limit discount amount by min price line order source shop product line product get shop instance order source shop if shop product minimum price min total shop product minimum price value * line quantity base price line base unit price value * line quantity if base price - line discount amount value < min total lin... | def _limit_discount_amount_by_min_price line order_source shop_product line product get_shop_instance order_source shop if shop_product minimum_price min_total shop_product minimum_price value * line quantity base_price line base_unit_price value * line quantity if base_price - line discount_amount value < min_total li... | 68 |
python-test-4757 | python | What exceeds the minimium total price set by minimum_price constraint in shopproduct ? | the discount amount | def limit discount amount by min price line order source shop product line product get shop instance order source shop if shop product minimum price min total shop product minimum price value * line quantity base price line base unit price value * line quantity if base price - line discount amount value < min total lin... | def _limit_discount_amount_by_min_price line order_source shop_product line product get_shop_instance order_source shop if shop_product minimum_price min_total shop_product minimum_price value * line quantity base_price line base_unit_price value * line quantity if base_price - line discount_amount value < min_total li... | 68 |
python-test-4760 | python | How do proxy values set ? | from http_proxy | def set builddefaults facts facts if 'builddefaults' in facts builddefaults facts['builddefaults']common facts['common']if 'http proxy' not in builddefaults and 'http proxy' in common builddefaults['http proxy'] common['http proxy']if 'https proxy' not in builddefaults and 'https proxy' in common builddefaults['https p... | def set_builddefaults_facts facts if 'builddefaults' in facts builddefaults facts['builddefaults']common facts['common']if 'http_proxy' not in builddefaults and 'http_proxy' in common builddefaults['http_proxy'] common['http_proxy']if 'https_proxy' not in builddefaults and 'https_proxy' in common builddefaults['https_p... | 131 |
python-test-4765 | python | What does the code get ? | a pretty print view of the given number of bytes | def Get Pretty Bytes bytes num significant digits 0 byte prefixes ['' 'K' 'M' 'G' 'T' 'P' 'E']for i in range 0 7 exp i * 10 if bytes num < 1 << exp + 10 if i 0 formatted bytes str bytes num else formatted bytes '% *f' % significant digits bytes num * 1 0 / 1 << exp if formatted bytes '1 ' plural 's'else plural ''return... | def GetPrettyBytes bytes_num significant_digits 0 byte_prefixes ['' 'K' 'M' 'G' 'T' 'P' 'E']for i in range 0 7 exp i * 10 if bytes_num < 1 << exp + 10 if i 0 formatted_bytes str bytes_num else formatted_bytes '% *f' % significant_digits bytes_num * 1 0 / 1 << exp if formatted_bytes '1' plural 's'else plural ''return '%... | 88 |
python-test-4766 | python | What does the code ensure ? | the is_default db field matches the create / update request | @db api retry if session inactive def ensure external network default value callback resource event trigger context request network is default request get IS DEFAULT False if event in events BEFORE CREATE events BEFORE UPDATE and is default obj context session query ext net models External Network filter by is default ... | @db_api retry_if_session_inactive def _ensure_external_network_default_value_callback resource event trigger context request network is_default request get IS_DEFAULT False if event in events BEFORE_CREATE events BEFORE_UPDATE and is_default obj context session query ext_net_models ExternalNetwork filter_by is_default ... | 91 |
python-test-4767 | python | What do the is_default db field match ? | the create / update request | @db api retry if session inactive def ensure external network default value callback resource event trigger context request network is default request get IS DEFAULT False if event in events BEFORE CREATE events BEFORE UPDATE and is default obj context session query ext net models External Network filter by is default ... | @db_api retry_if_session_inactive def _ensure_external_network_default_value_callback resource event trigger context request network is_default request get IS_DEFAULT False if event in events BEFORE_CREATE events BEFORE_UPDATE and is_default obj context session query ext_net_models ExternalNetwork filter_by is_default ... | 91 |
python-test-4768 | python | What matches the create / update request ? | the is_default db field | @db api retry if session inactive def ensure external network default value callback resource event trigger context request network is default request get IS DEFAULT False if event in events BEFORE CREATE events BEFORE UPDATE and is default obj context session query ext net models External Network filter by is default ... | @db_api retry_if_session_inactive def _ensure_external_network_default_value_callback resource event trigger context request network is_default request get IS_DEFAULT False if event in events BEFORE_CREATE events BEFORE_UPDATE and is_default obj context session query ext_net_models ExternalNetwork filter_by is_default ... | 91 |
python-test-4769 | python | What does the code select ? | the pyzmq backend | def select backend name try mod import name fromlist public api except Import Error raiseexcept Exception as e import sysfrom zmq utils sixcerpt import reraiseexc info sys exc info reraise Import Error Import Error ' Importing%sfailedwith%s' % name e exc info[ 2 ] ns {}for key in public api ns[key] getattr mod key retu... | def select_backend name try mod __import__ name fromlist public_api except ImportError raiseexcept Exception as e import sysfrom zmq utils sixcerpt import reraiseexc_info sys exc_info reraise ImportError ImportError 'Importing%sfailedwith%s' % name e exc_info[2] ns {}for key in public_api ns[key] getattr mod key return... | 55 |
python-test-4772 | python | What does the code perform ? | an actual interpolation of values | def interpolate 2d values method 'pad' axis 0 limit None fill value None dtype None transf lambda x x if axis 0 else lambda x x T ndim values ndimif values ndim 1 if axis 0 raise Assertion Error 'cannotinterpolateonandim 1withaxis 0' values values reshape tuple 1 + values shape if fill value is None mask Noneelse mask ... | def interpolate_2d values method 'pad' axis 0 limit None fill_value None dtype None transf lambda x x if axis 0 else lambda x x T ndim values ndimif values ndim 1 if axis 0 raise AssertionError 'cannotinterpolateonandim 1withaxis 0' values values reshape tuple 1 + values shape if fill_value is None mask Noneelse mask m... | 105 |
python-test-4774 | python | What has the highest information content value ? | the least common subsumer | def lcs ic synset 1 synset 2 ic verbose False if synset 1 pos synset 2 pos raise Word Net Error u' Computingtheleastcommonsubsumerrequires' + u'%sand%stohavethesamepartofspeech ' % synset 1 synset 2 ic 1 information content synset 1 ic ic 2 information content synset 2 ic subsumers synset 1 common hypernyms synset 2 if... | def _lcs_ic synset1 synset2 ic verbose False if synset1 _pos synset2 _pos raise WordNetError u'Computingtheleastcommonsubsumerrequires' + u'%sand%stohavethesamepartofspeech ' % synset1 synset2 ic1 information_content synset1 ic ic2 information_content synset2 ic subsumers synset1 common_hypernyms synset2 if len subsume... | 85 |
python-test-4775 | python | What does the least common subsumer have ? | the highest information content value | def lcs ic synset 1 synset 2 ic verbose False if synset 1 pos synset 2 pos raise Word Net Error u' Computingtheleastcommonsubsumerrequires' + u'%sand%stohavethesamepartofspeech ' % synset 1 synset 2 ic 1 information content synset 1 ic ic 2 information content synset 2 ic subsumers synset 1 common hypernyms synset 2 if... | def _lcs_ic synset1 synset2 ic verbose False if synset1 _pos synset2 _pos raise WordNetError u'Computingtheleastcommonsubsumerrequires' + u'%sand%stohavethesamepartofspeech ' % synset1 synset2 ic1 information_content synset1 ic ic2 information_content synset2 ic subsumers synset1 common_hypernyms synset2 if len subsume... | 85 |
python-test-4776 | python | What does the code get ? | the information content of the least common subsumer that has the highest information content value | def lcs ic synset 1 synset 2 ic verbose False if synset 1 pos synset 2 pos raise Word Net Error u' Computingtheleastcommonsubsumerrequires' + u'%sand%stohavethesamepartofspeech ' % synset 1 synset 2 ic 1 information content synset 1 ic ic 2 information content synset 2 ic subsumers synset 1 common hypernyms synset 2 if... | def _lcs_ic synset1 synset2 ic verbose False if synset1 _pos synset2 _pos raise WordNetError u'Computingtheleastcommonsubsumerrequires' + u'%sand%stohavethesamepartofspeech ' % synset1 synset2 ic1 information_content synset1 ic ic2 information_content synset2 ic subsumers synset1 common_hypernyms synset2 if len subsume... | 85 |
python-test-4778 | python | Do backticks contribute inside the inline or block regions ? | No | def post match view name style first second center bfr threshold if first is not None and second is not None diff first size - second size if diff > 0 first first move first begin first end - diff elif diff < 0 second second move second begin - diff second end return first second style | def post_match view name style first second center bfr threshold if first is not None and second is not None diff first size - second size if diff > 0 first first move first begin first end - diff elif diff < 0 second second move second begin - diff second end return first second style | 57 |
python-test-4779 | python | What does the code ensure ? | that backticks that do not contribute inside the inline or block regions are not highlighted | def post match view name style first second center bfr threshold if first is not None and second is not None diff first size - second size if diff > 0 first first move first begin first end - diff elif diff < 0 second second move second begin - diff second end return first second style | def post_match view name style first second center bfr threshold if first is not None and second is not None diff first size - second size if diff > 0 first first move first begin first end - diff elif diff < 0 second second move second begin - diff second end return first second style | 57 |
python-test-4780 | python | Where do backticks not contribute ? | inside the inline or block regions | def post match view name style first second center bfr threshold if first is not None and second is not None diff first size - second size if diff > 0 first first move first begin first end - diff elif diff < 0 second second move second begin - diff second end return first second style | def post_match view name style first second center bfr threshold if first is not None and second is not None diff first size - second size if diff > 0 first first move first begin first end - diff elif diff < 0 second second move second begin - diff second end return first second style | 57 |
python-test-4781 | python | What do not contribute inside the inline or block regions ? | backticks | def post match view name style first second center bfr threshold if first is not None and second is not None diff first size - second size if diff > 0 first first move first begin first end - diff elif diff < 0 second second move second begin - diff second end return first second style | def post_match view name style first second center bfr threshold if first is not None and second is not None diff first size - second size if diff > 0 first first move first begin first end - diff elif diff < 0 second second move second begin - diff second end return first second style | 57 |
python-test-4784 | python | What does the code decide depending on the input arguments ? | the right type of dot product | def dot inp matrix if 'int' in inp dtype and inp ndim 2 return matrix[inp flatten ]elif 'int' in inp dtype return matrix[inp]elif 'float' in inp dtype and inp ndim 3 shape 0 inp shape[ 0 ]shape 1 inp shape[ 1 ]shape 2 inp shape[ 2 ]return TT dot inp reshape shape 0 * shape 1 shape 2 matrix else return TT dot inp matrix | def dot inp matrix if 'int' in inp dtype and inp ndim 2 return matrix[inp flatten ]elif 'int' in inp dtype return matrix[inp]elif 'float' in inp dtype and inp ndim 3 shape0 inp shape[0]shape1 inp shape[1]shape2 inp shape[2]return TT dot inp reshape shape0 * shape1 shape2 matrix else return TT dot inp matrix | 65 |
python-test-4789 | python | What does this inject into the astropy ? | entry points | def populate entry points entry points for entry point in entry points name entry point nametry entry point entry point load except Exception as e warnings warn Astropy User Warning u'{type}erroroccurredinentrypoint{name} ' format type type e name name name else if not inspect isclass entry point warnings warn Astropy ... | def populate_entry_points entry_points for entry_point in entry_points name entry_point nametry entry_point entry_point load except Exception as e warnings warn AstropyUserWarning u'{type}erroroccurredinentrypoint{name} ' format type type e __name__ name name else if not inspect isclass entry_point warnings warn Astrop... | 89 |
python-test-4793 | python | What does a function return ? | a default value for a field | def Default Value Constructor For Field field if field label Field Descriptor LABEL REPEATED if field has default value and field default value [] raise Value Error ' Repeatedfielddefaultvaluenotemptylist %s' % field default value if field cpp type Field Descriptor CPPTYPE MESSAGE message type field message typedef Mak... | def _DefaultValueConstructorForField field if field label _FieldDescriptor LABEL_REPEATED if field has_default_value and field default_value [] raise ValueError 'Repeatedfielddefaultvaluenotemptylist %s' % field default_value if field cpp_type _FieldDescriptor CPPTYPE_MESSAGE message_type field message_typedef MakeRepe... | 147 |
python-test-4798 | python | What authorizes the user for the action ? | the given token | @ helpers positional 3 def validate token key token user id action id '' current time None if not token return Falsetry decoded base 64 urlsafe b64 decode token token time int decoded split DELIMITER [ -1 ] except Type Error Value Error binascii Error return Falseif current time is None current time time time if curren... | @_helpers positional 3 def validate_token key token user_id action_id '' current_time None if not token return Falsetry decoded base64 urlsafe_b64decode token token_time int decoded split DELIMITER [ -1 ] except TypeError ValueError binascii Error return Falseif current_time is None current_time time time if current_ti... | 105 |
python-test-4799 | python | What does the code get ? | an appropriate backendapi for the specified dataset backend | def get backend api cluster id backend config filename environ get 'FLOCKER ACCEPTANCE TEST VOLUME BACKEND CONFIG' if backend config filename is None raise Skip Test ' Thistestrequirestheabilitytoconstructan I Block Device AP Iinordertoverifyconstruction Pleaseset FLOCKER ACCEPTANCE TEST VOLUME BACKEND CONFI Gtoayamlfi... | def get_backend_api cluster_id backend_config_filename environ get 'FLOCKER_ACCEPTANCE_TEST_VOLUME_BACKEND_CONFIG' if backend_config_filename is None raise SkipTest 'ThistestrequirestheabilitytoconstructanIBlockDeviceAPIinordertoverifyconstruction PleasesetFLOCKER_ACCEPTANCE_TEST_VOLUME_BACKEND_CONFIGtoayamlfilepathwit... | 133 |
python-test-4800 | python | Should valid coordinates raise an error ? | No | def test validate coord result conesearch validate coord ICRS 6 02233 * u degree -72 08144 * u degree np testing assert allclose result [6 022330000000011 -72 08144 ] result conesearch validate coord Sky Coord 6 02233 * u degree -72 08144 * u degree frame u'icrs' np testing assert allclose result [6 022330000000011 -72... | def test_validate_coord result conesearch _validate_coord ICRS 6 02233 * u degree -72 08144 * u degree np testing assert_allclose result [6 022330000000011 -72 08144 ] result conesearch _validate_coord SkyCoord 6 02233 * u degree -72 08144 * u degree frame u'icrs' np testing assert_allclose result [6 022330000000011 -7... | 84 |
python-test-4801 | python | What should not raise an error ? | valid coordinates | def test validate coord result conesearch validate coord ICRS 6 02233 * u degree -72 08144 * u degree np testing assert allclose result [6 022330000000011 -72 08144 ] result conesearch validate coord Sky Coord 6 02233 * u degree -72 08144 * u degree frame u'icrs' np testing assert allclose result [6 022330000000011 -72... | def test_validate_coord result conesearch _validate_coord ICRS 6 02233 * u degree -72 08144 * u degree np testing assert_allclose result [6 022330000000011 -72 08144 ] result conesearch _validate_coord SkyCoord 6 02233 * u degree -72 08144 * u degree frame u'icrs' np testing assert_allclose result [6 022330000000011 -7... | 84 |
python-test-4802 | python | What should valid coordinates not raise ? | an error | def test validate coord result conesearch validate coord ICRS 6 02233 * u degree -72 08144 * u degree np testing assert allclose result [6 022330000000011 -72 08144 ] result conesearch validate coord Sky Coord 6 02233 * u degree -72 08144 * u degree frame u'icrs' np testing assert allclose result [6 022330000000011 -72... | def test_validate_coord result conesearch _validate_coord ICRS 6 02233 * u degree -72 08144 * u degree np testing assert_allclose result [6 022330000000011 -72 08144 ] result conesearch _validate_coord SkyCoord 6 02233 * u degree -72 08144 * u degree frame u'icrs' np testing assert_allclose result [6 022330000000011 -7... | 84 |
python-test-4810 | python | Where did all controllers use ? | in system | def get all controllers try result utils run 'lssubsys' ignore status False controllers str result stdout strip controller list []for controller in controllers str splitlines controller sub list controller split ' ' controller list + controller sub listexcept error Cmd Error controller list ['cpuacct' 'cpu' 'memory' 'c... | def get_all_controllers try result utils run 'lssubsys' ignore_status False controllers_str result stdout strip controller_list []for controller in controllers_str splitlines controller_sub_list controller split ' ' controller_list + controller_sub_listexcept error CmdError controller_list ['cpuacct' 'cpu' 'memory' 'cp... | 53 |
python-test-4811 | python | What used in system ? | all controllers | def get all controllers try result utils run 'lssubsys' ignore status False controllers str result stdout strip controller list []for controller in controllers str splitlines controller sub list controller split ' ' controller list + controller sub listexcept error Cmd Error controller list ['cpuacct' 'cpu' 'memory' 'c... | def get_all_controllers try result utils run 'lssubsys' ignore_status False controllers_str result stdout strip controller_list []for controller in controllers_str splitlines controller_sub_list controller split ' ' controller_list + controller_sub_listexcept error CmdError controller_list ['cpuacct' 'cpu' 'memory' 'cp... | 53 |
python-test-4812 | python | What does the code get ? | all controllers used in system | def get all controllers try result utils run 'lssubsys' ignore status False controllers str result stdout strip controller list []for controller in controllers str splitlines controller sub list controller split ' ' controller list + controller sub listexcept error Cmd Error controller list ['cpuacct' 'cpu' 'memory' 'c... | def get_all_controllers try result utils run 'lssubsys' ignore_status False controllers_str result stdout strip controller_list []for controller in controllers_str splitlines controller_sub_list controller split ' ' controller_list + controller_sub_listexcept error CmdError controller_list ['cpuacct' 'cpu' 'memory' 'cp... | 53 |
python-test-4819 | python | For what purpose do borders of a certain color add ? | to make the resized image fit exactly within the dimensions given | def background im size background None **kwargs if not background return imif not size[ 0 ] or not size[ 1 ] return im x y im sizeif x > size[ 0 ] and y > size[ 1 ] return imim colorspace im replace alpha background **kwargs new im Image new 'RGB' size background if new im mode im mode new im new im convert im mode off... | def background im size background None **kwargs if not background return imif not size[0] or not size[1] return im x y im sizeif x > size[0] and y > size[1] return imim colorspace im replace_alpha background **kwargs new_im Image new 'RGB' size background if new_im mode im mode new_im new_im convert im mode offset size... | 89 |
python-test-4820 | python | What lacks it ? | any plugin | def add default version None overwrite False plugins module loader all path only True plugins os path splitext os path basename p [0 ] p for p in plugins plugins p for p in plugins if p[ 0 ] not in NONMODULE MODULE NAMES processed set diagnostic messages []for name filename in info for info in plugins if info[ 0 ] not ... | def add_default version None overwrite False plugins module_loader all path_only True plugins os path splitext os path basename p [0] p for p in plugins plugins p for p in plugins if p[0] not in NONMODULE_MODULE_NAMES processed set diagnostic_messages []for name filename in info for info in plugins if info[0] not in pr... | 95 |
python-test-4821 | python | What do the subcommand add to modules ? | default metadata | def add default version None overwrite False plugins module loader all path only True plugins os path splitext os path basename p [0 ] p for p in plugins plugins p for p in plugins if p[ 0 ] not in NONMODULE MODULE NAMES processed set diagnostic messages []for name filename in info for info in plugins if info[ 0 ] not ... | def add_default version None overwrite False plugins module_loader all path_only True plugins os path splitext os path basename p [0] p for p in plugins plugins p for p in plugins if p[0] not in NONMODULE_MODULE_NAMES processed set diagnostic_messages []for name filename in info for info in plugins if info[0] not in pr... | 95 |
python-test-4822 | python | For what purpose do the subcommand implement ? | to add default metadata to modules | def add default version None overwrite False plugins module loader all path only True plugins os path splitext os path basename p [0 ] p for p in plugins plugins p for p in plugins if p[ 0 ] not in NONMODULE MODULE NAMES processed set diagnostic messages []for name filename in info for info in plugins if info[ 0 ] not ... | def add_default version None overwrite False plugins module_loader all path_only True plugins os path splitext os path basename p [0] p for p in plugins plugins p for p in plugins if p[0] not in NONMODULE_MODULE_NAMES processed set diagnostic_messages []for name filename in info for info in plugins if info[0] not in pr... | 95 |
python-test-4826 | python | What did the code give ? | finite floats expected | def ulp abs check expected got ulp tol abs tol ulp error abs to ulps expected - to ulps got abs error abs expected - got if abs error < abs tol or ulp error < ulp tol return Noneelse fmt 'error { 3g} { d}ulps permittederror { 3g}or{ d}ulps'return fmt format abs error ulp error abs tol ulp tol | def ulp_abs_check expected got ulp_tol abs_tol ulp_error abs to_ulps expected - to_ulps got abs_error abs expected - got if abs_error < abs_tol or ulp_error < ulp_tol return Noneelse fmt 'error { 3g} { d}ulps permittederror { 3g}or{ d}ulps'return fmt format abs_error ulp_error abs_tol ulp_tol | 60 |
python-test-4827 | python | What does nt return value in scientific notation ? | formatteddecimalfield | def test formatted decimal field class Test Model Form Model Form class Meta model Productfields ['width']values [' 0 E- 9 ' '0 E- 30 ' '1 E- 9 ' '123 E- 10 ' '- 123 E- 10 ' '1 12345666666666 E 20 ']for value in values product Product width Decimal value form Test Model Form instance product rendered form force text fo... | def test_formatted_decimal_field class TestModelForm ModelForm class Meta model Productfields ['width']values ['0E-9' '0E-30' '1E-9' '123E-10' '-123E-10' '1 12345666666666E20']for value in values product Product width Decimal value form TestModelForm instance product rendered_form force_text form rendered_value re sear... | 127 |
python-test-4828 | python | How does formatteddecimalfield nt return value ? | in scientific notation | def test formatted decimal field class Test Model Form Model Form class Meta model Productfields ['width']values [' 0 E- 9 ' '0 E- 30 ' '1 E- 9 ' '123 E- 10 ' '- 123 E- 10 ' '1 12345666666666 E 20 ']for value in values product Product width Decimal value form Test Model Form instance product rendered form force text fo... | def test_formatted_decimal_field class TestModelForm ModelForm class Meta model Productfields ['width']values ['0E-9' '0E-30' '1E-9' '123E-10' '-123E-10' '1 12345666666666E20']for value in values product Product width Decimal value form TestModelForm instance product rendered_form force_text form rendered_value re sear... | 127 |
python-test-4829 | python | What does formatteddecimalfield nt return in scientific notation ? | value | def test formatted decimal field class Test Model Form Model Form class Meta model Productfields ['width']values [' 0 E- 9 ' '0 E- 30 ' '1 E- 9 ' '123 E- 10 ' '- 123 E- 10 ' '1 12345666666666 E 20 ']for value in values product Product width Decimal value form Test Model Form instance product rendered form force text fo... | def test_formatted_decimal_field class TestModelForm ModelForm class Meta model Productfields ['width']values ['0E-9' '0E-30' '1E-9' '123E-10' '-123E-10' '1 12345666666666E20']for value in values product Product width Decimal value form TestModelForm instance product rendered_form force_text form rendered_value re sear... | 127 |
python-test-4830 | python | Does formatteddecimalfield return value in scientific notation ? | No | def test formatted decimal field class Test Model Form Model Form class Meta model Productfields ['width']values [' 0 E- 9 ' '0 E- 30 ' '1 E- 9 ' '123 E- 10 ' '- 123 E- 10 ' '1 12345666666666 E 20 ']for value in values product Product width Decimal value form Test Model Form instance product rendered form force text fo... | def test_formatted_decimal_field class TestModelForm ModelForm class Meta model Productfields ['width']values ['0E-9' '0E-30' '1E-9' '123E-10' '-123E-10' '1 12345666666666E20']for value in values product Product width Decimal value form TestModelForm instance product rendered_form force_text form rendered_value re sear... | 127 |
python-test-4841 | python | What does the code create ? | a shadow trigger for triggertype with no parameters | def create shadow trigger trigger type db trigger type ref trigger type db get reference refif trigger type db parameters schema LOG debug ' Skipshadowtriggerfor Trigger Typewithparameters%s ' trigger type ref return Nonetrigger {'name' trigger type db name 'pack' trigger type db pack 'type' trigger type ref 'parameter... | def create_shadow_trigger trigger_type_db trigger_type_ref trigger_type_db get_reference refif trigger_type_db parameters_schema LOG debug 'SkipshadowtriggerforTriggerTypewithparameters%s ' trigger_type_ref return Nonetrigger {'name' trigger_type_db name 'pack' trigger_type_db pack 'type' trigger_type_ref 'parameters' ... | 55 |
python-test-4842 | python | What does the code detrend ? | an array with a trend of given order along axis 0 or 1 parameters x : array_like | def detrend x order 1 axis 0 if x ndim 2 and int axis 1 x x Telif x ndim > 2 raise Not Implemented Error 'x ndim> 2 isnotimplementeduntilitisneeded' nobs x shape[ 0 ]if order 0 resid x - x mean axis 0 else trends np vander np arange float nobs N order + 1 beta np linalg pinv trends dot x resid x - np dot trends beta if... | def detrend x order 1 axis 0 if x ndim 2 and int axis 1 x x Telif x ndim > 2 raise NotImplementedError 'x ndim>2isnotimplementeduntilitisneeded' nobs x shape[0]if order 0 resid x - x mean axis 0 else trends np vander np arange float nobs N order + 1 beta np linalg pinv trends dot x resid x - np dot trends beta if x ndi... | 82 |
python-test-4844 | python | What does the code build ? | a cluster instance | def get test cluster reactor control node environ get 'FLOCKER ACCEPTANCE CONTROL NODE' if control node is None raise Skip Test ' Setacceptancetestingcontrolnode I Paddressusingthe' + 'FLOCKER ACCEPTANCE CONTROL NOD Eenvironmentvariable ' agent nodes env var environ get 'FLOCKER ACCEPTANCE NUM AGENT NODES' if agent nod... | def _get_test_cluster reactor control_node environ get 'FLOCKER_ACCEPTANCE_CONTROL_NODE' if control_node is None raise SkipTest 'SetacceptancetestingcontrolnodeIPaddressusingthe' + 'FLOCKER_ACCEPTANCE_CONTROL_NODEenvironmentvariable ' agent_nodes_env_var environ get 'FLOCKER_ACCEPTANCE_NUM_AGENT_NODES' if agent_nodes_e... | 121 |
python-test-4845 | python | What does the code elide ? | a filename to the given length | def elide filename filename length elidestr ' 'if length < len elidestr raise Value Error 'lengthmustbegreaterorequalto 3 ' if len filename < length return filenamelength - len elidestr left length // 2 right length - left if right 0 return filename[ left] + elidestr else return filename[ left] + elidestr + filename[ -... | def elide_filename filename length elidestr ' 'if length < len elidestr raise ValueError 'lengthmustbegreaterorequalto3' if len filename < length return filenamelength - len elidestr left length // 2 right length - left if right 0 return filename[ left] + elidestr else return filename[ left] + elidestr + filename[ - ri... | 55 |
python-test-4856 | python | What does the code get with subscribers ? | streams | def get occupied streams realm subs filter Subscription objects filter active True user profile realm realm user profile is active True values 'recipient id' stream ids Recipient objects filter type Recipient STREAM id in subs filter values 'type id' return Stream objects filter id in stream ids realm realm deactivated... | def get_occupied_streams realm subs_filter Subscription objects filter active True user_profile__realm realm user_profile__is_active True values 'recipient_id' stream_ids Recipient objects filter type Recipient STREAM id__in subs_filter values 'type_id' return Stream objects filter id__in stream_ids realm realm deactiv... | 51 |
python-test-4858 | python | What does the code transform back to the legacy data format ? | a list of block devices of an instance | def legacy mapping block device mapping legacy block device mapping []for bdm in block device mapping try legacy block device Block Device Dict bdm legacy except exception Invalid BDM For Legacy continuelegacy block device mapping append legacy block device for i dev in enumerate dev for dev in legacy block device mapp... | def legacy_mapping block_device_mapping legacy_block_device_mapping []for bdm in block_device_mapping try legacy_block_device BlockDeviceDict bdm legacy except exception InvalidBDMForLegacy continuelegacy_block_device_mapping append legacy_block_device for i dev in enumerate dev for dev in legacy_block_device_mapping i... | 74 |
python-test-4861 | python | What does the code execute ? | a puppet run | def run *args **kwargs puppet Puppet buildargs for arg in range len args if args[arg] in ['agent' 'apply'] puppet subcmd args[arg]else buildargs + args[arg] puppet arguments buildargs puppet kwargs update salt utils clean kwargs **kwargs ret salt ['cmd run all'] repr puppet python shell puppet useshell if ret['retcode'... | def run *args **kwargs puppet _Puppet buildargs for arg in range len args if args[arg] in ['agent' 'apply'] puppet subcmd args[arg]else buildargs + args[arg] puppet arguments buildargs puppet kwargs update salt utils clean_kwargs **kwargs ret __salt__['cmd run_all'] repr puppet python_shell puppet useshell if ret['retc... | 56 |
python-test-4864 | python | What should the reader try ? | to convert each column to ints | @pytest mark parametrize 'parallel' [ True False] def test conversion parallel read basic text '\n ABCDE\n 1 a 345 \n 2 1910 - 5 3e 4 \n 42 - 12 4six\n'table read basic text parallel parallel assert equal table['A'] dtype kind 'f' assert table['B'] dtype kind in 'S' 'U' assert equal table['C'] dtype kind 'i' assert equ... | @pytest mark parametrize 'parallel' [True False] def test_conversion parallel read_basic text '\nABCDE\n1a345\n2 1910-5 3e4\n42-12 4six\n'table read_basic text parallel parallel assert_equal table['A'] dtype kind 'f' assert table['B'] dtype kind in 'S' 'U' assert_equal table['C'] dtype kind 'i' assert_equal table['D'] ... | 68 |
python-test-4869 | python | What cover tuples of ranges in mask ? | all true value | def split ranges mask ranges [ 0 len mask ]for pos val in enumerate mask if not val r ranges pop if pos > r[ 0 ] yield r[ 0 ] pos if pos + 1 < len mask ranges append pos + 1 len mask if ranges yield ranges[ -1 ] | def split_ranges mask ranges [ 0 len mask ]for pos val in enumerate mask if not val r ranges pop if pos > r[0] yield r[0] pos if pos + 1 < len mask ranges append pos + 1 len mask if ranges yield ranges[ -1 ] | 52 |
python-test-4870 | python | Where do all true value cover tuples of ranges ? | in mask | def split ranges mask ranges [ 0 len mask ]for pos val in enumerate mask if not val r ranges pop if pos > r[ 0 ] yield r[ 0 ] pos if pos + 1 < len mask ranges append pos + 1 len mask if ranges yield ranges[ -1 ] | def split_ranges mask ranges [ 0 len mask ]for pos val in enumerate mask if not val r ranges pop if pos > r[0] yield r[0] pos if pos + 1 < len mask ranges append pos + 1 len mask if ranges yield ranges[ -1 ] | 52 |
python-test-4879 | python | How do them sort first ? | with general headers | def normalize headers response headers strict True category {}for idx in range len response headers key val response headers[idx]head get header key strict if not head newhead '-' join [x capitalize for x in key replace ' ' '-' split '-' ] response headers[idx] newhead val category[newhead] 4continueresponse headers[id... | def normalize_headers response_headers strict True category {}for idx in range len response_headers key val response_headers[idx]head get_header key strict if not head newhead '-' join [x capitalize for x in key replace '_' '-' split '-' ] response_headers[idx] newhead val category[newhead] 4continueresponse_headers[id... | 73 |
python-test-4880 | python | How did count values read ? | from fo using the deprecated bitpacking encoding | def read bitpacked deprecated file obj byte count count width debug logging raw bytes array array ARRAY BYTE STR file obj read byte count tolist mask mask for bits width index 0res []word 0bits in word 0while len res < count and index < len raw bytes if debug logging logger debug u'index %d' index logger debug u'bitsin... | def read_bitpacked_deprecated file_obj byte_count count width debug_logging raw_bytes array array ARRAY_BYTE_STR file_obj read byte_count tolist mask _mask_for_bits width index 0res []word 0bits_in_word 0while len res < count and index < len raw_bytes if debug_logging logger debug u'index %d' index logger debug u'bitsi... | 127 |
python-test-4884 | python | What do testusingpsychopymonitorconfig provide ? | a psychopy monitor configuration file name | def test Using Psycho Py Monitor Config io launch Hub Server psychopy monitor name 'test Monitor' display io devices displayprint ' Display Psychopy Monitor Name ' display get Psychopy Monitor Name print ' Display Default Eye Distance ' display get Default Eye Distance print ' Display Physical Dimensions ' display get ... | def testUsingPsychoPyMonitorConfig io launchHubServer psychopy_monitor_name 'testMonitor' display io devices displayprint 'DisplayPsychopyMonitorName ' display getPsychopyMonitorName print 'DisplayDefaultEyeDistance ' display getDefaultEyeDistance print 'DisplayPhysicalDimensions ' display getPhysicalDimensions io quit | 55 |
python-test-4885 | python | What does testusingpsychopymonitorconfig illustrate ? | using the launchhubserver function and providing a psychopy monitor configuration file name | def test Using Psycho Py Monitor Config io launch Hub Server psychopy monitor name 'test Monitor' display io devices displayprint ' Display Psychopy Monitor Name ' display get Psychopy Monitor Name print ' Display Default Eye Distance ' display get Default Eye Distance print ' Display Physical Dimensions ' display get ... | def testUsingPsychoPyMonitorConfig io launchHubServer psychopy_monitor_name 'testMonitor' display io devices displayprint 'DisplayPsychopyMonitorName ' display getPsychopyMonitorName print 'DisplayDefaultEyeDistance ' display getDefaultEyeDistance print 'DisplayPhysicalDimensions ' display getPhysicalDimensions io quit | 55 |
python-test-4886 | python | What does the code get ? | all installed apps that are not from django | def harvest lettuces only the apps None avoid apps None path 'features' apps get apps if isinstance only the apps list tuple and any only the apps def filter only specified module return module name in only the apps apps filter filter only specified apps else apps filter filter bultins apps apps filter filter configure... | def harvest_lettuces only_the_apps None avoid_apps None path 'features' apps get_apps if isinstance only_the_apps list tuple and any only_the_apps def _filter_only_specified module return module __name__ in only_the_apps apps filter _filter_only_specified apps else apps filter _filter_bultins apps apps filter _filter_c... | 102 |
python-test-4888 | python | For what purpose do an spline order k with knots t assemble using full matrices ? | to interpolate y(x ) | def make interp full matr x y t k assert x size y size assert t size x size + k + 1 n x size A np zeros n n dtype np float for j in range n xval x[j]if xval t[k] left kelse left np searchsorted t xval - 1 bb bspl evaluate all bspl t k xval left A[j left - k left + 1 ] bbc sl solve A y return c | def make_interp_full_matr x y t k assert x size y size assert t size x size + k + 1 n x sizeA np zeros n n dtype np float_ for j in range n xval x[j]if xval t[k] left kelse left np searchsorted t xval - 1 bb _bspl evaluate_all_bspl t k xval left A[j left - k left + 1 ] bbc sl solve A y return c | 76 |
python-test-4889 | python | How do an spline order k with knots t assemble to interpolate y(x ) ? | using full matrices | def make interp full matr x y t k assert x size y size assert t size x size + k + 1 n x size A np zeros n n dtype np float for j in range n xval x[j]if xval t[k] left kelse left np searchsorted t xval - 1 bb bspl evaluate all bspl t k xval left A[j left - k left + 1 ] bbc sl solve A y return c | def make_interp_full_matr x y t k assert x size y size assert t size x size + k + 1 n x sizeA np zeros n n dtype np float_ for j in range n xval x[j]if xval t[k] left kelse left np searchsorted t xval - 1 bb _bspl evaluate_all_bspl t k xval left A[j left - k left + 1 ] bbc sl solve A y return c | 76 |
python-test-4890 | python | What does the code add ? | an instance of the html component with the specified name | def add html component page menu index boilerplate None page wait for component menu click css page 'button>span large-html-icon' menu index require notification False page wait for element visibility ' new-component-html' 'HTM Lcomponentmenuisvisible' component css 'button[data-category html]'if boilerplate component ... | def add_html_component page menu_index boilerplate None page wait_for_component_menu click_css page 'button>span large-html-icon' menu_index require_notification False page wait_for_element_visibility ' new-component-html' 'HTMLcomponentmenuisvisible' component_css 'button[data-category html]'if boilerplate component_c... | 69 |
python-test-4892 | python | What does the code get ? | the groups roles in a given project | def get project groups roles request project groups roles collections defaultdict list project role assignments role assignments list request project project for role assignment in project role assignments if not hasattr role assignment 'group' continuegroup id role assignment group['id']role id role assignment role['i... | def get_project_groups_roles request project groups_roles collections defaultdict list project_role_assignments role_assignments_list request project project for role_assignment in project_role_assignments if not hasattr role_assignment 'group' continuegroup_id role_assignment group['id']role_id role_assignment role['i... | 62 |
python-test-4893 | python | How does the code clean the temporary directory ? | by removing all files in it called _ cffi _ * | def cleanup tmpdir tmpdir None keep so False tmpdir tmpdir or caller dir pycache try filelist os listdir tmpdir except OS Error returnif keep so suffix ' c'else suffix get so suffixes [0 ] lower for fn in filelist if fn lower startswith ' cffi ' and fn lower endswith suffix or fn lower endswith ' c' try os unlink os pa... | def cleanup_tmpdir tmpdir None keep_so False tmpdir tmpdir or _caller_dir_pycache try filelist os listdir tmpdir except OSError returnif keep_so suffix ' c'else suffix _get_so_suffixes [0] lower for fn in filelist if fn lower startswith '_cffi_' and fn lower endswith suffix or fn lower endswith ' c' try os unlink os pa... | 110 |
python-test-4895 | python | What does the code return ? | a selected template | @register simple tag takes context True def zinnia loop template context default template matching context object get context first matching object context ['category' 'tag' 'author' 'pattern' 'year' 'month' 'week' 'day'] context positions get context loop positions context templates loop template list context position... | @register simple_tag takes_context True def zinnia_loop_template context default_template matching context_object get_context_first_matching_object context ['category' 'tag' 'author' 'pattern' 'year' 'month' 'week' 'day'] context_positions get_context_loop_positions context templates loop_template_list context_position... | 55 |
python-test-4898 | python | What does the code add ? | days to the given date | def add to date date years 0 months 0 days 0 hours 0 as string False as datetime False from dateutil relativedelta import relativedeltaif date None date now datetime if hours as datetime Trueif isinstance date basestring as string Trueif u'' in date as datetime Truedate parser parse date date date + relativedelta years... | def add_to_date date years 0 months 0 days 0 hours 0 as_string False as_datetime False from dateutil relativedelta import relativedeltaif date None date now_datetime if hours as_datetime Trueif isinstance date basestring as_string Trueif u'' in date as_datetime Truedate parser parse date date date + relativedelta years... | 81 |
python-test-4899 | python | What do a registered user claim ? | the unclaimed user account | def send claim registered email claimer unclaimed user node throttle 24 * 3600 unclaimed record unclaimed user get unclaimed record node primary key timestamp unclaimed record get 'last sent' if not throttle period expired timestamp throttle raise HTTP Error http BAD REQUEST data dict message long ' Useraccountcanonlyb... | def send_claim_registered_email claimer unclaimed_user node throttle 24 * 3600 unclaimed_record unclaimed_user get_unclaimed_record node _primary_key timestamp unclaimed_record get 'last_sent' if not throttle_period_expired timestamp throttle raise HTTPError http BAD_REQUEST data dict message_long 'Useraccountcanonlybe... | 146 |
python-test-4900 | python | What is claiming the unclaimed user account ? | a registered user | def send claim registered email claimer unclaimed user node throttle 24 * 3600 unclaimed record unclaimed user get unclaimed record node primary key timestamp unclaimed record get 'last sent' if not throttle period expired timestamp throttle raise HTTP Error http BAD REQUEST data dict message long ' Useraccountcanonlyb... | def send_claim_registered_email claimer unclaimed_user node throttle 24 * 3600 unclaimed_record unclaimed_user get_unclaimed_record node _primary_key timestamp unclaimed_record get 'last_sent' if not throttle_period_expired timestamp throttle raise HTTPError http BAD_REQUEST data dict message_long 'Useraccountcanonlybe... | 146 |
python-test-4902 | python | What does it parse ? | the information that will go in the xml file | def parse extra info info if not info return infofinfos info split ' ' data for files {}for finfo in finfos items finfo split '{' if len items 1 fname fake sff nameinfo items[ 0 ]else fname items[ 0 ]info items[ 1 ]info info replace '}' '' data {}for item in info split ' ' key value item strip split ' ' key key strip v... | def parse_extra_info info if not info return infofinfos info split ' ' data_for_files {}for finfo in finfos items finfo split '{' if len items 1 fname fake_sff_nameinfo items[0]else fname items[0]info items[1]info info replace '}' '' data {}for item in info split ' ' key value item strip split ' ' key key strip value v... | 76 |
python-test-4904 | python | What does the code create ? | a new decorator decorator converts a caller function into a decorator | def decorator caller func None if func is None @functools wraps caller def decorator f *args **opts @functools wraps f def caller *args **opts return caller f *args **opts return caller decorator func callerreturn decoratorelse @functools wraps func def decorated *args **opts return caller func *args **opts decorated f... | def decorator caller func None if func is None @functools wraps caller def _decorator f *args **opts @functools wraps f def _caller *args **opts return caller f *args **opts return _caller_decorator func callerreturn _decoratorelse @functools wraps func def _decorated *args **opts return caller func *args **opts _decor... | 51 |
python-test-4905 | python | What does decorator use ? | a caller | def decorator caller func None if func is None @functools wraps caller def decorator f *args **opts @functools wraps f def caller *args **opts return caller f *args **opts return caller decorator func callerreturn decoratorelse @functools wraps func def decorated *args **opts return caller func *args **opts decorated f... | def decorator caller func None if func is None @functools wraps caller def _decorator f *args **opts @functools wraps f def _caller *args **opts return caller f *args **opts return _caller_decorator func callerreturn _decoratorelse @functools wraps func def _decorated *args **opts return caller func *args **opts _decor... | 51 |
python-test-4906 | python | What converts a caller function into a decorator ? | a new decorator decorator | def decorator caller func None if func is None @functools wraps caller def decorator f *args **opts @functools wraps f def caller *args **opts return caller f *args **opts return caller decorator func callerreturn decoratorelse @functools wraps func def decorated *args **opts return caller func *args **opts decorated f... | def decorator caller func None if func is None @functools wraps caller def _decorator f *args **opts @functools wraps f def _caller *args **opts return caller f *args **opts return _caller_decorator func callerreturn _decoratorelse @functools wraps func def _decorated *args **opts return caller func *args **opts _decor... | 51 |
python-test-4907 | python | What does the code create ? | a dock widget | def create dock title parent stretch True dock Qt Widgets Q Dock Widget parent dock set Window Title title dock set Object Name title titlebar Dock Title Bar Widget dock title stretch stretch dock set Title Bar Widget titlebar dock set Auto Fill Background True if hasattr parent u'dockwidgets' parent dockwidgets append... | def create_dock title parent stretch True dock QtWidgets QDockWidget parent dock setWindowTitle title dock setObjectName title titlebar DockTitleBarWidget dock title stretch stretch dock setTitleBarWidget titlebar dock setAutoFillBackground True if hasattr parent u'dockwidgets' parent dockwidgets append dock return doc... | 55 |
python-test-4909 | python | What do multiple file locations contain ? | mime - types | def load Mime Types mimetype locations ['/etc/mime types'] import mimetypescontent Types mimetypes types mapcontent Types update {' conf' 'text/plain' ' diff' 'text/plain' ' exe' 'application/x-executable' ' flac' 'audio/x-flac' ' java' 'text/plain' ' ogg' 'application/ogg' ' oz' 'text/x-oz' ' swf' 'application/x-shock... | def loadMimeTypes mimetype_locations ['/etc/mime types'] import mimetypescontentTypes mimetypes types_mapcontentTypes update {' conf' 'text/plain' ' diff' 'text/plain' ' exe' 'application/x-executable' ' flac' 'audio/x-flac' ' java' 'text/plain' ' ogg' 'application/ogg' ' oz' 'text/x-oz' ' swf' 'application/x-shockwave... | 87 |
python-test-4910 | python | What is containing mime - types ? | multiple file locations | def load Mime Types mimetype locations ['/etc/mime types'] import mimetypescontent Types mimetypes types mapcontent Types update {' conf' 'text/plain' ' diff' 'text/plain' ' exe' 'application/x-executable' ' flac' 'audio/x-flac' ' java' 'text/plain' ' ogg' 'application/ogg' ' oz' 'text/x-oz' ' swf' 'application/x-shock... | def loadMimeTypes mimetype_locations ['/etc/mime types'] import mimetypescontentTypes mimetypes types_mapcontentTypes update {' conf' 'text/plain' ' diff' 'text/plain' ' exe' 'application/x-executable' ' flac' 'audio/x-flac' ' java' 'text/plain' ' ogg' 'application/ogg' ' oz' 'text/x-oz' ' swf' 'application/x-shockwave... | 87 |
python-test-4911 | python | What does the code write ? | the flv header and the metadata to stream | def write flv header stream metadata stream write 'FLV\x 01 ' stream write '\x 05 ' stream write '\x 00 \x 00 \x 00 DCTB ' stream write '\x 00 \x 00 \x 00 \x 00 ' stream write '\x 12 ' stream write struct pack u' L' len metadata [1 ] stream write '\x 00 \x 00 \x 00 \x 00 \x 00 \x 00 \x 00 ' stream write metadata stream... | def write_flv_header stream metadata stream write 'FLV\x01' stream write '\x05' stream write '\x00\x00\x00 DCTB ' stream write '\x00\x00\x00\x00' stream write '\x12' stream write struct_pack u' L' len metadata [1 ] stream write '\x00\x00\x00\x00\x00\x00\x00' stream write metadata stream write '\x00\x00\x01s' | 81 |
python-test-4912 | python | How do rectangular data plot ? | as a color - encoded matrix | def heatmap data vmin None vmax None cmap None center None robust False annot None fmt ' 2g' annot kws None linewidths 0 linecolor 'white' cbar True cbar kws None cbar ax None square False ax None xticklabels True yticklabels True mask None **kwargs plotter Heat Mapper data vmin vmax cmap center robust annot fmt annot ... | def heatmap data vmin None vmax None cmap None center None robust False annot None fmt ' 2g' annot_kws None linewidths 0 linecolor 'white' cbar True cbar_kws None cbar_ax None square False ax None xticklabels True yticklabels True mask None **kwargs plotter _HeatMapper data vmin vmax cmap center robust annot fmt annot_... | 86 |
python-test-4914 | python | Where is the derivative evaluated ? | array parameters | def approx fprime cs x f epsilon None args kwargs {} n len x epsilon get epsilon x 1 epsilon n increments np identity n * 1j * epsilon partials [ f x + ih *args **kwargs imag / epsilon[i] for i ih in enumerate increments ]return np array partials T | def approx_fprime_cs x f epsilon None args kwargs {} n len x epsilon _get_epsilon x 1 epsilon n increments np identity n * 1j * epsilon partials [ f x + ih *args **kwargs imag / epsilon[i] for i ih in enumerate increments ]return np array partials T | 51 |
python-test-4915 | python | How do gradient or jacobian calculate ? | with complex step derivative approximation parameters x : array parameters at which the derivative is evaluated f : function f(*(+args ) | def approx fprime cs x f epsilon None args kwargs {} n len x epsilon get epsilon x 1 epsilon n increments np identity n * 1j * epsilon partials [ f x + ih *args **kwargs imag / epsilon[i] for i ih in enumerate increments ]return np array partials T | def approx_fprime_cs x f epsilon None args kwargs {} n len x epsilon _get_epsilon x 1 epsilon n increments np identity n * 1j * epsilon partials [ f x + ih *args **kwargs imag / epsilon[i] for i ih in enumerate increments ]return np array partials T | 51 |
python-test-4916 | python | What is evaluated array parameters ? | the derivative | def approx fprime cs x f epsilon None args kwargs {} n len x epsilon get epsilon x 1 epsilon n increments np identity n * 1j * epsilon partials [ f x + ih *args **kwargs imag / epsilon[i] for i ih in enumerate increments ]return np array partials T | def approx_fprime_cs x f epsilon None args kwargs {} n len x epsilon _get_epsilon x 1 epsilon n increments np identity n * 1j * epsilon partials [ f x + ih *args **kwargs imag / epsilon[i] for i ih in enumerate increments ]return np array partials T | 51 |
python-test-4917 | python | What does the code create ? | a json with the open distribution for all the subsections in the course | def all sequential open distrib request course id data {}course key Slash Separated Course Key from deprecated string course id if has instructor access for class request user course key try data dashboard data get d3 sequential open distrib course key except Exception as ex log error ' Generatingmetricsfailedwithexcep... | def all_sequential_open_distrib request course_id data {}course_key SlashSeparatedCourseKey from_deprecated_string course_id if has_instructor_access_for_class request user course_key try data dashboard_data get_d3_sequential_open_distrib course_key except Exception as ex log error 'Generatingmetricsfailedwithexception... | 68 |
python-test-4921 | python | What does the code get ? | a dict mapping funcs to colors from palette | def get colors palette funcs palettes import required 'bokeh palettes' BOKEH MISSING MSG tz import required 'toolz' TOOLZ MISSING MSG unique funcs list sorted tz unique funcs n funcs len unique funcs palette lookup palettes all palettes[palette]keys list sorted palette lookup keys index keys[min bisect left keys n func... | def get_colors palette funcs palettes import_required 'bokeh palettes' _BOKEH_MISSING_MSG tz import_required 'toolz' _TOOLZ_MISSING_MSG unique_funcs list sorted tz unique funcs n_funcs len unique_funcs palette_lookup palettes all_palettes[palette]keys list sorted palette_lookup keys index keys[min bisect_left keys n_fu... | 86 |
python-test-4924 | python | What does the code save ? | a collection item to file system | def serialize item collection item if item name is None or item name '' raise exceptions Runtime Error 'nameunsetforitem ' if collection collection type in ['mgmtclass'] filename '/var/lib/cobbler/collections/%ses/%s' % collection collection type item name else filename '/var/lib/cobbler/collections/%ss/%s' % collectio... | def serialize_item collection item if item name is None or item name '' raise exceptions RuntimeError 'nameunsetforitem ' if collection collection_type in ['mgmtclass'] filename '/var/lib/cobbler/collections/%ses/%s' % collection collection_type item name else filename '/var/lib/cobbler/collections/%ss/%s' % collection... | 93 |
python-test-4929 | python | What have the same meaning as they do when using : func : ssl ? | all arguments except for server_hostname and ssl_context | def ssl wrap socket sock keyfile None certfile None cert reqs None ca certs None server hostname None ssl version None ciphers None ssl context None context ssl contextif context is None context create urllib 3 context ssl version cert reqs ciphers ciphers if ca certs try context load verify locations ca certs except I... | def ssl_wrap_socket sock keyfile None certfile None cert_reqs None ca_certs None server_hostname None ssl_version None ciphers None ssl_context None context ssl_contextif context is None context create_urllib3_context ssl_version cert_reqs ciphers ciphers if ca_certs try context load_verify_locations ca_certs except IO... | 101 |
python-test-4930 | python | What do all arguments except for server_hostname and ssl_context have ? | the same meaning as they do when using : func : ssl | def ssl wrap socket sock keyfile None certfile None cert reqs None ca certs None server hostname None ssl version None ciphers None ssl context None context ssl contextif context is None context create urllib 3 context ssl version cert reqs ciphers ciphers if ca certs try context load verify locations ca certs except I... | def ssl_wrap_socket sock keyfile None certfile None cert_reqs None ca_certs None server_hostname None ssl_version None ciphers None ssl_context None context ssl_contextif context is None context create_urllib3_context ssl_version cert_reqs ciphers ciphers if ca_certs try context load_verify_locations ca_certs except IO... | 101 |
python-test-4931 | python | What does the code allow ? | some basic logging configuration to be read from the cherrpy config | def configure logging config format config get 'log format' '% name s% levelname s% asctime s% message s' level logging level Names[config get 'log level' 'DEBUG' ]destination config get 'log destination' 'stdout' log info " Loggingat'%s'levelto'%s'" % level destination root logging get Logger root set Level level if l... | def configure_logging config format config get 'log_format' '% name s% levelname s% asctime s% message s' level logging _levelNames[config get 'log_level' 'DEBUG' ]destination config get 'log_destination' 'stdout' log info "Loggingat'%s'levelto'%s'" % level destination root logging getLogger root setLevel level if leve... | 100 |
python-test-4932 | python | How be some basic logging configuration read ? | from the cherrpy config | def configure logging config format config get 'log format' '% name s% levelname s% asctime s% message s' level logging level Names[config get 'log level' 'DEBUG' ]destination config get 'log destination' 'stdout' log info " Loggingat'%s'levelto'%s'" % level destination root logging get Logger root set Level level if l... | def configure_logging config format config get 'log_format' '% name s% levelname s% asctime s% message s' level logging _levelNames[config get 'log_level' 'DEBUG' ]destination config get 'log_destination' 'stdout' log info "Loggingat'%s'levelto'%s'" % level destination root logging getLogger root setLevel level if leve... | 100 |
python-test-4938 | python | What does binary search use ? | to find what module a given address resides in | def find module modlist mod addrs addr pos bisect right mod addrs addr - 1 if pos -1 return Nonemod modlist[mod addrs[pos]]if mod obj vm address compare addr mod Dll Base -1 and mod obj vm address compare addr mod Dll Base + mod Size Of Image -1 return modelse return None | def find_module modlist mod_addrs addr pos bisect_right mod_addrs addr - 1 if pos -1 return Nonemod modlist[mod_addrs[pos]]if mod obj_vm address_compare addr mod DllBase -1 and mod obj_vm address_compare addr mod DllBase + mod SizeOfImage -1 return modelse return None | 52 |
python-test-4948 | python | Where are boundaries between labeled regions are true ? | return bool array | def find boundaries label img connectivity 1 mode 'thick' background 0 if label img dtype 'bool' label img label img astype np uint 8 ndim label img ndimselem ndi generate binary structure ndim connectivity if mode 'subpixel' boundaries dilation label img selem erosion label img selem if mode 'inner' foreground image l... | def find_boundaries label_img connectivity 1 mode 'thick' background 0 if label_img dtype 'bool' label_img label_img astype np uint8 ndim label_img ndimselem ndi generate_binary_structure ndim connectivity if mode 'subpixel' boundaries dilation label_img selem erosion label_img selem if mode 'inner' foreground_image la... | 121 |
python-test-4949 | python | What are true return bool array ? | boundaries between labeled regions | def find boundaries label img connectivity 1 mode 'thick' background 0 if label img dtype 'bool' label img label img astype np uint 8 ndim label img ndimselem ndi generate binary structure ndim connectivity if mode 'subpixel' boundaries dilation label img selem erosion label img selem if mode 'inner' foreground image l... | def find_boundaries label_img connectivity 1 mode 'thick' background 0 if label_img dtype 'bool' label_img label_img astype np uint8 ndim label_img ndimselem ndi generate_binary_structure ndim connectivity if mode 'subpixel' boundaries dilation label_img selem erosion label_img selem if mode 'inner' foreground_image la... | 121 |
python-test-4950 | python | What does the code make ? | home assistant discoverable | def setup hass config from zeroconf import Zeroconf Service Infozeroconf Zeroconf zeroconf name '{} {}' format hass config location name ZEROCONF TYPE requires api password hass config api api password is not None params {'version' version 'base url' hass config api base url 'requires api password' requires api passwor... | def setup hass config from zeroconf import Zeroconf ServiceInfozeroconf Zeroconf zeroconf_name '{} {}' format hass config location_name ZEROCONF_TYPE requires_api_password hass config api api_password is not None params {'version' __version__ 'base_url' hass config api base_url 'requires_api_password' requires_api_pass... | 126 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.