idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
7,200 | def env ( self ) : env_vars = os . environ . copy ( ) env_vars . update ( self . _env ) new_path = ":" . join ( self . _paths + [ env_vars [ "PATH" ] ] if "PATH" in env_vars else [ ] + self . _paths ) env_vars [ "PATH" ] = new_path for env_var in self . _env_drop : if env_var in env_vars : del env_vars [ env_var ] return env_vars | Dict of all environment variables that will be run with this command . | 126 | 14 |
7,201 | def ignore_errors ( self ) : new_command = copy . deepcopy ( self ) new_command . _ignore_errors = True return new_command | Return new command object that will not raise an exception when return code > 0 . | 33 | 16 |
7,202 | def with_env ( self , * * environment_variables ) : new_env_vars = { str ( var ) : str ( val ) for var , val in environment_variables . items ( ) } new_command = copy . deepcopy ( self ) new_command . _env . update ( new_env_vars ) return new_command | Return new Command object that will be run with additional environment variables . | 77 | 13 |
7,203 | def without_env ( self , environment_variable ) : new_command = copy . deepcopy ( self ) new_command . _env_drop . append ( str ( environment_variable ) ) return new_command | Return new Command object that will drop a specified environment variable if it is set . | 45 | 16 |
7,204 | def in_dir ( self , directory ) : new_command = copy . deepcopy ( self ) new_command . _directory = str ( directory ) return new_command | Return new Command object that will be run in specified directory . | 36 | 12 |
7,205 | def with_shell ( self ) : new_command = copy . deepcopy ( self ) new_command . _shell = True return new_command | Return new Command object that will be run using shell . | 31 | 11 |
7,206 | def with_trailing_args ( self , * arguments ) : new_command = copy . deepcopy ( self ) new_command . _trailing_args = [ str ( arg ) for arg in arguments ] return new_command | Return new Command object that will be run with specified trailing arguments . | 49 | 13 |
7,207 | def with_path ( self , path ) : new_command = copy . deepcopy ( self ) new_command . _paths . append ( str ( path ) ) return new_command | Return new Command object that will be run with a new addition to the PATH environment variable that will be fed to the command . | 40 | 25 |
7,208 | def pexpect ( self ) : import pexpect assert not self . _ignore_errors _check_directory ( self . directory ) arguments = self . arguments return pexpect . spawn ( arguments [ 0 ] , args = arguments [ 1 : ] , env = self . env , cwd = self . directory ) | Run command and return pexpect process object . | 67 | 10 |
7,209 | def run ( self ) : _check_directory ( self . directory ) with DirectoryContextManager ( self . directory ) : process = subprocess . Popen ( self . arguments , shell = self . _shell , env = self . env ) _ , _ = process . communicate ( ) returncode = process . returncode if returncode != 0 and not self . _ignore_errors : raise CommandError ( '"{0}" failed (err code {1})' . format ( self . __repr__ ( ) , returncode ) ) | Run command and wait until it finishes . | 113 | 8 |
7,210 | def primitive_structure_from_cif ( cif , parse_engine , symprec , site_tolerance ) : CifCleanWorkChain = WorkflowFactory ( 'codtools.cif_clean' ) # pylint: disable=invalid-name try : structure = cif . get_structure ( converter = parse_engine . value , site_tolerance = site_tolerance , store = False ) except exceptions . UnsupportedSpeciesError : return CifCleanWorkChain . exit_codes . ERROR_CIF_HAS_UNKNOWN_SPECIES except InvalidOccupationsError : return CifCleanWorkChain . exit_codes . ERROR_CIF_HAS_INVALID_OCCUPANCIES except Exception : # pylint: disable=broad-except return CifCleanWorkChain . exit_codes . ERROR_CIF_STRUCTURE_PARSING_FAILED try : seekpath_results = get_kpoints_path ( structure , symprec = symprec ) except ValueError : return CifCleanWorkChain . exit_codes . ERROR_SEEKPATH_INCONSISTENT_SYMMETRY except SymmetryDetectionError : return CifCleanWorkChain . exit_codes . ERROR_SEEKPATH_SYMMETRY_DETECTION_FAILED # Store important information that should be easily queryable as attributes in the StructureData parameters = seekpath_results [ 'parameters' ] . get_dict ( ) structure = seekpath_results [ 'primitive_structure' ] for key in [ 'spacegroup_international' , 'spacegroup_number' , 'bravais_lattice' , 'bravais_lattice_extended' ] : try : value = parameters [ key ] structure . set_extra ( key , value ) except KeyError : pass # Store the formula as a string, in both hill as well as hill-compact notation, so it can be easily queried for structure . set_extra ( 'formula_hill' , structure . get_formula ( mode = 'hill' ) ) structure . set_extra ( 'formula_hill_compact' , structure . get_formula ( mode = 'hill_compact' ) ) structure . set_extra ( 'chemical_system' , '-{}-' . format ( '-' . join ( sorted ( structure . get_symbols_set ( ) ) ) ) ) return structure | This calcfunction will take a CifData node attempt to create a StructureData object from it using the parse_engine and pass it through SeeKpath to try and get the primitive cell . Finally it will store several keys from the SeeKpath output parameters dictionary directly on the structure data as attributes which are otherwise difficult if not impossible to query for . | 534 | 71 |
7,211 | def export_capacities ( self ) : return [ export for cls in getmro ( type ( self ) ) if hasattr ( cls , "EXPORT_TO" ) for export in cls . EXPORT_TO ] | List Mimetypes that current object can export to | 51 | 10 |
7,212 | def _filter_options ( self , aliases = True , comments = True , historical = True ) : options = [ ] if not aliases : options . append ( 'noaliases' ) if not comments : options . append ( 'nocomments' ) if not historical : options . append ( 'nohistorical' ) return options | Converts a set of boolean - valued options into the relevant HTTP values . | 70 | 15 |
7,213 | def _request ( self , path , key , data , method , key_is_cik , extra_headers = { } ) : if method == 'GET' : if len ( data ) > 0 : url = path + '?' + data else : url = path body = None else : url = path body = data headers = { } if key_is_cik : headers [ 'X-Exosite-CIK' ] = key else : headers [ 'X-Exosite-Token' ] = key if method == 'POST' : headers [ 'Content-Type' ] = 'application/x-www-form-urlencoded; charset=utf-8' headers [ 'Accept' ] = 'text/plain, text/csv, application/x-www-form-urlencoded' headers . update ( extra_headers ) body , response = self . _onephttp . request ( method , url , body , headers ) pr = ProvisionResponse ( body , response ) if self . _raise_api_exceptions and not pr . isok : raise ProvisionException ( pr ) return pr | Generically shared HTTP request method . | 236 | 7 |
7,214 | def content_create ( self , key , model , contentid , meta , protected = False ) : params = { 'id' : contentid , 'meta' : meta } if protected is not False : params [ 'protected' ] = 'true' data = urlencode ( params ) path = PROVISION_MANAGE_CONTENT + model + '/' return self . _request ( path , key , data , 'POST' , self . _manage_by_cik ) | Creates a content entity bucket with the given contentid . | 103 | 12 |
7,215 | def content_list ( self , key , model ) : path = PROVISION_MANAGE_CONTENT + model + '/' return self . _request ( path , key , '' , 'GET' , self . _manage_by_cik ) | Returns the list of content IDs for a given model . | 54 | 11 |
7,216 | def content_remove ( self , key , model , contentid ) : path = PROVISION_MANAGE_CONTENT + model + '/' + contentid return self . _request ( path , key , '' , 'DELETE' , self . _manage_by_cik ) | Deletes the information for the given contentid under the given model . | 62 | 14 |
7,217 | def content_upload ( self , key , model , contentid , data , mimetype ) : headers = { "Content-Type" : mimetype } path = PROVISION_MANAGE_CONTENT + model + '/' + contentid return self . _request ( path , key , data , 'POST' , self . _manage_by_cik , headers ) | Store the given data as a result of a query for content id given the model . | 81 | 17 |
7,218 | def url_should_be ( self , url ) : if world . browser . current_url != url : raise AssertionError ( "Browser URL expected to be {!r}, got {!r}." . format ( url , world . browser . current_url ) ) | Assert the absolute URL of the browser is as provided . | 59 | 12 |
7,219 | def url_should_contain ( self , url ) : if url not in world . browser . current_url : raise AssertionError ( "Browser URL expected to contain {!r}, got {!r}." . format ( url , world . browser . current_url ) ) | Assert the absolute URL of the browser contains the provided . | 61 | 12 |
7,220 | def url_should_not_contain ( self , url ) : if url in world . browser . current_url : raise AssertionError ( "Browser URL expected not to contain {!r}, got {!r}." . format ( url , world . browser . current_url ) ) | Assert the absolute URL of the browser does not contain the provided . | 63 | 14 |
7,221 | def page_title ( self , title ) : if world . browser . title != title : raise AssertionError ( "Page title expected to be {!r}, got {!r}." . format ( title , world . browser . title ) ) | Assert the page title matches the given text . | 53 | 10 |
7,222 | def click ( self , name ) : try : elem = world . browser . find_element_by_link_text ( name ) except NoSuchElementException : raise AssertionError ( "Cannot find the link with text '{}'." . format ( name ) ) elem . click ( ) | Click the link with the provided link text . | 65 | 9 |
7,223 | def should_see_link ( self , link_url ) : elements = ElementSelector ( world . browser , str ( '//a[@href="%s"]' % link_url ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected link not found." ) | Assert a link with the provided URL is visible on the page . | 69 | 14 |
7,224 | def should_see_link_text ( self , link_text , link_url ) : elements = ElementSelector ( world . browser , str ( '//a[@href="%s"][./text()="%s"]' % ( link_url , link_text ) ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected link not found." ) | Assert a link with the provided text points to the provided URL . | 89 | 14 |
7,225 | def should_include_link_text ( self , link_text , link_url ) : elements = ElementSelector ( world . browser , str ( '//a[@href="%s"][contains(., %s)]' % ( link_url , string_literal ( link_text ) ) ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected link not found." ) | Assert a link containing the provided text points to the provided URL . | 95 | 14 |
7,226 | def element_contains ( self , element_id , value ) : elements = ElementSelector ( world . browser , str ( 'id("{id}")[contains(., "{value}")]' . format ( id = element_id , value = value ) ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected element not found." ) | Assert provided content is contained within an element found by id . | 85 | 13 |
7,227 | def element_not_contains ( self , element_id , value ) : elem = world . browser . find_elements_by_xpath ( str ( 'id("{id}")[contains(., "{value}")]' . format ( id = element_id , value = value ) ) ) assert not elem , "Expected element not to contain the given text." | Assert provided content is not contained within an element found by id . | 84 | 14 |
7,228 | def should_see_id_in_seconds ( self , element_id , timeout ) : def check_element ( ) : """Check for the element with the given id.""" assert ElementSelector ( world . browser , 'id("%s")' % element_id , filter_displayed = True , ) , "Expected element with given id." wait_for ( check_element ) ( timeout = int ( timeout ) ) | Assert an element with the given id is visible within n seconds . | 92 | 14 |
7,229 | def should_see_id ( self , element_id ) : elements = ElementSelector ( world . browser , 'id("%s")' % element_id , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected element with given id." ) | Assert an element with the given id is visible . | 63 | 11 |
7,230 | def element_focused ( self , id_ ) : try : elem = world . browser . find_element_by_id ( id_ ) except NoSuchElementException : raise AssertionError ( "Element with ID '{}' not found." . format ( id_ ) ) focused = world . browser . switch_to . active_element # Elements don't have __ne__ defined, cannot test for inequality if not elem == focused : raise AssertionError ( "Expected element to be focused." ) | Assert the element is focused . | 110 | 7 |
7,231 | def should_see_in_seconds ( self , text , timeout ) : def check_element ( ) : """Check for an element with the given content.""" assert contains_content ( world . browser , text ) , "Expected element with the given text." wait_for ( check_element ) ( timeout = int ( timeout ) ) | Assert provided text is visible within n seconds . | 71 | 10 |
7,232 | def see_form ( self , url ) : elements = ElementSelector ( world . browser , str ( '//form[@action="%s"]' % url ) , filter_displayed = True , ) if not elements : raise AssertionError ( "Expected form not found." ) | Assert the existence of a HTML form that submits to the given URL . | 63 | 16 |
7,233 | def press_button ( self , value ) : button = find_button ( world . browser , value ) if not button : raise AssertionError ( "Cannot find a button named '{}'." . format ( value ) ) button . click ( ) | Click the button with the given label . | 54 | 8 |
7,234 | def click_on_label ( self , label ) : elem = ElementSelector ( world . browser , str ( '//label[normalize-space(text())=%s]' % string_literal ( label ) ) , filter_displayed = True , ) if not elem : raise AssertionError ( "Cannot find a label with text '{}'." . format ( label ) ) elem . click ( ) | Click on the given label . | 93 | 6 |
7,235 | def submit_the_only_form ( self ) : form = ElementSelector ( world . browser , str ( '//form' ) ) assert form , "Cannot find a form on the page." form . submit ( ) | Look for a form on the page and submit it . | 48 | 11 |
7,236 | def check_alert ( self , text ) : try : alert = Alert ( world . browser ) if alert . text != text : raise AssertionError ( "Alert text expected to be {!r}, got {!r}." . format ( text , alert . text ) ) except WebDriverException : # PhantomJS is kinda poor pass | Assert an alert is showing with the given text . | 71 | 11 |
7,237 | def check_no_alert ( self ) : try : alert = Alert ( world . browser ) raise AssertionError ( "Should not see an alert. Alert '%s' shown." % alert . text ) except NoAlertPresentException : pass | Assert there is no alert . | 52 | 7 |
7,238 | def find_by_tooltip ( browser , tooltip ) : return ElementSelector ( world . browser , str ( '//*[@title=%(tooltip)s or @data-original-title=%(tooltip)s]' % dict ( tooltip = string_literal ( tooltip ) ) ) , filter_displayed = True , ) | Find elements with the given tooltip . | 75 | 7 |
7,239 | def press_by_tooltip ( self , tooltip ) : for button in find_by_tooltip ( world . browser , tooltip ) : try : button . click ( ) break except : # pylint:disable=bare-except pass else : raise AssertionError ( "No button with tooltip '{0}' found" . format ( tooltip ) ) | Click on a HTML element with a given tooltip . | 77 | 10 |
7,240 | def print_equations ( self ) : print ( "P_static: " , self . eqn_st ) print ( "P_thermal: " , self . eqn_th ) print ( "P_anharmonic: " , self . eqn_anh ) print ( "P_electronic: " , self . eqn_el ) | show equations used for the EOS | 78 | 7 |
7,241 | def _set_params ( self , p ) : if self . force_norm : params = [ value . n for key , value in p . items ( ) ] else : params = [ value for key , value in p . items ( ) ] return params | change parameters in OrderedDict to list with or without uncertainties | 54 | 13 |
7,242 | def cal_pel ( self , v , temp ) : if ( self . eqn_el is None ) or ( self . params_el is None ) : return np . zeros_like ( v ) params = self . _set_params ( self . params_el ) return func_el [ self . eqn_el ] ( v , temp , * params , self . n , self . z , t_ref = self . t_ref , three_r = self . three_r ) | calculate pressure from electronic contributions | 107 | 7 |
7,243 | def cal_panh ( self , v , temp ) : if ( self . eqn_anh is None ) or ( self . params_anh is None ) : return np . zeros_like ( v ) params = self . _set_params ( self . params_anh ) return func_anh [ self . eqn_anh ] ( v , temp , * params , self . n , self . z , t_ref = self . t_ref , three_r = self . three_r ) | calculate pressure from anharmonic contributions | 113 | 9 |
7,244 | def _hugoniot_t ( self , v ) : rho = self . _get_rho ( v ) params_h = self . _set_params ( self . params_hugoniot ) params_t = self . _set_params ( self . params_therm ) if self . nonlinear : return hugoniot_t ( rho , * params_h [ : - 1 ] , * params_t [ 1 : ] , self . n , self . mass , three_r = self . three_r , c_v = self . c_v ) else : return hugoniot_t ( rho , * params_h , * params_t [ 1 : ] , self . n , self . mass , three_r = self . three_r , c_v = self . c_v ) | calculate Hugoniot temperature | 182 | 7 |
7,245 | def _hugoniot_pth ( self , v ) : temp = self . _hugoniot_t ( v ) return self . cal_pth ( v , temp ) | calculate thermal pressure along hugoniot | 41 | 9 |
7,246 | def cal_v ( self , p , temp , min_strain = 0.3 , max_strain = 1.0 ) : v0 = self . params_therm [ 'v0' ] . nominal_value self . force_norm = True pp = unp . nominal_values ( p ) ttemp = unp . nominal_values ( temp ) def _cal_v_single ( pp , ttemp ) : if ( pp <= 1.e-5 ) and ( ttemp == 300. ) : return v0 def f_diff ( v , ttemp , pp ) : return self . cal_p ( v , ttemp ) - pp # print(f_diff(v0 * 0.3, temp, p)) v = brenth ( f_diff , v0 * max_strain , v0 * min_strain , args = ( ttemp , pp ) ) return v f_vu = np . vectorize ( _cal_v_single ) v = f_vu ( pp , ttemp ) self . force_norm = False return v | calculate unit - cell volume at given pressure and temperature | 231 | 12 |
7,247 | def parse_intervals ( path , as_context = False ) : def _regions_from_range ( ) : if as_context : ctxs = list ( set ( pf . lines [ start - 1 : stop - 1 ] ) ) return [ ContextInterval ( filename , ctx ) for ctx in ctxs ] else : return [ LineInterval ( filename , start , stop ) ] if ':' in path : path , subpath = path . split ( ':' ) else : subpath = '' pf = PythonFile . from_modulename ( path ) filename = pf . filename rng = NUMBER_RE . match ( subpath ) if rng : # specified a line or line range start , stop = map ( int , rng . groups ( 0 ) ) stop = stop or start + 1 return _regions_from_range ( ) elif not subpath : # asked for entire module if as_context : return [ ContextInterval ( filename , pf . prefix ) ] start , stop = 1 , pf . line_count + 1 return _regions_from_range ( ) else : # specified a context name context = pf . prefix + ':' + subpath if context not in pf . lines : raise ValueError ( "%s is not a valid context for %s" % ( context , pf . prefix ) ) if as_context : return [ ContextInterval ( filename , context ) ] else : start , stop = pf . context_range ( context ) return [ LineInterval ( filename , start , stop ) ] | Parse path strings into a collection of Intervals . | 340 | 11 |
7,248 | def p_suffix ( self , length = None , elipsis = False ) : if length is not None : result = self . input [ self . pos : self . pos + length ] if elipsis and len ( result ) == length : result += "..." return result return self . input [ self . pos : ] | Return the rest of the input | 69 | 6 |
7,249 | def p_debug ( self , message ) : print ( "{}{} `{}`" . format ( self . _debug_indent * " " , message , repr ( self . p_suffix ( 10 ) ) ) ) | Format and print debug messages | 50 | 5 |
7,250 | def p_next ( self ) : try : self . pos += 1 return self . input [ self . pos - 1 ] except IndexError : self . pos -= 1 return None | Consume and return the next char | 37 | 7 |
7,251 | def p_current_col ( self ) : prefix = self . input [ : self . pos ] nlidx = prefix . rfind ( '\n' ) if nlidx == - 1 : return self . pos return self . pos - nlidx | Return currnet column in line | 58 | 7 |
7,252 | def p_pretty_pos ( self ) : col = self . p_current_col suffix = self . input [ self . pos - col : ] end = suffix . find ( "\n" ) if end != - 1 : suffix = suffix [ : end ] return "%s\n%s" % ( suffix , "-" * col + "^" ) | Print current line and a pretty cursor below . Used in error messages | 76 | 13 |
7,253 | def p_startswith ( self , st , ignorecase = False ) : length = len ( st ) matcher = result = self . input [ self . pos : self . pos + length ] if ignorecase : matcher = result . lower ( ) st = st . lower ( ) if matcher == st : self . pos += length return result return False | Return True if the input starts with st at current position | 76 | 11 |
7,254 | def p_flatten ( self , obj , * * kwargs ) : if isinstance ( obj , six . string_types ) : return obj result = "" for i in obj : result += self . p_flatten ( i ) return result | Flatten a list of lists of lists ... of strings into a string | 53 | 14 |
7,255 | def p_parse ( cls , input , methodname = None , parse_all = True ) : if methodname is None : methodname = cls . __default__ p = cls ( input ) result = getattr ( p , methodname ) ( ) if result is cls . NoMatch or parse_all and p . p_peek ( ) is not None : p . p_raise ( ) return result | Parse the input using methodname as entry point . | 90 | 11 |
7,256 | def bulk_delete ( handler , request ) : ids = request . GET . getall ( 'ids' ) Message . delete ( ) . where ( Message . id << ids ) . execute ( ) raise muffin . HTTPFound ( handler . url ) | Bulk delete items | 54 | 4 |
7,257 | def make ( parser ) : s = parser . add_subparsers ( title = 'commands' , metavar = 'COMMAND' , help = 'description' , ) def install_f ( args ) : install ( args ) install_parser = install_subparser ( s ) install_parser . set_defaults ( func = install_f ) | provison Manila Share with HA | 79 | 6 |
7,258 | def _parse_paginated_members ( self , direction = "children" ) : page = self . _last_page_parsed [ direction ] if not page : page = 1 else : page = int ( page ) while page : if page > 1 : response = self . _resolver . endpoint . get_collection ( collection_id = self . id , page = page , nav = direction ) else : response = self . _resolver . endpoint . get_collection ( collection_id = self . id , nav = direction ) response . raise_for_status ( ) data = response . json ( ) data = expand ( data ) [ 0 ] if direction == "children" : self . children . update ( { o . id : o for o in type ( self ) . parse_member ( obj = data , collection = self , direction = direction , resolver = self . _resolver ) } ) else : self . parents . update ( { o for o in type ( self ) . parse_member ( obj = data , collection = self , direction = direction , resolver = self . _resolver ) } ) self . _last_page_parsed [ direction ] = page page = None if "https://www.w3.org/ns/hydra/core#view" in data : if "https://www.w3.org/ns/hydra/core#next" in data [ "https://www.w3.org/ns/hydra/core#view" ] [ 0 ] : page = int ( _re_page . findall ( data [ "https://www.w3.org/ns/hydra/core#view" ] [ 0 ] [ "https://www.w3.org/ns/hydra/core#next" ] [ 0 ] [ "@value" ] ) [ 0 ] ) self . _parsed [ direction ] = True | Launch parsing of children | 409 | 4 |
7,259 | def request_token ( self ) : logging . debug ( "Getting request token from %s:%d" , self . server , self . port ) token , secret = self . _token ( "/oauth/requestToken" ) return "{}/oauth/authorize?oauth_token={}" . format ( self . host , token ) , token , secret | Returns url request_token request_secret | 78 | 8 |
7,260 | def access_token ( self , request_token , request_secret ) : logging . debug ( "Getting access token from %s:%d" , self . server , self . port ) self . access_token , self . access_secret = self . _token ( "/oauth/accessToken" , request_token , request_secret ) return self . access_token , self . access_secret | Returns access_token access_secret | 85 | 7 |
7,261 | def open_resource ( self , name ) : # Import nested here so we can run setup.py without GAE. from google . appengine . api import memcache from pytz import OLSON_VERSION name_parts = name . lstrip ( '/' ) . split ( '/' ) if os . path . pardir in name_parts : raise ValueError ( 'Bad path segment: %r' % os . path . pardir ) cache_key = 'pytz.zoneinfo.%s.%s' % ( OLSON_VERSION , name ) zonedata = memcache . get ( cache_key ) if zonedata is None : zonedata = get_zoneinfo ( ) . read ( 'zoneinfo/' + '/' . join ( name_parts ) ) memcache . add ( cache_key , zonedata ) log . info ( 'Added timezone to memcache: %s' % cache_key ) else : log . info ( 'Loaded timezone from memcache: %s' % cache_key ) return StringIO ( zonedata ) | Opens a resource from the zoneinfo subdir for reading . | 234 | 13 |
7,262 | def resource_exists ( self , name ) : if name not in self . available : try : get_zoneinfo ( ) . getinfo ( 'zoneinfo/' + name ) self . available [ name ] = True except KeyError : self . available [ name ] = False return self . available [ name ] | Return true if the given resource exists | 66 | 7 |
7,263 | def bdd ( * keywords ) : settings = _personal_settings ( ) . data _storybook ( ) . with_params ( * * { "python version" : settings [ "params" ] [ "python version" ] } ) . only_uninherited ( ) . shortcut ( * keywords ) . play ( ) | Run tests matching keywords . | 68 | 5 |
7,264 | def authenticate ( self , username : str , password : str ) -> bool : self . username = username self . password = password auth_payload = """<authenticate1 xmlns=\"utcs\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"> <password>{password}</password> <username>{username}</username> <application>treeview</application> </authenticate1>""" payload = auth_payload . format ( password = self . password , username = self . username ) xdoc = self . connection . soap_action ( '/ws/AuthenticationService' , 'authenticate' , payload ) if xdoc : isok = xdoc . find ( './SOAP-ENV:Body/ns1:authenticate2/ns1:loginWasSuccessful' , IHCSoapClient . ihcns ) return isok . text == 'true' return False | Do an Authentricate request and save the cookie returned to be used on the following requests . Return True if the request was successfull | 205 | 27 |
7,265 | def get_project ( self ) -> str : xdoc = self . connection . soap_action ( '/ws/ControllerService' , 'getIHCProject' , "" ) if xdoc : base64data = xdoc . find ( './SOAP-ENV:Body/ns1:getIHCProject1/ns1:data' , IHCSoapClient . ihcns ) . text if not base64 : return False compresseddata = base64 . b64decode ( base64data ) return zlib . decompress ( compresseddata , 16 + zlib . MAX_WBITS ) . decode ( 'ISO-8859-1' ) return False | Get the ihc project | 145 | 6 |
7,266 | def _get_node ( response , * ancestors ) : document = response for ancestor in ancestors : if ancestor not in document : return { } else : document = document [ ancestor ] return document | Traverse tree to node | 39 | 5 |
7,267 | def update_token ( self ) : headers = { 'Content-Type' : 'application/x-www-form-urlencoded' , 'Authorization' : 'Basic ' + base64 . b64encode ( ( self . _key + ':' + self . _secret ) . encode ( ) ) . decode ( ) } data = { 'grant_type' : 'client_credentials' } response = requests . post ( TOKEN_URL , data = data , headers = headers ) obj = json . loads ( response . content . decode ( 'UTF-8' ) ) self . _token = obj [ 'access_token' ] self . _token_expire_date = ( datetime . now ( ) + timedelta ( minutes = self . _expiery ) ) | Get token from key and secret | 171 | 6 |
7,268 | def location_nearbystops ( self , origin_coord_lat , origin_coord_long ) : response = self . _request ( 'location.nearbystops' , originCoordLat = origin_coord_lat , originCoordLong = origin_coord_long ) return _get_node ( response , 'LocationList' , 'StopLocation' ) | location . nearbystops | 79 | 5 |
7,269 | def location_name ( self , name ) : response = self . _request ( 'location.name' , input = name ) return _get_node ( response , 'LocationList' , 'StopLocation' ) | location . name | 45 | 3 |
7,270 | def expand_namespace ( nsmap , string ) : for ns in nsmap : if isinstance ( string , str ) and isinstance ( ns , str ) and string . startswith ( ns + ":" ) : return string . replace ( ns + ":" , nsmap [ ns ] ) return string | If the string starts with a known prefix in nsmap replace it by full URI | 68 | 17 |
7,271 | def graphiter ( self , graph , target , ascendants = 0 , descendants = 1 ) : asc = 0 + ascendants if asc != 0 : asc -= 1 desc = 0 + descendants if desc != 0 : desc -= 1 t = str ( target ) if descendants != 0 and self . downwards [ t ] is True : self . downwards [ t ] = False for pred , obj in graph . predicate_objects ( target ) : if desc == 0 and isinstance ( obj , BNode ) : continue self . add ( ( target , pred , obj ) ) # Retrieve triples about the object if desc != 0 and self . downwards [ str ( obj ) ] is True : self . graphiter ( graph , target = obj , ascendants = 0 , descendants = desc ) if ascendants != 0 and self . updwards [ t ] is True : self . updwards [ t ] = False for s , p in graph . subject_predicates ( object = target ) : if desc == 0 and isinstance ( s , BNode ) : continue self . add ( ( s , p , target ) ) # Retrieve triples about the parent as object if asc != 0 and self . updwards [ str ( s ) ] is True : self . graphiter ( graph , target = s , ascendants = asc , descendants = 0 ) | Iter on a graph to finds object connected | 278 | 8 |
7,272 | def uniqued ( iterable ) : seen = set ( ) add = seen . add return [ i for i in iterable if i not in seen and not add ( i ) ] | Return unique list of items preserving order . | 39 | 8 |
7,273 | def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second | Yield all items from iterable except the last one . | 42 | 12 |
7,274 | def generic_translate ( frm = None , to = None , delete = '' ) : if PY2 : delete_dict = dict . fromkeys ( ord ( unicode ( d ) ) for d in delete ) if frm is None and to is None : string_trans = None unicode_table = delete_dict else : string_trans = string . maketrans ( frm , to ) unicode_table = dict ( ( ( ord ( unicode ( f ) ) , unicode ( t ) ) for f , t in zip ( frm , to ) ) , * * delete_dict ) string_args = ( string_trans , delete ) if delete else ( string_trans , ) translate_args = [ string_args , ( unicode_table , ) ] def translate ( basestr ) : args = translate_args [ isinstance ( basestr , unicode ) ] return basestr . translate ( * args ) else : string_trans = str . maketrans ( frm or '' , to or '' , delete or '' ) def translate ( basestr ) : return basestr . translate ( string_trans ) return translate | Return a translate function for strings and unicode . | 251 | 10 |
7,275 | def _cryptography_cipher ( key , iv ) : return Cipher ( algorithm = algorithms . TripleDES ( key ) , mode = modes . CBC ( iv ) , backend = default_backend ( ) ) | Build a cryptography TripleDES Cipher object . | 44 | 8 |
7,276 | def _calc_degreeminutes ( decimal_degree ) : sign = compare ( decimal_degree , 0 ) # Store whether the coordinate is negative or positive decimal_degree = abs ( decimal_degree ) degree = decimal_degree // 1 # Truncate degree to be an integer decimal_minute = ( decimal_degree - degree ) * 60. # Calculate the decimal minutes minute = decimal_minute // 1 # Truncate minute to be an integer second = ( decimal_minute - minute ) * 60. # Calculate the decimal seconds # Finally, re-impose the appropriate sign degree = degree * sign minute = minute * sign second = second * sign return ( degree , minute , decimal_minute , second ) | Calculate degree minute second from decimal degree | 151 | 9 |
7,277 | def set_hemisphere ( self , hemi_str ) : if hemi_str == 'W' : self . degree = abs ( self . degree ) * - 1 self . minute = abs ( self . minute ) * - 1 self . second = abs ( self . second ) * - 1 self . _update ( ) elif hemi_str == 'E' : self . degree = abs ( self . degree ) self . minute = abs ( self . minute ) self . second = abs ( self . second ) self . _update ( ) else : raise ValueError ( 'Hemisphere identifier for longitudes must be E or W' ) | Given a hemisphere identifier set the sign of the coordinate to match that hemisphere | 137 | 14 |
7,278 | def project ( self , projection ) : x , y = projection ( self . lon . decimal_degree , self . lat . decimal_degree ) return ( x , y ) | Return coordinates transformed to a given projection Projection should be a basemap or pyproj projection object or similar | 37 | 23 |
7,279 | def _pyproj_inv ( self , other , ellipse = 'WGS84' ) : lat1 , lon1 = self . lat . decimal_degree , self . lon . decimal_degree lat2 , lon2 = other . lat . decimal_degree , other . lon . decimal_degree g = pyproj . Geod ( ellps = ellipse ) heading_initial , heading_reverse , distance = g . inv ( lon1 , lat1 , lon2 , lat2 , radians = False ) distance = distance / 1000.0 if heading_initial == 0.0 : # Reverse heading not well handled for coordinates that are directly south heading_reverse = 180.0 return { 'heading_initial' : heading_initial , 'heading_reverse' : heading_reverse , 'distance' : distance } | Perform Pyproj s inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees and the distance in km . | 181 | 29 |
7,280 | def to_string ( self , formatter = 'D' ) : return ( self . lat . to_string ( formatter ) , self . lon . to_string ( formatter ) ) | Return string representation of lat and lon as a 2 - element tuple using the format specified by formatter | 42 | 21 |
7,281 | def _sub_latlon ( self , other ) : inv = self . _pyproj_inv ( other ) heading = inv [ 'heading_reverse' ] distance = inv [ 'distance' ] return GeoVector ( initial_heading = heading , distance = distance ) | Called when subtracting a LatLon object from self | 57 | 12 |
7,282 | def _update ( self ) : try : theta_radians = math . atan ( float ( self . dy ) / self . dx ) except ZeroDivisionError : if self . dy > 0 : theta_radians = 0.5 * math . pi elif self . dy < 0 : theta_radians = 1.5 * math . pi self . magnitude = self . dy else : self . magnitude = 1. / ( math . cos ( theta_radians ) ) * self . dx theta = math . degrees ( theta_radians ) self . heading = self . _angle_or_heading ( theta ) | Calculate heading and distance from dx and dy | 139 | 10 |
7,283 | def _authstr ( self , auth ) : if type ( auth ) is dict : return '{' + ',' . join ( [ "{0}:{1}" . format ( k , auth [ k ] ) for k in sorted ( auth . keys ( ) ) ] ) + '}' return auth | Convert auth to str so that it can be hashed | 64 | 12 |
7,284 | def _call ( self , method , auth , arg , defer , notimeout = False ) : if defer : self . deferred . add ( auth , method , arg , notimeout = notimeout ) return True else : calls = self . _composeCalls ( [ ( method , arg ) ] ) return self . _callJsonRPC ( auth , calls , notimeout = notimeout ) | Calls the Exosite One Platform RPC API . | 88 | 10 |
7,285 | def create ( self , auth , type , desc , defer = False ) : return self . _call ( 'create' , auth , [ type , desc ] , defer ) | Create something in Exosite . | 36 | 6 |
7,286 | def drop ( self , auth , resource , defer = False ) : return self . _call ( 'drop' , auth , [ resource ] , defer ) | Deletes the specified resource . | 32 | 6 |
7,287 | def flush ( self , auth , resource , options = None , defer = False ) : args = [ resource ] if options is not None : args . append ( options ) return self . _call ( 'flush' , auth , args , defer ) | Empties the specified resource of data per specified constraints . | 51 | 12 |
7,288 | def grant ( self , auth , resource , permissions , ttl = None , defer = False ) : args = [ resource , permissions ] if ttl is not None : args . append ( { "ttl" : ttl } ) return self . _call ( 'grant' , auth , args , defer ) | Grant resources with specific permissions and return a token . | 66 | 10 |
7,289 | def info ( self , auth , resource , options = { } , defer = False ) : return self . _call ( 'info' , auth , [ resource , options ] , defer ) | Request creation and usage information of specified resource according to the specified options . | 39 | 14 |
7,290 | def listing ( self , auth , types , options = None , resource = None , defer = False ) : if options is None : # This variant is deprecated return self . _call ( 'listing' , auth , [ types ] , defer ) else : if resource is None : # This variant is deprecated, too return self . _call ( 'listing' , auth , [ types , options ] , defer ) else : # pass resource to use the non-deprecated variant return self . _call ( 'listing' , auth , [ resource , types , options ] , defer ) | This provides backward compatibility with two previous variants of listing . To use the non - deprecated API pass both options and resource . | 122 | 24 |
7,291 | def map ( self , auth , resource , alias , defer = False ) : return self . _call ( 'map' , auth , [ 'alias' , resource , alias ] , defer ) | Creates an alias for a resource . | 40 | 8 |
7,292 | def move ( self , auth , resource , destinationresource , options = { "aliases" : True } , defer = False ) : return self . _call ( 'move' , auth , [ resource , destinationresource , options ] , defer ) | Moves a resource from one parent client to another . | 51 | 11 |
7,293 | def revoke ( self , auth , codetype , code , defer = False ) : return self . _call ( 'revoke' , auth , [ codetype , code ] , defer ) | Given an activation code the associated entity is revoked after which the activation code can no longer be used . | 41 | 20 |
7,294 | def share ( self , auth , resource , options = { } , defer = False ) : return self . _call ( 'share' , auth , [ resource , options ] , defer ) | Generates a share code for the given resource . | 39 | 10 |
7,295 | def update ( self , auth , resource , desc = { } , defer = False ) : return self . _call ( 'update' , auth , [ resource , desc ] , defer ) | Updates the description of the resource . | 39 | 8 |
7,296 | def usage ( self , auth , resource , metric , starttime , endtime , defer = False ) : return self . _call ( 'usage' , auth , [ resource , metric , starttime , endtime ] , defer ) | Returns metric usage for client and its subhierarchy . | 48 | 12 |
7,297 | def wait ( self , auth , resource , options , defer = False ) : # let the server control the timeout return self . _call ( 'wait' , auth , [ resource , options ] , defer , notimeout = True ) | This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated . | 49 | 21 |
7,298 | def write ( self , auth , resource , value , options = { } , defer = False ) : return self . _call ( 'write' , auth , [ resource , value , options ] , defer ) | Writes a single value to the resource specified . | 43 | 10 |
7,299 | def writegroup ( self , auth , entries , defer = False ) : return self . _call ( 'writegroup' , auth , [ entries ] , defer ) | Writes the given values for the respective resources in the list all writes have same timestamp . | 34 | 18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.