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-6370 | python | Do print ops block gpu optimization ? | No | def test print op b tensor fmatrix f theano function [b] theano printing Print b * 2 mode mode with gpu topo f maker fgraph toposort assert isinstance topo[ 0 ] op Gpu From Host assert isinstance topo[ 1 ] op theano printing Print assert isinstance topo[ 2 ] op Gpu Elemwise assert topo[ 3 ] op host from gpu f numpy ran... | def test_print_op b tensor fmatrix f theano function [b] theano printing Print b * 2 mode mode_with_gpu topo f maker fgraph toposort assert isinstance topo[0] op GpuFromHost assert isinstance topo[1] op theano printing Print assert isinstance topo[2] op GpuElemwise assert topo[3] op host_from_gpu f numpy random random ... | 70 |
python-test-6371 | python | What do print ops nt block ? | gpu optimization | def test print op b tensor fmatrix f theano function [b] theano printing Print b * 2 mode mode with gpu topo f maker fgraph toposort assert isinstance topo[ 0 ] op Gpu From Host assert isinstance topo[ 1 ] op theano printing Print assert isinstance topo[ 2 ] op Gpu Elemwise assert topo[ 3 ] op host from gpu f numpy ran... | def test_print_op b tensor fmatrix f theano function [b] theano printing Print b * 2 mode mode_with_gpu topo f maker fgraph toposort assert isinstance topo[0] op GpuFromHost assert isinstance topo[1] op theano printing Print assert isinstance topo[2] op GpuElemwise assert topo[3] op host_from_gpu f numpy random random ... | 70 |
python-test-6372 | python | What nt blocks gpu optimization ? | print ops | def test print op b tensor fmatrix f theano function [b] theano printing Print b * 2 mode mode with gpu topo f maker fgraph toposort assert isinstance topo[ 0 ] op Gpu From Host assert isinstance topo[ 1 ] op theano printing Print assert isinstance topo[ 2 ] op Gpu Elemwise assert topo[ 3 ] op host from gpu f numpy ran... | def test_print_op b tensor fmatrix f theano function [b] theano printing Print b * 2 mode mode_with_gpu topo f maker fgraph toposort assert isinstance topo[0] op GpuFromHost assert isinstance topo[1] op theano printing Print assert isinstance topo[2] op GpuElemwise assert topo[3] op host_from_gpu f numpy random random ... | 70 |
python-test-6373 | python | How do a certain module import ? | in a clean subprocess | def loaded vispy modules import module depth None all modules False vispy dir os path dirname os path dirname vispy file code "importsys %s print ' ' join sys modules " % import module res run subprocess [sys executable '-c' code] cwd vispy dir [0 ]loaded modules [name strip for name in res split ' ' ]if all modules re... | def loaded_vispy_modules import_module depth None all_modules False vispy_dir os path dirname os path dirname vispy __file__ code "importsys %s print ' ' join sys modules " % import_module res run_subprocess [sys executable '-c' code] cwd vispy_dir [0]loaded_modules [name strip for name in res split ' ' ]if all_modules... | 100 |
python-test-6374 | python | What returns the vispy modules that are subsequently loaded ? | loaded modules | def loaded vispy modules import module depth None all modules False vispy dir os path dirname os path dirname vispy file code "importsys %s print ' ' join sys modules " % import module res run subprocess [sys executable '-c' code] cwd vispy dir [0 ]loaded modules [name strip for name in res split ' ' ]if all modules re... | def loaded_vispy_modules import_module depth None all_modules False vispy_dir os path dirname os path dirname vispy __file__ code "importsys %s print ' ' join sys modules " % import_module res run_subprocess [sys executable '-c' code] cwd vispy_dir [0]loaded_modules [name strip for name in res split ' ' ]if all_modules... | 100 |
python-test-6375 | python | What do loaded modules return ? | the vispy modules that are subsequently loaded | def loaded vispy modules import module depth None all modules False vispy dir os path dirname os path dirname vispy file code "importsys %s print ' ' join sys modules " % import module res run subprocess [sys executable '-c' code] cwd vispy dir [0 ]loaded modules [name strip for name in res split ' ' ]if all modules re... | def loaded_vispy_modules import_module depth None all_modules False vispy_dir os path dirname os path dirname vispy __file__ code "importsys %s print ' ' join sys modules " % import_module res run_subprocess [sys executable '-c' code] cwd vispy_dir [0]loaded_modules [name strip for name in res split ' ' ]if all_modules... | 100 |
python-test-6377 | python | What does the code create ? | a health monitor | def pool health monitor create request **kwargs body {'health monitor' {'type' kwargs['type'] 'delay' kwargs['delay'] 'timeout' kwargs['timeout'] 'max retries' kwargs['max retries'] 'http method' kwargs['http method'] 'url path' kwargs['url path'] 'expected codes' kwargs['expected codes'] 'admin state up' kwargs['admin... | def pool_health_monitor_create request **kwargs body {'health_monitor' {'type' kwargs['type'] 'delay' kwargs['delay'] 'timeout' kwargs['timeout'] 'max_retries' kwargs['max_retries'] 'http_method' kwargs['http_method'] 'url_path' kwargs['url_path'] 'expected_codes' kwargs['expected_codes'] 'admin_state_up' kwargs['admin... | 63 |
python-test-6378 | python | What does the code verify to ? | a message or file text the text | def verify text None user None filename None gnupghome None gpg create gpg user if text verified gpg verify text elif filename with salt utils flopen filename 'rb' as fp verified gpg verify file fp else raise Salt Invocation Error 'filenameortextmustbepassed ' ret {}if verified trust level is not None ret['res'] Truere... | def verify text None user None filename None gnupghome None gpg _create_gpg user if text verified gpg verify text elif filename with salt utils flopen filename 'rb' as _fp verified gpg verify_file _fp else raise SaltInvocationError 'filenameortextmustbepassed ' ret {}if verified trust_level is not None ret['res'] Truer... | 75 |
python-test-6379 | python | What do constant extension at the boundaries of an array generate ? | a new ndarray that is a constant extension of x along an axis | def const ext x n axis -1 if n < 1 return xleft end axis slice x start 0 stop 1 axis axis ones shape [1 ] * x ndim ones shape[axis] nones np ones ones shape dtype x dtype left ext ones * left end right end axis slice x start -1 axis axis right ext ones * right end ext np concatenate left ext x right ext axis axis retur... | def const_ext x n axis -1 if n < 1 return xleft_end axis_slice x start 0 stop 1 axis axis ones_shape [1] * x ndim ones_shape[axis] nones np ones ones_shape dtype x dtype left_ext ones * left_end right_end axis_slice x start -1 axis axis right_ext ones * right_end ext np concatenate left_ext x right_ext axis axis return... | 73 |
python-test-6380 | python | What generates a new ndarray that is a constant extension of x along an axis ? | constant extension at the boundaries of an array | def const ext x n axis -1 if n < 1 return xleft end axis slice x start 0 stop 1 axis axis ones shape [1 ] * x ndim ones shape[axis] nones np ones ones shape dtype x dtype left ext ones * left end right end axis slice x start -1 axis axis right ext ones * right end ext np concatenate left ext x right ext axis axis retur... | def const_ext x n axis -1 if n < 1 return xleft_end axis_slice x start 0 stop 1 axis axis ones_shape [1] * x ndim ones_shape[axis] nones np ones ones_shape dtype x dtype left_ext ones * left_end right_end axis_slice x start -1 axis axis right_ext ones * right_end ext np concatenate left_ext x right_ext axis axis return... | 73 |
python-test-6381 | python | What respects the assumptions ? | diophantine | def test assumptions m n symbols 'mn' integer True positive True diof diophantine n ** 2 + m * n - 500 assert diof set [ 5 20 40 10 95 5 121 4 248 2 499 1 ] a b symbols 'ab' integer True positive False diof diophantine a * b + 2 * a + 3 * b - 6 assert diof set [ -15 -3 -9 -4 -7 -5 -6 -6 -5 -8 -4 -14 ] | def test_assumptions m n symbols 'mn' integer True positive True diof diophantine n ** 2 + m * n - 500 assert diof set [ 5 20 40 10 95 5 121 4 248 2 499 1 ] a b symbols 'ab' integer True positive False diof diophantine a * b + 2 * a + 3 * b - 6 assert diof set [ -15 -3 -9 -4 -7 -5 -6 -6 -5 -8 -4 -14 ] | 79 |
python-test-6382 | python | What does diophantine respect ? | the assumptions | def test assumptions m n symbols 'mn' integer True positive True diof diophantine n ** 2 + m * n - 500 assert diof set [ 5 20 40 10 95 5 121 4 248 2 499 1 ] a b symbols 'ab' integer True positive False diof diophantine a * b + 2 * a + 3 * b - 6 assert diof set [ -15 -3 -9 -4 -7 -5 -6 -6 -5 -8 -4 -14 ] | def test_assumptions m n symbols 'mn' integer True positive True diof diophantine n ** 2 + m * n - 500 assert diof set [ 5 20 40 10 95 5 121 4 248 2 499 1 ] a b symbols 'ab' integer True positive False diof diophantine a * b + 2 * a + 3 * b - 6 assert diof set [ -15 -3 -9 -4 -7 -5 -6 -6 -5 -8 -4 -14 ] | 79 |
python-test-6383 | python | In which direction do an object copy to another ? | from one s3 location | def copy self Copy Source Bucket Key Extra Args None Callback None Source Client None Config None subscribers Noneif Callback is not None subscribers [ Progress Callback Invoker Callback ]config Configif config is None config Transfer Config with create transfer manager self config as manager future manager copy copy s... | def copy self CopySource Bucket Key ExtraArgs None Callback None SourceClient None Config None subscribers Noneif Callback is not None subscribers [ProgressCallbackInvoker Callback ]config Configif config is None config TransferConfig with create_transfer_manager self config as manager future manager copy copy_source C... | 69 |
python-test-6389 | python | What does the sopform function use to convert the list of all input combos that generate 1 into the smallest sum of products form ? | simplified_pairs and a redundant group- eliminating algorithm | def SO Pform variables minterms dontcares None variables [sympify v for v in variables]if minterms [] return falseminterms [list i for i in minterms]dontcares [list i for i in dontcares or [] ]for d in dontcares if d in minterms raise Value Error '%sinmintermsisalsoindontcares' % d old Nonenew minterms + dontcares whil... | def SOPform variables minterms dontcares None variables [sympify v for v in variables]if minterms [] return falseminterms [list i for i in minterms]dontcares [list i for i in dontcares or [] ]for d in dontcares if d in minterms raise ValueError '%sinmintermsisalsoindontcares' % d old Nonenew minterms + dontcares while ... | 77 |
python-test-6390 | python | What generate 1 ? | all input combos | def SO Pform variables minterms dontcares None variables [sympify v for v in variables]if minterms [] return falseminterms [list i for i in minterms]dontcares [list i for i in dontcares or [] ]for d in dontcares if d in minterms raise Value Error '%sinmintermsisalsoindontcares' % d old Nonenew minterms + dontcares whil... | def SOPform variables minterms dontcares None variables [sympify v for v in variables]if minterms [] return falseminterms [list i for i in minterms]dontcares [list i for i in dontcares or [] ]for d in dontcares if d in minterms raise ValueError '%sinmintermsisalsoindontcares' % d old Nonenew minterms + dontcares while ... | 77 |
python-test-6391 | python | How do algorithm eliminate ? | group- | def SO Pform variables minterms dontcares None variables [sympify v for v in variables]if minterms [] return falseminterms [list i for i in minterms]dontcares [list i for i in dontcares or [] ]for d in dontcares if d in minterms raise Value Error '%sinmintermsisalsoindontcares' % d old Nonenew minterms + dontcares whil... | def SOPform variables minterms dontcares None variables [sympify v for v in variables]if minterms [] return falseminterms [list i for i in minterms]dontcares [list i for i in dontcares or [] ]for d in dontcares if d in minterms raise ValueError '%sinmintermsisalsoindontcares' % d old Nonenew minterms + dontcares while ... | 77 |
python-test-6392 | python | What uses simplified_pairs and a redundant group- eliminating algorithm to convert the list of all input combos that generate 1 into the smallest sum of products form ? | the sopform function | def SO Pform variables minterms dontcares None variables [sympify v for v in variables]if minterms [] return falseminterms [list i for i in minterms]dontcares [list i for i in dontcares or [] ]for d in dontcares if d in minterms raise Value Error '%sinmintermsisalsoindontcares' % d old Nonenew minterms + dontcares whil... | def SOPform variables minterms dontcares None variables [sympify v for v in variables]if minterms [] return falseminterms [list i for i in minterms]dontcares [list i for i in dontcares or [] ]for d in dontcares if d in minterms raise ValueError '%sinmintermsisalsoindontcares' % d old Nonenew minterms + dontcares while ... | 77 |
python-test-6393 | python | How do partitions concatenate on axis=0 ? | by doing a simple stack | def stack partitions dfs divisions join 'outer' meta methods concat [df meta for df in dfs] join join empty strip unknown categories meta name 'concat-{ 0 }' format tokenize *dfs dsk {}i 0for df in dfs dsk update df dask try df meta meta match Trueexcept Value Error Type Error match Falsefor key in df keys if match dsk... | def stack_partitions dfs divisions join 'outer' meta methods concat [df _meta for df in dfs] join join empty strip_unknown_categories meta name 'concat-{0}' format tokenize *dfs dsk {}i 0for df in dfs dsk update df dask try df _meta meta match Trueexcept ValueError TypeError match Falsefor key in df _keys if match dsk[... | 83 |
python-test-6394 | python | What concatenates on axis=0 ? | partitions | def stack partitions dfs divisions join 'outer' meta methods concat [df meta for df in dfs] join join empty strip unknown categories meta name 'concat-{ 0 }' format tokenize *dfs dsk {}i 0for df in dfs dsk update df dask try df meta meta match Trueexcept Value Error Type Error match Falsefor key in df keys if match dsk... | def stack_partitions dfs divisions join 'outer' meta methods concat [df _meta for df in dfs] join join empty strip_unknown_categories meta name 'concat-{0}' format tokenize *dfs dsk {}i 0for df in dfs dsk update df dask try df _meta meta match Trueexcept ValueError TypeError match Falsefor key in df _keys if match dsk[... | 83 |
python-test-6395 | python | Where do partitions concatenate by doing a simple stack ? | on axis=0 | def stack partitions dfs divisions join 'outer' meta methods concat [df meta for df in dfs] join join empty strip unknown categories meta name 'concat-{ 0 }' format tokenize *dfs dsk {}i 0for df in dfs dsk update df dask try df meta meta match Trueexcept Value Error Type Error match Falsefor key in df keys if match dsk... | def stack_partitions dfs divisions join 'outer' meta methods concat [df _meta for df in dfs] join join empty strip_unknown_categories meta name 'concat-{0}' format tokenize *dfs dsk {}i 0for df in dfs dsk update df dask try df _meta meta match Trueexcept ValueError TypeError match Falsefor key in df _keys if match dsk[... | 83 |
python-test-6396 | python | What is using a user provided command ? | a file or block device | def mkfs os type fs label target run as root True specified fs None mkfs command MKFS COMMAND get os type DEFAULT MKFS COMMAND or '' % {'fs label' fs label 'target' target} if mkfs command utils execute run as root run as root *mkfs command split else if not specified fs specified fs CONF default ephemeral formatif not... | def mkfs os_type fs_label target run_as_root True specified_fs None mkfs_command _MKFS_COMMAND get os_type _DEFAULT_MKFS_COMMAND or '' % {'fs_label' fs_label 'target' target} if mkfs_command utils execute run_as_root run_as_root *mkfs_command split else if not specified_fs specified_fs CONF default_ephemeral_formatif n... | 86 |
python-test-6397 | python | What do a file or block device use ? | a user provided command | def mkfs os type fs label target run as root True specified fs None mkfs command MKFS COMMAND get os type DEFAULT MKFS COMMAND or '' % {'fs label' fs label 'target' target} if mkfs command utils execute run as root run as root *mkfs command split else if not specified fs specified fs CONF default ephemeral formatif not... | def mkfs os_type fs_label target run_as_root True specified_fs None mkfs_command _MKFS_COMMAND get os_type _DEFAULT_MKFS_COMMAND or '' % {'fs_label' fs_label 'target' target} if mkfs_command utils execute run_as_root run_as_root *mkfs_command split else if not specified_fs specified_fs CONF default_ephemeral_formatif n... | 86 |
python-test-6398 | python | What does the code find ? | the greedy policy | def greedy Policy Ts R discount Factor V dim len V num A len Ts Vnext V * discount Factor + R policy zeros dim num A for si in range dim actions all argmax [dot T[si ] Vnext for T in Ts] for a in actions policy[ si a ] 1 0 / len actions return policy collapsed Transitions Ts policy | def greedyPolicy Ts R discountFactor V dim len V numA len Ts Vnext V * discountFactor + R policy zeros dim numA for si in range dim actions all_argmax [dot T[si ] Vnext for T in Ts] for a in actions policy[ si a ] 1 0 / len actions return policy collapsedTransitions Ts policy | 62 |
python-test-6399 | python | What can we get ? | a percent change | def get old unhelpful old formatted {}cursor connection cursor cursor execute 'SELEC Tdoc id yes no\n FROM\n SELEC Twiki revision document idasdoc id \n SUM limitedvotes helpful asyes \n SUM NOT limitedvotes helpful asno\n FROM\n SELECT*FRO Mwiki helpfulvote\n WHER Ecreated< DATE SUB CURDATE INTERVAL 1 WEEK \n AN Dcrea... | def _get_old_unhelpful old_formatted {}cursor connection cursor cursor execute 'SELECTdoc_id yes no\nFROM\n SELECTwiki_revision document_idasdoc_id \nSUM limitedvotes helpful asyes \nSUM NOT limitedvotes helpful asno\nFROM\n SELECT*FROMwiki_helpfulvote\nWHEREcreated< DATE_SUB CURDATE INTERVAL1WEEK \nANDcreated> DATE_SU... | 135 |
python-test-6401 | python | For what purpose be which met ? | for doctesting the docstrings of the decorated objects | def doctest depends on exe None modules None disable viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends on deco fn fn doctest depends on dict exe exe modules modules disable viewers disable viewers pyglet pyglet if inspect isclass fn fn doctest depdends on no attrs in subclas... | def doctest_depends_on exe None modules None disable_viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends_on_deco fn fn _doctest_depends_on dict exe exe modules modules disable_viewers disable_viewers pyglet pyglet if inspect isclass fn fn _doctest_depdends_on no_attrs_in_subcl... | 64 |
python-test-6402 | python | What need to be met for doctesting the docstrings of the decorated objects ? | the depenencies | def doctest depends on exe None modules None disable viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends on deco fn fn doctest depends on dict exe exe modules modules disable viewers disable viewers pyglet pyglet if inspect isclass fn fn doctest depdends on no attrs in subclas... | def doctest_depends_on exe None modules None disable_viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends_on_deco fn fn _doctest_depends_on dict exe exe modules modules disable_viewers disable_viewers pyglet pyglet if inspect isclass fn fn _doctest_depdends_on no_attrs_in_subcl... | 64 |
python-test-6403 | python | What does the code add ? | metadata about the depenencies which need to be met for doctesting the docstrings of the decorated objects | def doctest depends on exe None modules None disable viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends on deco fn fn doctest depends on dict exe exe modules modules disable viewers disable viewers pyglet pyglet if inspect isclass fn fn doctest depdends on no attrs in subclas... | def doctest_depends_on exe None modules None disable_viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends_on_deco fn fn _doctest_depends_on dict exe exe modules modules disable_viewers disable_viewers pyglet pyglet if inspect isclass fn fn _doctest_depdends_on no_attrs_in_subcl... | 64 |
python-test-6404 | python | What do the depenencies need ? | to be met for doctesting the docstrings of the decorated objects | def doctest depends on exe None modules None disable viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends on deco fn fn doctest depends on dict exe exe modules modules disable viewers disable viewers pyglet pyglet if inspect isclass fn fn doctest depdends on no attrs in subclas... | def doctest_depends_on exe None modules None disable_viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends_on_deco fn fn _doctest_depends_on dict exe exe modules modules disable_viewers disable_viewers pyglet pyglet if inspect isclass fn fn _doctest_depdends_on no_attrs_in_subcl... | 64 |
python-test-6405 | python | What do which doctest ? | the docstrings of the decorated objects | def doctest depends on exe None modules None disable viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends on deco fn fn doctest depends on dict exe exe modules modules disable viewers disable viewers pyglet pyglet if inspect isclass fn fn doctest depdends on no attrs in subclas... | def doctest_depends_on exe None modules None disable_viewers None pyglet Falseif modules is not None and 'pyglet' in modules pyglet Truedef depends_on_deco fn fn _doctest_depends_on dict exe exe modules modules disable_viewers disable_viewers pyglet pyglet if inspect isclass fn fn _doctest_depdends_on no_attrs_in_subcl... | 64 |
python-test-6406 | python | What does the code get ? | a : class : thumbnailer for a source file | def get thumbnailer obj relative name None if hasattr obj 'easy thumbnails thumbnailer' return obj easy thumbnails thumbnailerif isinstance obj Thumbnailer return objelif isinstance obj Field File if not relative name relative name obj namereturn Thumbnailer Field File obj instance obj field relative name source storag... | def get_thumbnailer obj relative_name None if hasattr obj 'easy_thumbnails_thumbnailer' return obj easy_thumbnails_thumbnailerif isinstance obj Thumbnailer return objelif isinstance obj FieldFile if not relative_name relative_name obj namereturn ThumbnailerFieldFile obj instance obj field relative_name source_storage N... | 102 |
python-test-6409 | python | What do internet gateway fail ? | to detach unattached | @mock ec 2 def test igw detach unattached conn boto connect vpc u'the key' u'the secret' igw conn create internet gateway vpc conn create vpc VPC CIDR with assert raises EC 2 Response Error as cm conn detach internet gateway igw id vpc id cm exception code should equal u' Gateway Not Attached' cm exception status shoul... | @mock_ec2def test_igw_detach_unattached conn boto connect_vpc u'the_key' u'the_secret' igw conn create_internet_gateway vpc conn create_vpc VPC_CIDR with assert_raises EC2ResponseError as cm conn detach_internet_gateway igw id vpc id cm exception code should equal u'Gateway NotAttached' cm exception status should equal... | 67 |
python-test-6410 | python | For what purpose did a yaml snippet pad ? | to match the indent level you specify | def to padded yaml data level 0 indent 2 **kw if data in [ None ''] return ''try transformed yaml dump data indent indent allow unicode True default flow style False Dumper Ansible Dumper **kw padded '\n' join [ '' * level * indent + line for line in transformed splitlines ] return to text '\n{ 0 }' format padded excep... | def to_padded_yaml data level 0 indent 2 **kw if data in [None ''] return ''try transformed yaml dump data indent indent allow_unicode True default_flow_style False Dumper AnsibleDumper **kw padded '\n' join [ '' * level * indent + line for line in transformed splitlines ] return to_text '\n{0}' format padded except Ex... | 76 |
python-test-6417 | python | What does the code get ? | the pushover options from salt | def get options ret None defaults {'priority' '0 '}attrs {'pushover profile' 'profile' 'user' 'user' 'device' 'device' 'token' 'token' 'priority' 'priority' 'title' 'title' 'api version' 'api version' 'expire' 'expire' 'retry' 'retry' 'sound' 'sound'}profile attr 'pushover profile'profile attrs {'user' 'user' 'device' ... | def _get_options ret None defaults {'priority' '0'}attrs {'pushover_profile' 'profile' 'user' 'user' 'device' 'device' 'token' 'token' 'priority' 'priority' 'title' 'title' 'api_version' 'api_version' 'expire' 'expire' 'retry' 'retry' 'sound' 'sound'}profile_attr 'pushover_profile'profile_attrs {'user' 'user' 'device' ... | 81 |
python-test-6419 | python | What does the code find ? | all decoders and map decoder to import | def get Decoders decoder paths import base os path commonprefix decoder paths split os path sep [ -1 ]decoders {}for path in decoder paths import path path split os path sep [len import base ]for f in glob iglob '%s/* py' % path name os path splitext os path basename f [0 ]if name ' init ' decoders[name] ' ' join impor... | def getDecoders decoder_paths import_base os path commonprefix decoder_paths split os path sep [ -1 ]decoders {}for path in decoder_paths import_path path split os path sep [len import_base ]for f in glob iglob '%s/* py' % path name os path splitext os path basename f [0]if name '__init__' decoders[name] ' ' join impor... | 67 |
python-test-6426 | python | What does the code get ? | a fully - named package | def find Object name names name split ' ' top Level Package Nonemodule Names names[ ]while not top Level Package trialname ' ' join module Names if len trialname 0 return False None try top Level Package import trialname except Import Error exc info sys exc info if len traceback extract tb exc info[ 2 ] > 1 try del sys... | def findObject name names name split ' ' topLevelPackage NonemoduleNames names[ ]while not topLevelPackage trialname ' ' join moduleNames if len trialname 0 return False None try topLevelPackage __import__ trialname except ImportError exc_info sys exc_info if len traceback extract_tb exc_info[2] > 1 try del sys modules... | 102 |
python-test-6428 | python | What did the code set ? | new rate limit for a task type | @ Panel registerdef rate limit panel task name rate limit **kwargs try timeutils rate rate limit except Value Error as exc return {'error' ' Invalidratelimitstring %s' % exc }try tasks[task name] rate limit rate limitexcept Key Error panel logger error ' Ratelimitattemptforunknowntask%s' task name exc info sys exc info... | @Panel registerdef rate_limit panel task_name rate_limit **kwargs try timeutils rate rate_limit except ValueError as exc return {'error' 'Invalidratelimitstring %s' % exc }try tasks[task_name] rate_limit rate_limitexcept KeyError panel logger error 'Ratelimitattemptforunknowntask%s' task_name exc_info sys exc_info retu... | 100 |
python-test-6432 | python | What does the code get ? | a title suitable for an create - or - update view | def get create or change title request instance name field None if not instance pk return u' New%s' % instance meta verbose name if name field name getattr instance name field None else name u'%s' % instance if name return force text name return u' Unnamed%s' % instance meta verbose name | def get_create_or_change_title request instance name_field None if not instance pk return _ u'New%s' % instance _meta verbose_name if name_field name getattr instance name_field None else name u'%s' % instance if name return force_text name return _ u'Unnamed%s' % instance _meta verbose_name | 51 |
python-test-6433 | python | What does the code compute ? | the logistic loss and gradient | def logistic loss and grad w X y alpha sample weight None n samples n features X shapegrad np empty like w w c yz intercept dot w X y if sample weight is None sample weight np ones n samples out - np sum sample weight * log logistic yz + 0 5 * alpha * np dot w w z expit yz z0 sample weight * z - 1 * y grad[ n features]... | def _logistic_loss_and_grad w X y alpha sample_weight None n_samples n_features X shapegrad np empty_like w w c yz _intercept_dot w X y if sample_weight is None sample_weight np ones n_samples out - np sum sample_weight * log_logistic yz + 0 5 * alpha * np dot w w z expit yz z0 sample_weight * z - 1 * y grad[ n_feature... | 102 |
python-test-6440 | python | What does the code show ? | the details of an existing static address | def show address kwargs None call None if call 'function' raise Salt Cloud System Exit ' Theshow snapshotfunctionmustbecalledwith-for--function ' if not kwargs or 'name' not in kwargs log error ' Mustspecifyname ' return Falseif not kwargs or 'region' not in kwargs log error ' Mustspecifyregion ' return Falseconn get c... | def show_address kwargs None call None if call 'function' raise SaltCloudSystemExit 'Theshow_snapshotfunctionmustbecalledwith-for--function ' if not kwargs or 'name' not in kwargs log error 'Mustspecifyname ' return Falseif not kwargs or 'region' not in kwargs log error 'Mustspecifyregion ' return Falseconn get_conn re... | 59 |
python-test-6443 | python | What did the code read ? | an xml worksheet | def read worksheet xml source parent preset title string table style table workbook name None sheet codename None if workbook name and sheet codename ws Iterable Worksheet parent preset title workbook name sheet codename xml source else ws Worksheet parent preset title fast parse ws xml source string table style table ... | def read_worksheet xml_source parent preset_title string_table style_table workbook_name None sheet_codename None if workbook_name and sheet_codename ws IterableWorksheet parent preset_title workbook_name sheet_codename xml_source else ws Worksheet parent preset_title fast_parse ws xml_source string_table style_table r... | 53 |
python-test-6444 | python | What does the code retrieve from the java_object ? | the field named field_name | def get field java object field name command proto FIELD COMMAND NAME + proto FIELD GET SUBCOMMAND NAME + java object target id + u'\n' + field name + u'\n' + proto END COMMAND PART answer java object gateway client send command command if answer proto NO MEMBER COMMAND or is error answer [0 ] raise Py 4 J Error u'nofi... | def get_field java_object field_name command proto FIELD_COMMAND_NAME + proto FIELD_GET_SUBCOMMAND_NAME + java_object _target_id + u'\n' + field_name + u'\n' + proto END_COMMAND_PART answer java_object _gateway_client send_command command if answer proto NO_MEMBER_COMMAND or is_error answer [0] raise Py4JError u'nofiel... | 88 |
python-test-6445 | python | What does the code compute for points in x ? | the graph of k - neighbors | def kneighbors graph X n neighbors mode 'connectivity' metric 'minkowski' p 2 metric params None include self False n jobs 1 if not isinstance X K Neighbors Mixin X Nearest Neighbors n neighbors metric metric p p metric params metric params n jobs n jobs fit X else check params X metric p metric params query query incl... | def kneighbors_graph X n_neighbors mode 'connectivity' metric 'minkowski' p 2 metric_params None include_self False n_jobs 1 if not isinstance X KNeighborsMixin X NearestNeighbors n_neighbors metric metric p p metric_params metric_params n_jobs n_jobs fit X else _check_params X metric p metric_params query _query_inclu... | 74 |
python-test-6446 | python | What does the code notify ? | a list_member_added event | def notify list member added e target e['target']if target['screen name'] c['original name'] returnsource e['source']target object [e['target object']]created at e['created at']source user cycle color source['name'] + color func c['NOTIFICATION']['source nick'] '@' + source['screen name'] notify color func c['NOTIFICAT... | def notify_list_member_added e target e['target']if target['screen_name'] c['original_name'] returnsource e['source']target_object [e['target_object']]created_at e['created_at']source_user cycle_color source['name'] + color_func c['NOTIFICATION']['source_nick'] '@' + source['screen_name'] notify color_func c['NOTIFICAT... | 89 |
python-test-6449 | python | Where do a bug test ? | in the interaction between the ner model and the gazetteer | @pytest mark modelsdef test unit end gazetteer EN matcher Matcher EN vocab {u' Member Names' u'PERSON' {} [[{LOWER u'cal'}] [{LOWER u'cal'} {LOWER u'henderson'}]] } doc EN u'whoiscalthemanagerof?' if len list doc ents 0 ents matcher doc assert len ents 1 doc ents + tuple ents EN entity doc assert list doc ents [0 ] tex... | @pytest mark modelsdef test_unit_end_gazetteer EN matcher Matcher EN vocab {u'MemberNames' u'PERSON' {} [[{LOWER u'cal'}] [{LOWER u'cal'} {LOWER u'henderson'}]] } doc EN u'whoiscalthemanagerof?' if len list doc ents 0 ents matcher doc assert len ents 1 doc ents + tuple ents EN entity doc assert list doc ents [0] text u... | 56 |
python-test-6450 | python | What does the code get ? | current system keyboard setting cli example | def get sys cmd ''if salt utils which 'localectl' cmd 'localectl grep Keymap sed-e"s/ / /"-e"s/^[ DCTB ]*//"'elif ' Red Hat' in grains ['os family'] cmd 'grep LAYOUT/etc/sysconfig/keyboard grep-v E"^#"'elif ' Debian' in grains ['os family'] cmd 'grep XKBLAYOUT/etc/default/keyboard grep-v E"^#"'elif ' Gentoo' in grains ... | def get_sys cmd ''if salt utils which 'localectl' cmd 'localectl grepKeymap sed-e"s/ / /"-e"s/^[ DCTB ]*//"'elif 'RedHat' in __grains__['os_family'] cmd 'grepLAYOUT/etc/sysconfig/keyboard grep-vE"^#"'elif 'Debian' in __grains__['os_family'] cmd 'grepXKBLAYOUT/etc/default/keyboard grep-vE"^#"'elif 'Gentoo' in __grains__... | 71 |
python-test-6456 | python | What does the code convert to human classic representation ? | a size in bit | def human Bit Size size divisor 1000 if size < divisor return ngettext '%ubit' '%ubits' size % size units [u' Kbit' u' Mbit' u' Gbit' u' Tbit']size float size for unit in units size size / divisor if size < divisor return '% 1f%s' % size unit return u'%u%s' % size unit | def humanBitSize size divisor 1000if size < divisor return ngettext '%ubit' '%ubits' size % size units [u'Kbit' u'Mbit' u'Gbit' u'Tbit']size float size for unit in units size size / divisor if size < divisor return '% 1f%s' % size unit return u'%u%s' % size unit | 52 |
python-test-6459 | python | How did regions separate ? | by weight less than threshold | def cut threshold labels rag thresh in place True if not in place rag rag copy to remove [ x y for x y d in rag edges iter data True if d['weight'] > thresh ]rag remove edges from to remove comps nx connected components rag map array np arange labels max + 1 dtype labels dtype for i nodes in enumerate comps for node in... | def cut_threshold labels rag thresh in_place True if not in_place rag rag copy to_remove [ x y for x y d in rag edges_iter data True if d['weight'] > thresh ]rag remove_edges_from to_remove comps nx connected_components rag map_array np arange labels max + 1 dtype labels dtype for i nodes in enumerate comps for node in... | 77 |
python-test-6464 | python | What does the code resolve ? | the full hash for committish | def rev parse committish repo dir None head read ref committish repo dir repo dir if head debug 2 'resolvedfromref commit %s\n' % head encode 'hex' return headp L Pack Idx List repo 'objects/pack' repo dir repo dir if len committish 40 try hash committish decode 'hex' except Type Error return Noneif pL exists hash retu... | def rev_parse committish repo_dir None head read_ref committish repo_dir repo_dir if head debug2 'resolvedfromref commit %s\n' % head encode 'hex' return headpL PackIdxList repo 'objects/pack' repo_dir repo_dir if len committish 40 try hash committish decode 'hex' except TypeError return Noneif pL exists hash return ha... | 58 |
python-test-6469 | python | What does the code take ? | an old | def update url url debug if not url return urloriginal url urlurl url replace ' //raw github com/' ' //raw githubusercontent com/' url url replace ' //nodeload github com/' ' //codeload github com/' url re sub '^ https //codeload github com/[^/]+/[^/]+/ zipball / * $' '\\ 1 zip\\ 2 ' url if url 'https //sublime wbond n... | def update_url url debug if not url return urloriginal_url urlurl url replace ' //raw github com/' ' //raw githubusercontent com/' url url replace ' //nodeload github com/' ' //codeload github com/' url re sub '^ https //codeload github com/[^/]+/[^/]+/ zipball / * $' '\\1zip\\2' url if url 'https //sublime wbond net/r... | 87 |
python-test-6478 | python | For what purpose do the value(s ) from the given data_dict return ? | for the given key(s | def get or bust data dict keys if isinstance keys basestring keys [keys]import ckan logic schema as schemaschema schema create schema for required keys keys data dict errors validate data dict schema if errors raise Validation Error errors values [data dict[key] for key in keys]if len values 1 return values[ 0 ]return ... | def get_or_bust data_dict keys if isinstance keys basestring keys [keys]import ckan logic schema as schemaschema schema create_schema_for_required_keys keys data_dict errors _validate data_dict schema if errors raise ValidationError errors values [data_dict[key] for key in keys]if len values 1 return values[0]return tu... | 54 |
python-test-6480 | python | What would it create ? | a milestone | def add prerequisite course course key prerequisite course key if not is prerequisite courses enabled return Nonemilestone name ' Course{course id}requires{prerequisite course id}' format course id unicode course key prerequisite course id unicode prerequisite course key milestone milestones api add milestone {'name' m... | def add_prerequisite_course course_key prerequisite_course_key if not is_prerequisite_courses_enabled return Nonemilestone_name _ 'Course{course_id}requires{prerequisite_course_id}' format course_id unicode course_key prerequisite_course_id unicode prerequisite_course_key milestone milestones_api add_milestone {'name' ... | 72 |
python-test-6484 | python | What does the code get ? | a namespace resource_type association | def get context namespace name resource type name namespace id resource type id session try query session query models Metadef Namespace Resource Type filter by namespace id namespace id resource type id resource type id db rec query one except sa orm exc No Result Found LOG debug ' Themetadatadefinitionresource-typeas... | def _get context namespace_name resource_type_name namespace_id resource_type_id session try query session query models MetadefNamespaceResourceType filter_by namespace_id namespace_id resource_type_id resource_type_id db_rec query one except sa_orm exc NoResultFound LOG debug 'Themetadatadefinitionresource-typeassocia... | 93 |
python-test-6485 | python | What does the code get ? | every host that has had a benchmark run on it | def get hosts and tests host info {}q dbmodels Q test name startswith 'kernbench' dbmodels Q test name startswith 'dbench' dbmodels Q test name startswith 'tbench' dbmodels Q test name startswith 'unixbench' dbmodels Q test name startswith 'iozone' test query models Test View objects filter q values 'test name' 'hostna... | def get_hosts_and_tests host_info {}q dbmodels Q test_name__startswith 'kernbench' dbmodels Q test_name__startswith 'dbench' dbmodels Q test_name__startswith 'tbench' dbmodels Q test_name__startswith 'unixbench' dbmodels Q test_name__startswith 'iozone' test_query models TestView objects filter q values 'test_name' 'ho... | 93 |
python-test-6486 | python | Where has every host had a benchmark run ? | on it | def get hosts and tests host info {}q dbmodels Q test name startswith 'kernbench' dbmodels Q test name startswith 'dbench' dbmodels Q test name startswith 'tbench' dbmodels Q test name startswith 'unixbench' dbmodels Q test name startswith 'iozone' test query models Test View objects filter q values 'test name' 'hostna... | def get_hosts_and_tests host_info {}q dbmodels Q test_name__startswith 'kernbench' dbmodels Q test_name__startswith 'dbench' dbmodels Q test_name__startswith 'tbench' dbmodels Q test_name__startswith 'unixbench' dbmodels Q test_name__startswith 'iozone' test_query models TestView objects filter q values 'test_name' 'ho... | 93 |
python-test-6487 | python | What has every host had on it ? | a benchmark run | def get hosts and tests host info {}q dbmodels Q test name startswith 'kernbench' dbmodels Q test name startswith 'dbench' dbmodels Q test name startswith 'tbench' dbmodels Q test name startswith 'unixbench' dbmodels Q test name startswith 'iozone' test query models Test View objects filter q values 'test name' 'hostna... | def get_hosts_and_tests host_info {}q dbmodels Q test_name__startswith 'kernbench' dbmodels Q test_name__startswith 'dbench' dbmodels Q test_name__startswith 'tbench' dbmodels Q test_name__startswith 'unixbench' dbmodels Q test_name__startswith 'iozone' test_query models TestView objects filter q values 'test_name' 'ho... | 93 |
python-test-6488 | python | What has had a benchmark run on it ? | every host | def get hosts and tests host info {}q dbmodels Q test name startswith 'kernbench' dbmodels Q test name startswith 'dbench' dbmodels Q test name startswith 'tbench' dbmodels Q test name startswith 'unixbench' dbmodels Q test name startswith 'iozone' test query models Test View objects filter q values 'test name' 'hostna... | def get_hosts_and_tests host_info {}q dbmodels Q test_name__startswith 'kernbench' dbmodels Q test_name__startswith 'dbench' dbmodels Q test_name__startswith 'tbench' dbmodels Q test_name__startswith 'unixbench' dbmodels Q test_name__startswith 'iozone' test_query models TestView objects filter q values 'test_name' 'ho... | 93 |
python-test-6489 | python | What does the code make ? | a fastq file for each library warning | def make fastq multi in fasta quals out fp label transform split lib transform mkdir out fp seen libs defaultdict list for rec label in iter fastq in fasta quals label transform lib id seq id label rsplit ' ' 1 seen libs[lib id] append rec for lib recs in seen libs items if lib is None continueoutfile open out fp + '/'... | def make_fastq_multi in_fasta quals out_fp label_transform split_lib_transform mkdir out_fp seen_libs defaultdict list for rec label in iter_fastq in_fasta quals label_transform lib_id seq_id label rsplit '_' 1 seen_libs[lib_id] append rec for lib recs in seen_libs items if lib is None continueoutfile open out_fp + '/'... | 76 |
python-test-6496 | python | What does the code ensure ? | that the named index is absent | def absent name ret {'name' name 'changes' {} 'result' True 'comment' ''}index exists salt ['elasticsearch index exists'] index name if index exists if opts ['test'] ret['comment'] ' Index{ 0 }willberemoved' format name ret['result'] Noneelse ret['result'] salt ['elasticsearch index delete'] index name if ret['result']... | def absent name ret {'name' name 'changes' {} 'result' True 'comment' ''}index_exists __salt__['elasticsearch index_exists'] index name if index_exists if __opts__['test'] ret['comment'] 'Index{0}willberemoved' format name ret['result'] Noneelse ret['result'] __salt__['elasticsearch index_delete'] index name if ret['re... | 82 |
python-test-6501 | python | What do a string represent ? | a time span | def fmt Time Span time pad 0 point 0 short False after False unit 99 type point optimal Period time point unit time convert Seconds To time type if not point time int round time if short fmt short Time Fmt type elif after fmt after Time Table[type] plural Count time point else fmt time Table[type] plural Count time poi... | def fmtTimeSpan time pad 0 point 0 short False after False unit 99 type point optimalPeriod time point unit time convertSecondsTo time type if not point time int round time if short fmt shortTimeFmt type elif after fmt afterTimeTable[type] _pluralCount time point else fmt timeTable[type] _pluralCount time point timestr... | 82 |
python-test-6502 | python | What does the code create using the supplied data / header ? | a new fits file | @deprecated renamed argument 'clobber' 'overwrite' '1 3' def writeto filename data header None output verify 'exception' overwrite False checksum False hdu makehdu data header if hdu is image and not isinstance hdu Primary HDU hdu Primary HDU data header header hdu writeto filename overwrite overwrite output verify out... | @deprecated_renamed_argument 'clobber' 'overwrite' '1 3' def writeto filename data header None output_verify 'exception' overwrite False checksum False hdu _makehdu data header if hdu is_image and not isinstance hdu PrimaryHDU hdu PrimaryHDU data header header hdu writeto filename overwrite overwrite output_verify outp... | 51 |
python-test-6503 | python | How does the code create a new fits file ? | using the supplied data / header | @deprecated renamed argument 'clobber' 'overwrite' '1 3' def writeto filename data header None output verify 'exception' overwrite False checksum False hdu makehdu data header if hdu is image and not isinstance hdu Primary HDU hdu Primary HDU data header header hdu writeto filename overwrite overwrite output verify out... | @deprecated_renamed_argument 'clobber' 'overwrite' '1 3' def writeto filename data header None output_verify 'exception' overwrite False checksum False hdu _makehdu data header if hdu is_image and not isinstance hdu PrimaryHDU hdu PrimaryHDU data header header hdu writeto filename overwrite overwrite output_verify outp... | 51 |
python-test-6504 | python | What does the code remove ? | a incron job for a specified user | def rm job user path mask cmd mask str mask upper for item in mask split ' ' if item not in MASK TYPES return ' Invalidmasktype {0 }' format item lst list tab user ret 'absent'rm Nonefor ind in range len lst['crons'] if rm is not None breakif path lst['crons'][ind]['path'] if cmd lst['crons'][ind]['cmd'] if mask lst['c... | def rm_job user path mask cmd mask str mask upper for item in mask split ' ' if item not in _MASK_TYPES return 'Invalidmasktype {0}' format item lst list_tab user ret 'absent'rm_ Nonefor ind in range len lst['crons'] if rm_ is not None breakif path lst['crons'][ind]['path'] if cmd lst['crons'][ind]['cmd'] if mask lst['... | 80 |
python-test-6508 | python | What does the code make ? | sure memory reallocation works okay when the number of columns is large | @pytest mark parametrize 'parallel' [ True False] def test many columns parallel read basic text '' join [str i for i in range 500 ] text + '\n' + text + '\n' + text table read basic text parallel parallel expected Table [[i i] for i in range 500 ] names [str i for i in range 500 ] assert table equal table expected | @pytest mark parametrize 'parallel' [True False] def test_many_columns parallel read_basic text '' join [str i for i in range 500 ] text + '\n' + text + '\n' + text table read_basic text parallel parallel expected Table [[i i] for i in range 500 ] names [str i for i in range 500 ] assert_table_equal table expected | 64 |
python-test-6514 | python | What does the user choose ? | which ones to build | def project versions request project slug project get object or 404 Project objects protected request user slug project slug versions Version objects public user request user project project only active False active versions versions filter active True inactive versions versions filter active False inactive filter Vers... | def project_versions request project_slug project get_object_or_404 Project objects protected request user slug project_slug versions Version objects public user request user project project only_active False active_versions versions filter active True inactive_versions versions filter active False inactive_filter Vers... | 112 |
python-test-6515 | python | What does project version list view let ? | the user choose which ones to build | def project versions request project slug project get object or 404 Project objects protected request user slug project slug versions Version objects public user request user project project only active False active versions versions filter active True inactive versions versions filter active False inactive filter Vers... | def project_versions request project_slug project get_object_or_404 Project objects protected request user slug project_slug versions Version objects public user request user project project only_active False active_versions versions filter active True inactive_versions versions filter active False inactive_filter Vers... | 112 |
python-test-6520 | python | What do url convert ? | to mirror url | def encode mirror url raw url or path remote domain None is scheme None is escape False if is escape raw url or path raw url or path replace 'r\\/' '/' else raw url or path raw url or pathsp urlsplit raw url or path if '/extdomains/' sp path[ 12 ] return raw url or pathdomain remote domain or sp netloc or parse remote ... | def encode_mirror_url raw_url_or_path remote_domain None is_scheme None is_escape False if is_escape _raw_url_or_path raw_url_or_path replace 'r\\/' '/' else _raw_url_or_path raw_url_or_pathsp urlsplit _raw_url_or_path if '/extdomains/' sp path[ 12] return raw_url_or_pathdomain remote_domain or sp netloc or parse remot... | 156 |
python-test-6521 | python | What does the code create ? | a graph that can be pickled | def create dot graph graph show connectinfo False simple form True logger debug u'creatingdotgraph' pklgraph nx Di Graph for edge in graph edges data graph get edge data *edge srcname get print name edge[ 0 ] simple form simple form destname get print name edge[ 1 ] simple form simple form if show connectinfo pklgraph ... | def _create_dot_graph graph show_connectinfo False simple_form True logger debug u'creatingdotgraph' pklgraph nx DiGraph for edge in graph edges data graph get_edge_data *edge srcname get_print_name edge[0] simple_form simple_form destname get_print_name edge[1] simple_form simple_form if show_connectinfo pklgraph add_... | 70 |
python-test-6522 | python | What does the code create ? | a schemenode from an element instance | def scheme node from element node el registry try widget desc registry widget node el get 'qualified name' except Key Error as ex raise Unknown Widget Definition *ex args title node el get 'title' pos node el get 'position' if pos is not None pos tuple eval pos return Scheme Node widget desc title title position pos | def scheme_node_from_element node_el registry try widget_desc registry widget node_el get 'qualified_name' except KeyError as ex raise UnknownWidgetDefinition *ex args title node_el get 'title' pos node_el get 'position' if pos is not None pos tuple_eval pos return SchemeNode widget_desc title title position pos | 57 |
python-test-6527 | python | What does the code compute under the model in est ? | the gaussian log likelihood of x | def gaussian loglik scorer est X y None precision est get precision n samples n features X shapelog like np zeros n samples log like -0 5 * X * np dot X precision sum axis 1 log like - 0 5 * n features * log 2 0 * np pi - logdet precision out np mean log like return out | def _gaussian_loglik_scorer est X y None precision est get_precision n_samples n_features X shapelog_like np zeros n_samples log_like -0 5 * X * np dot X precision sum axis 1 log_like - 0 5 * n_features * log 2 0 * np pi - _logdet precision out np mean log_like return out | 62 |
python-test-6528 | python | Where does the code compute the gaussian log likelihood of x ? | under the model in est | def gaussian loglik scorer est X y None precision est get precision n samples n features X shapelog like np zeros n samples log like -0 5 * X * np dot X precision sum axis 1 log like - 0 5 * n features * log 2 0 * np pi - logdet precision out np mean log like return out | def _gaussian_loglik_scorer est X y None precision est get_precision n_samples n_features X shapelog_like np zeros n_samples log_like -0 5 * X * np dot X precision sum axis 1 log_like - 0 5 * n_features * log 2 0 * np pi - _logdet precision out np mean log_like return out | 62 |
python-test-6529 | python | What does this find ? | a match in the sub keys | def get reg software ignore list [u' Address Book' u' Connection Manager' u' Direct Draw Ex' u' Fontcore' u'IE 40 ' u'IE 4 Data' u'IE 5 BAKEX' u'IE Data' u' Mobile Option Pack' u' Scheduling Agent' u'WIC' u' Not Found' u' valuenotset ' u'' None]reg software {}hive u'HKLM'key u' Software\\ Microsoft\\ Windows\\ Current ... | def _get_reg_software ignore_list [u'AddressBook' u'ConnectionManager' u'DirectDrawEx' u'Fontcore' u'IE40' u'IE4Data' u'IE5BAKEX' u'IEData' u'MobileOptionPack' u'SchedulingAgent' u'WIC' u'NotFound' u' valuenotset ' u'' None]reg_software {}hive u'HKLM'key u'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'def upd... | 163 |
python-test-6530 | python | What does this search to find a match in the sub keys ? | the uninstall keys in the registry | def get reg software ignore list [u' Address Book' u' Connection Manager' u' Direct Draw Ex' u' Fontcore' u'IE 40 ' u'IE 4 Data' u'IE 5 BAKEX' u'IE Data' u' Mobile Option Pack' u' Scheduling Agent' u'WIC' u' Not Found' u' valuenotset ' u'' None]reg software {}hive u'HKLM'key u' Software\\ Microsoft\\ Windows\\ Current ... | def _get_reg_software ignore_list [u'AddressBook' u'ConnectionManager' u'DirectDrawEx' u'Fontcore' u'IE40' u'IE4Data' u'IE5BAKEX' u'IEData' u'MobileOptionPack' u'SchedulingAgent' u'WIC' u'NotFound' u' valuenotset ' u'' None]reg_software {}hive u'HKLM'key u'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'def upd... | 163 |
python-test-6531 | python | For what purpose does this search the uninstall keys in the registry ? | to find a match in the sub keys | def get reg software ignore list [u' Address Book' u' Connection Manager' u' Direct Draw Ex' u' Fontcore' u'IE 40 ' u'IE 4 Data' u'IE 5 BAKEX' u'IE Data' u' Mobile Option Pack' u' Scheduling Agent' u'WIC' u' Not Found' u' valuenotset ' u'' None]reg software {}hive u'HKLM'key u' Software\\ Microsoft\\ Windows\\ Current ... | def _get_reg_software ignore_list [u'AddressBook' u'ConnectionManager' u'DirectDrawEx' u'Fontcore' u'IE40' u'IE4Data' u'IE5BAKEX' u'IEData' u'MobileOptionPack' u'SchedulingAgent' u'WIC' u'NotFound' u' valuenotset ' u'' None]reg_software {}hive u'HKLM'key u'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'def upd... | 163 |
python-test-6532 | python | How does this set the test ? | by making a directory named some_directory | def make loc files file creator size None if size body '*' * size else body ' Thisisatest 'filename 1 file creator create file os path join 'some directory' 'text 1 txt' body filename 2 file creator create file os path join 'some directory' 'another directory' 'text 2 txt' body filename 1 six text type filename 1 filen... | def make_loc_files file_creator size None if size body '*' * size else body 'Thisisatest 'filename1 file_creator create_file os path join 'some_directory' 'text1 txt' body filename2 file_creator create_file os path join 'some_directory' 'another_directory' 'text2 txt' body filename1 six text_type filename1 filename2 si... | 80 |
python-test-6533 | python | What does the code convert to a pandas dataframe parameters reader ? | a block of bytes | def pandas read text reader b header kwargs dtypes None columns None write header True enforce False bio Bytes IO if write header and not b startswith header rstrip bio write header bio write b bio seek 0 df reader bio **kwargs if dtypes coerce dtypes df dtypes if enforce and columns and list df columns list columns ra... | def pandas_read_text reader b header kwargs dtypes None columns None write_header True enforce False bio BytesIO if write_header and not b startswith header rstrip bio write header bio write b bio seek 0 df reader bio **kwargs if dtypes coerce_dtypes df dtypes if enforce and columns and list df columns list columns rai... | 72 |
python-test-6535 | python | What do the config take as the base path ? | the profile path | def rewrite config CONFIG[' Mob SF']['dir'] expanduser '~' + CONFIG[' Mob SF']['dir'] CONFIG[' Mob SF']['downloads'] CONFIG[' Mob SF']['dir'] + CONFIG[' Mob SF']['downloads'] CONFIG[' Mob SF']['tools'] CONFIG[' Mob SF']['dir'] + CONFIG[' Mob SF']['tools'] CONFIG[' Mob SF']['samples'] CONFIG[' Mob SF']['dir'] + CONFIG['... | def rewrite_config CONFIG['MobSF']['dir'] expanduser '~' + CONFIG['MobSF']['dir'] CONFIG['MobSF']['downloads'] CONFIG['MobSF']['dir'] + CONFIG['MobSF']['downloads'] CONFIG['MobSF']['tools'] CONFIG['MobSF']['dir'] + CONFIG['MobSF']['tools'] CONFIG['MobSF']['samples'] CONFIG['MobSF']['dir'] + CONFIG['MobSF']['samples'] C... | 95 |
python-test-6536 | python | For what purpose does the code rewrite the config ? | to take the profile path as the base path | def rewrite config CONFIG[' Mob SF']['dir'] expanduser '~' + CONFIG[' Mob SF']['dir'] CONFIG[' Mob SF']['downloads'] CONFIG[' Mob SF']['dir'] + CONFIG[' Mob SF']['downloads'] CONFIG[' Mob SF']['tools'] CONFIG[' Mob SF']['dir'] + CONFIG[' Mob SF']['tools'] CONFIG[' Mob SF']['samples'] CONFIG[' Mob SF']['dir'] + CONFIG['... | def rewrite_config CONFIG['MobSF']['dir'] expanduser '~' + CONFIG['MobSF']['dir'] CONFIG['MobSF']['downloads'] CONFIG['MobSF']['dir'] + CONFIG['MobSF']['downloads'] CONFIG['MobSF']['tools'] CONFIG['MobSF']['dir'] + CONFIG['MobSF']['tools'] CONFIG['MobSF']['samples'] CONFIG['MobSF']['dir'] + CONFIG['MobSF']['samples'] C... | 95 |
python-test-6551 | python | What does the code setup ? | the nzbget sensors | def setup platform hass config add devices discovery info None host config get CONF HOST port config get CONF PORT name config get CONF NAME username config get CONF USERNAME password config get CONF PASSWORD monitored types config get CONF MONITORED VARIABLES url 'http //{} {}/jsonrpc' format host port try nzbgetapi N... | def setup_platform hass config add_devices discovery_info None host config get CONF_HOST port config get CONF_PORT name config get CONF_NAME username config get CONF_USERNAME password config get CONF_PASSWORD monitored_types config get CONF_MONITORED_VARIABLES url 'http //{} {}/jsonrpc' format host port try nzbgetapi N... | 117 |
python-test-6554 | python | Where does the mod_aggregate function merge them into a single pkgs ref ? | in the present low data | def mod aggregate low chunks running pkgs []agg enabled ['installed' 'latest' 'removed' 'purged']if low get 'fun' not in agg enabled return lowfor chunk in chunks tag salt utils gen state tag chunk if tag in running continueif chunk get 'state' 'pkg' if ' agg ' in chunk continueif chunk get 'fun' low get 'fun' continue... | def mod_aggregate low chunks running pkgs []agg_enabled ['installed' 'latest' 'removed' 'purged']if low get 'fun' not in agg_enabled return lowfor chunk in chunks tag salt utils gen_state_tag chunk if tag in running continueif chunk get 'state' 'pkg' if '__agg__' in chunk continueif chunk get 'fun' low get 'fun' contin... | 94 |
python-test-6555 | python | What does the mod_aggregate function look ? | all packages in the available low chunks | def mod aggregate low chunks running pkgs []agg enabled ['installed' 'latest' 'removed' 'purged']if low get 'fun' not in agg enabled return lowfor chunk in chunks tag salt utils gen state tag chunk if tag in running continueif chunk get 'state' 'pkg' if ' agg ' in chunk continueif chunk get 'fun' low get 'fun' continue... | def mod_aggregate low chunks running pkgs []agg_enabled ['installed' 'latest' 'removed' 'purged']if low get 'fun' not in agg_enabled return lowfor chunk in chunks tag salt utils gen_state_tag chunk if tag in running continueif chunk get 'state' 'pkg' if '__agg__' in chunk continueif chunk get 'fun' low get 'fun' contin... | 94 |
python-test-6557 | python | What does the code retrieve ? | the operational status of the port | def get port status cluster lswitch id port id try r do single request HTTP GET '/ws v1 /lswitch/%s/lport/%s/status' % lswitch id port id cluster cluster r json loads r except Nvp Api Client Resource Not Found as e LOG error ' Portnotfound Error %s' str e raise exception Port Not Found port id port id net id lswitch id... | def get_port_status cluster lswitch_id port_id try r do_single_request HTTP_GET '/ws v1/lswitch/%s/lport/%s/status' % lswitch_id port_id cluster cluster r json loads r except NvpApiClient ResourceNotFound as e LOG error _ 'Portnotfound Error %s' str e raise exception PortNotFound port_id port_id net_id lswitch_id excep... | 90 |
python-test-6561 | python | How did the code set the matplotlib color cycle ? | using a seaborn palette | def set palette palette n colors None desat None color codes False colors palettes color palette palette n colors desat if mpl ge 150 from cycler import cyclercyl cycler 'color' colors mpl rc Params['axes prop cycle'] cylelse mpl rc Params['axes color cycle'] list colors mpl rc Params['patch facecolor'] colors[ 0 ]if c... | def set_palette palette n_colors None desat None color_codes False colors palettes color_palette palette n_colors desat if mpl_ge_150 from cycler import cyclercyl cycler 'color' colors mpl rcParams['axes prop_cycle'] cylelse mpl rcParams['axes color_cycle'] list colors mpl rcParams['patch facecolor'] colors[0]if color_... | 58 |
python-test-6562 | python | What did the code set using a seaborn palette ? | the matplotlib color cycle | def set palette palette n colors None desat None color codes False colors palettes color palette palette n colors desat if mpl ge 150 from cycler import cyclercyl cycler 'color' colors mpl rc Params['axes prop cycle'] cylelse mpl rc Params['axes color cycle'] list colors mpl rc Params['patch facecolor'] colors[ 0 ]if c... | def set_palette palette n_colors None desat None color_codes False colors palettes color_palette palette n_colors desat if mpl_ge_150 from cycler import cyclercyl cycler 'color' colors mpl rcParams['axes prop_cycle'] cylelse mpl rcParams['axes color_cycle'] list colors mpl rcParams['patch facecolor'] colors[0]if color_... | 58 |
python-test-6563 | python | What does the code ensure ? | we can compile functions with & kwonly if were on python 3 | def test lambda list keywords kwonly kwonly demo u' fn[&kwonlya[b 2 ]] printab 'if PY 3 code can compile kwonly demo for i kwonlyarg name in enumerate u'a' u'b' assert kwonlyarg name code body[ 0 ] args kwonlyargs[i] arg assert code body[ 0 ] args kw defaults[ 0 ] is None assert code body[ 0 ] args kw defaults[ 1 ] n 2... | def test_lambda_list_keywords_kwonly kwonly_demo u' fn[&kwonlya[b2]] printab 'if PY3 code can_compile kwonly_demo for i kwonlyarg_name in enumerate u'a' u'b' assert kwonlyarg_name code body[0] args kwonlyargs[i] arg assert code body[0] args kw_defaults[0] is None assert code body[0] args kw_defaults[1] n 2 else excepti... | 83 |
python-test-6564 | python | How can we were compile functions if were on python 3 ? | with & kwonly | def test lambda list keywords kwonly kwonly demo u' fn[&kwonlya[b 2 ]] printab 'if PY 3 code can compile kwonly demo for i kwonlyarg name in enumerate u'a' u'b' assert kwonlyarg name code body[ 0 ] args kwonlyargs[i] arg assert code body[ 0 ] args kw defaults[ 0 ] is None assert code body[ 0 ] args kw defaults[ 1 ] n 2... | def test_lambda_list_keywords_kwonly kwonly_demo u' fn[&kwonlya[b2]] printab 'if PY3 code can_compile kwonly_demo for i kwonlyarg_name in enumerate u'a' u'b' assert kwonlyarg_name code body[0] args kwonlyargs[i] arg assert code body[0] args kw_defaults[0] is None assert code body[0] args kw_defaults[1] n 2 else excepti... | 83 |
python-test-6565 | python | Where is this function used ? | in a module definition | def module Provides *interfaces frame sys getframe 1 locals frame f localsif locals is not frame f globals or ' name ' not in locals raise Type Error 'module Providescanonlybeusedfromamoduledefinition ' if ' provides ' in locals raise Type Error 'module Providescanonlybeusedonceinamoduledefinition ' locals[' provides '... | def moduleProvides *interfaces frame sys _getframe 1 locals frame f_localsif locals is not frame f_globals or '__name__' not in locals raise TypeError 'moduleProvidescanonlybeusedfromamoduledefinition ' if '__provides__' in locals raise TypeError 'moduleProvidescanonlybeusedonceinamoduledefinition ' locals['__provides_... | 52 |
python-test-6566 | python | What did the code set ? | due date | @frappe whitelist def get due date posting date party type party company due date Noneif posting date and party due date posting date credit days based on credit days get credit days party type party company if credit days based on u' Fixed Days' and credit days due date add days posting date credit days elif credit da... | @frappe whitelist def get_due_date posting_date party_type party company due_date Noneif posting_date and party due_date posting_date credit_days_based_on credit_days get_credit_days party_type party company if credit_days_based_on u'FixedDays' and credit_days due_date add_days posting_date credit_days elif credit_days... | 83 |
python-test-6567 | python | What does the code walk to check if they re multi - package xpis ? | the themes and addons files | def run returnfor file in File objects filter version addon type in [amo ADDON EXTENSION amo ADDON THEME] try data parse addon file file path addon file version addon if data get 'is multi package' file update is multi package True except log error ' Failedcheckingfile{ 0 }' format file pk | def run returnfor file_ in File objects filter version__addon__type__in [amo ADDON_EXTENSION amo ADDON_THEME] try data parse_addon file_ file_path addon file_ version addon if data get 'is_multi_package' file_ update is_multi_package True except log error 'Failedcheckingfile{0}' format file_ pk | 51 |
python-test-6568 | python | How do they be multi - package ? | xpis | def run returnfor file in File objects filter version addon type in [amo ADDON EXTENSION amo ADDON THEME] try data parse addon file file path addon file version addon if data get 'is multi package' file update is multi package True except log error ' Failedcheckingfile{ 0 }' format file pk | def run returnfor file_ in File objects filter version__addon__type__in [amo ADDON_EXTENSION amo ADDON_THEME] try data parse_addon file_ file_path addon file_ version addon if data get 'is_multi_package' file_ update is_multi_package True except log error 'Failedcheckingfile{0}' format file_ pk | 51 |
python-test-6569 | python | For what purpose does the code walk the themes and addons files ? | to check if they re multi - package xpis | def run returnfor file in File objects filter version addon type in [amo ADDON EXTENSION amo ADDON THEME] try data parse addon file file path addon file version addon if data get 'is multi package' file update is multi package True except log error ' Failedcheckingfile{ 0 }' format file pk | def run returnfor file_ in File objects filter version__addon__type__in [amo ADDON_EXTENSION amo ADDON_THEME] try data parse_addon file_ file_path addon file_ version addon if data get 'is_multi_package' file_ update is_multi_package True except log error 'Failedcheckingfile{0}' format file_ pk | 51 |
python-test-6570 | python | What does the code clean ? | all header and footer images files | @cronjobs registerdef cleanup image files log info ' Removingonedayoldtemporaryimagefilesforthemes ' for folder in 'persona footer' 'persona header' root os path join settings TMP PATH folder if not os path exists root continuefor path in os listdir root full path os path join root path age time time - os stat full pat... | @cronjobs registerdef cleanup_image_files log info 'Removingonedayoldtemporaryimagefilesforthemes ' for folder in 'persona_footer' 'persona_header' root os path join settings TMP_PATH folder if not os path exists root continuefor path in os listdir root full_path os path join root path age time time - os stat full_path... | 77 |
python-test-6573 | python | What does the code get ? | a namespaces list | @log calldef metadef namespace get all context marker None limit None sort key 'created at' sort dir 'desc' filters None resource types filters get 'resource types' [] if filters else [] visibility filters get 'visibility' None if filters else None namespaces []for namespace in DATA['metadef namespaces'] if not is name... | @log_calldef metadef_namespace_get_all context marker None limit None sort_key 'created_at' sort_dir 'desc' filters None resource_types filters get 'resource_types' [] if filters else [] visibility filters get 'visibility' None if filters else None namespaces []for namespace in DATA['metadef_namespaces'] if not _is_nam... | 83 |
python-test-6575 | python | What does the code start ? | all instances for the given version of the server | def start server server version req servers service pb Start Server Request req set server server req set version version resp servers service pb Start Server Response try apiproxy stub map Make Sync Call 'servers' ' Start Server' req resp except apiproxy errors Application Error as e if e application error servers ser... | def start_server server version req servers_service_pb StartServerRequest req set_server server req set_version version resp servers_service_pb StartServerResponse try apiproxy_stub_map MakeSyncCall 'servers' 'StartServer' req resp except apiproxy_errors ApplicationError as e if e application_error servers_service_pb S... | 97 |
python-test-6576 | python | What does the code create ? | a copy of _ _ salt _ _ dictionary with module | def split module dicts if not isinstance salt dict return salt mod dict dict salt for module func name mod fun in six iteritems mod dict copy mod fun module func name split ' ' 1 if mod not in mod dict mod dict[mod] lambda None setattr mod dict[mod] fun mod fun return mod dict | def _split_module_dicts if not isinstance __salt__ dict return __salt__mod_dict dict __salt__ for module_func_name mod_fun in six iteritems mod_dict copy mod fun module_func_name split ' ' 1 if mod not in mod_dict mod_dict[mod] lambda None setattr mod_dict[mod] fun mod_fun return mod_dict | 55 |
python-test-6577 | python | What does the code create ? | an iprovisioner for provisioning nodes on aws ec2 | def aws provisioner access key secret access token keyname region zone security groups instance type 'm 3 large' session token None conn connect to region region aws access key id access key aws secret access key secret access token security token session token if conn is None raise Value Error ' Invalidregion {}' form... | def aws_provisioner access_key secret_access_token keyname region zone security_groups instance_type 'm3 large' session_token None conn connect_to_region region aws_access_key_id access_key aws_secret_access_key secret_access_token security_token session_token if conn is None raise ValueError 'Invalidregion {}' format ... | 72 |
python-test-6581 | python | What does the code flip together ? | the axises of multiple images | def flip axis multi x axis is random False if is random factor np random uniform -1 1 if factor > 0 results []for data in x data np asarray data swapaxes axis 0 data data[ -1 ]data data swapaxes 0 axis results append data return np asarray results else return np asarray x else results []for data in x data np asarray da... | def flip_axis_multi x axis is_random False if is_random factor np random uniform -1 1 if factor > 0 results []for data in x data np asarray data swapaxes axis 0 data data[ -1 ]data data swapaxes 0 axis results append data return np asarray results else return np asarray x else results []for data in x data np asarray da... | 82 |
python-test-6582 | python | What does the code begin ? | initialization of review board | def initialize import loggingimport osimport settings localos environ['RBSITE PYTHONPATH'] os path dirname settings local file from Crypto import Randomfrom django conf import settingsfrom django db import Database Errorfrom djblets import logfrom djblets cache serials import generate ajax serialfrom reviewboard import... | def initialize import loggingimport osimport settings_localos environ['RBSITE_PYTHONPATH'] os path dirname settings_local __file__ from Crypto import Randomfrom django conf import settingsfrom django db import DatabaseErrorfrom djblets import logfrom djblets cache serials import generate_ajax_serialfrom reviewboard imp... | 129 |
python-test-6583 | python | How are files approved ? | using the correct review type | def test approve addons approve files use case mozilla user addon file 1 file 2 review type use caseapprove addons approve files [ file 1 review type file 2 review type ] assert file 1 reload status amo STATUS PUBLIC assert file 2 reload status amo STATUS PUBLIC logs Addon Log objects filter addon addon assert len logs... | def test_approve_addons_approve_files use_case mozilla_user addon file1 file2 review_type use_caseapprove_addons approve_files [ file1 review_type file2 review_type ] assert file1 reload status amo STATUS_PUBLIC assert file2 reload status amo STATUS_PUBLIC logs AddonLog objects filter addon addon assert len logs 2 file... | 105 |
python-test-6584 | python | What does the code run ? | the quickstart - web | def quickstart generator war path sdk root None if not sdk root sdk root SDK ROO Tquickstart xml path os path join war path 'WEB-INF' 'quickstart-web xml' if os path exists quickstart xml path os remove quickstart xml path java home exec suffix java utils Java Home And Suffix java command os path join java home 'bin' '... | def quickstart_generator war_path sdk_root None if not sdk_root sdk_root _SDK_ROOTquickstart_xml_path os path join war_path 'WEB-INF' 'quickstart-web xml' if os path exists quickstart_xml_path os remove quickstart_xml_path java_home exec_suffix java_utils JavaHomeAndSuffix java_command os path join java_home 'bin' 'jav... | 108 |
python-test-6585 | python | What does function create ? | an oauth client | def get oauth client server token url client id client secret if not is valid url server token url returnclient Backend Application Client client id client id oauth ccxcon O Auth 2 Session client client oauth ccxcon fetch token token url server token url client id client id client secret client secret timeout CCXCON RE... | def get_oauth_client server_token_url client_id client_secret if not is_valid_url server_token_url returnclient BackendApplicationClient client_id client_id oauth_ccxcon OAuth2Session client client oauth_ccxcon fetch_token token_url server_token_url client_id client_id client_secret client_secret timeout CCXCON_REQUEST... | 59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.