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-992
python
What parses a redactionrule from a dictionary like : " description " : " this is the first rule " ?
parse_one_rule_from_dict
def parse one rule from dict rule rule pop 'description' None trigger rule pop 'trigger' None case sensitive rule pop 'case Sensitive' True if case sensitive 'false' case sensitive Falseelif case sensitive 'true' case sensitive Truetry search rule pop 'search' except Key Error raise Value Error ' Redactionruleismissing...
def parse_one_rule_from_dict rule rule pop 'description' None trigger rule pop 'trigger' None case_sensitive rule pop 'caseSensitive' True if case_sensitive 'false' case_sensitive Falseelif case_sensitive 'true' case_sensitive Truetry search rule pop 'search' except KeyError raise ValueError 'Redactionruleismissing`sea...
81
python-test-993
python
What does the code subtract from the subtractfromtable ?
the subtracttable
def subtract X Intersections Table subtract From Table subtract Table subtract From Table Keys subtract From Table keys subtract From Table Keys sort for subtract From Table Key in subtract From Table Keys x Intersection Index List []add X Intersection Indexes From X Intersections -1 x Intersection Index List subtract ...
def subtractXIntersectionsTable subtractFromTable subtractTable subtractFromTableKeys subtractFromTable keys subtractFromTableKeys sort for subtractFromTableKey in subtractFromTableKeys xIntersectionIndexList []addXIntersectionIndexesFromXIntersections -1 xIntersectionIndexList subtractFromTable[subtractFromTableKey] i...
112
python-test-995
python
What is considered on the current network ?
roaming
def is Network Roaming try m Context autoclass 'android content Context' python Activity autoclass 'org renpy android Python Service' telephony Manager cast 'android telephony Telephony Manager' python Activity m Service get System Service m Context TELEPHONY SERVICE is Network Roaming telephony Manager is Network Roam...
def isNetworkRoaming try mContext autoclass 'android content Context' pythonActivity autoclass 'org renpy android PythonService' telephonyManager cast 'android telephony TelephonyManager' pythonActivity mService getSystemService mContext TELEPHONY_SERVICE isNetworkRoaming telephonyManager isNetworkRoaming return isNetw...
54
python-test-996
python
Where is roaming considered ?
on the current network
def is Network Roaming try m Context autoclass 'android content Context' python Activity autoclass 'org renpy android Python Service' telephony Manager cast 'android telephony Telephony Manager' python Activity m Service get System Service m Context TELEPHONY SERVICE is Network Roaming telephony Manager is Network Roam...
def isNetworkRoaming try mContext autoclass 'android content Context' pythonActivity autoclass 'org renpy android PythonService' telephonyManager cast 'android telephony TelephonyManager' pythonActivity mService getSystemService mContext TELEPHONY_SERVICE isNetworkRoaming telephonyManager isNetworkRoaming return isNetw...
54
python-test-997
python
What can we run successfully ?
a multi - line macro
@dec skip without 'sqlite 3 ' def test macro run ip get ipython ip history manager reset cmds ['a 10 ' 'a+ 1' py 3 compat doctest refactor print 'printa' '%macrotest 2 - 3 ']for cmd in cmds ip run cell cmd store history True nt assert equal ip user ns['test'] value py 3 compat doctest refactor print 'a+ 1\nprinta\n' wi...
@dec skip_without 'sqlite3' def test_macro_run ip get_ipython ip history_manager reset cmds ['a 10' 'a+ 1' py3compat doctest_refactor_print 'printa' '%macrotest2-3']for cmd in cmds ip run_cell cmd store_history True nt assert_equal ip user_ns['test'] value py3compat doctest_refactor_print 'a+ 1\nprinta\n' with tt Asser...
80
python-test-1010
python
What does the code establish ?
connection to ec2 client
def ec 2 client region zone access key id secret access key session token None validate region True connection boto 3 session Session aws access key id access key id aws secret access key secret access key aws session token session token connection session set config variable 'metadata service num attempts' BOTO NUM RE...
def ec2_client region zone access_key_id secret_access_key session_token None validate_region True connection boto3 session Session aws_access_key_id access_key_id aws_secret_access_key secret_access_key aws_session_token session_token connection _session set_config_variable 'metadata_service_num_attempts' BOTO_NUM_RET...
121
python-test-1017
python
For what purpose do the nearest neighbour sentences return ?
to query text
def nn model text vectors query k 5 qf encode model [query] qf / norm qf scores numpy dot qf vectors T flatten sorted args numpy argsort scores [ -1 ]sentences [text[a] for a in sorted args[ k]]print 'QUERY ' + query print 'NEAREST 'for i s in enumerate sentences print s sorted args[i]
def nn model text vectors query k 5 qf encode model [query] qf / norm qf scores numpy dot qf vectors T flatten sorted_args numpy argsort scores [ -1 ]sentences [text[a] for a in sorted_args[ k]]print 'QUERY ' + query print 'NEAREST 'for i s in enumerate sentences print s sorted_args[i]
54
python-test-1019
python
Where did an ip address give ?
in quad segments
def increment ipv 4 segments segments segments [int segment for segment in segments]segments[ 3 ] + 1if segments[ 3 ] 256 segments[ 3 ] 0segments[ 2 ] + 1if segments[ 2 ] 256 segments[ 2 ] 0segments[ 1 ] + 1if segments[ 1 ] 256 segments[ 1 ] 0segments[ 0 ] + 1return segments
def increment_ipv4_segments segments segments [int segment for segment in segments]segments[3] + 1if segments[3] 256 segments[3] 0segments[2] + 1if segments[2] 256 segments[2] 0segments[1] + 1if segments[1] 256 segments[1] 0segments[0] + 1return segments
54
python-test-1022
python
What are written the file ?
the predictions
def conlleval p g w filename script path out ''for sl sp sw in zip g p w out + 'BOSOO\n'for wl wp w in zip sl sp sw out + w + '' + wl + '' + wp + '\n' out + 'EOSOO\n\n'f open filename 'w' f writelines out f close return get perf filename script path
def conlleval p g w filename script_path out ''for sl sp sw in zip g p w out + 'BOSOO\n'for wl wp w in zip sl sp sw out + w + '' + wl + '' + wp + '\n' out + 'EOSOO\n\n'f open filename 'w' f writelines out f close return get_perf filename script_path
59
python-test-1025
python
When are snapshots userdata created ?
when snapper
def get jid snapshots jid config 'root' jid snapshots [x for x in list snapshots config if x['userdata'] get 'salt jid' jid ]pre snapshot [x for x in jid snapshots if x['type'] 'pre' ]post snapshot [x for x in jid snapshots if x['type'] 'post' ]if not pre snapshot or not post snapshot raise Command Execution Error " Ji...
def _get_jid_snapshots jid config 'root' jid_snapshots [x for x in list_snapshots config if x['userdata'] get 'salt_jid' jid ]pre_snapshot [x for x in jid_snapshots if x['type'] 'pre' ]post_snapshot [x for x in jid_snapshots if x['type'] 'post' ]if not pre_snapshot or not post_snapshot raise CommandExecutionError "Jid'...
71
python-test-1026
python
What renders the index page ?
basic handler
@webauth Security Check@csrf ensure csrf cookiedef Homepage request renderers js files set ['statistics js' 'usage js'] create time psutil Process os getpid create time context {'heading' config lib CONFIG[' Admin UI heading'] 'report url' config lib CONFIG[' Admin UI report url'] 'help url' config lib CONFIG[' Admin U...
@webauth SecurityCheck@csrf ensure_csrf_cookiedef Homepage request renderers_js_files set ['statistics js' 'usage js'] create_time psutil Process os getpid create_time context {'heading' config_lib CONFIG['AdminUI heading'] 'report_url' config_lib CONFIG['AdminUI report_url'] 'help_url' config_lib CONFIG['AdminUI help_...
149
python-test-1027
python
What do basic handler render ?
the index page
@webauth Security Check@csrf ensure csrf cookiedef Homepage request renderers js files set ['statistics js' 'usage js'] create time psutil Process os getpid create time context {'heading' config lib CONFIG[' Admin UI heading'] 'report url' config lib CONFIG[' Admin UI report url'] 'help url' config lib CONFIG[' Admin U...
@webauth SecurityCheck@csrf ensure_csrf_cookiedef Homepage request renderers_js_files set ['statistics js' 'usage js'] create_time psutil Process os getpid create_time context {'heading' config_lib CONFIG['AdminUI heading'] 'report_url' config_lib CONFIG['AdminUI report_url'] 'help_url' config_lib CONFIG['AdminUI help_...
149
python-test-1028
python
What does the code remove ?
roidb entries that have no usable rois
def filter roidb roidb def is valid entry overlaps entry['max overlaps']fg inds np where overlaps > cfg TRAIN FG THRESH [0 ]bg inds np where overlaps < cfg TRAIN BG THRESH HI & overlaps > cfg TRAIN BG THRESH LO [0 ]valid len fg inds > 0 or len bg inds > 0 return validnum len roidb filtered roidb [entry for entry in roi...
def filter_roidb roidb def is_valid entry overlaps entry['max_overlaps']fg_inds np where overlaps > cfg TRAIN FG_THRESH [0]bg_inds np where overlaps < cfg TRAIN BG_THRESH_HI & overlaps > cfg TRAIN BG_THRESH_LO [0]valid len fg_inds > 0 or len bg_inds > 0 return validnum len roidb filtered_roidb [entry for entry in roidb...
88
python-test-1029
python
What have no usable rois ?
roidb entries
def filter roidb roidb def is valid entry overlaps entry['max overlaps']fg inds np where overlaps > cfg TRAIN FG THRESH [0 ]bg inds np where overlaps < cfg TRAIN BG THRESH HI & overlaps > cfg TRAIN BG THRESH LO [0 ]valid len fg inds > 0 or len bg inds > 0 return validnum len roidb filtered roidb [entry for entry in roi...
def filter_roidb roidb def is_valid entry overlaps entry['max_overlaps']fg_inds np where overlaps > cfg TRAIN FG_THRESH [0]bg_inds np where overlaps < cfg TRAIN BG_THRESH_HI & overlaps > cfg TRAIN BG_THRESH_LO [0]valid len fg_inds > 0 or len bg_inds > 0 return validnum len roidb filtered_roidb [entry for entry in roidb...
88
python-test-1030
python
What do roidb entries have ?
no usable rois
def filter roidb roidb def is valid entry overlaps entry['max overlaps']fg inds np where overlaps > cfg TRAIN FG THRESH [0 ]bg inds np where overlaps < cfg TRAIN BG THRESH HI & overlaps > cfg TRAIN BG THRESH LO [0 ]valid len fg inds > 0 or len bg inds > 0 return validnum len roidb filtered roidb [entry for entry in roi...
def filter_roidb roidb def is_valid entry overlaps entry['max_overlaps']fg_inds np where overlaps > cfg TRAIN FG_THRESH [0]bg_inds np where overlaps < cfg TRAIN BG_THRESH_HI & overlaps > cfg TRAIN BG_THRESH_LO [0]valid len fg_inds > 0 or len bg_inds > 0 return validnum len roidb filtered_roidb [entry for entry in roidb...
88
python-test-1031
python
How do argumentparser instance for the action generate ?
with the provided metadata object
def generate argument parser for metadata metadata parameters metadata['parameters']parser argparse Argument Parser description metadata['description'] for parameter name parameter options in parameters items name parameter name replace ' ' '-' description parameter options['description'] type parameter options['type']...
def generate_argument_parser_for_metadata metadata parameters metadata['parameters']parser argparse ArgumentParser description metadata['description'] for parameter_name parameter_options in parameters items name parameter_name replace '_' '-' description parameter_options['description']_type parameter_options['type']r...
100
python-test-1037
python
What does they be ?
authenticating
def add data sharing consent field request form desc enterprise customer get enterprise customer for request request required data sharing consent required at login request if not data sharing consent requested request returnlabel ' Iagreetoallow{platform name}tosharedataaboutmyenrollment completionandperformanceinall{...
def add_data_sharing_consent_field request form_desc enterprise_customer get_enterprise_customer_for_request request required data_sharing_consent_required_at_login request if not data_sharing_consent_requested request returnlabel _ 'Iagreetoallow{platform_name}tosharedataaboutmyenrollment completionandperformanceinall...
91
python-test-1038
python
What does the code add if the user consents to share data with the enterprisecustomer attached to the sso provider with which they re authenticating ?
a checkbox field to be selected
def add data sharing consent field request form desc enterprise customer get enterprise customer for request request required data sharing consent required at login request if not data sharing consent requested request returnlabel ' Iagreetoallow{platform name}tosharedataaboutmyenrollment completionandperformanceinall{...
def add_data_sharing_consent_field request form_desc enterprise_customer get_enterprise_customer_for_request request required data_sharing_consent_required_at_login request if not data_sharing_consent_requested request returnlabel _ 'Iagreetoallow{platform_name}tosharedataaboutmyenrollment completionandperformanceinall...
91
python-test-1047
python
What does the code generate ?
a new filename for a file upload field
def generate filename and delete previous ffile name before delete None new filename ffile field generate filename ffile instance name try orig instance ffile instance class objects get id ffile instance id orig field file getattr orig instance ffile field name orig filename orig field file nameif orig filename and new...
def generate_filename_and_delete_previous ffile name before_delete None new_filename ffile field generate_filename ffile instance name try orig_instance ffile instance __class__ objects get id ffile instance id orig_field_file getattr orig_instance ffile field name orig_filename orig_field_file nameif orig_filename and...
76
python-test-1050
python
When do a function retry using rpc call ?
in case of messagingexception
def call with retry max attempts def wrapper f def func wrapper *args **kwargs action '% func s' % {'func' getattr f ' name ' f } for attempt in range 1 max attempts + 1 try return f *args **kwargs except oslo messaging Messaging Exception with excutils save and reraise exception reraise False as ctxt LOG warning LW ' ...
def _call_with_retry max_attempts def wrapper f def func_wrapper *args **kwargs action '% func s' % {'func' getattr f '__name__' f } for attempt in range 1 max_attempts + 1 try return f *args **kwargs except oslo_messaging MessagingException with excutils save_and_reraise_exception reraise False as ctxt LOG warning _LW...
87
python-test-1051
python
How do a function retry in case of messagingexception ?
using rpc call
def call with retry max attempts def wrapper f def func wrapper *args **kwargs action '% func s' % {'func' getattr f ' name ' f } for attempt in range 1 max attempts + 1 try return f *args **kwargs except oslo messaging Messaging Exception with excutils save and reraise exception reraise False as ctxt LOG warning LW ' ...
def _call_with_retry max_attempts def wrapper f def func_wrapper *args **kwargs action '% func s' % {'func' getattr f '__name__' f } for attempt in range 1 max_attempts + 1 try return f *args **kwargs except oslo_messaging MessagingException with excutils save_and_reraise_exception reraise False as ctxt LOG warning _LW...
87
python-test-1052
python
What has access to the given course arguments ?
the user with this ip_address
def check course access course key user None ip address None url None if not settings FEATURES get 'EMBARGO' return Truecourse is restricted Restricted Course is restricted course course key if not course is restricted return Trueif user is not None and has course author access user course key return Trueif ip address ...
def check_course_access course_key user None ip_address None url None if not settings FEATURES get 'EMBARGO' return Truecourse_is_restricted RestrictedCourse is_restricted_course course_key if not course_is_restricted return Trueif user is not None and has_course_author_access user course_key return Trueif ip_address i...
149
python-test-1053
python
What is the user trying ?
to access
def check course access course key user None ip address None url None if not settings FEATURES get 'EMBARGO' return Truecourse is restricted Restricted Course is restricted course course key if not course is restricted return Trueif user is not None and has course author access user course key return Trueif ip address ...
def check_course_access course_key user None ip_address None url None if not settings FEATURES get 'EMBARGO' return Truecourse_is_restricted RestrictedCourse is_restricted_course course_key if not course_is_restricted return Trueif user is not None and has_course_author_access user course_key return Trueif ip_address i...
149
python-test-1054
python
What does the user with this ip_address have ?
access to the given course arguments
def check course access course key user None ip address None url None if not settings FEATURES get 'EMBARGO' return Truecourse is restricted Restricted Course is restricted course course key if not course is restricted return Trueif user is not None and has course author access user course key return Trueif ip address ...
def check_course_access course_key user None ip_address None url None if not settings FEATURES get 'EMBARGO' return Truecourse_is_restricted RestrictedCourse is_restricted_course course_key if not course_is_restricted return Trueif user is not None and has_course_author_access user course_key return Trueif ip_address i...
149
python-test-1055
python
What does the code validate ?
the named ports parameters
def validate named port params params if not params['named ports'] return True '' if not isinstance params['named ports'] list return False 'named ports expectedlistofname portdictionaries ' req fields [{'name' 'name' 'required' True 'type' str} {'name' 'port' 'required' True 'type' int}]for np in params['named ports']...
def _validate_named_port_params params if not params['named_ports'] return True '' if not isinstance params['named_ports'] list return False 'named_ports expectedlistofname portdictionaries ' req_fields [{'name' 'name' 'required' True 'type' str} {'name' 'port' 'required' True 'type' int}]for np in params['named_ports'...
66
python-test-1056
python
What do python packages need ?
explicit uninstallation
@task@timeddef uninstall python packages hasher hashlib sha 1 hasher update repr PACKAGES TO UNINSTALL expected version hasher hexdigest state file path os path join PREREQS STATE DIR ' Python uninstall sha 1 ' create prereqs cache dir if os path isfile state file path with open state file path as state file version st...
@task@timeddef uninstall_python_packages hasher hashlib sha1 hasher update repr PACKAGES_TO_UNINSTALL expected_version hasher hexdigest state_file_path os path join PREREQS_STATE_DIR 'Python_uninstall sha1' create_prereqs_cache_dir if os path isfile state_file_path with open state_file_path as state_file version state_...
116
python-test-1057
python
What need explicit uninstallation ?
python packages
@task@timeddef uninstall python packages hasher hashlib sha 1 hasher update repr PACKAGES TO UNINSTALL expected version hasher hexdigest state file path os path join PREREQS STATE DIR ' Python uninstall sha 1 ' create prereqs cache dir if os path isfile state file path with open state file path as state file version st...
@task@timeddef uninstall_python_packages hasher hashlib sha1 hasher update repr PACKAGES_TO_UNINSTALL expected_version hasher hexdigest state_file_path os path join PREREQS_STATE_DIR 'Python_uninstall sha1' create_prereqs_cache_dir if os path isfile state_file_path with open state_file_path as state_file version state_...
116
python-test-1060
python
What does the code create ?
a sizer block bound to the block with the specified name
def s size block name offset 0 length 4 endian '<' format 'binary' inclusive False signed False math None fuzzable False name None if block name in blocks CURRENT block stack raise sex Sully Runtime Error 'CANNOTADDASIZEFORABLOCKCURRENTLYINTHESTACK' size blocks size block name blocks CURRENT offset length endian format...
def s_size block_name offset 0 length 4 endian '<' format 'binary' inclusive False signed False math None fuzzable False name None if block_name in blocks CURRENT block_stack raise sex SullyRuntimeError 'CANNOTADDASIZEFORABLOCKCURRENTLYINTHESTACK' size blocks size block_name blocks CURRENT offset length endian format i...
57
python-test-1062
python
What matches the given filter criteria ?
at least one host group
def hostgroup exists name None groupid None node None nodeids None **connection args conn args login **connection args zabbix version apiinfo version **connection args try if conn args if Loose Version zabbix version > Loose Version '2 5' if not groupid groupid Noneif not name name Noneret hostgroup get name groupid **...
def hostgroup_exists name None groupid None node None nodeids None **connection_args conn_args _login **connection_args zabbix_version apiinfo_version **connection_args try if conn_args if LooseVersion zabbix_version > LooseVersion '2 5' if not groupid groupid Noneif not name name Noneret hostgroup_get name groupid **c...
119
python-test-1063
python
What does factory return depending on the browser filter type and hotswap target ?
an appropriate browser model
def make browser model browser filter type None factories { Filter Type instrument hotswap make instruments browser model Filter Type drum pad hotswap make drum pad browser model Filter Type audio effect hotswap make audio effect browser model Filter Type midi effect hotswap make midi effect browser model}if filter typ...
def make_browser_model browser filter_type None factories {FilterType instrument_hotswap make_instruments_browser_model FilterType drum_pad_hotswap make_drum_pad_browser_model FilterType audio_effect_hotswap make_audio_effect_browser_model FilterType midi_effect_hotswap make_midi_effect_browser_model}if filter_type Non...
68
python-test-1064
python
For what purpose does the local cache check ?
for the file
def get file from s3 creds metadata saltenv bucket path cached file path if os path isfile cached file path file meta find file meta metadata bucket saltenv path file md 5 '' join list filter str isalnum file meta['E Tag'] if file meta else None cached md 5 salt utils get hash cached file path 'md 5 ' log debug ' Cache...
def _get_file_from_s3 creds metadata saltenv bucket path cached_file_path if os path isfile cached_file_path file_meta _find_file_meta metadata bucket saltenv path file_md5 '' join list filter str isalnum file_meta['ETag'] if file_meta else None cached_md5 salt utils get_hash cached_file_path 'md5' log debug 'Cachedfil...
163
python-test-1069
python
What does the code get ?
a list of all the ip addresses for adapters on the local system
def get ip addresses include loopback True system platform system if system lower in ['linux' 'darwin' 'macosx'] ips [iface get 'inet' for iface in ifcfg interfaces values ]elif system lower 'windows' ipconfig os popen 'ipconfig/all' read ips [match[ 1 ] for match in re findall 'IP v4 ? Address[\\ \\ ]+ [\\d\\ ]+ ' ipc...
def get_ip_addresses include_loopback True system platform system if system lower in ['linux' 'darwin' 'macosx'] ips [iface get 'inet' for iface in ifcfg interfaces values ]elif system lower 'windows' ipconfig os popen 'ipconfig/all' read ips [match[1] for match in re findall 'IP v4 ?Address[\\ \\ ]+ [\\d\\ ]+ ' ipconf...
89
python-test-1070
python
Where does the code run the validator ?
on the given file or fileupload object
def validate file listed None subtask None from utils import Validation Annotatorannotator Validation Annotator file listed listed task id cache get annotator cache key if task id return Async Result task id else chain annotator taskif subtask is not None chain subtaskresult chain delay cache set annotator cache key re...
def validate file_ listed None subtask None from utils import ValidationAnnotatorannotator ValidationAnnotator file_ listed listed task_id cache get annotator cache_key if task_id return AsyncResult task_id else chain annotator taskif subtask is not None chain subtaskresult chain delay cache set annotator cache_key res...
57
python-test-1072
python
What does the code setup ?
the calendar platform for event devices
def setup platform hass config add devices disc info None if disc info is None returnif not any [data[CONF TRACK] for data in disc info[CONF ENTITIES]] returncalendar service Google Calendar Service hass config path TOKEN FILE add devices [ Google Calendar Event Device hass calendar service disc info[CONF CAL ID] data ...
def setup_platform hass config add_devices disc_info None if disc_info is None returnif not any [data[CONF_TRACK] for data in disc_info[CONF_ENTITIES]] returncalendar_service GoogleCalendarService hass config path TOKEN_FILE add_devices [GoogleCalendarEventDevice hass calendar_service disc_info[CONF_CAL_ID] data for da...
60
python-test-1073
python
What do a dictionary represent ?
the parse tree of a sentence
def to dict sentence token str list children [[] for token in sentence token]root -1 for i in range 0 len sentence token token sentence token[i]token str append '%s%s%s@%d' % token word token tag token label i + 1 if token head -1 root ielse children[token head] append i def get dict i d collections Ordered Dict for c ...
def to_dict sentence token_str list children [[] for token in sentence token]root -1 for i in range 0 len sentence token token sentence token[i]token_str append '%s%s%s@%d' % token word token tag token label i + 1 if token head -1 root ielse children[token head] append i def _get_dict i d collections OrderedDict for c ...
78
python-test-1074
python
What does the code write ?
a new nexus file containing the given trees
def write obj handle **kwargs trees list obj writer Newick IO Writer trees nexus trees [ TREE TEMPLATE % {'index' idx + 1 'tree' nwk} for idx nwk in enumerate writer to strings plain False plain newick True **kwargs ]tax labels [str x name for x in chain * t get terminals for t in trees ]text NEX TEMPLATE % {'count' le...
def write obj handle **kwargs trees list obj writer NewickIO Writer trees nexus_trees [ TREE_TEMPLATE % {'index' idx + 1 'tree' nwk} for idx nwk in enumerate writer to_strings plain False plain_newick True **kwargs ]tax_labels [str x name for x in chain * t get_terminals for t in trees ]text NEX_TEMPLATE % {'count' len...
82
python-test-1075
python
What do a new nexus file contain ?
the given trees
def write obj handle **kwargs trees list obj writer Newick IO Writer trees nexus trees [ TREE TEMPLATE % {'index' idx + 1 'tree' nwk} for idx nwk in enumerate writer to strings plain False plain newick True **kwargs ]tax labels [str x name for x in chain * t get terminals for t in trees ]text NEX TEMPLATE % {'count' le...
def write obj handle **kwargs trees list obj writer NewickIO Writer trees nexus_trees [ TREE_TEMPLATE % {'index' idx + 1 'tree' nwk} for idx nwk in enumerate writer to_strings plain False plain_newick True **kwargs ]tax_labels [str x name for x in chain * t get_terminals for t in trees ]text NEX_TEMPLATE % {'count' len...
82
python-test-1076
python
What is containing the given trees ?
a new nexus file
def write obj handle **kwargs trees list obj writer Newick IO Writer trees nexus trees [ TREE TEMPLATE % {'index' idx + 1 'tree' nwk} for idx nwk in enumerate writer to strings plain False plain newick True **kwargs ]tax labels [str x name for x in chain * t get terminals for t in trees ]text NEX TEMPLATE % {'count' le...
def write obj handle **kwargs trees list obj writer NewickIO Writer trees nexus_trees [ TREE_TEMPLATE % {'index' idx + 1 'tree' nwk} for idx nwk in enumerate writer to_strings plain False plain_newick True **kwargs ]tax_labels [str x name for x in chain * t get_terminals for t in trees ]text NEX_TEMPLATE % {'count' len...
82
python-test-1078
python
What does the code create ?
the paths required for binary configs
def Create Binary Config Paths token None required urns set try for platform in SUPPORTED PLATFORMS required urns add 'aff 4 /config/executables/%s/agentupdates' % platform required urns add 'aff 4 /config/executables/%s/installers' % platform existing urns [x['urn'] for x in aff 4 FACTORY Stat list required urns token...
def CreateBinaryConfigPaths token None required_urns set try for platform in SUPPORTED_PLATFORMS required_urns add 'aff4 /config/executables/%s/agentupdates' % platform required_urns add 'aff4 /config/executables/%s/installers' % platform existing_urns [x['urn'] for x in aff4 FACTORY Stat list required_urns token token...
85
python-test-1081
python
What is removing the event ?
us
def test strongly typed events def f global calledcalled Trueglobal calledcalled Falseev Iron Python Test Events ev Instance Test + Iron Python Test Event Test Delegate f ev Call Instance Are Equal called True called Falseev Instance Test - Iron Python Test Event Test Delegate f ev Call Instance Are Equal called False
def test_strongly_typed_events def f global calledcalled Trueglobal calledcalled Falseev IronPythonTest Events ev InstanceTest + IronPythonTest EventTestDelegate f ev CallInstance AreEqual called True called Falseev InstanceTest - IronPythonTest EventTestDelegate f ev CallInstance AreEqual called False
53
python-test-1082
python
Does recreating a strongly typed delegate prevent us from removing the event ?
No
def test strongly typed events def f global calledcalled Trueglobal calledcalled Falseev Iron Python Test Events ev Instance Test + Iron Python Test Event Test Delegate f ev Call Instance Are Equal called True called Falseev Instance Test - Iron Python Test Event Test Delegate f ev Call Instance Are Equal called False
def test_strongly_typed_events def f global calledcalled Trueglobal calledcalled Falseev IronPythonTest Events ev InstanceTest + IronPythonTest EventTestDelegate f ev CallInstance AreEqual called True called Falseev InstanceTest - IronPythonTest EventTestDelegate f ev CallInstance AreEqual called False
53
python-test-1083
python
What do us remove ?
the event
def test strongly typed events def f global calledcalled Trueglobal calledcalled Falseev Iron Python Test Events ev Instance Test + Iron Python Test Event Test Delegate f ev Call Instance Are Equal called True called Falseev Instance Test - Iron Python Test Event Test Delegate f ev Call Instance Are Equal called False
def test_strongly_typed_events def f global calledcalled Trueglobal calledcalled Falseev IronPythonTest Events ev InstanceTest + IronPythonTest EventTestDelegate f ev CallInstance AreEqual called True called Falseev InstanceTest - IronPythonTest EventTestDelegate f ev CallInstance AreEqual called False
53
python-test-1084
python
What does nt prevent us from removing the event ?
recreating a strongly typed delegate
def test strongly typed events def f global calledcalled Trueglobal calledcalled Falseev Iron Python Test Events ev Instance Test + Iron Python Test Event Test Delegate f ev Call Instance Are Equal called True called Falseev Instance Test - Iron Python Test Event Test Delegate f ev Call Instance Are Equal called False
def test_strongly_typed_events def f global calledcalled Trueglobal calledcalled Falseev IronPythonTest Events ev InstanceTest + IronPythonTest EventTestDelegate f ev CallInstance AreEqual called True called Falseev InstanceTest - IronPythonTest EventTestDelegate f ev CallInstance AreEqual called False
53
python-test-1085
python
How did delegate type ?
strongly
def test strongly typed events def f global calledcalled Trueglobal calledcalled Falseev Iron Python Test Events ev Instance Test + Iron Python Test Event Test Delegate f ev Call Instance Are Equal called True called Falseev Instance Test - Iron Python Test Event Test Delegate f ev Call Instance Are Equal called False
def test_strongly_typed_events def f global calledcalled Trueglobal calledcalled Falseev IronPythonTest Events ev InstanceTest + IronPythonTest EventTestDelegate f ev CallInstance AreEqual called True called Falseev InstanceTest - IronPythonTest EventTestDelegate f ev CallInstance AreEqual called False
53
python-test-1086
python
What does recreating a strongly typed delegate nt prevent from removing the event ?
us
def test strongly typed events def f global calledcalled Trueglobal calledcalled Falseev Iron Python Test Events ev Instance Test + Iron Python Test Event Test Delegate f ev Call Instance Are Equal called True called Falseev Instance Test - Iron Python Test Event Test Delegate f ev Call Instance Are Equal called False
def test_strongly_typed_events def f global calledcalled Trueglobal calledcalled Falseev IronPythonTest Events ev InstanceTest + IronPythonTest EventTestDelegate f ev CallInstance AreEqual called True called Falseev InstanceTest - IronPythonTest EventTestDelegate f ev CallInstance AreEqual called False
53
python-test-1089
python
What do the cache directory follow ?
a directory convention
def reap fileserver cache dir cache base find func for saltenv in os listdir cache base env base os path join cache base saltenv for root dirs files in os walk env base if len dirs 0 and len files 0 if time time - os path getctime root > 60 os rmdir root continuefor file in files file path os path join root file file r...
def reap_fileserver_cache_dir cache_base find_func for saltenv in os listdir cache_base env_base os path join cache_base saltenv for root dirs files in os walk env_base if len dirs 0 and len files 0 if time time - os path getctime root > 60 os rmdir root continuefor file_ in files file_path os path join root file_ file...
111
python-test-1090
python
What does the code remove assuming the cache directory follows a directory convention : cache_base - > saltenv - > relpath ?
unused cache items
def reap fileserver cache dir cache base find func for saltenv in os listdir cache base env base os path join cache base saltenv for root dirs files in os walk env base if len dirs 0 and len files 0 if time time - os path getctime root > 60 os rmdir root continuefor file in files file path os path join root file file r...
def reap_fileserver_cache_dir cache_base find_func for saltenv in os listdir cache_base env_base os path join cache_base saltenv for root dirs files in os walk env_base if len dirs 0 and len files 0 if time time - os path getctime root > 60 os rmdir root continuefor file_ in files file_path os path join root file_ file...
111
python-test-1091
python
What follows a directory convention ?
the cache directory
def reap fileserver cache dir cache base find func for saltenv in os listdir cache base env base os path join cache base saltenv for root dirs files in os walk env base if len dirs 0 and len files 0 if time time - os path getctime root > 60 os rmdir root continuefor file in files file path os path join root file file r...
def reap_fileserver_cache_dir cache_base find_func for saltenv in os listdir cache_base env_base os path join cache_base saltenv for root dirs files in os walk env_base if len dirs 0 and len files 0 if time time - os path getctime root > 60 os rmdir root continuefor file_ in files file_path os path join root file_ file...
111
python-test-1094
python
What do a user claim on a project page ?
from the x - editable form
@must be contributor or publicdef claim user post node **kwargs request data request jsonunclaimed user User load request data['pk'] unclaimed data unclaimed user get unclaimed record node primary key if 'value' in request data email request data['value'] lower strip claimer get user email email if claimer and claimer ...
@must_be_contributor_or_publicdef claim_user_post node **kwargs request_data request jsonunclaimed_user User load request_data['pk'] unclaimed_data unclaimed_user get_unclaimed_record node _primary_key if 'value' in request_data email request_data['value'] lower strip claimer get_user email email if claimer and claimer...
108
python-test-1095
python
What does the code set ?
the number of instances on the server and version
def set num instances instances server None version None if not isinstance instances long int raise Type Error "'instances'argmustbeoftypelongorint " req servers service pb Set Num Instances Request req set instances instances if server req set server server if version req set version version resp servers service pb Se...
def set_num_instances instances server None version None if not isinstance instances long int raise TypeError "'instances'argmustbeoftypelongorint " req servers_service_pb SetNumInstancesRequest req set_instances instances if server req set_server server if version req set_version version resp servers_service_pb SetNum...
107
python-test-1100
python
What do an array contain ?
objects of type t
def create array of type t if t in array types return array types[t] array type name ' Array Of%s' % t array type type array type name Data Object {} def init self super array type self init array type name setattr self t [] setattr array type ' init ' init array types[t] array typereturn array type
def _create_array_of_type t if t in _array_types return _array_types[t] array_type_name 'ArrayOf%s' % t array_type type array_type_name DataObject {} def __init__ self super array_type self __init__ array_type_name setattr self t [] setattr array_type '__init__' __init__ _array_types[t] array_typereturn array_type
59
python-test-1102
python
What processs a file for uploading ?
a unix pipeline
def get upload pipeline in fd out fd rate limit None gpg key None lzop True commands []if rate limit is not None commands append Pipe Viewer Rate Limit Filter rate limit if lzop commands append LZO Compression Filter if gpg key is not None commands append GPG Encryption Filter gpg key return Pipeline commands in fd out...
def get_upload_pipeline in_fd out_fd rate_limit None gpg_key None lzop True commands []if rate_limit is not None commands append PipeViewerRateLimitFilter rate_limit if lzop commands append LZOCompressionFilter if gpg_key is not None commands append GPGEncryptionFilter gpg_key return Pipeline commands in_fd out_fd
59
python-test-1103
python
What do a unix pipeline process ?
a file for uploading
def get upload pipeline in fd out fd rate limit None gpg key None lzop True commands []if rate limit is not None commands append Pipe Viewer Rate Limit Filter rate limit if lzop commands append LZO Compression Filter if gpg key is not None commands append GPG Encryption Filter gpg key return Pipeline commands in fd out...
def get_upload_pipeline in_fd out_fd rate_limit None gpg_key None lzop True commands []if rate_limit is not None commands append PipeViewerRateLimitFilter rate_limit if lzop commands append LZOCompressionFilter if gpg_key is not None commands append GPGEncryptionFilter gpg_key return Pipeline commands in_fd out_fd
59
python-test-1104
python
What does the code create ?
a unix pipeline to process a file for uploading
def get upload pipeline in fd out fd rate limit None gpg key None lzop True commands []if rate limit is not None commands append Pipe Viewer Rate Limit Filter rate limit if lzop commands append LZO Compression Filter if gpg key is not None commands append GPG Encryption Filter gpg key return Pipeline commands in fd out...
def get_upload_pipeline in_fd out_fd rate_limit None gpg_key None lzop True commands []if rate_limit is not None commands append PipeViewerRateLimitFilter rate_limit if lzop commands append LZOCompressionFilter if gpg_key is not None commands append GPGEncryptionFilter gpg_key return Pipeline commands in_fd out_fd
59
python-test-1112
python
What does the code ensure ?
that rtl text is rendered rtl & also that arabic text is rewritten to use the joined format
def bi Di Text text text s3 unicode text if bi Di Imported and current deployment settings get pdf bidi is Arabic Falseis Bidi Falsefor c in text cat unicodedata bidirectional c if cat in 'AL' 'AN' is Arabic Trueis Bidi Truebreakelif cat in 'R' 'RLE' 'RLO' is Bidi Trueif is Arabic text arabic reshaper reshape text if i...
def biDiText text text s3_unicode text if biDiImported and current deployment_settings get_pdf_bidi isArabic FalseisBidi Falsefor c in text cat unicodedata bidirectional c if cat in 'AL' 'AN' isArabic TrueisBidi Truebreakelif cat in 'R' 'RLE' 'RLO' isBidi Trueif isArabic text arabic_reshaper reshape text if isBidi text...
66
python-test-1113
python
For what purpose is that arabic text rewritten ?
to use the joined format
def bi Di Text text text s3 unicode text if bi Di Imported and current deployment settings get pdf bidi is Arabic Falseis Bidi Falsefor c in text cat unicodedata bidirectional c if cat in 'AL' 'AN' is Arabic Trueis Bidi Truebreakelif cat in 'R' 'RLE' 'RLO' is Bidi Trueif is Arabic text arabic reshaper reshape text if i...
def biDiText text text s3_unicode text if biDiImported and current deployment_settings get_pdf_bidi isArabic FalseisBidi Falsefor c in text cat unicodedata bidirectional c if cat in 'AL' 'AN' isArabic TrueisBidi Truebreakelif cat in 'R' 'RLE' 'RLO' isBidi Trueif isArabic text arabic_reshaper reshape text if isBidi text...
66
python-test-1114
python
What do views require user ?
to be a member of a group
def membership required function None def decorator request *args **kwargs group get object or 404 Group slug kwargs['slug'] if request user is anonymous return Http Response Redirect reverse 'django contrib auth views login' if Group Member objects is member group request user return function request *args **kwargs el...
def membership_required function None def decorator request *args **kwargs group get_object_or_404 Group slug kwargs['slug'] if request user is_anonymous return HttpResponseRedirect reverse 'django contrib auth views login' if GroupMember objects is_member group request user return function request *args **kwargs else ...
60
python-test-1115
python
How do extra_kwargs return ?
by calling resource manager kwargs hooks
def get resource manager extra kwargs f args allow conflicts False hooks getattr f 'resource manager kwargs hooks' [] extra kwargs {}for hook in hooks hook kwargs hook args hook name hook name conflicting keys set hook kwargs keys & set extra kwargs keys if conflicting keys and not allow conflicts msg " Hook'% hook nam...
def get_resource_manager_extra_kwargs f args allow_conflicts False hooks getattr f 'resource_manager_kwargs_hooks' [] extra_kwargs {}for hook in hooks hook_kwargs hook args hook_name hook __name__conflicting_keys set hook_kwargs keys & set extra_kwargs keys if conflicting_keys and not allow_conflicts msg _ "Hook'% hook...
83
python-test-1118
python
What does the code convert into a message object ?
a dns wire format message
def from wire wire keyring None request mac '' xfr False origin None tsig ctx None multi False first True question only False one rr per rrset False ignore trailing False m Message id 0 m keyring keyringm request mac request macm xfr xfrm origin originm tsig ctx tsig ctxm multi multim first firstreader Wire Reader wire...
def from_wire wire keyring None request_mac '' xfr False origin None tsig_ctx None multi False first True question_only False one_rr_per_rrset False ignore_trailing False m Message id 0 m keyring keyringm request_mac request_macm xfr xfrm origin originm tsig_ctx tsig_ctxm multi multim first firstreader _WireReader wire...
70
python-test-1119
python
What do a generator yield ?
the content of all passed template_names
def load external templates spec base spider name spider dir join spec base spider name if not isdir spider dir raise Stop Iterationfor name in os listdir spider dir if not name endswith ' json' continuepath join spider dir name with open path as f sample json load f sample dir path[ - len ' json' ]if isdir sample dir ...
def load_external_templates spec_base spider_name spider_dir join spec_base spider_name if not isdir spider_dir raise StopIterationfor name in os listdir spider_dir if not name endswith ' json' continuepath join spider_dir name with open path as f sample json load f sample_dir path[ - len ' json' ]if isdir sample_dir f...
104
python-test-1123
python
What do we read correctly ?
right indented tables
def test read right indented table table '\n#comment withblanklineabove \n \n Col 1 Col 2 Col 3 \n \n 33 4foo\n 14 5bar\n \n'reader ascii get reader Reader ascii RST dat reader read table assert equal dat colnames [' Col 1 ' ' Col 2 ' ' Col 3 '] assert equal dat[ 0 ][ 2 ] 'foo' assert equal dat[ 1 ][ 0 ] 1
def test_read_right_indented_table table '\n#comment withblanklineabove \n \nCol1Col2Col3\n \n33 4foo\n14 5bar\n \n'reader ascii get_reader Reader ascii RST dat reader read table assert_equal dat colnames ['Col1' 'Col2' 'Col3'] assert_equal dat[0][2] 'foo' assert_equal dat[1][0] 1
66
python-test-1124
python
What does the code convert ?
a polynomial f in mathbb z[x_1
def to ANP poly f ring domain ring domainf ring zeroif isinstance f ring domain Polynomial Ring for monom coeff in f iterterms for mon coef in coeff iterterms m monom[ 0 ] + mon c domain [domain domain coef ] + [0 ] * monom[ 1 ] if m not in f f [m] celse f [m] + celse for monom coeff in f iterterms m monom[ 0 ] c domai...
def _to_ANP_poly f ring domain ring domainf_ ring zeroif isinstance f ring domain PolynomialRing for monom coeff in f iterterms for mon coef in coeff iterterms m monom[0] + mon c domain [domain domain coef ] + [0] * monom[1] if m not in f_ f_[m] celse f_[m] + celse for monom coeff in f iterterms m monom[0] c domain [do...
96
python-test-1130
python
What does the code compute ?
the average hamming loss
def hamming loss y true y pred labels None sample weight None classes None if classes is not None warnings warn "'classes'wasrenamedto'labels'inversion 0 18 andwillberemovedin 0 20 " Deprecation Warning labels classes y type y true y pred check targets y true y pred if labels is None labels unique labels y true y pred ...
def hamming_loss y_true y_pred labels None sample_weight None classes None if classes is not None warnings warn "'classes'wasrenamedto'labels'inversion0 18andwillberemovedin0 20 " DeprecationWarning labels classes y_type y_true y_pred _check_targets y_true y_pred if labels is None labels unique_labels y_true y_pred els...
135
python-test-1132
python
What does the code produce ?
an output similar to nmap script ssl - cert from masscan x509 " service " tag
def masscan x509 output certificate output decode 'base 64 ' newout []for hashtype hashname in [ 'md 5 ' 'MD 5 ' 'sha 1 ' 'SHA- 1 ' ] hashvalue hashlib new hashtype cert hexdigest newout append '%- 7 s%s\n' % hashname '' join hashvalue[i i + 4 ] for i in xrange 0 len hashvalue 4 b64 cert certificate encode 'base 64 ' n...
def masscan_x509 output certificate output decode 'base64' newout []for hashtype hashname in [ 'md5' 'MD5 ' 'sha1' 'SHA-1 ' ] hashvalue hashlib new hashtype cert hexdigest newout append '%-7s%s\n' % hashname '' join hashvalue[i i + 4 ] for i in xrange 0 len hashvalue 4 b64cert certificate encode 'base64' newout append ...
93
python-test-1133
python
What does this create ?
a coursegrader
def grader from conf conf if isinstance conf Course Grader return confsubgraders []for subgraderconf in conf subgraderconf subgraderconf copy weight subgraderconf pop 'weight' 0 try if 'min count' in subgraderconf subgrader class Assignment Format Graderelse raise Value Error ' Configurationhasnoappropriategraderclass ...
def grader_from_conf conf if isinstance conf CourseGrader return confsubgraders []for subgraderconf in conf subgraderconf subgraderconf copy weight subgraderconf pop 'weight' 0 try if 'min_count' in subgraderconf subgrader_class AssignmentFormatGraderelse raise ValueError 'Configurationhasnoappropriategraderclass ' bad...
113
python-test-1136
python
What does callback show ?
a single channel in a new figure
def plot topo onpick event show func orig ax event inaxesif event inaxes is None or not hasattr orig ax ' mne ch idx' and not hasattr orig ax ' mne axs' returnimport matplotlib pyplot as plttry if hasattr orig ax ' mne axs' x y event xdata event ydata for ax in orig ax mne axs if x > ax pos[ 0 ] and y > ax pos[ 1 ] and...
def _plot_topo_onpick event show_func orig_ax event inaxesif event inaxes is None or not hasattr orig_ax '_mne_ch_idx' and not hasattr orig_ax '_mne_axs' returnimport matplotlib pyplot as plttry if hasattr orig_ax '_mne_axs' x y event xdata event ydata for ax in orig_ax _mne_axs if x > ax pos[0] and y > ax pos[1] and x...
142
python-test-1140
python
In which direction do all objects start with gl ?
from the source
def copy gl functions source dest constants False if isinstance source Base GL Proxy s {}for key in dir source s[key] getattr source key source selif not isinstance source dict source source dict if not isinstance dest dict dest dest dict funcnames [name for name in source keys if name startswith 'gl' ]for name in func...
def _copy_gl_functions source dest constants False if isinstance source BaseGLProxy s {}for key in dir source s[key] getattr source key source selif not isinstance source dict source source __dict__if not isinstance dest dict dest dest __dict__funcnames [name for name in source keys if name startswith 'gl' ]for name in...
77
python-test-1141
python
What does the code inject ?
all objects that start with gl from the source
def copy gl functions source dest constants False if isinstance source Base GL Proxy s {}for key in dir source s[key] getattr source key source selif not isinstance source dict source source dict if not isinstance dest dict dest dest dict funcnames [name for name in source keys if name startswith 'gl' ]for name in func...
def _copy_gl_functions source dest constants False if isinstance source BaseGLProxy s {}for key in dir source s[key] getattr source key source selif not isinstance source dict source source __dict__if not isinstance dest dict dest dest __dict__funcnames [name for name in source keys if name startswith 'gl' ]for name in...
77
python-test-1142
python
What does the request contain ?
all required parameters
def require params oauth request parameters None if parameters is None parameters []params ['oauth consumer key' 'oauth nonce' 'oauth signature' 'oauth signature method' 'oauth timestamp']params extend parameters missing list param for param in params if not oauth request or param not in oauth request if missing respon...
def require_params oauth_request parameters None if parameters is None parameters []params ['oauth_consumer_key' 'oauth_nonce' 'oauth_signature' 'oauth_signature_method' 'oauth_timestamp']params extend parameters missing list param for param in params if not oauth_request or param not in oauth_request if missing respon...
66
python-test-1146
python
What does the code get from input lines which should be valid yaml in the ecsv meta format ?
a header dict
def get header from yaml lines try import yamlexcept Import Error raise Import Error '`importyaml`failed Py YAM Lpackageisrequiredfor ECS Vformat' from io misc yaml import Astropy Loaderclass Table Loader Astropy Loader '\n Custom Loaderthatconstructs Ordered Dictfroman omapobject \n Thisdoesnothingbutprovideanamespace...
def get_header_from_yaml lines try import yamlexcept ImportError raise ImportError '`importyaml`failed PyYAMLpackageisrequiredforECSVformat' from io misc yaml import AstropyLoaderclass TableLoader AstropyLoader '\nCustomLoaderthatconstructsOrderedDictfroman omapobject \nThisdoesnothingbutprovideanamespaceforaddingthe\n...
79
python-test-1147
python
What did the code split into parts where each part is no longer than strlen and no word is cut into two pieces ?
a long string
def words group input strlen words []nblanks input count '' nmax max nblanks len input // strlen + 1 arr np fromstring input + '' dtype binary type 1 blank loc np nonzero arr '' [0 ]offset 0xoffset 0for idx in range nmax try loc np nonzero blank loc > strlen + offset [0 ][ 0 ]offset blank loc[ loc - 1 ] + 1 if loc 0 of...
def _words_group input strlen words []nblanks input count '' nmax max nblanks len input // strlen + 1 arr np fromstring input + '' dtype binary_type 1 blank_loc np nonzero arr '' [0]offset 0xoffset 0for idx in range nmax try loc np nonzero blank_loc > strlen + offset [0][0]offset blank_loc[ loc - 1 ] + 1 if loc 0 offse...
94
python-test-1148
python
What is no longer than strlen parts ?
each part
def words group input strlen words []nblanks input count '' nmax max nblanks len input // strlen + 1 arr np fromstring input + '' dtype binary type 1 blank loc np nonzero arr '' [0 ]offset 0xoffset 0for idx in range nmax try loc np nonzero blank loc > strlen + offset [0 ][ 0 ]offset blank loc[ loc - 1 ] + 1 if loc 0 of...
def _words_group input strlen words []nblanks input count '' nmax max nblanks len input // strlen + 1 arr np fromstring input + '' dtype binary_type 1 blank_loc np nonzero arr '' [0]offset 0xoffset 0for idx in range nmax try loc np nonzero blank_loc > strlen + offset [0][0]offset blank_loc[ loc - 1 ] + 1 if loc 0 offse...
94
python-test-1158
python
What does exist in the bookmarks ?
the given line
def check marks quteproc quickmarks expected contains if quickmarks mark file os path join quteproc basedir 'config' 'quickmarks' else mark file os path join quteproc basedir 'config' 'bookmarks' 'urls' quteproc clear data quteproc send cmd ' save' quteproc wait for message ' Savedto{}' format mark file with open mark ...
def _check_marks quteproc quickmarks expected contains if quickmarks mark_file os path join quteproc basedir 'config' 'quickmarks' else mark_file os path join quteproc basedir 'config' 'bookmarks' 'urls' quteproc clear_data quteproc send_cmd ' save' quteproc wait_for message 'Savedto{}' format mark_file with open mark_...
81
python-test-1159
python
Where does the given line exist ?
in the bookmarks
def check marks quteproc quickmarks expected contains if quickmarks mark file os path join quteproc basedir 'config' 'quickmarks' else mark file os path join quteproc basedir 'config' 'bookmarks' 'urls' quteproc clear data quteproc send cmd ' save' quteproc wait for message ' Savedto{}' format mark file with open mark ...
def _check_marks quteproc quickmarks expected contains if quickmarks mark_file os path join quteproc basedir 'config' 'quickmarks' else mark_file os path join quteproc basedir 'config' 'bookmarks' 'urls' quteproc clear_data quteproc send_cmd ' save' quteproc wait_for message 'Savedto{}' format mark_file with open mark_...
81
python-test-1167
python
For what purpose is the template returned places ?
so that it becomes compatible with the page cache
def responsive res space compress None if space compress is None space compress not g template debug if is api res res or u'' if not c allowed callback and request environ get 'WANT RAW JSON' res scriptsafe dumps res else res websafe json simplejson dumps res if c allowed callback res '/**/%s %s ' % websafe json c allo...
def responsive res space_compress None if space_compress is None space_compress not g template_debug if is_api res res or u'' if not c allowed_callback and request environ get 'WANT_RAW_JSON' res scriptsafe_dumps res else res websafe_json simplejson dumps res if c allowed_callback res '/**/%s %s ' % websafe_json c allo...
71
python-test-1168
python
What does the code join ?
a number of strings to one
def limited join sep items max chars 30 overflow marker ' ' full str sep join items if len full str < max chars return full strn chars 0n items 0for j item in enumerate items n chars + len item + len sep if n chars < max chars - len overflow marker n items + 1else breakreturn sep join list items[ n items] + [overflow m...
def limited_join sep items max_chars 30 overflow_marker ' ' full_str sep join items if len full_str < max_chars return full_strn_chars 0n_items 0for j item in enumerate items n_chars + len item + len sep if n_chars < max_chars - len overflow_marker n_items + 1else breakreturn sep join list items[ n_items] + [overflow_m...
68
python-test-1171
python
What does the code get ?
precision based on docfield options
def get field precision df doc None currency None from frappe utils import get number format infoif cint df precision precision cint df precision elif df fieldtype u' Currency' number format Noneif not currency and doc currency get field currency df doc if not currency currency frappe db get default u'currency' if curr...
def get_field_precision df doc None currency None from frappe utils import get_number_format_infoif cint df precision precision cint df precision elif df fieldtype u'Currency' number_format Noneif not currency and doc currency get_field_currency df doc if not currency currency frappe db get_default u'currency' if curre...
106
python-test-1177
python
What does the code return ?
the body of a recent tile
def get Recent Tile layer coord format key layer coord format body use by recent tiles['hash'] get key None 0 if body is None return Noneif time < use by logging debug ' Tile Stache Core add Recent Tile foundtileinrecenttiles %s' key return bodytry del recent tiles['hash'][key]except Key Error passreturn None
def _getRecentTile layer coord format key layer coord format body use_by _recent_tiles['hash'] get key None 0 if body is None return Noneif time < use_by logging debug 'TileStache Core _addRecentTile foundtileinrecenttiles %s' key return bodytry del _recent_tiles['hash'][key]except KeyError passreturn None
51
python-test-1178
python
Where does globals find ?
in an ast tree
def find globals g tree for child in tree if hasattr child 'body' and isinstance child body list find globals g child body elif isinstance child ast Function Def ast Class Def g add child name continueelif isinstance child ast Assign try g add child targets[ 0 ] id except Index Error Attribute Error passelif isinstance...
def find_globals g tree for child in tree if hasattr child 'body' and isinstance child body list find_globals g child body elif isinstance child ast FunctionDef ast ClassDef g add child name continueelif isinstance child ast Assign try g add child targets[0] id except IndexError AttributeError passelif isinstance child...
92
python-test-1179
python
What does ast use ?
to find globals in an ast tree
def find globals g tree for child in tree if hasattr child 'body' and isinstance child body list find globals g child body elif isinstance child ast Function Def ast Class Def g add child name continueelif isinstance child ast Assign try g add child targets[ 0 ] id except Index Error Attribute Error passelif isinstance...
def find_globals g tree for child in tree if hasattr child 'body' and isinstance child body list find_globals g child body elif isinstance child ast FunctionDef ast ClassDef g add child name continueelif isinstance child ast Assign try g add child targets[0] id except IndexError AttributeError passelif isinstance child...
92
python-test-1180
python
What does the code get ?
the current log entry for this asset
def asset get current log asset id table current s3 db asset logquery table asset id asset id & table cancel False & table deleted False asset log current db query select table id table status table datetime table cond table person id table organisation id table site id orderby ~ table datetime limitby 0 1 first if ass...
def asset_get_current_log asset_id table current s3db asset_logquery table asset_id asset_id & table cancel False & table deleted False asset_log current db query select table id table status table datetime table cond table person_id table organisation_id table site_id orderby ~ table datetime limitby 0 1 first if asse...
101
python-test-1181
python
How do an episode mark ?
as failed
def mark Failed ep Obj log str u''try with ep Obj lock quality Quality split Composite Status ep Obj status [1 ]ep Obj status Quality composite Status FAILED quality ep Obj save To DB except Episode Not Found Exception as e logger log u' Unabletogetepisode pleasesetitsstatusmanually ' + ex e logger WARNING return log s...
def markFailed epObj log_str u''try with epObj lock quality Quality splitCompositeStatus epObj status [1]epObj status Quality compositeStatus FAILED quality epObj saveToDB except EpisodeNotFoundException as e logger log u'Unabletogetepisode pleasesetitsstatusmanually ' + ex e logger WARNING return log_str
55
python-test-1188
python
What does the code get if it exists ?
the selected radio button
def get Selected Radio Plugin names radio Plugins for radio Plugin in radio Plugins if radio Plugin value return radio Pluginfor name in names for radio Plugin in radio Plugins if radio Plugin name name radio Plugin value Truereturn radio Pluginprint 'thisshouldneverhappen noget Selected Radio Plugininsettings'print na...
def getSelectedRadioPlugin names radioPlugins for radioPlugin in radioPlugins if radioPlugin value return radioPluginfor name in names for radioPlugin in radioPlugins if radioPlugin name name radioPlugin value Truereturn radioPluginprint 'thisshouldneverhappen nogetSelectedRadioPlugininsettings'print namesreturn radioP...
51
python-test-1190
python
When has checks been requested if the host is already locked / unlocked ?
when locking / unlocking
def check modify host locking host update data locked update data get 'locked' None if locked is not None if locked and host locked raise model logic Validation Error {'locked' ' Hostalreadylockedby%son%s ' % host locked by host lock time } if not locked and not host locked raise model logic Validation Error {'locked' ...
def check_modify_host_locking host update_data locked update_data get 'locked' None if locked is not None if locked and host locked raise model_logic ValidationError {'locked' 'Hostalreadylockedby%son%s ' % host locked_by host lock_time } if not locked and not host locked raise model_logic ValidationError {'locked' 'Ho...
57
python-test-1200
python
How do we connect to a task ?
with a named vip using minuteman
@pytest mark skipif not lb enabled reason ' Load Balancerdisabled' def test if minuteman routes to named vip dcos api session origin app origin uuid get test app origin app['port Definitions'][ 0 ]['labels'] {'VIP 0' 'foo 5000 '}with dcos api session marathon deploy and cleanup origin app proxy app proxy uuid get test ...
@pytest mark skipif not lb_enabled reason 'LoadBalancerdisabled' def test_if_minuteman_routes_to_named_vip dcos_api_session origin_app origin_uuid get_test_app origin_app['portDefinitions'][0]['labels'] {'VIP_0' 'foo 5000'}with dcos_api_session marathon deploy_and_cleanup origin_app proxy_app proxy_uuid get_test_app wi...
83
python-test-1202
python
Where did each function prototype declare ?
in * code
def find prototypes code prots []lines code split '\n' for line in lines m re match '\\s*' + re func prot line if m is not None rtype name args m groups [ 3]if args 'void' or args strip '' args []else args [tuple arg strip split '' for arg in args split ' ' ]prots append name args rtype return prots
def find_prototypes code prots []lines code split '\n' for line in lines m re match '\\s*' + re_func_prot line if m is not None rtype name args m groups [ 3]if args 'void' or args strip '' args []else args [tuple arg strip split '' for arg in args split ' ' ]prots append name args rtype return prots
62
python-test-1203
python
What declared in * code ?
each function prototype
def find prototypes code prots []lines code split '\n' for line in lines m re match '\\s*' + re func prot line if m is not None rtype name args m groups [ 3]if args 'void' or args strip '' args []else args [tuple arg strip split '' for arg in args split ' ' ]prots append name args rtype return prots
def find_prototypes code prots []lines code split '\n' for line in lines m re match '\\s*' + re_func_prot line if m is not None rtype name args m groups [ 3]if args 'void' or args strip '' args []else args [tuple arg strip split '' for arg in args split ' ' ]prots append name args rtype return prots
62
python-test-1204
python
What does the code load for processing ?
one or multiple images
@cli command 'open' @click option '-i' '--image' 'images' type click Path multiple True help ' Theimagefiletoopen ' @generatordef open cmd images for image in images try click echo ' Opening"%s"' % image if image '-' img Image open click get binary stdin img filename '-'else img Image open image yield img except Except...
@cli command 'open' @click option '-i' '--image' 'images' type click Path multiple True help 'Theimagefiletoopen ' @generatordef open_cmd images for image in images try click echo 'Opening"%s"' % image if image '-' img Image open click get_binary_stdin img filename '-'else img Image open image yield img except Exceptio...
65
python-test-1206
python
What does the code return up to a maximum of num_words words ?
the leading text contained in top_elem
def lead text top elem num words 10 pat re compile u'\\s+' flags re UNICODE words []def get text x attr u'text' ans getattr x attr if ans words extend filter None pat split ans stack [ top elem u'text' ]while stack and len words < num words elem attr stack pop get text elem attr if attr u'text' if elem is not top elem ...
def lead_text top_elem num_words 10 pat re compile u'\\s+' flags re UNICODE words []def get_text x attr u'text' ans getattr x attr if ans words extend filter None pat split ans stack [ top_elem u'text' ]while stack and len words < num_words elem attr stack pop get_text elem attr if attr u'text' if elem is not top_elem ...
87
python-test-1208
python
What does the code clean ?
an html fragment
def clean text tags ALLOWED TAGS attributes ALLOWED ATTRIBUTES styles ALLOWED STYLES strip False strip comments True if not text return u''text force unicode text if text startswith u'< --' text u'' + text class s Bleach Sanitizer allowed elements tagsallowed attributes attributesallowed css properties stylesstrip disa...
def clean text tags ALLOWED_TAGS attributes ALLOWED_ATTRIBUTES styles ALLOWED_STYLES strip False strip_comments True if not text return u''text force_unicode text if text startswith u'< --' text u'' + text class s BleachSanitizer allowed_elements tagsallowed_attributes attributesallowed_css_properties stylesstrip_disal...
67
python-test-1211
python
What do html indicate ?
that the users payment was declined
def get processor decline html params payment support email configuration helpers get value 'payment support email' settings PAYMENT SUPPORT EMAIL return format error html ' Sorry Ourpaymentprocessordidnotacceptyourpayment Thedecisiontheyreturnedwas{decision} andthereasonwas{reason} Youwerenotcharged Pleasetryadifferen...
def _get_processor_decline_html params payment_support_email configuration_helpers get_value 'payment_support_email' settings PAYMENT_SUPPORT_EMAIL return _format_error_html _ 'Sorry Ourpaymentprocessordidnotacceptyourpayment Thedecisiontheyreturnedwas{decision} andthereasonwas{reason} Youwerenotcharged Pleasetryadiffe...
62
python-test-1214
python
In which direction does the code carve vertical or horizontal seams ?
off an image
def seam carve img energy map mode num border 1 force copy True utils assert nD img 2 3 image util img as float img force copy energy map util img as float energy map force copy if image ndim 2 image image[ np newaxis]if mode 'horizontal' image np transpose image 1 0 2 image np ascontiguousarray image out seam carve v ...
def seam_carve img energy_map mode num border 1 force_copy True utils assert_nD img 2 3 image util img_as_float img force_copy energy_map util img_as_float energy_map force_copy if image ndim 2 image image[ np newaxis]if mode 'horizontal' image np transpose image 1 0 2 image np ascontiguousarray image out _seam_carve_v...
81
python-test-1215
python
What does the code carve off an image ?
vertical or horizontal seams
def seam carve img energy map mode num border 1 force copy True utils assert nD img 2 3 image util img as float img force copy energy map util img as float energy map force copy if image ndim 2 image image[ np newaxis]if mode 'horizontal' image np transpose image 1 0 2 image np ascontiguousarray image out seam carve v ...
def seam_carve img energy_map mode num border 1 force_copy True utils assert_nD img 2 3 image util img_as_float img force_copy energy_map util img_as_float energy_map force_copy if image ndim 2 image image[ np newaxis]if mode 'horizontal' image np transpose image 1 0 2 image np ascontiguousarray image out _seam_carve_v...
81
python-test-1216
python
What does the code create ?
a new defaulttoolstate
def new state trans tool invalid False state galaxy tools Default Tool State state inputs {}if invalid return statetry return tool new state trans except Exception as e log debug ' Failedtobuildtoolstatefortool"%s"usingstandardmethod willtrytofallbackoncustommethod %s' tool id e inputs tool inputs by page[ 0 ]context E...
def new_state trans tool invalid False state galaxy tools DefaultToolState state inputs {}if invalid return statetry return tool new_state trans except Exception as e log debug 'Failedtobuildtoolstatefortool"%s"usingstandardmethod willtrytofallbackoncustommethod %s' tool id e inputs tool inputs_by_page[0]context Expres...
71
python-test-1222
python
What does the code create ?
a new permission grant
def create permission grant role db resource uid resource type permission types permission grant db Permission Grant DB resource uid resource uid resource type resource type permission types permission types permission grant db Permission Grant add or update permission grant db role db update push permission grants str...
def create_permission_grant role_db resource_uid resource_type permission_types permission_grant_db PermissionGrantDB resource_uid resource_uid resource_type resource_type permission_types permission_types permission_grant_db PermissionGrant add_or_update permission_grant_db role_db update push__permission_grants str p...
56
python-test-1224
python
What does the code make ?
messages type report
def report messages stats sect stats if not stats['by msg'] raise utils Empty Report in order sorted [ value msg id for msg id value in six iteritems stats['by msg'] if not msg id startswith 'I' ] in order reverse lines 'messageid' 'occurrences' for value msg id in in order lines + msg id str value sect append ureports...
def report_messages_stats sect stats _ if not stats['by_msg'] raise utils EmptyReport in_order sorted [ value msg_id for msg_id value in six iteritems stats['by_msg'] if not msg_id startswith 'I' ] in_order reverse lines 'messageid' 'occurrences' for value msg_id in in_order lines + msg_id str value sect append ureport...
66
python-test-1232
python
What does the code find ?
a show by indexer i d in the show list
def find Certain Show show List indexerid if indexerid is None or show List is None or len show List 0 return Noneindexer ids [indexerid] if not isinstance indexerid list else indexerid results [show for show in show List if show indexerid in indexer ids ]if not results return Noneif len results 1 return results[ 0 ]ra...
def findCertainShow showList indexerid if indexerid is None or showList is None or len showList 0 return Noneindexer_ids [indexerid] if not isinstance indexerid list else indexerid results [show for show in showList if show indexerid in indexer_ids ]if not results return Noneif len results 1 return results[0]raise Mult...
61
python-test-1234
python
What do an array resample with minute data ?
into an array with session data
def minute to session column close locs data out if column 'open' minute to session open close locs data out elif column 'high' minute to session high close locs data out elif column 'low' minute to session low close locs data out elif column 'close' minute to session close close locs data out elif column 'volume' minu...
def minute_to_session column close_locs data out if column 'open' _minute_to_session_open close_locs data out elif column 'high' _minute_to_session_high close_locs data out elif column 'low' _minute_to_session_low close_locs data out elif column 'close' _minute_to_session_close close_locs data out elif column 'volume' ...
66
python-test-1235
python
How do an array resample into an array with session data ?
with minute data
def minute to session column close locs data out if column 'open' minute to session open close locs data out elif column 'high' minute to session high close locs data out elif column 'low' minute to session low close locs data out elif column 'close' minute to session close close locs data out elif column 'volume' minu...
def minute_to_session column close_locs data out if column 'open' _minute_to_session_open close_locs data out elif column 'high' _minute_to_session_high close_locs data out elif column 'low' _minute_to_session_low close_locs data out elif column 'close' _minute_to_session_close close_locs data out elif column 'volume' ...
66
python-test-1237
python
What does the code calculate in trace in trace in a paper by some of the leading authorities on model selection - dx ?
the deviance information criterion of the samples
def dic trace model None model modelcontext model mean deviance -2 * np mean [model logp pt for pt in trace] free rv means {rv name trace[rv name] mean axis 0 for rv in model free R Vs}deviance at mean -2 * model logp free rv means return 2 * mean deviance - deviance at mean
def dic trace model None model modelcontext model mean_deviance -2 * np mean [model logp pt for pt in trace] free_rv_means {rv name trace[rv name] mean axis 0 for rv in model free_RVs}deviance_at_mean -2 * model logp free_rv_means return 2 * mean_deviance - deviance_at_mean
56