signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def quality_comparator ( video_data ) :
"""Custom comparator used to choose the right format based on the resolution .""" | def parse_resolution ( res : str ) -> Tuple [ int , ... ] :
return tuple ( map ( int , res . split ( 'x' ) ) )
raw_resolution = video_data [ 'resolution' ]
resolution = parse_resolution ( raw_resolution )
return resolution |
def group_list ( auth = None , ** kwargs ) :
'''List groups
CLI Example :
. . code - block : : bash
salt ' * ' keystoneng . group _ list
salt ' * ' keystoneng . group _ list domain _ id = b62e76fbeeff4e8fb77073f591cf211e''' | cloud = get_operator_cloud ( auth )
kwargs = _clean_kwargs ( ** kwargs )
return cloud . list_groups ( ** kwargs ) |
def _get_start_end_nans ( data ) :
"""Find NaN values in data that either start or end the time - series
Function to return a binary array of same size as data where ` True ` values correspond to NaN values present at
beginning or end of time - series . NaNs internal to the time - series are not included in the... | # find NaNs that start a time - series
start_nan = np . isnan ( data )
for idx , row in enumerate ( start_nan [ : - 1 ] ) :
start_nan [ idx + 1 ] = np . logical_and ( row , start_nan [ idx + 1 ] )
# find NaNs that end a time - series
end_nan = np . isnan ( data )
for idx , row in enumerate ( end_nan [ - 2 : : - 1 ]... |
def iter_related ( self ) :
'''Generator function that iterates this object ' s related providers ,
which includes this provider .''' | for tpl in self . provider_run . templates :
yield tpl . providers [ self . index ] |
def perp ( weights ) :
r"""Calculate the normalized perplexity : math : ` \ mathcal { P } ` of samples
with ` ` weights ` ` : math : ` \ omega _ i ` . : math : ` \ mathcal { P } = 0 ` is
terrible and : math : ` \ mathcal { P } = 1 ` is perfect .
. . math : :
\ mathcal { P } = exp ( H ) / N
where
. . mat... | # normalize weights
w = _np . asarray ( weights ) / _np . sum ( weights )
# mask zero weights
w = _np . ma . MaskedArray ( w , copy = False , mask = ( w == 0 ) )
# avoid NaN due to log ( 0 ) by log ( 1 ) = 0
entr = - _np . sum ( w * _np . log ( w . filled ( 1.0 ) ) )
return _np . exp ( entr ) / len ( w ) |
def bind ( self ) :
"""Attempts to bind to the LDAP server using the credentials of the
service account .
: return : Bound LDAP connection object if successful or ` ` None ` ` if
unsuccessful .""" | conn = self . initialize
try :
conn . simple_bind_s ( current_app . config [ 'LDAP_USERNAME' ] , current_app . config [ 'LDAP_PASSWORD' ] )
return conn
except ldap . LDAPError as e :
raise LDAPException ( self . error ( e . args ) ) |
def split ( self , url ) :
"""Split the url into I { protocol } and I { location }
@ param url : A URL .
@ param url : str
@ return : ( I { url } , I { location } )
@ rtype : tuple""" | parts = url . split ( '://' , 1 )
if len ( parts ) == 2 :
return parts
else :
return ( None , url ) |
def make_routing_table ( obj , keys , prefix = 'on_' ) :
""": return :
a dictionary roughly equivalent to ` ` { ' key1 ' : obj . on _ key1 , ' key2 ' : obj . on _ key2 , . . . } ` ` ,
but ` ` obj ` ` does not have to define all methods . It may define the needed ones only .
: param obj : the object
: param ... | def maptuple ( k ) :
if isinstance ( k , tuple ) :
if len ( k ) == 2 :
return k
elif len ( k ) == 1 :
return k [ 0 ] , lambda * aa , ** kw : getattr ( obj , prefix + k [ 0 ] ) ( * aa , ** kw )
else :
raise ValueError ( )
else :
return k , lambd... |
def _read_motifs_from_filehandle ( handle , fmt ) :
"""Read motifs from a file - like object .
Parameters
handle : file - like object
Motifs .
fmt : string , optional
Motif format , can be ' pwm ' , ' transfac ' , ' xxmotif ' , ' jaspar ' or ' align ' .
Returns
motifs : list
List of Motif instances ... | if fmt . lower ( ) == "pwm" :
motifs = _read_motifs_pwm ( handle )
if fmt . lower ( ) == "transfac" :
motifs = _read_motifs_transfac ( handle )
if fmt . lower ( ) == "xxmotif" :
motifs = _read_motifs_xxmotif ( handle )
if fmt . lower ( ) == "align" :
motifs = _read_motifs_align ( handle )
if fmt . lower... |
def resetState ( self ) :
"""Reset to the original domain state , including all possible values""" | self . extend ( self . _hidden )
del self . _hidden [ : ]
del self . _states [ : ] |
def check_dimensionless_vertical_coordinate ( self , ds ) :
'''Check the validity of dimensionless coordinates under CF
CF § 4.3.2 The units attribute is not required for dimensionless
coordinates .
The standard _ name attribute associates a coordinate with its definition
from Appendix D , Dimensionless Ver... | ret_val = [ ]
z_variables = cfutil . get_z_variables ( ds )
deprecated_units = [ 'level' , 'layer' , 'sigma_level' ]
for name in z_variables :
variable = ds . variables [ name ]
standard_name = getattr ( variable , 'standard_name' , None )
units = getattr ( variable , 'units' , None )
formula_terms = ge... |
def detectSyntax ( self , xmlFileName = None , mimeType = None , language = None , sourceFilePath = None , firstLine = None ) :
"""Get syntax by next parameters ( fill as many , as known ) :
* name of XML file with syntax definition
* MIME type of source file
* Programming language name
* Source file path
... | oldLanguage = self . language ( )
self . clearSyntax ( )
syntax = self . _globalSyntaxManager . getSyntax ( xmlFileName = xmlFileName , mimeType = mimeType , languageName = language , sourceFilePath = sourceFilePath , firstLine = firstLine )
if syntax is not None :
self . _highlighter = SyntaxHighlighter ( syntax ,... |
async def get_my_did_with_meta ( wallet_handle : int , did : str ) -> str :
"""Get DID metadata and verkey stored in the wallet .
: param wallet _ handle : wallet handler ( created by open _ wallet ) .
: param did : The DID to retrieve metadata .
: return : DID with verkey and metadata .""" | logger = logging . getLogger ( __name__ )
logger . debug ( "get_my_did_with_meta: >>> wallet_handle: %r, did: %r" , wallet_handle , did )
if not hasattr ( get_my_did_with_meta , "cb" ) :
logger . debug ( "get_my_did_with_meta: Creating callback" )
get_my_did_with_meta . cb = create_cb ( CFUNCTYPE ( None , c_int... |
def _get_body_instance ( self ) :
"""Return the body instance .""" | simple_body = { MultipartType . OFPMP_FLOW : FlowStatsRequest , MultipartType . OFPMP_AGGREGATE : AggregateStatsRequest , MultipartType . OFPMP_PORT_STATS : PortStatsRequest , MultipartType . OFPMP_QUEUE : QueueStatsRequest , MultipartType . OFPMP_GROUP : GroupStatsRequest , MultipartType . OFPMP_METER : MeterMultipart... |
def store_shot ( self ) :
"""Store current cregs to shots _ result""" | def to_str ( cregs ) :
return '' . join ( str ( b ) for b in cregs )
key = to_str ( self . cregs )
self . shots_result [ key ] = self . shots_result . get ( key , 0 ) + 1 |
def _publish ( self , msg ) :
"""Publish , handling retries , a message in the queue .
: param msg : Object which represents the message to be sent in
the queue . Note that this object should be serializable in the
configured format ( by default JSON ) .""" | connection = self . _connection . clone ( )
publish = connection . ensure ( self . producer , self . producer . publish , errback = self . __error_callback , max_retries = MQ_PRODUCER_MAX_RETRIES )
publish ( json . dumps ( msg ) , exchange = self . _exchange , routing_key = self . _routing_key , declare = [ self . _que... |
def unsubscribe_from_data ( self , subscriber : Callable [ [ bytes ] , bool ] , ) -> None :
"""Not thread - safe .""" | self . _data_subscribers . remove ( subscriber ) |
def open ( self , fn ) :
"Open image in ` fn ` , subclass and overwrite for custom behavior ." | return open_image ( fn , convert_mode = self . convert_mode , after_open = self . after_open ) |
def to_dict ( self ) :
"""Convert attributes and properties to a dict ,
so that it can be serialized .""" | return { k : getattr ( self , k ) for k in filter ( lambda k : not k . startswith ( '_' ) and k != 'to_dict' , dir ( self ) ) } |
def likes ( self ) :
"""A : class : ` Feed < pypump . models . feed . Feed > `
of the people who ' ve liked the object .
Example :
> > > for person in mynote . likes :
. . . print ( person . webfinger )
pypumptest1 @ pumpity . net
pypumptest2 @ pumpyourself . com""" | endpoint = self . links [ "likes" ]
if self . _likes is None :
self . _likes = Feed ( endpoint , pypump = self . _pump )
return self . _likes |
def circleconvert ( amount , currentformat , newformat ) :
"""Convert a circle measurement .
: type amount : number
: param amount : The number to convert .
: type currentformat : string
: param currentformat : The format of the provided value .
: type newformat : string
: param newformat : The intended... | # If the same format was provided
if currentformat . lower ( ) == newformat . lower ( ) : # Return the provided value
return amount
# If the lowercase version of the current format is ' radius '
if currentformat . lower ( ) == 'radius' : # If the lowercase version of the new format is ' diameter '
if newformat ... |
def readUTF ( self ) :
"""Reads a UTF - 8 string from the data stream .
The string is assumed to be prefixed with an unsigned
short indicating the length in bytes .
@ rtype : C { str }
@ return : A UTF - 8 string produced by the byte
representation of characters .""" | length = self . stream . read_ushort ( )
return self . stream . read_utf8_string ( length ) |
def find_one_project ( zero_ok = False , more_ok = True , ** kwargs ) :
""": param zero _ ok :
If False ( default ) , : class : ` ~ dxpy . exceptions . DXSearchError ` is
raised if the search has 0 results ; if True , returns None if the
search has 0 results
: type zero _ ok : bool
: param more _ ok :
I... | return _find_one ( find_projects , zero_ok = zero_ok , more_ok = more_ok , ** kwargs ) |
def cassist ( self , dc , dt , dt2 , nodiag = False , memlimit = - 1 ) :
"""Calculates probability of gene i regulating gene j with continuous data assisted method ,
with the recommended combination of multiple tests .
Probabilities are converted from likelihood ratios separately for each A . This gives better ... | return _cassist_any ( self , dc , dt , dt2 , "pij_cassist" , nodiag = nodiag , memlimit = memlimit ) |
def _get_seaborn_chart ( self , xfield , yfield , chart_type , label , _opts = None , _style = None , ** kwargs ) :
"""Get an Seaborn chart object""" | plt . figure ( )
try :
opts , style = self . _get_opts_seaborn ( _opts , _style )
except Exception as e :
self . err ( e , "Can not get chart options" )
return
# params
# opts [ " xfield " ] = xfield
# opts [ " yfield " ] = yfield
# opts [ " dataobj " ] = self . df
opts [ "chart_type" ] = chart_type
self . ... |
def _get_variant_silent ( parser , variant ) :
"""Gets a variant from the parser while disabling logging .""" | prev_log = config . LOG_NOT_FOUND
config . LOG_NOT_FOUND = False
results = parser . get_variant_genotypes ( variant )
config . LOG_NOT_FOUND = prev_log
return results |
def c_var_decls ( self ) :
"""Get the needed variable definitions .""" | if self . opts . no_structs :
mod_decl = 'HMODULE {} = NULL;\n' . format ( self . name )
return [ mod_decl ] + [ '{} *{} = NULL;\n' . format ( self . _c_type_name ( name ) , name ) for name , dummy_args in self . funcs ]
if self . opts . windll :
return ''
return [ '{} _{} = {{ 0 }};\n' . format ( self . _c... |
def calc_resize_factor ( prediction , image_size ) :
"""Calculates how much prediction . shape and image _ size differ .""" | resize_factor_x = prediction . shape [ 1 ] / float ( image_size [ 1 ] )
resize_factor_y = prediction . shape [ 0 ] / float ( image_size [ 0 ] )
if abs ( resize_factor_x - resize_factor_y ) > 1.0 / image_size [ 1 ] :
raise RuntimeError ( """The aspect ratio of the fixations does not
mat... |
def _incr_counter ( self , * args ) :
"""Increments a Hadoop counter .
Note that this seems to be a bit slow , ~ 1 ms
Don ' t overuse this function by updating very frequently .""" | if len ( args ) == 2 : # backwards compatibility with existing hadoop jobs
group_name , count = args
print ( 'reporter:counter:%s,%s' % ( group_name , count ) , file = sys . stderr )
else :
group , name , count = args
print ( 'reporter:counter:%s,%s,%s' % ( group , name , count ) , file = sys . stderr ) |
def _revoked_to_list ( revs ) :
'''Turn the mess of OrderedDicts and Lists into a list of dicts for
use in the CRL module .''' | list_ = [ ]
for rev in revs :
for rev_name , props in six . iteritems ( rev ) : # pylint : disable = unused - variable
dict_ = { }
for prop in props :
for propname , val in six . iteritems ( prop ) :
if isinstance ( val , datetime . datetime ) :
val = ... |
def list_lights ( self , selector = 'all' ) :
"""Given a selector ( defaults to all ) , return a list of lights .
Without a selector provided , return list of all lights .""" | return self . client . perform_request ( method = 'get' , endpoint = 'lights/{}' , endpoint_args = [ selector ] , parse_data = False ) |
def left_motion ( self , event ) :
"""Callback for the B1 - Motion event , or the dragging of an item .
Moves the item to the desired location , but limits its movement to a
place on the actual Canvas . The item cannot be moved outside of the Canvas .
: param event : Tkinter event""" | self . set_current ( )
results = self . canvas . find_withtag ( tk . CURRENT )
if len ( results ) is 0 :
return
item = results [ 0 ]
rectangle = self . items [ item ]
self . config ( cursor = "exchange" )
self . canvas . itemconfigure ( item , fill = "blue" )
xc , yc = self . canvas . canvasx ( event . x ) , self .... |
def batch_predict_async ( training_dir , prediction_input_file , output_dir , mode , batch_size = 16 , shard_files = True , output_format = 'csv' , cloud = False ) :
"""Local and cloud batch prediction .
Args :
training _ dir : The output folder of training .
prediction _ input _ file : csv file pattern to a ... | import google . datalab . utils as du
with warnings . catch_warnings ( ) :
warnings . simplefilter ( "ignore" )
if cloud :
runner_results = cloud_batch_predict ( training_dir , prediction_input_file , output_dir , mode , batch_size , shard_files , output_format )
job = du . DataflowJob ( runner_... |
def sensor_offsets_encode ( self , mag_ofs_x , mag_ofs_y , mag_ofs_z , mag_declination , raw_press , raw_temp , gyro_cal_x , gyro_cal_y , gyro_cal_z , accel_cal_x , accel_cal_y , accel_cal_z ) :
'''Offsets and calibrations values for hardware sensors . This makes it
easier to debug the calibration process .
mag... | return MAVLink_sensor_offsets_message ( mag_ofs_x , mag_ofs_y , mag_ofs_z , mag_declination , raw_press , raw_temp , gyro_cal_x , gyro_cal_y , gyro_cal_z , accel_cal_x , accel_cal_y , accel_cal_z ) |
def connect ( self , tab_key ) :
"""Open a websocket connection to remote browser , determined by
self . host and self . port . Each tab has it ' s own websocket
endpoint .""" | assert self . tablist is not None
tab_idx = self . _get_tab_idx_for_key ( tab_key )
if not self . tablist :
self . tablist = self . fetch_tablist ( )
for fails in range ( 9999 ) :
try : # If we ' re one past the end of the tablist , we need to create a new tab
if tab_idx is None :
self . log... |
def show_feature ( self , user , feature ) :
"""Return True or False for the given feature .""" | user_filter = { self . model . USER_FEATURE_FIELD : user , }
return self . get_feature ( feature ) . filter ( models . Q ( ** user_filter ) | models . Q ( everyone = True ) ) . exists ( ) |
def trim_empty_columns ( self ) :
"""Removes all trailing empty columns .""" | if self . nrows != 0 and self . ncols != 0 :
last_col = - 1
for row in self . rows :
for i in range ( last_col + 1 , len ( row ) ) :
if not self . is_cell_empty ( row [ i ] ) :
last_col = i
ncols = last_col + 1
self . rows = [ row [ : ncols ] for row in self . rows ]
... |
def next ( self ) :
"""Goes one item ahead and returns it .""" | rv = self . current
self . pos = ( self . pos + 1 ) % len ( self . items )
return rv |
def datetime ( self ) -> hints . Datetime :
"""Creates a : class : ` ~ datetime . datetime ` instance ( assumes UTC ) from the Unix time value of the timestamp
with millisecond precision .
: return : Timestamp in datetime form .
: rtype : : class : ` ~ datetime . datetime `""" | mills = self . int
return datetime . datetime . utcfromtimestamp ( mills // 1000.0 ) . replace ( microsecond = mills % 1000 * 1000 ) |
def aes_encrypt ( self , plain , sec_key , enable_b64 = True ) :
"""使用 ` ` aes ` ` 加密数据 , 并由 ` ` base64编码 ` ` 加密后的数据
- ` ` sec _ key ` ` 加密 ` ` msg ` ` , 最后选择 ` ` 是否由base64编码数据 ` `
- msg长度为16位数 , 不足则补 ' ascii \\ 0'
. . warning : :
msg长度为16位数 , 不足则补 ' ascii \\ 0'
: param plain :
: type plain : str
: pa... | plain = helper . to_str ( plain )
sec_key = helper . to_str ( sec_key )
# 如果msg长度不为16倍数 , 需要补位 ' \ 0'
plain += '\0' * ( self . bs - len ( plain ) % self . bs )
# 使用生成的 key , iv 加密
plain = helper . to_bytes ( plain )
cipher = self . aes_obj ( sec_key ) . encrypt ( plain )
# 是否返回 base64 编码数据
cip = base64 . b64encode ( ci... |
def parse_parameters ( self , parameters , array_class = None ) :
"""Parses a parameters arg to figure out what fields need to be loaded .
Parameters
parameters : ( list of ) strings
The parameter ( s ) to retrieve . A parameter can be the name of any
field in ` ` samples _ group ` ` , a virtual field or me... | # get the type of array class to use
if array_class is None :
array_class = FieldArray
# get the names of fields needed for the given parameters
possible_fields = self [ self . samples_group ] . keys ( )
return array_class . parse_parameters ( parameters , possible_fields ) |
def relativize_path ( path , base , os_sep = os . sep ) :
'''Make absolute path relative to an absolute base .
: param path : absolute path
: type path : str
: param base : absolute base path
: type base : str
: param os _ sep : path component separator , defaults to current OS separator
: type os _ sep... | if not check_base ( path , base , os_sep ) :
raise OutsideDirectoryBase ( "%r is not under %r" % ( path , base ) )
prefix_len = len ( base )
if not base . endswith ( os_sep ) :
prefix_len += len ( os_sep )
return path [ prefix_len : ] |
def mon_status_check ( conn , logger , hostname , args ) :
"""A direct check for JSON output on the monitor status .
For newer versions of Ceph ( dumpling and newer ) a new mon _ status command
was added ( ` ceph daemon mon mon _ status ` ) and should be revisited if the
output changes as this check depends o... | asok_path = paths . mon . asok ( args . cluster , hostname )
out , err , code = remoto . process . check ( conn , [ 'ceph' , '--cluster={cluster}' . format ( cluster = args . cluster ) , '--admin-daemon' , asok_path , 'mon_status' , ] , )
for line in err :
logger . error ( line )
try :
return json . loads ( b''... |
def nTE ( cells1 = [ ] , cells2 = [ ] , spks1 = None , spks2 = None , timeRange = None , binSize = 20 , numShuffle = 30 ) :
'''Calculate normalized transfer entropy
- cells1 ( [ ' all ' , | ' allCells ' , ' allNetStims ' , | , 120 , | , ' E1 ' | , ( ' L2 ' , 56 ) | , ( ' L5 ' , [ 4,5,6 ] ) ] ) : Subset of cells f... | from neuron import h
import netpyne
from . . import sim
import os
root = os . path . dirname ( netpyne . __file__ )
if 'nte' not in dir ( h ) :
try :
print ( ' Warning: support/nte.mod not compiled; attempting to compile from %s via "nrnivmodl support"' % ( root ) )
os . system ( 'cd ' + root + '; n... |
def on_page_markdown ( self , markdown , page , config , site_navigation = None , ** kwargs ) :
"Provide a hook for defining functions from an external module" | # the site _ navigation argument has been made optional
# ( deleted in post 1.0 mkdocs , but maintained here
# for backward compatibility )
if not self . variables :
return markdown
else : # Create templae and get the variables
md_template = Template ( markdown )
# Execute the jinja2 template and return
... |
def pip_installer_url ( version = None ) :
"""Get argument to give to ` ` pip ` ` to install HPCBench .""" | version = version or hpcbench . __version__
version = str ( version )
if '.dev' in version :
git_rev = 'master'
if 'TRAVIS_BRANCH' in os . environ :
git_rev = version . split ( '+' , 1 ) [ - 1 ]
if '.' in git_rev : # get rid of date suffix
git_rev = git_rev . split ( '.' , 1 ) [ 0 ]
... |
def __get_header_with_auth ( self ) :
"""This private method returns the HTTP heder filled with the Authorization information with the user token .
The token validity is monitored whenever this function is called , so according to the swagger page of TheTVDB
( https : / / api . thetvdb . com / swagger ) the tok... | auth_header = self . __get_header ( )
auth_header [ 'Authorization' ] = 'Bearer %s' % self . __token
token_renew_time = self . __auth_time + timedelta ( seconds = self . TOKEN_DURATION_SECONDS )
if datetime . now ( ) > token_renew_time :
token_max_time = self . __auth_time + timedelta ( seconds = self . TOKEN_MAX_D... |
def content_preview ( self , request ) :
"""Admin view to preview Entry . content in HTML ,
useful when using markups to write entries .""" | data = request . POST . get ( 'data' , '' )
entry = self . model ( content = data )
return TemplateResponse ( request , 'admin/zinnia/entry/preview.html' , { 'preview' : entry . html_content } ) |
def count_of_wells ( self ) :
"""Number of wells in x / y - direction of template .
Returns
tuple
( xs , ys ) number of wells in x and y direction .""" | xs = set ( [ w . attrib [ 'WellX' ] for w in self . wells ] )
ys = set ( [ w . attrib [ 'WellY' ] for w in self . wells ] )
return ( len ( xs ) , len ( ys ) ) |
def map ( self , function , options = None ) :
"""Add a map phase to the map / reduce operation .
: param function : Either a named Javascript function ( ie :
' Riak . mapValues ' ) , or an anonymous javascript function ( ie :
' function ( . . . ) . . . ' or an array [ ' erlang _ module ' ,
' function ' ] .... | if options is None :
options = dict ( )
if isinstance ( function , list ) :
language = 'erlang'
else :
language = 'javascript'
mr = RiakMapReducePhase ( 'map' , function , options . get ( 'language' , language ) , options . get ( 'keep' , False ) , options . get ( 'arg' , None ) )
self . _phases . append ( ... |
def pull_request ( self , number ) :
"""Get the pull request indicated by ` ` number ` ` .
: param int number : ( required ) , number of the pull request .
: returns : : class : ` PullRequest < github3 . pulls . PullRequest > `""" | json = None
if int ( number ) > 0 :
url = self . _build_url ( 'pulls' , str ( number ) , base_url = self . _api )
json = self . _json ( self . _get ( url ) , 200 )
return PullRequest ( json , self ) if json else None |
def preloop ( self ) :
"""Initialization before prompting user for commands .
Despite the claims in the Cmd documentaion , Cmd . preloop ( ) is not a stub .""" | cmd . Cmd . preloop ( self )
# # sets up command completion
try :
if readline :
readline . read_history_file ( sys . argv [ 0 ] + ".history" )
except Exception , err :
if not isinstance ( err , IOError ) :
self . stdout . write ( "history error: %s\n" % err ) |
def all ( cls ) :
'''Return all tags that are currently applied to any dataset .
: returns : a list of all tags that are currently applied to any dataset
: rtype : list of ckan . model . tag . Tag objects''' | # if vocab _ id _ or _ name :
# vocab = vocabulary . Vocabulary . get ( vocab _ id _ or _ name )
# if vocab is None :
# # The user specified an invalid vocab .
# raise ckan . logic . NotFound ( " could not find vocabulary ' % s ' "
# % vocab _ id _ or _ name )
# query = meta . Session . query ( Tag ) . filter ( Tag . v... |
def locale_title ( locale_name ) :
"""Giving a locale name return its title , taken from the settings . EXTRA _ COUNTRY _ LOCALES
If the locale is not in the settings . EXTRA _ COUNTRY _ LOCALES , return it unchanged""" | l = dict ( settings . EXTRA_COUNTRY_LOCALES )
if locale_name not in l :
return locale_name
return l . get ( locale_name ) |
def create_union_mnist_dataset ( ) :
"""Create a UnionDataset composed of two versions of the MNIST datasets
where each item in the dataset contains 2 distinct images superimposed""" | transform = transforms . Compose ( [ transforms . ToTensor ( ) , transforms . Normalize ( ( 0.1307 , ) , ( 0.3081 , ) ) ] )
mnist1 = datasets . MNIST ( 'data' , train = False , download = True , transform = transform )
data1 = zip ( mnist1 . test_data , mnist1 . test_labels )
# Randomize second dataset
mnist2 = dataset... |
def iter_prepostorder ( self , is_leaf_fn = None ) :
"""Iterate over all nodes in a tree yielding every node in both
pre and post order . Each iteration returns a postorder flag
( True if node is being visited in postorder ) and a node
instance .""" | to_visit = [ self ]
if is_leaf_fn is not None :
_leaf = is_leaf_fn
else :
_leaf = self . __class__ . is_leaf
while to_visit :
node = to_visit . pop ( - 1 )
try :
node = node [ 1 ]
except TypeError : # PREORDER ACTIONS
yield ( False , node )
if not _leaf ( node ) : # ADD CHILD... |
def __Autostart_TCP_Server_checkBox_set_ui ( self ) :
"""Sets the * * Autostart _ TCP _ Server _ checkBox * * Widget .""" | # Adding settings key if it doesn ' t exists .
self . __settings . get_key ( self . __settings_section , "autostart_tcp_server" ) . isNull ( ) and self . __settings . set_key ( self . __settings_section , "autostart_tcp_server" , Qt . Checked )
autostart_tcp_server = foundations . common . get_first_item ( self . __set... |
def generate_ssh ( self , server , args , configure ) :
"""异步同时执行SSH生成 generate ssh
: param server :
: param args :
: param configure :
: return :""" | self . reset_server_env ( server , configure )
# chmod project root owner
sudo ( 'chown {user}:{user} -R {path}' . format ( user = configure [ server ] [ 'user' ] , path = bigdata_conf . project_root ) )
# generate ssh key
if not exists ( '~/.ssh/id_rsa.pub' ) :
run ( 'ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa' ) |
def tile ( self , map_id , x , y , z , retina = False , file_format = "png" , style_id = None , timestamp = None ) :
"""Returns an image tile , vector tile , or UTFGrid
in the specified file format .
Parameters
map _ id : str
The tile ' s unique identifier in the format username . id .
x : int
The tile ... | # Check x , y , and z .
if x is None or y is None or z is None :
raise ValidationError ( "x, y, and z must be not be None" )
# Validate x , y , z , retina , and file _ format .
x = self . _validate_x ( x , z )
y = self . _validate_y ( y , z )
z = self . _validate_z ( z )
retina = self . _validate_retina ( retina )
... |
def update_from_json ( self , json_device ) :
"""Set all attributes based on API response .""" | self . identifier = json_device [ 'Id' ]
self . license_plate = json_device [ 'EquipmentHeader' ] [ 'SerialNumber' ]
self . make = json_device [ 'EquipmentHeader' ] [ 'Make' ]
self . model = json_device [ 'EquipmentHeader' ] [ 'Model' ]
self . equipment_id = json_device [ 'EquipmentHeader' ] [ 'EquipmentID' ]
self . ac... |
def genome_name_from_fasta_path ( fasta_path ) :
"""Extract genome name from fasta filename
Get the filename without directory and remove the file extension .
Example :
With fasta file path ` ` / path / to / genome _ 1 . fasta ` ` : :
fasta _ path = ' / path / to / genome _ 1 . fasta '
genome _ name = gen... | filename = os . path . basename ( fasta_path )
return re . sub ( r'(\.fa$)|(\.fas$)|(\.fasta$)|(\.fna$)|(\.\w{1,}$)' , '' , filename ) |
def delete_ace ( self , domain = None , user = None , sid = None ) :
"""delete ACE for the share
delete ACE for the share . User could either supply the domain and
username or the sid of the user .
: param domain : domain of the user
: param user : username
: param sid : sid of the user or sid list of the... | if sid is None :
if domain is None :
domain = self . cifs_server . domain
sid = UnityAclUser . get_sid ( self . _cli , user = user , domain = domain )
if isinstance ( sid , six . string_types ) :
sid = [ sid ]
ace_list = [ self . _make_remove_ace_entry ( s ) for s in sid ]
resp = self . action ( "se... |
def run_with_retcodes ( argv ) :
"""Run luigi with command line parsing , but raise ` ` SystemExit ` ` with the configured exit code .
Note : Usually you use the luigi binary directly and don ' t call this function yourself .
: param argv : Should ( conceptually ) be ` ` sys . argv [ 1 : ] ` `""" | logger = logging . getLogger ( 'luigi-interface' )
with luigi . cmdline_parser . CmdlineParser . global_instance ( argv ) :
retcodes = retcode ( )
worker = None
try :
worker = luigi . interface . _run ( argv ) . worker
except luigi . interface . PidLockAlreadyTakenExit :
sys . exit ( retcodes . already_runn... |
def resolve ( self , name , recursive = False , ** kwargs ) :
"""Accepts an identifier and resolves it to the referenced item .
There are a number of mutable name protocols that can link among
themselves and into IPNS . For example IPNS references can ( currently )
point at an IPFS object , and DNS links can ... | kwargs . setdefault ( "opts" , { "recursive" : recursive } )
args = ( name , )
return self . _client . request ( '/resolve' , args , decoder = 'json' , ** kwargs ) |
def modify_environment ( self , environment_id , ** kwargs ) :
'''modify _ environment ( self , environment _ id , * * kwargs )
Modifies an existing environment
: Parameters :
* * environment _ id * ( ` string ` ) - - The environment identifier
Keywords args :
The variables to change in the environment
... | request_data = { 'id' : environment_id }
request_data . update ( ** kwargs )
return self . _call_rest_api ( 'post' , '/environments' , data = request_data , error = 'Failed to modify environment' ) |
def load_netcdf4 ( fnames = None , strict_meta = False , file_format = None , epoch_name = 'Epoch' , units_label = 'units' , name_label = 'long_name' , notes_label = 'notes' , desc_label = 'desc' , plot_label = 'label' , axis_label = 'axis' , scale_label = 'scale' , min_label = 'value_min' , max_label = 'value_max' , f... | import netCDF4
import string
import pysat
if fnames is None :
raise ValueError ( "Must supply a filename/list of filenames" )
if isinstance ( fnames , basestring ) :
fnames = [ fnames ]
if file_format is None :
file_format = 'NETCDF4'
else :
file_format = file_format . upper ( )
saved_mdata = None
runni... |
def get_connections ( self , id , connection_name , ** args ) :
"""Fetches the connections for given object .""" | return self . request ( "{0}/{1}/{2}" . format ( self . version , id , connection_name ) , args ) |
def convert_item_to_flask_url ( self , ctx , item , filepath = None ) :
"""Given a relative reference like ` foo / bar . css ` , returns
the Flask static url . By doing so it takes into account
blueprints , i . e . in the aformentioned example ,
` ` foo ` ` may reference a blueprint .
If an absolute path is... | if ctx . environment . _app . config . get ( "FLASK_ASSETS_USE_S3" ) :
try :
from flask_s3 import url_for
except ImportError as e :
print ( "You must have Flask S3 to use FLASK_ASSETS_USE_S3 option" )
raise e
elif ctx . environment . _app . config . get ( "FLASK_ASSETS_USE_CDN" ) :
t... |
def email_finder ( self , domain = None , company = None , first_name = None , last_name = None , full_name = None , raw = False ) :
"""Find the email address of a person given its name and company ' s domain .
: param domain : The domain of the company where the person works . Must
be defined if company is not... | params = self . base_params
if not domain and not company :
raise MissingCompanyError ( 'You must supply at least a domain name or a company name' )
if domain :
params [ 'domain' ] = domain
elif company :
params [ 'company' ] = company
if not ( first_name and last_name ) and not full_name :
raise Missin... |
def _process_project_transfer ( self , action , transfer_id , status_comment ) :
"""Send PUT request to one of the project transfer action endpoints
: param action : str name of the action ( reject / accept / cancel )
: param transfer _ id : str uuid of the project _ transfer
: param status _ comment : str co... | data = { }
if status_comment :
data [ "status_comment" ] = status_comment
path = "/project_transfers/{}/{}" . format ( transfer_id , action )
return self . _put ( path , data , content_type = ContentType . form ) |
def html_init ( name ) :
"""Return HTML report file first lines .
: param name : name of file
: type name : str
: return : html _ init as str""" | result = ""
result += "<html>\n"
result += "<head>\n"
result += "<title>" + str ( name ) + "</title>\n"
result += "</head>\n"
result += "<body>\n"
result += '<h1 style="border-bottom:1px solid ' 'black;text-align:center;">PyCM Report</h1>'
return result |
def fire ( self , args , kwargs ) :
"""Fire this signal with the specified arguments and keyword arguments .
Typically this is used by using : meth : ` _ _ call _ _ ( ) ` on this object which
is more natural as it does all the argument packing / unpacking
transparently .""" | for info in self . _listeners [ : ] :
if info . pass_signal :
info . listener ( * args , signal = self , ** kwargs )
else :
info . listener ( * args , ** kwargs ) |
def random_sample ( obj , n_samples , seed = None ) :
"""Create a random array by sampling a ROOT function or histogram .
Parameters
obj : TH [ 1 | 2 | 3 ] or TF [ 1 | 2 | 3]
The ROOT function or histogram to sample .
n _ samples : positive int
The number of random samples to generate .
seed : None , po... | import ROOT
if n_samples <= 0 :
raise ValueError ( "n_samples must be greater than 0" )
if seed is not None :
if seed < 0 :
raise ValueError ( "seed must be positive or 0" )
ROOT . gRandom . SetSeed ( seed )
# functions
if isinstance ( obj , ROOT . TF1 ) :
if isinstance ( obj , ROOT . TF3 ) :
... |
def draw_lines ( ) :
"""Draws a line between a set of random values""" | r = numpy . random . randn ( 200 )
fig = pyplot . figure ( )
ax = fig . add_subplot ( 111 )
ax . plot ( r )
ax . grid ( True )
pyplot . savefig ( lines_filename ) |
def create_custom_field ( self , field_name , data_type , options = [ ] , visible_in_preference_center = True ) :
"""Creates a new custom field for this list .""" | body = { "FieldName" : field_name , "DataType" : data_type , "Options" : options , "VisibleInPreferenceCenter" : visible_in_preference_center }
response = self . _post ( self . uri_for ( "customfields" ) , json . dumps ( body ) )
return json_to_py ( response ) |
def update_serial ( self , new_serial ) :
"""Updates the serial number of a device .
The " serial number " used with adb ' s ` - s ` arg is not necessarily the
actual serial number . For remote devices , it could be a combination of
host names and port numbers .
This is used for when such identifier of remo... | new_serial = str ( new_serial )
if self . has_active_service :
raise DeviceError ( self , 'Cannot change device serial number when there is service running.' )
if self . _debug_tag == self . serial :
self . _debug_tag = new_serial
self . _serial = new_serial
self . adb . serial = new_serial
self . fastboot . se... |
def _build_tree ( self ) :
"""Build a full or a partial tree , depending on the groups / sub - groups specified .""" | groups = self . _groups or self . get_children_paths ( self . root_path )
for group in groups :
node = Node ( name = group , parent = self . root )
self . root . children . append ( node )
self . _init_sub_groups ( node ) |
def create_transcript_file ( video_id , language_code , file_format , resource_fs , static_dir ) :
"""Writes transcript file to file system .
Arguments :
video _ id ( str ) : Video id of the video transcript file is attached .
language _ code ( str ) : Language code of the transcript .
file _ format ( str )... | transcript_filename = '{video_id}-{language_code}.srt' . format ( video_id = video_id , language_code = language_code )
transcript_data = get_video_transcript_data ( video_id , language_code )
if transcript_data :
transcript_content = Transcript . convert ( transcript_data [ 'content' ] , input_format = file_format... |
def cast_callback ( value ) :
"""Override ` cast _ callback ` method .""" | # Postgresql / MySQL drivers change the format on ' TIMESTAMP ' columns ;
if 'T' in value :
value = value . replace ( 'T' , ' ' )
return datetime . strptime ( value . split ( '.' ) [ 0 ] , '%Y-%m-%d %H:%M:%S' ) |
def csv_to_PyDbLite ( src , dest , fieldnames = None , fieldtypes = None , dialect = 'excel' ) :
"""Convert a CSV file to a PyDbLite base
src is the file object from which csv values are read
dest is the name of the PyDbLite base
If fieldnames is not set , the CSV file * must * have row names
in the first l... | import csv
import PyDbLite
if not fieldnames :
_in = csv . DictReader ( open ( src ) , fieldnames = fieldnames )
_in . next ( )
fieldnames = _in . fieldnames
out = PyDbLite . Base ( dest )
kw = { "mode" : "override" }
out . create ( * _in . fieldnames , ** kw )
default_fieldtypes = { "__id__" : int , "__ver... |
async def _run_state ( self , responder , state , trigger , request ) -> BaseState :
"""Execute the state , or if execution fails handle it .""" | user_trigger = trigger
# noinspection PyBroadException
try :
if trigger :
await state . handle ( )
else :
await state . confused ( )
for i in range ( 0 , settings . MAX_INTERNAL_JUMPS + 1 ) :
if i == settings . MAX_INTERNAL_JUMPS :
raise MaxInternalJump ( )
trigge... |
def __exists ( self , p ) :
"""Check if file of given path exists .
Parameters
p : str or tuple
Path or tuple identifier .
Returns
exists : bool
` ` True ` ` , if file exists . Otherwise ` ` False ` ` .""" | try :
p = self . __pathToTuple ( p )
except TypeError :
pass
return ( ( not p [ 0 ] and not p [ 1 ] ) or ( p [ 0 ] in self . searches and not p [ 1 ] ) or ( p [ 0 ] in self . searches and p [ 1 ] in self . searches [ p [ 0 ] ] ) ) |
def __build_export ( self , stats ) :
"""Build the export lists .""" | export_names = [ ]
export_values = [ ]
if isinstance ( stats , dict ) : # Stats is a dict
# Is there a key ?
if 'key' in iterkeys ( stats ) and stats [ 'key' ] in iterkeys ( stats ) :
pre_key = '{}.' . format ( stats [ stats [ 'key' ] ] )
else :
pre_key = ''
# Walk through the dict
for k... |
def norm_to_uniform ( im , scale = None ) :
r"""Take an image with normally distributed greyscale values and converts it to
a uniform ( i . e . flat ) distribution . It ' s also possible to specify the
lower and upper limits of the uniform distribution .
Parameters
im : ND - image
The image containing the... | if scale is None :
scale = [ im . min ( ) , im . max ( ) ]
im = ( im - sp . mean ( im ) ) / sp . std ( im )
im = 1 / 2 * sp . special . erfc ( - im / sp . sqrt ( 2 ) )
im = ( im - im . min ( ) ) / ( im . max ( ) - im . min ( ) )
im = im * ( scale [ 1 ] - scale [ 0 ] ) + scale [ 0 ]
return im |
def _standalone ( argv ) :
"""Parse the given input directory and emit generated code .""" | varprefix = "GEOCODE"
per_locale = True
separator = None
chunks = - 1
try :
opts , args = getopt . getopt ( argv , "hv:fs:c:" , ( "help" , "var=" , "flat" , "sep=" , "chunks=" ) )
except getopt . GetoptError :
prnt ( __doc__ , file = sys . stderr )
sys . exit ( 1 )
for opt , arg in opts :
if opt in ( "-... |
def create_copy ( self ) :
"""Initialises a temporary directory structure and copy of MAGICC
configuration files and binary .""" | if self . executable is None or not isfile ( self . executable ) :
raise FileNotFoundError ( "Could not find MAGICC{} executable: {}" . format ( self . version , self . executable ) )
if self . is_temp :
assert ( self . root_dir is None ) , "A temp copy for this instance has already been created"
self . roo... |
def items ( self ) -> Iterable [ Tuple [ str , Any ] ] :
"""An iterable of ( name , value ) pairs .
. . versionadded : : 3.1""" | return [ ( opt . name , opt . value ( ) ) for name , opt in self . _options . items ( ) ] |
def _get_asset_size ( self , asset_type ) :
"""Helper function to dynamically create * _ size properties .""" | if asset_type == 'page' :
assets = self . entries
else :
assets = getattr ( self , '{0}_files' . format ( asset_type ) , None )
return self . get_total_size ( assets ) |
def serialize ( self ) :
"""Serializes the node data as a JSON map string .""" | return json . dumps ( { "port" : self . port , "ip" : self . ip , "host" : self . host , "peer" : self . peer . serialize ( ) if self . peer else None , "metadata" : json . dumps ( self . metadata or { } , sort_keys = True ) , } , sort_keys = True ) |
def retry_count ( self ) :
"""Amount of retried test cases in this list .
: return : integer""" | retries = len ( [ i for i , result in enumerate ( self . data ) if result . retries_left > 0 ] )
return retries |
def waitForNextState ( self ) :
'''After each command has been sent we wait for the observation to change as expected and a frame .''' | # wait for the observation position to have changed
print ( 'Waiting for observation...' , end = ' ' )
while True :
world_state = self . agent_host . peekWorldState ( )
if not world_state . is_mission_running :
print ( 'mission ended.' )
break
if not all ( e . text == '{}' for e in world_sta... |
def intersection ( self , other ) :
"intersection with another patch" | res = { }
if set ( self . sets . keys ( ) ) != set ( other . sets . keys ( ) ) :
raise KeyError ( 'Incompatible patches in intersection' )
for name , s1 in self . sets . items ( ) :
s2 = other . sets [ name ]
res [ name ] = s1 . intersection ( s2 )
return Patch ( res ) |
def linreg ( x , y ) :
"""does a linear regression""" | if len ( x ) != len ( y ) :
print ( 'x and y must be same length' )
return
xx , yy , xsum , ysum , xy , n , sum = 0 , 0 , 0 , 0 , 0 , len ( x ) , 0
linpars = { }
for i in range ( n ) :
xx += x [ i ] * x [ i ]
yy += y [ i ] * y [ i ]
xy += x [ i ] * y [ i ]
xsum += x [ i ]
ysum += y [ i ]
... |
def get ( self ) :
"""Gets the next item from the queue .
Returns a Future that resolves to the next item once it is available .""" | io_loop = IOLoop . current ( )
new_get = Future ( )
with self . _lock :
get , self . _get = self . _get , new_get
answer = Future ( )
def _on_node ( future ) :
if future . exception ( ) : # pragma : no cover ( never happens )
return answer . set_exc_info ( future . exc_info ( ) )
node = future . res... |
def assertFileSizeLess ( self , filename , size , msg = None ) :
'''Fail if ` ` filename ` ` ' s size is not less than ` ` size ` ` as
determined by the ' < ' operator .
Parameters
filename : str , bytes , file - like
size : int , float
msg : str
If not provided , the : mod : ` marbles . mixins ` or
:... | fsize = self . _get_file_size ( filename )
self . assertLess ( fsize , size , msg = msg ) |
def from_directory ( filepath , from_methods , * , name = None , parent = None , verbose = True ) :
"""Create a WrightTools Collection from a directory of source files .
Parameters
filepath : path - like
Path to the directory on the file system
from _ methods : dict < str , callable >
Dictionary which map... | filepath = pathlib . Path ( filepath ) . resolve ( )
if name is None :
name = filepath . name
if verbose :
print ( "Creating Collection:" , name )
root = Collection ( name = name , parent = parent )
q = queue . Queue ( )
for i in filepath . iterdir ( ) :
q . put ( ( filepath , i . name , root ) )
while not ... |
def handle_exec_method ( self , msg ) :
"""Handle data returned by silent executions of kernel methods
This is based on the _ handle _ exec _ callback of RichJupyterWidget .
Therefore this is licensed BSD .""" | user_exp = msg [ 'content' ] . get ( 'user_expressions' )
if not user_exp :
return
for expression in user_exp :
if expression in self . _kernel_methods : # Process kernel reply
method = self . _kernel_methods [ expression ]
reply = user_exp [ expression ]
data = reply . get ( 'data' )
... |
def axisar ( axis , angle ) :
"""Construct a rotation matrix that rotates vectors by a specified
angle about a specified axis .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / axisar _ c . html
: param axis : Rotation axis .
: type axis : 3 Element vector ( list , tuple , num... | axis = stypes . toDoubleVector ( axis )
angle = ctypes . c_double ( angle )
r = stypes . emptyDoubleMatrix ( )
libspice . axisar_c ( axis , angle , r )
return stypes . cMatrixToNumpy ( r ) |
def _init_conn ( self ) :
"""This method will be called after ` connect ` is called .
After this method finishes , the writer will be drained .
Subclasses should make use of this if they need to send
data to Telegram to indicate which connection mode will
be used .""" | if self . _codec . tag :
self . _writer . write ( self . _codec . tag ) |
def get_filters ( self , request , ** resources ) :
"""Make filters from GET variables .
: return dict : filters""" | filters = dict ( )
if not self . _meta . fields :
return filters
for field in request . GET . iterkeys ( ) :
tokens = field . split ( LOOKUP_SEP )
field_name = tokens [ 0 ]
if field_name not in self . _meta . fields :
continue
exclude = False
if tokens [ - 1 ] == 'not' :
exclude ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.