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-2721
python
What does the code support only from a - > zzz ?
1 - 3 letter column names
def column index from string column fast False column column upper clen len column if not fast and not all 'A' < char < 'Z' for char in column msg ' Columnstringmustcontainonlycharacters A-Z got%s' % column raise Column String Index Exception msg if clen 1 return ord column[ 0 ] - 64 elif clen 2 return 1 + ord column[ ...
def column_index_from_string column fast False column column upper clen len column if not fast and not all 'A' < char < 'Z' for char in column msg 'ColumnstringmustcontainonlycharactersA-Z got%s' % column raise ColumnStringIndexException msg if clen 1 return ord column[0] - 64 elif clen 2 return 1 + ord column[0] - 65 ...
126
python-test-2722
python
What does the code convert into a column number ?
a column letter
def column index from string column fast False column column upper clen len column if not fast and not all 'A' < char < 'Z' for char in column msg ' Columnstringmustcontainonlycharacters A-Z got%s' % column raise Column String Index Exception msg if clen 1 return ord column[ 0 ] - 64 elif clen 2 return 1 + ord column[ ...
def column_index_from_string column fast False column column upper clen len column if not fast and not all 'A' < char < 'Z' for char in column msg 'ColumnstringmustcontainonlycharactersA-Z got%s' % column raise ColumnStringIndexException msg if clen 1 return ord column[0] - 64 elif clen 2 return 1 + ord column[0] - 65 ...
126
python-test-2723
python
When does the code support 1 - 3 letter column names only ?
from a - > zzz
def column index from string column fast False column column upper clen len column if not fast and not all 'A' < char < 'Z' for char in column msg ' Columnstringmustcontainonlycharacters A-Z got%s' % column raise Column String Index Exception msg if clen 1 return ord column[ 0 ] - 64 elif clen 2 return 1 + ord column[ ...
def column_index_from_string column fast False column column upper clen len column if not fast and not all 'A' < char < 'Z' for char in column msg 'ColumnstringmustcontainonlycharactersA-Z got%s' % column raise ColumnStringIndexException msg if clen 1 return ord column[0] - 64 elif clen 2 return 1 + ord column[0] - 65 ...
126
python-test-2729
python
What requires a reboot ?
a pending domain join action
def get pending domain join vname ' Default 'base key 'SYSTEM\\ Current Control Set\\ Services\\ Netlogon'avoid key '{ 0 }\\ Avoid Spn Set' format base key join key '{ 0 }\\ Join Domain' format base key avoid reg ret salt ['reg read value'] 'HKLM' avoid key vname if avoid reg ret['success'] log debug ' Foundkey %s' avo...
def get_pending_domain_join vname ' Default 'base_key 'SYSTEM\\CurrentControlSet\\Services\\Netlogon'avoid_key '{0}\\AvoidSpnSet' format base_key join_key '{0}\\JoinDomain' format base_key avoid_reg_ret __salt__['reg read_value'] 'HKLM' avoid_key vname if avoid_reg_ret['success'] log debug 'Foundkey %s' avoid_key retur...
100
python-test-2732
python
What should raise a repositorynotfound exception ?
an unknown local repository
def test local repo typo tmpdir template path os path join 'tests' 'unknown-repo' with pytest raises exceptions Repository Not Found as err repository determine repo dir template path abbreviations {} clone to dir str tmpdir checkout None no input True assert str err value ' Avalidrepositoryfor"{}"couldnotbefoundinthef...
def test_local_repo_typo tmpdir template_path os path join 'tests' 'unknown-repo' with pytest raises exceptions RepositoryNotFound as err repository determine_repo_dir template_path abbreviations {} clone_to_dir str tmpdir checkout None no_input True assert str err value 'Avalidrepositoryfor"{}"couldnotbefoundinthefoll...
59
python-test-2733
python
What should an unknown local repository raise ?
a repositorynotfound exception
def test local repo typo tmpdir template path os path join 'tests' 'unknown-repo' with pytest raises exceptions Repository Not Found as err repository determine repo dir template path abbreviations {} clone to dir str tmpdir checkout None no input True assert str err value ' Avalidrepositoryfor"{}"couldnotbefoundinthef...
def test_local_repo_typo tmpdir template_path os path join 'tests' 'unknown-repo' with pytest raises exceptions RepositoryNotFound as err repository determine_repo_dir template_path abbreviations {} clone_to_dir str tmpdir checkout None no_input True assert str err value 'Avalidrepositoryfor"{}"couldnotbefoundinthefoll...
59
python-test-2734
python
What do tables use ?
osm2pgsql
def prepare data filename tmp prefix dbargs osm 2 pgsql projection args osm 2 pgsql split + ['--create' '--merc' '--prefix' tmp prefix] for flag key in [ '-d' 'database' '-U' 'user' '-W' 'password' '-H' 'host' ] if key in dbargs args + flag dbargs[key] args + [filename]create Popen args stderr PIPE stdout PIPE create w...
def prepare_data filename tmp_prefix dbargs osm2pgsql projection args osm2pgsql split + ['--create' '--merc' '--prefix' tmp_prefix] for flag key in [ '-d' 'database' '-U' 'user' '-W' 'password' '-H' 'host' ] if key in dbargs args + flag dbargs[key] args + [filename]create Popen args stderr PIPE stdout PIPE create wait ...
68
python-test-2741
python
What does the code update ?
the users that contributed yesterday
@cronjobs registerdef reindex users that contributed yesterday if settings STAGE returntoday datetime now yesterday today - timedelta days 1 user ids list Answer objects filter created gte yesterday created lt today values list 'creator id' flat True user ids + list Revision objects filter created gte yesterday created...
@cronjobs registerdef reindex_users_that_contributed_yesterday if settings STAGE returntoday datetime now yesterday today - timedelta days 1 user_ids list Answer objects filter created__gte yesterday created__lt today values_list 'creator_id' flat True user_ids + list Revision objects filter created__gte yesterday crea...
85
python-test-2742
python
When did the users contribute ?
yesterday
@cronjobs registerdef reindex users that contributed yesterday if settings STAGE returntoday datetime now yesterday today - timedelta days 1 user ids list Answer objects filter created gte yesterday created lt today values list 'creator id' flat True user ids + list Revision objects filter created gte yesterday created...
@cronjobs registerdef reindex_users_that_contributed_yesterday if settings STAGE returntoday datetime now yesterday today - timedelta days 1 user_ids list Answer objects filter created__gte yesterday created__lt today values_list 'creator_id' flat True user_ids + list Revision objects filter created__gte yesterday crea...
85
python-test-2746
python
What does the code create ?
a django user on the cabot server
def create user username password email code "username '{username}' password '{password}' email '{email}' fromdjango contrib auth modelsimport User User objects filter username username delete User objects create superuser username email password "code code format username username password password email email shell c...
def create_user username password email code "username '{username}' password '{password}' email '{email}' fromdjango contrib auth modelsimportUser User objects filter username username delete User objects create_superuser username email password "code code format username username password password email email shell_cm...
60
python-test-2751
python
What did the code set ?
the hp ilo sensor
def setup platform hass config add devices discovery info None hostname config get CONF HOST port config get CONF PORT login config get CONF USERNAME password config get CONF PASSWORD monitored variables config get CONF MONITORED VARIABLES name config get CONF NAME try hp ilo data Hp Ilo Data hostname port login passwo...
def setup_platform hass config add_devices discovery_info None hostname config get CONF_HOST port config get CONF_PORT login config get CONF_USERNAME password config get CONF_PASSWORD monitored_variables config get CONF_MONITORED_VARIABLES name config get CONF_NAME try hp_ilo_data HpIloData hostname port login password...
97
python-test-2754
python
What does the code get ?
the prefix to operate in args : ctx : the context of conda args : the argparse args from the command line search : whether search for prefix returns : the prefix raises : condaenvironmentnotfounderror if the prefix is invalid
def get prefix ctx args search True if getattr args u'name' None if u'/' in args name raise Conda Value Error u"'/'notallowedinenvironmentname %s" % args name getattr args u'json' False if args name ROOT ENV NAME return ctx root dirif search return locate prefix by name ctx args name else return join ctx envs dirs[ 0 ]...
def get_prefix ctx args search True if getattr args u'name' None if u'/' in args name raise CondaValueError u"'/'notallowedinenvironmentname %s" % args name getattr args u'json' False if args name ROOT_ENV_NAME return ctx root_dirif search return locate_prefix_by_name ctx args name else return join ctx envs_dirs[0] arg...
74
python-test-2755
python
What raises condaenvironmentnotfounderror if the prefix is invalid ?
the prefix
def get prefix ctx args search True if getattr args u'name' None if u'/' in args name raise Conda Value Error u"'/'notallowedinenvironmentname %s" % args name getattr args u'json' False if args name ROOT ENV NAME return ctx root dirif search return locate prefix by name ctx args name else return join ctx envs dirs[ 0 ]...
def get_prefix ctx args search True if getattr args u'name' None if u'/' in args name raise CondaValueError u"'/'notallowedinenvironmentname %s" % args name getattr args u'json' False if args name ROOT_ENV_NAME return ctx root_dirif search return locate_prefix_by_name ctx args name else return join ctx envs_dirs[0] arg...
74
python-test-2756
python
In which direction does the argparse arg ?
from the command line search
def get prefix ctx args search True if getattr args u'name' None if u'/' in args name raise Conda Value Error u"'/'notallowedinenvironmentname %s" % args name getattr args u'json' False if args name ROOT ENV NAME return ctx root dirif search return locate prefix by name ctx args name else return join ctx envs dirs[ 0 ]...
def get_prefix ctx args search True if getattr args u'name' None if u'/' in args name raise CondaValueError u"'/'notallowedinenvironmentname %s" % args name getattr args u'json' False if args name ROOT_ENV_NAME return ctx root_dirif search return locate_prefix_by_name ctx args name else return join ctx envs_dirs[0] arg...
74
python-test-2757
python
What does the prefix raise if the prefix is invalid ?
condaenvironmentnotfounderror
def get prefix ctx args search True if getattr args u'name' None if u'/' in args name raise Conda Value Error u"'/'notallowedinenvironmentname %s" % args name getattr args u'json' False if args name ROOT ENV NAME return ctx root dirif search return locate prefix by name ctx args name else return join ctx envs dirs[ 0 ]...
def get_prefix ctx args search True if getattr args u'name' None if u'/' in args name raise CondaValueError u"'/'notallowedinenvironmentname %s" % args name getattr args u'json' False if args name ROOT_ENV_NAME return ctx root_dirif search return locate_prefix_by_name ctx args name else return join ctx envs_dirs[0] arg...
74
python-test-2758
python
What does the code update ?
the portage tree
def refresh db if 'eix sync' in salt return salt ['eix sync'] if 'makeconf features contains' in salt and salt ['makeconf features contains'] 'webrsync-gpg' cmd 'emerge-webrsync-q'if salt utils which 'emerge-delta-webrsync' cmd 'emerge-delta-webrsync-q'return salt ['cmd retcode'] cmd python shell False 0 else if salt [...
def refresh_db if 'eix sync' in __salt__ return __salt__['eix sync'] if 'makeconf features_contains' in __salt__ and __salt__['makeconf features_contains'] 'webrsync-gpg' cmd 'emerge-webrsync-q'if salt utils which 'emerge-delta-webrsync' cmd 'emerge-delta-webrsync-q'return __salt__['cmd retcode'] cmd python_shell False...
67
python-test-2763
python
What has cybersource accepted ?
the payment
def payment accepted order id auth amount currency decision try order Order objects get id order id except Order Does Not Exist raise CC Processor Data Exception ' Thepaymentprocessoracceptedanorderwhosenumberisnotinoursystem ' if decision 'ACCEPT' if auth amount order total cost and currency lower order currency lower...
def _payment_accepted order_id auth_amount currency decision try order Order objects get id order_id except Order DoesNotExist raise CCProcessorDataException _ 'Thepaymentprocessoracceptedanorderwhosenumberisnotinoursystem ' if decision 'ACCEPT' if auth_amount order total_cost and currency lower order currency lower re...
104
python-test-2767
python
What did the code read ?
the header of a pack file
def read pack header read header read 12 if not header return None None if header[ 4] 'PACK' raise Assertion Error ' Invalidpackheader%r' % header version unpack from '>L' header 4 if version not in 2 3 raise Assertion Error ' Versionwas%d' % version num objects unpack from '>L' header 8 return version num objects
def read_pack_header read header read 12 if not header return None None if header[ 4] 'PACK' raise AssertionError 'Invalidpackheader%r' % header version unpack_from '>L' header 4 if version not in 2 3 raise AssertionError 'Versionwas%d' % version num_objects unpack_from '>L' header 8 return version num_objects
55
python-test-2775
python
What does this fix ?
a bunch of validation errors that happen during the migration
def fix bad data django obj dirty if isinstance django obj models Node if django obj title strip u'' django obj title u' Blank Title'dirty Trueif isinstance django obj models Embargo if django obj state u'active' django obj state u'completed'dirty Trueelif django obj state u'cancelled' django obj state u'rejected'dirty...
def fix_bad_data django_obj dirty if isinstance django_obj models Node if django_obj title strip u'' django_obj title u'BlankTitle'dirty Trueif isinstance django_obj models Embargo if django_obj state u'active' django_obj state u'completed'dirty Trueelif django_obj state u'cancelled' django_obj state u'rejected'dirty T...
86
python-test-2776
python
When do validation errors happen ?
during the migration
def fix bad data django obj dirty if isinstance django obj models Node if django obj title strip u'' django obj title u' Blank Title'dirty Trueif isinstance django obj models Embargo if django obj state u'active' django obj state u'completed'dirty Trueelif django obj state u'cancelled' django obj state u'rejected'dirty...
def fix_bad_data django_obj dirty if isinstance django_obj models Node if django_obj title strip u'' django_obj title u'BlankTitle'dirty Trueif isinstance django_obj models Embargo if django_obj state u'active' django_obj state u'completed'dirty Trueelif django_obj state u'cancelled' django_obj state u'rejected'dirty T...
86
python-test-2780
python
What does the code get ?
statistics for the answer groups and rules of this state
def get state rules stats exploration id state name exploration exp services get exploration by id exploration id state exploration states[state name]rule keys []for group in state interaction answer groups for rule in group rule specs rule keys append OLD SUBMIT HANDLER NAME rule stringify classified rule if state int...
def get_state_rules_stats exploration_id state_name exploration exp_services get_exploration_by_id exploration_id state exploration states[state_name]rule_keys []for group in state interaction answer_groups for rule in group rule_specs rule_keys append _OLD_SUBMIT_HANDLER_NAME rule stringify_classified_rule if state in...
122
python-test-2784
python
What do stats give ?
to * stats *
def log stats resource None stats source None log level DEFAULT LOG LEVEL **kwargs if stats source is not None kwargs stats source if stats resource is None if RESOURCE ID not in kwargs or RESOURCE NAME not in kwargs raise Value Error ' Missingrequiredstatslabels ' else if not hasattr stats resource Conf With Id ID and...
def log stats_resource None stats_source None log_level DEFAULT_LOG_LEVEL **kwargs if stats_source is not None kwargs stats_source if stats_resource is None if RESOURCE_ID not in kwargs or RESOURCE_NAME not in kwargs raise ValueError 'Missingrequiredstatslabels ' else if not hasattr stats_resource ConfWithId ID and has...
104
python-test-2789
python
How do state functions match disabled states ?
in funs
def disabled funs ret [] disabled salt ['grains get'] 'state runs disabled' for state in funs for state in disabled if ' *' in state target state state split ' ' [0 ]target state target state + ' ' if not target state endswith ' ' else target state if state startswith target state err ' Thestatefile"{ 0 }"iscurrentlydi...
def _disabled funs ret []_disabled __salt__['grains get'] 'state_runs_disabled' for state in funs for _state in _disabled if ' *' in _state target_state _state split ' ' [0]target_state target_state + ' ' if not target_state endswith ' ' else target_state if state startswith target_state err 'Thestatefile"{0}"iscurrent...
94
python-test-2792
python
For what purpose does the code add extra xml properties to the tag ?
for the calling test
@pytest fixturedef record xml property request request node warn code 'C 3 ' message 'record xml propertyisanexperimentalfeature' xml getattr request config ' xml' None if xml is not None node reporter xml node reporter request node nodeid return node reporter add propertyelse def add property noop name value passretur...
@pytest fixturedef record_xml_property request request node warn code 'C3' message 'record_xml_propertyisanexperimentalfeature' xml getattr request config '_xml' None if xml is not None node_reporter xml node_reporter request node nodeid return node_reporter add_propertyelse def add_property_noop name value passreturn ...
52
python-test-2793
python
What does the code add to the tag for the calling test ?
extra xml properties
@pytest fixturedef record xml property request request node warn code 'C 3 ' message 'record xml propertyisanexperimentalfeature' xml getattr request config ' xml' None if xml is not None node reporter xml node reporter request node nodeid return node reporter add propertyelse def add property noop name value passretur...
@pytest fixturedef record_xml_property request request node warn code 'C3' message 'record_xml_propertyisanexperimentalfeature' xml getattr request config '_xml' None if xml is not None node_reporter xml node_reporter request node nodeid return node_reporter add_propertyelse def add_property_noop name value passreturn ...
52
python-test-2795
python
What do pexpect use ?
to retrieve the output of show ip int brief
def main ip addr raw input ' Enter I Paddress ' username 'pyclass'port 22 ssh conn pexpect spawn 'ssh-l{}{}-p{}' format username ip addr port ssh conn timeout 3login ssh conn prompt find prompt ssh conn ssh conn sendline 'terminallength 0 ' ssh conn expect prompt ssh conn sendline 'showipintbrief' ssh conn expect promp...
def main ip_addr raw_input 'EnterIPaddress ' username 'pyclass'port 22ssh_conn pexpect spawn 'ssh-l{}{}-p{}' format username ip_addr port ssh_conn timeout 3login ssh_conn prompt find_prompt ssh_conn ssh_conn sendline 'terminallength0' ssh_conn expect prompt ssh_conn sendline 'showipintbrief' ssh_conn expect prompt prin...
59
python-test-2796
python
How is the specified ruby installed ?
with rvm
def installed name default False user None ret {'name' name 'result' None 'comment' '' 'changes' {}}if opts ['test'] ret['comment'] ' Ruby{ 0 }issettobeinstalled' format name return retret check rvm ret user if ret['result'] is False if not salt ['rvm install'] runas user ret['comment'] 'RV Mfailedtoinstall 'return ret...
def installed name default False user None ret {'name' name 'result' None 'comment' '' 'changes' {}}if __opts__['test'] ret['comment'] 'Ruby{0}issettobeinstalled' format name return retret _check_rvm ret user if ret['result'] is False if not __salt__['rvm install'] runas user ret['comment'] 'RVMfailedtoinstall 'return ...
68
python-test-2802
python
How does it prepend the name as the class is subclassed ?
with as many " > "
def get Name obj def sanitize name return name replace ' ' '/' if isinstance obj Build Step Factory klass obj factoryelse klass type obj name ''klasses klass + inspect getmro klass for klass in klasses if hasattr klass ' module ' and klass module startswith 'buildbot ' return sanitize name + klass module + ' ' + klass ...
def getName obj def sanitize name return name replace ' ' '/' if isinstance obj _BuildStepFactory klass obj factoryelse klass type obj name ''klasses klass + inspect getmro klass for klass in klasses if hasattr klass '__module__' and klass __module__ startswith 'buildbot ' return sanitize name + klass __module__ + ' ' ...
68
python-test-2805
python
What does the code remove ?
an lvm volume group name the volume group to remove
def vg absent name ret {'changes' {} 'comment' '' 'name' name 'result' True}if not salt ['lvm vgdisplay'] name ret['comment'] ' Volume Group{ 0 }alreadyabsent' format name elif opts ['test'] ret['comment'] ' Volume Group{ 0 }issettoberemoved' format name ret['result'] Nonereturn retelse changes salt ['lvm vgremove'] na...
def vg_absent name ret {'changes' {} 'comment' '' 'name' name 'result' True}if not __salt__['lvm vgdisplay'] name ret['comment'] 'VolumeGroup{0}alreadyabsent' format name elif __opts__['test'] ret['comment'] 'VolumeGroup{0}issettoberemoved' format name ret['result'] Nonereturn retelse changes __salt__['lvm vgremove'] n...
74
python-test-2806
python
What does the code get ?
the slaac address within given network
def slaac value query '' try vtype ipaddr value 'type' if vtype 'address' v ipaddr value 'cidr' elif vtype 'network' v ipaddr value 'subnet' if ipaddr value 'version' 6 return Falsevalue netaddr IP Network v except return Falseif not query return Falsetry mac hwaddr query alias 'slaac' eui netaddr EUI mac except return...
def slaac value query '' try vtype ipaddr value 'type' if vtype 'address' v ipaddr value 'cidr' elif vtype 'network' v ipaddr value 'subnet' if ipaddr value 'version' 6 return Falsevalue netaddr IPNetwork v except return Falseif not query return Falsetry mac hwaddr query alias 'slaac' eui netaddr EUI mac except return ...
59
python-test-2808
python
What does the code find ?
irc logins
def irc logins full load pkt user search re match irc user re full load pass search re match irc pw re full load pass search 2 re search irc pw re 2 full load lower if user search msg 'IR Cnick %s' % user search group 1 return msgif pass search msg 'IR Cpass %s' % pass search group 1 return msgif pass search 2 msg 'IR ...
def irc_logins full_load pkt user_search re match irc_user_re full_load pass_search re match irc_pw_re full_load pass_search2 re search irc_pw_re2 full_load lower if user_search msg 'IRCnick %s' % user_search group 1 return msgif pass_search msg 'IRCpass %s' % pass_search group 1 return msgif pass_search2 msg 'IRCpass ...
78
python-test-2810
python
What does function handle ?
a forgotten password request
@anonymous user requireddef forgot password form class security forgot password formif request json form form class Multi Dict request json else form form class if form validate on submit send reset password instructions form user if request json is None do flash *get message 'PASSWORD RESET REQUEST' email form user em...
@anonymous_user_requireddef forgot_password form_class _security forgot_password_formif request json form form_class MultiDict request json else form form_class if form validate_on_submit send_reset_password_instructions form user if request json is None do_flash *get_message 'PASSWORD_RESET_REQUEST' email form user em...
78
python-test-2813
python
What do the minion refresh ?
the module and grain data
def refresh modules async True try if async ret salt ['event fire'] {} 'module refresh' else eventer salt utils event get event 'minion' opts opts listen True ret salt ['event fire'] {'notify' True} 'module refresh' log trace 'refresh moduleswaitingformodulerefreshtocomplete' eventer get event tag '/salt/minion/minion ...
def refresh_modules async True try if async ret __salt__['event fire'] {} 'module_refresh' else eventer salt utils event get_event 'minion' opts __opts__ listen True ret __salt__['event fire'] {'notify' True} 'module_refresh' log trace 'refresh_moduleswaitingformodulerefreshtocomplete' eventer get_event tag '/salt/mini...
60
python-test-2816
python
How does pt - br - > language class support portuguese ?
through code " pt - br "
def test language portuguese lang Language 'pt-br' assert equals lang code u'pt-br' assert equals lang name u' Portuguese' assert equals lang native u' Portugu\xeas' assert equals lang feature u' Funcionalidade' assert equals lang scenario u' Cen\xe 1 rio Cenario' assert equals lang examples u' Exemplos Cen\xe 1 rios' ...
def test_language_portuguese lang Language 'pt-br' assert_equals lang code u'pt-br' assert_equals lang name u'Portuguese' assert_equals lang native u'Portugu\xeas' assert_equals lang feature u'Funcionalidade' assert_equals lang scenario u'Cen\xe1rio Cenario' assert_equals lang examples u'Exemplos Cen\xe1rios' assert_eq...
60
python-test-2817
python
What can the task runner be used ?
to run the given job
def get task runner local task job if TASK RUNNER ' Bash Task Runner' return Bash Task Runner local task job elif TASK RUNNER ' Cgroup Task Runner' from airflow contrib task runner cgroup task runner import Cgroup Task Runnerreturn Cgroup Task Runner local task job else raise Airflow Exception ' Unknowntaskrunnertype{}...
def get_task_runner local_task_job if _TASK_RUNNER 'BashTaskRunner' return BashTaskRunner local_task_job elif _TASK_RUNNER 'CgroupTaskRunner' from airflow contrib task_runner cgroup_task_runner import CgroupTaskRunnerreturn CgroupTaskRunner local_task_job else raise AirflowException 'Unknowntaskrunnertype{}' format _TA...
55
python-test-2818
python
What does the code get ?
the task runner that can be used to run the given job
def get task runner local task job if TASK RUNNER ' Bash Task Runner' return Bash Task Runner local task job elif TASK RUNNER ' Cgroup Task Runner' from airflow contrib task runner cgroup task runner import Cgroup Task Runnerreturn Cgroup Task Runner local task job else raise Airflow Exception ' Unknowntaskrunnertype{}...
def get_task_runner local_task_job if _TASK_RUNNER 'BashTaskRunner' return BashTaskRunner local_task_job elif _TASK_RUNNER 'CgroupTaskRunner' from airflow contrib task_runner cgroup_task_runner import CgroupTaskRunnerreturn CgroupTaskRunner local_task_job else raise AirflowException 'Unknowntaskrunnertype{}' format _TA...
55
python-test-2819
python
What can be used to run the given job ?
the task runner
def get task runner local task job if TASK RUNNER ' Bash Task Runner' return Bash Task Runner local task job elif TASK RUNNER ' Cgroup Task Runner' from airflow contrib task runner cgroup task runner import Cgroup Task Runnerreturn Cgroup Task Runner local task job else raise Airflow Exception ' Unknowntaskrunnertype{}...
def get_task_runner local_task_job if _TASK_RUNNER 'BashTaskRunner' return BashTaskRunner local_task_job elif _TASK_RUNNER 'CgroupTaskRunner' from airflow contrib task_runner cgroup_task_runner import CgroupTaskRunnerreturn CgroupTaskRunner local_task_job else raise AirflowException 'Unknowntaskrunnertype{}' format _TA...
55
python-test-2822
python
What does the code setup ?
the mqtt lock
def setup platform hass config add devices discovery info None value template config get CONF VALUE TEMPLATE if value template is not None value template hass hassadd devices [ Mqtt Lock hass config get CONF NAME config get CONF STATE TOPIC config get CONF COMMAND TOPIC config get CONF QOS config get CONF RETAIN config...
def setup_platform hass config add_devices discovery_info None value_template config get CONF_VALUE_TEMPLATE if value_template is not None value_template hass hassadd_devices [MqttLock hass config get CONF_NAME config get CONF_STATE_TOPIC config get CONF_COMMAND_TOPIC config get CONF_QOS config get CONF_RETAIN config g...
71
python-test-2823
python
When do flocker instal ?
on centos 7
def centos 7 install commands version installable version get installable version flocker version return sequence [run command 'yumcleanall' run command 'yuminstall-y{}' format get repository url distribution 'centos- 7 ' flocker version installable version run from args ['yum' 'install'] + get repo options installable...
def _centos7_install_commands version installable_version get_installable_version flocker_version return sequence [run command 'yumcleanall' run command 'yuminstall-y{}' format get_repository_url distribution 'centos-7' flocker_version installable_version run_from_args ['yum' 'install'] + get_repo_options installable_v...
51
python-test-2824
python
What does the code add to an lvm volume group cli examples ?
physical volumes
def vgextend vgname devices if not vgname or not devices return ' Error vgnameanddevice s arebothrequired'if isinstance devices six string types devices devices split ' ' cmd ['vgextend' vgname]for device in devices cmd append device out salt ['cmd run'] cmd python shell False splitlines vgdata {' Outputfromvgextend' o...
def vgextend vgname devices if not vgname or not devices return 'Error vgnameanddevice s arebothrequired'if isinstance devices six string_types devices devices split ' ' cmd ['vgextend' vgname]for device in devices cmd append device out __salt__['cmd run'] cmd python_shell False splitlines vgdata {'Outputfromvgextend' ...
53
python-test-2827
python
What does a string represent ?
that list
def makelist inlist listchar '' stringify False escape False encoding None if stringify inlist list stringify inlist listdict {'[' '[%s]' ' ' ' %s ' '' '%s'}outline []if len inlist < 2 listchar listchar or '[' for item in inlist if not isinstance item list tuple if escape item quote escape item outline append elem quot...
def makelist inlist listchar '' stringify False escape False encoding None if stringify inlist list_stringify inlist listdict {'[' '[%s]' ' ' ' %s ' '' '%s'}outline []if len inlist < 2 listchar listchar or '[' for item in inlist if not isinstance item list tuple if escape item quote_escape item outline append elem_quot...
77
python-test-2830
python
What should have wrappers created for them ?
all the sem compliant tools
def generate all classes modules list [] launcher [] redirect x False mipav hacks False all code {}for module in modules list print u' ' * 80 print u' Generating Definitionformodule{ 0 }' format module print u'^' * 80 package code module generate class module launcher redirect x redirect x mipav hacks mipav hacks cur p...
def generate_all_classes modules_list [] launcher [] redirect_x False mipav_hacks False all_code {}for module in modules_list print u' ' * 80 print u'GeneratingDefinitionformodule{0}' format module print u'^' * 80 package code module generate_class module launcher redirect_x redirect_x mipav_hacks mipav_hacks cur_packa...
128
python-test-2831
python
What should all the sem compliant tools have ?
wrappers created for them
def generate all classes modules list [] launcher [] redirect x False mipav hacks False all code {}for module in modules list print u' ' * 80 print u' Generating Definitionformodule{ 0 }' format module print u'^' * 80 package code module generate class module launcher redirect x redirect x mipav hacks mipav hacks cur p...
def generate_all_classes modules_list [] launcher [] redirect_x False mipav_hacks False all_code {}for module in modules_list print u' ' * 80 print u'GeneratingDefinitionformodule{0}' format module print u'^' * 80 package code module generate_class module launcher redirect_x redirect_x mipav_hacks mipav_hacks cur_packa...
128
python-test-2832
python
What contains all the sem compliant tools that should have wrappers created for them ?
modules_list
def generate all classes modules list [] launcher [] redirect x False mipav hacks False all code {}for module in modules list print u' ' * 80 print u' Generating Definitionformodule{ 0 }' format module print u'^' * 80 package code module generate class module launcher redirect x redirect x mipav hacks mipav hacks cur p...
def generate_all_classes modules_list [] launcher [] redirect_x False mipav_hacks False all_code {}for module in modules_list print u' ' * 80 print u'GeneratingDefinitionformodule{0}' format module print u'^' * 80 package code module generate_class module launcher redirect_x redirect_x mipav_hacks mipav_hacks cur_packa...
128
python-test-2833
python
What does modules_list contain ?
all the sem compliant tools that should have wrappers created for them
def generate all classes modules list [] launcher [] redirect x False mipav hacks False all code {}for module in modules list print u' ' * 80 print u' Generating Definitionformodule{ 0 }' format module print u'^' * 80 package code module generate class module launcher redirect x redirect x mipav hacks mipav hacks cur p...
def generate_all_classes modules_list [] launcher [] redirect_x False mipav_hacks False all_code {}for module in modules_list print u' ' * 80 print u'GeneratingDefinitionformodule{0}' format module print u'^' * 80 package code module generate_class module launcher redirect_x redirect_x mipav_hacks mipav_hacks cur_packa...
128
python-test-2834
python
What do the user have ?
an existing primary allauth
def verify user user if not user email raise Validation Error " Youcannotverifyanaccountwithnoemailset Youcansetthisuser'semailwith'pootleupdate user email%s EMAIL'" % user username try validate email unique user email user except Validation Error raise Validation Error " Thisuser'semailisnotunique Youcanfindduplicatee...
def verify_user user if not user email raise ValidationError "Youcannotverifyanaccountwithnoemailset Youcansetthisuser'semailwith'pootleupdate_user_email%sEMAIL'" % user username try validate_email_unique user email user except ValidationError raise ValidationError "Thisuser'semailisnotunique Youcanfindduplicateemailsw...
107
python-test-2835
python
How has the code verify a user account if the user has an existing primary allauth ?
without email confirmation
def verify user user if not user email raise Validation Error " Youcannotverifyanaccountwithnoemailset Youcansetthisuser'semailwith'pootleupdate user email%s EMAIL'" % user username try validate email unique user email user except Validation Error raise Validation Error " Thisuser'semailisnotunique Youcanfindduplicatee...
def verify_user user if not user email raise ValidationError "Youcannotverifyanaccountwithnoemailset Youcansetthisuser'semailwith'pootleupdate_user_email%sEMAIL'" % user username try validate_email_unique user email user except ValidationError raise ValidationError "Thisuser'semailisnotunique Youcanfindduplicateemailsw...
107
python-test-2837
python
What can contain sensitive information that should not be logged ?
header values
def scrub headers headers if isinstance headers dict headers headers items headers [ parse header string key parse header string val for key val in headers]if not logger settings get 'redact sensitive headers' True return dict headers if logger settings get 'reveal sensitive prefix' 16 < 0 logger settings['reveal sensi...
def scrub_headers headers if isinstance headers dict headers headers items headers [ parse_header_string key parse_header_string val for key val in headers]if not logger_settings get 'redact_sensitive_headers' True return dict headers if logger_settings get 'reveal_sensitive_prefix' 16 < 0 logger_settings['reveal_sensi...
63
python-test-2838
python
What can header values contain ?
sensitive information that should not be logged
def scrub headers headers if isinstance headers dict headers headers items headers [ parse header string key parse header string val for key val in headers]if not logger settings get 'redact sensitive headers' True return dict headers if logger settings get 'reveal sensitive prefix' 16 < 0 logger settings['reveal sensi...
def scrub_headers headers if isinstance headers dict headers headers items headers [ parse_header_string key parse_header_string val for key val in headers]if not logger_settings get 'redact_sensitive_headers' True return dict headers if logger_settings get 'reveal_sensitive_prefix' 16 < 0 logger_settings['reveal_sensi...
63
python-test-2859
python
What do we add to the end of that here ?
< ins > ins_chunks</ins
def merge insert ins chunks doc unbalanced start balanced unbalanced end split unbalanced ins chunks doc extend unbalanced start if doc and not doc[ -1 ] endswith '' doc[ -1 ] + ''doc append '<ins>' if balanced and balanced[ -1 ] endswith '' balanced[ -1 ] balanced[ -1 ][ -1 ]doc extend balanced doc append '</ins>' doc...
def merge_insert ins_chunks doc unbalanced_start balanced unbalanced_end split_unbalanced ins_chunks doc extend unbalanced_start if doc and not doc[ -1 ] endswith '' doc[ -1 ] + ''doc append '<ins>' if balanced and balanced[ -1 ] endswith '' balanced[ -1 ] balanced[ -1 ][ -1 ]doc extend balanced doc append '</ins>' doc...
60
python-test-2860
python
For what purpose does the code update the db field in all version models ?
to point to the correct write db for the model
def set version db apps schema editor db alias schema editor connection alias Version apps get model u'reversion' u' Version' content types Version objects using db alias order by values list u'content type id' u'content type app label' u'content type model' distinct model dbs defaultdict list for content type id app l...
def set_version_db apps schema_editor db_alias schema_editor connection aliasVersion apps get_model u'reversion' u'Version' content_types Version objects using db_alias order_by values_list u'content_type_id' u'content_type__app_label' u'content_type__model' distinct model_dbs defaultdict list for content_type_id app_l...
131
python-test-2861
python
What does the code update to point to the correct write db for the model ?
the db field in all version models
def set version db apps schema editor db alias schema editor connection alias Version apps get model u'reversion' u' Version' content types Version objects using db alias order by values list u'content type id' u'content type app label' u'content type model' distinct model dbs defaultdict list for content type id app l...
def set_version_db apps schema_editor db_alias schema_editor connection aliasVersion apps get_model u'reversion' u'Version' content_types Version objects using db_alias order_by values_list u'content_type_id' u'content_type__app_label' u'content_type__model' distinct model_dbs defaultdict list for content_type_id app_l...
131
python-test-2871
python
How do changes to the directory read ?
using the specified directory handle
def read directory changes handle recursive event buffer ctypes create string buffer BUFFER SIZE nbytes ctypes wintypes DWORD try Read Directory Changes W handle ctypes byref event buffer len event buffer recursive WATCHDOG FILE NOTIFY FLAGS ctypes byref nbytes None None except Windows Error as e if e winerror ERROR OP...
def read_directory_changes handle recursive event_buffer ctypes create_string_buffer BUFFER_SIZE nbytes ctypes wintypes DWORD try ReadDirectoryChangesW handle ctypes byref event_buffer len event_buffer recursive WATCHDOG_FILE_NOTIFY_FLAGS ctypes byref nbytes None None except WindowsError as e if e winerror ERROR_OPERAT...
72
python-test-2873
python
What do a decorator perform ?
a lock-*-unlock cycle
def with backing lock method def wrapped method self *args **dargs already have lock self backing file lock is not None if not already have lock self lock backing file try return method self *args **dargs finally if not already have lock self unlock backing file wrapped method name method name wrapped method doc method...
def with_backing_lock method def wrapped_method self *args **dargs already_have_lock self _backing_file_lock is not None if not already_have_lock self _lock_backing_file try return method self *args **dargs finally if not already_have_lock self _unlock_backing_file wrapped_method __name__ method __name__wrapped_method ...
59
python-test-2877
python
What does the code ensure ?
the current node joined to a cluster with node user@host name irrelevant
def joined name host user 'rabbit' ram node None runas 'root' ret {'name' name 'result' True 'comment' '' 'changes' {}}status salt ['rabbitmq cluster status'] if '{ 0 }@{ 1 }' format user host in status ret['comment'] ' Alreadyincluster'return retif not opts ['test'] result salt ['rabbitmq join cluster'] host user ram ...
def joined name host user 'rabbit' ram_node None runas 'root' ret {'name' name 'result' True 'comment' '' 'changes' {}}status __salt__['rabbitmq cluster_status'] if '{0}@{1}' format user host in status ret['comment'] 'Alreadyincluster'return retif not __opts__['test'] result __salt__['rabbitmq join_cluster'] host user ...
97
python-test-2878
python
How do the current node join to a cluster ?
with node user@host name irrelevant
def joined name host user 'rabbit' ram node None runas 'root' ret {'name' name 'result' True 'comment' '' 'changes' {}}status salt ['rabbitmq cluster status'] if '{ 0 }@{ 1 }' format user host in status ret['comment'] ' Alreadyincluster'return retif not opts ['test'] result salt ['rabbitmq join cluster'] host user ram ...
def joined name host user 'rabbit' ram_node None runas 'root' ret {'name' name 'result' True 'comment' '' 'changes' {}}status __salt__['rabbitmq cluster_status'] if '{0}@{1}' format user host in status ret['comment'] 'Alreadyincluster'return retif not __opts__['test'] result __salt__['rabbitmq join_cluster'] host user ...
97
python-test-2881
python
What does the code attach to the python root logger ?
a logging handler
def setup logging handler excluded loggers EXCLUDED LOGGER DEFAULTS log level logging INFO all excluded loggers set excluded loggers + EXCLUDED LOGGER DEFAULTS logger logging get Logger logger set Level log level logger add Handler handler logger add Handler logging Stream Handler for logger name in all excluded logger...
def setup_logging handler excluded_loggers EXCLUDED_LOGGER_DEFAULTS log_level logging INFO all_excluded_loggers set excluded_loggers + EXCLUDED_LOGGER_DEFAULTS logger logging getLogger logger setLevel log_level logger addHandler handler logger addHandler logging StreamHandler for logger_name in all_excluded_loggers log...
63
python-test-2882
python
What does the code exclude ?
loggers that this library itself uses to avoid infinite recursion
def setup logging handler excluded loggers EXCLUDED LOGGER DEFAULTS log level logging INFO all excluded loggers set excluded loggers + EXCLUDED LOGGER DEFAULTS logger logging get Logger logger set Level log level logger add Handler handler logger add Handler logging Stream Handler for logger name in all excluded logger...
def setup_logging handler excluded_loggers EXCLUDED_LOGGER_DEFAULTS log_level logging INFO all_excluded_loggers set excluded_loggers + EXCLUDED_LOGGER_DEFAULTS logger logging getLogger logger setLevel log_level logger addHandler handler logger addHandler logging StreamHandler for logger_name in all_excluded_loggers log...
63
python-test-2883
python
What does this library itself use loggers ?
to avoid infinite recursion
def setup logging handler excluded loggers EXCLUDED LOGGER DEFAULTS log level logging INFO all excluded loggers set excluded loggers + EXCLUDED LOGGER DEFAULTS logger logging get Logger logger set Level log level logger add Handler handler logger add Handler logging Stream Handler for logger name in all excluded logger...
def setup_logging handler excluded_loggers EXCLUDED_LOGGER_DEFAULTS log_level logging INFO all_excluded_loggers set excluded_loggers + EXCLUDED_LOGGER_DEFAULTS logger logging getLogger logger setLevel log_level logger addHandler handler logger addHandler logging StreamHandler for logger_name in all_excluded_loggers log...
63
python-test-2884
python
What does this library itself avoid ?
infinite recursion
def setup logging handler excluded loggers EXCLUDED LOGGER DEFAULTS log level logging INFO all excluded loggers set excluded loggers + EXCLUDED LOGGER DEFAULTS logger logging get Logger logger set Level log level logger add Handler handler logger add Handler logging Stream Handler for logger name in all excluded logger...
def setup_logging handler excluded_loggers EXCLUDED_LOGGER_DEFAULTS log_level logging INFO all_excluded_loggers set excluded_loggers + EXCLUDED_LOGGER_DEFAULTS logger logging getLogger logger setLevel log_level logger addHandler handler logger addHandler logging StreamHandler for logger_name in all_excluded_loggers log...
63
python-test-2885
python
What does the code create ?
a one - off transfer from amazon s3 to google cloud storage
def main description project id day month year hours minutes source bucket access key secret access key sink bucket credentials Google Credentials get application default storagetransfer discovery build 'storagetransfer' 'v 1 ' credentials credentials transfer job {'description' description 'status' 'ENABLED' 'project ...
def main description project_id day month year hours minutes source_bucket access_key secret_access_key sink_bucket credentials GoogleCredentials get_application_default storagetransfer discovery build 'storagetransfer' 'v1' credentials credentials transfer_job {'description' description 'status' 'ENABLED' 'projectId' ...
122
python-test-2888
python
For what purpose do part of the trapezoidal rule perform ?
to integrate a function
def difftrap function interval numtraps if numtraps < 0 raise Value Error 'numtrapsmustbe> 0 indifftrap ' elif numtraps 1 return 0 5 * function interval[ 0 ] + function interval[ 1 ] else numtosum numtraps / 2 h float interval[ 1 ] - interval[ 0 ] / numtosum lox interval[ 0 ] + 0 5 * h points lox + h * np arange numtos...
def _difftrap function interval numtraps if numtraps < 0 raise ValueError 'numtrapsmustbe>0indifftrap ' elif numtraps 1 return 0 5 * function interval[0] + function interval[1] else numtosum numtraps / 2 h float interval[1] - interval[0] / numtosum lox interval[0] + 0 5 * h points lox + h * np arange numtosum s np sum ...
74
python-test-2889
python
Where did the dataset shuffle ?
at each iteration
def get minibatches idx n minibatch size shuffle False idx list numpy arange n dtype 'int 32 ' if shuffle numpy random shuffle idx list minibatches []minibatch start 0for i in range n // minibatch size minibatches append idx list[minibatch start minibatch start + minibatch size ] minibatch start + minibatch sizeif mini...
def get_minibatches_idx n minibatch_size shuffle False idx_list numpy arange n dtype 'int32' if shuffle numpy random shuffle idx_list minibatches []minibatch_start 0for i in range n // minibatch_size minibatches append idx_list[minibatch_start minibatch_start + minibatch_size ] minibatch_start + minibatch_sizeif miniba...
67
python-test-2890
python
What did the code use ?
to shuffle the dataset at each iteration
def get minibatches idx n minibatch size shuffle False idx list numpy arange n dtype 'int 32 ' if shuffle numpy random shuffle idx list minibatches []minibatch start 0for i in range n // minibatch size minibatches append idx list[minibatch start minibatch start + minibatch size ] minibatch start + minibatch sizeif mini...
def get_minibatches_idx n minibatch_size shuffle False idx_list numpy arange n dtype 'int32' if shuffle numpy random shuffle idx_list minibatches []minibatch_start 0for i in range n // minibatch_size minibatches append idx_list[minibatch_start minibatch_start + minibatch_size ] minibatch_start + minibatch_sizeif miniba...
67
python-test-2891
python
What is throttling us ?
datapipeline api
def next datetime with utc hour table name utc hour today datetime date today start date time datetime datetime year today year month today month day today day hour utc hour minute get deterministic value for table name table name 60 second get deterministic value for table name table name 60 if start date time < datet...
def _next_datetime_with_utc_hour table_name utc_hour today datetime date today start_date_time datetime datetime year today year month today month day today day hour utc_hour minute _get_deterministic_value_for_table_name table_name 60 second _get_deterministic_value_for_table_name table_name 60 if start_date_time < da...
74
python-test-2893
python
What returns the default value for a dict variable rather than the display value ?
read_user_dict
def test read user dict default value mocker mock prompt mocker patch u'cookiecutter prompt click prompt' autospec True return value u'default' val read user dict u'name' {u'project slug' u'pytest-plugin'} assert mock prompt call args mocker call u'name' type click STRING default u'default' value proc process json asse...
def test_read_user_dict_default_value mocker mock_prompt mocker patch u'cookiecutter prompt click prompt' autospec True return_value u'default' val read_user_dict u'name' {u'project_slug' u'pytest-plugin'} assert mock_prompt call_args mocker call u'name' type click STRING default u'default' value_proc process_json asse...
51
python-test-2894
python
What does read_user_dict return ?
the default value for a dict variable rather than the display value
def test read user dict default value mocker mock prompt mocker patch u'cookiecutter prompt click prompt' autospec True return value u'default' val read user dict u'name' {u'project slug' u'pytest-plugin'} assert mock prompt call args mocker call u'name' type click STRING default u'default' value proc process json asse...
def test_read_user_dict_default_value mocker mock_prompt mocker patch u'cookiecutter prompt click prompt' autospec True return_value u'default' val read_user_dict u'name' {u'project_slug' u'pytest-plugin'} assert mock_prompt call_args mocker call u'name' type click STRING default u'default' value_proc process_json asse...
51
python-test-2895
python
What does the code pick ?
the right stream type based on env and args
def get stream type env args if not env stdout isatty and not args prettify Stream partial Raw Stream chunk size Raw Stream CHUNK SIZE BY LINE if args stream else Raw Stream CHUNK SIZE elif args prettify Stream partial Pretty Stream if args stream else Buffered Pretty Stream env env conversion Conversion formatting For...
def get_stream_type env args if not env stdout_isatty and not args prettify Stream partial RawStream chunk_size RawStream CHUNK_SIZE_BY_LINE if args stream else RawStream CHUNK_SIZE elif args prettify Stream partial PrettyStream if args stream else BufferedPrettyStream env env conversion Conversion formatting Formattin...
77
python-test-2896
python
For what purpose do the table contents return ?
for the given readout and mode
@require GE Tdef wiki rows request readout slug product get product request readout kb readout request readout slug READOUTS locale request GET get 'locale' mode smart int request GET get 'mode' None product product max rows smart int request GET get 'max' fallback None return Http Response readout render max rows max ...
@require_GETdef wiki_rows request readout_slug product _get_product request readout _kb_readout request readout_slug READOUTS locale request GET get 'locale' mode smart_int request GET get 'mode' None product product max_rows smart_int request GET get 'max' fallback None return HttpResponse readout render max_rows max_...
53
python-test-2897
python
How does the code obtain a cert ?
using a user - supplied csr
def csr obtain cert config le client csr typ config actual csr certr chain le client obtain certificate from csr config domains csr typ if config dry run logger debug ' Dryrun skippingsavingcertificateto%s' config cert path else cert path cert fullchain le client save certificate certr chain config cert path config cha...
def _csr_obtain_cert config le_client csr typ config actual_csr certr chain le_client obtain_certificate_from_csr config domains csr typ if config dry_run logger debug 'Dryrun skippingsavingcertificateto%s' config cert_path else cert_path _ cert_fullchain le_client save_certificate certr chain config cert_path config c...
64
python-test-2898
python
What does the code obtain using a user - supplied csr ?
a cert
def csr obtain cert config le client csr typ config actual csr certr chain le client obtain certificate from csr config domains csr typ if config dry run logger debug ' Dryrun skippingsavingcertificateto%s' config cert path else cert path cert fullchain le client save certificate certr chain config cert path config cha...
def _csr_obtain_cert config le_client csr typ config actual_csr certr chain le_client obtain_certificate_from_csr config domains csr typ if config dry_run logger debug 'Dryrun skippingsavingcertificateto%s' config cert_path else cert_path _ cert_fullchain le_client save_certificate certr chain config cert_path config c...
64
python-test-2899
python
Where have this works because we do nt have the privkey differently ?
in the csr case
def csr obtain cert config le client csr typ config actual csr certr chain le client obtain certificate from csr config domains csr typ if config dry run logger debug ' Dryrun skippingsavingcertificateto%s' config cert path else cert path cert fullchain le client save certificate certr chain config cert path config cha...
def _csr_obtain_cert config le_client csr typ config actual_csr certr chain le_client obtain_certificate_from_csr config domains csr typ if config dry_run logger debug 'Dryrun skippingsavingcertificateto%s' config cert_path else cert_path _ cert_fullchain le_client save_certificate certr chain config cert_path config c...
64
python-test-2900
python
Do we have the privkey ?
No
def csr obtain cert config le client csr typ config actual csr certr chain le client obtain certificate from csr config domains csr typ if config dry run logger debug ' Dryrun skippingsavingcertificateto%s' config cert path else cert path cert fullchain le client save certificate certr chain config cert path config cha...
def _csr_obtain_cert config le_client csr typ config actual_csr certr chain le_client obtain_certificate_from_csr config domains csr typ if config dry_run logger debug 'Dryrun skippingsavingcertificateto%s' config cert_path else cert_path _ cert_fullchain le_client save_certificate certr chain config cert_path config c...
64
python-test-2901
python
What do we nt have ?
the privkey
def csr obtain cert config le client csr typ config actual csr certr chain le client obtain certificate from csr config domains csr typ if config dry run logger debug ' Dryrun skippingsavingcertificateto%s' config cert path else cert path cert fullchain le client save certificate certr chain config cert path config cha...
def _csr_obtain_cert config le_client csr typ config actual_csr certr chain le_client obtain_certificate_from_csr config domains csr typ if config dry_run logger debug 'Dryrun skippingsavingcertificateto%s' config cert_path else cert_path _ cert_fullchain le_client save_certificate certr chain config cert_path config c...
64
python-test-2902
python
Why have this works in the csr case differently ?
because we do nt have the privkey
def csr obtain cert config le client csr typ config actual csr certr chain le client obtain certificate from csr config domains csr typ if config dry run logger debug ' Dryrun skippingsavingcertificateto%s' config cert path else cert path cert fullchain le client save certificate certr chain config cert path config cha...
def _csr_obtain_cert config le_client csr typ config actual_csr certr chain le_client obtain_certificate_from_csr config domains csr typ if config dry_run logger debug 'Dryrun skippingsavingcertificateto%s' config cert_path else cert_path _ cert_fullchain le_client save_certificate certr chain config cert_path config c...
64
python-test-2903
python
How have this works because we do nt have the privkey in the csr case ?
differently
def csr obtain cert config le client csr typ config actual csr certr chain le client obtain certificate from csr config domains csr typ if config dry run logger debug ' Dryrun skippingsavingcertificateto%s' config cert path else cert path cert fullchain le client save certificate certr chain config cert path config cha...
def _csr_obtain_cert config le_client csr typ config actual_csr certr chain le_client obtain_certificate_from_csr config domains csr typ if config dry_run logger debug 'Dryrun skippingsavingcertificateto%s' config cert_path else cert_path _ cert_fullchain le_client save_certificate certr chain config cert_path config c...
64
python-test-2904
python
What have works in the csr case ?
this
def csr obtain cert config le client csr typ config actual csr certr chain le client obtain certificate from csr config domains csr typ if config dry run logger debug ' Dryrun skippingsavingcertificateto%s' config cert path else cert path cert fullchain le client save certificate certr chain config cert path config cha...
def _csr_obtain_cert config le_client csr typ config actual_csr certr chain le_client obtain_certificate_from_csr config domains csr typ if config dry_run logger debug 'Dryrun skippingsavingcertificateto%s' config cert_path else cert_path _ cert_fullchain le_client save_certificate certr chain config cert_path config c...
64
python-test-2906
python
What matches the payload version ?
the given exploration version
def require valid version version from payload exploration version if version from payload is None raise base Base Handler Invalid Input Exception ' Invalid POS Trequest aversionmustbespecified ' if version from payload exploration version raise base Base Handler Invalid Input Exception ' Tryingtoupdateversion%sofexplo...
def _require_valid_version version_from_payload exploration_version if version_from_payload is None raise base BaseHandler InvalidInputException 'InvalidPOSTrequest aversionmustbespecified ' if version_from_payload exploration_version raise base BaseHandler InvalidInputException 'Tryingtoupdateversion%sofexplorationfro...
52
python-test-2910
python
What does the code get ?
a free ip range
def get free range parent range excluded ranges size PRIMARY VIP RANGE SIZE free cidrs netaddr IP Set [parent range] - netaddr IP Set excluded ranges for cidr in free cidrs iter cidrs if cidr prefixlen < size return '%s/%s' % cidr network size raise Value Error ' Networkofsize% size s from I Prange% parent range sexclu...
def get_free_range parent_range excluded_ranges size PRIMARY_VIP_RANGE_SIZE free_cidrs netaddr IPSet [parent_range] - netaddr IPSet excluded_ranges for cidr in free_cidrs iter_cidrs if cidr prefixlen < size return '%s/%s' % cidr network size raise ValueError _ 'Networkofsize% size s fromIPrange% parent_range sexcluding...
74
python-test-2911
python
What does the code update ?
the bound with likelihood terms
def bound state log lik X initial bound precs means covariance type n components n features means shapen samples X shape[ 0 ]bound np empty n samples n components bound[ ] initial boundif covariance type in ['diag' 'spherical'] for k in range n components d X - means[k] bound[ k] - 0 5 * np sum d * d * precs[k] axis 1 ...
def _bound_state_log_lik X initial_bound precs means covariance_type n_components n_features means shapen_samples X shape[0]bound np empty n_samples n_components bound[ ] initial_boundif covariance_type in ['diag' 'spherical'] for k in range n_components d X - means[k] bound[ k] - 0 5 * np sum d * d * precs[k] axis 1 e...
109
python-test-2912
python
What does the code build ?
an ill - posed linear regression problem with many noisy features and comparatively few samples
def build dataset n samples 50 n features 200 n informative features 10 n targets 1 random state np random Random State 0 if n targets > 1 w random state randn n features n targets else w random state randn n features w[n informative features ] 0 0X random state randn n samples n features y np dot X w X test random sta...
def build_dataset n_samples 50 n_features 200 n_informative_features 10 n_targets 1 random_state np random RandomState 0 if n_targets > 1 w random_state randn n_features n_targets else w random_state randn n_features w[n_informative_features ] 0 0X random_state randn n_samples n_features y np dot X w X_test random_stat...
84
python-test-2913
python
How did linear regression problem pose ?
ill
def build dataset n samples 50 n features 200 n informative features 10 n targets 1 random state np random Random State 0 if n targets > 1 w random state randn n features n targets else w random state randn n features w[n informative features ] 0 0X random state randn n samples n features y np dot X w X test random sta...
def build_dataset n_samples 50 n_features 200 n_informative_features 10 n_targets 1 random_state np random RandomState 0 if n_targets > 1 w random_state randn n_features n_targets else w random_state randn n_features w[n_informative_features ] 0 0X random_state randn n_samples n_features y np dot X w X_test random_stat...
84
python-test-2914
python
What does the code compute ?
the sokal - michener dissimilarity between two boolean 1-d arrays
def sokalmichener u v u validate vector u v validate vector v if u dtype bool ntt u & v sum nff ~ u & ~ v sum else ntt u * v sum nff 1 0 - u * 1 0 - v sum nft ntf nbool correspond ft tf u v return float 2 0 * ntf + nft / float ntt + nff + 2 0 * ntf + nft
def sokalmichener u v u _validate_vector u v _validate_vector v if u dtype bool ntt u & v sum nff ~ u & ~ v sum else ntt u * v sum nff 1 0 - u * 1 0 - v sum nft ntf _nbool_correspond_ft_tf u v return float 2 0 * ntf + nft / float ntt + nff + 2 0 * ntf + nft
73
python-test-2917
python
How do labels and inertia compute ?
using a full distance matrix
def labels inertia precompute dense X x squared norms centers distances n samples X shape[ 0 ] labels mindist pairwise distances argmin min X X Y centers metric 'euclidean' metric kwargs {'squared' True} labels labels astype np int 32 if n samples distances shape[ 0 ] distances[ ] mindistinertia mindist sum return labe...
def _labels_inertia_precompute_dense X x_squared_norms centers distances n_samples X shape[0] labels mindist pairwise_distances_argmin_min X X Y centers metric 'euclidean' metric_kwargs {'squared' True} labels labels astype np int32 if n_samples distances shape[0] distances[ ] mindistinertia mindist sum return labels i...
54
python-test-2918
python
How does the code perform the oauth dance ?
with some command - line prompts
def oauth dance app name consumer key consumer secret token filename None open browser True print " Hithere We'regonnagetyouallsetuptouse%s " % app name twitter Twitter auth O Auth '' '' consumer key consumer secret format '' api version None oauth token oauth token secret parse oauth tokens twitter oauth request token...
def oauth_dance app_name consumer_key consumer_secret token_filename None open_browser True print "Hithere We'regonnagetyouallsetuptouse%s " % app_name twitter Twitter auth OAuth '' '' consumer_key consumer_secret format '' api_version None oauth_token oauth_token_secret parse_oauth_tokens twitter oauth request_token o...
137
python-test-2919
python
What does the code perform with some command - line prompts ?
the oauth dance
def oauth dance app name consumer key consumer secret token filename None open browser True print " Hithere We'regonnagetyouallsetuptouse%s " % app name twitter Twitter auth O Auth '' '' consumer key consumer secret format '' api version None oauth token oauth token secret parse oauth tokens twitter oauth request token...
def oauth_dance app_name consumer_key consumer_secret token_filename None open_browser True print "Hithere We'regonnagetyouallsetuptouse%s " % app_name twitter Twitter auth OAuth '' '' consumer_key consumer_secret format '' api_version None oauth_token oauth_token_secret parse_oauth_tokens twitter oauth request_token o...
137
python-test-2922
python
What does the code create ?
a parser for command line options
def get default parser usage '%prog[options]<start stop status>' parser Option Parser usage usage parser add option '--debug' action 'store true' help ' Runintheforeground logtostdout' parser add option '--syslog' action 'store true' help ' Writelogstosyslog' parser add option '--nodaemon' action 'store true' help ' Ru...
def get_default_parser usage '%prog[options]<start stop status>' parser OptionParser usage usage parser add_option '--debug' action 'store_true' help 'Runintheforeground logtostdout' parser add_option '--syslog' action 'store_true' help 'Writelogstosyslog' parser add_option '--nodaemon' action 'store_true' help 'Runint...
123
python-test-2925
python
Where does the code remove a cluster ?
on a postgres server
def cluster remove version name 'main' stop False cmd [salt utils which 'pg dropcluster' ]if stop cmd + ['--stop']cmd + [version name]cmdstr '' join [pipes quote c for c in cmd] ret salt ['cmd run all'] cmdstr python shell False if ret get 'retcode' 0 0 log error ' Errorremovinga Postgresqlcluster{ 0 }/{ 1 }' format ve...
def cluster_remove version name 'main' stop False cmd [salt utils which 'pg_dropcluster' ]if stop cmd + ['--stop']cmd + [version name]cmdstr '' join [pipes quote c for c in cmd] ret __salt__['cmd run_all'] cmdstr python_shell False if ret get 'retcode' 0 0 log error 'ErrorremovingaPostgresqlcluster{0}/{1}' format versi...
71
python-test-2926
python
What is using local directories for the extra_dirs ?
non - local plugin decorator
def local extra dirs func def wraps self *args **kwargs if kwargs get 'base dir' None is None return func self *args **kwargs else for c in self class mro if c name ' Disk Object Store' return getattr c func name self *args **kwargs raise Exception " Couldnotcall Disk Object Store's%smethod doesyour Object Storeplugini...
def local_extra_dirs func def wraps self *args **kwargs if kwargs get 'base_dir' None is None return func self *args **kwargs else for c in self __class__ __mro__ if c __name__ 'DiskObjectStore' return getattr c func __name__ self *args **kwargs raise Exception "CouldnotcallDiskObjectStore's%smethod doesyourObjectStore...
63
python-test-2927
python
What do non - local plugin decorator use ?
local directories for the extra_dirs
def local extra dirs func def wraps self *args **kwargs if kwargs get 'base dir' None is None return func self *args **kwargs else for c in self class mro if c name ' Disk Object Store' return getattr c func name self *args **kwargs raise Exception " Couldnotcall Disk Object Store's%smethod doesyour Object Storeplugini...
def local_extra_dirs func def wraps self *args **kwargs if kwargs get 'base_dir' None is None return func self *args **kwargs else for c in self __class__ __mro__ if c __name__ 'DiskObjectStore' return getattr c func __name__ self *args **kwargs raise Exception "CouldnotcallDiskObjectStore's%smethod doesyourObjectStore...
63
python-test-2928
python
What does the code find ?
destinations for resources files
def get resources dests resources root rules def get rel path base path base base replace os path sep '/' path path replace os path sep '/' assert path startswith base return path[len base ] lstrip '/' destinations {}for base suffix dest in rules prefix os path join resources root base for abs base in iglob prefix abs ...
def get_resources_dests resources_root rules def get_rel_path base path base base replace os path sep '/' path path replace os path sep '/' assert path startswith base return path[len base ] lstrip '/' destinations {}for base suffix dest in rules prefix os path join resources_root base for abs_base in iglob prefix abs_...
121
python-test-2931
python
How does salt not handle unicode strings ?
internally
def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc
def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc
54
python-test-2932
python
How do to convert any unicode text into ascii without stack tracing since salt internally does not handle unicode strings try ?
its best
def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc
def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc
54
python-test-2933
python
What does salt not handle internally ?
unicode strings
def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc
def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc
54
python-test-2934
python
How do any unicode text convert into ascii since salt internally does not handle unicode strings ?
without stack tracing
def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc
def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc
54
python-test-2935
python
Does salt handle unicode strings internally ?
No
def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc
def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc
54
python-test-2936
python
Is this method supposed to be used directly helper method ?
No
def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc
def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc
54
python-test-2937
python
How be this method used ?
directly
def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc
def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc
54
python-test-2938
python
What does not handle unicode strings internally ?
salt
def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc
def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc
54
python-test-2939
python
Why do any unicode text convert into ascii without stack tracing ?
since salt internally does not handle unicode strings
def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc
def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc
54