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-5381
python
What does the code compute ?
the current utilization of a given host
def get host utilization context host ram mb disk gb instances instance get all by host context host vms len instances free ram mb ram mb - FLAGS reserved host memory mb free disk gb disk gb - FLAGS reserved host disk mb * 1024 work 0for instance in instances free ram mb - instance memory mbfree disk gb - instance root...
def _get_host_utilization context host ram_mb disk_gb instances instance_get_all_by_host context host vms len instances free_ram_mb ram_mb - FLAGS reserved_host_memory_mb free_disk_gb disk_gb - FLAGS reserved_host_disk_mb * 1024 work 0for instance in instances free_ram_mb - instance memory_mbfree_disk_gb - instance roo...
107
python-test-5384
python
What does the code find ?
all the branches whose names start with " p4/ "
def p4 Branches In Git branches Are In Remotes True branches {}cmdline 'gitrev-parse--symbolic'if branches Are In Remotes cmdline + '--remotes'else cmdline + '--branches'for line in read pipe lines cmdline line line strip if not line startswith 'p 4 /' continueif line 'p 4 /HEAD' continuebranch line[len 'p 4 /' ]branch...
def p4BranchesInGit branchesAreInRemotes True branches {}cmdline 'gitrev-parse--symbolic'if branchesAreInRemotes cmdline + '--remotes'else cmdline + '--branches'for line in read_pipe_lines cmdline line line strip if not line startswith 'p4/' continueif line 'p4/HEAD' continuebranch line[len 'p4/' ]branches[branch] pars...
55
python-test-5385
python
What does page handle ?
refund requests for marketplace
@anonymous csrf@mobile template 'questions/{mobile/}marketplace refund html' def marketplace refund request template error message Noneif request method 'GET' form Marketplace Refund Form request user else form Marketplace Refund Form request user request POST if form is valid try form submit ticket return Http Respons...
@anonymous_csrf@mobile_template 'questions/{mobile/}marketplace_refund html' def marketplace_refund request template error_message Noneif request method 'GET' form MarketplaceRefundForm request user else form MarketplaceRefundForm request user request POST if form is_valid try form submit_ticket return HttpResponseRedi...
67
python-test-5386
python
What does the code ensure ?
that a tenant exists
def ensure tenant exists keystone tenant name tenant description check mode try tenant get tenant keystone tenant name except Key Error passelse if tenant description tenant description return False tenant id elif check mode return True tenant id else tenant update description tenant description return True tenant id i...
def ensure_tenant_exists keystone tenant_name tenant_description check_mode try tenant get_tenant keystone tenant_name except KeyError passelse if tenant description tenant_description return False tenant id elif check_mode return True tenant id else tenant update description tenant_description return True tenant id if...
73
python-test-5387
python
For what purpose does the code build the string from the xblock type set ?
to append to the block url for block_count types arguments
def get block count url string xblock type set block url ''if len xblock type set > 0 block url + '&all blocks true&block counts 'for index block type in enumerate xblock type set block url + block typeif index < len xblock type set - 1 block url + ' 'return block url
def _get_block_count_url_string xblock_type_set block_url ''if len xblock_type_set > 0 block_url + '&all_blocks true&block_counts 'for index block_type in enumerate xblock_type_set block_url + block_typeif index < len xblock_type_set - 1 block_url + ' 'return block_url
54
python-test-5388
python
What does the code build to append to the block url for block_count types arguments ?
the string from the xblock type set
def get block count url string xblock type set block url ''if len xblock type set > 0 block url + '&all blocks true&block counts 'for index block type in enumerate xblock type set block url + block typeif index < len xblock type set - 1 block url + ' 'return block url
def _get_block_count_url_string xblock_type_set block_url ''if len xblock_type_set > 0 block_url + '&all_blocks true&block_counts 'for index block_type in enumerate xblock_type_set block_url + block_typeif index < len xblock_type_set - 1 block_url + ' 'return block_url
54
python-test-5389
python
What ordered from nestedrings ?
nestedrings
def get Ordered Nested Rings nested Rings insides []ordered Nested Rings []for loop Index in xrange len nested Rings nested Ring nested Rings[loop Index]other Loops []for before Index in xrange loop Index other Loops append nested Rings[before Index] boundary for after Index in xrange loop Index + 1 len nested Rings ot...
def getOrderedNestedRings nestedRings insides []orderedNestedRings []for loopIndex in xrange len nestedRings nestedRing nestedRings[loopIndex]otherLoops []for beforeIndex in xrange loopIndex otherLoops append nestedRings[beforeIndex] boundary for afterIndex in xrange loopIndex + 1 len nestedRings otherLoops append nest...
96
python-test-5390
python
What did nestedrings order ?
from nestedrings
def get Ordered Nested Rings nested Rings insides []ordered Nested Rings []for loop Index in xrange len nested Rings nested Ring nested Rings[loop Index]other Loops []for before Index in xrange loop Index other Loops append nested Rings[before Index] boundary for after Index in xrange loop Index + 1 len nested Rings ot...
def getOrderedNestedRings nestedRings insides []orderedNestedRings []for loopIndex in xrange len nestedRings nestedRing nestedRings[loopIndex]otherLoops []for beforeIndex in xrange loopIndex otherLoops append nestedRings[beforeIndex] boundary for afterIndex in xrange loopIndex + 1 len nestedRings otherLoops append nest...
96
python-test-5392
python
What does the code make ?
them comma seperated string
def make providers strings providers if not providers return Noneif len providers 1 providers string providers[ 0 ]elif len providers 2 providers string '{first provider}and{second provider}' format first provider providers[ 0 ] second provider providers[ 1 ] else providers string '{first providers} and{last provider}'...
def make_providers_strings providers if not providers return Noneif len providers 1 providers_string providers[0]elif len providers 2 providers_string _ '{first_provider}and{second_provider}' format first_provider providers[0] second_provider providers[1] else providers_string _ '{first_providers} and{last_provider}' f...
61
python-test-5393
python
What does the code get ?
the list of course providers
def make providers strings providers if not providers return Noneif len providers 1 providers string providers[ 0 ]elif len providers 2 providers string '{first provider}and{second provider}' format first provider providers[ 0 ] second provider providers[ 1 ] else providers string '{first providers} and{last provider}'...
def make_providers_strings providers if not providers return Noneif len providers 1 providers_string providers[0]elif len providers 2 providers_string _ '{first_provider}and{second_provider}' format first_provider providers[0] second_provider providers[1] else providers_string _ '{first_providers} and{last_provider}' f...
61
python-test-5396
python
What does the code rewrite ?
a list of expressions as integer multiples of each other
def integer powers exprs terms {}for term in exprs for j in terms a cancel term / j if a is Rational terms[j] append term a breakelse terms[term] [ term S 1 ]newterms {}for term in terms common denom reduce ilcm [i as numer denom [1 ] for i in terms[term]] newterm term / common denom newmults [ i j * common denom for i...
def integer_powers exprs terms {}for term in exprs for j in terms a cancel term / j if a is_Rational terms[j] append term a breakelse terms[term] [ term S 1 ]newterms {}for term in terms common_denom reduce ilcm [i as_numer_denom [1] for _ i in terms[term]] newterm term / common_denom newmults [ i j * common_denom for ...
81
python-test-5404
python
What does the code create ?
a protobuf request for a createinstance request
def prepare create request instance parent name 'projects/' + instance client project message messages v2 pb 2 Create Instance Request parent parent name instance id instance instance id instance data v2 pb 2 Instance display name instance display name cluster message clusters[instance instance id]cluster name instance...
def _prepare_create_request instance parent_name 'projects/' + instance _client project message messages_v2_pb2 CreateInstanceRequest parent parent_name instance_id instance instance_id instance data_v2_pb2 Instance display_name instance display_name cluster message clusters[instance instance_id]cluster name instance n...
72
python-test-5405
python
What does the code reconstruct ?
the full " updates " dictionary
def fgraph updated vars fgraph expanded inputs updated vars {}potential values list fgraph outputs if len expanded inputs len fgraph inputs raise Value Error 'expanded inputsmustmatchlen fgraph inputs ' for e input ivar in reversed list zip expanded inputs fgraph inputs if e input update is not None updated vars[ivar] ...
def fgraph_updated_vars fgraph expanded_inputs updated_vars {}potential_values list fgraph outputs if len expanded_inputs len fgraph inputs raise ValueError 'expanded_inputsmustmatchlen fgraph inputs ' for e_input ivar in reversed list zip expanded_inputs fgraph inputs if e_input update is not None updated_vars[ivar] p...
56
python-test-5406
python
What does the code get ?
the tag browser serialized as json optional : ? library_id=<default library>&sort_tags_by = name&partition_method = first letter & collapse_at=25&dont_collapse=&hide_empty_categories=
@endpoint u'/interface-data/tag-browser' def tag browser ctx rd db library id get library data ctx rd [ 2]etag u'%s %s %s' % db last modified rd username library id etag hashlib sha 1 etag encode u'utf- 8 ' hexdigest def generate db library id get library data ctx rd [ 2]return json ctx rd tag browser categories as jso...
@endpoint u'/interface-data/tag-browser' def tag_browser ctx rd db library_id get_library_data ctx rd [ 2]etag u'%s %s %s' % db last_modified rd username library_id etag hashlib sha1 etag encode u'utf-8' hexdigest def generate db library_id get_library_data ctx rd [ 2]return json ctx rd tag_browser categories_as_json c...
68
python-test-5407
python
How do essid get from cap file ?
using bssid as reference
def get essid from cap bssid capfile if not program exists 'tshark' return ''cmd ['tshark' '-r' capfile '-R' 'wlan fc type subtype 0x 05 &&wlan sa %s' % bssid '-n']proc Popen cmd stdout PIPE stderr DN proc wait for line in proc communicate [0 ] split '\n' if line find 'SSID ' -1 essid line[ line find 'SSID ' + 5 ]print...
def get_essid_from_cap bssid capfile if not program_exists 'tshark' return ''cmd ['tshark' '-r' capfile '-R' 'wlan fc type_subtype 0x05&&wlan sa %s' % bssid '-n']proc Popen cmd stdout PIPE stderr DN proc wait for line in proc communicate [0] split '\n' if line find 'SSID ' -1 essid line[ line find 'SSID ' + 5 ]print GR...
91
python-test-5409
python
What can a dict be used ?
to create an anomaly model via opfs modelfactory
def get Scalar Metric With Time Of Day Anomaly Params metric Data min Val None max Val None min Resolution None tm Implementation 'cpp' if min Resolution is None min Resolution 0 001 if min Val is None or max Val is None comp Min Val comp Max Val range Gen metric Data if min Val is None min Val comp Min Valif max Val i...
def getScalarMetricWithTimeOfDayAnomalyParams metricData minVal None maxVal None minResolution None tmImplementation 'cpp' if minResolution is None minResolution 0 001if minVal is None or maxVal is None compMinVal compMaxVal _rangeGen metricData if minVal is None minVal compMinValif maxVal is None maxVal compMaxValif m...
169
python-test-5410
python
How did an anomaly model create ?
via opfs modelfactory
def get Scalar Metric With Time Of Day Anomaly Params metric Data min Val None max Val None min Resolution None tm Implementation 'cpp' if min Resolution is None min Resolution 0 001 if min Val is None or max Val is None comp Min Val comp Max Val range Gen metric Data if min Val is None min Val comp Min Valif max Val i...
def getScalarMetricWithTimeOfDayAnomalyParams metricData minVal None maxVal None minResolution None tmImplementation 'cpp' if minResolution is None minResolution 0 001if minVal is None or maxVal is None compMinVal compMaxVal _rangeGen metricData if minVal is None minVal compMinValif maxVal is None maxVal compMaxValif m...
169
python-test-5411
python
How did array coarsen ?
by applying reduction to fixed size neighborhoods parameters reduction
def coarsen reduction x axes trim excess False for i in range x ndim if i not in axes axes[i] 1if trim excess ind tuple slice 0 - d % axes[i] if d % axes[i] else slice None None for i d in enumerate x shape x x[ind]newshape tuple concat [ x shape[i] / axes[i] axes[i] for i in range x ndim ] return reduction x reshape n...
def coarsen reduction x axes trim_excess False for i in range x ndim if i not in axes axes[i] 1if trim_excess ind tuple slice 0 - d % axes[i] if d % axes[i] else slice None None for i d in enumerate x shape x x[ind]newshape tuple concat [ x shape[i] / axes[i] axes[i] for i in range x ndim ] return reduction x reshape n...
77
python-test-5412
python
What do reduction apply ?
to fixed size neighborhoods parameters reduction
def coarsen reduction x axes trim excess False for i in range x ndim if i not in axes axes[i] 1if trim excess ind tuple slice 0 - d % axes[i] if d % axes[i] else slice None None for i d in enumerate x shape x x[ind]newshape tuple concat [ x shape[i] / axes[i] axes[i] for i in range x ndim ] return reduction x reshape n...
def coarsen reduction x axes trim_excess False for i in range x ndim if i not in axes axes[i] 1if trim_excess ind tuple slice 0 - d % axes[i] if d % axes[i] else slice None None for i d in enumerate x shape x x[ind]newshape tuple concat [ x shape[i] / axes[i] axes[i] for i in range x ndim ] return reduction x reshape n...
77
python-test-5413
python
What is applying to fixed size neighborhoods parameters reduction ?
reduction
def coarsen reduction x axes trim excess False for i in range x ndim if i not in axes axes[i] 1if trim excess ind tuple slice 0 - d % axes[i] if d % axes[i] else slice None None for i d in enumerate x shape x x[ind]newshape tuple concat [ x shape[i] / axes[i] axes[i] for i in range x ndim ] return reduction x reshape n...
def coarsen reduction x axes trim_excess False for i in range x ndim if i not in axes axes[i] 1if trim_excess ind tuple slice 0 - d % axes[i] if d % axes[i] else slice None None for i d in enumerate x shape x x[ind]newshape tuple concat [ x shape[i] / axes[i] axes[i] for i in range x ndim ] return reduction x reshape n...
77
python-test-5414
python
What does the code calculate along the given axis ?
a one - dimensional uniform filter
@docfillerdef uniform filter 1 d input size axis -1 output None mode 'reflect' cval 0 0 origin 0 input numpy asarray input if numpy iscomplexobj input raise Type Error ' Complextypenotsupported' axis ni support check axis axis input ndim if size < 1 raise Runtime Error 'incorrectfiltersize' output return value ni suppo...
@docfillerdef uniform_filter1d input size axis -1 output None mode 'reflect' cval 0 0 origin 0 input numpy asarray input if numpy iscomplexobj input raise TypeError 'Complextypenotsupported' axis _ni_support _check_axis axis input ndim if size < 1 raise RuntimeError 'incorrectfiltersize' output return_value _ni_support...
100
python-test-5415
python
What does the code extract ?
all rx excludes
def parse rx excludes options fatal excluded patterns []for flag in options option parameter flagif option '--exclude-rx' try excluded patterns append re compile parameter except re error as ex fatal 'invalid--exclude-rxpattern %s %s' % parameter ex elif option '--exclude-rx-from' try f open resolve parent parameter ex...
def parse_rx_excludes options fatal excluded_patterns []for flag in options option parameter flagif option '--exclude-rx' try excluded_patterns append re compile parameter except re error as ex fatal 'invalid--exclude-rxpattern %s %s' % parameter ex elif option '--exclude-rx-from' try f open resolve_parent parameter ex...
89
python-test-5416
python
What executes a beaker build step ?
beaker
def beaker registry xml parent data beaker XML Sub Element xml parent 'org jenkinsci plugins beakerbuilder Beaker Builder' job Source XML Sub Element beaker 'job Source' if 'content' in data and 'path' in data raise Jenkins Jobs Exception " Usejustoneof'content'or'path'" elif 'content' in data job Source Class 'org jen...
def beaker registry xml_parent data beaker XML SubElement xml_parent 'org jenkinsci plugins beakerbuilder BeakerBuilder' jobSource XML SubElement beaker 'jobSource' if 'content' in data and 'path' in data raise JenkinsJobsException "Usejustoneof'content'or'path'" elif 'content' in data jobSourceClass 'org jenkinsci plu...
116
python-test-5417
python
What do beaker execute ?
a beaker build step
def beaker registry xml parent data beaker XML Sub Element xml parent 'org jenkinsci plugins beakerbuilder Beaker Builder' job Source XML Sub Element beaker 'job Source' if 'content' in data and 'path' in data raise Jenkins Jobs Exception " Usejustoneof'content'or'path'" elif 'content' in data job Source Class 'org jen...
def beaker registry xml_parent data beaker XML SubElement xml_parent 'org jenkinsci plugins beakerbuilder BeakerBuilder' jobSource XML SubElement beaker 'jobSource' if 'content' in data and 'path' in data raise JenkinsJobsException "Usejustoneof'content'or'path'" elif 'content' in data jobSourceClass 'org jenkinsci plu...
116
python-test-5420
python
What does the code add to a question ?
a named tag
def add tag request question id tag name request POST get 'tag-name' '' strip if tag name question get object or 404 Question pk question id try canonical name add existing tag tag name question tags except Tag Does Not Exist if request user has perm 'taggit add tag' question tags add tag name canonical name tag nameel...
def _add_tag request question_id tag_name request POST get 'tag-name' '' strip if tag_name question get_object_or_404 Question pk question_id try canonical_name add_existing_tag tag_name question tags except Tag DoesNotExist if request user has_perm 'taggit add_tag' question tags add tag_name canonical_name tag_nameels...
78
python-test-5425
python
What does the code get ?
all appropriate newer changeset revisions for the repository defined by the received tool_shed_url / name / owner combination
def get updated changeset revisions from tool shed app tool shed url name owner changeset revision tool shed url common util get tool shed url from tool shed registry app tool shed url if tool shed url is None or name is None or owner is None or changeset revision is None message ' Unabletogetupdatedchangesetrevisionsf...
def get_updated_changeset_revisions_from_tool_shed app tool_shed_url name owner changeset_revision tool_shed_url common_util get_tool_shed_url_from_tool_shed_registry app tool_shed_url if tool_shed_url is None or name is None or owner is None or changeset_revision is None message 'Unabletogetupdatedchangesetrevisionsfr...
124
python-test-5426
python
What does the code generate ?
a filter condition for host and cluster fields
def filter host field value match level None if match level is None if '#' in value match level 'pool'elif '@' in value match level 'backend'else match level 'host'conn str CONF database connectionif conn str startswith 'mysql' and conn str[ 5 ] in ['+' ' '] cmp value func binary value like op 'LIKEBINARY'else cmp valu...
def _filter_host field value match_level None if match_level is None if '#' in value match_level 'pool'elif '@' in value match_level 'backend'else match_level 'host'conn_str CONF database connectionif conn_str startswith 'mysql' and conn_str[5] in ['+' ' '] cmp_value func binary value like_op 'LIKEBINARY'else cmp_value...
92
python-test-5427
python
Where do decorator require a content type ?
in a handler
def require content content type def decorator f @functools wraps f def decorated function req if req content type content type raise webob exc HTTP Unsupported Media Type ' Themediatype% bad type sisnotsupported use% good type s' % {'bad type' req content type or ' None' 'good type' content type} json formatter json e...
def require_content content_type def decorator f @functools wraps f def decorated_function req if req content_type content_type raise webob exc HTTPUnsupportedMediaType _ 'Themediatype% bad_type sisnotsupported use% good_type s' % {'bad_type' req content_type or 'None' 'good_type' content_type} json_formatter json_erro...
63
python-test-5431
python
What does the code calcuate ?
the simple average over one hour
def first hour average timeseries last hour threshold time - FULL DURATION - 3600 series pandas Series [x[ 1 ] for x in timeseries if x[ 0 ] < last hour threshold ] mean series mean std Dev series std t tail avg timeseries return abs t - mean > 3 * std Dev
def first_hour_average timeseries last_hour_threshold time - FULL_DURATION - 3600 series pandas Series [x[1] for x in timeseries if x[0] < last_hour_threshold ] mean series mean stdDev series std t tail_avg timeseries return abs t - mean > 3 * stdDev
54
python-test-5433
python
What do the debian tools root ?
the root of the image
def bootstrap deb root arch flavor repo url None static qemu None pkgs None exclude pkgs None if repo url is None repo url 'http //ftp debian org/debian/'deb args ['debootstrap' '--foreign' '--arch' cmd quote arch '--include'] + pkgs + ['--exclude'] + exclude pkgs + [ cmd quote flavor cmd quote root cmd quote repo url ...
def _bootstrap_deb root arch flavor repo_url None static_qemu None pkgs None exclude_pkgs None if repo_url is None repo_url 'http //ftp debian org/debian/'deb_args ['debootstrap' '--foreign' '--arch' _cmd_quote arch '--include'] + pkgs + ['--exclude'] + exclude_pkgs + [_cmd_quote flavor _cmd_quote root _cmd_quote repo_...
119
python-test-5440
python
For what purpose did by the servicetester call the code ?
in order to test query_followed service api call
def Test Query Followed tester user cookie request dict validator tester validator user id device id tester Get Ids From Cookie user cookie def Make Viewpoint Dict followed ' Createaviewpointdictfromthefollowedobjectplusits\nreferencedviewpointobject \n'viewpoint validator Get Model Object Viewpoint followed viewpoint ...
def _TestQueryFollowed tester user_cookie request_dict validator tester validator user_id device_id tester GetIdsFromCookie user_cookie def _MakeViewpointDict followed 'Createaviewpointdictfromthefollowedobjectplusits\nreferencedviewpointobject \n'viewpoint validator GetModelObject Viewpoint followed viewpoint_id follo...
166
python-test-5441
python
What does the code create ?
a metadef resource type
@log calldef metadef resource type create context values global DAT Aresource type values copy deepcopy values resource type name resource type values['name']allowed attrubites ['name' 'protected']for resource type in DATA['metadef resource types'] if resource type['name'] resource type name raise exception Duplicate i...
@log_calldef metadef_resource_type_create context values global DATAresource_type_values copy deepcopy values resource_type_name resource_type_values['name']allowed_attrubites ['name' 'protected']for resource_type in DATA['metadef_resource_types'] if resource_type['name'] resource_type_name raise exception Duplicate in...
80
python-test-5445
python
What does the code find ?
a user i d and group i d from a string like user : group
def colon separated user group arg try parts arg split ' ' 1 if len parts 1 uid name to uid parts[ 0 ] gid -1 else uid name to uid parts[ 0 ] gid name to gid parts[ 1 ] return uid gid except raise Value Error ' Invaliduser groupdefinition%s' % arg
def colon_separated_user_group arg try parts arg split ' ' 1 if len parts 1 uid name_to_uid parts[0] gid -1 else uid name_to_uid parts[0] gid name_to_gid parts[1] return uid gid except raise ValueError 'Invaliduser groupdefinition%s' % arg
53
python-test-5447
python
How does a line split into tokens ?
using same rules as mpd
def split line if not line strip raise exceptions Mpd No Command u' Nocommandgiven' match WORD RE match line if not match raise exceptions Mpd Unknown Error u' Invalidwordcharacter' whitespace command remainder match groups if whitespace raise exceptions Mpd Unknown Error u' Letterexpected' result [command]while remain...
def split line if not line strip raise exceptions MpdNoCommand u'Nocommandgiven' match WORD_RE match line if not match raise exceptions MpdUnknownError u'Invalidwordcharacter' whitespace command remainder match groups if whitespace raise exceptions MpdUnknownError u'Letterexpected' result [command]while remainder match...
85
python-test-5449
python
What does the code equalize ?
the image histogram
def equalize image mask None if image mode 'P' image image convert 'RGB' h image histogram mask lut []for b in range 0 len h 256 histo [ f for f in h[b b + 256 ] if f]if len histo < 1 lut extend list range 256 else step functools reduce operator add histo - histo[ -1 ] // 255 if not step lut extend list range 256 else ...
def equalize image mask None if image mode 'P' image image convert 'RGB' h image histogram mask lut []for b in range 0 len h 256 histo [_f for _f in h[b b + 256 ] if _f]if len histo < 1 lut extend list range 256 else step functools reduce operator add histo - histo[ -1 ] // 255 if not step lut extend list range 256 els...
96
python-test-5450
python
What does the code run ?
the api server
@taskdef apiserver ctx port 8000 wait True autoreload True host '127 0 0 1' pty True env os environ copy cmd 'DJANGO SETTINGS MODULE api base settings{}manage pyrunserver{} {}--nothreading' format sys executable host port if not autoreload cmd + '--noreload'if settings SECURE MODE cmd cmd replace 'runserver' 'runsslser...
@taskdef apiserver ctx port 8000 wait True autoreload True host '127 0 0 1' pty True env os environ copy cmd 'DJANGO_SETTINGS_MODULE api base settings{}manage pyrunserver{} {}--nothreading' format sys executable host port if not autoreload cmd + '--noreload'if settings SECURE_MODE cmd cmd replace 'runserver' 'runsslser...
80
python-test-5452
python
What does the code create ?
a generic query to filter documents
def get filter query args query Q for arg in args if hasattr Document arg and args[arg] append Q **{str 'document ' + arg + ' id' long args[arg] } append append Q **{str 'file ' + arg + ' id' long args[arg] } append append Q **{str 'weblink ' + arg + ' id' long args[arg] } query query & append return query
def _get_filter_query args query Q for arg in args if hasattr Document arg and args[arg] append Q **{str 'document__' + arg + '__id' long args[arg] } append append Q **{str 'file__' + arg + '__id' long args[arg] } append append Q **{str 'weblink__' + arg + '__id' long args[arg] } query query & append return query
64
python-test-5453
python
How do a list of strings sort ?
by alphabetical order
def number aware alphabetical cmp str 1 str 2 def flatten tokens tokens l []for token in tokens if isinstance token str for char in token l append char else assert isinstance token float l append token return lseq 1 flatten tokens tokenize by number str 1 seq 2 flatten tokens tokenize by number str 2 l min len seq 1 le...
def number_aware_alphabetical_cmp str1 str2 def flatten_tokens tokens l []for token in tokens if isinstance token str for char in token l append char else assert isinstance token float l append token return lseq1 flatten_tokens tokenize_by_number str1 seq2 flatten_tokens tokenize_by_number str2 l min len seq1 len seq2 ...
140
python-test-5454
python
What did the code set ?
individual proximity component
def setup proximity component hass name config ignored zones config get CONF IGNORED ZONES proximity devices config get CONF DEVICES tolerance config get CONF TOLERANCE proximity zone nameunit of measurement config get CONF UNIT OF MEASUREMENT hass config units length unit zone id 'zone {}' format proximity zone proxim...
def setup_proximity_component hass name config ignored_zones config get CONF_IGNORED_ZONES proximity_devices config get CONF_DEVICES tolerance config get CONF_TOLERANCE proximity_zone nameunit_of_measurement config get CONF_UNIT_OF_MEASUREMENT hass config units length_unit zone_id 'zone {}' format proximity_zone proxim...
99
python-test-5458
python
What does openshift - build - verify perform once the list of builds are obtained ?
the equivalent of an oc get builds command invocation for the provided buildconfig key provided
def openshift build verify registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Build Verifier' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'bld-cfg' 'bld Cfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'auth Token' '' 've...
def openshift_build_verify registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftBuildVerifier' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'bld-cfg' 'bldCfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'authToken' '' 'verbose' ...
58
python-test-5459
python
When does openshift - build - verify perform the equivalent of an oc get builds command invocation for the provided buildconfig key provided ?
once the list of builds are obtained
def openshift build verify registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Build Verifier' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'bld-cfg' 'bld Cfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'auth Token' '' 've...
def openshift_build_verify registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftBuildVerifier' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'bld-cfg' 'bldCfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'authToken' '' 'verbose' ...
58
python-test-5460
python
For what purpose does command invocation build ?
for the provided buildconfig key provided
def openshift build verify registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Build Verifier' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'bld-cfg' 'bld Cfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'auth Token' '' 've...
def openshift_build_verify registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftBuildVerifier' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'bld-cfg' 'bldCfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'authToken' '' 'verbose' ...
58
python-test-5461
python
What performs the equivalent of an oc get builds command invocation for the provided buildconfig key provided once the list of builds are obtained ?
openshift - build - verify
def openshift build verify registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Build Verifier' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'bld-cfg' 'bld Cfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'auth Token' '' 've...
def openshift_build_verify registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftBuildVerifier' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'bld-cfg' 'bldCfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'authToken' '' 'verbose' ...
58
python-test-5462
python
What does the code compute ?
the triangle activation function used in adam coates aistats 2011 paper
def triangle code X centroids X sqr T sqr X sum axis 1 dimshuffle 0 'x' c sqr T sqr centroids sum axis 1 dimshuffle 'x' 0 c sqr name 'c sqr' Xc T dot X centroids T Xc name ' Xc'sq dists c sqr + X sqr - 2 0 * Xc sq dists safe T clip sq dists 0 0 1e+ 30 Z T sqrt sq dists safe Z name 'Z'mu Z mean axis 1 mu name 'mu'mu mu ...
def triangle_code X centroids X_sqr T sqr X sum axis 1 dimshuffle 0 'x' c_sqr T sqr centroids sum axis 1 dimshuffle 'x' 0 c_sqr name 'c_sqr'Xc T dot X centroids T Xc name 'Xc'sq_dists c_sqr + X_sqr - 2 0 * Xc sq_dists_safe T clip sq_dists 0 0 1e+30 Z T sqrt sq_dists_safe Z name 'Z'mu Z mean axis 1 mu name 'mu'mu mu dim...
102
python-test-5469
python
What do the user choose ?
their plugin
def choose plugin prepared question opts [ plugin ep description with name + '[ Misconfigured]' if plugin ep misconfigured else '' for plugin ep in prepared]while True disp z util interfaces I Display code index disp menu question opts help label ' More Info' force interactive True if code display util OK plugin ep pre...
def choose_plugin prepared question opts [ plugin_ep description_with_name + '[Misconfigured]' if plugin_ep misconfigured else '' for plugin_ep in prepared]while True disp z_util interfaces IDisplay code index disp menu question opts help_label 'MoreInfo' force_interactive True if code display_util OK plugin_ep prepare...
114
python-test-5470
python
What does the code calculate over data if specified ?
standard internet checksum
def checksum data start 0 skip word None if len data % 2 0 arr array array 'H' data[ -1 ] else arr array array 'H' data if skip word is not None for i in range 0 len arr if i skip word continuestart + arr[i]else for i in range 0 len arr start + arr[i]if len data % 2 0 start + struct unpack 'H' data[ -1 ] + '\x 00 ' [0 ...
def checksum data start 0 skip_word None if len data % 2 0 arr array array 'H' data[ -1 ] else arr array array 'H' data if skip_word is not None for i in range 0 len arr if i skip_word continuestart + arr[i]else for i in range 0 len arr start + arr[i]if len data % 2 0 start + struct unpack 'H' data[ -1 ] + '\x00' [0]st...
94
python-test-5471
python
What does the code return to a list of tuples ?
a map of servers
def wait on interfaces interfaces timeout 10 result defaultdict list timeout time time + timeout while len result < len interfaces and time time < timeout rin [i for i in interfaces values ]win [i for i in interfaces values if i unsent requests] rout wout xout select select rin win [] 1 for interface in wout interface ...
def wait_on_interfaces interfaces timeout 10 result defaultdict list timeout time time + timeout while len result < len interfaces and time time < timeout rin [i for i in interfaces values ]win [i for i in interfaces values if i unsent_requests] rout wout xout select select rin win [] 1 for interface in wout interface ...
76
python-test-5472
python
What does the service version description document indicate ?
that the desired version is supported
def Version Is Supported desired Version service Version Description root service Version Descriptionif root tag 'namespaces' if root get 'version' '1 0' raise Runtime Error 'vim Service Versions xmlhasversion%s whichisnotunderstood' % root get 'version' desired Version Id version Id Map[desired Version]supported Versi...
def __VersionIsSupported desiredVersion serviceVersionDescription root serviceVersionDescriptionif root tag 'namespaces' if root get 'version' '1 0' raise RuntimeError 'vimServiceVersions xmlhasversion%s whichisnotunderstood' % root get 'version' desiredVersionId versionIdMap[desiredVersion]supportedVersion Nonefor nam...
113
python-test-5473
python
What indicates that the desired version is supported ?
the service version description document
def Version Is Supported desired Version service Version Description root service Version Descriptionif root tag 'namespaces' if root get 'version' '1 0' raise Runtime Error 'vim Service Versions xmlhasversion%s whichisnotunderstood' % root get 'version' desired Version Id version Id Map[desired Version]supported Versi...
def __VersionIsSupported desiredVersion serviceVersionDescription root serviceVersionDescriptionif root tag 'namespaces' if root get 'version' '1 0' raise RuntimeError 'vimServiceVersions xmlhasversion%s whichisnotunderstood' % root get 'version' desiredVersionId versionIdMap[desiredVersion]supportedVersion Nonefor nam...
113
python-test-5478
python
What does you run manually ?
the groomer
def main zk connection locations appscale info get zk locations string zookeeper zk ZK Transaction host zk connection locations start gc False db info appscale info get db info table db info[' table']master appscale info get db master ip datastore path '{ 0 } 8888 ' format master ds groomer Datastore Groomer zookeeper ...
def main zk_connection_locations appscale_info get_zk_locations_string zookeeper zk ZKTransaction host zk_connection_locations start_gc False db_info appscale_info get_db_info table db_info[' table']master appscale_info get_db_master_ip datastore_path '{0} 8888' format master ds_groomer DatastoreGroomer zookeeper table...
150
python-test-5479
python
What does this main function allow ?
you to run the groomer manually
def main zk connection locations appscale info get zk locations string zookeeper zk ZK Transaction host zk connection locations start gc False db info appscale info get db info table db info[' table']master appscale info get db master ip datastore path '{ 0 } 8888 ' format master ds groomer Datastore Groomer zookeeper ...
def main zk_connection_locations appscale_info get_zk_locations_string zookeeper zk ZKTransaction host zk_connection_locations start_gc False db_info appscale_info get_db_info table db_info[' table']master appscale_info get_db_master_ip datastore_path '{0} 8888' format master ds_groomer DatastoreGroomer zookeeper table...
150
python-test-5480
python
What does the code get ?
the course modes for course
def get course enrollment details course id include expired False cache key u'enrollment course details {course id} {include expired}' format course id course id include expired include expired cached enrollment data Nonetry cached enrollment data cache get cache key except Exception log exception u' Erroroccurredwhile...
def get_course_enrollment_details course_id include_expired False cache_key u'enrollment course details {course_id} {include_expired}' format course_id course_id include_expired include_expired cached_enrollment_data Nonetry cached_enrollment_data cache get cache_key except Exception log exception u'Erroroccurredwhiler...
121
python-test-5488
python
What is ignoring querystrings * trimming off the initial / * trimming off the file extension ?
just the path name
def generate module src if not src return UNKNOWN MODULE filename ext splitext urlsplit src path if ext not in ' js' ' jsx' ' coffee' return UNKNOWN MODUL Eif filename endswith ' min' filename filename[ -4 ]tokens filename split '/' for idx token in enumerate tokens if VERSION RE match token return '/' join tokens[ idx...
def generate_module src if not src return UNKNOWN_MODULE filename ext splitext urlsplit src path if ext not in ' js' ' jsx' ' coffee' return UNKNOWN_MODULEif filename endswith ' min' filename filename[ -4 ]tokens filename split '/' for idx token in enumerate tokens if VERSION_RE match token return '/' join tokens[ idx ...
70
python-test-5489
python
How does a url convert into a made - up module name ?
by doing the following : * extract just the path name ignoring querystrings * trimming off the initial / * trimming off the file extension * removes off useless folder prefixes e
def generate module src if not src return UNKNOWN MODULE filename ext splitext urlsplit src path if ext not in ' js' ' jsx' ' coffee' return UNKNOWN MODUL Eif filename endswith ' min' filename filename[ -4 ]tokens filename split '/' for idx token in enumerate tokens if VERSION RE match token return '/' join tokens[ idx...
def generate_module src if not src return UNKNOWN_MODULE filename ext splitext urlsplit src path if ext not in ' js' ' jsx' ' coffee' return UNKNOWN_MODULEif filename endswith ' min' filename filename[ -4 ]tokens filename split '/' for idx token in enumerate tokens if VERSION_RE match token return '/' join tokens[ idx ...
70
python-test-5490
python
What do just the path name ignore ?
querystrings * trimming off the initial / * trimming off the file extension
def generate module src if not src return UNKNOWN MODULE filename ext splitext urlsplit src path if ext not in ' js' ' jsx' ' coffee' return UNKNOWN MODUL Eif filename endswith ' min' filename filename[ -4 ]tokens filename split '/' for idx token in enumerate tokens if VERSION RE match token return '/' join tokens[ idx...
def generate_module src if not src return UNKNOWN_MODULE filename ext splitext urlsplit src path if ext not in ' js' ' jsx' ' coffee' return UNKNOWN_MODULEif filename endswith ' min' filename filename[ -4 ]tokens filename split '/' for idx token in enumerate tokens if VERSION_RE match token return '/' join tokens[ idx ...
70
python-test-5492
python
For what purpose do this register activate ?
to turn on a minion status tracking register
def reg name ret {'name' name 'changes' {} 'comment' '' 'result' True}now time time if 'status' not in reg reg ['status'] {} reg ['status']['val'] {}for event in events if fnmatch fnmatch event['tag'] 'salt/beacon/*/status/*' idata {'recv time' now}for key in event['data']['data'] if key in 'id' 'recv time' continueida...
def reg name ret {'name' name 'changes' {} 'comment' '' 'result' True}now time time if 'status' not in __reg__ __reg__['status'] {}__reg__['status']['val'] {}for event in __events__ if fnmatch fnmatch event['tag'] 'salt/beacon/*/status/*' idata {'recv_time' now}for key in event['data']['data'] if key in 'id' 'recv_time...
53
python-test-5493
python
When is an error not raised ?
for future times not covered by iers
def test regression futuretimes 4302 from utils exceptions import Astropy Warningfrom builtin frames import utilsif hasattr utils u' warningregistry ' utils warningregistry clear with catch warnings as found warnings future time Time u' 2511 - 5 - 1 ' c CIRS 1 * u deg 2 * u deg obstime future time c transform to ITRS o...
def test_regression_futuretimes_4302 from utils exceptions import AstropyWarningfrom builtin_frames import utilsif hasattr utils u'__warningregistry__' utils __warningregistry__ clear with catch_warnings as found_warnings future_time Time u'2511-5-1' c CIRS 1 * u deg 2 * u deg obstime future_time c transform_to ITRS ob...
105
python-test-5500
python
What did the code convert into a list ?
each relation clause
def str 2 records filename rel recs []contents nltk data load u'corpora/chat 80 /%s' % filename format u'text' for line in contents splitlines if line startswith rel line re sub rel + u'\\ ' u'' line line re sub u'\\ \\ $' u'' line record line split u' ' recs append record return recs
def _str2records filename rel recs []contents nltk data load u'corpora/chat80/%s' % filename format u'text' for line in contents splitlines if line startswith rel line re sub rel + u'\\ ' u'' line line re sub u'\\ \\ $' u'' line record line split u' ' recs append record return recs
54
python-test-5506
python
What does the code ensure ?
the named launch configuration is deleted
def absent name region None key None keyid None profile None ret {'name' name 'result' True 'comment' '' 'changes' {}}exists salt ['boto asg launch configuration exists'] name region region key key keyid keyid profile profile if exists if opts ['test'] ret['comment'] ' Launchconfigurationsettobedeleted 'ret['result'] N...
def absent name region None key None keyid None profile None ret {'name' name 'result' True 'comment' '' 'changes' {}}exists __salt__['boto_asg launch_configuration_exists'] name region region key key keyid keyid profile profile if exists if __opts__['test'] ret['comment'] 'Launchconfigurationsettobedeleted 'ret['resul...
79
python-test-5507
python
What does the code deploy your documentation ?
to github pages
@cli command name u'gh-deploy' @click option u'-c' u'--clean/--dirty' is flag True default True help clean help @click option u'-f' u'--config-file' type click File u'rb' help config help @click option u'-m' u'--message' help commit message help @click option u'-b' u'--remote-branch' help remote branch help @click opti...
@cli command name u'gh-deploy' @click option u'-c' u'--clean/--dirty' is_flag True default True help clean_help @click option u'-f' u'--config-file' type click File u'rb' help config_help @click option u'-m' u'--message' help commit_message_help @click option u'-b' u'--remote-branch' help remote_branch_help @click opti...
119
python-test-5508
python
What does the code deploy to github pages ?
your documentation
@cli command name u'gh-deploy' @click option u'-c' u'--clean/--dirty' is flag True default True help clean help @click option u'-f' u'--config-file' type click File u'rb' help config help @click option u'-m' u'--message' help commit message help @click option u'-b' u'--remote-branch' help remote branch help @click opti...
@cli command name u'gh-deploy' @click option u'-c' u'--clean/--dirty' is_flag True default True help clean_help @click option u'-f' u'--config-file' type click File u'rb' help config_help @click option u'-m' u'--message' help commit_message_help @click option u'-b' u'--remote-branch' help remote_branch_help @click opti...
119
python-test-5509
python
What does the code find ?
the corresponding < that started a template
def Find Previous Matching Angle Bracket clean lines linenum init prefix line init prefixnesting stack ['>']while True match Search '^ * [<> \\[\\]] [^<> \\[\\]]*$' line if match operator match group 2 line match group 1 if nesting stack[ -1 ] '>' if operator in '>' ' ' ']' nesting stack append operator elif operator '...
def FindPreviousMatchingAngleBracket clean_lines linenum init_prefix line init_prefixnesting_stack ['>']while True match Search '^ * [<> \\[\\]] [^<> \\[\\]]*$' line if match operator match group 2 line match group 1 if nesting_stack[ -1 ] '>' if operator in '>' ' ' ']' nesting_stack append operator elif operator '<' n...
103
python-test-5510
python
What started a template ?
the corresponding < that
def Find Previous Matching Angle Bracket clean lines linenum init prefix line init prefixnesting stack ['>']while True match Search '^ * [<> \\[\\]] [^<> \\[\\]]*$' line if match operator match group 2 line match group 1 if nesting stack[ -1 ] '>' if operator in '>' ' ' ']' nesting stack append operator elif operator '...
def FindPreviousMatchingAngleBracket clean_lines linenum init_prefix line init_prefixnesting_stack ['>']while True match Search '^ * [<> \\[\\]] [^<> \\[\\]]*$' line if match operator match group 2 line match group 1 if nesting_stack[ -1 ] '>' if operator in '>' ' ' ']' nesting_stack append operator elif operator '<' n...
103
python-test-5515
python
What does the code find ?
the rotation matrix that maps unit vector a to b
def find vector rotation a b R np eye 3 v np cross a b if np allclose v 0 0 return Rs np dot v v c np dot a b vx skew symmetric cross v R + vx + np dot vx vx * 1 - c / s return R
def _find_vector_rotation a b R np eye 3 v np cross a b if np allclose v 0 0 return Rs np dot v v c np dot a b vx _skew_symmetric_cross v R + vx + np dot vx vx * 1 - c / s return R
53
python-test-5516
python
What does the rotation matrix map ?
unit vector a to b
def find vector rotation a b R np eye 3 v np cross a b if np allclose v 0 0 return Rs np dot v v c np dot a b vx skew symmetric cross v R + vx + np dot vx vx * 1 - c / s return R
def _find_vector_rotation a b R np eye 3 v np cross a b if np allclose v 0 0 return Rs np dot v v c np dot a b vx _skew_symmetric_cross v R + vx + np dot vx vx * 1 - c / s return R
53
python-test-5517
python
What maps unit vector a to b ?
the rotation matrix
def find vector rotation a b R np eye 3 v np cross a b if np allclose v 0 0 return Rs np dot v v c np dot a b vx skew symmetric cross v R + vx + np dot vx vx * 1 - c / s return R
def _find_vector_rotation a b R np eye 3 v np cross a b if np allclose v 0 0 return Rs np dot v v c np dot a b vx _skew_symmetric_cross v R + vx + np dot vx vx * 1 - c / s return R
53
python-test-5518
python
What does the code get ?
links that are rising right now
def get rising items omit sr ids count 4 all rising rising get all rising candidate sr ids {sr id for link score sr id in all rising} difference omit sr ids link fullnames [link for link score sr id in all rising if sr id in candidate sr ids ]link fullnames to show random sample link fullnames count rising links Link b...
def get_rising_items omit_sr_ids count 4 all_rising rising get_all_rising candidate_sr_ids {sr_id for link score sr_id in all_rising} difference omit_sr_ids link_fullnames [link for link score sr_id in all_rising if sr_id in candidate_sr_ids ]link_fullnames_to_show random_sample link_fullnames count rising_links Link _...
95
python-test-5520
python
What do we want ?
a prettier default format
def setup logging stream None hdlr logging Stream Handler stream default Fmt '% name s % levelname s % message s'info Fmt '% name s % message s'fmtr Per Level Formatter fmt default Fmt fmt From Level {logging INFO info Fmt} hdlr set Formatter fmtr logging root add Handler hdlr log set Level logging INFO
def _setup_logging stream None hdlr logging StreamHandler stream defaultFmt '% name s % levelname s % message s'infoFmt '% name s % message s'fmtr _PerLevelFormatter fmt defaultFmt fmtFromLevel {logging INFO infoFmt} hdlr setFormatter fmtr logging root addHandler hdlr log setLevel logging INFO
55
python-test-5525
python
Where does it show ?
in the gui
def load Icon stock item id stock item getattr gtk stock item id local icon os path join GUI DATA PATH 'icons' '16 ' '%s png' % stock item if os path exists local icon im gtk Image im set from file local icon im show return im get pixbuf else icon theme gtk Icon Theme try icon icon theme load icon stock item 16 except ...
def loadIcon stock_item_id stock_item getattr gtk stock_item_id local_icon os path join GUI_DATA_PATH 'icons' '16' '%s png' % stock_item if os path exists local_icon im gtk Image im set_from_file local_icon im show return im get_pixbuf else icon_theme gtk IconTheme try icon icon_theme load_icon stock_item 16 except ico...
75
python-test-5526
python
For what purpose does an icon load ?
to show it in the gui
def load Icon stock item id stock item getattr gtk stock item id local icon os path join GUI DATA PATH 'icons' '16 ' '%s png' % stock item if os path exists local icon im gtk Image im set from file local icon im show return im get pixbuf else icon theme gtk Icon Theme try icon icon theme load icon stock item 16 except ...
def loadIcon stock_item_id stock_item getattr gtk stock_item_id local_icon os path join GUI_DATA_PATH 'icons' '16' '%s png' % stock_item if os path exists local_icon im gtk Image im set_from_file local_icon im show return im get_pixbuf else icon_theme gtk IconTheme try icon icon_theme load_icon stock_item 16 except ico...
75
python-test-5530
python
What does the code get ?
the descendents which have the given local name
def get Elements By Local Name child Nodes local Name elements By Local Name get Child Elements By Local Name child Nodes local Name for child Node in child Nodes if child Node get Node Type 1 elements By Local Name + child Node get Elements By Local Name local Name return elements By Local Name
def getElementsByLocalName childNodes localName elementsByLocalName getChildElementsByLocalName childNodes localName for childNode in childNodes if childNode getNodeType 1 elementsByLocalName + childNode getElementsByLocalName localName return elementsByLocalName
56
python-test-5531
python
What have the given local name ?
the descendents
def get Elements By Local Name child Nodes local Name elements By Local Name get Child Elements By Local Name child Nodes local Name for child Node in child Nodes if child Node get Node Type 1 elements By Local Name + child Node get Elements By Local Name local Name return elements By Local Name
def getElementsByLocalName childNodes localName elementsByLocalName getChildElementsByLocalName childNodes localName for childNode in childNodes if childNode getNodeType 1 elementsByLocalName + childNode getElementsByLocalName localName return elementsByLocalName
56
python-test-5537
python
Does the code use this method ?
No
def start **kwargs import osfrom psychopy import visualopen Windows visual window open Windowsif len open Windows 0 print ' The Psycho Py Windowmustbecreatedpriortostartingiohub Exiting 'sys exit 1 '\n Display \nname display\nreporting unit type pix\ndevice number 0\nphysical dimensions \nwidth 500 \nheight 281 \nunit ...
def _start **kwargs import osfrom psychopy import visualopenWindows visual window openWindowsif len openWindows 0 print 'ThePsychoPyWindowmustbecreatedpriortostartingiohub Exiting 'sys exit 1 '\nDisplay \nname display\nreporting_unit_type pix\ndevice_number 0\nphysical_dimensions \nwidth 500\nheight 281\nunit_type mm\n...
137
python-test-5549
python
What does the code get ?
information for a role
def describe role name region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile try info conn get role name if not info return Falserole info get role response get role result rolerole['assume role policy document'] json loads unquote role assume role policy document ...
def describe_role name region None key None keyid None profile None conn _get_conn region region key key keyid keyid profile profile try info conn get_role name if not info return Falserole info get_role_response get_role_result rolerole['assume_role_policy_document'] json loads _unquote role assume_role_policy_documen...
107
python-test-5550
python
What does the code get ?
the email addresses collected between startdate and enddate
def get email addresses survey startdate enddate token settings SURVEYGIZMO API TOKE Nsecret settings SURVEYGIZMO API TOKEN SECRE Temails []page 1more pages Truesurvey id SURVEYS[survey]['email collection survey id']if token is None or secret is None return emailswhile more pages response requests get 'https //restapi ...
def get_email_addresses survey startdate enddate token settings SURVEYGIZMO_API_TOKENsecret settings SURVEYGIZMO_API_TOKEN_SECRETemails []page 1more_pages Truesurvey_id SURVEYS[survey]['email_collection_survey_id']if token is None or secret is None return emailswhile more_pages response requests get 'https //restapi su...
134
python-test-5551
python
Where did the email addresses collect ?
between startdate and enddate
def get email addresses survey startdate enddate token settings SURVEYGIZMO API TOKE Nsecret settings SURVEYGIZMO API TOKEN SECRE Temails []page 1more pages Truesurvey id SURVEYS[survey]['email collection survey id']if token is None or secret is None return emailswhile more pages response requests get 'https //restapi ...
def get_email_addresses survey startdate enddate token settings SURVEYGIZMO_API_TOKENsecret settings SURVEYGIZMO_API_TOKEN_SECRETemails []page 1more_pages Truesurvey_id SURVEYS[survey]['email_collection_survey_id']if token is None or secret is None return emailswhile more_pages response requests get 'https //restapi su...
134
python-test-5552
python
What does the code remove ?
template wikimedia markup
def remove template s n open n close 0 0 starts ends [] [] in template Falseprev c Nonefor i c in enumerate iter s if not in template if c '{' and c prev c starts append i - 1 in template Truen open 1if in template if c '{' n open + 1elif c '}' n close + 1if n open n close ends append i in template False n open n close...
def remove_template s n_open n_close 0 0 starts ends [] [] in_template Falseprev_c Nonefor i c in enumerate iter s if not in_template if c '{' and c prev_c starts append i - 1 in_template Truen_open 1if in_template if c '{' n_open + 1elif c '}' n_close + 1if n_open n_close ends append i in_template False n_open n_close...
104
python-test-5556
python
For what purpose does registration logs migrate ?
to set params[node ] to registered_from and params[registration ] to the registration
def migrate log logs logs count logs count count 0for log in logs count + 1node log params get 'node' or log params get 'project' params node Node load node if params node is registration log params['node'] get registered from params node log params['registration'] params node idelse log params['registration'] Registra...
def migrate_log logs logs_count logs count count 0for log in logs count + 1node log params get 'node' or log params get 'project' params_node Node load node if params_node is_registration log params['node'] get_registered_from params_node log params['registration'] params_node _idelse log params['registration'] Registr...
80
python-test-5557
python
What do columns need ?
joining
def expected cols expected attrs if not expected attrs return expected attrssimple cols [attr for attr in expected attrs if attr in INSTANCE OPTIONAL JOINED FIELDS ]complex cols [ 'extra %s' % field for field in INSTANCE EXTRA FIELDS if field in expected attrs ]if complex cols simple cols append 'extra' simple cols [x ...
def _expected_cols expected_attrs if not expected_attrs return expected_attrssimple_cols [attr for attr in expected_attrs if attr in _INSTANCE_OPTIONAL_JOINED_FIELDS ]complex_cols [ 'extra %s' % field for field in _INSTANCE_EXTRA_FIELDS if field in expected_attrs ]if complex_cols simple_cols append 'extra' simple_cols ...
83
python-test-5562
python
What detects nan values ?
the code snippet example
def test detect nan nan detected [ False]def detect nan i node fn for output in fn outputs if numpy isnan output[ 0 ] any print '*** Na Ndetected***' theano printing debugprint node print ' Inputs %s' % [input[ 0 ] for input in fn inputs] print ' Outputs %s' % [output[ 0 ] for output in fn outputs] nan detected[ 0 ] Tr...
def test_detect_nan nan_detected [False]def detect_nan i node fn for output in fn outputs if numpy isnan output[0] any print '***NaNdetected***' theano printing debugprint node print 'Inputs %s' % [input[0] for input in fn inputs] print 'Outputs %s' % [output[0] for output in fn outputs] nan_detected[0] Truebreakx thea...
96
python-test-5563
python
Till when does bytes from fileobj read ?
until the msb is zero
def parse sv 8 int fileobj limit 9 num 0for i in xrange limit c fileobj read 1 if len c 1 raise EOF Errorc bytearray c num num << 7 c[ 0 ] & 127 if not c[ 0 ] & 128 return num i + 1 if limit > 0 raise Value Errorreturn 0 0
def _parse_sv8_int fileobj limit 9 num 0for i in xrange limit c fileobj read 1 if len c 1 raise EOFErrorc bytearray c num num << 7 c[0] & 127 if not c[0] & 128 return num i + 1 if limit > 0 raise ValueErrorreturn 0 0
57
python-test-5565
python
What does the view mute ?
quality checks
@pytest mark django dbdef test toggle quality check rf admin qc filter dict false positive False unit state TRANSLATED unit store translation project project disabled False qc Quality Check objects filter **qc filter first unit qc unitdata 'mute 'request create api request rf method 'post' user admin data data encode a...
@pytest mark django_dbdef test_toggle_quality_check rf admin qc_filter dict false_positive False unit__state TRANSLATED unit__store__translation_project__project__disabled False qc QualityCheck objects filter **qc_filter first unit qc unitdata 'mute 'request create_api_request rf method 'post' user admin data data enco...
112
python-test-5568
python
What loads from all certificates in a directory ?
public keys
def load certificates directory ' ' certs {}if not os path isdir directory raise IO Error ' Invalidcertificatedirectory {0 }' format directory glob string os path join directory '* key' cert files glob glob glob string for cert file in cert files public key load certificate cert file if public key certs[public key] Tru...
def load_certificates directory ' ' certs {}if not os path isdir directory raise IOError 'Invalidcertificatedirectory {0}' format directory glob_string os path join directory '* key' cert_files glob glob glob_string for cert_file in cert_files public_key _ load_certificate cert_file if public_key certs[public_key] True...
55
python-test-5569
python
What does the code write to a file ?
the blob contents
def blob to file filename hint propertyname None directory hint '' directory []def transform function value bulkload state if not directory parent dir os path dirname bulkload state filename directory append os path join parent dir directory hint if directory[ 0 ] and not os path exists directory[ 0 ] os makedirs direc...
def blob_to_file filename_hint_propertyname None directory_hint '' directory []def transform_function value bulkload_state if not directory parent_dir os path dirname bulkload_state filename directory append os path join parent_dir directory_hint if directory[0] and not os path exists directory[0] os makedirs directory...
120
python-test-5574
python
For what purpose will the amount of information be kept in the change log ?
for api gw related return values
def object reducer o names 'id' 'name' 'path' 'http Method' 'status Code' ' Created' ' Deleted' ' Updated' ' Flushed' ' Associated' ' Disassociated' result {}if isinstance o dict for k v in six iteritems o if isinstance v dict reduced v if k 'variables' else object reducer v names if reduced or name matches k names res...
def _object_reducer o names 'id' 'name' 'path' 'httpMethod' 'statusCode' 'Created' 'Deleted' 'Updated' 'Flushed' 'Associated' 'Disassociated' result {}if isinstance o dict for k v in six iteritems o if isinstance v dict reduced v if k 'variables' else _object_reducer v names if reduced or _name_matches k names result[k...
93
python-test-5575
python
What will be kept in the change log ?
the amount of information
def object reducer o names 'id' 'name' 'path' 'http Method' 'status Code' ' Created' ' Deleted' ' Updated' ' Flushed' ' Associated' ' Disassociated' result {}if isinstance o dict for k v in six iteritems o if isinstance v dict reduced v if k 'variables' else object reducer v names if reduced or name matches k names res...
def _object_reducer o names 'id' 'name' 'path' 'httpMethod' 'statusCode' 'Created' 'Deleted' 'Updated' 'Flushed' 'Associated' 'Disassociated' result {}if isinstance o dict for k v in six iteritems o if isinstance v dict reduced v if k 'variables' else _object_reducer v names if reduced or _name_matches k names result[k...
93
python-test-5576
python
Where will the amount of information be kept for api gw related return values ?
in the change log
def object reducer o names 'id' 'name' 'path' 'http Method' 'status Code' ' Created' ' Deleted' ' Updated' ' Flushed' ' Associated' ' Disassociated' result {}if isinstance o dict for k v in six iteritems o if isinstance v dict reduced v if k 'variables' else object reducer v names if reduced or name matches k names res...
def _object_reducer o names 'id' 'name' 'path' 'httpMethod' 'statusCode' 'Created' 'Deleted' 'Updated' 'Flushed' 'Associated' 'Disassociated' result {}if isinstance o dict for k v in six iteritems o if isinstance v dict reduced v if k 'variables' else _object_reducer v names if reduced or _name_matches k names result[k...
93
python-test-5580
python
What does the code stop ?
a google app engine application process instance on current machine
def stop app instance app name port if not misc is app name valid app name logging error ' Unabletokillappprocess%sonport%dbecauseofinvalidnameforapplication' % app name int port return Falselogging info ' Stoppingapplication%s' % app name watch 'app ' + app name + '-' + str port if not monit interface stop watch is gr...
def stop_app_instance app_name port if not misc is_app_name_valid app_name logging error 'Unabletokillappprocess%sonport%dbecauseofinvalidnameforapplication' % app_name int port return Falselogging info 'Stoppingapplication%s' % app_name watch 'app___' + app_name + '-' + str port if not monit_interface stop watch is_gr...
100
python-test-5583
python
What does the code extract ?
the root path for a given key
def group for key key if not isinstance key entity pb Reference key entity pb Reference key first element key path element 0 key copy entity pb Reference key copy Copy From key key copy path clear element element key copy path add element element Merge From first element return key copy
def group_for_key key if not isinstance key entity_pb Reference key entity_pb Reference key first_element key path element 0 key_copy entity_pb Reference key_copy CopyFrom key key_copy path clear_element element key_copy path add_element element MergeFrom first_element return key_copy
52
python-test-5589
python
What does this function test ?
the norbsmall class
def test NORB Small skip if no data data NORB Small 'train' assert data X shape 24300 18432 assert data X dtype 'float 32 ' assert data y shape 24300 assert data y labels 5 assert data get topological view shape 24300 96 96 2 data NORB Small 'test' assert data X shape 24300 18432 assert data X dtype 'float 32 ' assert ...
def test_NORBSmall skip_if_no_data data NORBSmall 'train' assert data X shape 24300 18432 assert data X dtype 'float32' assert data y shape 24300 assert data y_labels 5 assert data get_topological_view shape 24300 96 96 2 data NORBSmall 'test' assert data X shape 24300 18432 assert data X dtype 'float32' assert data y ...
82
python-test-5590
python
How did a single timer object test ?
under various conditions
def timer helper num handlers 1 sleep time 5 event handlers [] a Timer None error margin 0 25 global COUN Tglobal TIMER HELPER FINISHEDCOUNT 0TIMER HELPER FINISHED Falsetry if a Timer None a Timer System Timers Timer for i in xrange num handlers a Timer Elapsed + System Timers Elapsed Event Handler on Timed Event for h...
def timer_helper num_handlers 1 sleep_time 5 event_handlers [] aTimer None error_margin 0 25 global COUNTglobal TIMER_HELPER_FINISHEDCOUNT 0TIMER_HELPER_FINISHED Falsetry if aTimer None aTimer System Timers Timer for i in xrange num_handlers aTimer Elapsed + System Timers ElapsedEventHandler onTimedEvent for handler in...
140
python-test-5591
python
What did helper function use ?
to test a single timer object under various conditions
def timer helper num handlers 1 sleep time 5 event handlers [] a Timer None error margin 0 25 global COUN Tglobal TIMER HELPER FINISHEDCOUNT 0TIMER HELPER FINISHED Falsetry if a Timer None a Timer System Timers Timer for i in xrange num handlers a Timer Elapsed + System Timers Elapsed Event Handler on Timed Event for h...
def timer_helper num_handlers 1 sleep_time 5 event_handlers [] aTimer None error_margin 0 25 global COUNTglobal TIMER_HELPER_FINISHEDCOUNT 0TIMER_HELPER_FINISHED Falsetry if aTimer None aTimer System Timers Timer for i in xrange num_handlers aTimer Elapsed + System Timers ElapsedEventHandler onTimedEvent for handler in...
140
python-test-5593
python
What does the code handle ?
the m2m_changed event for localsite and user
@receiver m2 m changed sender Local Site users through def on local site users changed sender instance model action pk set **kwargs if action u'post add' if isinstance instance User users [instance]local sites Local Site objects filter id in pk set else users User objects filter id in pk set local sites [instance]for u...
@receiver m2m_changed sender LocalSite users through def _on_local_site_users_changed sender instance model action pk_set **kwargs if action u'post_add' if isinstance instance User users [instance]local_sites LocalSite objects filter id__in pk_set else users User objects filter id__in pk_set local_sites [instance]for u...
76
python-test-5597
python
What does the code read ?
the cache file of a bibliography file
def read fmt bib name bib file cache name formatted cache name cache name bib name bib file try meta data formatted entries cache read global formatted cache name except raise cache Cache Miss modified time os path getmtime bib file if modified time > meta data['cache time'] raise cache Cache Miss if meta data['version...
def read_fmt bib_name bib_file cache_name formatted_cache_name _cache_name bib_name bib_file try meta_data formatted_entries cache read_global formatted_cache_name except raise cache CacheMiss modified_time os path getmtime bib_file if modified_time > meta_data['cache_time'] raise cache CacheMiss if meta_data['version'...
102
python-test-5598
python
For what purpose did the code set an aes dropfile ?
to request the master update the publish session key
def dropfile cachedir user None dfn os path join cachedir ' dfn' mask os umask 191 try log info ' Rotating AE Skey' if os path isfile dfn log info 'AE Skeyrotationalreadyrequested' returnif os path isfile dfn and not os access dfn os W OK os chmod dfn stat S IRUSR stat S IWUSR with salt utils fopen dfn 'wb+' as fp fp w...
def dropfile cachedir user None dfn os path join cachedir ' dfn' mask os umask 191 try log info 'RotatingAESkey' if os path isfile dfn log info 'AESkeyrotationalreadyrequested' returnif os path isfile dfn and not os access dfn os W_OK os chmod dfn stat S_IRUSR stat S_IWUSR with salt utils fopen dfn 'wb+' as fp_ fp_ wri...
98
python-test-5599
python
What did the code set to request the master update the publish session key ?
an aes dropfile
def dropfile cachedir user None dfn os path join cachedir ' dfn' mask os umask 191 try log info ' Rotating AE Skey' if os path isfile dfn log info 'AE Skeyrotationalreadyrequested' returnif os path isfile dfn and not os access dfn os W OK os chmod dfn stat S IRUSR stat S IWUSR with salt utils fopen dfn 'wb+' as fp fp w...
def dropfile cachedir user None dfn os path join cachedir ' dfn' mask os umask 191 try log info 'RotatingAESkey' if os path isfile dfn log info 'AESkeyrotationalreadyrequested' returnif os path isfile dfn and not os access dfn os W_OK os chmod dfn stat S_IRUSR stat S_IWUSR with salt utils fopen dfn 'wb+' as fp_ fp_ wri...
98
python-test-5600
python
What do the master update ?
the publish session key
def dropfile cachedir user None dfn os path join cachedir ' dfn' mask os umask 191 try log info ' Rotating AE Skey' if os path isfile dfn log info 'AE Skeyrotationalreadyrequested' returnif os path isfile dfn and not os access dfn os W OK os chmod dfn stat S IRUSR stat S IWUSR with salt utils fopen dfn 'wb+' as fp fp w...
def dropfile cachedir user None dfn os path join cachedir ' dfn' mask os umask 191 try log info 'RotatingAESkey' if os path isfile dfn log info 'AESkeyrotationalreadyrequested' returnif os path isfile dfn and not os access dfn os W_OK os chmod dfn stat S_IRUSR stat S_IWUSR with salt utils fopen dfn 'wb+' as fp_ fp_ wri...
98
python-test-5601
python
What does the code do ?
potential or field for spherical model
def sphere pot or field rr mri rr mri Q coils sphere bem rr n jobs coil type fun eeg spherepot coil if coil type 'eeg' else sphere field parallel p fun parallel func fun n jobs B np concatenate parallel p fun r coils sphere for r in np array split rr n jobs return B
def _sphere_pot_or_field rr mri_rr mri_Q coils sphere bem_rr n_jobs coil_type fun _eeg_spherepot_coil if coil_type 'eeg' else _sphere_field parallel p_fun _ parallel_func fun n_jobs B np concatenate parallel p_fun r coils sphere for r in np array_split rr n_jobs return B
57
python-test-5603
python
What lists under the current python installation ?
the names of all matplotlib backend modules importable
def get matplotlib backend module names import statement '\nimportos sys\n\n# Preservestdout \nsys stdout sys stdout\n\ntry \n# Redirectoutputprintedbythisimportationto"/dev/null" preventing\n#suchoutputfrombeingerroneouslyinterpretedasanerror \nwithopen os devnull \'w\' asdev null \nsys stdout dev null\n import \'%s\'...
def get_matplotlib_backend_module_names import_statement '\nimportos sys\n\n#Preservestdout \nsys_stdout sys stdout\n\ntry \n#Redirectoutputprintedbythisimportationto"/dev/null" preventing\n#suchoutputfrombeingerroneouslyinterpretedasanerror \nwithopen os devnull \'w\' asdev_null \nsys stdout dev_null\n__import__ \'%s\...
145
python-test-5604
python
Where do the names of all matplotlib backend modules importable list ?
under the current python installation
def get matplotlib backend module names import statement '\nimportos sys\n\n# Preservestdout \nsys stdout sys stdout\n\ntry \n# Redirectoutputprintedbythisimportationto"/dev/null" preventing\n#suchoutputfrombeingerroneouslyinterpretedasanerror \nwithopen os devnull \'w\' asdev null \nsys stdout dev null\n import \'%s\'...
def get_matplotlib_backend_module_names import_statement '\nimportos sys\n\n#Preservestdout \nsys_stdout sys stdout\n\ntry \n#Redirectoutputprintedbythisimportationto"/dev/null" preventing\n#suchoutputfrombeingerroneouslyinterpretedasanerror \nwithopen os devnull \'w\' asdev_null \nsys stdout dev_null\n__import__ \'%s\...
145