signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_object ( self , point , buffer_size = 0 , multiple = False ) :
"""lookup object based on point as [ longitude , latitude ]""" | # first search bounding boxes
# idx . intersection method modifies input if it is a list
try :
tmp = tuple ( point )
except TypeError :
return None
# point must be in the form ( minx , miny , maxx , maxy ) or ( x , y )
if len ( tmp ) not in [ 2 , 4 ] :
return None
# buffer point if size is specified
geom = ... |
def com_google_fonts_check_linegaps ( ttFont ) :
"""Checking Vertical Metric Linegaps .""" | if ttFont [ "hhea" ] . lineGap != 0 :
yield WARN , Message ( "hhea" , "hhea lineGap is not equal to 0." )
elif ttFont [ "OS/2" ] . sTypoLineGap != 0 :
yield WARN , Message ( "OS/2" , "OS/2 sTypoLineGap is not equal to 0." )
else :
yield PASS , "OS/2 sTypoLineGap and hhea lineGap are both 0." |
def port ( self , name ) :
"""Locate a port by name .
@ param name : A port name .
@ type name : str
@ return : The port object .
@ rtype : L { Port }""" | for p in self . ports :
if p . name == name :
return p |
def widthratio ( value , max_value , max_width ) :
"""Does the same like Django ' s ` widthratio ` template tag ( scales max _ width to factor value / max _ value )""" | ratio = float ( value ) / float ( max_value )
return int ( round ( ratio * max_width ) ) |
def get ( self , key ) :
"""Retrieve object indexed by < key >""" | try :
try :
obj = self . bucket . get ( key )
except couchbase . exception . MemcachedError , inst :
if str ( inst ) == "Memcached error #1: Not found" : # for some reason the py cb client raises an error when
# a key isnt found , instead we just want a none value .
obj = No... |
def FromTrimmedData ( byts ) :
"""Deserialize a block from raw bytes .
Args :
byts :
Returns :
Block :""" | block = Block ( )
block . __is_trimmed = True
ms = StreamManager . GetStream ( byts )
reader = BinaryReader ( ms )
block . DeserializeUnsigned ( reader )
reader . ReadByte ( )
witness = Witness ( )
witness . Deserialize ( reader )
block . Script = witness
bc = GetBlockchain ( )
tx_list = [ ]
for tx_hash in reader . Rea... |
def cache_path ( archive , root_dir , build_id ) :
"""Returns a ~ / . shiv cache directory for unzipping site - packages during bootstrap .
: param ZipFile archive : The zipfile object we are bootstrapping from .
: param str buidl _ id : The build id generated at zip creation .""" | root = root_dir or Path ( "~/.shiv" ) . expanduser ( )
name = Path ( archive . filename ) . resolve ( ) . stem
return root / f"{name}_{build_id}" |
def _read_para_encrypted ( self , code , cbit , clen , * , desc , length , version ) :
"""Read HIP ENCRYPTED parameter .
Structure of HIP ENCRYPTED parameter [ RFC 7401 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| Type | Length |
| Reserved |
| IV /
/ Encrypted data / ... | _resv = self . _read_fileng ( 4 )
_data = self . _read_fileng ( clen - 4 )
encrypted = dict ( type = desc , critical = cbit , length = clen , raw = _data , )
_plen = length - clen
if _plen :
self . _read_fileng ( _plen )
return encrypted |
def _type_container ( self , value , _type ) :
'apply type to all values in the list' | if value is None : # normalize null containers to empty list
return [ ]
elif not isinstance ( value , list ) :
raise ValueError ( "expected list type, got: %s" % type ( value ) )
else :
return sorted ( self . _type_single ( item , _type ) for item in value ) |
def extract_version ( txt ) :
"""This function tries to extract the version from the help text of any
program .""" | words = txt . replace ( ',' , ' ' ) . split ( )
version = None
for x in reversed ( words ) :
if len ( x ) > 2 :
if x [ 0 ] . lower ( ) == 'v' :
x = x [ 1 : ]
if '.' in x and x [ 0 ] . isdigit ( ) :
version = x
break
return version |
def change_interface_id ( self , interface_id ) :
"""Change the interface ID for this interface . This can be used on any
interface type . If the interface is an Inline interface , you must
provide the ` ` interface _ id ` ` in format ' 1-2 ' to define both
interfaces in the pair . The change is committed aft... | splitted = str ( interface_id ) . split ( '-' )
if1 = splitted [ 0 ]
for interface in self . all_interfaces : # Set top level interface , this only uses a single value which
# will be the leftmost interface
if isinstance ( interface , VlanInterface ) :
interface . interface_id = '{}.{}' . format ( if1 , int... |
def render_to_response ( self , context = None , request = None , def_name = None , content_type = None , status = None , charset = None ) :
'''Renders the template and returns an HttpRequest object containing its content .
This method returns a django . http . Http404 exception if the template is not found .
I... | try :
if content_type is None :
content_type = mimetypes . types_map . get ( os . path . splitext ( self . mako_template . filename ) [ 1 ] . lower ( ) , settings . DEFAULT_CONTENT_TYPE )
if charset is None :
charset = settings . DEFAULT_CHARSET
if status is None :
status = 200
c... |
def readDoc ( cur , URL , encoding , options ) :
"""parse an XML in - memory document and build a tree .""" | ret = libxml2mod . xmlReadDoc ( cur , URL , encoding , options )
if ret is None :
raise treeError ( 'xmlReadDoc() failed' )
return xmlDoc ( _obj = ret ) |
def valueFromString ( self , value , context = None ) :
"""Converts the inputted string text to a value that matches the type from
this column type .
: param value | < str >
extra | < variant >""" | if value in ( 'today' , 'now' ) :
return datetime . datetime . utcnow ( )
elif dateutil_parser :
return dateutil_parser . parse ( value )
else :
time_struct = time . strptime ( value , self . defaultFormat ( ) )
return datetime . datetime ( time_struct . tm_year , time_struct . tm_month , time_struct . ... |
def get_vbm ( self ) :
"""Returns data about the VBM .
Returns :
dict as { " band _ index " , " kpoint _ index " , " kpoint " , " energy " }
- " band _ index " : A dict with spin keys pointing to a list of the
indices of the band containing the VBM ( please note that you
can have several bands sharing the... | if self . is_metal ( ) :
return { "band_index" : [ ] , "kpoint_index" : [ ] , "kpoint" : [ ] , "energy" : None , "projections" : { } }
max_tmp = - float ( "inf" )
index = None
kpointvbm = None
for spin , v in self . bands . items ( ) :
for i , j in zip ( * np . where ( v < self . efermi ) ) :
if v [ i ,... |
def intersection ( self , * iterables ) :
"""Return a new set with elements common to the set and all * iterables * .""" | comb = self . _set . intersection ( * iterables )
return self . _fromset ( comb , key = self . _key ) |
def make_sentence ( list_words ) :
"""Return a sentence from list of words .
: param list list _ words : list of words
: returns : sentence
: rtype : str""" | lw_len = len ( list_words )
if lw_len > 6 :
list_words . insert ( lw_len // 2 + random . choice ( range ( - 2 , 2 ) ) , ',' )
sentence = ' ' . join ( list_words ) . replace ( ' ,' , ',' )
return sentence . capitalize ( ) + '.' |
def export ( self , Height = None , options = None , outputFile = None , Resolution = None , Units = None , Width = None , Zoom = None , view = "current" , verbose = False ) :
"""Exports the current view to a graphics file and returns the path to the
saved file . PNG and JPEG formats have options for scaling , wh... | PARAMS = set_param ( [ "Height" , "options" , "outputFile" , "Resolution" , "Units" , "Width" , "Zoom" , "view" ] , [ Height , options , outputFile , Resolution , Units , Width , Zoom , view ] )
response = api ( url = self . __url + "/export" , PARAMS = PARAMS , method = "POST" , verbose = verbose )
return response |
def context ( self , name ) :
"""Get a context .
Args :
name ( str ) : Name to store the context under .
Returns :
` ResolvedContext ` object .""" | data = self . _context ( name )
context = data . get ( "context" )
if context :
return context
assert self . load_path
context_path = os . path . join ( self . load_path , "contexts" , "%s.rxt" % name )
context = ResolvedContext . load ( context_path )
data [ "context" ] = context
data [ "loaded" ] = True
return co... |
def parse_addresses ( self ) :
"""Parse all mail addresses out of the URL target . Also parses
optional CGI headers like " ? to = foo @ example . org " .
Stores parsed addresses in the self . addresses set .""" | # cut off leading mailto : and unquote
url = urllib . unquote ( self . base_url [ 7 : ] )
# search for cc , bcc , to and store in headers
mode = 0
# 0 = default , 1 = quote , 2 = esc
quote = None
i = 0
for i , c in enumerate ( url ) :
if mode == 0 :
if c == '?' :
break
elif c in '<"' :
... |
def is_accessable_by_others ( filename ) :
"""Check if file is group or world accessable .""" | mode = os . stat ( filename ) [ stat . ST_MODE ]
return mode & ( stat . S_IRWXG | stat . S_IRWXO ) |
def attach ( zpool , device , new_device , force = False ) :
'''Attach specified device to zpool
zpool : string
Name of storage pool
device : string
Existing device name too
new _ device : string
New device name ( to be attached to ` ` device ` ` )
force : boolean
Forces use of device
CLI Example ... | # # Configure pool
# NOTE : initialize the defaults
flags = [ ]
target = [ ]
# NOTE : set extra config
if force :
flags . append ( '-f' )
# NOTE : append the pool name and specifications
target . append ( zpool )
target . append ( device )
target . append ( new_device )
# # Update storage pool
res = __salt__ [ 'cmd... |
def init ( config_object : Optional [ Any ] = None ) -> None :
"""Initialize NoneBot instance .
This function must be called at the very beginning of code ,
otherwise the get _ bot ( ) function will return None and nothing
is gonna work properly .
: param config _ object : configuration object""" | global _bot
_bot = NoneBot ( config_object )
if _bot . config . DEBUG :
logger . setLevel ( logging . DEBUG )
else :
logger . setLevel ( logging . INFO )
_bot . server_app . before_serving ( _start_scheduler ) |
def _process_phenstatement ( self , limit ) :
"""The phenstatements are the genotype - to - phenotype associations ,
in the context of an environment .
These are also curated to a publication . So we make oban associations ,
adding the pubs as a source . We additionally add the internal key as
a comment for... | if self . test_mode :
graph = self . testgraph
else :
graph = self . graph
model = Model ( graph )
raw = '/' . join ( ( self . rawdir , 'phenstatement' ) )
LOG . info ( "processing phenstatement" )
line_counter = 0
with open ( raw , 'r' ) as f :
filereader = csv . reader ( f , delimiter = '\t' , quotechar =... |
def calculate_similarity ( container1 = None , container2 = None , comparison = None , metric = None ) :
'''calculate _ similarity will calculate similarity of two containers
by files content , default will calculate
2.0 * len ( intersect ) / total package1 + total package2
Parameters
container1 : container... | if metric is None :
metric = information_coefficient
if comparison == None :
comparison = compare_containers ( container1 = container1 , container2 = container2 )
return metric ( total1 = comparison [ 'total1' ] , total2 = comparison [ 'total2' ] , intersect = comparison [ "intersect" ] ) |
def dump ( self , name ) :
"""get a redis RDB - like serialization of the object .
: param name : str the name of the redis key
: return : Future ( )""" | with self . pipe as pipe :
return pipe . dump ( self . redis_key ( name ) ) |
def simulate_indices ( self , ts_length , init = None , num_reps = None , random_state = None ) :
"""Simulate time series of state transitions , where state indices
are returned .
Parameters
ts _ length : scalar ( int )
Length of each simulation .
init : int or array _ like ( int , ndim = 1 ) , optional
... | random_state = check_random_state ( random_state )
dim = 1
# Dimension of the returned array : 1 or 2
msg_out_of_range = 'index {init} is out of the state space'
try :
k = len ( init )
# init is an array
dim = 2
init_states = np . asarray ( init , dtype = int )
# Check init _ states are in the state... |
def links ( self ) :
"""Return a list of links for endpoints related to the resource .
: rtype : list""" | links = [ ]
for foreign_key in self . __table__ . foreign_keys :
column = foreign_key . column . name
column_value = getattr ( self , column , None )
if column_value :
table = foreign_key . column . table . name
with app . app_context ( ) :
endpoint = current_app . class_referenc... |
def get ( self , sid ) :
"""Constructs a AssetContext
: param sid : The sid
: returns : twilio . rest . serverless . v1 . service . asset . AssetContext
: rtype : twilio . rest . serverless . v1 . service . asset . AssetContext""" | return AssetContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = sid , ) |
def get_storage_account_keys ( access_token , subscription_id , rgname , account_name ) :
'''Get the access keys for the specified storage account .
Args :
access _ token ( str ) : A valid Azure authentication token .
subscription _ id ( str ) : Azure subscription id .
rgname ( str ) : Azure resource group ... | endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourcegroups/' , rgname , '/providers/Microsoft.Storage/storageAccounts/' , account_name , '/listKeys' , '?api-version=' , STORAGE_API ] )
return do_post ( endpoint , '' , access_token ) |
def create_cert_signed_certificate ( self , sign_cert_str , sign_key_str , request_cert_str , hash_alg = "sha256" , valid_from = 0 , valid_to = 315360000 , sn = 1 , passphrase = None ) :
"""Will sign a certificate request with a give certificate .
: param sign _ cert _ str : This certificate will be used to sign ... | ca_cert = crypto . load_certificate ( crypto . FILETYPE_PEM , sign_cert_str )
ca_key = None
if passphrase is not None :
ca_key = crypto . load_privatekey ( crypto . FILETYPE_PEM , sign_key_str , passphrase )
else :
ca_key = crypto . load_privatekey ( crypto . FILETYPE_PEM , sign_key_str )
req_cert = crypto . lo... |
def post_create_app ( cls , app , ** settings ) :
"""Automatically register and init the Flask Marshmallow extension .
Args :
app ( flask . Flask ) : The application instance in which to initialize
Flask Marshmallow upon .
Kwargs :
settings ( dict ) : The settings passed to this method from the
parent a... | super ( MarshmallowAwareApp , cls ) . post_create_app ( app , ** settings )
marsh . init_app ( app )
return app |
def delete_from_all_link_group ( self , group ) :
"""Delete a device to an All - Link Group .""" | msg = StandardSend ( self . _address , COMMAND_DELETE_FROM_ALL_LINK_GROUP_0X02_NONE , cmd2 = group )
self . _send_msg ( msg ) |
def image_alias_delete ( image , alias , remote_addr = None , cert = None , key = None , verify_cert = True ) :
'''Delete an alias ( this is currently not restricted to the image )
image :
An image alias , a fingerprint or a image object
alias :
The alias to delete
remote _ addr :
An URL to a remote Ser... | image = _verify_image ( image , remote_addr , cert , key , verify_cert )
try :
image . delete_alias ( alias )
except pylxd . exceptions . LXDAPIException :
return False
return True |
def read_settings ( self ) :
"""Set the dock state from QSettings .
Do this on init and after changing options in the options dialog .""" | extent = setting ( 'user_extent' , None , str )
if extent :
extent = QgsGeometry . fromWkt ( extent )
if not extent . isGeosValid ( ) :
extent = None
crs = setting ( 'user_extent_crs' , None , str )
if crs :
crs = QgsCoordinateReferenceSystem ( crs )
if not crs . isValid ( ) :
crs = None... |
def _evalDateStd ( self , datetimeString , sourceTime ) :
"""Evaluate text passed by L { _ partialParseDateStd ( ) }""" | s = datetimeString . strip ( )
sourceTime = self . _evalDT ( datetimeString , sourceTime )
# Given string is in the format 07/21/2006
return self . parseDate ( s , sourceTime ) |
def floor ( value , mod = 1 ) :
"""x = = floor ( x , a ) + mod ( x , a ) FOR ALL a , x
RETURN None WHEN GIVEN INVALID ARGUMENTS""" | if value == None :
return None
elif mod <= 0 :
return None
elif mod == 1 :
return int ( math_floor ( value ) )
elif is_integer ( mod ) :
return int ( math_floor ( value / mod ) ) * mod
else :
return math_floor ( value / mod ) * mod |
def getCandScoresMapFromSamplesFile ( self , profile , sampleFileName ) :
"""Returns a dictonary that associates the integer representation of each candidate with the
Bayesian utilities we approximate from the samples we generated into a file .
: ivar Profile profile : A Profile object that represents an electi... | wmg = profile . getWmg ( True )
# Initialize our list of expected utilities .
utilities = dict ( )
for cand in wmg . keys ( ) :
utilities [ cand ] = 0.0
# Open the file and skip the lines of meta data in the file and skip samples for burn - in .
sampleFile = open ( sampleFileName )
for i in range ( 0 , SAMPLESFILEM... |
def defaultCrawlId ( ) :
"""Provide a reasonable default crawl name using the user name and date""" | timestamp = datetime . now ( ) . isoformat ( ) . replace ( ':' , '_' )
user = getuser ( )
return '_' . join ( ( 'crawl' , user , timestamp ) ) |
def _is_region_extremely_sparse ( self , start , end , base_state = None ) :
"""Check whether the given memory region is extremely sparse , i . e . , all bytes are the same value .
: param int start : The beginning of the region .
: param int end : The end of the region .
: param base _ state : The base state... | all_bytes = None
if base_state is not None :
all_bytes = base_state . memory . load ( start , end - start + 1 )
try :
all_bytes = base_state . solver . eval ( all_bytes , cast_to = bytes )
except SimError :
all_bytes = None
size = end - start + 1
if all_bytes is None : # load from the binary... |
def serialize ( self ) :
"""This function serialize into a simple dict object .
It is used when transferring data to other daemons over the network ( http )
Here we directly return all attributes
: return : json representation of a Timeperiod
: rtype : dict""" | res = super ( Timeperiod , self ) . serialize ( )
res [ 'dateranges' ] = [ ]
for elem in self . dateranges :
res [ 'dateranges' ] . append ( { '__sys_python_module__' : "%s.%s" % ( elem . __module__ , elem . __class__ . __name__ ) , 'content' : elem . serialize ( ) } )
return res |
def is_running ( self , port ) :
"""Return True if a host on a specific port is running .""" | try :
con = self . client ( 'localhost:%s' % port )
con . admin . command ( 'ping' )
return True
except ( AutoReconnect , ConnectionFailure , OperationFailure ) : # Catch OperationFailure to work around SERVER - 31916.
return False |
def addService ( self , moduleName , serviceName , service ) :
"""Add a service instance to the application service pool .
: param moduleName : < str > module name in which the service is located
: param serviceName : < str > service name
: param service : < object > service instance
: return : < void >""" | serviceIdentifier = "{}.{}" . format ( moduleName , serviceName )
if serviceIdentifier not in self . _services :
self . _services [ serviceIdentifier ] = service
else :
message = "Application - addService() - " "A service with the identifier {} already exists." . format ( serviceIdentifier )
raise Exception... |
def bruteVersionStr ( self , valu ) :
'''Brute force the version out of a string .
Args :
valu ( str ) : String to attempt to get version information for .
Notes :
This first attempts to parse strings using the it : semver normalization
before attempting to extract version parts out of the string .
Retu... | try :
valu , info = self . core . model . type ( 'it:semver' ) . norm ( valu )
subs = info . get ( 'subs' )
return valu , subs
except s_exc . BadTypeValu : # Try doing version part extraction by noming through the string
subs = s_version . parseVersionParts ( valu )
if subs is None :
raise s... |
def curargs ( self ) :
"""Returns the dictionary of arguments for plotting / tabulating of the active
unit test and analysis group .""" | # This is where we update the arguments to new dictionary versions when the code
# is updated with new features etc . so that the older , serialized sessions don ' t
# break .
if ( self . active not in self . _version_check or self . group not in self . _version_check [ self . active ] ) :
if ( "version" not in sel... |
def list_pkgs ( versions_as_list = False , ** kwargs ) :
'''List the packages currently installed in a dict : :
{ ' < package _ name > ' : ' < version > ' }
CLI Example :
. . code - block : : bash
salt ' * ' pkg . list _ pkgs''' | versions_as_list = salt . utils . data . is_true ( versions_as_list )
# ' removed ' , ' purge _ desired ' not yet implemented or not applicable
if any ( [ salt . utils . data . is_true ( kwargs . get ( x ) ) for x in ( 'removed' , 'purge_desired' ) ] ) :
return { }
if 'pkg.list_pkgs' in __context__ :
if version... |
def calculate_top_down_likelihood ( tree , character , frequencies , sf , kappa = None , model = F81 ) :
"""Calculates the top - down likelihood for the given tree .
The likelihood for each node is stored in the corresponding feature ,
given by get _ personalised _ feature _ name ( feature , TD _ LH ) .
To ca... | lh_feature = get_personalized_feature_name ( character , TD_LH )
lh_sf_feature = get_personalized_feature_name ( character , TD_LH_SF )
bu_lh_feature = get_personalized_feature_name ( character , BU_LH )
bu_lh_sf_feature = get_personalized_feature_name ( character , BU_LH_SF )
get_pij = get_pij_method ( model , frequen... |
def multiplypub ( pub , priv , outcompressed = True ) :
'''Input pubkey must be hex string and valid pubkey .
Input privkey must be 64 - char hex string .
Pubkey input can be compressed or uncompressed , as long as it ' s a
valid key and a hex string . Use the validatepubkey ( ) function to
validate the pub... | if len ( pub ) == 66 :
pub = uncompress ( pub )
x , y = ecmultiply ( int ( pub [ 2 : 66 ] , 16 ) , int ( pub [ 66 : ] , 16 ) , int ( priv , 16 ) )
x = dechex ( x , 32 )
y = dechex ( y , 32 )
o = '04' + x + y
if outcompressed :
return compress ( o )
else :
return o |
def apply_palette ( img , palette , options ) :
'''Apply the pallete to the given image . The first step is to set all
background pixels to the background color ; then , nearest - neighbor
matching is used to map each foreground color to the closest one in
the palette .''' | if not options . quiet :
print ( ' applying palette...' )
bg_color = palette [ 0 ]
fg_mask = get_fg_mask ( bg_color , img , options )
orig_shape = img . shape
pixels = img . reshape ( ( - 1 , 3 ) )
fg_mask = fg_mask . flatten ( )
num_pixels = pixels . shape [ 0 ]
labels = np . zeros ( num_pixels , dtype = np . uin... |
def search_rna_quantifications ( self , rna_quantification_set_id = "" ) :
"""Returns an iterator over the RnaQuantification objects from the server
: param str rna _ quantification _ set _ id : The ID of the
: class : ` ga4gh . protocol . RnaQuantificationSet ` of interest .""" | request = protocol . SearchRnaQuantificationsRequest ( )
request . rna_quantification_set_id = rna_quantification_set_id
request . page_size = pb . int ( self . _page_size )
return self . _run_search_request ( request , "rnaquantifications" , protocol . SearchRnaQuantificationsResponse ) |
def cli ( ctx , omit_empty_organisms = False ) :
"""Get all users known to this Apollo instance
Output :
list of user info dictionaries""" | return ctx . gi . users . get_users ( omit_empty_organisms = omit_empty_organisms ) |
def authorize_security_group ( self , group_name = None , src_security_group_name = None , src_security_group_owner_id = None , ip_protocol = None , from_port = None , to_port = None , cidr_ip = None , group_id = None , src_security_group_group_id = None ) :
"""Add a new rule to an existing security group .
You n... | if src_security_group_name :
if from_port is None and to_port is None and ip_protocol is None :
return self . authorize_security_group_deprecated ( group_name , src_security_group_name , src_security_group_owner_id )
params = { }
if group_name :
params [ 'GroupName' ] = group_name
if group_id :
para... |
def is_linuxbridge_interface ( port ) :
'''Check if the interface is a linuxbridge bridge
: param port : Name of an interface to check whether it is a Linux bridge
: returns : True if port is a Linux bridge''' | if os . path . exists ( '/sys/class/net/' + port + '/bridge' ) :
log ( 'Interface {} is a Linux bridge' . format ( port ) , level = DEBUG )
return True
else :
log ( 'Interface {} is not a Linux bridge' . format ( port ) , level = DEBUG )
return False |
def connect ( cls , ssid , key = None , ** kwargs ) :
"""Connect to the given ssid using the key ( if given ) .
Returns
result : future
A future that resolves with the result of the connect""" | app = AndroidApplication . instance ( )
f = app . create_future ( )
config = WifiConfiguration ( )
config . SSID = '"{}"' . format ( ssid )
if key is not None :
config . preSharedKey = '"{}"' . format ( key )
# : Set any other parameters
for k , v in kwargs . items ( ) :
setattr ( config , k , v )
def on_permis... |
def associate ( self , model ) :
"""Associate the model instance to the given parent .
: type model : eloquent . Model
: rtype : eloquent . Model""" | self . _parent . set_attribute ( self . _foreign_key , model . get_attribute ( self . _other_key ) )
return self . _parent . set_relation ( self . _relation , model ) |
def get_listeners ( self ) :
"""Returns a : class : ` list ` of ( name , function ) listener pairs that are defined in this cog .""" | return [ ( name , getattr ( self , method_name ) ) for name , method_name in self . __cog_listeners__ ] |
def set_options ( self , multiplex_first = True , ** bogus_options ) :
"Takes implementation specific options . To be overriden in a subclass ." | self . multiplex_first = multiplex_first
self . _warn_bogus_options ( ** bogus_options ) |
def factor_kkt ( U_S , R , d ) :
"""Factor the U22 block that we can only do after we know D .""" | nineq = R . size ( 0 )
U_S [ - nineq : , - nineq : ] = torch . potrf ( R + torch . diag ( 1 / d . cpu ( ) ) . type_as ( d ) ) |
def read_file ( self , url , location = None ) :
"""Read content from the web by overriding
` LiteralIncludeReader . read _ file ` .""" | response = requests_retry_session ( ) . get ( url , timeout = 10.0 )
response . raise_for_status ( )
text = response . text
if 'tab-width' in self . options :
text = text . expandtabs ( self . options [ 'tab-width' ] )
return text . splitlines ( True ) |
def get_objective ( self ) :
"""Gets the related objective .
return : ( osid . learning . Objective ) - the related objective
raise : OperationFailed - unable to complete request
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . learning . Activity . get _ objective
if not bool ( self . _my_map [ 'objectiveId' ] ) :
raise errors . IllegalState ( 'objective empty' )
mgr = self . _get_provider_manager ( 'LEARNING' )
if not mgr . supports_objective_lookup ( ) :
raise errors . OperationFailed ( 'Learn... |
def t0_ref_to_supconj ( t0_ref , period , ecc , per0 ) :
"""TODO : add documentation""" | return ConstraintParameter ( t0_ref . _bundle , "t0_ref_to_supconj({}, {}, {}, {})" . format ( _get_expr ( t0_ref ) , _get_expr ( period ) , _get_expr ( ecc ) , _get_expr ( per0 ) ) ) |
def _do_download_file ( self , dss_file , fh , num_retries , min_delay_seconds ) :
"""Abstracts away complications for downloading a file , handles retries and delays , and computes its hash""" | hasher = hashlib . sha256 ( )
delay = min_delay_seconds
retries_left = num_retries
while True :
try :
response = self . get_file . _request ( dict ( uuid = dss_file . uuid , version = dss_file . version , replica = dss_file . replica ) , stream = True , headers = { 'Range' : "bytes={}-" . format ( fh . tell... |
def normalize ( self ) :
"""Shift actor ' s center of mass at origin and scale its average size to unit .""" | cm = self . centerOfMass ( )
coords = self . coordinates ( )
if not len ( coords ) :
return
pts = coords - cm
xyz2 = np . sum ( pts * pts , axis = 0 )
scale = 1 / np . sqrt ( np . sum ( xyz2 ) / len ( pts ) )
t = vtk . vtkTransform ( )
t . Scale ( scale , scale , scale )
t . Translate ( - cm )
tf = vtk . vtkTransfo... |
def pearsonr ( self , target , correlation_length , mask = NotSpecified ) :
"""Construct a new Factor that computes rolling pearson correlation
coefficients between ` target ` and the columns of ` self ` .
This method can only be called on factors which are deemed safe for use
as inputs to other factors . Thi... | from . statistical import RollingPearson
return RollingPearson ( base_factor = self , target = target , correlation_length = correlation_length , mask = mask , ) |
def periodic_callback ( self ) :
"""Periodically help maintain adapter internal state""" | while True :
try :
action = self . _deferred . get ( False )
action ( )
except queue . Empty :
break
except Exception :
self . _logger . exception ( 'Exception in periodic callback' ) |
def _fused_batch_norm_op ( self , input_batch , mean , variance , use_batch_stats ) :
"""Creates a fused batch normalization op .""" | # Store the original shape of the mean and variance .
mean_shape = mean . get_shape ( )
variance_shape = variance . get_shape ( )
# The fused batch norm expects the mean , variance , gamma and beta
# tensors to have dimension 1 , so we flatten them to remove the
# extra dimensions .
gamma_flatten = tf . reshape ( self ... |
def set_main_wire ( self , wire = None ) :
"""Sets the specified wire as the link ' s main wire
This is done automatically during the first wire ( ) call
Keyword Arguments :
- wire ( Wire ) : if None , use the first wire instance found
Returns :
- Wire : the new main wire instance""" | if not wire :
for k in dir ( self ) :
if isinstance ( getattr ( self , k ) , Wire ) :
wire = getattr ( self , k )
break
elif not isinstance ( wire , Wire ) :
raise ValueError ( "wire needs to be a Wire instance" )
if not isinstance ( wire , Wire ) :
wire = None
self . main = ... |
def mainset ( self ) :
"""Returns information regarding the set""" | if self . mainsetcache :
return self . mainsetcache
set_uri = self . get_set_uri ( )
for row in self . graph . query ( "SELECT ?seturi ?setid ?setlabel ?setopen ?setempty WHERE { ?seturi rdf:type skos:Collection . OPTIONAL { ?seturi skos:notation ?setid } OPTIONAL { ?seturi skos:prefLabel ?setlabel } OPTIONAL { ?se... |
def maybe_open ( infile , mode = 'r' ) :
"""Take a file name or a handle , and return a handle .
Simplifies creating functions that automagically accept either a file name
or an already opened file handle .""" | # ENH : Exception safety ?
if isinstance ( infile , basestring ) :
handle = open ( infile , mode )
do_close = True
else :
handle = infile
do_close = False
yield handle
if do_close :
handle . close ( ) |
def last_heart_rate ( self ) :
"""Return avg heart rate for last session .""" | try :
rates = self . intervals [ 1 ] [ 'timeseries' ] [ 'heartRate' ]
except KeyError :
return None
tmp = 0
num_rates = len ( rates )
if num_rates == 0 :
return None
for rate in rates :
tmp += rate [ 1 ]
rateavg = tmp / num_rates
return rateavg |
def mount ( self , volume ) :
"""Mounts the given volume on the provided mountpoint . The default implementation simply calls mount .
: param Volume volume : The volume to be mounted
: param mountpoint : The file system path to mount the filesystem on .
: raises UnsupportedFilesystemError : when the volume sy... | volume . _make_mountpoint ( )
try :
self . _call_mount ( volume , volume . mountpoint , self . _mount_type or self . type , self . _mount_opts )
except Exception : # undo the creation of the mountpoint
volume . _clear_mountpoint ( )
raise |
def set_log_level ( level ) :
"""Sets the log level .
Lower log levels log more .
if level is 8 , nothing is logged . If level is 0 , everything is logged .""" | from . . _connect import main as _glconnect
unity = _glconnect . get_unity ( )
return unity . set_log_level ( level ) |
def get_insert_idx ( pos_dict , name ) :
"Return the position to insert a given function doc in a notebook ." | keys , i = list ( pos_dict . keys ( ) ) , 0
while i < len ( keys ) and str . lower ( keys [ i ] ) < str . lower ( name ) :
i += 1
if i == len ( keys ) :
return - 1
else :
return pos_dict [ keys [ i ] ] |
def remove_reference ( type_ ) :
"""removes reference from the type definition
If type is not reference type , it will be returned as is .""" | nake_type = remove_alias ( type_ )
if not is_reference ( nake_type ) :
return type_
return nake_type . base |
def split_stacks ( self , stacks : List [ List [ BaseLayer ] ] ) -> List [ List [ BaseLayer ] ] :
"""First step of the stacks cleanup process . We consider that if inside
a stack there ' s a text layer showing up then it ' s the beginning of a
new stack and split upon that .""" | ns : List [ List [ BaseLayer ] ] = [ ]
for stack in stacks :
cur : List [ BaseLayer ] = [ ]
for layer in stack :
if cur and isinstance ( layer , lyr . RawText ) :
ns . append ( cur )
cur = [ ]
cur . append ( layer )
if cur :
ns . append ( cur )
return ns |
def run ( self ) :
"""This defines the sequence of actions that are taken when the barrier concurrency state is executed
: return :""" | logger . debug ( "Starting execution of {0}{1}" . format ( self , " (backwards)" if self . backward_execution else "" ) )
self . setup_run ( )
# data to be accessed by the decider state
child_errors = { }
final_outcomes_dict = { }
decider_state = self . states [ UNIQUE_DECIDER_STATE_ID ]
try :
concurrency_history_i... |
def _tuple_requested ( self , namespace_tuple ) :
"""Helper for _ namespace _ requested . Supports limited wildcards""" | if not isinstance ( namespace_tuple [ 0 ] , unicode ) :
encoded_db = unicode ( namespace_tuple [ 0 ] )
else :
encoded_db = namespace_tuple [ 0 ]
if not isinstance ( namespace_tuple [ 1 ] , unicode ) :
encoded_coll = unicode ( namespace_tuple [ 1 ] )
else :
encoded_coll = namespace_tuple [ 1 ]
if namespa... |
def update_hyperparameters ( self , new_params , hyper_deriv_handling = 'default' , exit_on_bounds = True , inf_on_error = True ) :
r"""Update the kernel ' s hyperparameters to the new parameters .
This will call : py : meth : ` compute _ K _ L _ alpha _ ll ` to update the state
accordingly .
Note that if thi... | use_hyper_deriv = self . use_hyper_deriv
if hyper_deriv_handling == 'value' :
self . use_hyper_deriv = False
elif hyper_deriv_handling == 'deriv' :
self . use_hyper_deriv = True
self . k . set_hyperparams ( new_params [ : len ( self . k . free_params ) ] )
self . noise_k . set_hyperparams ( new_params [ len ( s... |
def save_model ( self ) :
'''Saves all of the de - trending information to disk in an ` npz ` file
and saves the DVS as a ` pdf ` .''' | # Save the data
log . info ( "Saving data to '%s.npz'..." % self . name )
d = dict ( self . __dict__ )
d . pop ( '_weights' , None )
d . pop ( '_A' , None )
d . pop ( '_B' , None )
d . pop ( '_f' , None )
d . pop ( '_mK' , None )
d . pop ( 'K' , None )
d . pop ( 'dvs' , None )
d . pop ( 'clobber' , None )
d . pop ( 'cl... |
def _random_mutation_operator ( self , individual , allow_shrink = True ) :
"""Perform a replacement , insertion , or shrink mutation on an individual .
Parameters
individual : DEAP individual
A list of pipeline operators and model parameters that can be
compiled by DEAP into a callable function
allow _ s... | if self . tree_structure :
mutation_techniques = [ partial ( gp . mutInsert , pset = self . _pset ) , partial ( mutNodeReplacement , pset = self . _pset ) ]
# We can ' t shrink pipelines with only one primitive , so we only add it if we find more primitives .
number_of_primitives = sum ( [ isinstance ( node... |
def _load_translations ( instance , lang = None ) :
"""Loads all translations as dynamic attributes :
< attr > _ < lang _ code >
< attr > _ < lang _ code > _ is _ fuzzy""" | # Gets field translations
translations = _get_fieldtranslations ( instance = instance , lang = lang )
for translation_i in translations : # Sets translated field lang for this language
field_lang = trans_attr ( translation_i . field , translation_i . lang )
setattr ( instance , field_lang , translation_i . tran... |
def readConfigFromJSON ( self , fileName ) :
"""Read configuration from JSON .
: param fileName : path to the configuration file .
: type fileName : str .""" | self . __logger . debug ( "readConfigFromJSON: reading from " + fileName )
with open ( fileName ) as data_file :
data = load ( data_file )
self . readConfig ( data ) |
def import_from_cwd ( module , imp = None , package = None ) :
"""Import module , but make sure it finds modules
located in the current directory .
Modules located in the current directory has
precedence over modules located in ` sys . path ` .""" | if imp is None :
imp = importlib . import_module
with cwd_in_path ( ) :
return imp ( module , package = package ) |
def nside_to_pixel_resolution ( nside ) :
"""Find the resolution of HEALPix pixels given the pixel dimensions of one of
the 12 ' top - level ' HEALPix tiles .
Parameters
nside : int
The number of pixels on the side of one of the 12 ' top - level ' HEALPix tiles .
Returns
resolution : : class : ` ~ astro... | nside = np . asanyarray ( nside , dtype = np . int64 )
_validate_nside ( nside )
return ( nside_to_pixel_area ( nside ) ** 0.5 ) . to ( u . arcmin ) |
def format_size ( num , format_str = '{num:.1f} {unit}' ) :
'''Format the file size into a human readable text .
http : / / stackoverflow . com / a / 1094933/1524507''' | for unit in ( 'B' , 'KiB' , 'MiB' , 'GiB' ) :
if - 1024 < num < 1024 :
return format_str . format ( num = num , unit = unit )
num /= 1024.0
return format_str . format ( num = num , unit = 'TiB' ) |
def shipping_options ( request , country ) :
"""Get the shipping options for a given country""" | qrs = models . ShippingRate . objects . filter ( countries__in = [ country ] )
serializer = serializers . ShippingRateSerializer ( qrs , many = True )
return Response ( data = serializer . data , status = status . HTTP_200_OK ) |
def _validate ( cls , options , items , warnfn ) :
"Validation of edge cases and incompatible options" | if 'html' in Store . display_formats :
pass
elif 'fig' in items and items [ 'fig' ] not in Store . display_formats :
msg = ( "Requesting output figure format %r " % items [ 'fig' ] + "not in display formats %r" % Store . display_formats )
if warnfn is None :
print ( 'Warning: {msg}' . format ( msg =... |
def from_git_rev_read ( path ) :
"""Retrieve given file path contents of certain Git revision .""" | if ":" not in path :
raise ValueError ( "Path identifier must start with a revision hash." )
cmd = "git" , "show" , "-t" , path
try :
return subprocess . check_output ( cmd ) . rstrip ( ) . decode ( "utf-8" )
except subprocess . CalledProcessError :
raise ValueError |
def __new_job_sync ( self , message , future_results ) :
"""Synchronous part of _ new _ job . Creates needed directories , copy files , and starts the container .""" | course_id = message . course_id
task_id = message . task_id
debug = message . debug
environment_name = message . environment
enable_network = message . enable_network
time_limit = message . time_limit
hard_time_limit = message . hard_time_limit or time_limit * 3
mem_limit = message . mem_limit
course_fs = self . tasks_... |
def show_slice ( data2d , contour2d = None , seeds2d = None ) :
""": param data2d :
: param contour2d :
: param seeds2d :
: return :""" | import copy as cp
# Show results
colormap = cp . copy ( plt . cm . get_cmap ( 'brg' ) )
colormap . _init ( )
colormap . _lut [ : 1 : , 3 ] = 0
plt . imshow ( data2d , cmap = 'gray' , interpolation = 'none' )
if contour2d is not None :
plt . contour ( contour2d , levels = [ 0.5 , 1.5 , 2.5 ] )
if seeds2d is not None... |
def get_port_monitor ( self ) :
"""Gets the port monitor configuration of a logical interconnect .
Returns :
dict : The Logical Interconnect .""" | uri = "{}{}" . format ( self . data [ "uri" ] , self . PORT_MONITOR_PATH )
return self . _helper . do_get ( uri ) |
def from_ase_atoms ( cls , atoms ) :
"""Create an instance of the own class from an ase molecule
Args :
molecule ( : class : ` ase . atoms . Atoms ` ) :
Returns :
Cartesian :""" | return cls ( atoms = atoms . get_chemical_symbols ( ) , coords = atoms . positions ) |
def get_lexer_for_filename ( _fn , code = None , ** options ) :
"""Get a lexer for a filename .
If multiple lexers match the filename pattern , use ` ` analyse _ text ( ) ` ` to
figure out which one is more appropriate .
Raises ClassNotFound if not found .""" | res = find_lexer_class_for_filename ( _fn , code )
if not res :
raise ClassNotFound ( 'no lexer for filename %r found' % _fn )
return res ( ** options ) |
def fitted ( self , fid = 0 ) :
"""Test if enough Levenberg - Marquardt loops have been done .
It returns True if no improvement possible .
: param fid : the id of the sub - fitter ( numerical )""" | self . _checkid ( fid )
return not ( self . _fitids [ fid ] [ "fit" ] > 0 or self . _fitids [ fid ] [ "fit" ] < - 0.001 ) |
def allowed_transitions ( ) :
"""Get target states allowed for the current state .""" | try :
sdp_state = SDPState ( )
return sdp_state . allowed_target_states [ sdp_state . current_state ]
except KeyError :
LOG . error ( "Key Error" )
return dict ( state = "KeyError" , reason = "KeyError" ) |
def _set_final_freeness ( self , flag ) :
"""Sets the freedom of the final chunk . Since no proper chunk follows the final chunk , the heap itself manages
this . Nonetheless , for now it is implemented as if an additional chunk followed the final chunk .""" | if flag :
self . state . memory . store ( self . heap_base + self . heap_size - self . _chunk_size_t_size , ~ CHUNK_P_MASK )
else :
self . state . memory . store ( self . heap_base + self . heap_size - self . _chunk_size_t_size , CHUNK_P_MASK ) |
def predict_log_proba ( self , X ) :
"""Return log - probability estimates for the test vector X .
Parameters
X : array - like , shape = [ n _ samples , n _ features ]
Returns
C : array - like , shape = [ n _ samples , n _ classes ]
Returns the log - probability of the samples for each class in
the mode... | jll = self . _joint_log_likelihood ( X )
# normalize by P ( x ) = P ( f _ 1 , . . . , f _ n )
log_prob_x = logsumexp ( jll , axis = 1 )
# return shape = ( 2 , )
return jll - np . atleast_2d ( log_prob_x ) . T |
def delete_relationship ( self , relationship_id = None ) :
"""Deletes a ` ` Relationship ` ` .
arg : relationship _ id ( osid . id . Id ) : the ` ` Id ` ` of the
` ` Relationship ` ` to remove
raise : NotFound - ` ` relationship _ id ` ` not found
raise : NullArgument - ` ` relationship _ id ` ` is ` ` nul... | if relationship_id is None :
raise NullArgument ( )
if not isinstance ( relationship_id , Id ) :
raise InvalidArgument ( 'argument type is not an osid Id' )
url_path = ( '/handcar/services/relationship/families/' + self . _catalog_idstr + '/relationships/' + str ( relationship_id ) )
result = self . _delete_req... |
def flushed_print ( * args , ** kwargs ) :
"""Use to replace print ( * args , flush = True ) that doesn ' t exist for python < 3.3""" | print ( * args , ** kwargs )
file = kwargs . get ( 'file' , sys . stdout )
file . flush ( ) if file is not None else sys . stdout . flush ( ) |
def simxGetCollisionHandle ( clientID , collisionObjectName , operationMode ) :
'''Please have a look at the function description / documentation in the V - REP user manual''' | handle = ct . c_int ( )
if ( sys . version_info [ 0 ] == 3 ) and ( type ( collisionObjectName ) is str ) :
collisionObjectName = collisionObjectName . encode ( 'utf-8' )
return c_GetCollisionHandle ( clientID , collisionObjectName , ct . byref ( handle ) , operationMode ) , handle . value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.