signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def request ( session , url , rule_payload , ** kwargs ) :
"""Executes a request with the given payload and arguments .
Args :
session ( requests . Session ) : the valid session object
url ( str ) : Valid API endpoint
rule _ payload ( str or dict ) : rule package for the POST . If you pass a
dictionary , ... | if isinstance ( rule_payload , dict ) :
rule_payload = json . dumps ( rule_payload )
logger . debug ( "sending request" )
result = session . post ( url , data = rule_payload , ** kwargs )
return result |
def get_num_branches ( self ) :
"""Return the number of effective branches for tectonic region type ,
as a dictionary .""" | num = { }
for trt , branches in itertools . groupby ( self . branches , operator . attrgetter ( 'trt' ) ) :
num [ trt ] = sum ( 1 for br in branches if br . effective )
return num |
def site_specific_coordination_numbers ( self ) :
"""Returns a dictionary of coordination numbers for each site type .
Args :
None
Returns :
( Dict ( Str : List ( Int ) ) ) : Dictionary of coordination numbers for each site type , e . g . : :
{ ' A ' : [ 2 , 4 ] , ' B ' : [ 2 ] }""" | specific_coordination_numbers = { }
for site in self . sites :
specific_coordination_numbers [ site . label ] = site . site_specific_neighbours ( )
return specific_coordination_numbers |
def iter_extensions ( prefix , event_id ) :
"""Return extension ( prefix + event _ id ) with an optional suffix which is
incremented step by step in case of collision""" | extension = '{prefix}{event_id}' . format ( prefix = prefix , event_id = event_id )
yield extension
suffix = 1
while True :
yield '{extension}{suffix}' . format ( extension = extension , suffix = suffix )
suffix += 1 |
def create_folder_structure ( self ) :
"""Creates a folder structure based on the project and batch name .
Project - Batch - name - Raw - data - dir
The info _ df JSON - file will be stored in the Project folder .
The summary - files will be saved in the Batch - name folder .
The raw data ( including export... | self . info_file , directories = create_folder_structure ( self . project , self . name )
self . project_dir , self . batch_dir , self . raw_dir = directories
logger . debug ( "create folders:" + str ( directories ) ) |
def handle_get_version_command ( self ) :
"""Handles < get _ version > command .
@ return : Response string for < get _ version > command .""" | protocol = Element ( 'protocol' )
for name , value in [ ( 'name' , 'OSP' ) , ( 'version' , self . get_protocol_version ( ) ) ] :
elem = SubElement ( protocol , name )
elem . text = value
daemon = Element ( 'daemon' )
for name , value in [ ( 'name' , self . get_daemon_name ( ) ) , ( 'version' , self . get_daemon... |
def data_received ( self , data ) :
"""Receive data from the protocol .
Called when asyncio . Protocol detects received data from network .""" | _LOGGER . debug ( "Starting: data_received" )
_LOGGER . debug ( 'Received %d bytes from PLM: %s' , len ( data ) , binascii . hexlify ( data ) )
self . _buffer . put_nowait ( data )
asyncio . ensure_future ( self . _peel_messages_from_buffer ( ) , loop = self . _loop )
_LOGGER . debug ( "Finishing: data_received" ) |
def create ( self , key , value ) :
"""Create method of CRUD operation for working with KeyValue DB .
This method will automatically determine the variable type and
call the appropriate method to write the data . If a non standard
type is provided the data will be written as RAW data .
Args :
key ( string... | data = None
if key is not None :
key = key . strip ( )
self . tcex . log . debug ( u'create variable {}' . format ( key ) )
# bcs - only for debugging or binary might cause issues
# self . tcex . log . debug ( u ' variable value : { } ' . format ( value ) )
parsed_key = self . parse_variable ( key .... |
def replace_namespaced_pod_template ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""replace _ namespaced _ pod _ template # noqa : E501
replace the specified PodTemplate # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_namespaced_pod_template_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . replace_namespaced_pod_template_with_http_info ( name , namespace , body , ** kwargs )
... |
def datasets ( self , limit = 0 , offset = 0 , order = None , ** kwargs ) :
'''Returns the list of datasets associated with a particular domain .
WARNING : Large limits ( > 1000 ) will return megabytes of data ,
which can be slow on low - bandwidth networks , and is also a lot of
data to hold in memory .
Th... | # Those filters can be passed multiple times ; this function expects
# an iterable for them
filter_multiple = set ( [ 'ids' , 'domains' , 'categories' , 'tags' , 'only' , 'shared_to' , 'column_names' ] )
# Those filters only get a single value
filter_single = set ( [ 'q' , 'min_should_match' , 'attribution' , 'license'... |
def from_file ( cls , filename , temperature_key = 'DEFT' , beamfill_key = 'BEAMFILL' , ** kwargs ) :
"""Creates a thermal spectral element from file .
. . note : :
Only FITS format is supported .
Parameters
filename : str
Thermal spectral element filename .
temperature _ key , beamfill _ key : str
Ke... | if not ( filename . endswith ( 'fits' ) or filename . endswith ( 'fit' ) ) :
raise exceptions . SynphotError ( 'Only FITS format is supported.' )
# Extra info from table header
ext = kwargs . get ( 'ext' , 1 )
tab_hdr = fits . getheader ( filename , ext = ext )
temperature = tab_hdr . get ( temperature_key )
if tem... |
def field ( self , type , field , default = None ) :
'''convenient function for returning an arbitrary MAVLink
field with a default''' | if not type in self . messages :
return default
return getattr ( self . messages [ type ] , field , default ) |
def _compress ( self ) :
"""Internal method to compress the cache . This method will
expire any old items in the cache , making the cache smaller""" | # Don ' t compress too often
now = time . time ( )
if self . _last_compression + self . _compression_timer < now :
self . _last_compression = now
for key in list ( self . _store . keys ( ) ) :
self . get ( key ) |
def remove ( self , iid ) :
'''Deletes file from vault and removes database information''' | for index in iid :
target = Target . getTarget ( index )
target . delete ( ) |
def by_land_area_in_sqmi ( self , lower = - 1 , upper = 2 ** 31 , zipcode_type = ZipcodeType . Standard , sort_by = SimpleZipcode . land_area_in_sqmi . name , ascending = False , returns = DEFAULT_LIMIT ) :
"""Search zipcode information by land area / sq miles range .""" | return self . query ( land_area_in_sqmi_lower = lower , land_area_in_sqmi_upper = upper , sort_by = sort_by , zipcode_type = zipcode_type , ascending = ascending , returns = returns , ) |
def bundle_dir ( ) :
"""Handle resource management within an executable file .""" | if frozen ( ) :
directory = sys . _MEIPASS
else :
directory = os . path . dirname ( os . path . abspath ( stack ( ) [ 1 ] [ 1 ] ) )
if os . path . exists ( directory ) :
return directory |
def listVersionHistory ( store ) :
"""List the software package version history of store .""" | q = store . query ( SystemVersion , sort = SystemVersion . creation . descending )
return [ sv . longWindedRepr ( ) for sv in q ] |
def diff_speed ( sw_dens = 1.028 , dens_gcm3 = 1.053 , seal_length = 300 , seal_girth = 200 , Cd = 0.09 ) :
'''Calculate terminal velocity of animal with a body size
Args
sw _ dens : float
Density of seawater ( g / cm ^ 3)
dens _ gcm3 : float
Density of animal ( g / cm ^ 3)
seal _ length : float
Lengt... | import numpy
surf , vol = surf_vol ( seal_length , seal_girth )
Fb = buoyant_force ( dens_gcm3 , vol , sw_dens )
x = 2 * ( Fb / ( Cd * sw_dens * ( surf * 1000 ) ) )
if x >= 0 :
Vt = numpy . sqrt ( x )
else :
Vt = - numpy . sqrt ( - x )
return Vt |
def verify_dir_structure ( full_path ) :
'''Check if given directory to see if it is usable by s2.
Checks that all required directories exist under the given
directory , and also checks that they are writable .''' | if full_path == None :
return False
r = True
for d2c in PREDEFINED_DIR_NAMES : # if d2c = = " s2 " :
# d2c = " . s2"
cp2c = os . path . join ( full_path , d2c )
# complete path to check
if not os . path . isdir ( cp2c ) :
r = False
break
else : # exists , let ' s check it ' s writabl... |
def modify_product_status ( self , standard , key , status ) :
"""提交审核 / 取消发布商品
详情请参考
http : / / mp . weixin . qq . com / wiki / 15/1007691d0f1c10a0588c6517f12ed70f . html
: param standard : 商品编码标准
: param key : 商品编码内容
: param status : 设置发布状态 。 on 为提交审核 , off 为取消发布
: return : 返回的 JSON 数据包""" | data = { 'keystandard' : standard , 'keystr' : key , 'status' : status , }
return self . _post ( 'product/modstatus' , data = data ) |
def _closeResources ( self ) :
"""Closes the root Dataset .""" | logger . info ( "Closing: {}" . format ( self . _fileName ) )
self . _h5Group . close ( )
self . _h5Group = None |
def historic_doslegs_parse ( html , url_an = None , logfile = sys . stderr , nth_dos_in_page = 0 , parse_previous_works = True , parse_next_works = True ) :
"""Parse an AN dosleg like http : / / www . assemblee - nationale . fr / 13 / dossiers / accord _ Montenegro _ mobilite _ jeunes . asp
nth _ dos _ in _ page ... | data = { 'url_dossier_assemblee' : clean_url ( url_an ) , 'urgence' : False , }
def log_error ( * error ) :
print ( '## ERROR ###' , * error , file = logfile )
def log_warning ( * error ) :
print ( '## WARNING ###' , * error , file = logfile )
soup = BeautifulSoup ( html , 'lxml' )
legislature , slug = parse_na... |
def _create_thumbnail ( self , model_instance , thumbnail , image_name ) :
"""Resizes and saves the thumbnail image""" | thumbnail = self . _do_resize ( thumbnail , self . thumbnail_size )
full_image_name = self . generate_filename ( model_instance , image_name )
thumbnail_filename = _get_thumbnail_filename ( full_image_name )
thumb = self . _get_simple_uploaded_file ( thumbnail , thumbnail_filename )
self . storage . save ( thumbnail_fi... |
def weighted_sum ( matrix : torch . Tensor , attention : torch . Tensor ) -> torch . Tensor :
"""Takes a matrix of vectors and a set of weights over the rows in the matrix ( which we call an
" attention " vector ) , and returns a weighted sum of the rows in the matrix . This is the typical
computation performed... | # We ' ll special - case a few settings here , where there are efficient ( but poorly - named )
# operations in pytorch that already do the computation we need .
if attention . dim ( ) == 2 and matrix . dim ( ) == 3 :
return attention . unsqueeze ( 1 ) . bmm ( matrix ) . squeeze ( 1 )
if attention . dim ( ) == 3 an... |
def from_bucket ( self , bucket , native = False ) :
'''Calculate the timestamp given a bucket .''' | # NOTE : this is due to a bug somewhere in strptime that does not process
# the week number of ' % Y % U ' correctly . That bug could be very specific to
# the combination of python and ubuntu that I was testing .
bucket = str ( bucket )
if self . _step == 'weekly' :
year , week = bucket [ : 4 ] , bucket [ 4 : ]
... |
def attach_related_file ( self , path , mimetype = None ) :
"""Attaches a file from the filesystem .""" | filename = os . path . basename ( path )
content = open ( path , 'rb' ) . read ( )
self . attach_related ( filename , content , mimetype ) |
def update ( self , instance ) :
'''Update a record to the table
emp = Employee ( emp _ id = 1 , name = ' John Doe ' , sex = ' Female ' )
updated = Session ( ) . add ( emp )
Returns a bool or raises mysql . Error exception''' | if not self . exists ( instance . __class__ , instance . id ) :
print ( "Cant update a value that does not exist" )
return False
instance_dict = vars ( instance )
table = instance . __class__ . __name__ . lower ( )
keys = ", " . join ( instance_dict . keys ( ) )
values = tuple ( instance_dict . values ( ) )
SQL... |
def validate_source_dir ( script , directory ) :
"""Validate that the source directory exists and it contains the user script
Args :
script ( str ) : Script filename .
directory ( str ) : Directory containing the source file .
Raises :
ValueError : If ` ` directory ` ` does not exist , is not a directory ... | if directory :
if not os . path . isfile ( os . path . join ( directory , script ) ) :
raise ValueError ( 'No file named "{}" was found in directory "{}".' . format ( script , directory ) )
return True |
def to_csv ( col , options = { } ) :
"""Converts a column containing a : class : ` StructType ` into a CSV string .
Throws an exception , in the case of an unsupported type .
: param col : name of column containing a struct .
: param options : options to control converting . accepts the same options as the CS... | sc = SparkContext . _active_spark_context
jc = sc . _jvm . functions . to_csv ( _to_java_column ( col ) , options )
return Column ( jc ) |
def attrs ( self ) :
"""Returns a dictionary of the archive ' s attributes .""" | return dict ( ( k , v ) for k , v in iteritems ( self . __dict__ ) if k is not "sdk" ) |
def _evaluate_usecols ( usecols , names ) :
"""Check whether or not the ' usecols ' parameter
is a callable . If so , enumerates the ' names '
parameter and returns a set of indices for
each entry in ' names ' that evaluates to True .
If not a callable , returns ' usecols ' .""" | if callable ( usecols ) :
return { i for i , name in enumerate ( names ) if usecols ( name ) }
return usecols |
def stream ( self , accountID , ** kwargs ) :
"""Get a stream of Transactions for an Account starting from when the
request is made .
Args :
accountID :
Account Identifier
Returns :
v20 . response . Response containing the results from submitting the
request""" | request = Request ( 'GET' , '/v3/accounts/{accountID}/transactions/stream' )
request . set_path_param ( 'accountID' , accountID )
request . set_stream ( True )
class Parser ( ) :
def __init__ ( self , ctx ) :
self . ctx = ctx
def __call__ ( self , line ) :
j = json . loads ( line . decode ( 'utf... |
def gen_df_site ( list_csv_in = list_table , url_base = url_repo_input_site ) -> pd . DataFrame :
'''Generate description info of supy output results as a dataframe
Parameters
path _ csv _ out : str , optional
path to the output csv file ( the default is ' df _ output . csv ' )
list _ csv _ in : list , opti... | # list of URLs
list_url_table = [ url_base / table for table in list_csv_in ]
try :
df_var_info = pd . concat ( [ pd . read_csv ( f ) for f in list_url_table ] )
# df _ var _ info = pd . concat (
# [ pd . read _ csv ( f ) for f in list _ url _ table ] ,
# sort = False )
except :
for url in list_url_... |
async def start ( self , connection : 'Connection' ) -> 'ClientResponse' :
"""Start response processing .""" | self . _closed = False
self . _protocol = connection . protocol
self . _connection = connection
with self . _timer :
while True : # read response
try :
message , payload = await self . _protocol . read ( )
# type : ignore # noqa
except http . HttpProcessingError as exc :
... |
def loads ( cls , s ) :
"""Parse the contents of the string ` ` s ` ` as a simple line - oriented
` ` . properties ` ` file and return a ` PropertiesFile ` instance .
` ` s ` ` may be either a text string or bytes string . If it is a bytes
string , its contents are decoded as Latin - 1.
. . versionchanged :... | if isinstance ( s , six . binary_type ) :
fp = six . BytesIO ( s )
else :
fp = six . StringIO ( s )
return cls . load ( fp ) |
def get_courses ( self ) :
"""use the base _ url and auth data from the configuration to list all courses the user is subscribed to""" | log . info ( "Listing Courses..." )
courses = json . loads ( self . _get ( '/api/courses' ) . text ) [ "courses" ]
courses = [ Course . from_response ( course ) for course in courses ]
log . debug ( "Courses: %s" % [ str ( entry ) for entry in courses ] )
return courses |
def add_token ( self , token , token_handler , request ) :
""": param token :
: param token _ handler : A token handler instance , for example of type
oauthlib . oauth2 . BearerToken .
: param request : OAuthlib request .
: type request : oauthlib . common . Request""" | # Only add a hybrid access token on auth step if asked for
if not request . response_type in [ "token" , "code token" , "id_token token" , "code id_token token" ] :
return token
token . update ( token_handler . create_token ( request , refresh_token = False ) )
return token |
def sectionsWord ( self , walkTrace = tuple ( ) , case = None , element = None , doc = None ) :
"""Prepares section for word output .""" | from docx . shared import Inches
from io import BytesIO
# p . add _ run ( ' italic . ' ) . italic = True
if case == 'sectionmain' :
if self . settings [ 'clearpage' ] :
doc . add_page_break ( )
doc . add_heading ( self . title , level = len ( walkTrace ) )
for p in renewliner ( self . p ) . split ( ... |
def get_closing_rule_for_now ( location ) :
"""Returns QuerySet of ClosingRules that are currently valid""" | now = get_now ( )
if location :
return ClosingRules . objects . filter ( company = location , start__lte = now , end__gte = now )
return Company . objects . first ( ) . closingrules_set . filter ( start__lte = now , end__gte = now ) |
def find_package ( name , installed , package = False ) :
'''Finds a package in the installed list .
If ` package ` is true , match package names , otherwise , match import paths .''' | if package :
name = name . lower ( )
tests = ( lambda x : x . user and name == x . name . lower ( ) , lambda x : x . local and name == x . name . lower ( ) , lambda x : name == x . name . lower ( ) , )
else :
tests = ( lambda x : x . user and name in x . import_names , lambda x : x . local and name in x . i... |
def get_occupancy ( last , bucketsize ) :
"""We deliver historical occupancy up until " now " . If the building has occupancy sensors , we pull that data
and aggregate it by zone . Take mean occupancy per zone ( across all sensors ) .
If building does * not * have occupancy sensors , then we need to read the re... | if last not in [ 'hour' , 'day' , 'week' ] :
return "Must be hour, day, week"
start_date = get_start ( last )
zones = defaultdict ( list )
prediction_start = datetime . now ( config . TZ )
md = config . HOD . do_query ( occupancy_query )
if md [ 'Rows' ] is not None :
for row in md [ 'Rows' ] :
zones [ ... |
def save ( self , obj , data , is_m2m = False ) :
"""If this field is not declared readonly , the object ' s attribute will
be set to the value returned by : meth : ` ~ import _ export . fields . Field . clean ` .""" | if not self . readonly :
attrs = self . attribute . split ( '__' )
for attr in attrs [ : - 1 ] :
obj = getattr ( obj , attr , None )
cleaned = self . clean ( data )
if cleaned is not None or self . saves_null_values :
if not is_m2m :
setattr ( obj , attrs [ - 1 ] , cleaned )
... |
def get_summed_icohp_by_label_list ( self , label_list , divisor = 1.0 , summed_spin_channels = True , spin = Spin . up ) :
"""get the sum of several ICOHP values that are indicated by a list of labels ( labels of the bonds are the same as in ICOHPLIST / ICOOPLIST )
Args :
label _ list : list of labels of the I... | sum_icohp = 0
for label in label_list :
icohp_here = self . _icohplist [ label ]
if icohp_here . num_bonds != 1 :
warnings . warn ( "One of the ICOHP values is an average over bonds. This is currently not considered." )
# prints warning if num _ bonds is not equal to 1
if icohp_here . _is_spin_p... |
def _g ( self , z ) :
"""Helper function to solve Frank copula .
This functions encapsulates : math : ` g _ z = e ^ { - \\ theta z } - 1 ` used on Frank copulas .
Argument :
z : np . ndarray
Returns :
np . ndarray""" | return np . exp ( np . multiply ( - self . theta , z ) ) - 1 |
def build ( args ) :
"""Build the documentation for the projects specified in the CLI .
It will do 4 different things for each project the
user asks for ( see flags ) :
1 . Update mkdocs ' s index . md file with links to project
documentations
2 . Build these documentations
3 . Update the documentations... | # Proceed ?
go = False
# Current working directory
dir_path = Path ( ) . resolve ( )
# Set of all available projects in the dir
# Projects must contain a PROJECT _ MARKER file .
all_projects = { m for m in os . listdir ( dir_path ) if os . path . isdir ( m ) and "source" in os . listdir ( dir_path / m ) }
if args . all... |
def package_url ( self ) :
"""Return the package URL associated with this metadata""" | return MetapackDocumentUrl ( str ( self . clear_fragment ( ) ) , downloader = self . _downloader ) . package_url |
def _receiveFromRemotes ( self , quotaPerRemote ) -> int :
"""Receives messages from remotes
: param quotaPerRemote : number of messages to receive from one remote
: return : number of received messages""" | assert quotaPerRemote
totalReceived = 0
for ident , remote in self . remotesByKeys . items ( ) :
if not remote . socket :
continue
i = 0
sock = remote . socket
while i < quotaPerRemote :
try :
msg , = sock . recv_multipart ( flags = zmq . NOBLOCK )
if not msg : # ... |
def save ( self , path : Union [ str , bytes , int ] ) -> None :
"""Write QASM output to a file specified by path .""" | with open ( path , 'w' ) as f :
def write ( s : str ) -> None :
f . write ( s )
self . _write_qasm ( write ) |
def create_widget ( self ) :
"""Create the underlying widget .
A dialog is not a subclass of view , hence we don ' t set name as widget
or children will try to use it as their parent .""" | d = self . declaration
self . dialog = Dialog ( self . get_context ( ) , d . style ) |
def modularity_und_sign ( W , ci , qtype = 'sta' ) :
'''This function simply calculates the signed modularity for a given
partition . It does not do automatic partition generation right now .
Parameters
W : NxN np . ndarray
undirected weighted / binary connection matrix with positive and
negative weights ... | n = len ( W )
_ , ci = np . unique ( ci , return_inverse = True )
ci += 1
W0 = W * ( W > 0 )
# positive weights matrix
W1 = - W * ( W < 0 )
# negative weights matrix
s0 = np . sum ( W0 )
# positive sum of weights
s1 = np . sum ( W1 )
# negative sum of weights
Knm0 = np . zeros ( ( n , n ) )
# positive node - to - modul... |
def counting_sort ( arr ) :
"""Counting _ sort
Sorting a array which has no element greater than k
Creating a new temp _ arr , where temp _ arr [ i ] contain the number of
element less than or equal to i in the arr
Then placing the number i into a correct position in the result _ arr
return the result _ a... | m = min ( arr )
# in case there are negative elements , change the array to all positive element
different = 0
if m < 0 : # save the change , so that we can convert the array back to all positive number
different = - m
for i in range ( len ( arr ) ) :
arr [ i ] += - m
k = max ( arr )
temp_arr = [ 0 ] * ... |
def local_property ( ) :
"""Property structure which maps within the : func : local ( ) thread
( c ) 2014 , Marcel Hellkamp""" | ls = local ( )
def fget ( self ) :
try :
return ls . var
except AttributeError :
raise RuntimeError ( "Request context not initialized." )
def fset ( self , value ) :
ls . var = value
def fdel ( self ) :
del ls . var
return property ( fget , fset , fdel , 'Thread-local property' ) |
def _local_run ( self , run_conf ) :
'''Execute local runner
: param run _ conf :
: return :''' | try :
ret = self . _get_runner ( run_conf ) . run ( )
except SystemExit :
ret = 'Runner is not available at this moment'
self . out . error ( ret )
except Exception as ex :
ret = 'Unhandled exception occurred: {}' . format ( ex )
log . debug ( ex , exc_info = True )
return ret |
def initialize ( self ) :
"""Initialize operation by generating new keys .""" | self . _signing_key = SigningKey ( os . urandom ( 32 ) )
self . _auth_private = self . _signing_key . to_seed ( )
self . _auth_public = self . _signing_key . get_verifying_key ( ) . to_bytes ( )
self . _verify_private = curve25519 . Private ( secret = os . urandom ( 32 ) )
self . _verify_public = self . _verify_private... |
def ensure_dir ( path ) :
"""Create all parent directories of path if they don ' t exist .
Args :
path . Path - like object . Create parent dirs to this path .
Return :
None .""" | os . makedirs ( os . path . abspath ( os . path . dirname ( path ) ) , exist_ok = True ) |
def _get_salt_params ( ) :
'''Try to get all sort of parameters for Server Density server info .
NOTE : Missing publicDNS and publicIPs parameters . There might be way of
getting them with salt - cloud .''' | all_stats = __salt__ [ 'status.all_status' ] ( )
all_grains = __salt__ [ 'grains.items' ] ( )
params = { }
try :
params [ 'name' ] = all_grains [ 'id' ]
params [ 'hostname' ] = all_grains [ 'host' ]
if all_grains [ 'kernel' ] == 'Darwin' :
sd_os = { 'code' : 'mac' , 'name' : 'Mac' }
else :
... |
def get_returns_no_block ( self , tag , match_type = None ) :
'''Raw function to just return events of jid excluding timeout logic
Yield either the raw event data or None
Pass a list of additional regular expressions as ` tags _ regex ` to search
the event bus for non - return data , such as minion lists retu... | while True :
raw = self . event . get_event ( wait = 0.01 , tag = tag , match_type = match_type , full = True , no_block = True , auto_reconnect = self . auto_reconnect )
yield raw |
def random_word ( self , * args , ** kwargs ) :
"""Return a random word from this tree . The length of the word depends on
the this tree .
: return : a random word from this tree .
args and kwargs are ignored .""" | word = ""
current = ( ">" , 0 )
while current [ 0 ] != "<" :
choices = self [ current ]
choice = random_weighted_choice ( choices )
current = choice
word += current [ 0 ] [ - 1 ]
return word [ : - 1 ] |
def disconnect_signals ( self ) :
"""Disable the signals within the work . This function reverses the process of ` connect _ signals `""" | for task in self :
try :
dispatcher . disconnect ( self . on_ok , signal = task . S_OK , sender = task )
except dispatcher . errors . DispatcherKeyError as exc :
logger . debug ( str ( exc ) ) |
def handle ( conn , addr , gateway , * args , ** kwargs ) :
"""NOTE : use tcp instead of udp because some operations need ack""" | conn . sendall ( b'OK pubsub 1.0\n' )
while True :
try :
s = conn . recv ( 1024 ) . decode ( 'utf-8' ) . strip ( )
if not s :
conn . close ( )
break
except ConnectionResetError :
logger . debug ( 'Client close the connection.' )
break
parts = s . split... |
def insert ( self , filename ) :
"""Parses files to load them into memory and insert them into the class .
: param filename : File or directory pointing to . ioc files .
: return : A list of . ioc files which could not be parsed .""" | errors = [ ]
if os . path . isfile ( filename ) :
log . info ( 'loading IOC from: {}' . format ( filename ) )
try :
self . parse ( ioc_api . IOC ( filename ) )
except ioc_api . IOCParseError :
log . exception ( 'Parse Error' )
errors . append ( filename )
elif os . path . isdir ( fil... |
def merge_conf_file ( self , result , conf_file_path ) :
"Merge a configuration in file with current configuration" | conf = parse_conf_file ( conf_file_path )
conf_file_name = os . path . splitext ( os . path . basename ( conf_file_path ) ) [ 0 ]
result_part = result
if not conf_file_name in File . TOP_LEVEL_CONF_FILES and ( not "top_level" in self . _options or not self . _options [ "top_level" ] ) :
for key_part in conf_file_na... |
def install ( ctx , plugin ) :
"""Install the given plugin .""" | ensure_inside_venv ( ctx )
plugin_name = get_plugin_name ( plugin )
try :
info = get_plugin_info ( plugin_name )
except NameError :
echo_error ( "Plugin {} could not be found." . format ( plugin ) )
sys . exit ( 1 )
except ValueError as e :
echo_error ( "Unable to retrieve plugin info. " "Error was:\n\n... |
def refresh_interval ( self , refresh_interval ) :
"""Set the new cache refresh interval""" | if isinstance ( refresh_interval , int ) and refresh_interval > 0 :
self . _refresh_interval = refresh_interval
else :
self . _refresh_interval = None |
def _receive_with_timeout ( self , socket , timeout_s , use_multipart = False ) :
"""Check for socket activity and either return what ' s
received on the socket or time out if timeout _ s expires
without anything on the socket .
This is implemented in loops of self . try _ length _ ms milliseconds
to allow ... | if timeout_s is config . FOREVER :
timeout_ms = config . FOREVER
else :
timeout_ms = int ( 1000 * timeout_s )
poller = zmq . Poller ( )
poller . register ( socket , zmq . POLLIN )
ms_so_far = 0
try :
for interval_ms in self . intervals_ms ( timeout_ms ) :
sockets = dict ( poller . poll ( interval_ms... |
def grid_prep ( self ) :
"""prepare grid - based parameterizations""" | if len ( self . grid_props ) == 0 :
return
if self . grid_geostruct is None :
self . logger . warn ( "grid_geostruct is None," " using ExpVario with contribution=1 and a=(max(delc,delr)*10" )
dist = 10 * float ( max ( self . m . dis . delr . array . max ( ) , self . m . dis . delc . array . max ( ) ) )
... |
def deliver ( self , project , new_project_name , to_user , share_users , force_send , path_filter , user_message ) :
"""Remove access to project _ name for to _ user , copy to new _ project _ name if not None ,
send message to service to email user so they can have access .
: param project : RemoteProject pre ... | if self . _is_current_user ( to_user ) :
raise ShareWithSelfError ( SHARE_WITH_SELF_MESSAGE . format ( "deliver" ) )
if not to_user . email :
self . _raise_user_missing_email_exception ( "deliver" )
self . remove_user_permission ( project , to_user )
if new_project_name :
project = self . _copy_project ( pr... |
def parse_flag ( exception_message ) :
"""Parse the flag from the solver exception .
e . g .
> > > parse _ flag ( " Exception : Dopri5 failed with flag - 3 " )
: param exception _ message : message from the exception
: type exception _ message : str
: return : flag id
: rtype : int""" | import re
match = re . match ( '.* failed with flag (-\d+)' , exception_message )
try :
return int ( match . group ( 1 ) )
except Exception :
return None |
def balance ( self , account : Address ) :
"""Return the balance of the account of the given address .""" | return self . web3 . eth . getBalance ( to_checksum_address ( account ) , 'pending' ) |
def _get_interval_closed_bounds ( interval ) :
"""Given an Interval or IntervalIndex , return the corresponding interval with
closed bounds .""" | left , right = interval . left , interval . right
if interval . open_left :
left = _get_next_label ( left )
if interval . open_right :
right = _get_prev_label ( right )
return left , right |
def link_parameter ( self , param , index = None ) :
""": param parameters : the parameters to add
: type parameters : list of or one : py : class : ` paramz . param . Param `
: param [ index ] : index of where to put parameters
Add all parameters to this param class , you can insert parameters
at any given... | if param in self . parameters and index is not None :
self . unlink_parameter ( param )
return self . link_parameter ( param , index )
# elif param . has _ parent ( ) :
# raise HierarchyError , " parameter { } already in another model ( { } ) , create new object ( or copy ) for adding " . format ( param . _ sho... |
def get_path ( self ) :
"""Returns a temporary file path based on a MD5 hash generated with the task ' s name and its arguments""" | md5_hash = hashlib . md5 ( self . task_id . encode ( ) ) . hexdigest ( )
logger . debug ( 'Hash %s corresponds to task %s' , md5_hash , self . task_id )
return os . path . join ( self . temp_dir , str ( self . unique . value ) , md5_hash ) |
def get_tile_info ( tile , time , aws_index = None , all_tiles = False ) :
"""Get basic information about image tile
: param tile : tile name ( e . g . ` ` ' T10UEV ' ` ` )
: type tile : str
: param time : A single date or a time interval , times have to be in ISO 8601 string
: type time : str or ( str , st... | start_date , end_date = parse_time_interval ( time )
candidates = [ ]
for tile_info in search_iter ( start_date = start_date , end_date = end_date ) :
path_props = tile_info [ 'properties' ] [ 's3Path' ] . split ( '/' )
this_tile = '' . join ( path_props [ 1 : 4 ] )
this_aws_index = int ( path_props [ - 1 ]... |
def listFileSummaries ( self , block_name = '' , dataset = '' , run_num = - 1 , validFileOnly = 0 , sumOverLumi = 0 ) :
"""API to list number of files , event counts and number of lumis in a given block or dataset .
If the optional run _ num , output are :
* The number of files which have data ( lumis ) for tha... | # run _ num = 1 caused full table scan and CERN DBS reported some of the queries ran more than 50 hours
# We will disbale all the run _ num = 1 calls in DBS .
# YG Jan . 16 2019
if ( run_num != - 1 ) :
for r in parseRunRange ( run_num ) :
if isinstance ( r , basestring ) or isinstance ( r , int ) or isinsta... |
def unique ( g ) :
"""Yield values yielded by ` ` g ` ` , removing any duplicates .
Example
> > > list ( unique ( iter ( [ 1 , 3 , 1 , 2 , 3 ] ) ) )
[1 , 3 , 2]""" | yielded = set ( )
for value in g :
if value not in yielded :
yield value
yielded . add ( value ) |
def size ( self ) :
"""Return the total size in bytes of all the files handled by this instance of fsdb .
Fsdb does not use auxiliary data structure , so this function could be expensive .
Look at _ iter _ over _ paths ( ) functions for more details .""" | tot = 0
for p in self . __iter__ ( overPath = True ) :
tot += os . path . getsize ( p )
return tot |
def load ( fnames , tag = None , sat_id = None , obs_long = 0. , obs_lat = 0. , obs_alt = 0. , TLE1 = None , TLE2 = None ) :
"""Returns data and metadata in the format required by pysat . Finds position
of satellite in both ECI and ECEF co - ordinates .
Routine is directly called by pysat and not the user .
P... | import sgp4
# wgs72 is the most commonly used gravity model in satellite tracking community
from sgp4 . earth_gravity import wgs72
from sgp4 . io import twoline2rv
import ephem
import pysatMagVect
# TLEs ( Two Line Elements for ISS )
# format of TLEs is fixed and available from wikipedia . . .
# lines encode list of or... |
def multiple_extend_request_args ( self , args , key , parameters , item_types , orig = False ) :
"""Go through a set of items ( by their type ) and add the attribute - value
that match the list of parameters to the arguments
If the same parameter occurs in 2 different items then the value in
the later one wi... | _state = self . get_state ( key )
for typ in item_types :
try :
_item = Message ( ** _state [ typ ] )
except KeyError :
continue
for parameter in parameters :
if orig :
try :
args [ parameter ] = _item [ parameter ]
except KeyError :
... |
def couchdb_admin_party ( ** kwargs ) :
"""Provides a context manager to create a CouchDB session in Admin Party mode
and provide access to databases , docs etc .
: param str url : URL for CouchDB server .
: param str encoder : Optional json Encoder object used to encode
documents for storage . Defaults to ... | couchdb_session = CouchDB ( None , None , True , ** kwargs )
couchdb_session . connect ( )
yield couchdb_session
couchdb_session . disconnect ( ) |
def create_domain_record ( self , domain_id , record_type , data , name = None , priority = None , port = None , weight = None ) :
"""This method creates a new domain name with an A record for the specified
[ ip _ address ] .
Required parameters
domain _ id :
Integer or Domain Name ( e . g . domain . com ) ... | params = dict ( record_type = record_type , data = data )
if name :
params . update ( { 'name' : name } )
if priority :
params . update ( { 'priority' : priority } )
if port :
params . update ( { 'port' : port } )
if weight :
params . update ( { 'weight' : weight } )
json = self . request ( '/domains/%s... |
def find_multifile_object_children ( self , parent_location , no_errors : bool = False ) -> Dict [ str , str ] :
"""Implementation of the parent abstract method .
In this mode , each item is a set of files with the same prefix than location , separated from the
attribute name by the character sequence < self . ... | if parent_location == '' :
parent_location = '.'
# (1 ) Find the base directory and base name
if isdir ( parent_location ) : # special case : parent location is the root folder where all the files are .
parent_dir = parent_location
base_prefix = ''
start_with = ''
else :
parent_dir = dirname ( paren... |
def run ( self , error_on_warning = False , verbose = False ) :
"""Main entry point .""" | warnings , criticals = self . check_limits ( verbose = verbose )
# output
if len ( warnings ) > 0 :
print ( "\nWARNING:\n" )
for w in warnings :
print ( w )
if len ( criticals ) > 0 :
print ( "\nCRITICAL:\n" )
for c in criticals :
print ( c )
# summary
if len ( warnings ) > 0 or len ( cr... |
def cylinder_inertia ( mass , radius , height , transform = None ) :
"""Return the inertia tensor of a cylinder .
Parameters
mass : float
Mass of cylinder
radius : float
Radius of cylinder
height : float
Height of cylinder
transform : ( 4,4 ) float
Transformation of cylinder
Returns
inertia : ... | h2 , r2 = height ** 2 , radius ** 2
diagonal = np . array ( [ ( ( mass * h2 ) / 12 ) + ( ( mass * r2 ) / 4 ) , ( ( mass * h2 ) / 12 ) + ( ( mass * r2 ) / 4 ) , ( mass * r2 ) / 2 ] )
inertia = diagonal * np . eye ( 3 )
if transform is not None :
inertia = transform_inertia ( transform , inertia )
return inertia |
def emit ( self , span_datas ) :
""": type span _ datas : list of : class :
` ~ opencensus . trace . span _ data . SpanData `
: param span _ datas :
SpanData tuples to emit""" | jaeger_spans = self . translate_to_jaeger ( span_datas )
batch = jaeger . Batch ( spans = jaeger_spans , process = jaeger . Process ( serviceName = self . service_name ) )
if self . collector is not None :
self . collector . export ( batch )
self . agent_client . export ( batch ) |
def DebyeChain ( q , Rg ) :
"""Scattering form - factor intensity of a Gaussian chain ( Debye )
Inputs :
` ` q ` ` : independent variable
` ` Rg ` ` : radius of gyration
Formula :
` ` 2 * ( exp ( - a ) - 1 + a ) / a ^ 2 ` ` where ` ` a = ( q * Rg ) ^ 2 ` `""" | a = ( q * Rg ) ** 2
return 2 * ( np . exp ( - a ) - 1 + a ) / a ** 2 |
def distance_quat ( p1 , p2 ) :
"""Returns the angle between two quaternions
http : / / math . stackexchange . com / a / 90098
: param q1 , q2 : two quaternions [ x , y , z , w ] or two poses [ [ x , y , z ] , [ x , y , z , w ] ] or two PoseStamped
: return : the angle between them ( radians )""" | if isinstance ( p1 , PoseStamped ) :
p1 = pose_to_list ( p1 )
if isinstance ( p2 , PoseStamped ) :
p2 = pose_to_list ( p2 )
if _is_indexable ( p1 ) and _is_indexable ( p1 [ 0 ] ) :
p1 = p1 [ 1 ]
p2 = p2 [ 1 ]
dotp = inner ( array ( p1 ) , array ( p2 ) )
return arccos ( 2 * dotp * dotp - 1 ) |
def _float_copy_to_out ( out , origin ) :
"""Copy origin to out and return it .
If ` ` out ` ` is None , a new copy ( casted to floating point ) is used . If
` ` out ` ` and ` ` origin ` ` are the same , we simply return it . Otherwise we
copy the values .""" | if out is None :
out = origin / 1
# The division forces cast to a floating point type
elif out is not origin :
np . copyto ( out , origin )
return out |
def nx_ensure_agraph_color ( graph ) :
"""changes colors to hex strings on graph attrs""" | from plottool import color_funcs
import plottool as pt
# import six
def _fix_agraph_color ( data ) :
try :
orig_color = data . get ( 'color' , None )
alpha = data . get ( 'alpha' , None )
color = orig_color
if color is None and alpha is not None :
color = [ 0 , 0 , 0 ]
... |
def chol ( A ) :
"""Calculate the lower triangular matrix of the Cholesky decomposition of
a symmetric , positive - definite matrix .""" | A = np . array ( A )
assert A . shape [ 0 ] == A . shape [ 1 ] , "Input matrix must be square"
L = [ [ 0.0 ] * len ( A ) for _ in range ( len ( A ) ) ]
for i in range ( len ( A ) ) :
for j in range ( i + 1 ) :
s = sum ( L [ i ] [ k ] * L [ j ] [ k ] for k in range ( j ) )
L [ i ] [ j ] = ( ( A [ i ]... |
def pan_cb ( self , setting , value ) :
"""Handle callback related to changes in pan .""" | pan_x , pan_y = value [ : 2 ]
self . logger . debug ( "pan set to %.2f,%.2f" % ( pan_x , pan_y ) )
self . redraw ( whence = 0 ) |
def FileEntryExistsByPathSpec ( self , path_spec ) :
"""Determines if a file entry for a path specification exists .
Args :
path _ spec ( PathSpec ) : path specification .
Returns :
bool : True if the file entry exists .
Raises :
BackEndError : if the file entry cannot be opened .""" | # Opening a file by MFT entry is faster than opening a file by location .
# However we need the index of the corresponding $ FILE _ NAME MFT attribute .
fsntfs_file_entry = None
location = getattr ( path_spec , 'location' , None )
mft_attribute = getattr ( path_spec , 'mft_attribute' , None )
mft_entry = getattr ( path... |
def read_userpass ( self , username , mount_point = 'userpass' ) :
"""GET / auth / < mount point > / users / < username >
: param username :
: type username :
: param mount _ point :
: type mount _ point :
: return :
: rtype :""" | return self . _adapter . get ( '/v1/auth/{}/users/{}' . format ( mount_point , username ) ) . json ( ) |
def set_iscsi_info ( self , target_name , lun , ip_address , port = '3260' , auth_method = None , username = None , password = None ) :
"""Set iscsi details of the system in uefi boot mode .
The initiator system is set with the target details like
IQN , LUN , IP , Port etc .
: param target _ name : Target Nam... | return self . _call_method ( 'set_iscsi_info' , target_name , lun , ip_address , port , auth_method , username , password ) |
def delete_role_from_user ( self , role , user ) :
"""Deletes the specified role from the specified user .
There is no return value upon success . Passing a non - existent role or
user raises a NotFound exception .""" | uri = "users/%s/roles/OS-KSADM/%s" % ( utils . get_id ( user ) , utils . get_id ( role ) )
resp , resp_body = self . method_delete ( uri ) |
def exclude_fields ( obj , exclude = EXCLUDE ) :
"""Return dict of object without parent attrs .""" | return dict ( [ ( k , getattr ( obj , k ) ) for k in obj . __slots__ if k not in exclude ] ) |
def sample ( self , n , returnaAdt = False , returndt = False , interp = None , xy = False , lb = False ) :
"""NAME :
sample
PURPOSE :
sample from the DF
INPUT :
n - number of points to return
returnaAdt = ( False ) if True , return ( Omega , angle , dt )
returndT = ( False ) if True , also return the... | # First sample frequencies
Om , angle , dt = self . _sample_aAt ( n )
if returnaAdt :
if _APY_UNITS and self . _voSet and self . _roSet :
Om = units . Quantity ( Om * bovy_conversion . freq_in_Gyr ( self . _vo , self . _ro ) , unit = 1 / units . Gyr )
angle = units . Quantity ( angle , unit = units ... |
def run ( self ) :
"""The main routine for a thread ' s work .
The thread pulls tasks from the manager ' s task queue and executes
them until it encounters a task with a function that is None .""" | try :
while True :
aFunction , arguments = self . manager . taskQueue . get ( )
if aFunction is None :
break
aFunction ( arguments )
except KeyboardInterrupt :
import thread
print >> sys . stderr , "%s caught KeyboardInterrupt" % threading . currentThread ( ) . getName ( ... |
def _build_graph ( self ) :
"""Produce a dependency graph based on a list
of tasks produced by the parser .""" | self . _graph . add_nodes_from ( self . tasks )
for node1 in self . _graph . nodes :
for node2 in self . _graph . nodes :
for input_file in node1 . inputs :
for output_file in node2 . outputs :
if output_file == input_file :
self . _graph . add_edge ( node2 , ... |
def get_name_servers ( self , id_or_uri ) :
"""Gets the named servers for an interconnect .
Args :
id _ or _ uri : Can be either the interconnect id or the interconnect uri .
Returns :
dict : the name servers for an interconnect .""" | uri = self . _client . build_uri ( id_or_uri ) + "/nameServers"
return self . _client . get ( uri ) |
def add_queue_handler ( queue ) :
"""Add a queue log handler to the global logger .""" | handler = QueueLogHandler ( queue )
handler . setFormatter ( QueueFormatter ( ) )
handler . setLevel ( DEBUG )
GLOBAL_LOGGER . addHandler ( handler ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.