signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def check ( self ) :
"""Check if data and third party tools , necessary to run the classification , are available
: raises : RuntimeError""" | pathfinder = Pathfinder ( True )
if pathfinder . add_path ( pathfinder [ 'superfamily' ] ) is None :
raise RuntimeError ( "'superfamily' data directory is missing" )
for tool in ( 'hmmscan' , 'phmmer' , 'mast' , 'blastp' , 'ass3.pl' , 'hmmscan.pl' ) :
if not pathfinder . exists ( tool ) :
raise RuntimeE... |
def move_safe ( origin , target ) :
"""Move file , skip if exists""" | if origin == target :
return origin
if file_exists ( target ) :
return target
shutil . move ( origin , target )
return target |
def _makeTimingAbsolute ( relativeDataList , startTime , endTime ) :
'''Maps values from 0 to 1 to the provided start and end time
Input is a list of tuples of the form
( [ ( time1 , pitch1 ) , ( time2 , pitch2 ) , . . . ]''' | timingSeq = [ row [ 0 ] for row in relativeDataList ]
valueSeq = [ list ( row [ 1 : ] ) for row in relativeDataList ]
absTimingSeq = makeSequenceAbsolute ( timingSeq , startTime , endTime )
absDataList = [ tuple ( [ time , ] + row ) for time , row in zip ( absTimingSeq , valueSeq ) ]
return absDataList |
def register_task ( self , input , deps = None , manager = None , task_class = None , append = False ) :
"""Utility function that generates a ` Work ` made of a single task
Args :
input : : class : ` AbinitInput `
deps : List of : class : ` Dependency ` objects specifying the dependency of this node .
An em... | # append True is much easier to use . In principle should be the default behaviour
# but this would break the previous API so . . .
if not append :
work = Work ( manager = manager )
else :
if not self . works :
work = Work ( manager = manager )
append = False
else :
work = self . wor... |
def save ( self , filename ) :
"""Save the entire REBOUND simulation to a binary file .""" | clibrebound . reb_output_binary ( byref ( self ) , c_char_p ( filename . encode ( "ascii" ) ) ) |
def floodFill ( points , startx , starty ) :
"""Returns a set of the ( x , y ) points of a filled in area .
` points ` is an iterable of ( x , y ) tuples of an arbitrary shape .
` startx ` and ` starty ` mark the starting point ( likely inside the
arbitrary shape ) to begin filling from .
> > > drawPoints (... | # Note : We ' re not going to use recursion here because 1 ) recursion is
# overrated 2 ) on a large enough shape it would cause a stackoverflow
# 3 ) flood fill doesn ' t strictly need recursion because it doesn ' t require
# a stack and 4 ) recursion is overrated .
allPoints = set ( points )
# Use a set because the l... |
def execute ( self , method , path , ** kwargs ) :
"""Executes a request to a given endpoint , returning the result""" | url = "{}{}" . format ( self . host , path )
kwargs . update ( self . _client_kwargs )
response = requests . request ( method , url , headers = { "Authorization" : "Bearer {}" . format ( self . api_key ) } , ** kwargs )
return response |
def image_format ( value ) :
"""Confirms that the uploaded image is of supported format .
Args :
value ( File ) : The file with an ` image ` property containing the image
Raises :
django . forms . ValidationError""" | if value . image . format . upper ( ) not in constants . ALLOWED_IMAGE_FORMATS :
raise ValidationError ( MESSAGE_INVALID_IMAGE_FORMAT ) |
def send_request ( self , request ) :
'''Send a Request . Return a ( message , event ) pair .
The message is an unframed message to send over the network .
Wait on the event for the response ; which will be in the
" result " attribute .
Raises : ProtocolError if the request violates the protocol
in some w... | request_id = next ( self . _id_counter )
message = self . _protocol . request_message ( request , request_id )
return message , self . _event ( request , request_id ) |
def import_process_template_status ( self , id ) :
"""ImportProcessTemplateStatus .
[ Preview API ] Tells whether promote has completed for the specified promote job ID .
: param str id : The ID of the promote job operation
: rtype : : class : ` < ProcessPromoteStatus > < azure . devops . v5_0 . work _ item _... | route_values = { }
if id is not None :
route_values [ 'id' ] = self . _serialize . url ( 'id' , id , 'str' )
route_values [ 'action' ] = 'Status'
response = self . _send ( http_method = 'GET' , location_id = '29e1f38d-9e9c-4358-86a5-cdf9896a5759' , version = '5.0-preview.1' , route_values = route_values )
return se... |
def get_data_source ( query ) :
"""Get data source connection metadata based on config . Prefer , in order :
- Query file frontmatter
- ` db . yaml ` file in query subdirectory
- DATABASE _ URL in environment
To allow for possible non - SQL sources to be contributed , we only
return a config value here , ... | # * * * GET CONNECTION PARAMS : * * *
# from frontmatter
try :
return query . metadata [ 'data_source' ]
except KeyError :
try :
return dict ( url = query . metadata [ 'database_url' ] )
except KeyError :
pass
# from file in directory if present
db_file = query . path . parent / 'db.yaml'
if... |
def _waterSupp ( cls , T , P ) :
"""Get properties of pure water using the supplementary release SR7-09,
Table4 pag 6""" | tau = ( T - 273.15 ) / 40
pi = ( P - 0.101325 ) / 100
J = [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 2 , 2 , 2 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 , 3 , 4 , 4 , 4 , 4 , 4 , 5 , 5 , 5 , 5 , 5 , 6 , 6 , 6 , 6 , 7 , 7 ]
K = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 0 , 1 , 2 , 3 , 4 , 5 , 0 , 1 , 2 , 3 , 4 , 5 , 0 , 1 , 2 , 3 ... |
def numRef_xml ( self , wksht_ref , number_format , values ) :
"""Return the ` ` < c : numRef > ` ` element specified by the parameters as
unicode text .""" | pt_xml = self . pt_xml ( values )
return ( ' <c:numRef>\n' ' <c:f>{wksht_ref}</c:f>\n' ' <c:numCache>\n' ' <c:formatCode>{number_format}</c:formatCode>\n' '{pt_xml}' ' </c:numCache>\n' ' </c:numRef>\n' ) . format ( ** { 'wksht_ref' : wksht_ref ... |
def on_created ( self , event , dry_run = False , remove_uploaded = True ) :
'Called when a file ( or directory ) is created .' | super ( ArchiveEventHandler , self ) . on_created ( event )
log . info ( "created: %s" , event ) |
def watch_active_servings ( dk_api , kitchen , period ) :
"""returns a string .
: param dk _ api : - - api object
: param kitchen : string
: param period : integer
: rtype : string""" | print 'period' , period
# try :
# p = int ( period )
# except ValueError :
# return ' DKCloudCommand . watch _ active _ servings requires an integer for the period '
if period <= 0 :
return 'DKCloudCommand.watch_active_servings requires a positive period'
DKActiveServingWatcherSingleton ( ) . set_sleep_time ( perio... |
def _findAll ( self , name , attrs , text , limit , generator , ** kwargs ) :
"Iterates over a generator looking for things that match ." | if isinstance ( name , SoupStrainer ) :
strainer = name
# ( Possibly ) special case some findAll * ( . . . ) searches
elif text is None and not limit and not attrs and not kwargs : # findAll * ( True )
if name is True :
return [ element for element in generator ( ) if isinstance ( element , Tag ) ]
... |
def get_assessments_offered_by_ids ( self , assessment_offered_ids ) :
"""Gets an ` ` AssessmentOfferedList ` ` corresponding to the given ` ` IdList ` ` .
In plenary mode , the returned list contains all of the
assessments specified in the ` ` Id ` ` list , in the order of the
list , including duplicates , o... | # Implemented from template for
# osid . resource . ResourceLookupSession . get _ resources _ by _ ids
# NOTE : This implementation currently ignores plenary view
collection = JSONClientValidated ( 'assessment' , collection = 'AssessmentOffered' , runtime = self . _runtime )
object_id_list = [ ]
for i in assessment_off... |
def save_apidoc ( text : str ) -> None :
"""save ` text ` to apidoc cache""" | apidoc_local = local . path ( APIDOC_LOCAL_FILE )
if not apidoc_local . dirname . exists ( ) :
apidoc_local . dirname . mkdir ( )
with open ( apidoc_local , 'w' ) as f :
f . write ( text ) |
def _find_widget_match ( self , prop_name ) :
"""Used to search ` ` self . view ` ` when : meth : ` adapt ` is not given a widget
name .
* prop _ name * is the name of a property in the model .
Returns a string with the best match . Raises
: class : ` TooManyCandidatesError ` or ` ` ValueError ` ` when noth... | names = [ ]
for wid_name in self . view : # if widget names ends with given property name : we skip
# any prefix in widget name
if wid_name . lower ( ) . endswith ( prop_name . lower ( ) ) :
names . append ( wid_name )
if len ( names ) == 0 :
raise ValueError ( "No widget candidates match property '%s':... |
def primary_mass ( mass1 , mass2 ) :
"""Returns the larger of mass1 and mass2 ( p = primary ) .""" | mass1 , mass2 , input_is_array = ensurearray ( mass1 , mass2 )
mp = copy . copy ( mass1 )
mask = mass1 < mass2
mp [ mask ] = mass2 [ mask ]
return formatreturn ( mp , input_is_array ) |
def register_pretty ( type = None , predicate = None ) :
"""Returns a decorator that registers the decorated function
as the pretty printer for instances of ` ` type ` ` .
: param type : the type to register the pretty printer for , or a ` ` str ` `
to indicate the module and name , e . g . : ` ` ' collection... | if type is None and predicate is None :
raise ValueError ( "You must provide either the 'type' or 'predicate' argument." )
if type is not None and predicate is not None :
raise ValueError ( "You must provide either the 'type' or 'predicate' argument," "but not both" )
if predicate is not None :
if not calla... |
def _secure ( self , to , From , authorize ) :
"""Response to a SECURE command , starting TLS when necessary , and using a
certificate identified by the I { To } header .
An occurrence of I { Secure } on the wire , together with the response
generated by this method , might have the following appearance : :
... | if self . hostCertificate is not None :
raise RuntimeError ( "Re-encrypting already encrypted connection" )
CS = self . service . certificateStorage
ourCert = CS . getPrivateCertificate ( str ( to . domainAddress ( ) ) )
if authorize :
D = CS . getSelfSignedCertificate ( str ( From . domainAddress ( ) ) )
else ... |
def get_proxy ( self , input_ ) :
"""Gets a proxy .
arg : input ( osid . proxy . ProxyCondition ) : a proxy condition
return : ( osid . proxy . Proxy ) - a proxy
raise : NullArgument - ` ` input ` ` is ` ` null ` `
raise : OperationFailed - unable to complete request
raise : PermissionDenied - authorizati... | if input_ . _http_request is not None :
authentication = Authentication ( )
authentication . set_django_user ( input_ . _http_request . user )
else :
authentication = None
effective_agent_id = input_ . _effective_agent_id
# Also need to deal with effective dates and Local
return rules . Proxy ( authenticati... |
def color_generator ( seed = None ) :
"""Generates random colors for control and evaluated curve / surface points plots .
The ` ` seed ` ` argument is used to set the random seed by directly passing the value to ` ` random . seed ( ) ` ` function .
Please see the Python documentation for more details on the ` `... | def r_int ( ) :
return random . randint ( 0 , 255 )
if seed is not None :
random . seed ( seed )
color_string = '#%02X%02X%02X'
return [ color_string % ( r_int ( ) , r_int ( ) , r_int ( ) ) , color_string % ( r_int ( ) , r_int ( ) , r_int ( ) ) ] |
def available ( self ) :
"""Check whether the ADB connection is intact .""" | if not self . adb_server_ip : # python - adb
return bool ( self . _adb )
# pure - python - adb
try : # make sure the server is available
adb_devices = self . _adb_client . devices ( )
# make sure the device is available
try : # case 1 : the device is currently available
if any ( [ self . host in... |
def get_node_index ( self , node ) :
"""Returns given Node index .
: param node : Node .
: type node : AbstractCompositeNode or GraphModelNode
: return : Index .
: rtype : QModelIndex""" | if node == self . __root_node :
return QModelIndex ( )
else :
row = node . row ( )
return self . createIndex ( row , 0 , node ) if row is not None else QModelIndex ( ) |
def read_namespaced_pod ( self , name , namespace , ** kwargs ) : # noqa : E501
"""read _ namespaced _ pod # noqa : E501
read the specified Pod # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . r... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . read_namespaced_pod_with_http_info ( name , namespace , ** kwargs )
# noqa : E501
else :
( data ) = self . read_namespaced_pod_with_http_info ( name , namespace , ** kwargs )
# noqa : E501
return data |
def __get_boxes ( self ) :
"""Get all the word boxes of this page .""" | if self . __boxes is not None :
return self . __boxes
# Check first if there is an OCR file available
boxfile = self . __get_box_path ( )
if self . fs . exists ( boxfile ) :
box_builder = pyocr . builders . LineBoxBuilder ( )
try :
with self . fs . open ( boxfile , 'r' ) as file_desc :
s... |
def _remove_existing_jobs ( data ) :
"""Remove jobs from data where we already have them in the same state .
1 . split the incoming jobs into pending , running and complete .
2 . fetch the ` ` job _ guids ` ` from the db that are in the same state as they
are in ` ` data ` ` .
3 . build a new list of jobs i... | new_data = [ ]
guids = [ datum [ 'job' ] [ 'job_guid' ] for datum in data ]
state_map = { guid : state for ( guid , state ) in Job . objects . filter ( guid__in = guids ) . values_list ( 'guid' , 'state' ) }
for datum in data :
job = datum [ 'job' ]
if not state_map . get ( job [ 'job_guid' ] ) :
new_da... |
def plot_self ( self , func ) :
"""define your callback function with the decorator @ plotter . plot _ self .
in the callback function set the data of lines
in the plot using self . lines [ i ] [ j ] . set _ data ( your data )""" | def func_wrapper ( ) :
func ( )
try :
self . manager . canvas . draw ( )
except ValueError as ve :
print ( ve )
pass
except RuntimeError as RtE :
print ( RtE )
pass
except Exception as e :
print ( e )
pass
return func_wrapper |
def find_version_by_regex ( file_source ) : # type : ( str ) - > Optional [ str ]
"""Regex for dunder version""" | if not file_source :
return None
version_match = re . search ( r"^version=['\"]([^'\"]*)['\"]" , file_source , re . M )
if version_match :
return version_match . group ( 1 )
return None |
def create_ssh_sftp_client ( host_ip , port , username , password ) :
'''create ssh client''' | try :
check_environment ( )
import paramiko
conn = paramiko . Transport ( host_ip , port )
conn . connect ( username = username , password = password )
sftp = paramiko . SFTPClient . from_transport ( conn )
return sftp
except Exception as exception :
print_error ( 'Create ssh client error %s... |
def update_org_invite ( cls , module ) :
"""Adds the links to the organization and to the organization user""" | try :
cls . module_registry [ module ] [ "OrgInviteModel" ] . _meta . get_field ( "invited_by" )
except FieldDoesNotExist :
cls . module_registry [ module ] [ "OrgInviteModel" ] . add_to_class ( "invited_by" , models . ForeignKey ( USER_MODEL , related_name = "%(app_label)s_%(class)s_sent_invitations" , on_dele... |
def read ( mfile , sfile ) :
"""Returns an IadhoreData object , constructed from the passed
i - ADHoRe multiplicon and segments output .
- mfile ( str ) , location of multiplicons . txt
- sfile ( str ) , location of segments . txt""" | assert os . path . isfile ( mfile ) , "%s multiplicon file does not exist"
assert os . path . isfile ( sfile ) , "%s segments file does not exist"
return IadhoreData ( mfile , sfile ) |
def CheckTaskReadyForMerge ( self , task ) :
"""Checks if a task is ready for merging with this session storage .
If the task is ready to be merged , this method also sets the task ' s
storage file size .
Args :
task ( Task ) : task .
Returns :
bool : True if the task is ready to be merged .
Raises : ... | if self . _storage_type != definitions . STORAGE_TYPE_SESSION :
raise IOError ( 'Unsupported storage type.' )
if not self . _processed_task_storage_path :
raise IOError ( 'Missing processed task storage path.' )
processed_storage_file_path = self . _GetProcessedStorageFilePath ( task )
try :
stat_info = os ... |
def match_positions ( shape , list_of_coords ) :
"""In cases where we have multiple matches , each highlighted by a region of coordinates ,
we need to separate matches , and find mean of each to return as match position""" | match_array = np . zeros ( shape )
try : # excpetion hit on this line if nothing in list _ of _ coords - i . e . no matches
match_array [ list_of_coords [ : , 0 ] , list_of_coords [ : , 1 ] ] = 1
labelled = label ( match_array )
objects = find_objects ( labelled [ 0 ] )
coords = [ { 'x' : ( slice_x . st... |
def notification_factory ( code , subcode ) :
"""Returns a ` Notification ` message corresponding to given codes .
Parameters :
- ` code ` : ( int ) BGP error code
- ` subcode ` : ( int ) BGP error sub - code""" | notification = BGPNotification ( code , subcode )
if not notification . reason :
raise ValueError ( 'Invalid code/sub-code.' )
return notification |
def distros_for_url ( url , metadata = None ) :
"""Yield egg or source distribution objects that might be found at a URL""" | base , fragment = egg_info_for_url ( url )
for dist in distros_for_location ( url , base , metadata ) :
yield dist
if fragment :
match = EGG_FRAGMENT . match ( fragment )
if match :
for dist in interpret_distro_name ( url , match . group ( 1 ) , metadata , precedence = CHECKOUT_DIST ) :
... |
def get_property_value ( self , selector , property , by = By . CSS_SELECTOR , timeout = settings . SMALL_TIMEOUT ) :
"""Returns the property value of a page element ' s computed style .
Example :
opacity = self . get _ property _ value ( " html body a " , " opacity " )
self . assertTrue ( float ( opacity ) >... | if self . timeout_multiplier and timeout == settings . SMALL_TIMEOUT :
timeout = self . __get_new_timeout ( timeout )
if page_utils . is_xpath_selector ( selector ) :
by = By . XPATH
if page_utils . is_link_text_selector ( selector ) :
selector = page_utils . get_link_text_from_selector ( selector )
by ... |
def density ( self , r , rho0 , Ra , Rs ) :
"""computes the density
: param x :
: param y :
: param rho0:
: param Ra :
: param Rs :
: return :""" | Ra , Rs = self . _sort_ra_rs ( Ra , Rs )
rho = rho0 / ( ( 1 + ( r / Ra ) ** 2 ) * ( 1 + ( r / Rs ) ** 2 ) )
return rho |
def _inplace_subset_var ( self , index ) :
"""Inplace subsetting along variables dimension .
Same as ` ` adata = adata [ : , index ] ` ` , but inplace .""" | adata_subset = self [ : , index ] . copy ( )
self . _init_as_actual ( adata_subset , dtype = self . _X . dtype ) |
def key_values ( self ) :
"""Return a dictionary of key / values in the payload received from
the webhook""" | key_values = { }
for key in self . keys :
if key in self . payload :
key_values [ key ] = self . payload [ key ]
return key_values |
def convert ( self , value , param , ctx ) :
"""Try to find correct kernel regarding version .""" | self . gandi = ctx . obj
# Exact match first
if value in self . choices :
return value
# Also try with x86-64 suffix
new_value = '%s-x86_64' % value
if new_value in self . choices :
return new_value
self . fail ( 'invalid choice: %s. (choose from %s)' % ( value , ', ' . join ( self . choices ) ) , param , ctx ) |
def RunInstaller ( ) :
"""Run all registered installers .
Run all the current installers and then exit the process .""" | try :
os . makedirs ( os . path . dirname ( config . CONFIG [ "Installer.logfile" ] ) )
except OSError :
pass
# Always log to the installer logfile at debug level . This way if our
# installer fails we can send detailed diagnostics .
handler = logging . FileHandler ( config . CONFIG [ "Installer.logfile" ] , mo... |
def perform_permissions_check ( self , user , obj , perms ) :
"""Performs the permission check .""" | return self . request . forum_permission_handler . can_delete_post ( obj , user ) |
def ajRadical ( self , i , r = None ) :
"""Ajoute le radical r de numéro i à la map des radicaux du lemme .
: param i : Index de radical
: type i : int
: param r : Radical à ajouter
: type r : Radical""" | if r :
self . _radicaux [ i ] . append ( r ) |
def copy ( self ) :
"""Create an exact copy of this quaternion .""" | return Quaternion ( self . w , self . x , self . y , self . z , False ) |
def consume ( self , tokens ) :
"""Consume tokens .
Args :
tokens ( float ) : number of transport tokens to consume
Returns :
wait _ time ( float ) : waiting time for the consumer""" | wait_time = 0.
self . tokens -= tokens
if self . tokens < 0 :
self . _get_tokens ( )
if self . tokens < 0 :
wait_time = - self . tokens / self . fill_rate
return wait_time |
def move ( doc , dest , src ) :
"""Move element from sequence , member from mapping .
: param doc : the document base
: param dest : the destination
: type dest : Pointer
: param src : the source
: type src : Pointer
: return : the new object
. . note : :
it delete then it add to the new location
... | return Target ( doc ) . move ( dest , src ) . document |
def pre_fork ( self , process_manager , kwargs = None ) :
'''Do anything necessary pre - fork . Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing''' | process_manager . add_process ( self . _publish_daemon , kwargs = kwargs ) |
def execute_from_command_line ( argv = None ) :
"""A simple method that runs a Command .""" | if sys . stdout . encoding is None :
print ( 'please set python env PYTHONIOENCODING=UTF-8, example: ' 'export PYTHONIOENCODING=UTF-8, when writing to stdout' , file = sys . stderr )
exit ( 1 )
command = Command ( argv )
command . execute ( ) |
def interpolate_to_isosurface ( level_var , interp_var , level , ** kwargs ) :
r"""Linear interpolation of a variable to a given vertical level from given values .
This function assumes that highest vertical level ( lowest pressure ) is zeroth index .
A classic use of this function would be to compute the poten... | # Change when Python 2.7 no longer supported
# Pull out keyword arguments
bottom_up_search = kwargs . pop ( 'bottom_up_search' , True )
# Find index values above and below desired interpolated surface value
above , below , good = metpy . calc . find_bounding_indices ( level_var , [ level ] , axis = 0 , from_below = bot... |
def drop ( self , codes , level = None , errors = 'raise' ) :
"""Make new MultiIndex with passed list of codes deleted
Parameters
codes : array - like
Must be a list of tuples
level : int or level name , default None
Returns
dropped : MultiIndex""" | if level is not None :
return self . _drop_from_level ( codes , level )
try :
if not isinstance ( codes , ( np . ndarray , Index ) ) :
codes = com . index_labels_to_array ( codes )
indexer = self . get_indexer ( codes )
mask = indexer == - 1
if mask . any ( ) :
if errors != 'ignore' ... |
def P ( self ) :
"""Contact frequency matrix with better precision on distance between
contigs . In the matrix M , the distance is assumed to be the distance
between mid - points of two contigs . In matrix Q , however , we compute
harmonic mean of the links for the orientation configuration that is
shortest... | N = self . N
tig_to_idx = self . tig_to_idx
P = np . zeros ( ( N , N , 2 ) , dtype = int )
for ( at , bt ) , ( strandedness , md , mh ) in self . orientations . items ( ) :
if not ( at in tig_to_idx and bt in tig_to_idx ) :
continue
ai = tig_to_idx [ at ]
bi = tig_to_idx [ bt ]
P [ ai , bi , 0 ]... |
def attach_user ( context , id , user_id ) :
"""attach _ user ( context , id , user _ id )
Attach a user to a remoteci .
> > > dcictl remoteci - attach - user [ OPTIONS ]
: param string id : ID of the remoteci to attach the user to [ required ]
: param string user _ id : ID of the user to attach [ required ... | result = remoteci . add_user ( context , id = id , user_id = user_id )
utils . format_output ( result , context . format , [ 'remoteci_id' , 'user_id' ] ) |
def previous_page ( self , max_ = None ) :
"""Return a query set which requests the page before this response .
: param max _ : Maximum number of items to return .
: type max _ : : class : ` int ` or : data : ` None `
: rtype : : class : ` ResultSetMetadata `
: return : A new request set up to request the p... | result = type ( self ) ( )
result . before = Before ( self . first . value )
result . max_ = max_
return result |
def find_invalid_filenames ( filenames , repository_root ) :
"""Find files that does not exist , are not in the repo or are directories .
Args :
filenames : list of filenames to check
repository _ root : the absolute path of the repository ' s root .
Returns : A list of errors .""" | errors = [ ]
for filename in filenames :
if not os . path . abspath ( filename ) . startswith ( repository_root ) :
errors . append ( ( filename , 'Error: File %s does not belong to ' 'repository %s' % ( filename , repository_root ) ) )
if not os . path . exists ( filename ) :
errors . append ( ... |
def split_sentences_regex ( text ) :
"""Use dead - simple regex to split text into sentences . Very poor accuracy .
> > > split _ sentences _ regex ( " Hello World . I ' m I . B . M . ' s Watson . - - Watson " )
[ ' Hello World . ' , " I ' m I . B . M . ' s Watson . " , ' - - Watson ' ]""" | parts = regex . split ( r'([a-zA-Z0-9][.?!])[\s$]' , text )
sentences = [ '' . join ( s ) for s in zip ( parts [ 0 : : 2 ] , parts [ 1 : : 2 ] ) ]
return sentences + [ parts [ - 1 ] ] if len ( parts ) % 2 else sentences |
def extract_table_identifiers ( token_stream ) :
"""yields tuples of ( schema _ name , table _ name , table _ alias )""" | for item in token_stream :
if isinstance ( item , IdentifierList ) :
for identifier in item . get_identifiers ( ) : # Sometimes Keywords ( such as FROM ) are classified as
# identifiers which don ' t have the get _ real _ name ( ) method .
try :
schema_name = identifier .... |
def save ( self , * args , ** kwargs ) :
"""ensure users cannot rate the same node multiple times
but let users change their rating""" | if not self . pk :
old_ratings = Rating . objects . filter ( user = self . user , node = self . node )
for old_rating in old_ratings :
old_rating . delete ( )
super ( Rating , self ) . save ( * args , ** kwargs ) |
def remap_name ( name_generator , names , table = None ) :
"""Produces a series of variable assignments in the form of : :
< obfuscated name > = < some identifier >
for each item in * names * using * name _ generator * to come up with the
replacement names .
If * table * is provided , replacements will be l... | out = ""
for name in names :
if table and name in table [ 0 ] . keys ( ) :
replacement = table [ 0 ] [ name ]
else :
replacement = next ( name_generator )
out += "%s=%s\n" % ( replacement , name )
return out |
def normalize_contract_type ( contract_type_data : Dict [ str , Any ] ) -> Iterable [ Tuple [ str , Any ] ] :
"""Serialize contract _ data found in compiler output to the defined fields .""" | yield "abi" , contract_type_data [ "abi" ]
if "evm" in contract_type_data :
if "bytecode" in contract_type_data [ "evm" ] :
yield "deployment_bytecode" , normalize_bytecode_object ( contract_type_data [ "evm" ] [ "bytecode" ] )
if "deployedBytecode" in contract_type_data [ "evm" ] :
yield "runti... |
def end_tag ( self , alt = None ) :
"""Return XML end tag for the receiver .""" | if alt :
name = alt
else :
name = self . name
return "</" + name + ">" |
def wait_for_service_tasks_all_changed ( service_name , old_task_ids , task_predicate = None , timeout_sec = 120 ) :
"""Returns once ALL of old _ task _ ids have been replaced with new tasks
: param service _ name : the service name
: type service _ name : str
: param old _ task _ ids : list of original task ... | return time_wait ( lambda : tasks_all_replaced_predicate ( service_name , old_task_ids , task_predicate ) , timeout_seconds = timeout_sec ) |
def allowDeletion ( store , tableClass , comparisonFactory ) :
"""Returns a C { bool } indicating whether deletion of an item or items of a
particular item type should be allowed to proceed .
@ param tableClass : An L { Item } subclass .
@ param comparison : A one - argument callable taking an attribute and
... | for cascadingAttr in ( _disallows . get ( tableClass , [ ] ) + _disallows . get ( None , [ ] ) ) :
for cascadedItem in store . query ( cascadingAttr . type , comparisonFactory ( cascadingAttr ) , limit = 1 ) :
return False
return True |
def p_switch_stmt ( p ) :
"""switch _ stmt : SWITCH expr semi _ opt case _ list END _ STMT""" | def backpatch ( expr , stmt ) :
if isinstance ( stmt , node . if_stmt ) :
stmt . cond_expr . args [ 1 ] = expr
backpatch ( expr , stmt . else_stmt )
backpatch ( p [ 2 ] , p [ 4 ] )
p [ 0 ] = p [ 4 ] |
def set_principal_credit_string ( self , credit_string ) :
"""Sets the principal credit string .
arg : credit _ string ( string ) : the new credit string
raise : InvalidArgument - ` ` credit _ string ` ` is invalid
raise : NoAccess - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
raise : NullArgument - `... | # Implemented from template for osid . repository . AssetForm . set _ title _ template
self . _my_map [ 'principalCreditString' ] = self . _get_display_text ( credit_string , self . get_principal_credit_string_metadata ( ) ) |
def find_stars ( self , data , mask = None ) :
"""Find stars in an astronomical image .
Parameters
data : 2D array _ like
The 2D image array .
mask : 2D bool array , optional
A boolean mask with the same shape as ` ` data ` ` , where a
` True ` value indicates the corresponding element of ` ` data ` `
... | star_cutouts = _find_stars ( data , self . kernel , self . threshold_eff , mask = mask , exclude_border = self . exclude_border )
if star_cutouts is None :
warnings . warn ( 'No sources were found.' , NoDetectionsWarning )
return None
self . _star_cutouts = star_cutouts
star_props = [ ]
for star_cutout in star_... |
def convert_l2normalization ( node , ** kwargs ) :
"""Map MXNet ' s L2Normalization operator attributes to onnx ' s LpNormalization operator
and return the created node .""" | name , input_nodes , attrs = get_inputs ( node , kwargs )
mode = attrs . get ( "mode" , "instance" )
if mode != "channel" :
raise AttributeError ( "L2Normalization: ONNX currently supports channel mode only" )
l2norm_node = onnx . helper . make_node ( "LpNormalization" , input_nodes , [ name ] , axis = 1 , # channe... |
def run ( self , inputs , ** kwargs ) :
"""Run model inference and return the result
Parameters
inputs : numpy array
input to run a layer on
Returns
params : numpy array
result obtained after running the inference on mxnet""" | input_data = np . asarray ( inputs [ 0 ] , dtype = 'f' )
# create module , passing cpu context
if self . device == 'CPU' :
ctx = mx . cpu ( )
else :
raise NotImplementedError ( "Only CPU context is supported for now" )
mod = mx . mod . Module ( symbol = self . symbol , data_names = [ 'input_0' ] , context = ctx... |
def gfevnt ( udstep , udrefn , gquant , qnpars , lenvals , qpnams , qcpars , qdpars , qipars , qlpars , op , refval , tol , adjust , rpt , udrepi , udrepu , udrepf , nintvls , bail , udbail , cnfine , result = None ) :
"""Determine time intervals when a specified geometric quantity
satisfies a specified mathemati... | assert isinstance ( cnfine , stypes . SpiceCell )
assert cnfine . is_double ( )
if result is None :
result = stypes . SPICEDOUBLE_CELL ( 2000 )
else :
assert isinstance ( result , stypes . SpiceCell )
assert result . is_double ( )
gquant = stypes . stringToCharP ( gquant )
qnpars = ctypes . c_int ( qnpars )... |
def register ( cls , note , provider ) :
"""Implementation to register provider via ` provider ` & ` factory ` .""" | basenote , name = cls . parse_note ( note )
if 'provider_registry' not in vars ( cls ) :
cls . provider_registry = { }
cls . provider_registry [ basenote ] = provider |
def get_internal_header ( request : HttpRequest ) -> str :
"""Return request ' s ' X _ POLYAXON _ INTERNAL : ' header , as a bytestring .""" | return get_header ( request = request , header_service = conf . get ( 'HEADERS_INTERNAL' ) ) |
def from_variant_and_transcript_and_sequence_key ( cls , variant , transcript , sequence_key ) :
"""Assuming that the transcript has a coding sequence , take a
ReferenceSequenceKey ( region of the transcript around the variant ) and
return a ReferenceCodingSequenceKey ( or None ) .""" | # get the interbase range of offsets which capture all reference
# bases modified by the variant
variant_start_offset , variant_end_offset = interbase_range_affected_by_variant_on_transcript ( variant = variant , transcript = transcript )
start_codon_idx = min ( transcript . start_codon_spliced_offsets )
# skip any var... |
def get_dataframe ( ) :
"""get a generic ( default ) control section dataframe
Returns
pandas . DataFrame : pandas . DataFrame""" | names = [ ]
[ names . extend ( line . split ( ) ) for line in CONTROL_VARIABLE_LINES ]
defaults = [ ]
[ defaults . extend ( line . split ( ) ) for line in CONTROL_DEFAULT_LINES ]
types , required , cast_defaults , formats = [ ] , [ ] , [ ] , [ ]
for name , default in zip ( names , defaults ) :
if '[' in name or ']'... |
def create_zip_codes_geo_zone ( cls , zip_codes_geo_zone , ** kwargs ) :
"""Create ZipCodesGeoZone
Create a new ZipCodesGeoZone
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . create _ zip _ codes _ geo _ zone ( z... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _create_zip_codes_geo_zone_with_http_info ( zip_codes_geo_zone , ** kwargs )
else :
( data ) = cls . _create_zip_codes_geo_zone_with_http_info ( zip_codes_geo_zone , ** kwargs )
return data |
def create_self_subject_access_review ( self , body , ** kwargs ) : # noqa : E501
"""create _ self _ subject _ access _ review # noqa : E501
create a SelfSubjectAccessReview # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req =... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_self_subject_access_review_with_http_info ( body , ** kwargs )
# noqa : E501
else :
( data ) = self . create_self_subject_access_review_with_http_info ( body , ** kwargs )
# noqa : E501
return data |
def MCMC ( self , niter = 500 , nburn = 200 , nwalkers = 200 , threads = 1 , fit_partial = False , width = 3 , savedir = None , refit = False , thin = 10 , conf = 0.95 , maxslope = MAXSLOPE , debug = False , p0 = None ) :
"""Fit transit signal to trapezoid model using MCMC
. . note : : As currently implemented , ... | if fit_partial :
wok = np . where ( ( np . absolute ( self . ts - self . center ) < ( width * self . dur ) ) & ~ np . isnan ( self . fs ) )
else :
wok = np . where ( ~ np . isnan ( self . fs ) )
if savedir is not None :
if not os . path . exists ( savedir ) :
os . mkdir ( savedir )
alreadydone = Tru... |
def load_dataframe ( self , df_loader_name ) :
"""Instead of joining a DataFrameJoiner with the Cohort in ` as _ dataframe ` , sometimes
we may want to just directly load a particular DataFrame .""" | logger . debug ( "loading dataframe: {}" . format ( df_loader_name ) )
# Get the DataFrameLoader object corresponding to this name .
df_loaders = [ df_loader for df_loader in self . df_loaders if df_loader . name == df_loader_name ]
if len ( df_loaders ) == 0 :
raise ValueError ( "No DataFrameLoader with name %s" %... |
def illum ( target , et , abcorr , obsrvr , spoint ) :
"""Deprecated : This routine has been superseded by the CSPICE
routine ilumin . This routine is supported for purposes of
backward compatibility only .
Find the illumination angles at a specified surface point of a
target body .
http : / / naif . jpl ... | target = stypes . stringToCharP ( target )
et = ctypes . c_double ( et )
abcorr = stypes . stringToCharP ( abcorr )
obsrvr = stypes . stringToCharP ( obsrvr )
spoint = stypes . toDoubleVector ( spoint )
phase = ctypes . c_double ( 0 )
solar = ctypes . c_double ( 0 )
emissn = ctypes . c_double ( 0 )
libspice . illum_c (... |
def _flushContour ( self ) :
"""This normalizes the contour so that :
- there are no line segments . in their place will be
curve segments with the off curves positioned on top
of the previous on curve and the new curve on curve .
- the contour starts with an on curve""" | self . contours . append ( dict ( identifier = self . _contourIdentifier , points = [ ] ) )
contourPoints = self . contours [ - 1 ] [ "points" ]
points = self . _points
# move offcurves at the beginning of the contour to the end
haveOnCurve = False
for point in points :
if point [ 0 ] is not None :
haveOnCu... |
def classes ( self , values ) :
"""Classes setter .""" | if isinstance ( values , dict ) :
if self . __data is not None and len ( self . __data ) != len ( values ) :
raise ValueError ( 'number of samples do not match the previously assigned data' )
elif set ( self . keys ) != set ( list ( values ) ) :
raise ValueError ( 'sample ids do not match the pr... |
def digester ( data ) :
"""Create SHA - 1 hash , get digest , b64 encode , split every 60 char .""" | if not isinstance ( data , six . binary_type ) :
data = data . encode ( 'utf_8' )
hashof = hashlib . sha1 ( data ) . digest ( )
encoded_hash = base64 . b64encode ( hashof )
if not isinstance ( encoded_hash , six . string_types ) :
encoded_hash = encoded_hash . decode ( 'utf_8' )
chunked = splitter ( encoded_has... |
def hist ( data ) :
"""Plots histogram""" | win = CurveDialog ( edit = False , toolbar = True , wintitle = "Histogram test" )
plot = win . get_plot ( )
plot . add_item ( make . histogram ( data ) )
win . show ( )
win . exec_ ( ) |
def slug ( self ) :
"""A concise slug for this feature .
Unlike the internal representation , which is 0 - based half - open , the
slug is a 1 - based closed interval ( a la GFF3 ) .""" | return '{:s}@{:s}[{:d}, {:d}]' . format ( self . type , self . seqid , self . start + 1 , self . end ) |
def __get_aws_metric ( table_name , lookback_window_start , lookback_period , metric_name ) :
"""Returns a metric list from the AWS CloudWatch service , may return
None if no metric exists
: type table _ name : str
: param table _ name : Name of the DynamoDB table
: type lookback _ window _ start : int
: ... | try :
now = datetime . utcnow ( )
start_time = now - timedelta ( minutes = lookback_window_start )
end_time = now - timedelta ( minutes = lookback_window_start - lookback_period )
return cloudwatch_connection . get_metric_statistics ( period = lookback_period * 60 , start_time = start_time , end_time = ... |
def url ( self , value ) :
"""The url property .
Args :
value ( string ) . the property value .""" | if value == self . _defaults [ 'url' ] and 'url' in self . _values :
del self . _values [ 'url' ]
else :
self . _values [ 'url' ] = value |
def register_conversion_handler ( self , name , handler ) :
u"""Регистрация обработчика конвертирования
: param name : Имя обработчика в таблице соответствия
: param handler : Обработчик""" | if name in self . conversion_table :
warnings . warn ( ( u'Конвертирующий тип с именем {} уже ' u'существует и будет перезаписан!' ) . format ( name ) )
self . conversion_table [ name ] = handler |
def optimize_NxN ( x , y , fit_offset = False , perc = None ) :
"""Just to compare with closed - form solution""" | if perc is not None :
if not fit_offset and isinstance ( perc , ( list , tuple ) ) :
perc = perc [ 1 ]
weights = get_weight ( x , y , perc ) . astype ( bool )
if issparse ( weights ) :
weights = weights . A
else :
weights = None
x , y = x . astype ( np . float64 ) , y . astype ( np . flo... |
def updateColumnValue ( self , column , value , index = None ) :
"""Assigns the value for the column of this record to the inputed value .
: param index | < int >
value | < variant >""" | if index is None :
index = self . treeWidget ( ) . column ( column . name ( ) )
if type ( value ) == datetime . date :
self . setData ( index , Qt . EditRole , wrapVariant ( value ) )
elif type ( value ) == datetime . time :
self . setData ( index , Qt . EditRole , wrapVariant ( value ) )
elif type ( value ... |
def grant ( self , lock , unit ) :
'''Maybe grant the lock to a unit .
The decision to grant the lock or not is made for $ lock
by a corresponding method grant _ $ lock , which you may define
in a subclass . If no such method is defined , the default _ grant
method is used . See Serial . default _ grant ( )... | if not hookenv . is_leader ( ) :
return False
# Not the leader , so we cannot grant .
# Set of units already granted the lock .
granted = set ( )
for u in self . grants :
if lock in self . grants [ u ] :
granted . add ( u )
if unit in granted :
return True
# Already granted .
# Ordered list of units... |
def is_twss ( self , phrase ) :
"""The magic function - this accepts a phrase and tells you if it
classifies as an entendre""" | featureset = self . extract_features ( phrase )
return self . classifier . classify ( featureset ) |
def _construct_manpage_specific_structure ( self , parser_info ) :
"""Construct a typical man page consisting of the following elements :
NAME ( automatically generated , out of our control )
SYNOPSIS
DESCRIPTION
OPTIONS
FILES
SEE ALSO
BUGS""" | items = [ ]
# SYNOPSIS section
synopsis_section = nodes . section ( '' , nodes . title ( text = 'Synopsis' ) , nodes . literal_block ( text = parser_info [ "bare_usage" ] ) , ids = [ 'synopsis-section' ] )
items . append ( synopsis_section )
# DESCRIPTION section
if 'nodescription' not in self . options :
descripti... |
def get_function ( self , dbName , funcName ) :
"""Parameters :
- dbName
- funcName""" | self . send_get_function ( dbName , funcName )
return self . recv_get_function ( ) |
def dottable_getitem ( data , dottable_key , default = None ) :
"""Return item as ` ` dict . _ _ getitem _ _ ` but using keys with dots .
It does not address indexes in iterables .""" | def getitem ( value , * keys ) :
if not keys :
return default
elif len ( keys ) == 1 :
key = keys [ 0 ]
if isinstance ( value , MutableMapping ) :
return value . get ( key , default )
elif isinstance ( value , Sequence ) and not isinstance ( value , six . string_types... |
def retrieve ( self , request , * args , ** kwargs ) :
"""gets basic information about the user
: param request : a WSGI request object
: param args : inline arguments ( optional )
: param kwargs : keyword arguments ( optional )
: return : ` rest _ framework . response . Response `""" | data = UserSerializer ( ) . to_representation ( request . user )
# add superuser flag only if user is a superuser , putting it here so users can only
# tell if they are themselves superusers
if request . user . is_superuser :
data [ 'is_superuser' ] = True
# attempt to add a firebase token if we have a firebase sec... |
def cublasZtrmm ( handle , side , uplo , trans , diag , m , n , alpha , A , lda , B , ldb , C , ldc ) :
"""Matrix - matrix product for complex triangular matrix .""" | status = _libcublas . cublasZtrmm_v2 ( handle , _CUBLAS_SIDE_MODE [ side ] , _CUBLAS_FILL_MODE [ uplo ] , _CUBLAS_OP [ trans ] , _CUBLAS_DIAG [ diag ] , m , n , ctypes . byref ( cuda . cuDoubleComplex ( alpha . real , alpha . imag ) ) , int ( A ) , lda , int ( B ) , ldb , int ( C ) , ldc )
cublasCheckStatus ( status ) |
def _data ( self ) :
"""A deep copy NDArray of the data array associated with the BaseSparseNDArray .
This function blocks . Do not use it in performance critical code .""" | self . wait_to_read ( )
hdl = NDArrayHandle ( )
check_call ( _LIB . MXNDArrayGetDataNDArray ( self . handle , ctypes . byref ( hdl ) ) )
return NDArray ( hdl ) |
def _encode_status ( status ) :
"""Cast status to bytes representation of current Python version .
According to : pep : ` 3333 ` , when using Python 3 , the response status
and headers must be bytes masquerading as unicode ; that is , they
must be of type " str " but are restricted to code points in the
" l... | if six . PY2 :
return status
if not isinstance ( status , str ) :
raise TypeError ( 'WSGI response status is not of type str.' )
return status . encode ( 'ISO-8859-1' ) |
def url ( self , schemes = None ) :
""": param schemes : a list of strings to use as schemes , one will chosen randomly .
If None , it will generate http and https urls .
Passing an empty list will result in schemeless url generation like " : / / domain . com " .
: returns : a random url string .""" | if schemes is None :
schemes = [ 'http' , 'https' ]
pattern = '{}://{}' . format ( self . random_element ( schemes ) if schemes else "" , self . random_element ( self . url_formats ) , )
return self . generator . parse ( pattern ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.