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-3678 | python | For what purpose does the code stop a running container container container i d timeout timeout ? | for container to exit gracefully before killing it | def stop container timeout 10 client get client status base status copy try dcontainer get container infos container [' Id']if is running dcontainer client stop dcontainer timeout timeout if not is running dcontainer valid status comment ' Container{ 0 }wasstopped' format container id container else invalid status else... | def stop container timeout 10 client _get_client status base_status copy try dcontainer _get_container_infos container ['Id']if is_running dcontainer client stop dcontainer timeout timeout if not is_running dcontainer _valid status comment 'Container{0}wasstopped' format container id_ container else _invalid status els... | 89 |
python-test-3679 | python | What does the code setup ? | the usps platform | def setup platform hass config add devices discovery info None import myuspstry cookie hass config path COOKIE session myusps get session config get CONF USERNAME config get CONF PASSWORD cookie path cookie except myusps USPS Error LOGGER exception ' Couldnotconnectto My USPS' return Falseadd devices [USPS Sensor sessi... | def setup_platform hass config add_devices discovery_info None import myuspstry cookie hass config path COOKIE session myusps get_session config get CONF_USERNAME config get CONF_PASSWORD cookie_path cookie except myusps USPSError _LOGGER exception 'CouldnotconnecttoMyUSPS' return Falseadd_devices [USPSSensor session c... | 54 |
python-test-3681 | python | Do objects have any referents ? | No | def get leaking objects objects None if objects is None gc collect objects gc get objects try ids set id i for i in objects for i in objects ids difference update id j for j in gc get referents i return [i for i in objects if id i in ids ]finally del objects i | def get_leaking_objects objects None if objects is None gc collect objects gc get_objects try ids set id i for i in objects for i in objects ids difference_update id j for j in gc get_referents i return [i for i in objects if id i in ids ]finally del objects i | 56 |
python-test-3682 | python | What do objects not have ? | any referents | def get leaking objects objects None if objects is None gc collect objects gc get objects try ids set id i for i in objects for i in objects ids difference update id j for j in gc get referents i return [i for i in objects if id i in ids ]finally del objects i | def get_leaking_objects objects None if objects is None gc collect objects gc get_objects try ids set id i for i in objects for i in objects ids difference_update id j for j in gc get_referents i return [i for i in objects if id i in ids ]finally del objects i | 56 |
python-test-3683 | python | What do not have any referents ? | objects | def get leaking objects objects None if objects is None gc collect objects gc get objects try ids set id i for i in objects for i in objects ids difference update id j for j in gc get referents i return [i for i in objects if id i in ids ]finally del objects i | def get_leaking_objects objects None if objects is None gc collect objects gc get_objects try ids set id i for i in objects for i in objects ids difference_update id j for j in gc get_referents i return [i for i in objects if id i in ids ]finally del objects i | 56 |
python-test-3685 | python | What does the code setup ? | the z - wave platform | def setup platform hass config add devices discovery info None if discovery info is None or zwave NETWORK is None returnnode zwave NETWORK nodes[discovery info[zwave const ATTR NODE ID]]value node values[discovery info[zwave const ATTR VALUE ID]]if not node has command class zwave const COMMAND CLASS SWITCH BINARY retu... | def setup_platform hass config add_devices discovery_info None if discovery_info is None or zwave NETWORK is None returnnode zwave NETWORK nodes[discovery_info[zwave const ATTR_NODE_ID]]value node values[discovery_info[zwave const ATTR_VALUE_ID]]if not node has_command_class zwave const COMMAND_CLASS_SWITCH_BINARY retu... | 73 |
python-test-3686 | python | How did the code read an image ? | using qts qimage | def imread qt filename qtimg Q Image if not qtimg load filename raise IO Error ' Unabletoloadfile%s' % filename if qtimg depth 1 raise IO Error '1 -bitimagescurrentlynotsupported' arrayptr qtimg bits bytes per pixel qtimg depth // 8 pixels per line qtimg bytes Per Line // bytes per pixel img size pixels per line * qtim... | def imread_qt filename qtimg QImage if not qtimg load filename raise IOError 'Unabletoloadfile%s' % filename if qtimg depth 1 raise IOError '1-bitimagescurrentlynotsupported' arrayptr qtimg bits bytes_per_pixel qtimg depth // 8 pixels_per_line qtimg bytesPerLine // bytes_per_pixel img_size pixels_per_line * qtimg heigh... | 131 |
python-test-3687 | python | What do an image use ? | qts qimage | def imread qt filename qtimg Q Image if not qtimg load filename raise IO Error ' Unabletoloadfile%s' % filename if qtimg depth 1 raise IO Error '1 -bitimagescurrentlynotsupported' arrayptr qtimg bits bytes per pixel qtimg depth // 8 pixels per line qtimg bytes Per Line // bytes per pixel img size pixels per line * qtim... | def imread_qt filename qtimg QImage if not qtimg load filename raise IOError 'Unabletoloadfile%s' % filename if qtimg depth 1 raise IOError '1-bitimagescurrentlynotsupported' arrayptr qtimg bits bytes_per_pixel qtimg depth // 8 pixels_per_line qtimg bytesPerLine // bytes_per_pixel img_size pixels_per_line * qtimg heigh... | 131 |
python-test-3691 | python | How do preprocess call on the cluster ? | via cluster_jobs_script | def preprocess on cluster sff fps log fp fasta fp None out fp '/tmp/' squeeze False verbose False primer STANDARD BACTERIAL PRIMER cmd 'denoiser preprocess py-i%s-l%s-o%s' % ' ' join sff fps log fp out fp if fasta fp cmd + '-f%s' % fasta fp if squeeze cmd + '-s'if verbose cmd + '-v'if primer cmd + '-p%s' % primer submi... | def preprocess_on_cluster sff_fps log_fp fasta_fp None out_fp '/tmp/' squeeze False verbose False primer STANDARD_BACTERIAL_PRIMER cmd 'denoiser_preprocess py-i%s-l%s-o%s' % ' ' join sff_fps log_fp out_fp if fasta_fp cmd + '-f%s' % fasta_fp if squeeze cmd + '-s'if verbose cmd + '-v'if primer cmd + '-p%s' % primer submi... | 80 |
python-test-3692 | python | What calls on the cluster ? | preprocess | def preprocess on cluster sff fps log fp fasta fp None out fp '/tmp/' squeeze False verbose False primer STANDARD BACTERIAL PRIMER cmd 'denoiser preprocess py-i%s-l%s-o%s' % ' ' join sff fps log fp out fp if fasta fp cmd + '-f%s' % fasta fp if squeeze cmd + '-s'if verbose cmd + '-v'if primer cmd + '-p%s' % primer submi... | def preprocess_on_cluster sff_fps log_fp fasta_fp None out_fp '/tmp/' squeeze False verbose False primer STANDARD_BACTERIAL_PRIMER cmd 'denoiser_preprocess py-i%s-l%s-o%s' % ' ' join sff_fps log_fp out_fp if fasta_fp cmd + '-f%s' % fasta_fp if squeeze cmd + '-s'if verbose cmd + '-v'if primer cmd + '-p%s' % primer submi... | 80 |
python-test-3693 | python | Where do preprocess call via cluster_jobs_script ? | on the cluster | def preprocess on cluster sff fps log fp fasta fp None out fp '/tmp/' squeeze False verbose False primer STANDARD BACTERIAL PRIMER cmd 'denoiser preprocess py-i%s-l%s-o%s' % ' ' join sff fps log fp out fp if fasta fp cmd + '-f%s' % fasta fp if squeeze cmd + '-s'if verbose cmd + '-v'if primer cmd + '-p%s' % primer submi... | def preprocess_on_cluster sff_fps log_fp fasta_fp None out_fp '/tmp/' squeeze False verbose False primer STANDARD_BACTERIAL_PRIMER cmd 'denoiser_preprocess py-i%s-l%s-o%s' % ' ' join sff_fps log_fp out_fp if fasta_fp cmd + '-f%s' % fasta_fp if squeeze cmd + '-s'if verbose cmd + '-v'if primer cmd + '-p%s' % primer submi... | 80 |
python-test-3698 | python | What does the code take ? | a soundcloud track item | def format track track show url True out track['title']out + 'by\x 02 {}\x 02 ' format track['user']['username'] if track['genre'] out + '-\x 02 {}\x 02 ' format track['genre'] out + '-\x 02 { }\x 02 plays \x 02 { }\x 02 favorites \x 02 { }\x 02 comments' format track['playback count'] track['favoritings count'] track[... | def format_track track show_url True out track['title']out + 'by\x02{}\x02' format track['user']['username'] if track['genre'] out + '-\x02{}\x02' format track['genre'] out + '-\x02{ }\x02plays \x02{ }\x02favorites \x02{ }\x02comments' format track['playback_count'] track['favoritings_count'] track['comment_count'] if ... | 69 |
python-test-3700 | python | What described in rfc 4021 ? | the mailing list headers | def parse ml headers headers attrs {}attrs[' List- Archive'] headers get ' List- Archive' attrs[' List- Help'] headers get ' List- Help' attrs[' List- Id'] headers get ' List- Id' attrs[' List- Owner'] headers get ' List- Owner' attrs[' List- Post'] headers get ' List- Post' attrs[' List- Subscribe'] headers get ' List... | def parse_ml_headers headers attrs {}attrs['List-Archive'] headers get 'List-Archive' attrs['List-Help'] headers get 'List-Help' attrs['List-Id'] headers get 'List-Id' attrs['List-Owner'] headers get 'List-Owner' attrs['List-Post'] headers get 'List-Post' attrs['List-Subscribe'] headers get 'List-Subscribe' attrs['List... | 64 |
python-test-3701 | python | Where did the mailing list headers describe ? | in rfc 4021 | def parse ml headers headers attrs {}attrs[' List- Archive'] headers get ' List- Archive' attrs[' List- Help'] headers get ' List- Help' attrs[' List- Id'] headers get ' List- Id' attrs[' List- Owner'] headers get ' List- Owner' attrs[' List- Post'] headers get ' List- Post' attrs[' List- Subscribe'] headers get ' List... | def parse_ml_headers headers attrs {}attrs['List-Archive'] headers get 'List-Archive' attrs['List-Help'] headers get 'List-Help' attrs['List-Id'] headers get 'List-Id' attrs['List-Owner'] headers get 'List-Owner' attrs['List-Post'] headers get 'List-Post' attrs['List-Subscribe'] headers get 'List-Subscribe' attrs['List... | 64 |
python-test-3702 | python | How does the code grab a list of all the fonts that are being tracked by fontconfig ? | by making a system call to fc - list | def get fontconfig fonts fontext 'ttf' try import commandsexcept Import Error return {}fontext get fontext synonyms fontext fontfiles {} status output commands getstatusoutput 'fc-listfile' if status 0 for line in output split '\n' fname line split ' ' [0 ]if os path splitext fname [1 ][ 1 ] in fontext and os path exis... | def get_fontconfig_fonts fontext 'ttf' try import commandsexcept ImportError return {}fontext get_fontext_synonyms fontext fontfiles {} status output commands getstatusoutput 'fc-listfile' if status 0 for line in output split '\n' fname line split ' ' [0]if os path splitext fname [1][1 ] in fontext and os path exists f... | 58 |
python-test-3703 | python | What does the code grab by making a system call to fc - list ? | a list of all the fonts that are being tracked by fontconfig | def get fontconfig fonts fontext 'ttf' try import commandsexcept Import Error return {}fontext get fontext synonyms fontext fontfiles {} status output commands getstatusoutput 'fc-listfile' if status 0 for line in output split '\n' fname line split ' ' [0 ]if os path splitext fname [1 ][ 1 ] in fontext and os path exis... | def get_fontconfig_fonts fontext 'ttf' try import commandsexcept ImportError return {}fontext get_fontext_synonyms fontext fontfiles {} status output commands getstatusoutput 'fc-listfile' if status 0 for line in output split '\n' fname line split ' ' [0]if os path splitext fname [1][1 ] in fontext and os path exists f... | 58 |
python-test-3706 | python | What does data load ? | out of the fips ecdsa keypair vector files | def load fips ecdsa key pair vectors vector data vectors []key data Nonefor line in vector data line line strip if not line or line startswith '#' continueif line[ 1 -1 ] in ECDSA CURVE NAMES curve name ECDSA CURVE NAMES[line[ 1 -1 ]]elif line startswith 'd ' if key data is not None vectors append key data key data {'c... | def load_fips_ecdsa_key_pair_vectors vector_data vectors []key_data Nonefor line in vector_data line line strip if not line or line startswith '#' continueif line[1 -1 ] in _ECDSA_CURVE_NAMES curve_name _ECDSA_CURVE_NAMES[line[1 -1 ]]elif line startswith 'd ' if key_data is not None vectors append key_data key_data {'c... | 122 |
python-test-3709 | python | How did bokeh applications build ? | using single handlers | def build single handler applications paths argvs None applications {}argvs {} or argvs for path in paths application build single handler application path argvs get path [] route application handlers[ 0 ] url path if not route if '/' in applications raise Runtime Error " Don'tknowthe UR Lpathtousefor%s" % path route '... | def build_single_handler_applications paths argvs None applications {}argvs {} or argvs for path in paths application build_single_handler_application path argvs get path [] route application handlers[0] url_path if not route if '/' in applications raise RuntimeError "Don'tknowtheURLpathtousefor%s" % path route '/'appl... | 54 |
python-test-3711 | python | Where did directories find ? | in < path > | def create files paths chroot dirs files set set for path in paths path osp join chroot path filename osp basename path if filename '' dirs add path else dirs add osp dirname path files add path for dirpath in dirs if not osp isdir dirpath os makedirs dirpath for filepath in files open filepath 'w' close | def create_files paths chroot dirs files set set for path in paths path osp join chroot path filename osp basename path if filename '' dirs add path else dirs add osp dirname path files add path for dirpath in dirs if not osp isdir dirpath os makedirs dirpath for filepath in files open filepath 'w' close | 57 |
python-test-3712 | python | What does the code generate ? | a selectfield consisting of the current list of tool dependency ids for an installed tool shed repository | def build tool dependencies select field app tool shed repository name multiple True display 'checkboxes' uninstalled only False tool dependencies select field Select Field name name multiple multiple display display for tool dependency in tool shed repository tool dependencies if uninstalled only if tool dependency st... | def build_tool_dependencies_select_field app tool_shed_repository name multiple True display 'checkboxes' uninstalled_only False tool_dependencies_select_field SelectField name name multiple multiple display display for tool_dependency in tool_shed_repository tool_dependencies if uninstalled_only if tool_dependency sta... | 123 |
python-test-3714 | python | What does the code begin ? | sending the contents of this l{file } to the given request | def render file file request file restat False if file type is None file type file encoding get Type And Encoding file basename file content Types file content Encodings file default Type if not file exists return file child Not Found render request if file isdir return file redirect request request set Header 'accept-... | def _render_file file request file restat False if file type is None file type file encoding getTypeAndEncoding file basename file contentTypes file contentEncodings file defaultType if not file exists return file childNotFound render request if file isdir return file redirect request request setHeader 'accept-ranges' ... | 100 |
python-test-3715 | python | What does the code send to the given request ? | the contents of this l{file } | def render file file request file restat False if file type is None file type file encoding get Type And Encoding file basename file content Types file content Encodings file default Type if not file exists return file child Not Found render request if file isdir return file redirect request request set Header 'accept-... | def _render_file file request file restat False if file type is None file type file encoding getTypeAndEncoding file basename file contentTypes file contentEncodings file defaultType if not file exists return file childNotFound render request if file isdir return file redirect request request setHeader 'accept-ranges' ... | 100 |
python-test-3716 | python | What does the code add ? | user default | def add user permission doctype name user with message False if name not in frappe defaults get user permissions user get doctype [] if not frappe db exists doctype name frappe throw u'{ 0 }{ 1 }notfound' format doctype name frappe Does Not Exist Error frappe defaults add default doctype name user u' User Permission' e... | def add_user_permission doctype name user with_message False if name not in frappe defaults get_user_permissions user get doctype [] if not frappe db exists doctype name frappe throw _ u'{0}{1}notfound' format _ doctype name frappe DoesNotExistError frappe defaults add_default doctype name user u'UserPermission' elif w... | 61 |
python-test-3721 | python | What does futures testing data simulate ? | the notice / expiration date behavior of physical commodities like oil | def make commodity future info first sid root symbols years month codes None nineteen days pd Timedelta days 19 one year pd Timedelta days 365 return make future info first sid first sid root symbols root symbols years years notice date func lambda dt dt - Month Begin 2 + nineteen days expiration date func lambda dt dt... | def make_commodity_future_info first_sid root_symbols years month_codes None nineteen_days pd Timedelta days 19 one_year pd Timedelta days 365 return make_future_info first_sid first_sid root_symbols root_symbols years years notice_date_func lambda dt dt - MonthBegin 2 + nineteen_days expiration_date_func lambda dt dt ... | 78 |
python-test-3722 | python | What is testing data that simulates the notice / expiration date behavior of physical commodities like oil ? | futures | def make commodity future info first sid root symbols years month codes None nineteen days pd Timedelta days 19 one year pd Timedelta days 365 return make future info first sid first sid root symbols root symbols years years notice date func lambda dt dt - Month Begin 2 + nineteen days expiration date func lambda dt dt... | def make_commodity_future_info first_sid root_symbols years month_codes None nineteen_days pd Timedelta days 19 one_year pd Timedelta days 365 return make_future_info first_sid first_sid root_symbols root_symbols years years notice_date_func lambda dt dt - MonthBegin 2 + nineteen_days expiration_date_func lambda dt dt ... | 78 |
python-test-3723 | python | What do futures test ? | data that simulates the notice / expiration date behavior of physical commodities like oil | def make commodity future info first sid root symbols years month codes None nineteen days pd Timedelta days 19 one year pd Timedelta days 365 return make future info first sid first sid root symbols root symbols years years notice date func lambda dt dt - Month Begin 2 + nineteen days expiration date func lambda dt dt... | def make_commodity_future_info first_sid root_symbols years month_codes None nineteen_days pd Timedelta days 19 one_year pd Timedelta days 365 return make_future_info first_sid first_sid root_symbols root_symbols years years notice_date_func lambda dt dt - MonthBegin 2 + nineteen_days expiration_date_func lambda dt dt ... | 78 |
python-test-3724 | python | What simulates the notice / expiration date behavior of physical commodities like oil ? | futures testing data | def make commodity future info first sid root symbols years month codes None nineteen days pd Timedelta days 19 one year pd Timedelta days 365 return make future info first sid first sid root symbols root symbols years years notice date func lambda dt dt - Month Begin 2 + nineteen days expiration date func lambda dt dt... | def make_commodity_future_info first_sid root_symbols years month_codes None nineteen_days pd Timedelta days 19 one_year pd Timedelta days 365 return make_future_info first_sid first_sid root_symbols root_symbols years years notice_date_func lambda dt dt - MonthBegin 2 + nineteen_days expiration_date_func lambda dt dt ... | 78 |
python-test-3725 | python | What does the code create ? | a new permission grant for a resource | def create permission grant for resource db role db resource db permission types permission types validate permission types resource db resource db permission types permission types resource uid resource db get uid resource type resource db get resource type result create permission grant role db role db resource uid r... | def create_permission_grant_for_resource_db role_db resource_db permission_types permission_types _validate_permission_types resource_db resource_db permission_types permission_types resource_uid resource_db get_uid resource_type resource_db get_resource_type result create_permission_grant role_db role_db resource_uid ... | 61 |
python-test-3728 | python | In which direction does the code load a module and all its submodules ? | from a the given module path | def walk modules path load False mods []mod import path {} {} [''] mods append mod if hasattr mod ' path ' for subpath ispkg in iter modules mod path fullpath path + ' ' + subpath if ispkg mods + walk modules fullpath else submod import fullpath {} {} [''] mods append submod return mods | def walk_modules path load False mods []mod __import__ path {} {} [''] mods append mod if hasattr mod '__path__' for _ subpath ispkg in iter_modules mod __path__ fullpath path + ' ' + subpath if ispkg mods + walk_modules fullpath else submod __import__ fullpath {} {} [''] mods append submod return mods | 56 |
python-test-3730 | python | What does validation decorator delegate to the controller ? | error handling | def validate *simple vals **param vals def val fn @wraps fn def newfn self *a **env try kw make validated kw fn simple vals param vals env except Reddit Error as err self on validation error err for err in c errors self on validation error c errors[err] try return fn self *a **kw except Reddit Error as err self on vali... | def validate *simple_vals **param_vals def val fn @wraps fn def newfn self *a **env try kw _make_validated_kw fn simple_vals param_vals env except RedditError as err self on_validation_error err for err in c errors self on_validation_error c errors[err] try return fn self *a **kw except RedditError as err self on_valid... | 85 |
python-test-3731 | python | What delegates error handling to the controller ? | validation decorator | def validate *simple vals **param vals def val fn @wraps fn def newfn self *a **env try kw make validated kw fn simple vals param vals env except Reddit Error as err self on validation error err for err in c errors self on validation error c errors[err] try return fn self *a **kw except Reddit Error as err self on vali... | def validate *simple_vals **param_vals def val fn @wraps fn def newfn self *a **env try kw _make_validated_kw fn simple_vals param_vals env except RedditError as err self on_validation_error err for err in c errors self on_validation_error c errors[err] try return fn self *a **kw except RedditError as err self on_valid... | 85 |
python-test-3732 | python | What does the code write ? | a quantity of the target | def write Element Node derivation file Names target xml Object target xml Objectif xml Object None print ' Warning write Targetinwritecouldnotgetxml Objectfor 'print targetprint derivation element Nodereturnparser Directory os path dirname derivation element Node get Owner Document file Name absolute Folder Directory o... | def writeElementNode derivation fileNames target xmlObject target xmlObjectif xmlObject None print 'Warning writeTargetinwritecouldnotgetxmlObjectfor 'print targetprint derivation elementNodereturnparserDirectory os path dirname derivation elementNode getOwnerDocument fileName absoluteFolderDirectory os path abspath os... | 107 |
python-test-3739 | python | What does the code calculate ? | the minimums and maximums of the values of an array at labels | def extrema input labels None index None dims numpy array numpy asarray input shape dim prod numpy cumprod [1 ] + list dims[ 0 -1 ] [ -1 ] minimums min positions maximums max positions select input labels index find min True find max True find min positions True find max positions True if numpy isscalar minimums return... | def extrema input labels None index None dims numpy array numpy asarray input shape dim_prod numpy cumprod [1] + list dims[ 0 -1 ] [ -1 ] minimums min_positions maximums max_positions _select input labels index find_min True find_max True find_min_positions True find_max_positions True if numpy isscalar minimums return... | 117 |
python-test-3740 | python | What does the code setup ? | the samsung tv platform | def setup platform hass config add devices discovery info None known devices hass data get KNOWN DEVICES KEY if known devices is None known devices set hass data[KNOWN DEVICES KEY] known devicesif config get CONF HOST is not None host config get CONF HOST port config get CONF PORT name config get CONF NAME timeout conf... | def setup_platform hass config add_devices discovery_info None known_devices hass data get KNOWN_DEVICES_KEY if known_devices is None known_devices set hass data[KNOWN_DEVICES_KEY] known_devicesif config get CONF_HOST is not None host config get CONF_HOST port config get CONF_PORT name config get CONF_NAME timeout conf... | 137 |
python-test-3741 | python | What does the code run ? | the prebuilt version of letsencrypt - auto | def run le auto venv dir base url **kwargs env environ copy d dict XDG DATA HOME venv dir LE AUTO JSON URL base url + 'certbot/json' LE AUTO DIR TEMPLATE base url + '%s/' LE AUTO PUBLIC KEY '-----BEGINPUBLICKEY-----\n MIIB Ij AN Bgkqhki G 9 w 0 BAQEFAAOCAQ 8 AMIIB Cg KCAQE As Mo Sz LYQ 7 E 1 sd S Okwelg\ntz K Ih 2 qi 3... | def run_le_auto venv_dir base_url **kwargs env environ copy d dict XDG_DATA_HOME venv_dir LE_AUTO_JSON_URL base_url + 'certbot/json' LE_AUTO_DIR_TEMPLATE base_url + '%s/' LE_AUTO_PUBLIC_KEY '-----BEGINPUBLICKEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsMoSzLYQ7E1sdSOkwelg\ntzKIh2qi3bpXuYtcfFC0XrvWig071NwIj+dZi... | 240 |
python-test-3742 | python | What does the code see ? | find_boundaries | def find boundaries subpixel label img ndim label img ndimmax label np iinfo label img dtype maxlabel img expanded np zeros [ 2 * s - 1 for s in label img shape] label img dtype pixels [slice None None 2 ] * ndim label img expanded[pixels] label imgedges np ones label img expanded shape dtype bool edges[pixels] Falsela... | def _find_boundaries_subpixel label_img ndim label_img ndimmax_label np iinfo label_img dtype maxlabel_img_expanded np zeros [ 2 * s - 1 for s in label_img shape] label_img dtype pixels [slice None None 2 ] * ndim label_img_expanded[pixels] label_imgedges np ones label_img_expanded shape dtype bool edges[pixels] Falsel... | 109 |
python-test-3743 | python | What do a pen represent ? | the given wavelength | def wl Pen wl l1 400 l 2 700 hue np clip l2 - l1 - wl - l1 * 0 8 / l2 - l1 0 0 8 val 1 0if wl > 700 val 1 0 * 700 - wl / 700 0 + 1 elif wl < 400 val wl * 1 0 / 400 0 color pg hsv Color hue 1 0 val pen pg mk Pen color return pen | def wlPen wl l1 400l2 700hue np clip l2 - l1 - wl - l1 * 0 8 / l2 - l1 0 0 8 val 1 0if wl > 700 val 1 0 * 700 - wl / 700 0 + 1 elif wl < 400 val wl * 1 0 / 400 0 color pg hsvColor hue 1 0 val pen pg mkPen color return pen | 74 |
python-test-3744 | python | What is representing the given wavelength ? | a pen | def wl Pen wl l1 400 l 2 700 hue np clip l2 - l1 - wl - l1 * 0 8 / l2 - l1 0 0 8 val 1 0if wl > 700 val 1 0 * 700 - wl / 700 0 + 1 elif wl < 400 val wl * 1 0 / 400 0 color pg hsv Color hue 1 0 val pen pg mk Pen color return pen | def wlPen wl l1 400l2 700hue np clip l2 - l1 - wl - l1 * 0 8 / l2 - l1 0 0 8 val 1 0if wl > 700 val 1 0 * 700 - wl / 700 0 + 1 elif wl < 400 val wl * 1 0 / 400 0 color pg hsvColor hue 1 0 val pen pg mkPen color return pen | 74 |
python-test-3745 | python | What does the code check ? | the total return value of the run | def check state result running recurse False if not isinstance running dict return Falseif not running return Falseret Truefor state result in six itervalues running if not recurse and not isinstance state result dict ret Falseif ret and isinstance state result dict result state result get 'result' empty if result is F... | def check_state_result running recurse False if not isinstance running dict return Falseif not running return Falseret Truefor state_result in six itervalues running if not recurse and not isinstance state_result dict ret Falseif ret and isinstance state_result dict result state_result get 'result' _empty if result is ... | 77 |
python-test-3750 | python | What does the code generate ? | a thumbnail filename of the source filename and options separately hashed | def source hashed source filename prepared options thumbnail extension **kwargs source sha hashlib sha 1 source filename encode u'utf- 8 ' digest source hash base 64 urlsafe b64 encode source sha[ 9] decode u'utf- 8 ' parts u' ' join prepared options[ 1 ] parts sha hashlib sha 1 parts encode u'utf- 8 ' digest options h... | def source_hashed source_filename prepared_options thumbnail_extension **kwargs source_sha hashlib sha1 source_filename encode u'utf-8' digest source_hash base64 urlsafe_b64encode source_sha[ 9] decode u'utf-8' parts u' ' join prepared_options[1 ] parts_sha hashlib sha1 parts encode u'utf-8' digest options_hash base64 ... | 85 |
python-test-3751 | python | What does the code check before returning it ? | a response status | def checked response status code int response['status'][ 3] if status code 401 raise Unauthorizedif status code 406 raise No Sessionif status code 407 raise Download Limit Reachedif status code 413 raise Invalid Imdbidif status code 414 raise Unknown User Agentif status code 415 raise Disabled User Agentif status code ... | def checked response status_code int response['status'][ 3] if status_code 401 raise Unauthorizedif status_code 406 raise NoSessionif status_code 407 raise DownloadLimitReachedif status_code 413 raise InvalidImdbidif status_code 414 raise UnknownUserAgentif status_code 415 raise DisabledUserAgentif status_code 503 rais... | 63 |
python-test-3752 | python | When does the code check a response status ? | before returning it | def checked response status code int response['status'][ 3] if status code 401 raise Unauthorizedif status code 406 raise No Sessionif status code 407 raise Download Limit Reachedif status code 413 raise Invalid Imdbidif status code 414 raise Unknown User Agentif status code 415 raise Disabled User Agentif status code ... | def checked response status_code int response['status'][ 3] if status_code 401 raise Unauthorizedif status_code 406 raise NoSessionif status_code 407 raise DownloadLimitReachedif status_code 413 raise InvalidImdbidif status_code 414 raise UnknownUserAgentif status_code 415 raise DisabledUserAgentif status_code 503 rais... | 63 |
python-test-3756 | python | Where do the installable changeset_revision return after the changeset to which after_changeset_revision refers ? | in the repository changelog | def get next downloadable changeset revision repository repo after changeset revision changeset revisions [revision[ 1 ] for revision in get metadata revisions repository repo ]if len changeset revisions 1 changeset revision changeset revisions[ 0 ]if changeset revision after changeset revision return after changeset r... | def get_next_downloadable_changeset_revision repository repo after_changeset_revision changeset_revisions [revision[1] for revision in get_metadata_revisions repository repo ]if len changeset_revisions 1 changeset_revision changeset_revisions[0]if changeset_revision after_changeset_revision return after_changeset_revis... | 89 |
python-test-3757 | python | When do the installable changeset_revision return in the repository changelog ? | after the changeset to which after_changeset_revision refers | def get next downloadable changeset revision repository repo after changeset revision changeset revisions [revision[ 1 ] for revision in get metadata revisions repository repo ]if len changeset revisions 1 changeset revision changeset revisions[ 0 ]if changeset revision after changeset revision return after changeset r... | def get_next_downloadable_changeset_revision repository repo after_changeset_revision changeset_revisions [revision[1] for revision in get_metadata_revisions repository repo ]if len changeset_revisions 1 changeset_revision changeset_revisions[0]if changeset_revision after_changeset_revision return after_changeset_revis... | 89 |
python-test-3758 | python | What returns in the repository changelog ? | the installable changeset_revision | def get next downloadable changeset revision repository repo after changeset revision changeset revisions [revision[ 1 ] for revision in get metadata revisions repository repo ]if len changeset revisions 1 changeset revision changeset revisions[ 0 ]if changeset revision after changeset revision return after changeset r... | def get_next_downloadable_changeset_revision repository repo after_changeset_revision changeset_revisions [revision[1] for revision in get_metadata_revisions repository repo ]if len changeset_revisions 1 changeset_revision changeset_revisions[0]if changeset_revision after_changeset_revision return after_changeset_revis... | 89 |
python-test-3761 | python | What returns over ? | num evenly spaced values | def linspace start stop num 50 chunks None dtype None num int num if chunks is None raise Value Error ' Mustsupplyachunks keywordargument' chunks normalize chunks chunks num range stop - start space float range / num - 1 if dtype is None dtype np linspace 0 1 1 dtypename 'linspace-' + tokenize start stop num chunks dty... | def linspace start stop num 50 chunks None dtype None num int num if chunks is None raise ValueError 'Mustsupplyachunks keywordargument' chunks normalize_chunks chunks num range_ stop - start space float range_ / num - 1 if dtype is None dtype np linspace 0 1 1 dtypename 'linspace-' + tokenize start stop num chunks dty... | 102 |
python-test-3765 | python | What does the code perform ? | a click on a css selector | @world absorbdef css click css selector index 0 wait time GLOBAL WAIT FOR TIMEOUT dismiss alert False wait for clickable css selector timeout wait time wait for visible css selector index index timeout wait time assert true css visible css selector index index msg ' Element{}[{}]ispresentbutnotvisible' format css selec... | @world absorbdef css_click css_selector index 0 wait_time GLOBAL_WAIT_FOR_TIMEOUT dismiss_alert False wait_for_clickable css_selector timeout wait_time wait_for_visible css_selector index index timeout wait_time assert_true css_visible css_selector index index msg 'Element{}[{}]ispresentbutnotvisible' format css_select... | 75 |
python-test-3766 | python | What does the code get ? | horizontal segment lists inside loops | def get Horizontal Segment Lists From Loop Lists already Filled Arounds front number Of Lines rotated Fill Loops width x Intersection Index Lists []y List []front Over Width get Front Over Width Add X List Y List front already Filled Arounds number Of Lines x Intersection Index Lists width y List add X Intersection Ind... | def getHorizontalSegmentListsFromLoopLists alreadyFilledArounds front numberOfLines rotatedFillLoops width xIntersectionIndexLists []yList []frontOverWidth getFrontOverWidthAddXListYList front alreadyFilledArounds numberOfLines xIntersectionIndexLists width yList addXIntersectionIndexesFromLoops frontOverWidth rotatedF... | 126 |
python-test-3768 | python | What is making code for several helper functions ? | common link | def link to text *args **kwargs assert len args < 2 ' Toomanyunnamedarguments'def link class kwargs 'createsclassesforthelink tocalls'suppress active class kwargs pop 'suppress active class' False if not suppress active class and link active kwargs active 'active'else active ''kwargs pop 'highlight actions' '' return k... | def _link_to text *args **kwargs assert len args < 2 'Toomanyunnamedarguments'def _link_class kwargs 'createsclassesforthelink_tocalls'suppress_active_class kwargs pop 'suppress_active_class' False if not suppress_active_class and _link_active kwargs active 'active'else active ''kwargs pop 'highlight_actions' '' return... | 109 |
python-test-3769 | python | What do common link make ? | code for several helper functions | def link to text *args **kwargs assert len args < 2 ' Toomanyunnamedarguments'def link class kwargs 'createsclassesforthelink tocalls'suppress active class kwargs pop 'suppress active class' False if not suppress active class and link active kwargs active 'active'else active ''kwargs pop 'highlight actions' '' return k... | def _link_to text *args **kwargs assert len args < 2 'Toomanyunnamedarguments'def _link_class kwargs 'createsclassesforthelink_tocalls'suppress_active_class kwargs pop 'suppress_active_class' False if not suppress_active_class and _link_active kwargs active 'active'else active ''kwargs pop 'highlight_actions' '' return... | 109 |
python-test-3772 | python | How does the code populate the database ? | with sample data | @click command @click option '-f' '--filename' help ' Fixtures JSO Npath' default ' /etc/fixtures/initial data json' @click option '-b' '--baseurl' help 'baseurltouse' default None @click option '--reset/--no-reset' default False def populate filename baseurl None reset False populator Populate db filepath filename bas... | @click command @click option '-f' '--filename' help 'FixturesJSONpath' default ' /etc/fixtures/initial_data json' @click option '-b' '--baseurl' help 'baseurltouse' default None @click option '--reset/--no-reset' default False def populate filename baseurl None reset False populator Populate db filepath filename baseur... | 70 |
python-test-3781 | python | What does the code compute ? | the indefinite integral of f in k[x ] | def dup integrate f m K if m < 0 or not f return fg [K zero] * m for i c in enumerate reversed f n i + 1 for j in range 1 m n * i + j + 1 g insert 0 K exquo c K n return g | def dup_integrate f m K if m < 0 or not f return fg [K zero] * m for i c in enumerate reversed f n i + 1 for j in range 1 m n * i + j + 1 g insert 0 K exquo c K n return g | 53 |
python-test-3785 | python | What does the code get ? | the list of yum repositories | def repolist status '' media None manager MANAGE Rwith settings hide 'running' 'stdout' if media repos run as root "% manager srepolist% status s sed'$d' sed-n'/repoid/ $p'" % locals else repos run as root "% manager srepolist% status s sed'/ Media\\ Debug/d' sed'$d' sed-n'/repoid/ $p'" % locals return map lambda line ... | def repolist status '' media None manager MANAGERwith settings hide 'running' 'stdout' if media repos run_as_root "% manager srepolist% status s sed'$d' sed-n'/repoid/ $p'" % locals else repos run_as_root "% manager srepolist% status s sed'/Media\\ Debug/d' sed'$d' sed-n'/repoid/ $p'" % locals return map lambda line li... | 60 |
python-test-3787 | python | What does the code check ? | state - space matrices | def abcd normalize A None B None C None D None A B C D map atleast 2d or none A B C D MA NA shape or none A MB NB shape or none B MC NC shape or none C MD ND shape or none D p choice not none MA MB NC q choice not none NB ND r choice not none MC MD if p is None or q is None or r is None raise Value Error ' Notenoughinf... | def abcd_normalize A None B None C None D None A B C D map _atleast_2d_or_none A B C D MA NA _shape_or_none A MB NB _shape_or_none B MC NC _shape_or_none C MD ND _shape_or_none D p _choice_not_none MA MB NC q _choice_not_none NB ND r _choice_not_none MC MD if p is None or q is None or r is None raise ValueError 'Noteno... | 123 |
python-test-3791 | python | What do the average of relaxed variables have ? | var_name_suffix | def relaxed average var name suffix rx step relaxed vars []for l in xrange rx step with tf variable scope 'RX%d' % l reuse True try relaxed vars append tf get variable var name suffix except Value Error passdsum tf add n relaxed vars avg dsum / len relaxed vars diff [ v - avg for v in relaxed vars]davg tf add n [ d * d... | def relaxed_average var_name_suffix rx_step relaxed_vars []for l in xrange rx_step with tf variable_scope 'RX%d' % l reuse True try relaxed_vars append tf get_variable var_name_suffix except ValueError passdsum tf add_n relaxed_vars avg dsum / len relaxed_vars diff [ v - avg for v in relaxed_vars]davg tf add_n [ d * d ... | 77 |
python-test-3792 | python | What is having var_name_suffix ? | the average of relaxed variables | def relaxed average var name suffix rx step relaxed vars []for l in xrange rx step with tf variable scope 'RX%d' % l reuse True try relaxed vars append tf get variable var name suffix except Value Error passdsum tf add n relaxed vars avg dsum / len relaxed vars diff [ v - avg for v in relaxed vars]davg tf add n [ d * d... | def relaxed_average var_name_suffix rx_step relaxed_vars []for l in xrange rx_step with tf variable_scope 'RX%d' % l reuse True try relaxed_vars append tf get_variable var_name_suffix except ValueError passdsum tf add_n relaxed_vars avg dsum / len relaxed_vars diff [ v - avg for v in relaxed_vars]davg tf add_n [ d * d ... | 77 |
python-test-3793 | python | What does the code calculate ? | the average of relaxed variables having var_name_suffix | def relaxed average var name suffix rx step relaxed vars []for l in xrange rx step with tf variable scope 'RX%d' % l reuse True try relaxed vars append tf get variable var name suffix except Value Error passdsum tf add n relaxed vars avg dsum / len relaxed vars diff [ v - avg for v in relaxed vars]davg tf add n [ d * d... | def relaxed_average var_name_suffix rx_step relaxed_vars []for l in xrange rx_step with tf variable_scope 'RX%d' % l reuse True try relaxed_vars append tf get_variable var_name_suffix except ValueError passdsum tf add_n relaxed_vars avg dsum / len relaxed_vars diff [ v - avg for v in relaxed_vars]davg tf add_n [ d * d ... | 77 |
python-test-3798 | python | What does the code receive ? | a raw bson message or raise socket | def receive message sock operation request id max message size MAX MESSAGE SIZE header receive data on socket sock 16 length UNPACK INT header[ 4] [0 ]actual op UNPACK INT header[ 12 ] [0 ]if operation actual op raise Protocol Error ' Gotopcode%rbutexpected%r' % actual op operation if request id is not None response id... | def receive_message sock operation request_id max_message_size MAX_MESSAGE_SIZE header _receive_data_on_socket sock 16 length _UNPACK_INT header[ 4] [0]actual_op _UNPACK_INT header[12 ] [0]if operation actual_op raise ProtocolError 'Gotopcode%rbutexpected%r' % actual_op operation if request_id is not None response_id _... | 121 |
python-test-3800 | python | What does the code remove ? | dependencies having the link_dependency attribute from the none targets | def Remove Link Dependencies From None Targets targets for target name target dict in targets iteritems for dependency key in dependency sections dependencies target dict get dependency key [] if dependencies for t in dependencies if target dict get 'type' None 'none' if targets[t] get 'variables' {} get 'link dependen... | def RemoveLinkDependenciesFromNoneTargets targets for target_name target_dict in targets iteritems for dependency_key in dependency_sections dependencies target_dict get dependency_key [] if dependencies for t in dependencies if target_dict get 'type' None 'none' if targets[t] get 'variables' {} get 'link_dependency' 0... | 59 |
python-test-3802 | python | What read in pgn_file ? | chess games | def chess pgn graph pgn file 'chess masters WCC pgn bz 2 ' import bz 2 G nx Multi Di Graph game {}datafile bz 2 BZ 2 File pgn file lines line decode rstrip '\r\n' for line in datafile for line in lines if line startswith '[' tag value line[ 1 -1 ] split '' 1 game[str tag ] value strip '"' elif game white game pop ' Whi... | def chess_pgn_graph pgn_file 'chess_masters_WCC pgn bz2' import bz2G nx MultiDiGraph game {}datafile bz2 BZ2File pgn_file lines line decode rstrip '\r\n' for line in datafile for line in lines if line startswith '[' tag value line[1 -1 ] split '' 1 game[str tag ] value strip '"' elif game white game pop 'White' black g... | 83 |
python-test-3803 | python | Where did chess games read in pgn format ? | in pgn_file | def chess pgn graph pgn file 'chess masters WCC pgn bz 2 ' import bz 2 G nx Multi Di Graph game {}datafile bz 2 BZ 2 File pgn file lines line decode rstrip '\r\n' for line in datafile for line in lines if line startswith '[' tag value line[ 1 -1 ] split '' 1 game[str tag ] value strip '"' elif game white game pop ' Whi... | def chess_pgn_graph pgn_file 'chess_masters_WCC pgn bz2' import bz2G nx MultiDiGraph game {}datafile bz2 BZ2File pgn_file lines line decode rstrip '\r\n' for line in datafile for line in lines if line startswith '[' tag value line[1 -1 ] split '' 1 game[str tag ] value strip '"' elif game white game pop 'White' black g... | 83 |
python-test-3804 | python | How did chess games read in pgn_file ? | in pgn format | def chess pgn graph pgn file 'chess masters WCC pgn bz 2 ' import bz 2 G nx Multi Di Graph game {}datafile bz 2 BZ 2 File pgn file lines line decode rstrip '\r\n' for line in datafile for line in lines if line startswith '[' tag value line[ 1 -1 ] split '' 1 game[str tag ] value strip '"' elif game white game pop ' Whi... | def chess_pgn_graph pgn_file 'chess_masters_WCC pgn bz2' import bz2G nx MultiDiGraph game {}datafile bz2 BZ2File pgn_file lines line decode rstrip '\r\n' for line in datafile for line in lines if line startswith '[' tag value line[1 -1 ] split '' 1 game[str tag ] value strip '"' elif game white game pop 'White' black g... | 83 |
python-test-3805 | python | For what purpose does the main help menu modify ? | to handle all registered help files | def Set Help Menu Other Help main Menu global help ID Mapif help ID Map is None help ID Map {}cmd ID win 32 ui ID HELP OTHE Rexclude List [' Main Python Documentation' ' Pythonwin Reference']first List List All Help Files exclude Fnames []for desc fname in first List if desc in exclude List exclude Fnames append fname ... | def SetHelpMenuOtherHelp mainMenu global helpIDMapif helpIDMap is None helpIDMap {}cmdID win32ui ID_HELP_OTHERexcludeList ['MainPythonDocumentation' 'PythonwinReference']firstList ListAllHelpFiles excludeFnames []for desc fname in firstList if desc in excludeList excludeFnames append fname helpDescs []for desc fname in... | 195 |
python-test-3815 | python | What does the code add ? | a package lock | def add lock packages **kwargs locks list locks added []try packages list salt ['pkg resource parse targets'] packages [0 ] keys except Minion Error as exc raise Command Execution Error exc for pkg in packages if not locks get pkg added append pkg if added zypper call 'al' *added return {'added' len added 'packages' ad... | def add_lock packages **kwargs locks list_locks added []try packages list __salt__['pkg_resource parse_targets'] packages [0] keys except MinionError as exc raise CommandExecutionError exc for pkg in packages if not locks get pkg added append pkg if added __zypper__ call 'al' *added return {'added' len added 'packages'... | 55 |
python-test-3822 | python | What does a user have ? | access to a local site | @simple decoratordef check local site access view func def check request local site name None *args **kwargs if local site name if not request local site raise Http 404 local site request local siteif not local site is accessible by request user if local site public or request user is authenticated response render to r... | @simple_decoratordef check_local_site_access view_func def _check request local_site_name None *args **kwargs if local_site_name if not request local_site raise Http404local_site request local_siteif not local_site is_accessible_by request user if local_site public or request user is_authenticated response render_to_re... | 96 |
python-test-3829 | python | For what purpose do teams @note currently ? | for development / testing / demo purposes only | def group def prep r if r interactive or r representation 'aadata' resource r resourcelist fields ['name' 'description' 'team status team status id' 'comments']resource configure list fields list fields if r interactive from s3 import S3 SQL Custom Form S3 SQL Inline Componentcrud fields ['name' 'description' S3 SQL In... | def group def prep r if r interactive or r representation 'aadata' resource r resourcelist_fields ['name' 'description' 'team_status_team status_id' 'comments']resource configure list_fields list_fields if r interactive from s3 import S3SQLCustomForm S3SQLInlineComponentcrud_fields ['name' 'description' S3SQLInlineComp... | 90 |
python-test-3831 | python | For what purpose did the code read the hc file ? | to get the hpi info and to prepare for coord trans | def read hc directory fname make ctf name directory 'hc' raise error False if fname is None logger info 'hcdatanotpresent' return Nones list with open fname 'rb' as fid while True p read one coil point fid if p is None if len s 0 logger info 'hcfileempty nodatapresent' return Nonelogger info 'hcdataread ' return sif p[... | def _read_hc directory fname _make_ctf_name directory 'hc' raise_error False if fname is None logger info 'hcdatanotpresent' return Nones list with open fname 'rb' as fid while True p _read_one_coil_point fid if p is None if len s 0 logger info 'hcfileempty nodatapresent' return Nonelogger info 'hcdataread ' return sif... | 60 |
python-test-3832 | python | What did the code read to get the hpi info and to prepare for coord trans ? | the hc file | def read hc directory fname make ctf name directory 'hc' raise error False if fname is None logger info 'hcdatanotpresent' return Nones list with open fname 'rb' as fid while True p read one coil point fid if p is None if len s 0 logger info 'hcfileempty nodatapresent' return Nonelogger info 'hcdataread ' return sif p[... | def _read_hc directory fname _make_ctf_name directory 'hc' raise_error False if fname is None logger info 'hcdatanotpresent' return Nones list with open fname 'rb' as fid while True p _read_one_coil_point fid if p is None if len s 0 logger info 'hcfileempty nodatapresent' return Nonelogger info 'hcdataread ' return sif... | 60 |
python-test-3834 | python | What does the code run ? | a traffic processing step | def run traffic step emr connection step jobflow name wait True sleeptime 60 retries 1 **jobflow kw jobflowid add step emr connection step jobflow name **jobflow kw if not wait returnattempts 1exit state wait for step emr connection step jobflowid sleeptime while attempts < retries and exit state COMPLETED jobflowid ad... | def run_traffic_step emr_connection step jobflow_name wait True sleeptime 60 retries 1 **jobflow_kw jobflowid _add_step emr_connection step jobflow_name **jobflow_kw if not wait returnattempts 1exit_state _wait_for_step emr_connection step jobflowid sleeptime while attempts < retries and exit_state COMPLETED jobflowid ... | 96 |
python-test-3838 | python | What does the code ensure tool contain ? | at least one valid citation | def lint citations tool xml lint ctx root tool xml getroot citations root findall 'citations' if len citations > 1 lint ctx error ' Morethanonecitationsectionfound behaviorundefined ' returnif len citations 0 lint ctx warn ' Nocitationsfound consideraddingcitationstoyourtool ' returnvalid citations 0for citation in cit... | def lint_citations tool_xml lint_ctx root tool_xml getroot citations root findall 'citations' if len citations > 1 lint_ctx error 'Morethanonecitationsectionfound behaviorundefined ' returnif len citations 0 lint_ctx warn 'Nocitationsfound consideraddingcitationstoyourtool ' returnvalid_citations 0for citation in citat... | 104 |
python-test-3839 | python | What does the code get ? | snapshot of the desired version of the artifact artifactory_url url of artifactory instance repository snapshot repository in artifactory to retrieve artifact from | def get snapshot artifactory url repository group id artifact id packaging version snapshot version None target dir '/tmp' target file None classifier None username None password None log debug ' MODULEFUNCTION artifactory get snapshot artifactory url %s repository %s group id %s artifact id %s packaging %s version %s ... | def get_snapshot artifactory_url repository group_id artifact_id packaging version snapshot_version None target_dir '/tmp' target_file None classifier None username None password None log debug ' MODULEFUNCTION artifactory get_snapshot artifactory_url %s repository %s group_id %s artifact_id %s packaging %s version %s ... | 145 |
python-test-3841 | python | What does the code delete ? | a single demo exploration | def delete demo exploration id if not exp domain Exploration is demo exploration id exploration id raise Exception ' Invaliddemoexplorationid%s' % exploration id exploration get exploration by id exploration id strict False if not exploration logging info ' Explorationwithid%swasnotdeleted becauseitdoesnotexist ' % exp... | def delete_demo exploration_id if not exp_domain Exploration is_demo_exploration_id exploration_id raise Exception 'Invaliddemoexplorationid%s' % exploration_id exploration get_exploration_by_id exploration_id strict False if not exploration logging info 'Explorationwithid%swasnotdeleted becauseitdoesnotexist ' % explo... | 56 |
python-test-3843 | python | What did the code set ? | the xbox platform | def setup platform hass config add devices discovery info None from xboxapi import xbox apiapi xbox api Xbox Api config get CONF API KEY devices []for xuid in config get CONF XUID new device Xbox Sensor hass api xuid if new device success init devices append new device if len devices > 0 add devices devices else return... | def setup_platform hass config add_devices discovery_info None from xboxapi import xbox_apiapi xbox_api XboxApi config get CONF_API_KEY devices []for xuid in config get CONF_XUID new_device XboxSensor hass api xuid if new_device success_init devices append new_device if len devices > 0 add_devices devices else return F... | 59 |
python-test-3847 | python | What compute the expected cumulative distribution of the periodogram for the null hypothesis - i ? | cumulative distribution for the lomb - scargle periodogram | def lombscargle cdf z N normalization dH 1 dK 3 if dK - dH 2 raise Not Implemented Error ' Degreesoffreedom 2' Nk N - dK if normalization 'psd' return 1 - np exp - z elif normalization 'standard' return 1 - 1 + z ** -0 5 * Nk elif normalization 'model' return 1 - 1 - z ** 0 5 * Nk elif normalization 'log' return 1 - np... | def _lombscargle_cdf z N normalization dH 1 dK 3 if dK - dH 2 raise NotImplementedError 'Degreesoffreedom 2' Nk N - dK if normalization 'psd' return 1 - np exp - z elif normalization 'standard' return 1 - 1 + z ** -0 5 * Nk elif normalization 'model' return 1 - 1 - z ** 0 5 * Nk elif normalization 'log' return 1 - np e... | 88 |
python-test-3848 | python | What do cumulative distribution for the lomb - scargle periodogram compute ? | the expected cumulative distribution of the periodogram for the null hypothesis - i | def lombscargle cdf z N normalization dH 1 dK 3 if dK - dH 2 raise Not Implemented Error ' Degreesoffreedom 2' Nk N - dK if normalization 'psd' return 1 - np exp - z elif normalization 'standard' return 1 - 1 + z ** -0 5 * Nk elif normalization 'model' return 1 - 1 - z ** 0 5 * Nk elif normalization 'log' return 1 - np... | def _lombscargle_cdf z N normalization dH 1 dK 3 if dK - dH 2 raise NotImplementedError 'Degreesoffreedom 2' Nk N - dK if normalization 'psd' return 1 - np exp - z elif normalization 'standard' return 1 - 1 + z ** -0 5 * Nk elif normalization 'model' return 1 - 1 - z ** 0 5 * Nk elif normalization 'log' return 1 - np e... | 88 |
python-test-3854 | python | What does the code provide ? | the memory usage in bytes for the given process | def memory usage pid if pid 0 return 0 0 start time parameter time time 'memoryusage' status path '/proc/%s/status' % pid mem lines get lines status path ' Vm RSS ' ' Vm Size ' parameter try resident Size int mem lines[' Vm RSS '] split [1 ] * 1024 virtual Size int mem lines[' Vm Size '] split [1 ] * 1024 log runtime p... | def memory_usage pid if pid 0 return 0 0 start_time parameter time time 'memoryusage' status_path '/proc/%s/status' % pid mem_lines _get_lines status_path 'VmRSS ' 'VmSize ' parameter try residentSize int mem_lines['VmRSS '] split [1] * 1024 virtualSize int mem_lines['VmSize '] split [1] * 1024 _log_runtime parameter '... | 106 |
python-test-3855 | python | For what purpose does the code convert the background image to jpg ? | to reduce the file size | def convert background to jpg background url file path get path of temp url background url im Image open file path out im file path replace 'png' 'jpg' bg Image new 'RGB' im size 255 255 255 bg paste im 0 0 im bg save out im quality 55 return out im | def convert_background_to_jpg background_url file_path get_path_of_temp_url background_url im Image open file_path out_im file_path replace 'png' 'jpg' bg Image new 'RGB' im size 255 255 255 bg paste im 0 0 im bg save out_im quality 55 return out_im | 52 |
python-test-3856 | python | What does the code convert the background image to reduce the file size ? | to jpg | def convert background to jpg background url file path get path of temp url background url im Image open file path out im file path replace 'png' 'jpg' bg Image new 'RGB' im size 255 255 255 bg paste im 0 0 im bg save out im quality 55 return out im | def convert_background_to_jpg background_url file_path get_path_of_temp_url background_url im Image open file_path out_im file_path replace 'png' 'jpg' bg Image new 'RGB' im size 255 255 255 bg paste im 0 0 im bg save out_im quality 55 return out_im | 52 |
python-test-3857 | python | What does the code convert to jpg to reduce the file size ? | the background image | def convert background to jpg background url file path get path of temp url background url im Image open file path out im file path replace 'png' 'jpg' bg Image new 'RGB' im size 255 255 255 bg paste im 0 0 im bg save out im quality 55 return out im | def convert_background_to_jpg background_url file_path get_path_of_temp_url background_url im Image open file_path out_im file_path replace 'png' 'jpg' bg Image new 'RGB' im size 255 255 255 bg paste im 0 0 im bg save out_im quality 55 return out_im | 52 |
python-test-3860 | python | What does the code show ? | a directory listing | def ls dir None recurse False indent 0 dir dir or os getcwd fns os listdir dir fns sort for fn in fns full os path join dir fn if os path isdir full fn fn + '/' print '' * indent + fn if os path isdir full and recurse ls dir full recurse True indent indent + 2 | def ls dir None recurse False indent 0 dir dir or os getcwd fns os listdir dir fns sort for fn in fns full os path join dir fn if os path isdir full fn fn + '/' print '' * indent + fn if os path isdir full and recurse ls dir full recurse True indent indent + 2 | 60 |
python-test-3865 | python | What does the code send to a logfile ? | paramiko logs | def log to file filename level DEBUG l logging get Logger 'paramiko' if len l handlers > 0 returnl set Level level f open filename 'w' lh logging Stream Handler f lh set Formatter logging Formatter '% levelname - 3s[% asctime s % msecs 03 d]thr % threadid -3 d% name s % message s' '%Y%m%d-%H %M %S' l add Handler lh | def log_to_file filename level DEBUG l logging getLogger 'paramiko' if len l handlers > 0 returnl setLevel level f open filename 'w' lh logging StreamHandler f lh setFormatter logging Formatter '% levelname - 3s[% asctime s % msecs 03d]thr % _threadid -3d% name s % message s' '%Y%m%d-%H %M %S' l addHandler lh | 62 |
python-test-3866 | python | What will an element render for a source listing ? | line numbers | def make Line Numbers how Many width len str how Many labels [ '%*d' % width i for i in range 1 how Many + 1 ]p dom Element 'p' p set Attribute 'class' 'py-linenumber' t dom Text t data '\n' join labels + '\n' p append Child t return p | def _makeLineNumbers howMany width len str howMany labels [ '%*d' % width i for i in range 1 howMany + 1 ]p dom Element 'p' p setAttribute 'class' 'py-linenumber' t dom Text t data '\n' join labels + '\n' p appendChild t return p | 51 |
python-test-3870 | python | Where does the code enable a server ? | globally cli example | def server enable s name **connection args ret Trueserver server get s name **connection args if server is None return Falseif server get state 'ENABLED' return Truenitro connect **connection args if nitro is None return Falsetry NS Server enable nitro server except NS Nitro Error as error log debug 'netscalermoduleerr... | def server_enable s_name **connection_args ret Trueserver _server_get s_name **connection_args if server is None return Falseif server get_state 'ENABLED' return Truenitro _connect **connection_args if nitro is None return Falsetry NSServer enable nitro server except NSNitroError as error log debug 'netscalermoduleerro... | 63 |
python-test-3879 | python | What does helper function wrap ? | the execution of freebsd - update command | def wrapper orig pre '' post '' err None run args None **kwargs ret ''cmd cmd **kwargs cmd str '' join [x for x in pre cmd post orig ] if run args and isinstance run args dict res salt ['cmd run all'] cmd str **run args else res salt ['cmd run all'] cmd str if isinstance err dict for k v in six itermitems res err [k] v... | def _wrapper orig pre '' post '' err_ None run_args None **kwargs ret ''cmd _cmd **kwargs cmd_str '' join [x for x in pre cmd post orig ] if run_args and isinstance run_args dict res __salt__['cmd run_all'] cmd_str **run_args else res __salt__['cmd run_all'] cmd_str if isinstance err_ dict for k v in six itermitems res... | 120 |
python-test-3885 | python | When do the boot time return code in number of seconds ? | since the epoch began | def boot time time format None try b time int psutil boot time except Attribute Error b time int psutil boot time if time format b time datetime datetime fromtimestamp b time try return b time strftime time format except Type Error as exc raise Salt Invocation Error ' Invalidformatstring {0 }' format exc return b time | def boot_time time_format None try b_time int psutil boot_time except AttributeError b_time int psutil boot_time if time_format b_time datetime datetime fromtimestamp b_time try return b_time strftime time_format except TypeError as exc raise SaltInvocationError 'Invalidformatstring {0}' format exc return b_time | 57 |
python-test-3886 | python | How do the boot time return code since the epoch began ? | in number of seconds | def boot time time format None try b time int psutil boot time except Attribute Error b time int psutil boot time if time format b time datetime datetime fromtimestamp b time try return b time strftime time format except Type Error as exc raise Salt Invocation Error ' Invalidformatstring {0 }' format exc return b time | def boot_time time_format None try b_time int psutil boot_time except AttributeError b_time int psutil boot_time if time_format b_time datetime datetime fromtimestamp b_time try return b_time strftime time_format except TypeError as exc raise SaltInvocationError 'Invalidformatstring {0}' format exc return b_time | 57 |
python-test-3887 | python | What does the code return ? | a list of paths to all modules below the given directory | def find files root dir should include paths []is module lambda path path endswith ' py' for dir path dir names file names in os walk root dir new paths [os path join dir path file name for file name in file names]new paths filter is module new paths new paths filter should include new paths paths extend new paths retu... | def _find_files root_dir should_include paths []is_module lambda path path endswith ' py' for dir_path dir_names file_names in os walk root_dir new_paths [os path join dir_path file_name for file_name in file_names]new_paths filter is_module new_paths new_paths filter should_include new_paths paths extend new_paths ret... | 62 |
python-test-3888 | python | What does the code send ? | a notification about aggregate update | def notify about aggregate update context event suffix aggregate payload aggregate identifier aggregate payload get 'aggregate id' None if not aggregate identifier aggregate identifier aggregate payload get 'name' None if not aggregate identifier LOG debug ' Noaggregateidornamespecifiedforthisnotificationanditwillbeign... | def notify_about_aggregate_update context event_suffix aggregate_payload aggregate_identifier aggregate_payload get 'aggregate_id' None if not aggregate_identifier aggregate_identifier aggregate_payload get 'name' None if not aggregate_identifier LOG debug 'Noaggregateidornamespecifiedforthisnotificationanditwillbeigno... | 56 |
python-test-3893 | python | How did a list give ? | with possible repetitions of elements in it | def letter form to array form array form group a list array form[ ] new array []n 1symbols group symbolsfor i in range len a if i len a - 1 if a[i] a[ i - 1 ] if - a[i] in symbols new array append - a[i] - n else new array append a[i] n elif - a[i] in symbols new array append - a[i] -1 else new array append a[i] 1 retu... | def letter_form_to_array_form array_form group a list array_form[ ] new_array []n 1symbols group symbolsfor i in range len a if i len a - 1 if a[i] a[ i - 1 ] if - a[i] in symbols new_array append - a[i] - n else new_array append a[i] n elif - a[i] in symbols new_array append - a[i] -1 else new_array append a[i] 1 retu... | 105 |
python-test-3894 | python | What does this method convert ? | a list given with possible repetitions of elements in it | def letter form to array form array form group a list array form[ ] new array []n 1symbols group symbolsfor i in range len a if i len a - 1 if a[i] a[ i - 1 ] if - a[i] in symbols new array append - a[i] - n else new array append a[i] n elif - a[i] in symbols new array append - a[i] -1 else new array append a[i] 1 retu... | def letter_form_to_array_form array_form group a list array_form[ ] new_array []n 1symbols group symbolsfor i in range len a if i len a - 1 if a[i] a[ i - 1 ] if - a[i] in symbols new_array append - a[i] - n else new_array append a[i] n elif - a[i] in symbols new_array append - a[i] -1 else new_array append a[i] 1 retu... | 105 |
python-test-3901 | python | How do views protect ? | by providing oauth2 authentication out of the box | def protected resource scopes None validator cls O Auth 2 Validator server cls Server scopes scopes or [] def decorator view func @wraps view func def validate request *args **kwargs validator validator cls core O Auth Lib Core server cls validator valid oauthlib req core verify request request scopes scopes if valid r... | def protected_resource scopes None validator_cls OAuth2Validator server_cls Server _scopes scopes or [] def decorator view_func @wraps view_func def _validate request *args **kwargs validator validator_cls core OAuthLibCore server_cls validator valid oauthlib_req core verify_request request scopes _scopes if valid requ... | 70 |
python-test-3914 | python | What does the code save db to the path specified by root ? | books | def save to disk db ids root opts None callback None root opts length sanitize args root opts failures []for x in ids tb ''try failed id title save book to disk x db root opts length tb ' Requestedformatsnotavailable' except failed id title True x db title x index is id True tb traceback format exc if failed failures a... | def save_to_disk db ids root opts None callback None root opts length sanitize_args root opts failures []for x in ids tb ''try failed id title save_book_to_disk x db root opts length tb _ 'Requestedformatsnotavailable' except failed id title True x db title x index_is_id True tb traceback format_exc if failed failures ... | 77 |
python-test-3916 | python | What does the code ensure ? | that its possible to route the output type format by the suffix of the requested url | def test suffix formatter hug output format suffix {' js' hug output format json ' html' hug output format text} class Fake Request object path 'endpoint js'request Fake Request response Fake Request converted hug input format json formatter Bytes IO hug output format json {'name' 'name'} request response assert conver... | def test_suffix formatter hug output_format suffix {' js' hug output_format json ' html' hug output_format text} class FakeRequest object path 'endpoint js'request FakeRequest response FakeRequest converted hug input_format json formatter BytesIO hug output_format json {'name' 'name'} request response assert converted ... | 75 |
python-test-3917 | python | How do the output type format route ? | by the suffix of the requested url | def test suffix formatter hug output format suffix {' js' hug output format json ' html' hug output format text} class Fake Request object path 'endpoint js'request Fake Request response Fake Request converted hug input format json formatter Bytes IO hug output format json {'name' 'name'} request response assert conver... | def test_suffix formatter hug output_format suffix {' js' hug output_format json ' html' hug output_format text} class FakeRequest object path 'endpoint js'request FakeRequest response FakeRequest converted hug input_format json formatter BytesIO hug output_format json {'name' 'name'} request response assert converted ... | 75 |
python-test-3922 | python | What does airmon - ng use ? | to put a device into monitor mode | def enable monitor mode iface global RUN CONFI Gprint GR + '[+]' + W + 'enablingmonitormodeon%s ' % G + iface + W stdout flush call ['airmon-ng' 'start' iface] stdout DN stderr DN print 'done'RUN CONFIG IFACE TO TAKE DOWN get iface if RUN CONFIG TX POWER > 0 print GR + '[+]' + W + 'setting Txpowerto%s%s%s ' % G RUN CON... | def enable_monitor_mode iface global RUN_CONFIGprint GR + '[+]' + W + 'enablingmonitormodeon%s ' % G + iface + W stdout flush call ['airmon-ng' 'start' iface] stdout DN stderr DN print 'done'RUN_CONFIG IFACE_TO_TAKE_DOWN get_iface if RUN_CONFIG TX_POWER > 0 print GR + '[+]' + W + 'settingTxpowerto%s%s%s ' % G RUN_CONFI... | 95 |
python-test-3923 | python | What uses to put a device into monitor mode ? | airmon - ng | def enable monitor mode iface global RUN CONFI Gprint GR + '[+]' + W + 'enablingmonitormodeon%s ' % G + iface + W stdout flush call ['airmon-ng' 'start' iface] stdout DN stderr DN print 'done'RUN CONFIG IFACE TO TAKE DOWN get iface if RUN CONFIG TX POWER > 0 print GR + '[+]' + W + 'setting Txpowerto%s%s%s ' % G RUN CON... | def enable_monitor_mode iface global RUN_CONFIGprint GR + '[+]' + W + 'enablingmonitormodeon%s ' % G + iface + W stdout flush call ['airmon-ng' 'start' iface] stdout DN stderr DN print 'done'RUN_CONFIG IFACE_TO_TAKE_DOWN get_iface if RUN_CONFIG TX_POWER > 0 print GR + '[+]' + W + 'settingTxpowerto%s%s%s ' % G RUN_CONFI... | 95 |
python-test-3924 | python | How do mime - type determine ? | from file name | def Get Mime Type file name extension index file name rfind ' ' if extension index -1 extension ''else extension file name[ extension index + 1 ] lower if extension in EXTENSION BLACKLIST raise Invalid Attachment Type Error ' Extension%sisnotsupported ' % extension mime type EXTENSION MIME MAP get extension None if mim... | def _GetMimeType file_name extension_index file_name rfind ' ' if extension_index -1 extension ''else extension file_name[ extension_index + 1 ] lower if extension in EXTENSION_BLACKLIST raise InvalidAttachmentTypeError 'Extension%sisnotsupported ' % extension mime_type EXTENSION_MIME_MAP get extension None if mime_typ... | 61 |
python-test-3926 | python | What does the code setup ? | the logentries component | def setup hass config conf config[DOMAIN]token conf get CONF TOKEN le wh '{}{}' format DEFAULT HOST token def logentries event listener event ' Listenfornewmessagesonthebusandsendsthemto Logentries 'state event data get 'new state' if state is None returntry state state helper state as number state except Value Error s... | def setup hass config conf config[DOMAIN]token conf get CONF_TOKEN le_wh '{}{}' format DEFAULT_HOST token def logentries_event_listener event 'ListenfornewmessagesonthebusandsendsthemtoLogentries 'state event data get 'new_state' if state is None returntry _state state_helper state_as_number state except ValueError _st... | 110 |
python-test-3928 | python | Where do indexes miss ? | on sqlite and postgresql | def upgrade migrate engine if migrate engine name in 'sqlite' 'postgresql' for table name index name column names in INDEXES ensure index exists migrate engine table name index name column names elif migrate engine name 'mysql' ensure index removed migrate engine 'dns domains' 'project id' ensure index exists migrate e... | def upgrade migrate_engine if migrate_engine name in 'sqlite' 'postgresql' for table_name index_name column_names in INDEXES ensure_index_exists migrate_engine table_name index_name column_names elif migrate_engine name 'mysql' ensure_index_removed migrate_engine 'dns_domains' 'project_id' ensure_index_exists migrate_e... | 82 |
python-test-3929 | python | What does the code add ? | indexes missing on sqlite and postgresql | def upgrade migrate engine if migrate engine name in 'sqlite' 'postgresql' for table name index name column names in INDEXES ensure index exists migrate engine table name index name column names elif migrate engine name 'mysql' ensure index removed migrate engine 'dns domains' 'project id' ensure index exists migrate e... | def upgrade migrate_engine if migrate_engine name in 'sqlite' 'postgresql' for table_name index_name column_names in INDEXES ensure_index_exists migrate_engine table_name index_name column_names elif migrate_engine name 'mysql' ensure_index_removed migrate_engine 'dns_domains' 'project_id' ensure_index_exists migrate_e... | 82 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.