idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
7,200
def set_conditions ( self , trigger_id , conditions , trigger_mode = None ) : data = self . _serialize_object ( conditions ) if trigger_mode is not None : url = self . _service_url ( [ 'triggers' , trigger_id , 'conditions' , trigger_mode ] ) else : url = self . _service_url ( [ 'triggers' , trigger_id , 'conditions' ] ) response = self . _put ( url , data ) return Condition . list_to_object_list ( response )
Set the conditions for the trigger .
7,201
def conditions ( self , trigger_id ) : response = self . _get ( self . _service_url ( [ 'triggers' , trigger_id , 'conditions' ] ) ) return Condition . list_to_object_list ( response )
Get all conditions for a specific trigger .
7,202
def create_dampening ( self , trigger_id , dampening ) : data = self . _serialize_object ( dampening ) url = self . _service_url ( [ 'triggers' , trigger_id , 'dampenings' ] ) return Dampening ( self . _post ( url , data ) )
Create a new dampening .
7,203
def delete_dampening ( self , trigger_id , dampening_id ) : self . _delete ( self . _service_url ( [ 'triggers' , trigger_id , 'dampenings' , dampening_id ] ) )
Delete an existing dampening definition .
7,204
def update_dampening ( self , trigger_id , dampening_id ) : data = self . _serialize_object ( dampening ) url = self . _service_url ( [ 'triggers' , trigger_id , 'dampenings' , dampening_id ] ) return Dampening ( self . _put ( url , data ) )
Update an existing dampening definition .
7,205
def create_group_dampening ( self , group_id , dampening ) : data = self . _serialize_object ( dampening ) url = self . _service_url ( [ 'triggers' , 'groups' , group_id , 'dampenings' ] ) return Dampening ( self . _post ( url , data ) )
Create a new group dampening
7,206
def update_group_dampening ( self , group_id , dampening_id , dampening ) : data = self . _serialize_object ( dampening ) url = self . _service_url ( [ 'triggers' , 'groups' , group_id , 'dampenings' , dampening_id ] ) return Dampening ( self . _put ( url , data ) )
Update an existing group dampening
7,207
def delete_group_dampening ( self , group_id , dampening_id ) : self . _delete ( self . _service_url ( [ 'triggers' , 'groups' , group_id , 'dampenings' , dampening_id ] ) )
Delete an existing group dampening
7,208
def set_group_member_orphan ( self , member_id ) : self . _put ( self . _service_url ( [ 'triggers' , 'groups' , 'members' , member_id , 'orphan' ] ) , data = None , parse_json = False )
Make a non - orphan member trigger into an orphan .
7,209
def set_group_member_unorphan ( self , member_id , unorphan_info ) : data = self . _serialize_object ( unorphan_info ) data = self . _service_url ( [ 'triggers' , 'groups' , 'members' , member_id , 'unorphan' ] ) return Trigger ( self . _put ( url , data ) )
Make an orphan member trigger into an group trigger .
7,210
def enable ( self , trigger_ids = [ ] ) : trigger_ids = ',' . join ( trigger_ids ) url = self . _service_url ( [ 'triggers' , 'enabled' ] , params = { 'triggerIds' : trigger_ids , 'enabled' : 'true' } ) self . _put ( url , data = None , parse_json = False )
Enable triggers .
7,211
def get_twitter ( app_key = None , app_secret = None , search = 'python' , location = '' , ** kwargs ) : if not app_key : from settings_secret import TWITTER_API_KEY as app_key if not app_secret : from settings_secret import TWITTER_API_SECRET as app_secret twitter = Twython ( app_key , app_secret , oauth_version = 2 ) return Twython ( app_key , access_token = twitter . obtain_access_token ( ) )
Location may be specified with a string name or latitude longitude radius
7,212
def limitted_dump ( cursor = None , twitter = None , path = 'tweets.json' , limit = 450 , rate = TWITTER_SEARCH_RATE_LIMIT , indent = - 1 ) : if not twitter : twitter = get_twitter ( ) cursor = cursor or 'python' if isinstance ( cursor , basestring ) : cursor = get_cursor ( twitter , search = cursor ) newline = '\n' if indent is not None else '' if indent < 0 : indent = None with ( open ( path , 'w' ) if not isinstance ( path , file ) else path ) as f : f . write ( '[\n' ) for i , obj in enumerate ( cursor ) : f . write ( json . dumps ( obj , indent = indent ) ) if i < limit - 1 : f . write ( ',' + newline ) else : break remaining = int ( twitter . get_lastfunction_header ( 'x-rate-limit-remaining' ) ) if remaining > 0 : sleep ( 1. / rate ) else : sleep ( 15 * 60 ) f . write ( '\n]\n' )
Dump a limitted number of json . dump - able objects to the indicated file
7,213
def altshuler_grun ( v , v0 , gamma0 , gamma_inf , beta ) : x = v / v0 return gamma_inf + ( gamma0 - gamma_inf ) * np . power ( x , beta )
calculate Gruneisen parameter for Altshuler equation
7,214
def altshuler_debyetemp ( v , v0 , gamma0 , gamma_inf , beta , theta0 ) : x = v / v0 if isuncertainties ( [ v , v0 , gamma0 , gamma_inf , beta , theta0 ] ) : theta = theta0 * np . power ( x , - 1. * gamma_inf ) * unp . exp ( ( gamma0 - gamma_inf ) / beta * ( 1. - np . power ( x , beta ) ) ) else : theta = theta0 * np . power ( x , - 1. * gamma_inf ) * np . exp ( ( gamma0 - gamma_inf ) / beta * ( 1. - np . power ( x , beta ) ) ) return theta
calculate Debye temperature for Altshuler equation
7,215
def dorogokupets2007_pth ( v , temp , v0 , gamma0 , gamma_inf , beta , theta0 , n , z , three_r = 3. * constants . R , t_ref = 300. ) : v_mol = vol_uc2mol ( v , z ) gamma = altshuler_grun ( v , v0 , gamma0 , gamma_inf , beta ) theta = altshuler_debyetemp ( v , v0 , gamma0 , gamma_inf , beta , theta0 ) def f ( t ) : xx = theta / t debye = debye_E ( xx ) Eth = three_r * n * t * debye return ( gamma / v_mol * Eth ) * 1.e-9 return f ( temp ) - f ( t_ref )
calculate thermal pressure for Dorogokupets 2007 EOS
7,216
def bind ( cls , app , * paths , methods = None , name = None , view = None ) : if view is None : app . ps . admin . register ( cls ) if not paths : paths = ( '%s/%s' % ( app . ps . admin . cfg . prefix , name or cls . name ) , ) cls . url = paths [ 0 ] return super ( AdminHandler , cls ) . bind ( app , * paths , methods = methods , name = name , view = view )
Connect to admin interface and application .
7,217
def action ( cls , view ) : name = "%s:%s" % ( cls . name , view . __name__ ) path = "%s/%s" % ( cls . url , view . __name__ ) cls . actions . append ( ( view . __doc__ , path ) ) return cls . register ( path , name = name ) ( view )
Register admin view action .
7,218
async def dispatch ( self , request , ** kwargs ) : self . auth = await self . authorize ( request ) self . collection = await self . load_many ( request ) self . resource = await self . load_one ( request ) if request . method == 'GET' and self . resource is None : self . collection = await self . filter ( request ) self . columns_sort = request . query . get ( 'ap-sort' , self . columns_sort ) if self . columns_sort : reverse = self . columns_sort . startswith ( '-' ) self . columns_sort = self . columns_sort . lstrip ( '+-' ) self . collection = await self . sort ( request , reverse = reverse ) try : self . offset = int ( request . query . get ( 'ap-offset' , 0 ) ) if self . limit : self . count = await self . count ( request ) self . collection = await self . paginate ( request ) except ValueError : pass return await super ( AdminHandler , self ) . dispatch ( request , ** kwargs )
Dispatch a request .
7,219
async def sort ( self , request , reverse = False ) : return sorted ( self . collection , key = lambda o : getattr ( o , self . columns_sort , 0 ) , reverse = reverse )
Sort collection .
7,220
async def get_form ( self , request ) : if not self . form : return None formdata = await request . post ( ) return self . form ( formdata , obj = self . resource )
Base point load resource .
7,221
async def get ( self , request ) : form = await self . get_form ( request ) ctx = dict ( active = self , form = form , request = request ) if self . resource : return self . app . ps . jinja2 . render ( self . template_item , ** ctx ) return self . app . ps . jinja2 . render ( self . template_list , ** ctx )
Get collection of resources .
7,222
def columns_formatter ( cls , colname ) : def wrapper ( func ) : cls . columns_formatters [ colname ] = func return func return wrapper
Decorator to mark a function as columns formatter .
7,223
def render_value ( self , data , column ) : renderer = self . columns_formatters . get ( column , format_value ) return renderer ( self , data , column )
Render value .
7,224
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 .
7,225
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 .
7,226
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 .
7,227
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 .
7,228
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 .
7,229
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 .
7,230
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 .
7,231
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 .
7,232
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 .
7,233
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 .
7,234
def primitive_structure_from_cif ( cif , parse_engine , symprec , site_tolerance ) : CifCleanWorkChain = WorkflowFactory ( 'codtools.cif_clean' ) 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 : 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 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 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 .
7,235
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
7,236
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 .
7,237
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 .
7,238
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 .
7,239
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 .
7,240
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 .
7,241
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 .
7,242
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 .
7,243
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 .
7,244
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 .
7,245
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 .
7,246
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 .
7,247
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 .
7,248
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 .
7,249
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 .
7,250
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 .
7,251
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 .
7,252
def should_see_id_in_seconds ( self , element_id , timeout ) : def check_element ( ) : 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 .
7,253
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 .
7,254
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 if not elem == focused : raise AssertionError ( "Expected element to be focused." )
Assert the element is focused .
7,255
def should_see_in_seconds ( self , text , timeout ) : def check_element ( ) : 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 .
7,256
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 .
7,257
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 .
7,258
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 .
7,259
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 .
7,260
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 : pass
Assert an alert is showing with the given text .
7,261
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 .
7,262
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 .
7,263
def press_by_tooltip ( self , tooltip ) : for button in find_by_tooltip ( world . browser , tooltip ) : try : button . click ( ) break except : pass else : raise AssertionError ( "No button with tooltip '{0}' found" . format ( tooltip ) )
Click on a HTML element with a given tooltip .
7,264
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
7,265
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
7,266
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
7,267
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
7,268
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
7,269
def _hugoniot_pth ( self , v ) : temp = self . _hugoniot_t ( v ) return self . cal_pth ( v , temp )
calculate thermal pressure along hugoniot
7,270
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 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
7,271
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 : start , stop = map ( int , rng . groups ( 0 ) ) stop = stop or start + 1 return _regions_from_range ( ) elif not subpath : if as_context : return [ ContextInterval ( filename , pf . prefix ) ] start , stop = 1 , pf . line_count + 1 return _regions_from_range ( ) else : 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 .
7,272
def p_suffix ( self , length = None , elipsis = False ) : "Return the rest of the input" 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
7,273
def p_debug ( self , message ) : "Format and print debug messages" print ( "{}{} `{}`" . format ( self . _debug_indent * " " , message , repr ( self . p_suffix ( 10 ) ) ) )
Format and print debug messages
7,274
def p_next ( self ) : "Consume and return the next char" try : self . pos += 1 return self . input [ self . pos - 1 ] except IndexError : self . pos -= 1 return None
Consume and return the next char
7,275
def p_current_col ( self ) : "Return currnet column in line" prefix = self . input [ : self . pos ] nlidx = prefix . rfind ( '\n' ) if nlidx == - 1 : return self . pos return self . pos - nlidx
Return currnet column in line
7,276
def p_pretty_pos ( self ) : "Print current line and a pretty cursor below. Used in error messages" 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
7,277
def p_startswith ( self , st , ignorecase = False ) : "Return True if the input starts with `st` at current position" 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
7,278
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
7,279
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 .
7,280
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
7,281
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
7,282
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
7,283
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
7,284
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
7,285
def open_resource ( self , name ) : 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 .
7,286
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
7,287
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 .
7,288
def authenticate ( self , username : str , password : str ) -> bool : self . username = username self . password = password auth_payload = 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
7,289
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
7,290
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
7,291
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
7,292
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
7,293
def location_name ( self , name ) : response = self . _request ( 'location.name' , input = name ) return _get_node ( response , 'LocationList' , 'StopLocation' )
location . name
7,294
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
7,295
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 ) ) 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 ) ) 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
7,296
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 .
7,297
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 .
7,298
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 .
7,299
def _cryptography_cipher ( key , iv ) : return Cipher ( algorithm = algorithms . TripleDES ( key ) , mode = modes . CBC ( iv ) , backend = default_backend ( ) )
Build a cryptography TripleDES Cipher object .