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-3170 | python | Where do jndi bind ? | in the running jboss instance jboss_config configuration dictionary with properties specified above | def create simple binding jboss config binding name value profile None log debug ' MODULEFUNCTION jboss 7 create simple binding binding name %s value %s profile %s' binding name value profile operation '/subsystem naming/binding "{binding name}" add binding-type simple value "{value}" ' format binding name binding name... | def create_simple_binding jboss_config binding_name value profile None log debug ' MODULEFUNCTION jboss7 create_simple_binding binding_name %s value %s profile %s' binding_name value profile operation '/subsystem naming/binding "{binding_name}" add binding-type simple value "{value}" ' format binding_name binding_name ... | 75 |
python-test-3171 | python | What is binding in the running jboss instance jboss_config configuration dictionary with properties specified above ? | jndi | def create simple binding jboss config binding name value profile None log debug ' MODULEFUNCTION jboss 7 create simple binding binding name %s value %s profile %s' binding name value profile operation '/subsystem naming/binding "{binding name}" add binding-type simple value "{value}" ' format binding name binding name... | def create_simple_binding jboss_config binding_name value profile None log debug ' MODULEFUNCTION jboss7 create_simple_binding binding_name %s value %s profile %s' binding_name value profile operation '/subsystem naming/binding "{binding_name}" add binding-type simple value "{value}" ' format binding_name binding_name ... | 75 |
python-test-3188 | python | When do message log ? | only once using given logger | @with sessiondef log once message logger logging get Logger u'log once' once level logging INFO suppressed level f logger VERBOSE session None from flexget manager import managerif not manager log warning u'D Bnotinitialized log oncewillnotworkproperly ' logger log once level message returndigest hashlib md 5 digest up... | @with_sessiondef log_once message logger logging getLogger u'log_once' once_level logging INFO suppressed_level f_logger VERBOSE session None from flexget manager import managerif not manager log warning u'DBnotinitialized log_oncewillnotworkproperly ' logger log once_level message returndigest hashlib md5 digest updat... | 94 |
python-test-3190 | python | What do the user want ? | the system to show | def get language from request request check path False if check path lang code get language from path request path info if lang code is not None return lang codesupported lang codes get languages if hasattr request 'session' lang code request session get LANGUAGE SESSION KEY if lang code in supported lang codes and lan... | def get_language_from_request request check_path False if check_path lang_code get_language_from_path request path_info if lang_code is not None return lang_codesupported_lang_codes get_languages if hasattr request 'session' lang_code request session get LANGUAGE_SESSION_KEY if lang_code in supported_lang_codes and lan... | 144 |
python-test-3191 | python | For what purpose does the code analyze the request ? | to find what language the user wants the system to show | def get language from request request check path False if check path lang code get language from path request path info if lang code is not None return lang codesupported lang codes get languages if hasattr request 'session' lang code request session get LANGUAGE SESSION KEY if lang code in supported lang codes and lan... | def get_language_from_request request check_path False if check_path lang_code get_language_from_path request path_info if lang_code is not None return lang_codesupported_lang_codes get_languages if hasattr request 'session' lang_code request session get LANGUAGE_SESSION_KEY if lang_code in supported_lang_codes and lan... | 144 |
python-test-3192 | python | What does the code approximate ? | the jacobian matrix of a callable function | def approx jacobian x func epsilon *args x0 asfarray x f0 atleast 1d func * x0 + args jac zeros [len x0 len f0 ] dx zeros len x0 for i in range len x0 dx[i] epsilonjac[i] func * x0 + dx + args - f0 / epsilon dx[i] 0 0return jac transpose | def approx_jacobian x func epsilon *args x0 asfarray x f0 atleast_1d func * x0 + args jac zeros [len x0 len f0 ] dx zeros len x0 for i in range len x0 dx[i] epsilonjac[i] func * x0 + dx + args - f0 / epsilon dx[i] 0 0return jac transpose | 53 |
python-test-3193 | python | When will this function be called from another process ? | when building the providers map | def run parallel map providers query data queue None reinit crypto cloud Cloud data['opts'] try with context func globals inject cloud clouds[data['fun']] active provider name ' ' join [data['alias'] data['driver']] return data['alias'] data['driver'] salt utils simple types filter cloud clouds[data['fun']] except Exce... | def run_parallel_map_providers_query data queue None reinit_crypto cloud Cloud data['opts'] try with context func_globals_inject cloud clouds[data['fun']] __active_provider_name__ ' ' join [data['alias'] data['driver']] return data['alias'] data['driver'] salt utils simple_types_filter cloud clouds[data['fun']] except ... | 65 |
python-test-3194 | python | How do a list of arguments process ? | using quotecmdexeargument | def Encode Rsp File List args if not args return ''if args[ 0 ] startswith 'call' call program args[ 0 ] split '' 1 program call + '' + os path normpath program else program os path normpath args[ 0 ] return program + '' + '' join Quote For Rsp File arg for arg in args[ 1 ] | def EncodeRspFileList args if not args return ''if args[0] startswith 'call' call program args[0] split '' 1 program call + '' + os path normpath program else program os path normpath args[0] return program + '' + '' join QuoteForRspFile arg for arg in args[1 ] | 59 |
python-test-3202 | python | What does the code create ? | a process for it | def spawn collector col LOG info '%s interval %d needstobespawned' col name col interval try col proc subprocess Popen col filename stdout subprocess PIPE stderr subprocess PIPE close fds True preexec fn os setsid except OS Error as e LOG error ' Failedtospawncollector%s %s' % col filename e returncol lastspawn int tim... | def spawn_collector col LOG info '%s interval %d needstobespawned' col name col interval try col proc subprocess Popen col filename stdout subprocess PIPE stderr subprocess PIPE close_fds True preexec_fn os setsid except OSError as e LOG error 'Failedtospawncollector%s %s' % col filename e returncol lastspawn int time ... | 96 |
python-test-3203 | python | What does the code take ? | a collector object | def spawn collector col LOG info '%s interval %d needstobespawned' col name col interval try col proc subprocess Popen col filename stdout subprocess PIPE stderr subprocess PIPE close fds True preexec fn os setsid except OS Error as e LOG error ' Failedtospawncollector%s %s' % col filename e returncol lastspawn int tim... | def spawn_collector col LOG info '%s interval %d needstobespawned' col name col interval try col proc subprocess Popen col filename stdout subprocess PIPE stderr subprocess PIPE close_fds True preexec_fn os setsid except OSError as e LOG error 'Failedtospawncollector%s %s' % col filename e returncol lastspawn int time ... | 96 |
python-test-3206 | python | What does the code create in an organisation ? | a new datasource | def create datasource orgname None profile 'grafana' **kwargs if isinstance profile string types profile salt ['config option'] profile if orgname switch org orgname profile response requests post '{ 0 }/api/datasources' format profile['grafana url'] json kwargs auth get auth profile headers get headers profile timeout... | def create_datasource orgname None profile 'grafana' **kwargs if isinstance profile string_types profile __salt__['config option'] profile if orgname switch_org orgname profile response requests post '{0}/api/datasources' format profile['grafana_url'] json kwargs auth _get_auth profile headers _get_headers profile time... | 62 |
python-test-3207 | python | What does the code retrieve ? | the given thread | def get thread and context request thread id retrieve kwargs None retrieve kwargs retrieve kwargs or {} try if 'with responses' not in retrieve kwargs retrieve kwargs['with responses'] Falseif 'mark as read' not in retrieve kwargs retrieve kwargs['mark as read'] Falsecc thread Thread id thread id retrieve **retrieve kw... | def _get_thread_and_context request thread_id retrieve_kwargs None retrieve_kwargs retrieve_kwargs or {} try if 'with_responses' not in retrieve_kwargs retrieve_kwargs['with_responses'] Falseif 'mark_as_read' not in retrieve_kwargs retrieve_kwargs['mark_as_read'] Falsecc_thread Thread id thread_id retrieve **retrieve_k... | 136 |
python-test-3208 | python | How do shallow commits find ? | according to a given depth | def find shallow store heads depth parents {}def get parents sha result parents get sha None if not result result store[sha] parentsparents[sha] resultreturn resulttodo []for head sha in heads obj store peel sha head sha if isinstance obj Commit todo append obj id 1 not shallow set shallow set while todo sha cur depth ... | def _find_shallow store heads depth parents {}def get_parents sha result parents get sha None if not result result store[sha] parentsparents[sha] resultreturn resulttodo []for head_sha in heads obj store peel_sha head_sha if isinstance obj Commit todo append obj id 1 not_shallow set shallow set while todo sha cur_depth... | 90 |
python-test-3210 | python | What does the code walk ? | the new directories list | def adjust recursive directory permissions pre existing dir new directory list module directory args changed if len new directory list > 0 working dir os path join pre existing dir new directory list pop 0 directory args['path'] working dirchanged module set fs attributes if different directory args changed changed adj... | def adjust_recursive_directory_permissions pre_existing_dir new_directory_list module directory_args changed if len new_directory_list > 0 working_dir os path join pre_existing_dir new_directory_list pop 0 directory_args['path'] working_dirchanged module set_fs_attributes_if_different directory_args changed changed adj... | 64 |
python-test-3211 | python | What did trimpoints set for all sff files in directory ? | to end of technical read | def set sff trimpoints sff dir technical lengths for lib id sff fp in get per lib sff fps sff dir try readlength technical lengths[lib id]except Key Error continuesff data parse binary sff open sff fp True clipped header clipped reads set clip qual left sff data readlength fd temp fp mkstemp dir sff dir close fd with o... | def set_sff_trimpoints sff_dir technical_lengths for lib_id sff_fp in get_per_lib_sff_fps sff_dir try readlength technical_lengths[lib_id]except KeyError continuesff_data parse_binary_sff open sff_fp True clipped_header clipped_reads set_clip_qual_left sff_data readlength fd temp_fp mkstemp dir sff_dir close fd with op... | 77 |
python-test-3212 | python | What set to end of technical read for all sff files in directory ? | trimpoints | def set sff trimpoints sff dir technical lengths for lib id sff fp in get per lib sff fps sff dir try readlength technical lengths[lib id]except Key Error continuesff data parse binary sff open sff fp True clipped header clipped reads set clip qual left sff data readlength fd temp fp mkstemp dir sff dir close fd with o... | def set_sff_trimpoints sff_dir technical_lengths for lib_id sff_fp in get_per_lib_sff_fps sff_dir try readlength technical_lengths[lib_id]except KeyError continuesff_data parse_binary_sff open sff_fp True clipped_header clipped_reads set_clip_qual_left sff_data readlength fd temp_fp mkstemp dir sff_dir close fd with op... | 77 |
python-test-3213 | python | What are found in task_cls ? | all the values in task_instance | def common params task instance task cls if not isinstance task cls task Register raise Type Error 'task clsmustbeanuninstantiated Task' task instance param names dict task instance get params keys task cls params dict dict task cls get params task cls param names task cls params dict keys common param names set task i... | def common_params task_instance task_cls if not isinstance task_cls task Register raise TypeError 'task_clsmustbeanuninstantiatedTask' task_instance_param_names dict task_instance get_params keys task_cls_params_dict dict task_cls get_params task_cls_param_names task_cls_params_dict keys common_param_names set task_ins... | 105 |
python-test-3214 | python | Where are all the values in task_instance found ? | in task_cls | def common params task instance task cls if not isinstance task cls task Register raise Type Error 'task clsmustbeanuninstantiated Task' task instance param names dict task instance get params keys task cls params dict dict task cls get params task cls param names task cls params dict keys common param names set task i... | def common_params task_instance task_cls if not isinstance task_cls task Register raise TypeError 'task_clsmustbeanuninstantiatedTask' task_instance_param_names dict task_instance get_params keys task_cls_params_dict dict task_cls get_params task_cls_param_names task_cls_params_dict keys common_param_names set task_ins... | 105 |
python-test-3215 | python | In which direction does the code walk the python tree ? | from method meth | def get Python Containers meth containers []containers append meth im class module Name meth im class module while module Name is not None module sys modules get module Name None if module is None module import module Name containers append module module Name getattr module ' module ' None return containers | def getPythonContainers meth containers []containers append meth im_class moduleName meth im_class __module__while moduleName is not None module sys modules get moduleName None if module is None module __import__ moduleName containers append module moduleName getattr module '__module__' None return containers | 51 |
python-test-3219 | python | What does the code execute ? | the basic regression on order stat proceedure | def impute df observations censorship transform in transform out uncensored mask df[censorship] False censored mask df[censorship] True fit params stats linregress df[' Zprelim'][uncensored mask] transform in df[observations][uncensored mask] slope intercept fit params[ 2]df loc[ 'estimated'] transform out slope * df['... | def _impute df observations censorship transform_in transform_out uncensored_mask df[censorship] False censored_mask df[censorship] True fit_params stats linregress df['Zprelim'][uncensored_mask] transform_in df[observations][uncensored_mask] slope intercept fit_params[ 2]df loc[ 'estimated'] transform_out slope * df['... | 54 |
python-test-3222 | python | What does the code compute ? | the squarefree factorization of the denominator of f and for each di the polynomial h in k[x ] | def recognize derivative a d DE z None flag True a d a cancel d include True q r a div d Np Sp splitfactor sqf d DE coefficient D True z z j 1for s i in Sp delta a delta d H laurent series r d s j DE g gcd d H[ -1 ] as poly if g is not d flag Falsebreakj j + 1 return flag | def recognize_derivative a d DE z None flag True a d a cancel d include True q r a div d Np Sp splitfactor_sqf d DE coefficientD True z z j 1for s i in Sp delta_a delta_d H laurent_series r d s j DE g gcd d H[ -1 ] as_poly if g is not d flag Falsebreakj j + 1 return flag | 71 |
python-test-3225 | python | What does the code remove from config vars ? | any unsupported archs | def remove unsupported archs config vars if 'CC' in os environ return config varsif re search '-arch\\s+ppc' config vars['CFLAGS'] is not None status os system "echo'intmain{} ' '%s'-c-archppc-xc-o/dev/null/dev/null 2 >/dev/null" % config vars['CC'] replace "'" '\'"\'"\'' if status for cv in UNIVERSAL CONFIG VARS if cv... | def _remove_unsupported_archs _config_vars if 'CC' in os environ return _config_varsif re search '-arch\\s+ppc' _config_vars['CFLAGS'] is not None status os system "echo'intmain{} ' '%s'-c-archppc-xc-o/dev/null/dev/null2>/dev/null" % _config_vars['CC'] replace "'" '\'"\'"\'' if status for cv in _UNIVERSAL_CONFIG_VARS i... | 73 |
python-test-3233 | python | What does the code get ? | versions of optional modules | def module versions lines []modules collections Ordered Dict [ 'sip' ['SIP VERSION STR'] 'colorama' ['VERSION' ' version '] 'pypeg 2 ' [' version '] 'jinja 2 ' [' version '] 'pygments' [' version '] 'yaml' [' version '] 'cssutils' [' version '] 'typing' [] ' Py Qt 5 Qt Web Engine Widgets' [] ] for name attributes in mo... | def _module_versions lines []modules collections OrderedDict [ 'sip' ['SIP_VERSION_STR'] 'colorama' ['VERSION' '__version__'] 'pypeg2' ['__version__'] 'jinja2' ['__version__'] 'pygments' ['__version__'] 'yaml' ['__version__'] 'cssutils' ['__version__'] 'typing' [] 'PyQt5 QtWebEngineWidgets' [] ] for name attributes in ... | 103 |
python-test-3236 | python | What does the code run ? | a dscl -create command | def dscl cmd ctype 'create' if grains ['osrelease info'] < 10 8 source noderoot ' ' '' else source noderoot 'localhost' '/ Local/ Default' if noderoot cmd[ 0 ] noderoot + cmd[ 0 ] return salt ['cmd run all'] ['dscl' source '-' + ctype ] + cmd output loglevel 'quiet' if ctype 'passwd' else 'debug' python shell False | def _dscl cmd ctype 'create' if __grains__['osrelease_info'] < 10 8 source noderoot ' ' '' else source noderoot 'localhost' '/Local/Default' if noderoot cmd[0] noderoot + cmd[0] return __salt__['cmd run_all'] ['dscl' source '-' + ctype ] + cmd output_loglevel 'quiet' if ctype 'passwd' else 'debug' python_shell False | 58 |
python-test-3247 | python | When do a modeljob return ? | when requested | @blueprint route '/<job id> json' methods ['GET'] @blueprint route '/<job id>' methods ['GET'] def show job id job scheduler get job job id if job is None raise werkzeug exceptions Not Found ' Jobnotfound' related jobs scheduler get related jobs job if request wants json return flask jsonify job json dict True elif isi... | @blueprint route '/<job_id> json' methods ['GET'] @blueprint route '/<job_id>' methods ['GET'] def show job_id job scheduler get_job job_id if job is None raise werkzeug exceptions NotFound 'Jobnotfound' related_jobs scheduler get_related_jobs job if request_wants_json return flask jsonify job json_dict True elif isins... | 100 |
python-test-3249 | python | What does the code add to app in the correct order ? | callback handlers | def attach handlers app settings if settings USE POSTGRES add handlers app django handlers handlers else add handlers app mongo handlers handlers add handlers app celery task handlers handlers add handlers app transaction handlers handlers add handlers app postcommit handlers handlers add handlers app {'before request'... | def attach_handlers app settings if settings USE_POSTGRES add_handlers app django_handlers handlers else add_handlers app mongo_handlers handlers add_handlers app celery_task_handlers handlers add_handlers app transaction_handlers handlers add_handlers app postcommit_handlers handlers add_handlers app {'before_request'... | 68 |
python-test-3253 | python | For what purpose does the code execute the rpc call ? | to get a list of public certificates | def make get public certificates call rpc request app identity service pb Get Public Certificate For App Request response app identity service pb Get Public Certificate For App Response def get certs result rpc ' Checksuccess handleexceptions andreturnconverted RP Cresult \n\n Thismethodwaitsforthe RP Cifithasnotyetfin... | def make_get_public_certificates_call rpc request app_identity_service_pb GetPublicCertificateForAppRequest response app_identity_service_pb GetPublicCertificateForAppResponse def get_certs_result rpc 'Checksuccess handleexceptions andreturnconvertedRPCresult \n\nThismethodwaitsfortheRPCifithasnotyetfinished andcallsth... | 128 |
python-test-3259 | python | How does a decorator facilitate authentication ? | per method | def authenticate func c expose request False if not python callable func raise Type Error 'funcmustbecallable' if not python callable c raise Type Error ' Authenticatormustbecallable' attr funcif isinstance func types Unbound Method Type attr func im funcif expose request is True c globals ['expose request'] c setattr ... | def authenticate func c expose_request False if not python callable func raise TypeError 'funcmustbecallable' if not python callable c raise TypeError 'Authenticatormustbecallable' attr funcif isinstance func types UnboundMethodType attr func im_funcif expose_request is True c globals ['expose_request'] c setattr attr ... | 55 |
python-test-3260 | python | What installs in the jinja2 ? | gettext translations | def install templates translations generator if 'JINJA ENVIRONMENT' in generator settings jinja extensions generator settings['JINJA ENVIRONMENT'] get 'extensions' [] else jinja extensions generator settings['JINJA EXTENSIONS']if 'jinja 2 ext i18 n' in jinja extensions domain generator settings get 'I 18 N GETTEXT DOMA... | def install_templates_translations generator if 'JINJA_ENVIRONMENT' in generator settings jinja_extensions generator settings['JINJA_ENVIRONMENT'] get 'extensions' [] else jinja_extensions generator settings['JINJA_EXTENSIONS']if 'jinja2 ext i18n' in jinja_extensions domain generator settings get 'I18N_GETTEXT_DOMAIN' ... | 134 |
python-test-3261 | python | Where do gettext translations install ? | in the jinja2 | def install templates translations generator if 'JINJA ENVIRONMENT' in generator settings jinja extensions generator settings['JINJA ENVIRONMENT'] get 'extensions' [] else jinja extensions generator settings['JINJA EXTENSIONS']if 'jinja 2 ext i18 n' in jinja extensions domain generator settings get 'I 18 N GETTEXT DOMA... | def install_templates_translations generator if 'JINJA_ENVIRONMENT' in generator settings jinja_extensions generator settings['JINJA_ENVIRONMENT'] get 'extensions' [] else jinja_extensions generator settings['JINJA_EXTENSIONS']if 'jinja2 ext i18n' in jinja_extensions domain generator settings get 'I18N_GETTEXT_DOMAIN' ... | 134 |
python-test-3262 | python | What does the code generate ? | a sparse symmetric definite positive matrix | def make sparse spd matrix dim 1 alpha 0 95 norm diag False smallest coef 0 1 largest coef 0 9 random state None random state check random state random state chol - np eye dim aux random state rand dim dim aux[ aux < alpha ] 0aux[ aux > alpha ] smallest coef + largest coef - smallest coef * random state rand np sum aux... | def make_sparse_spd_matrix dim 1 alpha 0 95 norm_diag False smallest_coef 0 1 largest_coef 0 9 random_state None random_state check_random_state random_state chol - np eye dim aux random_state rand dim dim aux[ aux < alpha ] 0aux[ aux > alpha ] smallest_coef + largest_coef - smallest_coef * random_state rand np sum aux... | 117 |
python-test-3263 | python | Where do the modules output calculate ? | on dataset | def test On Sequence Data module dataset target dataset get Field 'target' output Module Validator calculate Module Output module dataset ends Sequence Helper get Sequence Ends dataset summed output zeros dataset outdim class output []class target []for j in range len output summed output + output[j]if j in ends class ... | def testOnSequenceData module dataset target dataset getField 'target' output ModuleValidator calculateModuleOutput module dataset ends SequenceHelper getSequenceEnds dataset summed_output zeros dataset outdim class_output []class_target []for j in range len output summed_output + output[j]if j in ends class_output app... | 83 |
python-test-3264 | python | What calculates on dataset ? | the modules output | def test On Sequence Data module dataset target dataset get Field 'target' output Module Validator calculate Module Output module dataset ends Sequence Helper get Sequence Ends dataset summed output zeros dataset outdim class output []class target []for j in range len output summed output + output[j]if j in ends class ... | def testOnSequenceData module dataset target dataset getField 'target' output ModuleValidator calculateModuleOutput module dataset ends SequenceHelper getSequenceEnds dataset summed_output zeros dataset outdim class_output []class_target []for j in range len output summed_output + output[j]if j in ends class_output app... | 83 |
python-test-3265 | python | For what purpose do fs resize ? | to match the size specified by instance_types | def auto configure disk session vdi ref new gb with vdi attached here session vdi ref read only False as dev partitions get partitions dev if len partitions 1 return num start old sectors ptype partitions[ 0 ]if ptype in 'ext 3 ' 'ext 4 ' new sectors new gb * 1024 * 1024 * 1024 / SECTOR SIZE resize part and fs dev star... | def auto_configure_disk session vdi_ref new_gb with vdi_attached_here session vdi_ref read_only False as dev partitions _get_partitions dev if len partitions 1 return _num start old_sectors ptype partitions[0]if ptype in 'ext3' 'ext4' new_sectors new_gb * 1024 * 1024 * 1024 / SECTOR_SIZE _resize_part_and_fs dev start o... | 69 |
python-test-3267 | python | What does the code get according to the compare function ? | the loops in the order of area | def get Loops In Order Of Area compare Area Function loops loop Areas []for loop in loops loop Area Loop Area loop loop Areas append loop Area loop Areas sort compare Area Function loops In Descending Order Of Area []for loop Area in loop Areas loops In Descending Order Of Area append loop Area loop return loops In Des... | def getLoopsInOrderOfArea compareAreaFunction loops loopAreas []for loop in loops loopArea LoopArea loop loopAreas append loopArea loopAreas sort compareAreaFunction loopsInDescendingOrderOfArea []for loopArea in loopAreas loopsInDescendingOrderOfArea append loopArea loop return loopsInDescendingOrderOfArea | 62 |
python-test-3274 | python | For what purpose does the code get html string ? | to show current stock information for product | def get stock information html supplier product stock Stock Count objects filter product product supplier supplier first context {'div id' get stock information div id supplier product 'sales decimals' product sales unit decimals if product sales unit else 0 'sales unit' product sales unit short name if product sales u... | def get_stock_information_html supplier product stock StockCount objects filter product product supplier supplier first context {'div_id' get_stock_information_div_id supplier product 'sales_decimals' product sales_unit decimals if product sales_unit else 0 'sales_unit' product sales_unit short_name if product sales_un... | 71 |
python-test-3275 | python | What does the code show ? | current stock information for product | def get stock information html supplier product stock Stock Count objects filter product product supplier supplier first context {'div id' get stock information div id supplier product 'sales decimals' product sales unit decimals if product sales unit else 0 'sales unit' product sales unit short name if product sales u... | def get_stock_information_html supplier product stock StockCount objects filter product product supplier supplier first context {'div_id' get_stock_information_div_id supplier product 'sales_decimals' product sales_unit decimals if product sales_unit else 0 'sales_unit' product sales_unit short_name if product sales_un... | 71 |
python-test-3276 | python | What does the code get to show current stock information for product ? | html string | def get stock information html supplier product stock Stock Count objects filter product product supplier supplier first context {'div id' get stock information div id supplier product 'sales decimals' product sales unit decimals if product sales unit else 0 'sales unit' product sales unit short name if product sales u... | def get_stock_information_html supplier product stock StockCount objects filter product product supplier supplier first context {'div_id' get_stock_information_div_id supplier product 'sales_decimals' product sales_unit decimals if product sales_unit else 0 'sales_unit' product sales_unit short_name if product sales_un... | 71 |
python-test-3282 | python | How is this supported only ? | with windows vista | def symlink src link if sys getwindowsversion major < 6 raise Salt Invocation Error ' Symlinksareonlysupportedon Windows Vistaorlater ' if not os path exists src raise Salt Invocation Error ' Thegivensourcepathdoesnotexist ' if not os path isabs src raise Salt Invocation Error ' Filepathmustbeabsolute ' src os path nor... | def symlink src link if sys getwindowsversion major < 6 raise SaltInvocationError 'SymlinksareonlysupportedonWindowsVistaorlater ' if not os path exists src raise SaltInvocationError 'Thegivensourcepathdoesnotexist ' if not os path isabs src raise SaltInvocationError 'Filepathmustbeabsolute ' src os path normpath src l... | 96 |
python-test-3283 | python | What does the code create ? | a symbolic link to a file | def symlink src link if sys getwindowsversion major < 6 raise Salt Invocation Error ' Symlinksareonlysupportedon Windows Vistaorlater ' if not os path exists src raise Salt Invocation Error ' Thegivensourcepathdoesnotexist ' if not os path isabs src raise Salt Invocation Error ' Filepathmustbeabsolute ' src os path nor... | def symlink src link if sys getwindowsversion major < 6 raise SaltInvocationError 'SymlinksareonlysupportedonWindowsVistaorlater ' if not os path exists src raise SaltInvocationError 'Thegivensourcepathdoesnotexist ' if not os path isabs src raise SaltInvocationError 'Filepathmustbeabsolute ' src os path normpath src l... | 96 |
python-test-3288 | python | What does the code write ? | a pair of sequence records to fileobj in fasta / fastq format | def write record pair read 1 read 2 fileobj rec pair u'@%s\n%s\n+\n%s\n' * 2 rec pair no qual u'>%s\n%s\n' * 2 if hasattr read 1 u'quality' assert hasattr read 2 u'quality' recstr rec pair % read 1 name read 1 sequence read 1 quality read 2 name read 2 sequence read 2 quality else recstr rec pair no qual % read 1 name ... | def write_record_pair read1 read2 fileobj _rec_pair u'@%s\n%s\n+\n%s\n' * 2 _rec_pair_no_qual u'>%s\n%s\n' * 2 if hasattr read1 u'quality' assert hasattr read2 u'quality' recstr _rec_pair % read1 name read1 sequence read1 quality read2 name read2 sequence read2 quality else recstr _rec_pair_no_qual % read1 name read1 s... | 84 |
python-test-3290 | python | For what purpose did by the servicetester call the code ? | in order to test login / facebook | def Test Auth Facebook User action tester user dict device dict None user cookie None ident dict {'key' ' Facebook Graph %s' % user dict['id'] 'authority' ' Facebook' 'access token' 'access token'}if device dict device dict pop 'device uuid' None device dict pop 'test udid' None with mock patch 'tornado httpclient Asyn... | def _TestAuthFacebookUser action tester user_dict device_dict None user_cookie None ident_dict {'key' 'FacebookGraph %s' % user_dict['id'] 'authority' 'Facebook' 'access_token' 'access_token'}if device_dict device_dict pop 'device_uuid' None device_dict pop 'test_udid' None with mock patch 'tornado httpclient AsyncHTTP... | 155 |
python-test-3301 | python | Till when do lookup repeat ? | until all keys found | def extended lookup connection project key pbs missing None deferred None eventual False transaction id None if missing is not None and missing [] raise Value Error 'missingmustbe Noneoranemptylist' if deferred is not None and deferred [] raise Value Error 'deferredmustbe Noneoranemptylist' results []loop num 0while lo... | def _extended_lookup connection project key_pbs missing None deferred None eventual False transaction_id None if missing is not None and missing [] raise ValueError 'missingmustbeNoneoranemptylist' if deferred is not None and deferred [] raise ValueError 'deferredmustbeNoneoranemptylist' results []loop_num 0while loop_... | 107 |
python-test-3304 | python | How does a given list of torrents sort ? | using fulltext sorting | def sort torrent fulltext data set norm num seeders normalize data dict data set 'num seeders' 'infohash' norm neg votes normalize data dict data set 'neg votes' 'infohash' norm subscriptions normalize data dict data set 'subscriptions' 'infohash' for data in data set score 0 8 * norm num seeders[data get 'infohash' ] ... | def sort_torrent_fulltext data_set norm_num_seeders normalize_data_dict data_set 'num_seeders' 'infohash' norm_neg_votes normalize_data_dict data_set 'neg_votes' 'infohash' norm_subscriptions normalize_data_dict data_set 'subscriptions' 'infohash' for data in data_set score 0 8 * norm_num_seeders[data get 'infohash' ] ... | 90 |
python-test-3307 | python | When did the code copy from accountbroker ? | before the metadata column was added | def premetadata create account stat table self conn put timestamp conn executescript "\n CREATETABL Eaccount stat \naccount TEXT \ncreated at TEXT \nput timestamp TEXTDEFAULT' 0 ' \ndelete timestamp TEXTDEFAULT' 0 ' \ncontainer count INTEGER \nobject count INTEGERDEFAULT 0 \nbytes used INTEGERDEFAULT 0 \nhash TEX Tdefa... | def premetadata_create_account_stat_table self conn put_timestamp conn executescript "\nCREATETABLEaccount_stat \naccountTEXT \ncreated_atTEXT \nput_timestampTEXTDEFAULT'0' \ndelete_timestampTEXTDEFAULT'0' \ncontainer_countINTEGER \nobject_countINTEGERDEFAULT0 \nbytes_usedINTEGERDEFAULT0 \nhashTEXTdefault'0000000000000... | 93 |
python-test-3308 | python | For what purpose does general parms parse ? | for rate limits looking for things that start with the provided name_prefix within the provided conf and returns lists | def interpret conf limits conf name prefix info None conf limits []for conf key in conf if conf key startswith name prefix cont size int conf key[len name prefix ] rate float conf[conf key] conf limits append cont size rate conf limits sort ratelimits []conf limits info list conf limits while conf limits cur size cur r... | def interpret_conf_limits conf name_prefix info None conf_limits []for conf_key in conf if conf_key startswith name_prefix cont_size int conf_key[len name_prefix ] rate float conf[conf_key] conf_limits append cont_size rate conf_limits sort ratelimits []conf_limits_info list conf_limits while conf_limits cur_size cur_r... | 140 |
python-test-3309 | python | What does the code take ? | an exception name | def get exc from name name exc Nonetry return rc exc cache[name]except Key Error m rc exc regex match name if m base m group 1 rc or sig name m group 2 if base ' Signal Exception' try rc - int rc or sig name except Value Error rc - getattr signal rc or sig name else rc int rc or sig name exc get rc exc rc return exc | def get_exc_from_name name exc Nonetry return rc_exc_cache[name]except KeyError m rc_exc_regex match name if m base m group 1 rc_or_sig_name m group 2 if base 'SignalException' try rc - int rc_or_sig_name except ValueError rc - getattr signal rc_or_sig_name else rc int rc_or_sig_name exc get_rc_exc rc return exc | 71 |
python-test-3315 | python | What does the code use for speed here ? | a greedy approach | def combine similar molecules molecules list new guys start idx 0while new guys start idx < len molecules list combined [ False] * len molecules list new guys []for j in xrange new guys start idx len molecules list for i in xrange 0 j if combined[i] continue g1 m1 g2 m2 molecules list[i] molecules list[j] js jaccard si... | def _combine_similar_molecules molecules_list new_guys_start_idx 0while new_guys_start_idx < len molecules_list combined [False] * len molecules_list new_guys []for j in xrange new_guys_start_idx len molecules_list for i in xrange 0 j if combined[i] continue g1 m1 g2 m2 molecules_list[i] molecules_list[j] js _jaccard_s... | 110 |
python-test-3316 | python | What does the code find ? | a predefined compound unit pattern | def find compound unit numerator unit denominator unit locale LC NUMERIC locale Locale parse locale numerator unit find unit pattern numerator unit locale locale denominator unit find unit pattern denominator unit locale locale if not numerator unit and denominator unit return Nonebare numerator unit numerator unit spl... | def _find_compound_unit numerator_unit denominator_unit locale LC_NUMERIC locale Locale parse locale numerator_unit _find_unit_pattern numerator_unit locale locale denominator_unit _find_unit_pattern denominator_unit locale locale if not numerator_unit and denominator_unit return Nonebare_numerator_unit numerator_unit ... | 75 |
python-test-3319 | python | What do a formula contain ? | fancy cell names | def translate formula out []for part in re split ' \\w+ ? \\w+ ? ' formula m re match '^ [A-Z]+ [1 - 9 ][ 0 - 9 ]* ? [A-Z]+ [1 - 9 ][ 0 - 9 ]* ?$' part if m is None out append part else x1 y1 x2 y2 m groups x1 colname 2 num x1 if x2 is None s 'cell %s %s ' % x1 y1 else x2 colname 2 num x2 s 'cells %s %s %s %s ' % x1 y1... | def translate formula out []for part in re split ' \\w+ ? \\w+ ? ' formula m re match '^ [A-Z]+ [1-9][0-9]* ? [A-Z]+ [1-9][0-9]* ?$' part if m is None out append part else x1 y1 x2 y2 m groups x1 colname2num x1 if x2 is None s 'cell %s %s ' % x1 y1 else x2 colname2num x2 s 'cells %s %s %s %s ' % x1 y1 x2 y2 out append ... | 97 |
python-test-3320 | python | What can be used to draw a series of violin plots ? | dictionaries of data | def violin stats X method points 100 vpstats []X reshape 2D X for x in X stats {}min val np min x max val np max x coords np linspace min val max val points stats[u'vals'] method x coords stats[u'coords'] coordsstats[u'mean'] np mean x stats[u'median'] np median x stats[u'min'] min valstats[u'max'] max valvpstats appen... | def violin_stats X method points 100 vpstats []X _reshape_2D X for x in X stats {}min_val np min x max_val np max x coords np linspace min_val max_val points stats[u'vals'] method x coords stats[u'coords'] coordsstats[u'mean'] np mean x stats[u'median'] np median x stats[u'min'] min_valstats[u'max'] max_valvpstats appe... | 57 |
python-test-3321 | python | What can dictionaries of data be used ? | to draw a series of violin plots | def violin stats X method points 100 vpstats []X reshape 2D X for x in X stats {}min val np min x max val np max x coords np linspace min val max val points stats[u'vals'] method x coords stats[u'coords'] coordsstats[u'mean'] np mean x stats[u'median'] np median x stats[u'min'] min valstats[u'max'] max valvpstats appen... | def violin_stats X method points 100 vpstats []X _reshape_2D X for x in X stats {}min_val np min x max_val np max x coords np linspace min_val max_val points stats[u'vals'] method x coords stats[u'coords'] coordsstats[u'mean'] np mean x stats[u'median'] np median x stats[u'min'] min_valstats[u'max'] max_valvpstats appe... | 57 |
python-test-3326 | python | What does the code calculate ? | the root - mean - square difference between two images | def rmsdiff 2011 im 1 im 2 diff Image Chops difference im 1 im 2 h diff histogram sq value * idx ** 2 for idx value in enumerate h sum of squares sum sq rms math sqrt sum of squares / float im 1 size[ 0 ] * im 1 size[ 1 ] return rms | def rmsdiff_2011 im1 im2 diff ImageChops difference im1 im2 h diff histogram sq value * idx ** 2 for idx value in enumerate h sum_of_squares sum sq rms math sqrt sum_of_squares / float im1 size[0] * im1 size[1] return rms | 56 |
python-test-3333 | python | What does the code update ? | the count of each type of discussion on an entry | def count discussions handler sender **kwargs if kwargs get 'instance' and kwargs get 'created' returncomment 'comment' in kwargs and kwargs['comment'] or kwargs['instance'] entry comment content objectif isinstance entry Entry entry comment count entry comments count entry pingback count entry pingbacks count entry tr... | def count_discussions_handler sender **kwargs if kwargs get 'instance' and kwargs get 'created' returncomment 'comment' in kwargs and kwargs['comment'] or kwargs['instance'] entry comment content_objectif isinstance entry Entry entry comment_count entry comments count entry pingback_count entry pingbacks count entry tr... | 57 |
python-test-3334 | python | Where do local map layers publish as group layer ? | in local ows | def map wms request mapid map obj resolve map request mapid 'base view resourcebase' PERMISSION MSG VIEW if request method 'PUT' try layer Group Name map obj publish layer group response dict layer Group Name layer Group Name ows getattr ogc server settings 'ows' '' return Http Response json dumps response content type... | def map_wms request mapid map_obj _resolve_map request mapid 'base view_resourcebase' _PERMISSION_MSG_VIEW if request method 'PUT' try layerGroupName map_obj publish_layer_group response dict layerGroupName layerGroupName ows getattr ogc_server_settings 'ows' '' return HttpResponse json dumps response content_type 'app... | 99 |
python-test-3335 | python | What publishs in local ows ? | local map layers | def map wms request mapid map obj resolve map request mapid 'base view resourcebase' PERMISSION MSG VIEW if request method 'PUT' try layer Group Name map obj publish layer group response dict layer Group Name layer Group Name ows getattr ogc server settings 'ows' '' return Http Response json dumps response content type... | def map_wms request mapid map_obj _resolve_map request mapid 'base view_resourcebase' _PERMISSION_MSG_VIEW if request method 'PUT' try layerGroupName map_obj publish_layer_group response dict layerGroupName layerGroupName ows getattr ogc_server_settings 'ows' '' return HttpResponse json dumps response content_type 'app... | 99 |
python-test-3336 | python | How do local map layers publish in local ows ? | as group layer | def map wms request mapid map obj resolve map request mapid 'base view resourcebase' PERMISSION MSG VIEW if request method 'PUT' try layer Group Name map obj publish layer group response dict layer Group Name layer Group Name ows getattr ogc server settings 'ows' '' return Http Response json dumps response content type... | def map_wms request mapid map_obj _resolve_map request mapid 'base view_resourcebase' _PERMISSION_MSG_VIEW if request method 'PUT' try layerGroupName map_obj publish_layer_group response dict layerGroupName layerGroupName ows getattr ogc_server_settings 'ows' '' return HttpResponse json dumps response content_type 'app... | 99 |
python-test-3337 | python | For what purpose do decorator view ? | to verify the user is authorized to access this endpoint | def permitted func @functools wraps func def wrapper request *args **kwargs '\n Wrapperfortheviewthatonlycallstheviewiftheuserisauthorized \n'def fetch content '\n Extracttheforumobjectfromthekeywordargumentstotheview \n'if 'thread id' in kwargs content cc Thread find kwargs['thread id'] to dict elif 'comment id' in kw... | def permitted func @functools wraps func def wrapper request *args **kwargs '\nWrapperfortheviewthatonlycallstheviewiftheuserisauthorized \n'def fetch_content '\nExtracttheforumobjectfromthekeywordargumentstotheview \n'if 'thread_id' in kwargs content cc Thread find kwargs['thread_id'] to_dict elif 'comment_id' in kwar... | 96 |
python-test-3341 | python | What does the code take ? | a list of names | def namignizer iterator names counts batch size num steps epoch size name distribution counts / counts sum for i in range epoch size data np zeros batch size * num steps + 1 samples np random choice names size batch size * num steps // 2 replace True p name distribution data index 0for sample in samples if data index >... | def namignizer_iterator names counts batch_size num_steps epoch_size name_distribution counts / counts sum for i in range epoch_size data np zeros batch_size * num_steps + 1 samples np random choice names size batch_size * num_steps // 2 replace True p name_distribution data_index 0for sample in samples if data_index >... | 123 |
python-test-3342 | python | What does the code get ? | ip blocks with one or more unallocated ips | def get blocks with unallocated module cp driver lb driver network domain total unallocated ips 0all blocks list public ip blocks module cp driver network domain unalloc blocks []unalloc addresses []for block in all blocks d blocks get block allocation module cp driver lb driver network domain block i 0for addr in d bl... | def get_blocks_with_unallocated module cp_driver lb_driver network_domain total_unallocated_ips 0all_blocks list_public_ip_blocks module cp_driver network_domain unalloc_blocks []unalloc_addresses []for block in all_blocks d_blocks get_block_allocation module cp_driver lb_driver network_domain block i 0for addr in d_bl... | 90 |
python-test-3344 | python | What does the code validate ? | a cookie value string | def valid value value quote default cookie quote unquote default unquote if value is None return Falseencoded encode cookie value value quote quote decoded parse string encoded unquote unquote decoded normalized normalize 'NFKD' decoded if not isinstance decoded bytes else decoded value normalized normalize 'NFKD' valu... | def valid_value value quote default_cookie_quote unquote default_unquote if value is None return Falseencoded encode_cookie_value value quote quote decoded parse_string encoded unquote unquote decoded_normalized normalize 'NFKD' decoded if not isinstance decoded bytes else decoded value_normalized normalize 'NFKD' valu... | 61 |
python-test-3351 | python | What do those have ? | at least one of the required substrings | def select Some strings requiredsubstrings [] require All True if len requiredsubstrings 0 return stringsres []for s in strings if require All bad Falsefor rs in requiredsubstrings if s find rs < 0 bad Truebreakif not bad res append s else for rs in requiredsubstrings if s find rs > 0 res append s breakreturn res | def selectSome strings requiredsubstrings [] requireAll True if len requiredsubstrings 0 return stringsres []for s in strings if requireAll bad Falsefor rs in requiredsubstrings if s find rs < 0 bad Truebreakif not bad res append s else for rs in requiredsubstrings if s find rs > 0 res append s breakreturn res | 56 |
python-test-3352 | python | What does the code get ? | absolute path for all the given themes | def get theme paths themes theme dirs theme paths []for theme in themes theme base dirs get theme base dirs theme theme dirs if not theme base dirs print "\x 1 b[ 91 m\n Skipping'{theme}' \n Theme {theme} notfoundinanyofthethemedirs {theme dirs} \x 1 b[ 00 m" format theme theme theme dirs ' ' join theme dirs theme path... | def get_theme_paths themes theme_dirs theme_paths []for theme in themes theme_base_dirs get_theme_base_dirs theme theme_dirs if not theme_base_dirs print "\x1b[91m\nSkipping'{theme}' \nTheme {theme} notfoundinanyofthethemedirs {theme_dirs} \x1b[00m" format theme theme theme_dirs ' ' join theme_dirs theme_paths extend t... | 65 |
python-test-3353 | python | What does the code ensure ? | a user is not present name username to remove if it exists examples | def user absent name ret {'name' name 'result' False 'changes' {} 'comment' ''}old user salt ['nxos cmd'] 'get user' username name if not old user ret['result'] Trueret['comment'] ' Userdoesnotexist'return retif opts ['test'] is True and old user ret['result'] Noneret['comment'] ' Userwillberemoved'ret['changes']['old'... | def user_absent name ret {'name' name 'result' False 'changes' {} 'comment' ''}old_user __salt__['nxos cmd'] 'get_user' username name if not old_user ret['result'] Trueret['comment'] 'Userdoesnotexist'return retif __opts__['test'] is True and old_user ret['result'] Noneret['comment'] 'Userwillberemoved'ret['changes']['... | 71 |
python-test-3354 | python | What does the code find ? | the inputs and outputs generated by a rule | def Rule Inputs And Outputs rule trigger file raw inputs Fix Paths rule get 'inputs' [] raw outputs Fix Paths rule get 'outputs' [] inputs Ordered Set outputs Ordered Set inputs add trigger file for i in raw inputs inputs add Rule Expand Path i trigger file for o in raw outputs outputs add Rule Expand Path o trigger fi... | def _RuleInputsAndOutputs rule trigger_file raw_inputs _FixPaths rule get 'inputs' [] raw_outputs _FixPaths rule get 'outputs' [] inputs OrderedSet outputs OrderedSet inputs add trigger_file for i in raw_inputs inputs add _RuleExpandPath i trigger_file for o in raw_outputs outputs add _RuleExpandPath o trigger_file ret... | 63 |
python-test-3355 | python | For what purpose are the questions returned in the order of their position in the template ? | to return the list of questions for the given | def survey get All Questions For Template template id s3 db current s3 dbsectable s3 db survey sectionq ltable s3 db survey question listqsntable s3 db survey questionquery q ltable template id template id & q ltable section id sectable id & q ltable question id qsntable id rows current db query select qsntable id qsnt... | def survey_getAllQuestionsForTemplate template_id s3db current s3dbsectable s3db survey_sectionq_ltable s3db survey_question_listqsntable s3db survey_questionquery q_ltable template_id template_id & q_ltable section_id sectable id & q_ltable question_id qsntable id rows current db query select qsntable id qsntable code... | 114 |
python-test-3358 | python | What does the code get ? | a timezoned time from a given instant | def get time time tzinfo None if time is None time datetime utcnow elif isinstance time number types time datetime utcfromtimestamp time if time tzinfo is None time time replace tzinfo UTC if isinstance time datetime if tzinfo is not None time time astimezone tzinfo if hasattr tzinfo 'normalize' time tzinfo normalize t... | def _get_time time tzinfo None if time is None time datetime utcnow elif isinstance time number_types time datetime utcfromtimestamp time if time tzinfo is None time time replace tzinfo UTC if isinstance time datetime if tzinfo is not None time time astimezone tzinfo if hasattr tzinfo 'normalize' time tzinfo normalize ... | 68 |
python-test-3361 | python | Where did the units define ? | in units | def apply units string units inter None final float blank reg BLANK RE value reg VALUE RE if inter is None inter finalfstring BLANK RE sub '' string if not fstring and VALIDATION RE match fstring raise Value Error ' Invalidunitstring %r ' % string values []for match in value reg finditer fstring dic match groupdict lit... | def apply_units string units inter None final float blank_reg _BLANK_RE value_reg _VALUE_RE if inter is None inter finalfstring _BLANK_RE sub '' string if not fstring and _VALIDATION_RE match fstring raise ValueError 'Invalidunitstring %r ' % string values []for match in value_reg finditer fstring dic match groupdict l... | 94 |
python-test-3362 | python | What do the string apply ? | the units defined in units | def apply units string units inter None final float blank reg BLANK RE value reg VALUE RE if inter is None inter finalfstring BLANK RE sub '' string if not fstring and VALIDATION RE match fstring raise Value Error ' Invalidunitstring %r ' % string values []for match in value reg finditer fstring dic match groupdict lit... | def apply_units string units inter None final float blank_reg _BLANK_RE value_reg _VALUE_RE if inter is None inter finalfstring _BLANK_RE sub '' string if not fstring and _VALIDATION_RE match fstring raise ValueError 'Invalidunitstring %r ' % string values []for match in value_reg finditer fstring dic match groupdict l... | 94 |
python-test-3374 | python | What does the code do ? | a diff on the tokens | def htmldiff tokens html 1 tokens html 2 tokens s Insensitive Sequence Matcher a html 1 tokens b html 2 tokens commands s get opcodes result []for command i1 i2 j1 j2 in commands if command 'equal' result extend expand tokens html 2 tokens[j 1 j2 ] equal True continueif command 'insert' or command 'replace' ins tokens ... | def htmldiff_tokens html1_tokens html2_tokens s InsensitiveSequenceMatcher a html1_tokens b html2_tokens commands s get_opcodes result []for command i1 i2 j1 j2 in commands if command 'equal' result extend expand_tokens html2_tokens[j1 j2] equal True continueif command 'insert' or command 'replace' ins_tokens expand_to... | 97 |
python-test-3376 | python | What does the code create ? | a small matrix m to be triangularized | def create ma deg f deg g row 1 row 2 col num if deg g - deg f > 1 print ' Reversedegrees' returnm zeros deg f - deg g + 2 col num for i in range deg f - deg g + 1 m[i ] rotate r row 1 i m[ deg f - deg g + 1 ] row 2 return m | def create_ma deg_f deg_g row1 row2 col_num if deg_g - deg_f > 1 print 'Reversedegrees' returnm zeros deg_f - deg_g + 2 col_num for i in range deg_f - deg_g + 1 m[i ] rotate_r row1 i m[ deg_f - deg_g + 1 ] row2return m | 66 |
python-test-3380 | python | How do the input list of list augment ? | by appending n - grams values | def add ngram sequences token indice ngram range 2 new sequences []for input list in sequences new list input list[ ]for i in range len new list - ngram range + 1 for ngram value in range 2 ngram range + 1 ngram tuple new list[i i + ngram value ] if ngram in token indice new list append token indice[ngram] new sequence... | def add_ngram sequences token_indice ngram_range 2 new_sequences []for input_list in sequences new_list input_list[ ]for i in range len new_list - ngram_range + 1 for ngram_value in range 2 ngram_range + 1 ngram tuple new_list[i i + ngram_value ] if ngram in token_indice new_list append token_indice[ngram] new_sequence... | 69 |
python-test-3383 | python | What does the code setup ? | the panasonic viera tv platform | def setup platform hass config add devices discovery info None from panasonic viera import Remote Controlmac config get CONF MAC name config get CONF NAME port config get CONF PORT if discovery info LOGGER debug '%s' discovery info vals discovery info split ' ' if len vals > 1 port vals[ 1 ]host vals[ 0 ]remote Remote ... | def setup_platform hass config add_devices discovery_info None from panasonic_viera import RemoteControlmac config get CONF_MAC name config get CONF_NAME port config get CONF_PORT if discovery_info _LOGGER debug '%s' discovery_info vals discovery_info split ' ' if len vals > 1 port vals[1]host vals[0]remote RemoteContr... | 95 |
python-test-3387 | python | What does the code downgrade to the desired version ? | the assets db at the given engine | @preprocess engine coerce string to eng def downgrade engine desired version with engine begin as conn metadata sa Meta Data conn metadata reflect version info table metadata tables['version info']starting version sa select version info table c version scalar if starting version < desired version raise Asset DB Impossi... | @preprocess engine coerce_string_to_eng def downgrade engine desired_version with engine begin as conn metadata sa MetaData conn metadata reflect version_info_table metadata tables['version_info']starting_version sa select version_info_table c version scalar if starting_version < desired_version raise AssetDBImpossible... | 104 |
python-test-3399 | python | What does the code make ? | all of the stochastic nodes in expr use the rng uniform - > uniform | def recursive set rng kwarg expr rng None if rng is None rng np random Random State lrng as apply rng for node in dfs expr if node name in implicit stochastic symbols for ii name arg in enumerate list node named args if name 'rng' node named args[ii] 'rng' lrng breakelse node named args append 'rng' lrng return expr | def recursive_set_rng_kwarg expr rng None if rng is None rng np random RandomState lrng as_apply rng for node in dfs expr if node name in implicit_stochastic_symbols for ii name arg in enumerate list node named_args if name 'rng' node named_args[ii] 'rng' lrng breakelse node named_args append 'rng' lrng return expr | 60 |
python-test-3400 | python | What use the rng uniform - > uniform ? | all of the stochastic nodes in | def recursive set rng kwarg expr rng None if rng is None rng np random Random State lrng as apply rng for node in dfs expr if node name in implicit stochastic symbols for ii name arg in enumerate list node named args if name 'rng' node named args[ii] 'rng' lrng breakelse node named args append 'rng' lrng return expr | def recursive_set_rng_kwarg expr rng None if rng is None rng np random RandomState lrng as_apply rng for node in dfs expr if node name in implicit_stochastic_symbols for ii name arg in enumerate list node named_args if name 'rng' node named_args[ii] 'rng' lrng breakelse node named_args append 'rng' lrng return expr | 60 |
python-test-3401 | python | What do all of the stochastic nodes in use ? | the rng uniform - > uniform | def recursive set rng kwarg expr rng None if rng is None rng np random Random State lrng as apply rng for node in dfs expr if node name in implicit stochastic symbols for ii name arg in enumerate list node named args if name 'rng' node named args[ii] 'rng' lrng breakelse node named args append 'rng' lrng return expr | def recursive_set_rng_kwarg expr rng None if rng is None rng np random RandomState lrng as_apply rng for node in dfs expr if node name in implicit_stochastic_symbols for ii name arg in enumerate list node named_args if name 'rng' node named_args[ii] 'rng' lrng breakelse node named_args append 'rng' lrng return expr | 60 |
python-test-3406 | python | What do wrong hashes stop ? | installation | def test hashed install failure script data tmpdir with requirements file 'simple 2 1 0--hash sha 256 9336 af 72 ca 661 e 6336 eb 87 bc 7 de 3 e 8844 d 853 e 3848 c 2 b 9 bbd 2 e 8 bf 01 db 88 c 2 c\n' tmpdir as reqs file result script pip install local '-r' reqs file abspath expect error True assert len result files c... | def test_hashed_install_failure script data tmpdir with requirements_file 'simple2 1 0--hash sha256 9336af72ca661e6336eb87bc7de3e8844d853e3848c2b9bbd2e8bf01db88c2c\n' tmpdir as reqs_file result script pip_install_local '-r' reqs_file abspath expect_error True assert len result files_created 0 | 73 |
python-test-3407 | python | What stops installation ? | wrong hashes | def test hashed install failure script data tmpdir with requirements file 'simple 2 1 0--hash sha 256 9336 af 72 ca 661 e 6336 eb 87 bc 7 de 3 e 8844 d 853 e 3848 c 2 b 9 bbd 2 e 8 bf 01 db 88 c 2 c\n' tmpdir as reqs file result script pip install local '-r' reqs file abspath expect error True assert len result files c... | def test_hashed_install_failure script data tmpdir with requirements_file 'simple2 1 0--hash sha256 9336af72ca661e6336eb87bc7de3e8844d853e3848c2b9bbd2e8bf01db88c2c\n' tmpdir as reqs_file result script pip_install_local '-r' reqs_file abspath expect_error True assert len result files_created 0 | 73 |
python-test-3413 | python | What does the code get ? | the functions with the search string in the file | def get Functions With String By File Name file Name search String file Text archive get File Text file Name functions []lines archive get Text Lines file Text for line in lines line Stripped line strip if line Stripped startswith 'def' and search String in line Stripped if ' self ' not in line Stripped or line Strippe... | def getFunctionsWithStringByFileName fileName searchString fileText archive getFileText fileName functions []lines archive getTextLines fileText for line in lines lineStripped line strip if lineStripped startswith 'def' and searchString in lineStripped if ' self ' not in lineStripped or lineStripped count ' ' > 1 funct... | 74 |
python-test-3414 | python | What do a csv show students ? | grades for all problems in the course | @transaction non atomic requests@require POST@ensure csrf cookie@cache control no cache True no store True must revalidate True @require level 'staff' def problem grade report request course id course key Slash Separated Course Key from deprecated string course id try lms djangoapps instructor task api submit problem g... | @transaction non_atomic_requests@require_POST@ensure_csrf_cookie@cache_control no_cache True no_store True must_revalidate True @require_level 'staff' def problem_grade_report request course_id course_key SlashSeparatedCourseKey from_deprecated_string course_id try lms djangoapps instructor_task api submit_problem_grad... | 88 |
python-test-3415 | python | What does the code request ? | a csv showing students grades for all problems in the course | @transaction non atomic requests@require POST@ensure csrf cookie@cache control no cache True no store True must revalidate True @require level 'staff' def problem grade report request course id course key Slash Separated Course Key from deprecated string course id try lms djangoapps instructor task api submit problem g... | @transaction non_atomic_requests@require_POST@ensure_csrf_cookie@cache_control no_cache True no_store True must_revalidate True @require_level 'staff' def problem_grade_report request course_id course_key SlashSeparatedCourseKey from_deprecated_string course_id try lms djangoapps instructor_task api submit_problem_grad... | 88 |
python-test-3417 | python | What does the code enable ? | the given apikey | def enable api key api Key region None key None keyid None profile None try conn get conn region region key key keyid keyid profile profile response api key patch replace conn api Key '/enabled' ' True' return {'api Key' convert datetime str response }except Client Error as e return {'error' salt utils boto 3 get error... | def enable_api_key apiKey region None key None keyid None profile None try conn _get_conn region region key key keyid keyid profile profile response _api_key_patch_replace conn apiKey '/enabled' 'True' return {'apiKey' _convert_datetime_str response }except ClientError as e return {'error' salt utils boto3 get_error e ... | 59 |
python-test-3422 | python | What did private function use ? | to partition estimators between jobs | def partition estimators n estimators n jobs n jobs min get n jobs n jobs n estimators n estimators per job n estimators // n jobs * np ones n jobs dtype np int n estimators per job[ n estimators % n jobs ] + 1starts np cumsum n estimators per job return n jobs n estimators per job tolist [0 ] + starts tolist | def _partition_estimators n_estimators n_jobs n_jobs min _get_n_jobs n_jobs n_estimators n_estimators_per_job n_estimators // n_jobs * np ones n_jobs dtype np int n_estimators_per_job[ n_estimators % n_jobs ] + 1starts np cumsum n_estimators_per_job return n_jobs n_estimators_per_job tolist [0] + starts tolist | 65 |
python-test-3427 | python | What does heuristics use ? | to guess whether the given file is text or binary | def istextfile fp blocksize 512 int 2 byte lambda x bytes x if six PY 3 else chr text characters '' join int 2 byte i for i in range 32 127 + '\n\r DCTB \x 0 c\x 08 ' try block fp read blocksize except Attribute Error try with fopen fp 'rb' as fp 2 block fp 2 read blocksize except IO Error return Falseif '\x 00 ' in bl... | def istextfile fp_ blocksize 512 int2byte lambda x bytes x if six PY3 else chr text_characters '' join int2byte i for i in range 32 127 + '\n\r DCTB \x0c\x08' try block fp_ read blocksize except AttributeError try with fopen fp_ 'rb' as fp2_ block fp2_ read blocksize except IOError return Falseif '\x00' in block return... | 103 |
python-test-3428 | python | What uses to guess whether the given file is text or binary ? | heuristics | def istextfile fp blocksize 512 int 2 byte lambda x bytes x if six PY 3 else chr text characters '' join int 2 byte i for i in range 32 127 + '\n\r DCTB \x 0 c\x 08 ' try block fp read blocksize except Attribute Error try with fopen fp 'rb' as fp 2 block fp 2 read blocksize except IO Error return Falseif '\x 00 ' in bl... | def istextfile fp_ blocksize 512 int2byte lambda x bytes x if six PY3 else chr text_characters '' join int2byte i for i in range 32 127 + '\n\r DCTB \x0c\x08' try block fp_ read blocksize except AttributeError try with fopen fp_ 'rb' as fp2_ block fp2_ read blocksize except IOError return Falseif '\x00' in block return... | 103 |
python-test-3433 | python | What does the code get ? | the objects voted by an user | def get voted user or id model obj type apps get model 'contenttypes' ' Content Type' objects get for model model conditions 'votes vote content type id %s' '%s id votes vote object id' % model meta db table 'votes vote user id %s' if isinstance user or id get user model user id user or id idelse user id user or idretu... | def get_voted user_or_id model obj_type apps get_model 'contenttypes' 'ContentType' objects get_for_model model conditions 'votes_vote content_type_id %s' '%s id votes_vote object_id' % model _meta db_table 'votes_vote user_id %s' if isinstance user_or_id get_user_model user_id user_or_id idelse user_id user_or_idretur... | 77 |
python-test-3434 | python | What does the code create ? | the fully qualified name of the files created by { console | def script names dist script name is gui if dist in usersite dist bin dir bin userelse bin dir bin pyexe name os path join bin dir script name paths to remove [exe name]if WINDOWS paths to remove append exe name + ' exe' paths to remove append exe name + ' exe manifest' if is gui paths to remove append exe name + '-scr... | def _script_names dist script_name is_gui if dist_in_usersite dist bin_dir bin_userelse bin_dir bin_pyexe_name os path join bin_dir script_name paths_to_remove [exe_name]if WINDOWS paths_to_remove append exe_name + ' exe' paths_to_remove append exe_name + ' exe manifest' if is_gui paths_to_remove append exe_name + '-sc... | 80 |
python-test-3436 | python | In which direction do reseller_prefix option and associated options read ? | from configuration | def config read reseller options conf defaults reseller prefix opt conf get 'reseller prefix' 'AUTH' split ' ' reseller prefixes []for prefix in [pre strip for pre in reseller prefix opt if pre strip ] if prefix "''" prefix ''prefix append underscore prefix if prefix not in reseller prefixes reseller prefixes append pr... | def config_read_reseller_options conf defaults reseller_prefix_opt conf get 'reseller_prefix' 'AUTH' split ' ' reseller_prefixes []for prefix in [pre strip for pre in reseller_prefix_opt if pre strip ] if prefix "''" prefix ''prefix append_underscore prefix if prefix not in reseller_prefixes reseller_prefixes append pr... | 107 |
python-test-3443 | python | What does the code get ? | the xbps version | @decorators memoizedef get version xpath check xbps version string salt ['cmd run'] '{ 0 }--version' format xpath output loglevel 'trace' if version string is None return False VERSION MATCH re compile ' ? XBPS [\\s]+ [\\d ]+ ? [\\s]+ * ' version match VERSION MATCH search version string if not version match return Fal... | @decorators memoizedef _get_version xpath _check_xbps version_string __salt__['cmd run'] '{0}--version' format xpath output_loglevel 'trace' if version_string is None return FalseVERSION_MATCH re compile ' ? XBPS [\\s]+ [\\d ]+ ? [\\s]+ * ' version_match VERSION_MATCH search version_string if not version_match return F... | 61 |
python-test-3445 | python | How does the code open the named log file ? | in append mode | def open logfile filename mode 'a' filename os path expanduser filename filename os path abspath filename dirname os path dirname filename if not os path exists dirname os makedirs dirname exists os path exists filename log fp open filename mode if exists log fp write '%s\n' % '-' * 60 log fp write '%srunon%s\n' % sys ... | def open_logfile filename mode 'a' filename os path expanduser filename filename os path abspath filename dirname os path dirname filename if not os path exists dirname os makedirs dirname exists os path exists filename log_fp open filename mode if exists log_fp write '%s\n' % '-' * 60 log_fp write '%srunon%s\n' % sys ... | 65 |
python-test-3446 | python | What does the code open in append mode ? | the named log file | def open logfile filename mode 'a' filename os path expanduser filename filename os path abspath filename dirname os path dirname filename if not os path exists dirname os makedirs dirname exists os path exists filename log fp open filename mode if exists log fp write '%s\n' % '-' * 60 log fp write '%srunon%s\n' % sys ... | def open_logfile filename mode 'a' filename os path expanduser filename filename os path abspath filename dirname os path dirname filename if not os path exists dirname os makedirs dirname exists os path exists filename log_fp open filename mode if exists log_fp write '%s\n' % '-' * 60 log_fp write '%srunon%s\n' % sys ... | 65 |
python-test-3448 | python | What does the code validate using a model ? | some untrusted data | def validate cls instance or dict trusted data None partial False strict False convert True context None **kwargs context context or get validation context partial partial strict strict convert convert errors {}try data import loop cls instance or dict trusted data trusted data context context **kwargs except Data Erro... | def validate cls instance_or_dict trusted_data None partial False strict False convert True context None **kwargs context context or get_validation_context partial partial strict strict convert convert errors {}try data import_loop cls instance_or_dict trusted_data trusted_data context context **kwargs except DataError... | 72 |
python-test-3449 | python | How does the code validate some untrusted data ? | using a model | def validate cls instance or dict trusted data None partial False strict False convert True context None **kwargs context context or get validation context partial partial strict strict convert convert errors {}try data import loop cls instance or dict trusted data trusted data context context **kwargs except Data Erro... | def validate cls instance_or_dict trusted_data None partial False strict False convert True context None **kwargs context context or get_validation_context partial partial strict strict convert convert errors {}try data import_loop cls instance_or_dict trusted_data trusted_data context context **kwargs except DataError... | 72 |
python-test-3453 | python | What does the code create ? | a dataframe representing assets that exist for the full duration between start_date and end_date | def make simple equity info sids start date end date symbols None num assets len sids if symbols is None symbols list ascii uppercase[ num assets] return pd Data Frame {'symbol' list symbols 'start date' pd to datetime [start date] * num assets 'end date' pd to datetime [end date] * num assets 'exchange' 'TEST' 'exchan... | def make_simple_equity_info sids start_date end_date symbols None num_assets len sids if symbols is None symbols list ascii_uppercase[ num_assets] return pd DataFrame {'symbol' list symbols 'start_date' pd to_datetime [start_date] * num_assets 'end_date' pd to_datetime [end_date] * num_assets 'exchange' 'TEST' 'exchang... | 69 |
python-test-3454 | python | When do assets exist between start_date and end_date ? | for the full duration | def make simple equity info sids start date end date symbols None num assets len sids if symbols is None symbols list ascii uppercase[ num assets] return pd Data Frame {'symbol' list symbols 'start date' pd to datetime [start date] * num assets 'end date' pd to datetime [end date] * num assets 'exchange' 'TEST' 'exchan... | def make_simple_equity_info sids start_date end_date symbols None num_assets len sids if symbols is None symbols list ascii_uppercase[ num_assets] return pd DataFrame {'symbol' list symbols 'start_date' pd to_datetime [start_date] * num_assets 'end_date' pd to_datetime [end_date] * num_assets 'exchange' 'TEST' 'exchang... | 69 |
python-test-3455 | python | Where do assets exist for the full duration ? | between start_date and end_date | def make simple equity info sids start date end date symbols None num assets len sids if symbols is None symbols list ascii uppercase[ num assets] return pd Data Frame {'symbol' list symbols 'start date' pd to datetime [start date] * num assets 'end date' pd to datetime [end date] * num assets 'exchange' 'TEST' 'exchan... | def make_simple_equity_info sids start_date end_date symbols None num_assets len sids if symbols is None symbols list ascii_uppercase[ num_assets] return pd DataFrame {'symbol' list symbols 'start_date' pd to_datetime [start_date] * num_assets 'end_date' pd to_datetime [end_date] * num_assets 'exchange' 'TEST' 'exchang... | 69 |
python-test-3456 | python | What copys to our special flag line ? | each line up | def get non generated file lines lines to copy []flag found Falsewith open ' /plotly/graph objs/graph objs py' 'r' as f for line to copy in f if line to copy startswith FLAG flag found Truebreaklines to copy append line to copy if not flag found raise Value Error ' Failedtofindflag \n"{}"\ningraph objs tools py ' forma... | def get_non_generated_file_lines lines_to_copy []flag_found Falsewith open ' /plotly/graph_objs/graph_objs py' 'r' as f for line_to_copy in f if line_to_copy startswith FLAG flag_found Truebreaklines_to_copy append line_to_copy if not flag_found raise ValueError 'Failedtofindflag \n"{}"\ningraph_objs_tools py ' format ... | 62 |
python-test-3457 | python | What do each line up copy ? | to our special flag line | def get non generated file lines lines to copy []flag found Falsewith open ' /plotly/graph objs/graph objs py' 'r' as f for line to copy in f if line to copy startswith FLAG flag found Truebreaklines to copy append line to copy if not flag found raise Value Error ' Failedtofindflag \n"{}"\ningraph objs tools py ' forma... | def get_non_generated_file_lines lines_to_copy []flag_found Falsewith open ' /plotly/graph_objs/graph_objs py' 'r' as f for line_to_copy in f if line_to_copy startswith FLAG flag_found Truebreaklines_to_copy append line_to_copy if not flag_found raise ValueError 'Failedtofindflag \n"{}"\ningraph_objs_tools py ' format ... | 62 |
python-test-3460 | python | How does the code create a new model in a given api ? | with a given schema | def create api model rest Api Id model Name model Description schema content Type 'application/json' region None key None keyid None profile None try schema json json dumps schema if isinstance schema dict else schema conn get conn region region key key keyid keyid profile profile model conn create model rest Api Id re... | def create_api_model restApiId modelName modelDescription schema contentType 'application/json' region None key None keyid None profile None try schema_json json dumps schema if isinstance schema dict else schema conn _get_conn region region key key keyid keyid profile profile model conn create_model restApiId restApiI... | 94 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.