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-2203
python
What converts into unix epoch time ?
time specified in a variety of forms
def time to epoch t if isinstance t int return telif isinstance t tuple or isinstance t time struct time return int time mktime t elif hasattr t 'timetuple' return int time mktime t timetuple elif hasattr t 'strftime' return int t strftime '%s' elif isinstance t str or isinstance t unicode try if t startswith '+' retur...
def time_to_epoch t if isinstance t int return telif isinstance t tuple or isinstance t time struct_time return int time mktime t elif hasattr t 'timetuple' return int time mktime t timetuple elif hasattr t 'strftime' return int t strftime '%s' elif isinstance t str or isinstance t unicode try if t startswith '+' retur...
104
python-test-2204
python
What do time specified in a variety of forms convert ?
into unix epoch time
def time to epoch t if isinstance t int return telif isinstance t tuple or isinstance t time struct time return int time mktime t elif hasattr t 'timetuple' return int time mktime t timetuple elif hasattr t 'strftime' return int t strftime '%s' elif isinstance t str or isinstance t unicode try if t startswith '+' retur...
def time_to_epoch t if isinstance t int return telif isinstance t tuple or isinstance t time struct_time return int time mktime t elif hasattr t 'timetuple' return int time mktime t timetuple elif hasattr t 'strftime' return int t strftime '%s' elif isinstance t str or isinstance t unicode try if t startswith '+' retur...
104
python-test-2208
python
How does the code retrieve the creditprovider model data ?
against provided credit provider
def get credit provider info request provider id credit provider Credit Provider get credit provider provider id provider id credit provider data {}if credit provider credit provider data {'provider id' credit provider provider id 'display name' credit provider display name 'provider url' credit provider provider url '...
def get_credit_provider_info request provider_id credit_provider CreditProvider get_credit_provider provider_id provider_id credit_provider_data {}if credit_provider credit_provider_data {'provider_id' credit_provider provider_id 'display_name' credit_provider display_name 'provider_url' credit_provider provider_url 'p...
83
python-test-2209
python
What does the code retrieve against provided credit provider ?
the creditprovider model data
def get credit provider info request provider id credit provider Credit Provider get credit provider provider id provider id credit provider data {}if credit provider credit provider data {'provider id' credit provider provider id 'display name' credit provider display name 'provider url' credit provider provider url '...
def get_credit_provider_info request provider_id credit_provider CreditProvider get_credit_provider provider_id provider_id credit_provider_data {}if credit_provider credit_provider_data {'provider_id' credit_provider provider_id 'display_name' credit_provider display_name 'provider_url' credit_provider provider_url 'p...
83
python-test-2211
python
How do operation stream ?
semi
def join leftkey leftseq rightkey rightseq left default no default right default no default if not callable leftkey leftkey getter leftkey if not callable rightkey rightkey getter rightkey d groupby leftkey leftseq seen keys set left default is no default left default no default for item in rightseq key rightkey item s...
def join leftkey leftseq rightkey rightseq left_default no_default right_default no_default if not callable leftkey leftkey getter leftkey if not callable rightkey rightkey getter rightkey d groupby leftkey leftseq seen_keys set left_default_is_no_default left_default no_default for item in rightseq key rightkey item s...
105
python-test-2221
python
What does the code ensure ?
that attempting to write sequences with duplicate ids after truncation fails for phylip format
def check phylip reject duplicate handle String IO sequences [ Seq Record Seq 'AAAA' id 'longsequencename 1 ' Seq Record Seq 'AAAA' id 'longsequencename 2 ' Seq Record Seq 'AAAA' id 'other sequence' ]alignment Multiple Seq Alignment sequences try Align IO write alignment handle 'phylip' assert False ' Duplicate I Dsaft...
def check_phylip_reject_duplicate handle StringIO sequences [SeqRecord Seq 'AAAA' id 'longsequencename1' SeqRecord Seq 'AAAA' id 'longsequencename2' SeqRecord Seq 'AAAA' id 'other_sequence' ]alignment MultipleSeqAlignment sequences try AlignIO write alignment handle 'phylip' assert False 'DuplicateIDsaftertruncationare...
62
python-test-2224
python
What is recalculating in postgres ?
user disk usage
def pgcalc sa session id dryrun False sql calc 'SELECTCOALESCE SUM total size 0 \n FROM SELECTDISTINCTON d id d total size d id\n FRO Mhistory dataset associationhda\n JOI Nhistoryh O Nh id hda history id\n JOI Ndatasetd O Nhda dataset id d id\n WHER Eh user id id\n AN Dh purged false\n AN Dhda purged false\n AN Dd pur...
def pgcalc sa_session id dryrun False sql_calc 'SELECTCOALESCE SUM total_size 0 \nFROM SELECTDISTINCTON d id d total_size d id\nFROMhistory_dataset_associationhda\nJOINhistoryhONh id hda history_id\nJOINdatasetdONhda dataset_id d id\nWHEREh user_id id\nANDh purged false\nANDhda purged false\nANDd purged false\nANDd idN...
118
python-test-2225
python
Where do user disk usage recalculate quickly ?
in postgres
def pgcalc sa session id dryrun False sql calc 'SELECTCOALESCE SUM total size 0 \n FROM SELECTDISTINCTON d id d total size d id\n FRO Mhistory dataset associationhda\n JOI Nhistoryh O Nh id hda history id\n JOI Ndatasetd O Nhda dataset id d id\n WHER Eh user id id\n AN Dh purged false\n AN Dhda purged false\n AN Dd pur...
def pgcalc sa_session id dryrun False sql_calc 'SELECTCOALESCE SUM total_size 0 \nFROM SELECTDISTINCTON d id d total_size d id\nFROMhistory_dataset_associationhda\nJOINhistoryhONh id hda history_id\nJOINdatasetdONhda dataset_id d id\nWHEREh user_id id\nANDh purged false\nANDhda purged false\nANDd purged false\nANDd idN...
118
python-test-2228
python
What does the code ensure ?
service present in keystone catalog name the name of the service service_type the type of openstack service description description of the service
def service present name service type description None profile None **connection args ret {'name' name 'changes' {} 'result' True 'comment' ' Service"{ 0 }"alreadyexists' format name }role salt ['keystone service get'] name name profile profile **connection args if ' Error' not in role return retelse if opts get 'test'...
def service_present name service_type description None profile None **connection_args ret {'name' name 'changes' {} 'result' True 'comment' 'Service"{0}"alreadyexists' format name }role __salt__['keystone service_get'] name name profile profile **connection_args if 'Error' not in role return retelse if __opts__ get 'te...
83
python-test-2230
python
What is deciding what is to be updated when ?
modify_replication_group
def diff replication group current desired if current get ' Automatic Failover' is not None current[' Automatic Failover Enabled'] True if current[' Automatic Failover'] in 'enabled' 'enabling' else False modifiable {' Automatic Failover Enabled' ' Automatic Failover Enabled' ' Auto Minor Version Upgrade' None ' Cache ...
def _diff_replication_group current desired if current get 'AutomaticFailover' is not None current['AutomaticFailoverEnabled'] True if current['AutomaticFailover'] in 'enabled' 'enabling' else False modifiable {'AutomaticFailoverEnabled' 'AutomaticFailoverEnabled' 'AutoMinorVersionUpgrade' None 'CacheNodeType' None 'Ca...
146
python-test-2231
python
What do you enhance ?
what modify_replication_group ( ) considers when deciding what is to be updated
def diff replication group current desired if current get ' Automatic Failover' is not None current[' Automatic Failover Enabled'] True if current[' Automatic Failover'] in 'enabled' 'enabling' else False modifiable {' Automatic Failover Enabled' ' Automatic Failover Enabled' ' Auto Minor Version Upgrade' None ' Cache ...
def _diff_replication_group current desired if current get 'AutomaticFailover' is not None current['AutomaticFailoverEnabled'] True if current['AutomaticFailover'] in 'enabled' 'enabling' else False modifiable {'AutomaticFailoverEnabled' 'AutomaticFailoverEnabled' 'AutoMinorVersionUpgrade' None 'CacheNodeType' None 'Ca...
146
python-test-2232
python
What does you need ?
to enhance what modify_replication_group ( ) considers when deciding what is to be updated
def diff replication group current desired if current get ' Automatic Failover' is not None current[' Automatic Failover Enabled'] True if current[' Automatic Failover'] in 'enabled' 'enabling' else False modifiable {' Automatic Failover Enabled' ' Automatic Failover Enabled' ' Auto Minor Version Upgrade' None ' Cache ...
def _diff_replication_group current desired if current get 'AutomaticFailover' is not None current['AutomaticFailoverEnabled'] True if current['AutomaticFailover'] in 'enabled' 'enabling' else False modifiable {'AutomaticFailoverEnabled' 'AutomaticFailoverEnabled' 'AutoMinorVersionUpgrade' None 'CacheNodeType' None 'Ca...
146
python-test-2233
python
Where are the code restricted the points ?
at a distance lower than radius
def radius neighbors graph X radius mode 'connectivity' metric 'minkowski' p 2 metric params None include self False n jobs 1 if not isinstance X Radius Neighbors Mixin X Nearest Neighbors radius radius metric metric p p metric params metric params n jobs n jobs fit X else check params X metric p metric params query qu...
def radius_neighbors_graph X radius mode 'connectivity' metric 'minkowski' p 2 metric_params None include_self False n_jobs 1 if not isinstance X RadiusNeighborsMixin X NearestNeighbors radius radius metric metric p p metric_params metric_params n_jobs n_jobs fit X else _check_params X metric p metric_params query _que...
70
python-test-2234
python
What does the code take if it is coming from public ip space ?
a /proc / net / tcp encoded src or dest string return true
def is public ip ipstr addr ipstr split ' ' [0 ]addr int addr 16 byte 1 addr & 255 byte 2 addr >> 8 & 255 if byte 1 in 10 0 127 return Falseif byte 1 172 and byte 2 > 16 return Falseif byte 1 192 and byte 2 168 return Falsereturn True
def is_public_ip ipstr addr ipstr split ' ' [0]addr int addr 16 byte1 addr & 255 byte2 addr >> 8 & 255 if byte1 in 10 0 127 return Falseif byte1 172 and byte2 > 16 return Falseif byte1 192 and byte2 168 return Falsereturn True
56
python-test-2235
python
What does mako filter resolve to its name on disk ?
a human - readable asset path
def webpack asset path asset paths asset paths debug settings DEBUG MODE if not asset paths logger warn 'webpack-assets jsonhasnotyetbeengenerated Fallingbacktonon-cache-bustedassets' return pathif not debug key path replace base static path '' replace ' js' '' hash path asset paths[key]return os path join base static ...
def webpack_asset path asset_paths asset_paths debug settings DEBUG_MODE if not asset_paths logger warn 'webpack-assets jsonhasnotyetbeengenerated Fallingbacktonon-cache-bustedassets' return pathif not debug key path replace base_static_path '' replace ' js' '' hash_path asset_paths[key]return os path join base_static_...
51
python-test-2236
python
What does a helper function take ?
a sort string eg name asc
def unpick search sort allowed fields None total None sorts []split sort sort split ' ' for part in split sort split part part strip split field split part[ 0 ]if len split part > 1 order split part[ 1 ] lower else order 'asc'if allowed fields if field not in allowed fields raise Validation Error ' Cannotsortbyfield`%s...
def _unpick_search sort allowed_fields None total None sorts []split_sort sort split ' ' for part in split_sort split_part part strip split field split_part[0]if len split_part > 1 order split_part[1] lower else order 'asc'if allowed_fields if field not in allowed_fields raise ValidationError 'Cannotsortbyfield`%s`' % ...
93
python-test-2243
python
What does the code get into a reasonable state for installation ?
any system
def ensure minimal setup package manager if package manager in 'dnf' 'yum' return run network interacting from args ['su' 'root' '-c' [package manager '-y' 'install' 'sudo']] elif package manager 'apt' return sequence [run network interacting from args ['su' 'root' '-c' ['apt-get' 'update']] run network interacting fro...
def ensure_minimal_setup package_manager if package_manager in 'dnf' 'yum' return run_network_interacting_from_args ['su' 'root' '-c' [package_manager '-y' 'install' 'sudo']] elif package_manager 'apt' return sequence [run_network_interacting_from_args ['su' 'root' '-c' ['apt-get' 'update']] run_network_interacting_fro...
59
python-test-2245
python
What do whites lagrange ?
multiplier test for heteroscedasticity parameters
def het white resid exog retres False x np asarray exog y np asarray resid if x ndim 1 raise Value Error 'xshouldhaveconstantandatleastonemorevariable' nobs nvars 0 x shape i0 i1 np triu indices nvars 0 exog x[ i0 ] * x[ i1 ] nobs nvars exog shapeassert nvars nvars 0 * nvars 0 - 1 / 2 0 + nvars 0 resols OLS y ** 2 exog...
def het_white resid exog retres False x np asarray exog y np asarray resid if x ndim 1 raise ValueError 'xshouldhaveconstantandatleastonemorevariable' nobs nvars0 x shape i0 i1 np triu_indices nvars0 exog x[ i0] * x[ i1] nobs nvars exog shapeassert nvars nvars0 * nvars0 - 1 / 2 0 + nvars0 resols OLS y ** 2 exog fit fva...
102
python-test-2246
python
What lagrange multiplier test for heteroscedasticity parameters ?
whites
def het white resid exog retres False x np asarray exog y np asarray resid if x ndim 1 raise Value Error 'xshouldhaveconstantandatleastonemorevariable' nobs nvars 0 x shape i0 i1 np triu indices nvars 0 exog x[ i0 ] * x[ i1 ] nobs nvars exog shapeassert nvars nvars 0 * nvars 0 - 1 / 2 0 + nvars 0 resols OLS y ** 2 exog...
def het_white resid exog retres False x np asarray exog y np asarray resid if x ndim 1 raise ValueError 'xshouldhaveconstantandatleastonemorevariable' nobs nvars0 x shape i0 i1 np triu_indices nvars0 exog x[ i0] * x[ i1] nobs nvars exog shapeassert nvars nvars0 * nvars0 - 1 / 2 0 + nvars0 resols OLS y ** 2 exog fit fva...
102
python-test-2249
python
What does the code ensure ?
that the named index template is present
def present name definition None if definition is None definition {}ret {'name' name 'changes' {} 'result' True 'comment' ''}index template exists salt ['elasticsearch index template exists'] name name if not index template exists if opts ['test'] ret['comment'] ' Indextemplate{ 0 }willbecreated' format name ret['resul...
def present name definition None if definition is None definition {}ret {'name' name 'changes' {} 'result' True 'comment' ''}index_template_exists __salt__['elasticsearch index_template_exists'] name name if not index_template_exists if __opts__['test'] ret['comment'] 'Indextemplate{0}willbecreated' format name ret['re...
88
python-test-2251
python
What does the code execute ?
a function from the webadministration ps module
def srvmgr func as json False command ' Import- Module Web Administration 'if as json command '{ 0 } Convert To- Json- Compress- Depth 4 - Input Object@ {1 } ' format command func else command '{ 0 }{ 1 }' format command func cmd ret salt ['cmd run all'] command shell 'powershell' python shell True if cmd ret['retcode'...
def _srvmgr func as_json False command 'Import-ModuleWebAdministration 'if as_json command '{0}ConvertTo-Json-Compress-Depth4-InputObject@ {1} ' format command func else command '{0}{1}' format command func cmd_ret __salt__['cmd run_all'] command shell 'powershell' python_shell True if cmd_ret['retcode'] 0 _LOG error '...
73
python-test-2255
python
What has tag field already defined ?
the taggeditembase class
def tags for cls model instance None **extra filters kwargs extra filters or {} if instance is not None kwargs update { '%s content object' % cls tag relname instance} return cls tag model objects filter **kwargs kwargs update { '%s content object isnull' % cls tag relname False} return cls tag model objects filter **k...
def tags_for cls model instance None **extra_filters kwargs extra_filters or {} if instance is not None kwargs update { '%s__content_object' % cls tag_relname instance} return cls tag_model objects filter **kwargs kwargs update { '%s__content_object__isnull' % cls tag_relname False} return cls tag_model objects filter ...
57
python-test-2256
python
What does the taggeditembase class have ?
tag field already defined
def tags for cls model instance None **extra filters kwargs extra filters or {} if instance is not None kwargs update { '%s content object' % cls tag relname instance} return cls tag model objects filter **kwargs kwargs update { '%s content object isnull' % cls tag relname False} return cls tag model objects filter **k...
def tags_for cls model instance None **extra_filters kwargs extra_filters or {} if instance is not None kwargs update { '%s__content_object' % cls tag_relname instance} return cls tag_model objects filter **kwargs kwargs update { '%s__content_object__isnull' % cls tag_relname False} return cls tag_model objects filter ...
57
python-test-2257
python
What does the code render against defined variables ?
all string elements of the config
@event u'manager before config validate' def process variables config manager env params {u'block start string' u'^^disabled^^' u'block end string' u'^^disabled^^' u'variable start string' u'{?' u'variable end string' u'?}'}if u'variables' not in config or config get u'variables' is False returnenv Environment **env pa...
@event u'manager before_config_validate' def process_variables config manager env_params {u'block_start_string' u'^^disabled^^' u'block_end_string' u'^^disabled^^' u'variable_start_string' u'{?' u'variable_end_string' u'?}'}if u'variables' not in config or config get u'variables' is False returnenv Environment **env_pa...
83
python-test-2259
python
What will a function produce when called with dictionary of arguments ?
a kwarg that s compatible with the supplied function
def generate accepted kwargs function *named arguments if hasattr function ' code ' and takes kwargs function function takes kwargs Truefunction takes arguments []else function takes kwargs Falsefunction takes arguments takes arguments function *named arguments def accepted kwargs kwargs if function takes kwargs return...
def generate_accepted_kwargs function *named_arguments if hasattr function '__code__' and takes_kwargs function function_takes_kwargs Truefunction_takes_arguments []else function_takes_kwargs Falsefunction_takes_arguments takes_arguments function *named_arguments def accepted_kwargs kwargs if function_takes_kwargs retu...
68
python-test-2260
python
When will a function produce a kwarg that s compatible with the supplied function ?
when called with dictionary of arguments
def generate accepted kwargs function *named arguments if hasattr function ' code ' and takes kwargs function function takes kwargs Truefunction takes arguments []else function takes kwargs Falsefunction takes arguments takes arguments function *named arguments def accepted kwargs kwargs if function takes kwargs return...
def generate_accepted_kwargs function *named_arguments if hasattr function '__code__' and takes_kwargs function function_takes_kwargs Truefunction_takes_arguments []else function_takes_kwargs Falsefunction_takes_arguments takes_arguments function *named_arguments def accepted_kwargs kwargs if function_takes_kwargs retu...
68
python-test-2261
python
What are dropped where ?
missing observations
def drop missing Y X None axis 1 Y np asarray Y if Y ndim 1 Y Y[ None]if X is not None X np array X if X ndim 1 X X[ None]keepidx np logical and ~ np isnan Y any axis ~ np isnan X any axis return Y[keepidx] X[keepidx] else keepidx ~ np isnan Y any axis return Y[keepidx]
def drop_missing Y X None axis 1 Y np asarray Y if Y ndim 1 Y Y[ None]if X is not None X np array X if X ndim 1 X X[ None]keepidx np logical_and ~ np isnan Y any axis ~ np isnan X any axis return Y[keepidx] X[keepidx] else keepidx ~ np isnan Y any axis return Y[keepidx]
62
python-test-2262
python
What returns where missing observations are dropped ?
views on the arrays y and x
def drop missing Y X None axis 1 Y np asarray Y if Y ndim 1 Y Y[ None]if X is not None X np array X if X ndim 1 X X[ None]keepidx np logical and ~ np isnan Y any axis ~ np isnan X any axis return Y[keepidx] X[keepidx] else keepidx ~ np isnan Y any axis return Y[keepidx]
def drop_missing Y X None axis 1 Y np asarray Y if Y ndim 1 Y Y[ None]if X is not None X np array X if X ndim 1 X X[ None]keepidx np logical_and ~ np isnan Y any axis ~ np isnan X any axis return Y[keepidx] X[keepidx] else keepidx ~ np isnan Y any axis return Y[keepidx]
62
python-test-2263
python
Where does views on the arrays y and x return ?
where missing observations are dropped
def drop missing Y X None axis 1 Y np asarray Y if Y ndim 1 Y Y[ None]if X is not None X np array X if X ndim 1 X X[ None]keepidx np logical and ~ np isnan Y any axis ~ np isnan X any axis return Y[keepidx] X[keepidx] else keepidx ~ np isnan Y any axis return Y[keepidx]
def drop_missing Y X None axis 1 Y np asarray Y if Y ndim 1 Y Y[ None]if X is not None X np array X if X ndim 1 X X[ None]keepidx np logical_and ~ np isnan Y any axis ~ np isnan X any axis return Y[keepidx] X[keepidx] else keepidx ~ np isnan Y any axis return Y[keepidx]
62
python-test-2272
python
What does the code create ?
a url for the page where the request token can be authorized
def generate oauth authorization url token next None hd DEFAULT DOMAIN hl None btmpl None auth server OAUTH AUTHORIZE URL uri atom http core Uri parse uri auth server uri query['oauth token'] tokenuri query['hd'] hdif next is not None uri query['oauth callback'] str next if hl is not None uri query['hl'] hlif btmpl is ...
def generate_oauth_authorization_url token next None hd DEFAULT_DOMAIN hl None btmpl None auth_server OAUTH_AUTHORIZE_URL uri atom http_core Uri parse_uri auth_server uri query['oauth_token'] tokenuri query['hd'] hdif next is not None uri query['oauth_callback'] str next if hl is not None uri query['hl'] hlif btmpl is ...
60
python-test-2274
python
What does the code get ?
user icons for module setup page
def get user icons user user perms User Permissions user user perms build permissions from frappe boot import get allowed pagesallowed pages get allowed pages icons []for icon in get desktop icons user add Trueif icon hidden in standard add Falseif not icon custom if icon module name u' Learn' passelif icon type u'page...
def get_user_icons user user_perms UserPermissions user user_perms build_permissions from frappe boot import get_allowed_pagesallowed_pages get_allowed_pages icons []for icon in get_desktop_icons user add Trueif icon hidden_in_standard add Falseif not icon custom if icon module_name u'Learn' passelif icon type u'page' ...
84
python-test-2279
python
What does the code build ?
a model instance
def build instance Model data db obj Model **data if obj pk is None and hasattr Model 'natural key' and hasattr Model default manager 'get by natural key' natural key obj natural key try obj pk Model default manager db manager db get by natural key *natural key pkexcept Model Does Not Exist passreturn obj
def build_instance Model data db obj Model **data if obj pk is None and hasattr Model 'natural_key' and hasattr Model _default_manager 'get_by_natural_key' natural_key obj natural_key try obj pk Model _default_manager db_manager db get_by_natural_key *natural_key pkexcept Model DoesNotExist passreturn obj
55
python-test-2283
python
What do a string represent ?
the tasks age limit
def Parse Task Age Limit age limit age limit age limit strip if not age limit raise Malformed Queue Configuration ' Task Age Limitmustnotbeempty ' unit age limit[ -1 ]if unit not in 'smhd' raise Malformed Queue Configuration ' Task Age Limitmustbeins seconds m minutes h hours ord days ' try number float age limit[ 0 -1...
def ParseTaskAgeLimit age_limit age_limit age_limit strip if not age_limit raise MalformedQueueConfiguration 'TaskAgeLimitmustnotbeempty ' unit age_limit[ -1 ]if unit not in 'smhd' raise MalformedQueueConfiguration 'TaskAge_Limitmustbeins seconds m minutes h hours ord days ' try number float age_limit[0 -1 ] if unit 's...
103
python-test-2284
python
What do an ipac table have ?
invalid metadata stored in the top - level metadata
def test write invalid toplevel meta ipac table ascii get reader Reader ascii Ipac data table read 't/no data ipac dat' data meta['blah'] 'extra'with catch warnings Astropy Warning as A Swarn out String IO data write out format 'ascii ipac' assert len A Swarn 1 assert 'werenotwritten' in str A Swarn[ 0 ] message
def test_write_invalid_toplevel_meta_ipac table ascii get_reader Reader ascii Ipac data table read 't/no_data_ipac dat' data meta['blah'] 'extra'with catch_warnings AstropyWarning as ASwarn out StringIO data write out format 'ascii ipac' assert len ASwarn 1 assert 'werenotwritten' in str ASwarn[0] message
54
python-test-2285
python
What has the code write ?
an ipac table that contains no data but has invalid metadata stored in the top - level metadata and therefore should raise a warning
def test write invalid toplevel meta ipac table ascii get reader Reader ascii Ipac data table read 't/no data ipac dat' data meta['blah'] 'extra'with catch warnings Astropy Warning as A Swarn out String IO data write out format 'ascii ipac' assert len A Swarn 1 assert 'werenotwritten' in str A Swarn[ 0 ] message
def test_write_invalid_toplevel_meta_ipac table ascii get_reader Reader ascii Ipac data table read 't/no_data_ipac dat' data meta['blah'] 'extra'with catch_warnings AstropyWarning as ASwarn out StringIO data write out format 'ascii ipac' assert len ASwarn 1 assert 'werenotwritten' in str ASwarn[0] message
54
python-test-2286
python
Where did invalid metadata store ?
in the top - level metadata
def test write invalid toplevel meta ipac table ascii get reader Reader ascii Ipac data table read 't/no data ipac dat' data meta['blah'] 'extra'with catch warnings Astropy Warning as A Swarn out String IO data write out format 'ascii ipac' assert len A Swarn 1 assert 'werenotwritten' in str A Swarn[ 0 ] message
def test_write_invalid_toplevel_meta_ipac table ascii get_reader Reader ascii Ipac data table read 't/no_data_ipac dat' data meta['blah'] 'extra'with catch_warnings AstropyWarning as ASwarn out StringIO data write out format 'ascii ipac' assert len ASwarn 1 assert 'werenotwritten' in str ASwarn[0] message
54
python-test-2291
python
How do lapack type match ?
best
def find best blas type arrays dtype None dtype np dtype dtype prefer fortran Falseif arrays dtypes [ar dtype for ar in arrays]dtype np find common type dtypes try index dtypes index dtype except Value Error index 0if arrays[index] flags['FORTRAN'] prefer fortran Trueprefix type conv get dtype char 'd' if dtype char 'G...
def find_best_blas_type arrays dtype None dtype _np dtype dtype prefer_fortran Falseif arrays dtypes [ar dtype for ar in arrays]dtype _np find_common_type dtypes try index dtypes index dtype except ValueError index 0if arrays[index] flags['FORTRAN'] prefer_fortran Trueprefix _type_conv get dtype char 'd' if dtype char ...
73
python-test-2292
python
How do classification check on dataset iris ?
by average probabilities
def test weights iris clf 1 Logistic Regression random state 123 clf 2 Random Forest Classifier random state 123 clf 3 Gaussian NB eclf Voting Classifier estimators [ 'lr' clf 1 'rf' clf 2 'gnb' clf 3 ] voting 'soft' weights [1 2 10 ] scores cross val score eclf X y cv 5 scoring 'accuracy' assert almost equal scores me...
def test_weights_iris clf1 LogisticRegression random_state 123 clf2 RandomForestClassifier random_state 123 clf3 GaussianNB eclf VotingClassifier estimators [ 'lr' clf1 'rf' clf2 'gnb' clf3 ] voting 'soft' weights [1 2 10] scores cross_val_score eclf X y cv 5 scoring 'accuracy' assert_almost_equal scores mean 0 93 deci...
65
python-test-2295
python
What does the code require ?
a directory to exist
def directory path use sudo False owner '' group '' mode '' func use sudo and run as root or run if not is dir path func 'mkdir-p"% path s"' % locals if owner and owner path use sudo owner or group and group path use sudo group func 'chown% owner s % group s"% path s"' % locals if mode and mode path use sudo mode func ...
def directory path use_sudo False owner '' group '' mode '' func use_sudo and run_as_root or run if not is_dir path func 'mkdir-p"% path s"' % locals if owner and _owner path use_sudo owner or group and _group path use_sudo group func 'chown% owner s % group s"% path s"' % locals if mode and _mode path use_sudo mode fu...
75
python-test-2296
python
How does the code take a query ?
in the form of a key / value pair separated by a colon
def parse query part part query classes {} prefixes {} default class query Substring Query part part strip match PARSE QUERY PART REGEX match part assert matchkey match group 1 term match group 2 replace '\\ ' ' ' for pre query class in prefixes items if term startswith pre return key term[len pre ] query class query c...
def parse_query_part part query_classes {} prefixes {} default_class query SubstringQuery part part strip match PARSE_QUERY_PART_REGEX match part assert matchkey match group 1 term match group 2 replace '\\ ' ' ' for pre query_class in prefixes items if term startswith pre return key term[len pre ] query_class query_cl...
70
python-test-2301
python
What does a function format ?
the output of cmd
@skip if on windows@pytest mark parametrize 'cmd fmt exp' [ 'pwd' None lambda os getcwd + '\n' 'echo WORKING' None 'WORKING\n' 'ls-f' lambda out out splitlines sort os listdir sort ] def test single command cmd fmt exp out err rtn run xonsh cmd stderr sp DEVNULL if callable fmt out fmt out if callable exp exp exp asser...
@skip_if_on_windows@pytest mark parametrize 'cmd fmt exp' [ 'pwd' None lambda os getcwd + '\n' 'echoWORKING' None 'WORKING\n' 'ls-f' lambda out out splitlines sort os listdir sort ] def test_single_command cmd fmt exp out err rtn run_xonsh cmd stderr sp DEVNULL if callable fmt out fmt out if callable exp exp exp assert...
64
python-test-2302
python
What do test add to outer scope ?
new components
def test merge new merge log err packages {'pack 1' {'light' [{'platform' 'one'}]} 'pack 11 ' {'input select' {'ib 1 ' None}} 'pack 2' {'light' {'platform' 'one'} 'panel custom' {'pan 1 ' None} 'api' {}}}config {config util CONF CORE {config util CONF PACKAGES packages}}config util merge packages config config packages...
def test_merge_new merge_log_err packages {'pack_1' {'light' [{'platform' 'one'}]} 'pack_11' {'input_select' {'ib1' None}} 'pack_2' {'light' {'platform' 'one'} 'panel_custom' {'pan1' None} 'api' {}}}config {config_util CONF_CORE {config_util CONF_PACKAGES packages}}config_util merge_packages_config config packages asse...
74
python-test-2307
python
What is having the specified property value ?
the first managed object reference
def get mor by property service instance object type property value property name 'name' container ref None object list get mors with properties service instance object type property list [property name] container ref container ref for obj in object list obj id str obj get 'object' '' strip '\'"' if obj[property name] ...
def get_mor_by_property service_instance object_type property_value property_name 'name' container_ref None object_list get_mors_with_properties service_instance object_type property_list [property_name] container_ref container_ref for obj in object_list obj_id str obj get 'object' '' strip '\'"' if obj[property_name] ...
62
python-test-2308
python
What do the first managed object reference have ?
the specified property value
def get mor by property service instance object type property value property name 'name' container ref None object list get mors with properties service instance object type property list [property name] container ref container ref for obj in object list obj id str obj get 'object' '' strip '\'"' if obj[property name] ...
def get_mor_by_property service_instance object_type property_value property_name 'name' container_ref None object_list get_mors_with_properties service_instance object_type property_list [property_name] container_ref container_ref for obj in object_list obj_id str obj get 'object' '' strip '\'"' if obj[property_name] ...
62
python-test-2309
python
How do item add ?
with preselected type
@treeio login required@handle response formatdef item add typed request type id response format 'html' item type get object or 404 Item Type pk type id if not request user profile has permission item type mode 'x' return user denied request message " Youdon'thaveaccesstocreate" + unicode item type response format respo...
@treeio_login_required@handle_response_formatdef item_add_typed request type_id response_format 'html' item_type get_object_or_404 ItemType pk type_id if not request user profile has_permission item_type mode 'x' return user_denied request message "Youdon'thaveaccesstocreate" + unicode item_type response_format respons...
139
python-test-2311
python
What does the code get ?
package name for a module
@positional 1 def get package for module module if isinstance module basestring try module sys modules[module]except Key Error return Nonetry return unicode module package except Attribute Error if module name ' main ' try file name module file except Attribute Error passelse base name os path basename file name split ...
@positional 1 def get_package_for_module module if isinstance module basestring try module sys modules[module]except KeyError return Nonetry return unicode module package except AttributeError if module __name__ '__main__' try file_name module __file__except AttributeError passelse base_name os path basename file_name ...
78
python-test-2312
python
For what purpose does the code hydrate an index - field option value ?
to construct something like : : index_field : { doubleoptions : { defaultvalue : 0
def index hydrate params container cli type key value if ' Index Field' not in params params[' Index Field'] {}if ' Index Field Type' not in params[' Index Field'] raise Runtime Error ' Youmustpassthe--typeoption ' type params[' Index Field'][' Index Field Type'] type '' join [i capitalize for i in type split '-' ] if ...
def index_hydrate params container cli_type key value if 'IndexField' not in params params['IndexField'] {}if 'IndexFieldType' not in params['IndexField'] raise RuntimeError 'Youmustpassthe--typeoption ' _type params['IndexField']['IndexFieldType']_type '' join [i capitalize for i in _type split '-' ] if _type 'Latlon'...
114
python-test-2313
python
What does the code hydrate to construct something like : : index_field : { doubleoptions : { defaultvalue : 0 ?
an index - field option value
def index hydrate params container cli type key value if ' Index Field' not in params params[' Index Field'] {}if ' Index Field Type' not in params[' Index Field'] raise Runtime Error ' Youmustpassthe--typeoption ' type params[' Index Field'][' Index Field Type'] type '' join [i capitalize for i in type split '-' ] if ...
def index_hydrate params container cli_type key value if 'IndexField' not in params params['IndexField'] {}if 'IndexFieldType' not in params['IndexField'] raise RuntimeError 'Youmustpassthe--typeoption ' _type params['IndexField']['IndexFieldType']_type '' join [i capitalize for i in _type split '-' ] if _type 'Latlon'...
114
python-test-2315
python
How do go source file generate ?
by invoking protobuf compiler
def generate proto go source target source env source source[ 0 ]global proto import reimport protos proto import re findall source get text contents parameters 'import prefix %s/' % env['PROTOBUFGOPATH'] if import protos proto mappings []for proto in import protos dir os path dirname proto name os path basename proto ...
def generate_proto_go_source target source env source source[0]global proto_import_reimport_protos proto_import_re findall source get_text_contents parameters 'import_prefix %s/' % env['PROTOBUFGOPATH'] if import_protos proto_mappings []for proto in import_protos dir os path dirname proto name os path basename proto pr...
113
python-test-2316
python
How did strings return ?
by iterable and separated by a space
def fill stmt iterable fill len fill len + 1overflow Noneit iter iterable while True buffer []total len 0if overflow buffer append overflow total len + len overflow + 1 overflow Nonewhile total len < fill len try new item it next buffer append new item total len + len new item + 1 except Stop Iteration if buffer breaki...
def fill_stmt iterable fill_len fill_len + 1overflow Noneit iter iterable while True buffer_ []total_len 0if overflow buffer_ append overflow total_len + len overflow + 1 overflow Nonewhile total_len < fill_len try new_item it next buffer_ append new_item total_len + len new_item + 1 except StopIteration if buffer_ bre...
91
python-test-2320
python
What does the code find ?
href=
def fixup internal links config soups reverse directory {}for d s in config[u'sources'] items reverse directory[s] dfor name soup in soups items old src dir os path dirname config[u'sources'][name] for tag in soup find all True if not u'href' in tag attrs continueold rel path tag[u'href'] split u'#' [0 ]old dst os path...
def fixup_internal_links config soups reverse_directory {}for d s in config[u'sources'] items reverse_directory[s] dfor name soup in soups items old_src_dir os path dirname config[u'sources'][name] for tag in soup find_all True if not u'href' in tag attrs continueold_rel_path tag[u'href'] split u'#' [0]old_dst os path ...
96
python-test-2323
python
How does the code compute the power spectral density ?
using multitapers
@verbosedef psd multitaper inst fmin 0 fmax np inf tmin None tmax None bandwidth None adaptive False low bias True normalization 'length' picks None proj False n jobs 1 verbose None data sfreq check psd data inst tmin tmax picks proj return psd multitaper data sfreq fmin fmin fmax fmax bandwidth bandwidth adaptive adap...
@verbosedef psd_multitaper inst fmin 0 fmax np inf tmin None tmax None bandwidth None adaptive False low_bias True normalization 'length' picks None proj False n_jobs 1 verbose None data sfreq _check_psd_data inst tmin tmax picks proj return _psd_multitaper data sfreq fmin fmin fmax fmax bandwidth bandwidth adaptive ad...
64
python-test-2324
python
What does the code change ?
how matplotlib color shorthands are interpreted
def set color codes palette 'deep' if palette 'reset' colors [ 0 0 0 0 1 0 0 0 0 5 0 0 1 0 0 0 0 0 0 75 0 75 0 0 0 75 0 75 0 0 0 0 0 75 0 75 0 0 0 0 0 0 ]else colors SEABORN PALETTES[palette] + [ 0 1 0 1 0 1 ] for code color in zip 'bgrmyck' colors rgb mpl colors color Converter to rgb color mpl colors color Converter ...
def set_color_codes palette 'deep' if palette 'reset' colors [ 0 0 0 0 1 0 0 0 0 5 0 0 1 0 0 0 0 0 0 75 0 75 0 0 0 75 0 75 0 0 0 0 0 75 0 75 0 0 0 0 0 0 ]else colors SEABORN_PALETTES[palette] + [ 0 1 0 1 0 1 ] for code color in zip 'bgrmyck' colors rgb mpl colors colorConverter to_rgb color mpl colors colorConverter co...
92
python-test-2329
python
What is containing the given node ?
cliques
def cliques containing node G nodes None cliques None if cliques is None cliques list find cliques G if nodes is None nodes list G nodes if not isinstance nodes list v nodesvcliques [c for c in cliques if v in c ]else vcliques {}for v in nodes vcliques[v] [c for c in cliques if v in c ]return vcliques
def cliques_containing_node G nodes None cliques None if cliques is None cliques list find_cliques G if nodes is None nodes list G nodes if not isinstance nodes list v nodesvcliques [c for c in cliques if v in c ]else vcliques {}for v in nodes vcliques[v] [c for c in cliques if v in c ]return vcliques
60
python-test-2330
python
What do verify types have ?
no clr attributes
@skip 'multiple execute' def test no clr attributes class x passfor stuff in [object int float bool str long complex dict set None Not Implemented Ellipsis type test no clr attributes classmethod staticmethod frozenset property sys Base Exception type zip slice buffer enumerate file range xrange type x type x ] for dir...
@skip 'multiple_execute' def test_no_clr_attributes class x passfor stuff in [object int float bool str long complex dict set None NotImplemented Ellipsis type test_no_clr_attributes classmethod staticmethod frozenset property sys BaseException type zip slice buffer enumerate file range xrange type x type x ] for dir_s...
73
python-test-2331
python
What have no clr attributes ?
verify types
@skip 'multiple execute' def test no clr attributes class x passfor stuff in [object int float bool str long complex dict set None Not Implemented Ellipsis type test no clr attributes classmethod staticmethod frozenset property sys Base Exception type zip slice buffer enumerate file range xrange type x type x ] for dir...
@skip 'multiple_execute' def test_no_clr_attributes class x passfor stuff in [object int float bool str long complex dict set None NotImplemented Ellipsis type test_no_clr_attributes classmethod staticmethod frozenset property sys BaseException type zip slice buffer enumerate file range xrange type x type x ] for dir_s...
73
python-test-2336
python
For what purpose does the code create the query document ?
to find timestamps within that range
def make timestamp range start end start timestamp op None end timestamp op None ts range {}if start if start timestamp op 'gt' start timestamp op '$gt'else start timestamp op '$gte'ts range[start timestamp op] startif end if end timestamp op 'le' end timestamp op '$lte'else end timestamp op '$lt'ts range[end timestamp...
def make_timestamp_range start end start_timestamp_op None end_timestamp_op None ts_range {}if start if start_timestamp_op 'gt' start_timestamp_op '$gt'else start_timestamp_op '$gte'ts_range[start_timestamp_op] startif end if end_timestamp_op 'le' end_timestamp_op '$lte'else end_timestamp_op '$lt'ts_range[end_timestamp...
55
python-test-2337
python
What does the code create to find timestamps within that range ?
the query document
def make timestamp range start end start timestamp op None end timestamp op None ts range {}if start if start timestamp op 'gt' start timestamp op '$gt'else start timestamp op '$gte'ts range[start timestamp op] startif end if end timestamp op 'le' end timestamp op '$lte'else end timestamp op '$lt'ts range[end timestamp...
def make_timestamp_range start end start_timestamp_op None end_timestamp_op None ts_range {}if start if start_timestamp_op 'gt' start_timestamp_op '$gt'else start_timestamp_op '$gte'ts_range[start_timestamp_op] startif end if end_timestamp_op 'le' end_timestamp_op '$lte'else end_timestamp_op '$lt'ts_range[end_timestamp...
55
python-test-2342
python
What does the code compute ?
a theano function that computes one leapfrog step and the energy at the end of the trajectory
def theano leapfrog integrator H q p **theano kwargs epsilon tt dscalar 'epsilon' epsilon tag test value 1n steps tt iscalar 'n steps' n steps tag test value 2 q new p new leapfrog H q p epsilon n steps energy new energy H q new p new f theano function [q p epsilon n steps] [q new p new energy new] **theano kwargs f tr...
def _theano_leapfrog_integrator H q p **theano_kwargs epsilon tt dscalar 'epsilon' epsilon tag test_value 1n_steps tt iscalar 'n_steps' n_steps tag test_value 2 q_new p_new leapfrog H q p epsilon n_steps energy_new energy H q_new p_new f theano function [q p epsilon n_steps] [q_new p_new energy_new] **theano_kwargs f t...
69
python-test-2343
python
What does a theano function compute ?
one leapfrog step and the energy at the end of the trajectory
def theano leapfrog integrator H q p **theano kwargs epsilon tt dscalar 'epsilon' epsilon tag test value 1n steps tt iscalar 'n steps' n steps tag test value 2 q new p new leapfrog H q p epsilon n steps energy new energy H q new p new f theano function [q p epsilon n steps] [q new p new energy new] **theano kwargs f tr...
def _theano_leapfrog_integrator H q p **theano_kwargs epsilon tt dscalar 'epsilon' epsilon tag test_value 1n_steps tt iscalar 'n_steps' n_steps tag test_value 2 q_new p_new leapfrog H q p epsilon n_steps energy_new energy H q_new p_new f theano function [q p epsilon n_steps] [q_new p_new energy_new] **theano_kwargs f t...
69
python-test-2344
python
What does the code get ?
all iam user details
def export users path prefix '/' region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile if not conn return Noneresults odict Ordered Dict users get all users path prefix region key keyid profile for user in users name user user name policies conn get all user polici...
def export_users path_prefix '/' region None key None keyid None profile None conn _get_conn region region key key keyid keyid profile profile if not conn return Noneresults odict OrderedDict users get_all_users path_prefix region key keyid profile for user in users name user user_name_policies conn get_all_user_polici...
135
python-test-2345
python
What does the code add ?
accept selectors for existing annotations
def port standard standard annotations sel sample extractors new annotations []for annotation in standard annotations if not annotation get 'tagid' continueelement find element annotation sel if element is None continueselector find generalized css selector element sel if not selector continueannotation['accept selecto...
def port_standard standard_annotations sel sample extractors new_annotations []for annotation in standard_annotations if not annotation get 'tagid' continueelement find_element annotation sel if element is None continueselector find_generalized_css_selector element sel if not selector continueannotation['accept_selecto...
83
python-test-2346
python
What does the code convert into a valuation ?
a valuation string
def read valuation s encoding None if encoding is not None s s decode encoding statements []for linenum line in enumerate s splitlines line line strip if line startswith u'#' or line u'' continuetry statements append read valuation line line except Value Error raise Value Error u' Unabletoparseline%s %s' % linenum line...
def read_valuation s encoding None if encoding is not None s s decode encoding statements []for linenum line in enumerate s splitlines line line strip if line startswith u'#' or line u'' continuetry statements append _read_valuation_line line except ValueError raise ValueError u'Unabletoparseline%s %s' % linenum line r...
55
python-test-2350
python
What does URL require ?
the jenkins : jenkins - wiki : phabricator plugin < phabricator+differential+plugin >
def phabricator registry xml parent data root XML Sub Element xml parent 'com uber jenkins phabricator Phabricator Notifier' if 'comment-on-success' in data XML Sub Element root 'comment On Success' text str data get 'comment-on-success' lower if 'uberalls-enabled' in data XML Sub Element root 'uberalls Enabled' text s...
def phabricator registry xml_parent data root XML SubElement xml_parent 'com uber jenkins phabricator PhabricatorNotifier' if 'comment-on-success' in data XML SubElement root 'commentOnSuccess' text str data get 'comment-on-success' lower if 'uberalls-enabled' in data XML SubElement root 'uberallsEnabled' text str data...
100
python-test-2356
python
What does the code remove ?
the users requirement status
def remove credit requirement status username course key req namespace req name req to remove Credit Requirement get course requirements course key namespace req namespace name req name if not req to remove log error u' Couldnotremovecreditrequirementincourse"%s"withnamespace"%s"andname"%s"becausetherequirementdoesnote...
def remove_credit_requirement_status username course_key req_namespace req_name req_to_remove CreditRequirement get_course_requirements course_key namespace req_namespace name req_name if not req_to_remove log error u'Couldnotremovecreditrequirementincourse"%s"withnamespace"%s"andname"%s"becausetherequirementdoesnotexi...
56
python-test-2359
python
What does the code provide ?
the ipv6 mask for a given number of bits
def get mask ipv 6 bits if bits > 128 or bits < 0 raise Value Error ' Amaskcanonlybe 0 - 128 bits got%i' % bits elif bits 128 return FULL I Pv 6 MAS Kmask bin get binary 2 ** bits - 1 128 [ -1 ]groupings [mask bin[ 16 * i 16 * i + 1 ] for i in range 8 ]return ' ' join [ '% 04 x' % int group 2 for group in groupings] up...
def get_mask_ipv6 bits if bits > 128 or bits < 0 raise ValueError 'Amaskcanonlybe0-128bits got%i' % bits elif bits 128 return FULL_IPv6_MASKmask_bin _get_binary 2 ** bits - 1 128 [ -1 ]groupings [mask_bin[ 16 * i 16 * i + 1 ] for i in range 8 ]return ' ' join [ '%04x' % int group 2 for group in groupings] upper
81
python-test-2360
python
What does helper method create ?
an atom i d for a feed or entry
def create atom id resource path authority name None date string None if authority name is None authority name config get 'ckan feeds authority name' '' strip if not authority name site url config get 'ckan site url' '' strip authority name urlparse urlparse site url netlocif not authority name log warning ' Noauthorit...
def _create_atom_id resource_path authority_name None date_string None if authority_name is None authority_name config get 'ckan feeds authority_name' '' strip if not authority_name site_url config get 'ckan site_url' '' strip authority_name urlparse urlparse site_url netlocif not authority_name log warning 'Noauthorit...
116
python-test-2365
python
What do ssh use ?
to retrieve the network device running configuration
def retrieve config DEBUG Truenet devices Network Device objects all for a device in net devices if 'ssh' in a device device class if DEBUG print ' Retrievedeviceconfiguration {}{}\n' format a device device name a device device class ssh connect SSH Connection a device ssh connect enable mode output ssh connect send co...
def retrieve_config DEBUG Truenet_devices NetworkDevice objects all for a_device in net_devices if 'ssh' in a_device device_class if DEBUG print 'Retrievedeviceconfiguration {}{}\n' format a_device device_name a_device device_class ssh_connect SSHConnection a_device ssh_connect enable_mode output ssh_connect send_comma...
84
python-test-2366
python
What do a url bounce ?
off an outgoing url redirector
def get outgoing url url if not settings REDIRECT URL return urlparsed url urlparse url url netloc parsed url netlocif parsed url scheme not in ['http' 'https'] return '/'if url netloc urlparse settings REDIRECT URL netloc or url netloc in settings REDIRECT URL ALLOW LIST return urlurl force bytes jinja 2 utils Markup ...
def get_outgoing_url url if not settings REDIRECT_URL return urlparsed_url urlparse url url_netloc parsed_url netlocif parsed_url scheme not in ['http' 'https'] return '/'if url_netloc urlparse settings REDIRECT_URL netloc or url_netloc in settings REDIRECT_URL_ALLOW_LIST return urlurl force_bytes jinja2 utils Markup u...
85
python-test-2368
python
What did the code set ?
the keyboard layout for
def xorg name ret {'name' name 'changes' {} 'result' None 'comment' ''}if salt ['keyboard get x'] name ret['result'] Trueret['comment'] 'X Orglayout{ 0 }alreadyset' format name return retif opts ['test'] ret['comment'] 'X Orglayout{ 0 }needstobeset' format name return retif salt ['keyboard set x'] name ret['changes'] {...
def xorg name ret {'name' name 'changes' {} 'result' None 'comment' ''}if __salt__['keyboard get_x'] name ret['result'] Trueret['comment'] 'XOrglayout{0}alreadyset' format name return retif __opts__['test'] ret['comment'] 'XOrglayout{0}needstobeset' format name return retif __salt__['keyboard set_x'] name ret['changes'...
64
python-test-2369
python
What did user provide ?
precisions
def check precisions precisions covariance type n components n features precisions check array precisions dtype [np float 64 np float 32 ] ensure 2d False allow nd covariance type 'full' precisions shape {'full' n components n features n features 'tied' n features n features 'diag' n components n features 'spherical' n...
def _check_precisions precisions covariance_type n_components n_features precisions check_array precisions dtype [np float64 np float32] ensure_2d False allow_nd covariance_type 'full' precisions_shape {'full' n_components n_features n_features 'tied' n_features n_features 'diag' n_components n_features 'spherical' n_c...
89
python-test-2370
python
What replaces with another subcircuit in circuit ?
a subcircuit
def replace subcircuit circuit subcircuit replace None pos 0 if pos < 0 pos 0if isinstance circuit Mul circuit circuit argsif isinstance subcircuit Mul subcircuit subcircuit argsif isinstance replace Mul replace replace argselif replace is None replace loc find subcircuit circuit subcircuit start pos if loc > -1 left c...
def replace_subcircuit circuit subcircuit replace None pos 0 if pos < 0 pos 0if isinstance circuit Mul circuit circuit argsif isinstance subcircuit Mul subcircuit subcircuit argsif isinstance replace Mul replace replace argselif replace is None replace loc find_subcircuit circuit subcircuit start pos if loc > -1 left c...
67
python-test-2371
python
What does a subcircuit replace ?
with another subcircuit in circuit
def replace subcircuit circuit subcircuit replace None pos 0 if pos < 0 pos 0if isinstance circuit Mul circuit circuit argsif isinstance subcircuit Mul subcircuit subcircuit argsif isinstance replace Mul replace replace argselif replace is None replace loc find subcircuit circuit subcircuit start pos if loc > -1 left c...
def replace_subcircuit circuit subcircuit replace None pos 0 if pos < 0 pos 0if isinstance circuit Mul circuit circuit argsif isinstance subcircuit Mul subcircuit subcircuit argsif isinstance replace Mul replace replace argselif replace is None replace loc find_subcircuit circuit subcircuit start pos if loc > -1 left c...
67
python-test-2373
python
What does the code build using data from configuration ?
a gceblockdeviceapi instance
def gce from configuration cluster id project None zone None credentials None if project is None project get machine project if zone is None zone get machine zone gce credentials gce credentials from config credentials compute discovery build 'compute' 'v 1 ' credentials gce credentials return GCE Block Device API oper...
def gce_from_configuration cluster_id project None zone None credentials None if project is None project get_machine_project if zone is None zone get_machine_zone gce_credentials gce_credentials_from_config credentials compute discovery build 'compute' 'v1' credentials gce_credentials return GCEBlockDeviceAPI _operatio...
66
python-test-2374
python
How does the code build a gceblockdeviceapi instance ?
using data from configuration
def gce from configuration cluster id project None zone None credentials None if project is None project get machine project if zone is None zone get machine zone gce credentials gce credentials from config credentials compute discovery build 'compute' 'v 1 ' credentials gce credentials return GCE Block Device API oper...
def gce_from_configuration cluster_id project None zone None credentials None if project is None project get_machine_project if zone is None zone get_machine_zone gce_credentials gce_credentials_from_config credentials compute discovery build 'compute' 'v1' credentials gce_credentials return GCEBlockDeviceAPI _operatio...
66
python-test-2376
python
How do a dsc configuration compile ?
in the form of a powershell script
def run config path source None config name None config data None config data source None script parameters None salt env 'base' ret compile config path path source source config name config name config data config data config data source config data source script parameters script parameters salt env salt env if ret g...
def run_config path source None config_name None config_data None config_data_source None script_parameters None salt_env 'base' ret compile_config path path source source config_name config_name config_data config_data config_data_source config_data_source script_parameters script_parameters salt_env salt_env if ret g...
72
python-test-2377
python
What does the code unwatch ?
a forum
@require POST@login requireddef watch forum request forum slug forum get object or 404 Forum slug forum slug if not forum allows viewing by request user raise Http 404 if request POST get 'watch' 'yes' New Thread Event notify request user forum statsd incr 'forums watches forum' else New Thread Event stop notifying req...
@require_POST@login_requireddef watch_forum request forum_slug forum get_object_or_404 Forum slug forum_slug if not forum allows_viewing_by request user raise Http404if request POST get 'watch' 'yes' NewThreadEvent notify request user forum statsd incr 'forums watches forum' else NewThreadEvent stop_notifying request u...
65
python-test-2385
python
What do all of the students have ?
due date extensions for the given unit
@handle dashboard error@require POST@ensure csrf cookie@cache control no cache True no store True must revalidate True @require level 'staff' @require post params 'url' def show unit extensions request course id course get course by id Slash Separated Course Key from deprecated string course id unit find unit course re...
@handle_dashboard_error@require_POST@ensure_csrf_cookie@cache_control no_cache True no_store True must_revalidate True @require_level 'staff' @require_post_params 'url' def show_unit_extensions request course_id course get_course_by_id SlashSeparatedCourseKey from_deprecated_string course_id unit find_unit course reque...
60
python-test-2386
python
What have due date extensions for the given unit ?
all of the students
@handle dashboard error@require POST@ensure csrf cookie@cache control no cache True no store True must revalidate True @require level 'staff' @require post params 'url' def show unit extensions request course id course get course by id Slash Separated Course Key from deprecated string course id unit find unit course re...
@handle_dashboard_error@require_POST@ensure_csrf_cookie@cache_control no_cache True no_store True must_revalidate True @require_level 'staff' @require_post_params 'url' def show_unit_extensions request course_id course get_course_by_id SlashSeparatedCourseKey from_deprecated_string course_id unit find_unit course reque...
60
python-test-2389
python
What returns at given warehouse ?
stock balance quantity
@frappe whitelist def get stock balance item code warehouse posting date None posting time None with valuation rate False from erpnext stock stock ledger import get previous sleif not posting date posting date nowdate if not posting time posting time nowtime last entry get previous sle {u'item code' item code u'warehou...
@frappe whitelist def get_stock_balance item_code warehouse posting_date None posting_time None with_valuation_rate False from erpnext stock stock_ledger import get_previous_sleif not posting_date posting_date nowdate if not posting_time posting_time nowtime last_entry get_previous_sle {u'item_code' item_code u'warehou...
92
python-test-2390
python
When does stock balance quantity return at given warehouse ?
on given posting date or current date
@frappe whitelist def get stock balance item code warehouse posting date None posting time None with valuation rate False from erpnext stock stock ledger import get previous sleif not posting date posting date nowdate if not posting time posting time nowtime last entry get previous sle {u'item code' item code u'warehou...
@frappe whitelist def get_stock_balance item_code warehouse posting_date None posting_time None with_valuation_rate False from erpnext stock stock_ledger import get_previous_sleif not posting_date posting_date nowdate if not posting_time posting_time nowtime last_entry get_previous_sle {u'item_code' item_code u'warehou...
92
python-test-2391
python
Where does stock balance quantity return on given posting date or current date ?
at given warehouse
@frappe whitelist def get stock balance item code warehouse posting date None posting time None with valuation rate False from erpnext stock stock ledger import get previous sleif not posting date posting date nowdate if not posting time posting time nowtime last entry get previous sle {u'item code' item code u'warehou...
@frappe whitelist def get_stock_balance item_code warehouse posting_date None posting_time None with_valuation_rate False from erpnext stock stock_ledger import get_previous_sleif not posting_date posting_date nowdate if not posting_time posting_time nowtime last_entry get_previous_sle {u'item_code' item_code u'warehou...
92
python-test-2397
python
How does de solve ?
with constant coefficients
def solve explike DE f x DE g k from sympy solvers import rsolvefor t in Add make args DE coeff d t as independent g if coeff free symbols return RE exp re DE g k init {}for i in range len Add make args RE if i f f diff x init[g k subs k i ] f limit x 0 sol rsolve RE g k init if sol return sol / factorial k S Zero S Ze...
def _solve_explike_DE f x DE g k from sympy solvers import rsolvefor t in Add make_args DE coeff d t as_independent g if coeff free_symbols returnRE exp_re DE g k init {}for i in range len Add make_args RE if i f f diff x init[g k subs k i ] f limit x 0 sol rsolve RE g k init if sol return sol / factorial k S Zero S Ze...
80
python-test-2398
python
What does the code find ?
the shortest path from s to every other vertex findable from s using dijkstras algorithm in o time
def shortest path digr s nodes explored set [s] nodes unexplored DFS digr s nodes unexplored remove s dist {s 0}node heap []for n in nodes unexplored min compute min dist digr n nodes explored dist heapq heappush node heap min n while len node heap > 0 min dist nearest node heapq heappop node heap dist[nearest node] mi...
def shortest_path digr s nodes_explored set [s] nodes_unexplored DFS digr s nodes_unexplored remove s dist {s 0}node_heap []for n in nodes_unexplored min compute_min_dist digr n nodes_explored dist heapq heappush node_heap min n while len node_heap > 0 min_dist nearest_node heapq heappop node_heap dist[nearest_node] mi...
111
python-test-2401
python
What does the code remove from the running jboss instance ?
an existing datasource
def remove datasource jboss config name profile None log debug ' MODULEFUNCTION jboss 7 remove datasource name %s profile %s' name profile operation '/subsystem datasources/data-source {name} remove' format name name if profile is not None operation '/profile "{profile}"' format profile profile + operation return salt ...
def remove_datasource jboss_config name profile None log debug ' MODULEFUNCTION jboss7 remove_datasource name %s profile %s' name profile operation '/subsystem datasources/data-source {name} remove' format name name if profile is not None operation '/profile "{profile}"' format profile profile + operation return __salt...
57
python-test-2403
python
What does the code stop ?
the kalite server
def stop args [] sys exit True try kill pid get pid [0 ] os unlink PID FILE except Not Running as e sys stderr write ' Alreadystopped Statuswas {000 s}\n' format status codes[e status code] killed with force Falseif e status code STATUS NOT RESPONDING sys stderr write ' Notresponding killingwithforce\n' try pid read pi...
def stop args [] sys_exit True try kill_pid get_pid [0] os unlink PID_FILE except NotRunning as e sys stderr write 'Alreadystopped Statuswas {000 s}\n' format status codes[e status_code] killed_with_force Falseif e status_code STATUS_NOT_RESPONDING sys stderr write 'Notresponding killingwithforce\n' try pid __ read_pid...
106
python-test-2404
python
What does the code enable ?
a service cli example
def service enable s name **connection args ret Trueservice service get s name **connection args if service is None return Falsenitro connect **connection args if nitro is None return Falsetry NS Service enable nitro service except NS Nitro Error as error log debug 'netscalermoduleerror-NS Service enable failed {0 }' f...
def service_enable s_name **connection_args ret Trueservice _service_get s_name **connection_args if service is None return Falsenitro _connect **connection_args if nitro is None return Falsetry NSService enable nitro service except NSNitroError as error log debug 'netscalermoduleerror-NSService enable failed {0}' form...
57
python-test-2409
python
Where does static files discover ?
in given paths
def discover static files base path sub path '' js files discover files base path sub path sub path ext ' js' trim base path True sources mocks specs sort js files js files html files discover files base path sub path sub path ext ' html' trim base path True p path join base path sub path log sources ' Java Scriptsourc...
def discover_static_files base_path sub_path '' js_files discover_files base_path sub_path sub_path ext ' js' trim_base_path True sources mocks specs sort_js_files js_files html_files discover_files base_path sub_path sub_path ext ' html' trim_base_path True p path join base_path sub_path _log sources 'JavaScriptsource...
88
python-test-2410
python
What discovers in given paths ?
static files
def discover static files base path sub path '' js files discover files base path sub path sub path ext ' js' trim base path True sources mocks specs sort js files js files html files discover files base path sub path sub path ext ' html' trim base path True p path join base path sub path log sources ' Java Scriptsourc...
def discover_static_files base_path sub_path '' js_files discover_files base_path sub_path sub_path ext ' js' trim_base_path True sources mocks specs sort_js_files js_files html_files discover_files base_path sub_path sub_path ext ' html' trim_base_path True p path join base_path sub_path _log sources 'JavaScriptsource...
88
python-test-2412
python
How do a minimum shielding factor assert ?
using empty - room power
def assert shielding raw sss erm power shielding factor meg 'mag' picks pick types raw sss info meg meg ref meg False if isinstance erm power Base Raw picks erm pick types raw sss info meg meg ref meg False assert allclose picks picks erm erm power np sqrt erm power[picks erm][ 0 ] ** 2 sum sss power raw sss[picks][ 0 ...
def _assert_shielding raw_sss erm_power shielding_factor meg 'mag' picks pick_types raw_sss info meg meg ref_meg False if isinstance erm_power BaseRaw picks_erm pick_types raw_sss info meg meg ref_meg False assert_allclose picks picks_erm erm_power np sqrt erm_power[picks_erm][0] ** 2 sum sss_power raw_sss[picks][0] ra...
97
python-test-2418
python
What does the code remove ?
timezone info
def iso to plotly time string iso string if iso string split '-' [ 3] is '00 00 ' or iso string split '+' [0 ] is '00 00 ' raise Exception " Plotlywon'taccepttimestringswithtimezoneinfo \n Alltimestringsareassumedtobein UTC " iso string iso string replace '- 00 00 ' '' replace '+ 00 00 ' '' if iso string endswith 'T 00...
def iso_to_plotly_time_string iso_string if iso_string split '-' [ 3] is '00 00' or iso_string split '+' [0] is '00 00' raise Exception "Plotlywon'taccepttimestringswithtimezoneinfo \nAlltimestringsareassumedtobeinUTC " iso_string iso_string replace '-00 00' '' replace '+00 00' '' if iso_string endswith 'T00 00 00' ret...
80
python-test-2419
python
What does the code replace with ?
t delimeter
def iso to plotly time string iso string if iso string split '-' [ 3] is '00 00 ' or iso string split '+' [0 ] is '00 00 ' raise Exception " Plotlywon'taccepttimestringswithtimezoneinfo \n Alltimestringsareassumedtobein UTC " iso string iso string replace '- 00 00 ' '' replace '+ 00 00 ' '' if iso string endswith 'T 00...
def iso_to_plotly_time_string iso_string if iso_string split '-' [ 3] is '00 00' or iso_string split '+' [0] is '00 00' raise Exception "Plotlywon'taccepttimestringswithtimezoneinfo \nAlltimestringsareassumedtobeinUTC " iso_string iso_string replace '-00 00' '' replace '+00 00' '' if iso_string endswith 'T00 00 00' ret...
80
python-test-2420
python
In which direction are we installing ?
from an sdist
def fixup for packaged if exists join ROOT 'PKG-INF Ovi' if '--build-js' in sys argv or '--install-js' in sys argv print SDIST BUILD WARNING if '--build-js' in sys argv sys argv remove '--build-js' if '--install-js' in sys argv sys argv remove '--install-js' if '--existing-js' not in sys argv sys argv append '--existin...
def fixup_for_packaged if exists join ROOT 'PKG-INFOvi' if '--build-js' in sys argv or '--install-js' in sys argv print SDIST_BUILD_WARNING if '--build-js' in sys argv sys argv remove '--build-js' if '--install-js' in sys argv sys argv remove '--install-js' if '--existing-js' not in sys argv sys argv append '--existing...
52
python-test-2422
python
What does the code get ?
a cdot configuration object for a specific backend
def get backend configuration backend name config stanzas CONF list all sections if backend name not in config stanzas msg ' Couldnotfindbackendstanza% backend name sinconfiguration Availablestanzasare% stanzas s' params {'stanzas' config stanzas 'backend name' backend name}raise exception Config Not Found message msg ...
def get_backend_configuration backend_name config_stanzas CONF list_all_sections if backend_name not in config_stanzas msg _ 'Couldnotfindbackendstanza% backend_name sinconfiguration Availablestanzasare% stanzas s' params {'stanzas' config_stanzas 'backend_name' backend_name}raise exception ConfigNotFound message msg %...
128
python-test-2423
python
What does the code make ?
the least - square spline
def make lsq full matrix x y t k 3 x y t map np asarray x y t m x sizen t size - k - 1 A np zeros m n dtype np float for j in range m xval x[j]if xval t[k] left kelse left np searchsorted t xval - 1 bb bspl evaluate all bspl t k xval left A[j left - k left + 1 ] bb B np dot A T A Y np dot A T y c sl solve B Y return c ...
def make_lsq_full_matrix x y t k 3 x y t map np asarray x y t m x sizen t size - k - 1 A np zeros m n dtype np float_ for j in range m xval x[j]if xval t[k] left kelse left np searchsorted t xval - 1 bb _bspl evaluate_all_bspl t k xval left A[j left - k left + 1 ] bbB np dot A T A Y np dot A T y c sl solve B Y return c...
93
python-test-2428
python
What sees class ?
updates3errorpage
@sync performerdef perform update s3 error page dispatcher intent s3 boto connect s3 bucket s3 get bucket intent bucket config bucket get website configuration obj new error key intent error keyold error key config error keyif old error key new error key return Noneelse config error key new error keybucket set website ...
@sync_performerdef perform_update_s3_error_page dispatcher intent s3 boto connect_s3 bucket s3 get_bucket intent bucket config bucket get_website_configuration_obj new_error_key intent error_keyold_error_key config error_keyif old_error_key new_error_key return Noneelse config error_key new_error_keybucket set_website_...
58
python-test-2430
python
Where be an action performed ?
on a given virtual machine
def vm action name kwargs None call None if call 'action' raise Salt Cloud System Exit ' Thevm actionfunctionmustbecalledwith-aor--action ' if kwargs is None kwargs {}action kwargs get 'action' None if action is None raise Salt Cloud System Exit " Thevm actionfunctionmusthavean'action'provided " server user password ge...
def vm_action name kwargs None call None if call 'action' raise SaltCloudSystemExit 'Thevm_actionfunctionmustbecalledwith-aor--action ' if kwargs is None kwargs {}action kwargs get 'action' None if action is None raise SaltCloudSystemExit "Thevm_actionfunctionmusthavean'action'provided " server user password _get_xml_r...
96
python-test-2431
python
What does the code compute ?
a transversal for the orbit of alpha as a set
def orbit transversal degree generators alpha pairs af False tr [ alpha list range degree ]used [ False] * degree used[alpha] Truegens [x array form for x in generators]for x px in tr for gen in gens temp gen[x]if used[temp] False tr append temp af rmul gen px used[temp] Trueif pairs if not af tr [ x af new y for x y i...
def _orbit_transversal degree generators alpha pairs af False tr [ alpha list range degree ]used [False] * degree used[alpha] Truegens [x _array_form for x in generators]for x px in tr for gen in gens temp gen[x]if used[temp] False tr append temp _af_rmul gen px used[temp] Trueif pairs if not af tr [ x _af_new y for x ...
81
python-test-2436
python
What does the code create ?
a transfer from the google cloud storage standard class to the nearline storage class
def main description project id day month year hours minutes source bucket sink bucket credentials Google Credentials get application default storagetransfer discovery build 'storagetransfer' 'v 1 ' credentials credentials transfer job {'description' description 'status' 'ENABLED' 'project Id' project id 'schedule' {'s...
def main description project_id day month year hours minutes source_bucket sink_bucket credentials GoogleCredentials get_application_default storagetransfer discovery build 'storagetransfer' 'v1' credentials credentials transfer_job {'description' description 'status' 'ENABLED' 'projectId' project_id 'schedule' {'sched...
111
python-test-2439
python
What does the code compute ?
the hmac hash of the user secret
def Compute OTP secret t h hmac new base 64 b32 decode secret struct pack '>Q' t hashlib sha 1 hash h digest offset struct unpack 'B' hash[ -1 ] [0 ] & 15 truncated hash struct unpack '>I' hash[offset offset + 4 ] [0 ]truncated hash & 2147483647 truncated hash % VERIFY MODULU Sreturn truncated hash
def _ComputeOTP secret t h hmac new base64 b32decode secret struct pack '>Q' t hashlib sha1 hash h digest offset struct unpack 'B' hash[ -1 ] [0] & 15 truncated_hash struct unpack '>I' hash[offset offset + 4 ] [0]truncated_hash & 2147483647truncated_hash % _VERIFY_MODULUSreturn truncated_hash
57