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-4951 | python | What did the code set ? | zeroconf | 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 |
python-test-4952 | python | What does the code create from all the files under base_dir ? | a tar file | def make tarball base name base dir compress 'gzip' verbose 0 dry run 0 compress ext {'gzip' ' gz' 'bzip 2 ' ' bz 2 ' 'compress' ' Z'}compress flags {'gzip' ['-f 9 '] 'compress' ['-f'] 'bzip 2 ' ['-f 9 ']}if compress is not None and compress not in compress ext keys raise Value Error "badvaluefor'compress' mustbe None ... | def make_tarball base_name base_dir compress 'gzip' verbose 0 dry_run 0 compress_ext {'gzip' ' gz' 'bzip2' ' bz2' 'compress' ' Z'}compress_flags {'gzip' ['-f9'] 'compress' ['-f'] 'bzip2' ['-f9']}if compress is not None and compress not in compress_ext keys raise ValueError "badvaluefor'compress' mustbeNone 'gzip' or'co... | 113 |
python-test-4958 | python | What found in env ? | all prefixes | def prefix commands command which prefixes list env command prefixes cwd env cwd if which 'remote' else env lcwd redirect '>/dev/null' if not win 32 else '' if cwd prefixes insert 0 'cd%s%s' % cwd redirect glue '&&'prefix glue join prefixes + glue if prefixes else '' return prefix + command | def _prefix_commands command which prefixes list env command_prefixes cwd env cwd if which 'remote' else env lcwd redirect '>/dev/null' if not win32 else '' if cwd prefixes insert 0 'cd%s%s' % cwd redirect glue '&&'prefix glue join prefixes + glue if prefixes else '' return prefix + command | 51 |
python-test-4966 | python | What does the code create ? | the dialog showing the message | def Friendly Exception Dlg message class w3 af message dialog gtk Message Dialog def dialog response cb self widget response id '\nhttp //faq pygtk org/index py?req show&file faq 10 017 htp\n'self destroy def dialog run self '\nhttp //faq pygtk org/index py?req show&file faq 10 017 htp\n'if not self modal self set moda... | def FriendlyExceptionDlg message class w3af_message_dialog gtk MessageDialog def dialog_response_cb self widget response_id '\nhttp //faq pygtk org/index py?req show&file faq10 017 htp\n'self destroy def dialog_run self '\nhttp //faq pygtk org/index py?req show&file faq10 017 htp\n'if not self modal self set_modal True... | 95 |
python-test-4967 | python | What is showing the message ? | the dialog | def Friendly Exception Dlg message class w3 af message dialog gtk Message Dialog def dialog response cb self widget response id '\nhttp //faq pygtk org/index py?req show&file faq 10 017 htp\n'self destroy def dialog run self '\nhttp //faq pygtk org/index py?req show&file faq 10 017 htp\n'if not self modal self set moda... | def FriendlyExceptionDlg message class w3af_message_dialog gtk MessageDialog def dialog_response_cb self widget response_id '\nhttp //faq pygtk org/index py?req show&file faq10 017 htp\n'self destroy def dialog_run self '\nhttp //faq pygtk org/index py?req show&file faq10 017 htp\n'if not self modal self set_modal True... | 95 |
python-test-4969 | python | What does the code generate ? | the vertices for a third order bezier curve | def curve 4 bezier p1 p2 p3 p4 x1 y1 p1 x2 y2 p2 x3 y3 p3 x4 y4 p4 points [] curve 4 recursive bezier points x1 y1 x2 y2 x3 y3 x4 y4 dx dy points[ 0 ][ 0 ] - x1 points[ 0 ][ 1 ] - y1 if dx * dx + dy * dy > 1e- 10 points insert 0 x1 y1 dx dy points[ -1 ][ 0 ] - x4 points[ -1 ][ 1 ] - y4 if dx * dx + dy * dy > 1e- 10 poi... | def curve4_bezier p1 p2 p3 p4 x1 y1 p1 x2 y2 p2 x3 y3 p3 x4 y4 p4points []_curve4_recursive_bezier points x1 y1 x2 y2 x3 y3 x4 y4 dx dy points[0][0] - x1 points[0][1] - y1 if dx * dx + dy * dy > 1e-10 points insert 0 x1 y1 dx dy points[ -1 ][0] - x4 points[ -1 ][1] - y4 if dx * dx + dy * dy > 1e-10 points append x4 y4 ... | 106 |
python-test-4971 | python | How does the code remove a script ? | by running the various removal scripts | def remove package package dst path os path join package where package name run scripts path scripts ['prerm'] shutil rmtree os path join path 'data/' shutil rmtree os path join path 'docs/' run scripts os path join dst package name scripts ['postrm'] shutil rmtree os path join path 'scripts/' shutil rmtree path update... | def remove_package package dst path os path join package where package name run_scripts path scripts ['prerm'] shutil rmtree os path join path 'data/' shutil rmtree os path join path 'docs/' run_scripts os path join dst package name scripts ['postrm'] shutil rmtree os path join path 'scripts/' shutil rmtree path update... | 57 |
python-test-4980 | python | What does before_request handler check to see if the user is requesting from a view - only link ? | the referer header | def prepare private key if request method 'GET' returnif request args get 'view only' '' returnif request referrer referrer parsed urlparse urlparse request referrer scheme referrer parsed schemekey urlparse parse qs urlparse urlparse request referrer query get 'view only' if key key key[ 0 ]else scheme Nonekey Noneif ... | def prepare_private_key if request method 'GET' returnif request args get 'view_only' '' returnif request referrer referrer_parsed urlparse urlparse request referrer scheme referrer_parsed schemekey urlparse parse_qs urlparse urlparse request referrer query get 'view_only' if key key key[0]else scheme Nonekey Noneif ke... | 72 |
python-test-4981 | python | What checks the referer header to see if the user is requesting from a view - only link ? | before_request handler | def prepare private key if request method 'GET' returnif request args get 'view only' '' returnif request referrer referrer parsed urlparse urlparse request referrer scheme referrer parsed schemekey urlparse parse qs urlparse urlparse request referrer query get 'view only' if key key key[ 0 ]else scheme Nonekey Noneif ... | def prepare_private_key if request method 'GET' returnif request args get 'view_only' '' returnif request referrer referrer_parsed urlparse urlparse request referrer scheme referrer_parsed schemekey urlparse parse_qs urlparse urlparse request referrer query get 'view_only' if key key key[0]else scheme Nonekey Noneif ke... | 72 |
python-test-4985 | python | How do the network train ? | using both the default and the large starting weights | def run network filename n eta random seed 12345678 np random seed 12345678 training data validation data test data mnist loader load data wrapper net network 2 Network [784 n 10 ] cost network 2 Cross Entropy Cost print ' Trainthenetworkusingthedefaultstartingweights ' default vc default va default tc default ta net S... | def run_network filename n eta random seed 12345678 np random seed 12345678 training_data validation_data test_data mnist_loader load_data_wrapper net network2 Network [784 n 10] cost network2 CrossEntropyCost print 'Trainthenetworkusingthedefaultstartingweights ' default_vc default_va default_tc default_ta net SGD tra... | 132 |
python-test-4993 | python | What performs on the input image ? | logarithmic correction | def adjust log image gain 1 inv False assert non negative image dtype image dtype typescale float dtype limits image True [1 ] - dtype limits image True [0 ] if inv out 2 ** image / scale - 1 * scale * gain return dtype out out np log 2 1 + image / scale * scale * gain return dtype out | def adjust_log image gain 1 inv False _assert_non_negative image dtype image dtype typescale float dtype_limits image True [1] - dtype_limits image True [0] if inv out 2 ** image / scale - 1 * scale * gain return dtype out out np log2 1 + image / scale * scale * gain return dtype out | 63 |
python-test-4994 | python | What must the tables have ? | exactly the same number of rows | def hstack tables join type u'outer' uniq col name u'{col name} {table name}' table names None metadata conflicts u'warn' tables get list of tables tables if len tables 1 return tables[ 0 ]col name map Ordered Dict out hstack tables join type uniq col name table names col name map merge col meta out tables col name map... | def hstack tables join_type u'outer' uniq_col_name u'{col_name}_{table_name}' table_names None metadata_conflicts u'warn' tables _get_list_of_tables tables if len tables 1 return tables[0]col_name_map OrderedDict out _hstack tables join_type uniq_col_name table_names col_name_map _merge_col_meta out tables col_name_map... | 73 |
python-test-4995 | python | What does the code check ? | jd2jcal | def test jd 2 jcal import randomn 1000 year [random randint -4699 2200 for i in range n ]month [random randint 1 12 for i in range n ]day [random randint 1 28 for i in range n ]jd [jcal 2 jd y m d [1 ] for y m d in zip year month day ]x [jd 2 gcal MJD 0 i for i in jd]for i in range n assert x[i][ 0 ] year[i] assert x[i... | def _test_jd2jcal import randomn 1000year [random randint -4699 2200 for i in range n ]month [random randint 1 12 for i in range n ]day [random randint 1 28 for i in range n ]jd [jcal2jd y m d [1] for y m d in zip year month day ]x [jd2gcal MJD_0 i for i in jd]for i in range n assert x[i][0] year[i] assert x[i][1] mont... | 93 |
python-test-4997 | python | When were the indices attached to parameter names on a compound model have not handled an issue properly ? | when one or more submodels have no parameters | def test slicing on instance with parameterless model p2 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 p1 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x translation' offy Shift -1 name u'y translation' aff Affine Transformation 2 D matrix [[ 1 2] [3 4]] name u'rotation' model mapping p1 & ... | def test_slicing_on_instance_with_parameterless_model p2 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 p1 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x_translation' offy Shift -1 name u'y_translation' aff AffineTransformation2D matrix [[1 2] [3 4]] name u'rotation' model mapping p1 & p2 offx ... | 143 |
python-test-4998 | python | Were the indices attached to parameter names on a compound model have handled an issue properly when one or more submodels have no parameters ? | No | def test slicing on instance with parameterless model p2 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 p1 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x translation' offy Shift -1 name u'y translation' aff Affine Transformation 2 D matrix [[ 1 2] [3 4]] name u'rotation' model mapping p1 & ... | def test_slicing_on_instance_with_parameterless_model p2 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 p1 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x_translation' offy Shift -1 name u'y_translation' aff AffineTransformation2D matrix [[1 2] [3 4]] name u'rotation' model mapping p1 & p2 offx ... | 143 |
python-test-4999 | python | What have no parameters when ? | one or more submodels | def test slicing on instance with parameterless model p2 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 p1 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x translation' offy Shift -1 name u'y translation' aff Affine Transformation 2 D matrix [[ 1 2] [3 4]] name u'rotation' model mapping p1 & ... | def test_slicing_on_instance_with_parameterless_model p2 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 p1 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x_translation' offy Shift -1 name u'y_translation' aff AffineTransformation2D matrix [[1 2] [3 4]] name u'rotation' model mapping p1 & p2 offx ... | 143 |
python-test-5000 | python | What were have not handled an issue ? | the indices attached to parameter names on a compound model | def test slicing on instance with parameterless model p2 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 p1 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x translation' offy Shift -1 name u'y translation' aff Affine Transformation 2 D matrix [[ 1 2] [3 4]] name u'rotation' model mapping p1 & ... | def test_slicing_on_instance_with_parameterless_model p2 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 p1 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x_translation' offy Shift -1 name u'y_translation' aff AffineTransformation2D matrix [[1 2] [3 4]] name u'rotation' model mapping p1 & p2 offx ... | 143 |
python-test-5001 | python | Where were the indices attached to parameter names on a compound model have not handled properly when one or more submodels have no parameters ? | an issue | def test slicing on instance with parameterless model p2 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 p1 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x translation' offy Shift -1 name u'y translation' aff Affine Transformation 2 D matrix [[ 1 2] [3 4]] name u'rotation' model mapping p1 & ... | def test_slicing_on_instance_with_parameterless_model p2 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 p1 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x_translation' offy Shift -1 name u'y_translation' aff AffineTransformation2D matrix [[1 2] [3 4]] name u'rotation' model mapping p1 & p2 offx ... | 143 |
python-test-5002 | python | What do regression test fix ? | an issue where the indices attached to parameter names on a compound model were not handled properly when one or more submodels have no parameters | def test slicing on instance with parameterless model p2 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 p1 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x translation' offy Shift -1 name u'y translation' aff Affine Transformation 2 D matrix [[ 1 2] [3 4]] name u'rotation' model mapping p1 & ... | def test_slicing_on_instance_with_parameterless_model p2 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 p1 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x_translation' offy Shift -1 name u'y_translation' aff AffineTransformation2D matrix [[1 2] [3 4]] name u'rotation' model mapping p1 & p2 offx ... | 143 |
python-test-5003 | python | What did one or more submodels have when ? | no parameters | def test slicing on instance with parameterless model p2 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 p1 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x translation' offy Shift -1 name u'y translation' aff Affine Transformation 2 D matrix [[ 1 2] [3 4]] name u'rotation' model mapping p1 & ... | def test_slicing_on_instance_with_parameterless_model p2 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 p1 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x_translation' offy Shift -1 name u'y_translation' aff AffineTransformation2D matrix [[1 2] [3 4]] name u'rotation' model mapping p1 & p2 offx ... | 143 |
python-test-5004 | python | How were the indices attached to parameter names on a compound model have not handled an issue when one or more submodels have no parameters ? | properly | def test slicing on instance with parameterless model p2 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 p1 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x translation' offy Shift -1 name u'y translation' aff Affine Transformation 2 D matrix [[ 1 2] [3 4]] name u'rotation' model mapping p1 & ... | def test_slicing_on_instance_with_parameterless_model p2 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 p1 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x_translation' offy Shift -1 name u'y_translation' aff AffineTransformation2D matrix [[1 2] [3 4]] name u'rotation' model mapping p1 & p2 offx ... | 143 |
python-test-5005 | python | What fixs an issue where the indices attached to parameter names on a compound model were not handled properly when one or more submodels have no parameters ? | regression test | def test slicing on instance with parameterless model p2 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 p1 Polynomial 2 D 1 c0 0 1 c1 0 2 c0 1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x translation' offy Shift -1 name u'y translation' aff Affine Transformation 2 D matrix [[ 1 2] [3 4]] name u'rotation' model mapping p1 & ... | def test_slicing_on_instance_with_parameterless_model p2 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 p1 Polynomial2D 1 c0_0 1 c1_0 2 c0_1 3 mapping Mapping 0 1 0 1 offx Shift -2 name u'x_translation' offy Shift -1 name u'y_translation' aff AffineTransformation2D matrix [[1 2] [3 4]] name u'rotation' model mapping p1 & p2 offx ... | 143 |
python-test-5010 | python | What appends to filename ? | string text | def append filename text use sudo False partial False escape True shell False func use sudo and sudo or run if isinstance text basestring text [text]for line in text regex '^' + escape for regex line + '' if partial else '$' if exists filename use sudo use sudo and line and contains filename regex use sudo use sudo esc... | def append filename text use_sudo False partial False escape True shell False func use_sudo and sudo or run if isinstance text basestring text [text]for line in text regex '^' + _escape_for_regex line + '' if partial else '$' if exists filename use_sudo use_sudo and line and contains filename regex use_sudo use_sudo es... | 79 |
python-test-5011 | python | What do they follow otherwise ? | the bucket naming rules | def test ipv 4 detect assert is ipv 4 like '1 1 1 1' is True assert is ipv 4 like '1 1 1 256 ' is True assert is ipv 4 like '- 1 1 1 1' is True assert is ipv 4 like '1 1 1 hello' is False assert is ipv 4 like 'hello' is False assert is ipv 4 like '- 1 1 1' is False assert is ipv 4 like '- 1 1 1 ' is False | def test_ipv4_detect assert _is_ipv4_like '1 1 1 1' is True assert _is_ipv4_like '1 1 1 256' is True assert _is_ipv4_like '-1 1 1 1' is True assert _is_ipv4_like '1 1 1 hello' is False assert _is_ipv4_like 'hello' is False assert _is_ipv4_like '-1 1 1' is False assert _is_ipv4_like '-1 1 1 ' is False | 82 |
python-test-5013 | python | How does the code match a node ? | by specified attribute values | def attribute matcher kwargs def match node if 'terminal' in kwargs kwa copy kwargs copy pattern kwa copy pop 'terminal' if pattern is not None and not hasattr node 'is terminal' or node is terminal pattern return Falseelse kwa copy kwargsfor key pattern in kwa copy items if not hasattr node key return Falsetarget geta... | def _attribute_matcher kwargs def match node if 'terminal' in kwargs kwa_copy kwargs copy pattern kwa_copy pop 'terminal' if pattern is not None and not hasattr node 'is_terminal' or node is_terminal pattern return Falseelse kwa_copy kwargsfor key pattern in kwa_copy items if not hasattr node key return Falsetarget get... | 106 |
python-test-5019 | python | What does the code update ? | the datastore / datacenter cache | def update datacenter cache from objects session dcs while dcs for dco in dcs objects dc ref dco objds refs []prop dict vm util propset dict dco prop Set name prop dict get 'name' vm Folder prop dict get 'vm Folder' datastore refs prop dict get 'datastore' if datastore refs datastore refs datastore refs Managed Object ... | def _update_datacenter_cache_from_objects session dcs while dcs for dco in dcs objects dc_ref dco objds_refs []prop_dict vm_util propset_dict dco propSet name prop_dict get 'name' vmFolder prop_dict get 'vmFolder' datastore_refs prop_dict get 'datastore' if datastore_refs datastore_refs datastore_refs ManagedObjectRefe... | 102 |
python-test-5026 | python | What do that use ? | their metadata | def group albums session def group item return item albumartist or item artist item album task Nonewhile True task yield task if task skip continuetasks []sorted items sorted task items key group for items in itertools groupby sorted items group items list items task Import Task task toppath [i path for i in items] ite... | def group_albums session def group item return item albumartist or item artist item album task Nonewhile True task yield task if task skip continuetasks []sorted_items sorted task items key group for _ items in itertools groupby sorted_items group items list items task ImportTask task toppath [i path for i in items] it... | 74 |
python-test-5027 | python | What groups the items of each task into albums using their metadata ? | a pipeline stage | def group albums session def group item return item albumartist or item artist item album task Nonewhile True task yield task if task skip continuetasks []sorted items sorted task items key group for items in itertools groupby sorted items group items list items task Import Task task toppath [i path for i in items] ite... | def group_albums session def group item return item albumartist or item artist item album task Nonewhile True task yield task if task skip continuetasks []sorted_items sorted task items key group for _ items in itertools groupby sorted_items group items list items task ImportTask task toppath [i path for i in items] it... | 74 |
python-test-5028 | python | How does a pipeline stage group the items of each task into albums ? | using their metadata | def group albums session def group item return item albumartist or item artist item album task Nonewhile True task yield task if task skip continuetasks []sorted items sorted task items key group for items in itertools groupby sorted items group items list items task Import Task task toppath [i path for i in items] ite... | def group_albums session def group item return item albumartist or item artist item album task Nonewhile True task yield task if task skip continuetasks []sorted_items sorted task items key group for _ items in itertools groupby sorted_items group items list items task ImportTask task toppath [i path for i in items] it... | 74 |
python-test-5029 | python | What does a pipeline stage group into albums using their metadata ? | the items of each task | def group albums session def group item return item albumartist or item artist item album task Nonewhile True task yield task if task skip continuetasks []sorted items sorted task items key group for items in itertools groupby sorted items group items list items task Import Task task toppath [i path for i in items] ite... | def group_albums session def group item return item albumartist or item artist item album task Nonewhile True task yield task if task skip continuetasks []sorted_items sorted task items key group for _ items in itertools groupby sorted_items group items list items task ImportTask task toppath [i path for i in items] it... | 74 |
python-test-5030 | python | What does this method provide ? | a generator of patches from the data field in a chunk | def unpack patches hg unbundle 10 obj remaining while remaining > 12 start end blocklen struct unpack '>lll' readexactly hg unbundle 10 obj 12 remaining - 12 if blocklen > remaining raise Exception 'unexpectedendofpatchstream' block readexactly hg unbundle 10 obj blocklen remaining - blocklen yield {'start' start 'end'... | def unpack_patches hg_unbundle10_obj remaining while remaining > 12 start end blocklen struct unpack '>lll' readexactly hg_unbundle10_obj 12 remaining - 12if blocklen > remaining raise Exception 'unexpectedendofpatchstream' block readexactly hg_unbundle10_obj blocklen remaining - blocklen yield {'start' start 'end' end... | 70 |
python-test-5031 | python | For what purpose do bot irc ? | for interacting with salt | def start nick host port 6667 username None password None channels None use ssl False use sasl False char ' ' allow hosts False allow nicks False disable query True client IRC Client nick host port username password channels or [] use ssl use sasl char allow hosts allow nicks disable query client io loop start | def start nick host port 6667 username None password None channels None use_ssl False use_sasl False char ' ' allow_hosts False allow_nicks False disable_query True client IRCClient nick host port username password channels or [] use_ssl use_sasl char allow_hosts allow_nicks disable_query client io_loop start | 56 |
python-test-5032 | python | What do a dict describe as key ? | all group_types with name | @require contextdef group type get all context inactive False filters None marker None limit None sort keys None sort dirs None offset None list result False session get session with session begin filters filters or {} filters['context'] contextquery generate paginate query context session marker limit sort keys sort d... | @require_contextdef group_type_get_all context inactive False filters None marker None limit None sort_keys None sort_dirs None offset None list_result False session get_session with session begin filters filters or {} filters['context'] contextquery _generate_paginate_query context session marker limit sort_keys sort_... | 98 |
python-test-5033 | python | What do the baseline and deltas expressions have ? | a timestamp field | def ensure timestamp field dataset expr deltas checkpoints measure dataset expr dshape measureif TS FIELD NAME not in measure names dataset expr bz transform dataset expr **{TS FIELD NAME dataset expr[AD FIELD NAME]} deltas ad as ts deltas checkpoints ad as ts checkpoints else check datetime field TS FIELD NAME measure... | def _ensure_timestamp_field dataset_expr deltas checkpoints measure dataset_expr dshape measureif TS_FIELD_NAME not in measure names dataset_expr bz transform dataset_expr **{TS_FIELD_NAME dataset_expr[AD_FIELD_NAME]} deltas _ad_as_ts deltas checkpoints _ad_as_ts checkpoints else _check_datetime_field TS_FIELD_NAME mea... | 56 |
python-test-5034 | python | What have a timestamp field ? | the baseline and deltas expressions | def ensure timestamp field dataset expr deltas checkpoints measure dataset expr dshape measureif TS FIELD NAME not in measure names dataset expr bz transform dataset expr **{TS FIELD NAME dataset expr[AD FIELD NAME]} deltas ad as ts deltas checkpoints ad as ts checkpoints else check datetime field TS FIELD NAME measure... | def _ensure_timestamp_field dataset_expr deltas checkpoints measure dataset_expr dshape measureif TS_FIELD_NAME not in measure names dataset_expr bz transform dataset_expr **{TS_FIELD_NAME dataset_expr[AD_FIELD_NAME]} deltas _ad_as_ts deltas checkpoints _ad_as_ts checkpoints else _check_datetime_field TS_FIELD_NAME mea... | 56 |
python-test-5036 | python | How does the code obtain a password ? | by prompting or from stdin | def get Password prompt ' Password ' confirm 0 force TTY 0 confirm Prompt ' Confirmpassword ' mismatch Message " Passwordsdon'tmatch " isa TTY hasattr sys stdin 'isatty' and sys stdin isatty old Nonetry if not isa TTY if force TTY try old sys stdin sys stdout sys stdin sys stdout open '/dev/tty' 'r+' except raise Runti... | def getPassword prompt 'Password ' confirm 0 forceTTY 0 confirmPrompt 'Confirmpassword ' mismatchMessage "Passwordsdon'tmatch " isaTTY hasattr sys stdin 'isatty' and sys stdin isatty old Nonetry if not isaTTY if forceTTY try old sys stdin sys stdout sys stdin sys stdout open '/dev/tty' 'r+' except raise RuntimeError 'C... | 119 |
python-test-5037 | python | How did an assetfinder generate ? | via tmp_asset_finder | @contextmanagerdef temp pipeline engine calendar sids random seed symbols None equity info make simple equity info sids sids start date calendar[ 0 ] end date calendar[ -1 ] symbols symbols loader make seeded random loader random seed calendar sids def get loader column return loaderwith tmp asset finder equities equit... | @contextmanagerdef temp_pipeline_engine calendar sids random_seed symbols None equity_info make_simple_equity_info sids sids start_date calendar[0] end_date calendar[ -1 ] symbols symbols loader make_seeded_random_loader random_seed calendar sids def get_loader column return loaderwith tmp_asset_finder equities equity_... | 61 |
python-test-5038 | python | What does a contextmanager yield ? | a simplepipelineengine holding a reference to an assetfinder generated via tmp_asset_finder | @contextmanagerdef temp pipeline engine calendar sids random seed symbols None equity info make simple equity info sids sids start date calendar[ 0 ] end date calendar[ -1 ] symbols symbols loader make seeded random loader random seed calendar sids def get loader column return loaderwith tmp asset finder equities equit... | @contextmanagerdef temp_pipeline_engine calendar sids random_seed symbols None equity_info make_simple_equity_info sids sids start_date calendar[0] end_date calendar[ -1 ] symbols symbols loader make_seeded_random_loader random_seed calendar sids def get_loader column return loaderwith tmp_asset_finder equities equity_... | 61 |
python-test-5039 | python | How do webhook consumer search project repository urls gitlab ? | using the site url from gitlab webhook payload | @csrf exemptdef gitlab build request if request method 'POST' try data json loads request body url data['project']['http url']search url re sub '^https? // *? ? \\ git $' '\\ 1 ' url branches [data['ref'] replace 'refs/heads/' '' ]except Value Error Type Error Key Error log error ' Invalid Git Labwebhookpayload' exc in... | @csrf_exemptdef gitlab_build request if request method 'POST' try data json loads request body url data['project']['http_url']search_url re sub '^https? // *? ? \\ git $' '\\1' url branches [data['ref'] replace 'refs/heads/' '' ]except ValueError TypeError KeyError log error 'InvalidGitLabwebhookpayload' exc_info True ... | 113 |
python-test-5042 | python | What do a given passphrase match ? | its hashed version | def passwd check hashed passphrase passphrase try algorithm salt pw digest hashed passphrase split ' ' 2 except Value Error Type Error return Falsetry h hashlib new algorithm except Value Error return Falseif len pw digest 0 return Falseh update cast bytes passphrase 'utf- 8 ' + cast bytes salt 'ascii' return h hexdige... | def passwd_check hashed_passphrase passphrase try algorithm salt pw_digest hashed_passphrase split ' ' 2 except ValueError TypeError return Falsetry h hashlib new algorithm except ValueError return Falseif len pw_digest 0 return Falseh update cast_bytes passphrase 'utf-8' + cast_bytes salt 'ascii' return h hexdigest pw... | 56 |
python-test-5043 | python | What matches its hashed version ? | a given passphrase | def passwd check hashed passphrase passphrase try algorithm salt pw digest hashed passphrase split ' ' 2 except Value Error Type Error return Falsetry h hashlib new algorithm except Value Error return Falseif len pw digest 0 return Falseh update cast bytes passphrase 'utf- 8 ' + cast bytes salt 'ascii' return h hexdige... | def passwd_check hashed_passphrase passphrase try algorithm salt pw_digest hashed_passphrase split ' ' 2 except ValueError TypeError return Falsetry h hashlib new algorithm except ValueError return Falseif len pw_digest 0 return Falseh update cast_bytes passphrase 'utf-8' + cast_bytes salt 'ascii' return h hexdigest pw... | 56 |
python-test-5049 | python | What did the code set ? | global proxy facts | def set proxy facts facts if 'common' in facts common facts['common']if 'http proxy' in common or 'https proxy' in common if 'no proxy' in common and isinstance common['no proxy'] string types common['no proxy'] common['no proxy'] split ' ' elif 'no proxy' not in common common['no proxy'] []if 'generate no proxy hosts'... | def set_proxy_facts facts if 'common' in facts common facts['common']if 'http_proxy' in common or 'https_proxy' in common if 'no_proxy' in common and isinstance common['no_proxy'] string_types common['no_proxy'] common['no_proxy'] split ' ' elif 'no_proxy' not in common common['no_proxy'] []if 'generate_no_proxy_hosts'... | 99 |
python-test-5054 | python | What does the code make ? | a bed file with track and browser lines ready for liftover | def safe bed file infile fix pat re compile '^ track browser ' fd fname tempfile mkstemp in handle open infile out handle open fname 'w' for line in in handle if fix pat match line line '#' + line out handle write line in handle close out handle close return fname | def safe_bed_file infile fix_pat re compile '^ track browser ' fd fname tempfile mkstemp in_handle open infile out_handle open fname 'w' for line in in_handle if fix_pat match line line '#' + line out_handle write line in_handle close out_handle close return fname | 52 |
python-test-5062 | python | What should support the with statement automatically ? | classes implementing idisposable | def test disposable x Disposable Test with x pass Are Equal x Called True Assert hasattr x ' enter ' Assert hasattr x ' exit ' x Disposable Test x enter try passfinally Are Equal x exit None None None None Are Equal x Called True Assert ' enter ' in dir x Assert ' exit ' in dir x Assert ' enter ' in dir Disposable Test... | def test_disposable x DisposableTest with x passAreEqual x Called True Assert hasattr x '__enter__' Assert hasattr x '__exit__' x DisposableTest x __enter__ try passfinally AreEqual x __exit__ None None None None AreEqual x Called True Assert '__enter__' in dir x Assert '__exit__' in dir x Assert '__enter__' in dir Dis... | 76 |
python-test-5063 | python | What should classes implementing idisposable support automatically ? | the with statement | def test disposable x Disposable Test with x pass Are Equal x Called True Assert hasattr x ' enter ' Assert hasattr x ' exit ' x Disposable Test x enter try passfinally Are Equal x exit None None None None Are Equal x Called True Assert ' enter ' in dir x Assert ' exit ' in dir x Assert ' enter ' in dir Disposable Test... | def test_disposable x DisposableTest with x passAreEqual x Called True Assert hasattr x '__enter__' Assert hasattr x '__exit__' x DisposableTest x __enter__ try passfinally AreEqual x __exit__ None None None None AreEqual x Called True Assert '__enter__' in dir x Assert '__exit__' in dir x Assert '__enter__' in dir Dis... | 76 |
python-test-5065 | python | What does the code get without ambiguation ? | tab title | def get file title files path list filename fname os path basename filename same name files get same name files files path list fname if len same name files > 1 compare path shortest path same name files if compare path filename same name files remove path components filename compare path shortest path same name files ... | def get_file_title files_path_list filename fname os path basename filename same_name_files get_same_name_files files_path_list fname if len same_name_files > 1 compare_path shortest_path same_name_files if compare_path filename same_name_files remove path_components filename compare_path shortest_path same_name_files ... | 142 |
python-test-5066 | python | How does the code get tab title ? | without ambiguation | def get file title files path list filename fname os path basename filename same name files get same name files files path list fname if len same name files > 1 compare path shortest path same name files if compare path filename same name files remove path components filename compare path shortest path same name files ... | def get_file_title files_path_list filename fname os path basename filename same_name_files get_same_name_files files_path_list fname if len same_name_files > 1 compare_path shortest_path same_name_files if compare_path filename same_name_files remove path_components filename compare_path shortest_path same_name_files ... | 142 |
python-test-5068 | python | What does decorator translate into nosuchprocess ? | bare oserror and ioerror exceptions | def wrap exceptions fun @functools wraps fun def wrapper self *args **kwargs try return fun self *args **kwargs except Environment Error as err if err errno in errno ENOENT errno ESRCH raise No Such Process self pid self name if err errno in errno EPERM errno EACCES raise Access Denied self pid self name raisereturn wr... | def wrap_exceptions fun @functools wraps fun def wrapper self *args **kwargs try return fun self *args **kwargs except EnvironmentError as err if err errno in errno ENOENT errno ESRCH raise NoSuchProcess self pid self _name if err errno in errno EPERM errno EACCES raise AccessDenied self pid self _name raisereturn wrap... | 56 |
python-test-5081 | python | What does the code get ? | the field name usable without quotes | def get model field name field field slugify field field field replace '-' ' ' field field replace ' ' ' ' if field in 'id' field + ' 'if field upper in PG RESERVED KEYWORDS field + ' 'if field[ -1 ] ' ' field + 'field'try int field float field field ' %s' % field except Value Error passreturn field | def get_model_field_name field field slugify field field field replace '-' '_' field field replace ' ' '_' if field in 'id' field + '_'if field upper in PG_RESERVED_KEYWORDS field + '_'if field[ -1 ] '_' field + 'field'try int field float field field '_%s' % field except ValueError passreturn field | 62 |
python-test-5082 | python | What does the code evaluate ? | a string - node | def evaluate for annotation evaluator annotation index None if annotation is not None definitions evaluator eval element fix forward reference evaluator annotation if index is not None definitions list itertools chain from iterable definition py getitem index for definition in definitions if definition type 'tuple' and... | def _evaluate_for_annotation evaluator annotation index None if annotation is not None definitions evaluator eval_element _fix_forward_reference evaluator annotation if index is not None definitions list itertools chain from_iterable definition py__getitem__ index for definition in definitions if definition type 'tuple... | 69 |
python-test-5085 | python | What do a helper function convert into the proper elements ? | text streams | def append Text Elements e contents List se def uconcat text new Text se if type new Text type text if type text is str text text decode se else new Text new Text decode se return text + new Text e text ''last Element Nonefor content in contents List if not isinstance content Text new Element content to Element se if n... | def appendTextElements e contentsList se def uconcat text newText se if type newText type text if type text is str text text decode se else newText newText decode se return text + newText e text ''lastElement Nonefor content in contentsList if not isinstance content Text newElement content toElement se if newElement is... | 100 |
python-test-5087 | python | What does the code classify into 2 classes using single layer of gru units and softmax applied to the last activations of the units ? | temporal sequences of float numbers of length 3 | @keras testdef test temporal classification X train y train X test y test get test data nb train 500 nb test 500 input shape 3 5 classification True nb class 2 y train to categorical y train y test to categorical y test model Sequential model add GRU y train shape[ -1 ] input shape X train shape[ 1 ] X train shape[ 2 ]... | @keras_testdef test_temporal_classification X_train y_train X_test y_test get_test_data nb_train 500 nb_test 500 input_shape 3 5 classification True nb_class 2 y_train to_categorical y_train y_test to_categorical y_test model Sequential model add GRU y_train shape[ -1 ] input_shape X_train shape[1] X_train shape[2] act... | 106 |
python-test-5088 | python | How does the code classify temporal sequences of float numbers of length 3 into 2 classes ? | using single layer of gru units and softmax applied to the last activations of the units | @keras testdef test temporal classification X train y train X test y test get test data nb train 500 nb test 500 input shape 3 5 classification True nb class 2 y train to categorical y train y test to categorical y test model Sequential model add GRU y train shape[ -1 ] input shape X train shape[ 1 ] X train shape[ 2 ]... | @keras_testdef test_temporal_classification X_train y_train X_test y_test get_test_data nb_train 500 nb_test 500 input_shape 3 5 classification True nb_class 2 y_train to_categorical y_train y_test to_categorical y_test model Sequential model add GRU y_train shape[ -1 ] input_shape X_train shape[1] X_train shape[2] act... | 106 |
python-test-5089 | python | What does the code dump into a yaml representation ? | the given aff4object | def Yaml Dumper aff 4 object aff 4 object Flush result {}for attribute values in aff 4 object synced attributes items result[attribute predicate] []for value in values value value To RDF Value result[attribute predicate] append [value class name value Serialize To String str value age ] return yaml dump dict aff 4 clas... | def YamlDumper aff4object aff4object Flush result {}for attribute values in aff4object synced_attributes items result[attribute predicate] []for value in values value value ToRDFValue result[attribute predicate] append [value __class__ __name__ value SerializeToString str value age ] return yaml dump dict aff4_class af... | 75 |
python-test-5096 | python | What do a list contain ? | cartesian product of data types | def get thunk type set it types []i types []j 0getter code 'if 0 {}'for I typenum I type in I TYPES piece '\nelseif I typenum % I typenum s {\nif T typenum -1 {return% j s }'getter code + piece % dict I typenum I typenum j j i types append j I typenum None I type None j + 1for T typenum T type in T TYPES piece '\nelsei... | def get_thunk_type_set it_types []i_types []j 0getter_code 'if 0 {}'for I_typenum I_type in I_TYPES piece '\nelseif I_typenum % I_typenum s {\nif T_typenum -1 {return% j s }'getter_code + piece % dict I_typenum I_typenum j j i_types append j I_typenum None I_type None j + 1for T_typenum T_type in T_TYPES piece '\nelsei... | 123 |
python-test-5097 | python | What does the code get ? | a list containing cartesian product of data types | def get thunk type set it types []i types []j 0getter code 'if 0 {}'for I typenum I type in I TYPES piece '\nelseif I typenum % I typenum s {\nif T typenum -1 {return% j s }'getter code + piece % dict I typenum I typenum j j i types append j I typenum None I type None j + 1for T typenum T type in T TYPES piece '\nelsei... | def get_thunk_type_set it_types []i_types []j 0getter_code 'if 0 {}'for I_typenum I_type in I_TYPES piece '\nelseif I_typenum % I_typenum s {\nif T_typenum -1 {return% j s }'getter_code + piece % dict I_typenum I_typenum j j i_types append j I_typenum None I_type None j + 1for T_typenum T_type in T_TYPES piece '\nelsei... | 123 |
python-test-5098 | python | What does the code given two axes return ? | a guess of the plateau point | def guess plateau x y if len x len y return 0diffs []indexes range len y for i in indexes if i + 1 not in indexes continuediffs append y[ i + 1 ] - y[i] diffs np array diffs ymax y[ -1 ]for i in indexes if y[i] > ymax - diffs std and y[i] < ymax + diffs std ymax y[i]breakreturn ymax | def guess_plateau x y if len x len y return 0diffs []indexes range len y for i in indexes if i + 1 not in indexes continuediffs append y[ i + 1 ] - y[i] diffs np array diffs ymax y[ -1 ]for i in indexes if y[i] > ymax - diffs std and y[i] < ymax + diffs std ymax y[i]breakreturn ymax | 64 |
python-test-5101 | python | What does the code parse ? | the output spec | def Parse Output Spec output spec pattern re compile ' O 0 1 2 l s c \\d+ ' m pattern match output spec if m is None raise Value Error ' Failedtoparseoutputspec ' + output spec out dims int m group 2 out func m group 3 if out func 'c' and out dims 1 raise Value Error 'CT Ccanonlybeusedwitha 1 - Dsequence ' num classes ... | def _ParseOutputSpec output_spec pattern re compile ' O 0 1 2 l s c \\d+ ' m pattern match output_spec if m is None raise ValueError 'Failedtoparseoutputspec ' + output_spec out_dims int m group 2 out_func m group 3 if out_func 'c' and out_dims 1 raise ValueError 'CTCcanonlybeusedwitha1-Dsequence ' num_classes int m gr... | 78 |
python-test-5104 | python | What does this calculate actually ? | the kerning + advance | def get k p a font left right chars left + right args [ None 1 cf kCF Type Dictionary Key Call Backs cf kCF Type Dictionary Value Call Backs]attributes cf CF Dictionary Create Mutable *args cf CF Dictionary Add Value attributes kCT Font Attribute Name font string cf CF Attributed String Create None CFSTR chars attribut... | def _get_k_p_a font left right chars left + right args [None 1 cf kCFTypeDictionaryKeyCallBacks cf kCFTypeDictionaryValueCallBacks]attributes cf CFDictionaryCreateMutable *args cf CFDictionaryAddValue attributes kCTFontAttributeName font string cf CFAttributedStringCreate None CFSTR chars attributes typesetter ct CTTyp... | 109 |
python-test-5105 | python | What did the code set ? | the concord232 binary sensor platform | def setup platform hass config add devices discovery info None from concord 232 import client as concord 232 clienthost config get CONF HOST port config get CONF PORT exclude config get CONF EXCLUDE ZONES zone types config get CONF ZONE TYPES sensors []try LOGGER debug ' Initializing Client' client concord 232 client C... | def setup_platform hass config add_devices discovery_info None from concord232 import client as concord232_clienthost config get CONF_HOST port config get CONF_PORT exclude config get CONF_EXCLUDE_ZONES zone_types config get CONF_ZONE_TYPES sensors []try _LOGGER debug 'InitializingClient' client concord232_client Clien... | 127 |
python-test-5106 | python | What does the code compare against the given data ? | the schema | def get all key combinations data flattened schema schema prefixes set [key[ -1 ] for key in flattened schema] combinations set [ ] for key in sorted data keys key flattened order key key prefix key[ -1 2]if key prefix not in schema prefixes continueif tuple tuple key[ -3 ] not in combinations continuecombinations add ... | def get_all_key_combinations data flattened_schema schema_prefixes set [key[ -1 ] for key in flattened_schema] combinations set [ ] for key in sorted data keys key flattened_order_key key_prefix key[ -1 2]if key_prefix not in schema_prefixes continueif tuple tuple key[ -3 ] not in combinations continuecombinations add ... | 61 |
python-test-5107 | python | What does the code get ? | all valid tuples that match the schema ignoring the last value in the tuple | def get all key combinations data flattened schema schema prefixes set [key[ -1 ] for key in flattened schema] combinations set [ ] for key in sorted data keys key flattened order key key prefix key[ -1 2]if key prefix not in schema prefixes continueif tuple tuple key[ -3 ] not in combinations continuecombinations add ... | def get_all_key_combinations data flattened_schema schema_prefixes set [key[ -1 ] for key in flattened_schema] combinations set [ ] for key in sorted data keys key flattened_order_key key_prefix key[ -1 2]if key_prefix not in schema_prefixes continueif tuple tuple key[ -3 ] not in combinations continuecombinations add ... | 61 |
python-test-5108 | python | What do a beautifulsoup < td > tag represent ? | a book | def book info td title td find 'div' 'thumbheader' a textby author td find 'div' ' Author Name' textauthors [x strip for x in re sub '^ By' '' by author split ' ' ]isbn link td find 'div' 'thumbheader' a get 'href' isbn re match '/product/ * \\ do' isbn link groups [0 ]date td find 'span' 'directorydate' text strip ret... | def book_info td title td find 'div' 'thumbheader' a textby_author td find 'div' 'AuthorName' textauthors [x strip for x in re sub '^By' '' by_author split ' ' ]isbn_link td find 'div' 'thumbheader' a get 'href' isbn re match '/product/ * \\ do' isbn_link groups [0]date td find 'span' 'directorydate' text strip return ... | 70 |
python-test-5109 | python | What is representing a book ? | a beautifulsoup < td > tag | def book info td title td find 'div' 'thumbheader' a textby author td find 'div' ' Author Name' textauthors [x strip for x in re sub '^ By' '' by author split ' ' ]isbn link td find 'div' 'thumbheader' a get 'href' isbn re match '/product/ * \\ do' isbn link groups [0 ]date td find 'span' 'directorydate' text strip ret... | def book_info td title td find 'div' 'thumbheader' a textby_author td find 'div' 'AuthorName' textauthors [x strip for x in re sub '^By' '' by_author split ' ' ]isbn_link td find 'div' 'thumbheader' a get 'href' isbn re match '/product/ * \\ do' isbn_link groups [0]date td find 'span' 'directorydate' text strip return ... | 70 |
python-test-5110 | python | When does this handler look at s3 requests ? | just before they are signed | def fix s3 host request signature version region name default endpoint url 's 3 amazonaws com' **kwargs if signature version is not botocore UNSIGNED and 's 3 v 4 ' in signature version returnelif not allowed region region name returntry switch to virtual host style request signature version default endpoint url except... | def fix_s3_host request signature_version region_name default_endpoint_url 's3 amazonaws com' **kwargs if signature_version is not botocore UNSIGNED and 's3v4' in signature_version returnelif not _allowed_region region_name returntry switch_to_virtual_host_style request signature_version default_endpoint_url except Inv... | 73 |
python-test-5111 | python | What do project have ? | a build_queue | def trigger build project version None record True force False basic False from readthedocs projects tasks import update docsfrom readthedocs builds models import Buildif project skip return Noneif not version version project versions get slug LATEST kwargs dict pk project pk version pk version pk record record force f... | def trigger_build project version None record True force False basic False from readthedocs projects tasks import update_docsfrom readthedocs builds models import Buildif project skip return Noneif not version version project versions get slug LATEST kwargs dict pk project pk version_pk version pk record record force f... | 119 |
python-test-5112 | python | For what purpose has build trigger ? | for project and version | def trigger build project version None record True force False basic False from readthedocs projects tasks import update docsfrom readthedocs builds models import Buildif project skip return Noneif not version version project versions get slug LATEST kwargs dict pk project pk version pk version pk record record force f... | def trigger_build project version None record True force False basic False from readthedocs projects tasks import update_docsfrom readthedocs builds models import Buildif project skip return Noneif not version version project versions get slug LATEST kwargs dict pk project pk version_pk version pk record record force f... | 119 |
python-test-5113 | python | What has a build_queue ? | project | def trigger build project version None record True force False basic False from readthedocs projects tasks import update docsfrom readthedocs builds models import Buildif project skip return Noneif not version version project versions get slug LATEST kwargs dict pk project pk version pk version pk record record force f... | def trigger_build project version None record True force False basic False from readthedocs projects tasks import update_docsfrom readthedocs builds models import Buildif project skip return Noneif not version version project versions get slug LATEST kwargs dict pk project pk version_pk version pk record record force f... | 119 |
python-test-5114 | python | For what purpose did the code set ? | for computing the solution at a set of eeg electrodes | def bem specify els bem els mults sol np zeros len els bem['solution'] shape[ 1 ] scalp bem['surfs'][ 0 ]rrs np concatenate [apply trans bem['head mri t']['trans'] el['rmag'] for el in els] axis 0 ws np concatenate [el['w'] for el in els] tri weights tri idx project onto surface rrs scalp tri weights * wsweights np ein... | def _bem_specify_els bem els mults sol np zeros len els bem['solution'] shape[1] scalp bem['surfs'][0]rrs np concatenate [apply_trans bem['head_mri_t']['trans'] el['rmag'] for el in els] axis 0 ws np concatenate [el['w'] for el in els] tri_weights tri_idx _project_onto_surface rrs scalp tri_weights * wsweights np einsu... | 100 |
python-test-5115 | python | Where do the solution compute ? | at a set of eeg electrodes | def bem specify els bem els mults sol np zeros len els bem['solution'] shape[ 1 ] scalp bem['surfs'][ 0 ]rrs np concatenate [apply trans bem['head mri t']['trans'] el['rmag'] for el in els] axis 0 ws np concatenate [el['w'] for el in els] tri weights tri idx project onto surface rrs scalp tri weights * wsweights np ein... | def _bem_specify_els bem els mults sol np zeros len els bem['solution'] shape[1] scalp bem['surfs'][0]rrs np concatenate [apply_trans bem['head_mri_t']['trans'] el['rmag'] for el in els] axis 0 ws np concatenate [el['w'] for el in els] tri_weights tri_idx _project_onto_surface rrs scalp tri_weights * wsweights np einsu... | 100 |
python-test-5120 | python | What does the code translate ? | the current url for the given language code | @register simple tag takes context True def translate url context language try request context[u'request']except Key Error return u''view resolve request path current language translation get language translation activate language try url reverse view func args view args kwargs view kwargs except No Reverse Match try u... | @register simple_tag takes_context True def translate_url context language try request context[u'request']except KeyError return u''view resolve request path current_language translation get_language translation activate language try url reverse view func args view args kwargs view kwargs except NoReverseMatch try url_... | 112 |
python-test-5123 | python | Did the user write permissions on the given note ? | No | def user has perm note note profile request None if note author and note author id profile id return Trueif request and note note type comm REVIEWER COMMENT return acl check reviewer request if request and note note type comm DEVELOPER COMMENT and acl check reviewer request return Trueuser is author profile addons filt... | def user_has_perm_note note profile request None if note author and note author id profile id return Trueif request and note note_type comm REVIEWER_COMMENT return acl check_reviewer request if request and note note_type comm DEVELOPER_COMMENT and acl check_reviewer request return Trueuser_is_author profile addons filt... | 85 |
python-test-5127 | python | What do internal utility raise ? | the appropriate exception class | def check rc rc errno None if rc -1 if errno is None from zmq backend import zmq errnoerrno zmq errno from zmq import EAGAIN ETER Mif errno EINTR raise Interrupted System Call errno elif errno EAGAIN raise Again errno elif errno ETERM raise Context Terminated errno else raise ZMQ Error errno | def _check_rc rc errno None if rc -1 if errno is None from zmq backend import zmq_errnoerrno zmq_errno from zmq import EAGAIN ETERMif errno EINTR raise InterruptedSystemCall errno elif errno EAGAIN raise Again errno elif errno ETERM raise ContextTerminated errno else raise ZMQError errno | 52 |
python-test-5128 | python | What is raising the appropriate exception class ? | internal utility | def check rc rc errno None if rc -1 if errno is None from zmq backend import zmq errnoerrno zmq errno from zmq import EAGAIN ETER Mif errno EINTR raise Interrupted System Call errno elif errno EAGAIN raise Again errno elif errno ETERM raise Context Terminated errno else raise ZMQ Error errno | def _check_rc rc errno None if rc -1 if errno is None from zmq backend import zmq_errnoerrno zmq_errno from zmq import EAGAIN ETERMif errno EINTR raise InterruptedSystemCall errno elif errno EAGAIN raise Again errno elif errno ETERM raise ContextTerminated errno else raise ZMQError errno | 52 |
python-test-5130 | python | What does the code take ? | a successful object - get http response | def http response to document iters response read chunk size 4096 chunked is chunked dict response getheaders if response status 200 if chunked return iter [ 0 None None response getheaders response ] content length int response getheader ' Content- Length' return iter [ 0 content length - 1 content length response get... | def http_response_to_document_iters response read_chunk_size 4096 chunked is_chunked dict response getheaders if response status 200 if chunked return iter [ 0 None None response getheaders response ] content_length int response getheader 'Content-Length' return iter [ 0 content_length - 1 content_length response gethe... | 108 |
python-test-5132 | python | What does the code setup ? | the knx sensor platform | def setup platform hass config add entities discovery info None if config[CONF TYPE] TEMPERATURE minimum value maximum value update and define min max config KNX TEMP MIN KNX TEMP MAX add entities [KNX Sensor Float Class hass KNX Config config TEMP CELSIUS minimum value maximum value ] elif config[CONF TYPE] SPEED MS m... | def setup_platform hass config add_entities discovery_info None if config[CONF_TYPE] TEMPERATURE minimum_value maximum_value update_and_define_min_max config KNX_TEMP_MIN KNX_TEMP_MAX add_entities [KNXSensorFloatClass hass KNXConfig config TEMP_CELSIUS minimum_value maximum_value ] elif config[CONF_TYPE] SPEED_MS minim... | 124 |
python-test-5139 | python | How does the code create a github release ? | using the github - release command - line tool | @release command def ghrelease version get version 1 tag 'v' + version with open os path join BASE 'changelog md' as f cl md f read subprocess check call ['github-release' 'release' '-u' GITHUB USER '-r' GITHUB REPO '--tag' tag '--name' '{}{}' format GITHUB REPO version '--description' cl md] tarball os path join BASE ... | @release command def ghrelease version get_version 1 tag 'v' + version with open os path join BASE 'changelog md' as f cl_md f read subprocess check_call ['github-release' 'release' '-u' GITHUB_USER '-r' GITHUB_REPO '--tag' tag '--name' '{}{}' format GITHUB_REPO version '--description' cl_md] tarball os path join BASE ... | 79 |
python-test-5140 | python | What do a github release use ? | the github - release command - line tool | @release command def ghrelease version get version 1 tag 'v' + version with open os path join BASE 'changelog md' as f cl md f read subprocess check call ['github-release' 'release' '-u' GITHUB USER '-r' GITHUB REPO '--tag' tag '--name' '{}{}' format GITHUB REPO version '--description' cl md] tarball os path join BASE ... | @release command def ghrelease version get_version 1 tag 'v' + version with open os path join BASE 'changelog md' as f cl_md f read subprocess check_call ['github-release' 'release' '-u' GITHUB_USER '-r' GITHUB_REPO '--tag' tag '--name' '{}{}' format GITHUB_REPO version '--description' cl_md] tarball os path join BASE ... | 79 |
python-test-5143 | python | When does the code calculate the mean of the quadratic weighted kappas ? | after applying fishers r - to - z transform | def mean quadratic weighted kappa kappas weights None kappas np array kappas dtype float if weights is None weights np ones np shape kappas else weights weights / np mean weights kappas np array [min x 0 999 for x in kappas] kappas np array [max x -0 999 for x in kappas] z 0 5 * np log 1 + kappas / 1 - kappas * weights... | def mean_quadratic_weighted_kappa kappas weights None kappas np array kappas dtype float if weights is None weights np ones np shape kappas else weights weights / np mean weights kappas np array [min x 0 999 for x in kappas] kappas np array [max x -0 999 for x in kappas] z 0 5 * np log 1 + kappas / 1 - kappas * weights... | 88 |
python-test-5144 | python | What does the code calculate after applying fishers r - to - z transform ? | the mean of the quadratic weighted kappas | def mean quadratic weighted kappa kappas weights None kappas np array kappas dtype float if weights is None weights np ones np shape kappas else weights weights / np mean weights kappas np array [min x 0 999 for x in kappas] kappas np array [max x -0 999 for x in kappas] z 0 5 * np log 1 + kappas / 1 - kappas * weights... | def mean_quadratic_weighted_kappa kappas weights None kappas np array kappas dtype float if weights is None weights np ones np shape kappas else weights weights / np mean weights kappas np array [min x 0 999 for x in kappas] kappas np array [max x -0 999 for x in kappas] z 0 5 * np log 1 + kappas / 1 - kappas * weights... | 88 |
python-test-5145 | python | How do fishers r - to - z apply ? | transform | def mean quadratic weighted kappa kappas weights None kappas np array kappas dtype float if weights is None weights np ones np shape kappas else weights weights / np mean weights kappas np array [min x 0 999 for x in kappas] kappas np array [max x -0 999 for x in kappas] z 0 5 * np log 1 + kappas / 1 - kappas * weights... | def mean_quadratic_weighted_kappa kappas weights None kappas np array kappas dtype float if weights is None weights np ones np shape kappas else weights weights / np mean weights kappas np array [min x 0 999 for x in kappas] kappas np array [max x -0 999 for x in kappas] z 0 5 * np log 1 + kappas / 1 - kappas * weights... | 88 |
python-test-5147 | python | What does the code prepare ? | a token revocation request | def prepare token revocation request url token token type hint u'access token' callback None body u'' **kwargs if not is secure transport url raise Insecure Transport Error params [ u'token' token ]if token type hint params append u'token type hint' token type hint for k in kwargs if kwargs[k] params append unicode typ... | def prepare_token_revocation_request url token token_type_hint u'access_token' callback None body u'' **kwargs if not is_secure_transport url raise InsecureTransportError params [ u'token' token ]if token_type_hint params append u'token_type_hint' token_type_hint for k in kwargs if kwargs[k] params append unicode_type ... | 84 |
python-test-5150 | python | What helps you write l{deferred}-using code that looks like a regular sequential function ? | inlinecallbacks | def inline Callbacks f @wraps f def unwind Generator *args **kwargs try gen f *args **kwargs except Def Gen Return raise Type Error 'inline Callbacksrequires%rtoproduceagenerator insteadcaughtreturn Valuebeingusedinanon-generator' % f if not isinstance gen types Generator Type raise Type Error 'inline Callbacksrequires... | def inlineCallbacks f @wraps f def unwindGenerator *args **kwargs try gen f *args **kwargs except _DefGen_Return raise TypeError 'inlineCallbacksrequires%rtoproduceagenerator insteadcaughtreturnValuebeingusedinanon-generator' % f if not isinstance gen types GeneratorType raise TypeError 'inlineCallbacksrequires%rtoprod... | 54 |
python-test-5153 | python | What does the code generate ? | the common url patterns for the given names | def generate patterns django name gwt name pattern list defaults patterns django name '^rpc/' 'views handle rpc' '^rpc doc' 'views rpc documentation' debug pattern list defaults patterns '' '^ ?P<forward addr>autotest * ' 'autotest frontend afe views gwt forward' '^client/ ?P<path> * $' 'django views static serve' {'do... | def generate_patterns django_name gwt_name pattern_list defaults patterns django_name '^rpc/' 'views handle_rpc' '^rpc_doc' 'views rpc_documentation' debug_pattern_list defaults patterns '' '^ ?P<forward_addr>autotest * ' 'autotest frontend afe views gwt_forward' '^client/ ?P<path> * $' 'django views static serve' {'do... | 89 |
python-test-5157 | python | Where does a gcsfilestat iterator return ? | over a bucket | def listbucket path prefix marker None prefix None max keys None delimiter None retry params None account id None if prefix common validate bucket path path prefix bucket path prefixelse bucket prefix common process path prefix path prefix if marker and marker startswith bucket marker marker[ len bucket + 1 ]api storag... | def listbucket path_prefix marker None prefix None max_keys None delimiter None retry_params None _account_id None if prefix common validate_bucket_path path_prefix bucket path_prefixelse bucket prefix common _process_path_prefix path_prefix if marker and marker startswith bucket marker marker[ len bucket + 1 ]api stor... | 84 |
python-test-5158 | python | What returns over a bucket ? | a gcsfilestat iterator | def listbucket path prefix marker None prefix None max keys None delimiter None retry params None account id None if prefix common validate bucket path path prefix bucket path prefixelse bucket prefix common process path prefix path prefix if marker and marker startswith bucket marker marker[ len bucket + 1 ]api storag... | def listbucket path_prefix marker None prefix None max_keys None delimiter None retry_params None _account_id None if prefix common validate_bucket_path path_prefix bucket path_prefixelse bucket prefix common _process_path_prefix path_prefix if marker and marker startswith bucket marker marker[ len bucket + 1 ]api stor... | 84 |
python-test-5166 | python | How do an ssh key upload to an esxi host ? | via http put | def upload ssh key host username password ssh key None ssh key file None protocol None port None certificate verify False if protocol is None protocol 'https'if port is None port 443 url '{ 0 } //{ 1 } {2 }/host/ssh root authorized keys' format protocol host port ret {}result Nonetry if ssh key result salt utils http q... | def upload_ssh_key host username password ssh_key None ssh_key_file None protocol None port None certificate_verify False if protocol is None protocol 'https'if port is None port 443url '{0} //{1} {2}/host/ssh_root_authorized_keys' format protocol host port ret {}result Nonetry if ssh_key result salt utils http query u... | 128 |
python-test-5168 | python | What cli example ? | software | def updating name jail None chroot None root None filedate None filename None opts ''if filedate opts + 'd{ 0 }' format filedate if filename opts + 'f{ 0 }' format filename cmd pkg jail chroot root cmd append 'updating' if opts cmd append '-' + opts cmd append name return salt ['cmd run'] cmd output loglevel 'trace' py... | def updating name jail None chroot None root None filedate None filename None opts ''if filedate opts + 'd{0}' format filedate if filename opts + 'f{0}' format filename cmd _pkg jail chroot root cmd append 'updating' if opts cmd append '-' + opts cmd append name return __salt__['cmd run'] cmd output_loglevel 'trace' py... | 61 |
python-test-5171 | python | Where does the code create a volumes filesystem ? | on one pool | def create and copy test fixture pool fixture test service service for pool test pool volume service get MY VOLUME pool 2 fixture test service 2 service for pool test pool 2 volume 2 Volume node id service node id name MY VOLUME service service 2 d pool create volume def created filesystem filesystem path filesystem ge... | def create_and_copy test fixture pool fixture test service service_for_pool test pool volume service get MY_VOLUME pool2 fixture test service2 service_for_pool test pool2 volume2 Volume node_id service node_id name MY_VOLUME service service2 d pool create volume def created_filesystem filesystem path filesystem get_pat... | 95 |
python-test-5172 | python | What does the code create on one pool ? | a volumes filesystem | def create and copy test fixture pool fixture test service service for pool test pool volume service get MY VOLUME pool 2 fixture test service 2 service for pool test pool 2 volume 2 Volume node id service node id name MY VOLUME service service 2 d pool create volume def created filesystem filesystem path filesystem ge... | def create_and_copy test fixture pool fixture test service service_for_pool test pool volume service get MY_VOLUME pool2 fixture test service2 service_for_pool test pool2 volume2 Volume node_id service node_id name MY_VOLUME service service2 d pool create volume def created_filesystem filesystem path filesystem get_pat... | 95 |
python-test-5173 | python | What does it serialize ? | discussion entity | def serialize discussion entities request context discussion entities requested fields discussion entity type results []usernames []include profile image include profile image requested fields for entity in discussion entities if discussion entity type Discussion Entity thread serialized entity Thread Serializer entity... | def _serialize_discussion_entities request context discussion_entities requested_fields discussion_entity_type results []usernames []include_profile_image _include_profile_image requested_fields for entity in discussion_entities if discussion_entity_type DiscussionEntity thread serialized_entity ThreadSerializer entity... | 123 |
python-test-5174 | python | What does unzips an archive into a temporary directory return ? | a link to that directory arguments : archive -- the path to an archive file | def unzip archive archive assert os path exists archive ' Filenotfound-%s' % archive tmpdir os path join tempfile gettempdir os path basename archive assert tmpdir archive if os path exists tmpdir passelif tarfile is tarfile archive print ' Extractingtarfile 'with tarfile open archive as tf tf extractall path tmpdir el... | def unzip_archive archive assert os path exists archive 'Filenotfound-%s' % archive tmpdir os path join tempfile gettempdir os path basename archive assert tmpdir archive if os path exists tmpdir passelif tarfile is_tarfile archive print 'Extractingtarfile 'with tarfile open archive as tf tf extractall path tmpdir elif... | 81 |
python-test-5175 | python | What returns a link to that directory arguments : archive -- the path to an archive file ? | unzips an archive into a temporary directory | def unzip archive archive assert os path exists archive ' Filenotfound-%s' % archive tmpdir os path join tempfile gettempdir os path basename archive assert tmpdir archive if os path exists tmpdir passelif tarfile is tarfile archive print ' Extractingtarfile 'with tarfile open archive as tf tf extractall path tmpdir el... | def unzip_archive archive assert os path exists archive 'Filenotfound-%s' % archive tmpdir os path join tempfile gettempdir os path basename archive assert tmpdir archive if os path exists tmpdir passelif tarfile is_tarfile archive print 'Extractingtarfile 'with tarfile open archive as tf tf extractall path tmpdir elif... | 81 |
python-test-5182 | python | What does the code create ? | a policy decision point descriptor | def do pdp descriptor conf cert pdp md PDP Descriptor pdp protocol support enumeration samlp NAMESPAC Eendps conf getattr 'endpoints' 'pdp' if endps for endpoint instlist in do endpoints endps ENDPOINTS['pdp'] items setattr pdp endpoint instlist do nameid format pdp conf 'pdp' if cert pdp key descriptor do key descript... | def do_pdp_descriptor conf cert pdp md PDPDescriptor pdp protocol_support_enumeration samlp NAMESPACEendps conf getattr 'endpoints' 'pdp' if endps for endpoint instlist in do_endpoints endps ENDPOINTS['pdp'] items setattr pdp endpoint instlist _do_nameid_format pdp conf 'pdp' if cert pdp key_descriptor do_key_descripto... | 53 |
python-test-5184 | python | What triggered the build ? | the pull request | def github pull request merge registry xml parent data osb XML Sub Element xml parent 'org jenkinsci plugins ghprb Ghprb Pull Request Merge' mapping [ 'only-admins-merge' 'only Admins Merge' 'false' 'disallow-own-code' 'disallow Own Code' 'false' 'merge-comment' 'merge Comment' '' 'fail-on-non-merge' 'fail On Non Merge... | def github_pull_request_merge registry xml_parent data osb XML SubElement xml_parent 'org jenkinsci plugins ghprb GhprbPullRequestMerge' mapping [ 'only-admins-merge' 'onlyAdminsMerge' 'false' 'disallow-own-code' 'disallowOwnCode' 'false' 'merge-comment' 'mergeComment' '' 'fail-on-non-merge' 'failOnNonMerge' 'false' 'd... | 61 |
python-test-5185 | python | What merges the pull request that triggered the build github - pull - request - merge ? | this action | def github pull request merge registry xml parent data osb XML Sub Element xml parent 'org jenkinsci plugins ghprb Ghprb Pull Request Merge' mapping [ 'only-admins-merge' 'only Admins Merge' 'false' 'disallow-own-code' 'disallow Own Code' 'false' 'merge-comment' 'merge Comment' '' 'fail-on-non-merge' 'fail On Non Merge... | def github_pull_request_merge registry xml_parent data osb XML SubElement xml_parent 'org jenkinsci plugins ghprb GhprbPullRequestMerge' mapping [ 'only-admins-merge' 'onlyAdminsMerge' 'false' 'disallow-own-code' 'disallowOwnCode' 'false' 'merge-comment' 'mergeComment' '' 'fail-on-non-merge' 'failOnNonMerge' 'false' 'd... | 61 |
python-test-5186 | python | How do this action merge ? | github - | def github pull request merge registry xml parent data osb XML Sub Element xml parent 'org jenkinsci plugins ghprb Ghprb Pull Request Merge' mapping [ 'only-admins-merge' 'only Admins Merge' 'false' 'disallow-own-code' 'disallow Own Code' 'false' 'merge-comment' 'merge Comment' '' 'fail-on-non-merge' 'fail On Non Merge... | def github_pull_request_merge registry xml_parent data osb XML SubElement xml_parent 'org jenkinsci plugins ghprb GhprbPullRequestMerge' mapping [ 'only-admins-merge' 'onlyAdminsMerge' 'false' 'disallow-own-code' 'disallowOwnCode' 'false' 'merge-comment' 'mergeComment' '' 'fail-on-non-merge' 'failOnNonMerge' 'false' 'd... | 61 |
python-test-5187 | python | What does the pull request that triggered the build require ? | the jenkins : jenkins - wiki : github | def github pull request merge registry xml parent data osb XML Sub Element xml parent 'org jenkinsci plugins ghprb Ghprb Pull Request Merge' mapping [ 'only-admins-merge' 'only Admins Merge' 'false' 'disallow-own-code' 'disallow Own Code' 'false' 'merge-comment' 'merge Comment' '' 'fail-on-non-merge' 'fail On Non Merge... | def github_pull_request_merge registry xml_parent data osb XML SubElement xml_parent 'org jenkinsci plugins ghprb GhprbPullRequestMerge' mapping [ 'only-admins-merge' 'onlyAdminsMerge' 'false' 'disallow-own-code' 'disallowOwnCode' 'false' 'merge-comment' 'mergeComment' '' 'fail-on-non-merge' 'failOnNonMerge' 'false' 'd... | 61 |
python-test-5188 | python | How does this action merge the pull request that triggered the build ? | github - pull - request - merge | def github pull request merge registry xml parent data osb XML Sub Element xml parent 'org jenkinsci plugins ghprb Ghprb Pull Request Merge' mapping [ 'only-admins-merge' 'only Admins Merge' 'false' 'disallow-own-code' 'disallow Own Code' 'false' 'merge-comment' 'merge Comment' '' 'fail-on-non-merge' 'fail On Non Merge... | def github_pull_request_merge registry xml_parent data osb XML SubElement xml_parent 'org jenkinsci plugins ghprb GhprbPullRequestMerge' mapping [ 'only-admins-merge' 'onlyAdminsMerge' 'false' 'disallow-own-code' 'disallowOwnCode' 'false' 'merge-comment' 'mergeComment' '' 'fail-on-non-merge' 'failOnNonMerge' 'false' 'd... | 61 |
python-test-5189 | python | What does the code perform ? | total - variation denoising on n - dimensional images | def denoise tv chambolle im weight 0 1 eps 0 0002 n iter max 200 multichannel False im type im dtypeif not im type kind 'f' im img as float im if multichannel out np zeros like im for c in range im shape[ -1 ] out[ c] denoise tv chambolle nd im[ c] weight eps n iter max else out denoise tv chambolle nd im weight eps n ... | def denoise_tv_chambolle im weight 0 1 eps 0 0002 n_iter_max 200 multichannel False im_type im dtypeif not im_type kind 'f' im img_as_float im if multichannel out np zeros_like im for c in range im shape[ -1 ] out[ c] _denoise_tv_chambolle_nd im[ c] weight eps n_iter_max else out _denoise_tv_chambolle_nd im weight eps ... | 73 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.