signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def linear ( self , fnct , x , y , sd = None , wt = 1.0 , fid = 0 ) :
"""Make a linear least squares solution .
Makes a linear least squares solution for the points through the
ordinates at the x values , using the specified fnct . The x can be of
any dimension , depending on the number of arguments needed in... | self . _fit ( fitfunc = "linear" , fnct = fnct , x = x , y = y , sd = sd , wt = wt , fid = fid ) |
def search ( self , name : str = None , acc_type : str = None ) :
"""Search accounts by passing parameters .
name = exact name
name _ part = part of name
parent _ id = id of the parent account
type = account type""" | query = self . query
if name is not None :
query = query . filter ( Account . name == name )
if acc_type is not None : # account type is capitalized
acc_type = acc_type . upper ( )
query = query . filter ( Account . type == acc_type )
return query . all ( ) |
def list_insert ( lst , new_elements , index_or_name = None , after = True ) :
"""Return a copy of the list with the new element ( s ) inserted .
Args :
lst ( list ) : The original list .
new _ elements ( " any " or list of " any " ) : The element ( s ) to insert in the list .
index _ or _ name ( int or str... | if index_or_name is None :
index = None
else :
try :
index = get_list_index ( lst , index_or_name )
except ValueError :
index = None
to_return = lst [ : ]
if index is None : # Append .
to_return += new_elements
elif index == 0 : # Prepend .
to_return = new_elements + to_return
else :... |
def on_backward_begin ( self , last_loss , last_output , ** kwargs ) :
"Record ` last _ loss ` in the proper list ." | last_loss = last_loss . detach ( ) . cpu ( )
if self . gen_mode :
self . smoothenerG . add_value ( last_loss )
self . glosses . append ( self . smoothenerG . smooth )
self . last_gen = last_output . detach ( ) . cpu ( )
else :
self . smoothenerC . add_value ( last_loss )
self . closses . append ( se... |
def file_needs_update ( target_file , source_file ) :
"""Checks if target _ file is not existing or differing from source _ file
: param target _ file : File target for a copy action
: param source _ file : File to be copied
: return : True , if target _ file not existing or differing from source _ file , els... | if not os . path . isfile ( target_file ) or get_md5_file_hash ( target_file ) != get_md5_file_hash ( source_file ) :
return True
return False |
def put ( self , item , * args , ** kwargs ) :
"""Put an item into the cache , for this combination of args and kwargs .
Args :
* args : any arguments .
* * kwargs : any keyword arguments . If ` ` timeout ` ` is specified as one
of the keyword arguments , the item will remain available
for retrieval for `... | if not self . enabled :
return
# Check for a timeout keyword , store and remove it .
timeout = kwargs . pop ( 'timeout' , None )
if timeout is None :
timeout = self . default_timeout
cache_key = self . make_key ( args , kwargs )
# Store the item , along with the time at which it will expire
with self . _cache_l... |
def inasafe_place_value_coefficient ( number , feature , parent ) :
"""Given a number , it will return the coefficient of the place value name .
For instance :
* inasafe _ place _ value _ coefficient ( 10 ) - > 1
* inasafe _ place _ value _ coefficient ( 1700 ) - > 1.7
It needs to be used with inasafe _ num... | _ = feature , parent
# NOQA
if number >= 0 :
rounded_number = round_affected_number ( number , use_rounding = True , use_population_rounding = True )
min_number = 1000
value , unit = denomination ( rounded_number , min_number )
if number < min_number :
rounded_number = int ( round ( value , 1 ) ... |
def _init_properties ( self ) :
"""Init Properties""" | super ( BaseCRUDView , self ) . _init_properties ( )
# Reset init props
self . related_views = self . related_views or [ ]
self . _related_views = self . _related_views or [ ]
self . description_columns = self . description_columns or { }
self . validators_columns = self . validators_columns or { }
self . formatters_co... |
def select_where_like ( self , table , cols , where_col , start = None , end = None , anywhere = None , index = ( None , None ) , length = None ) :
"""Query rows from a table where a specific pattern is found in a column .
MySQL syntax assumptions :
( % ) The percent sign represents zero , one , or multiple cha... | # Retrieve search pattern
pattern = self . _like_pattern ( start , end , anywhere , index , length )
# Concatenate full statement and execute
statement = "SELECT {0} FROM {1} WHERE {2} LIKE '{3}'" . format ( join_cols ( cols ) , wrap ( table ) , where_col , pattern )
return self . fetch ( statement ) |
def is_int_type ( val ) :
"""Return True if ` val ` is of integer type .""" | try : # Python 2
return isinstance ( val , ( int , long ) )
except NameError : # Python 3
return isinstance ( val , int ) |
def mouseDoubleClickEvent ( self , event ) :
"""Launches an editor for the component , if the mouse cursor is over an item""" | if self . mode == BuildMode :
if event . button ( ) == QtCore . Qt . LeftButton :
index = self . indexAt ( event . pos ( ) )
self . edit ( index ) |
def __advice_stack_frame_protection ( self , frame ) :
"""Overriding of this is only permitted if and only if your name is
Megumin and you have a pet / familiar named Chomusuke .""" | if frame is None :
logger . debug ( 'currentframe() returned None; frame protection disabled' )
return
f_back = frame . f_back
while f_back :
if f_back . f_code is self . handle . __code__ :
raise RuntimeError ( "indirect invocation of '%s' by 'handle' is forbidden" % frame . f_code . co_name , )
... |
def _attach_to_model ( self , model ) :
"""When we have a model , save the relation in the database , to later create
RelatedCollection objects in the related model""" | super ( RelatedFieldMixin , self ) . _attach_to_model ( model )
if model . abstract : # do not manage the relation if it ' s an abstract model
return
# now , check related _ name and save the relation in the database
# get related parameters to identify the relation
self . related_name = self . _get_related_name ( ... |
def get_default_datatable_kwargs ( self , ** kwargs ) :
"""Builds the default set of kwargs for initializing a Datatable class . Note that by default
the MultipleDatatableMixin does not support any configuration via the view ' s class
attributes , and instead relies completely on the Datatable class itself to d... | kwargs [ 'view' ] = self
# This is provided by default , but if the view is instantiated outside of the request cycle
# ( such as for the purposes of embedding that view ' s datatable elsewhere ) , the request may
# not be required , so the user may not have a compelling reason to go through the trouble of
# putting it... |
def other_set_producer ( socket , which_set , image_archive , patch_archive , groundtruth ) :
"""Push image files read from the valid / test set TAR to a socket .
Parameters
socket : : class : ` zmq . Socket `
PUSH socket on which to send images .
which _ set : str
Which set of images is being processed .... | patch_images = extract_patch_images ( patch_archive , which_set )
num_patched = 0
with tar_open ( image_archive ) as tar :
filenames = sorted ( info . name for info in tar if info . isfile ( ) )
images = ( load_from_tar_or_patch ( tar , filename , patch_images ) for filename in filenames )
pathless_filename... |
def is_B_hypergraph ( self ) :
"""Indicates whether the hypergraph is a B - hypergraph .
In a B - hypergraph , all hyperedges are B - hyperedges - - that is , every
hyperedge has exactly one node in the head .
: returns : bool - - True iff the hypergraph is a B - hypergraph .""" | for hyperedge_id in self . _hyperedge_attributes :
head = self . get_hyperedge_head ( hyperedge_id )
if len ( head ) > 1 :
return False
return True |
def get_belapi_handle ( client , username = None , password = None ) :
"""Get BEL API arango db handle""" | ( username , password ) = get_user_creds ( username , password )
sys_db = client . db ( "_system" , username = username , password = password )
# Create a new database named " belapi "
try :
if username and password :
belapi_db = sys_db . create_database ( name = belapi_db_name , users = [ { "username" : us... |
def generic_converter_cli ( docgraph_class , file_descriptor = '' ) :
"""generic command line interface for importers . Will convert the file
specified on the command line into a dot representation of the
corresponding DiscourseDocumentGraph and write the output to stdout
or a file specified on the command li... | parser = argparse . ArgumentParser ( )
parser . add_argument ( 'input_file' , help = '{} file to be converted' . format ( file_descriptor ) )
parser . add_argument ( 'output_file' , nargs = '?' , default = sys . stdout )
args = parser . parse_args ( sys . argv [ 1 : ] )
assert os . path . isfile ( args . input_file ) ,... |
def start ( self ) :
"""Start a node""" | try : # For IOU we need to send the licence everytime
if self . node_type == "iou" :
try :
licence = self . _project . controller . settings [ "IOU" ] [ "iourc_content" ]
except KeyError :
raise aiohttp . web . HTTPConflict ( text = "IOU licence is not configured" )
y... |
def insert_element_to_dict_of_dicts_of_list ( dict_of_dict_of_list , first_key , second_key , parser ) :
"""Utility method
: param dict _ of _ dict _ of _ list :
: param first _ key :
: param second _ key :
: param parser :
: return :""" | list_to_insert = parser if isinstance ( parser , list ) else [ parser ]
if first_key not in dict_of_dict_of_list . keys ( ) :
dict_of_dict_of_list [ first_key ] = { second_key : list_to_insert }
else :
if second_key not in dict_of_dict_of_list [ first_key ] . keys ( ) :
dict_of_dict_of_list [ first_key ... |
def _load_feed ( path : str , view : View , config : nx . DiGraph ) -> Feed :
"""Multi - file feed filtering""" | config_ = remove_node_attributes ( config , [ "converters" , "transformations" ] )
feed_ = Feed ( path , view = { } , config = config_ )
for filename , column_filters in view . items ( ) :
config_ = reroot_graph ( config_ , filename )
view_ = { filename : column_filters }
feed_ = Feed ( feed_ , view = view_... |
def _ctypes_ex_variables ( executable ) :
"""Returns a list of the local variable definitions required to construct the
ctypes interop wrapper .""" | result = [ ]
for p in executable . ordered_parameters :
_ctypes_code_parameter ( result , p , "indices" )
_ctypes_code_parameter ( result , p , "variable" )
_ctypes_code_parameter ( result , p , "out" )
if type ( executable ) . __name__ == "Function" : # For functions , we still create a subroutine - type i... |
def setdoc ( self , newdoc ) :
"""Set a different document . Usually no need to call this directly , invoked implicitly by : meth : ` copy `""" | self . doc = newdoc
if self . doc and self . id :
self . doc . index [ self . id ] = self
for c in self :
if isinstance ( c , AbstractElement ) :
c . setdoc ( newdoc ) |
def title_prefix_json ( soup ) :
"titlePrefix with capitalisation changed" | prefix = title_prefix ( soup )
prefix_rewritten = elifetools . json_rewrite . rewrite_json ( "title_prefix_json" , soup , prefix )
return prefix_rewritten |
def getUnitCost ( self , CorpNum ) :
"""αα
’α¨αα
³ αα
₯α«αα
©αΌ αα
‘α«αα
‘ αα
ͺα¨αα
΅α«
args
CorpNum : αα
‘αΈαα
΅α―αα
¬αα
―α« αα
‘αα
₯αΈαα
‘αα
₯α«αα
©
return
αα
₯α«αα
©αΌ αα
‘α«αα
‘ by float
raise
PopbillException""" | result = self . _httpget ( '/FAX/UnitCost' , CorpNum )
return int ( result . unitCost ) |
def else_ ( self , result_expr ) :
"""Specify
Returns
builder : CaseBuilder""" | kwargs = { slot : getattr ( self , slot ) for slot in self . __slots__ if slot != 'default' }
result_expr = ir . as_value_expr ( result_expr )
kwargs [ 'default' ] = result_expr
# Maintain immutability
return type ( self ) ( ** kwargs ) |
def add_metadata ( self , observation_n , info_n , available_at = None ) :
"""Mutates the info _ n dictionary .""" | if self . instance_n is None :
return
with pyprofile . push ( 'vnc_env.diagnostics.Diagnostics.add_metadata' ) :
async = self . pool . imap_unordered ( self . _add_metadata_i , zip ( self . instance_n , observation_n , info_n , [ available_at ] * len ( observation_n ) ) )
list ( async ) |
def require_backup_exists ( func ) :
"""Requires that the file referred to by ` backup _ file ` exists in the file
system before running the decorated function .""" | def new_func ( * args , ** kwargs ) :
backup_file = kwargs [ 'backup_file' ]
if not os . path . exists ( backup_file ) :
raise RestoreError ( "Could not find file '{0}'" . format ( backup_file ) )
return func ( * args , ** kwargs )
return new_func |
def load ( source , triples = False , cls = PENMANCodec , ** kwargs ) :
"""Deserialize a list of PENMAN - encoded graphs from * source * .
Args :
source : a filename or file - like object to read from
triples : if True , read graphs as triples instead of as PENMAN
cls : serialization codec class
kwargs : ... | decode = cls ( ** kwargs ) . iterdecode
if hasattr ( source , 'read' ) :
return list ( decode ( source . read ( ) ) )
else :
with open ( source ) as fh :
return list ( decode ( fh . read ( ) ) ) |
def set_end_date ( self , lifetime ) :
"""Computes and store an absolute end _ date session according to the
lifetime of the session""" | self . end_date = ( datetime . datetime . now ( ) + datetime . timedelta ( 0 , lifetime ) ) |
def _create ( cls , name , node_type , physical_interfaces , nodes = 1 , loopback_ndi = None , log_server_ref = None , domain_server_address = None , enable_antivirus = False , enable_gti = False , sidewinder_proxy_enabled = False , default_nat = False , location_ref = None , enable_ospf = None , ospf_profile = None , ... | node_list = [ ]
for nodeid in range ( 1 , nodes + 1 ) : # start at nodeid = 1
node_list . append ( Node . _create ( name , node_type , nodeid , loopback_ndi ) )
domain_server_list = [ ]
if domain_server_address :
for num , server in enumerate ( domain_server_address ) :
try :
domain_server =... |
def Serialize ( self , writer ) :
"""Serialize full object .
Args :
writer ( neo . IO . BinaryWriter ) :""" | super ( Header , self ) . Serialize ( writer )
writer . WriteByte ( 0 ) |
def from_forums ( cls , forums ) :
"""Initializes a ` ` ForumVisibilityContentTree ` ` instance from a list of forums .""" | root_level = None
current_path = [ ]
nodes = [ ]
# Ensures forums last posts and related poster relations are " followed " for better
# performance ( only if we ' re considering a queryset ) .
forums = ( forums . select_related ( 'last_post' , 'last_post__poster' ) if isinstance ( forums , QuerySet ) else forums )
for ... |
def medlineRecordParser ( record ) :
"""The parser [ ` MedlineRecord ` ] ( . . / classes / MedlineRecord . html # metaknowledge . medline . MedlineRecord ) use . This takes an entry from [ medlineParser ( ) ] ( # metaknowledge . medline . medlineHandlers . medlineParser ) and parses it a part of the creation of a `... | tagDict = collections . OrderedDict ( )
tag = 'PMID'
mostRecentAuthor = None
for lineNum , line in record :
tmptag = line [ : 4 ] . rstrip ( )
contents = line [ 6 : - 1 ]
if tmptag . isalpha ( ) and line [ 4 ] == '-' :
tag = tmptag
if tag == 'AU' :
mostRecentAuthor = contents
... |
def distorted_bounding_box_crop ( image , bbox , min_object_covered = 0.1 , aspect_ratio_range = ( 0.75 , 1.33 ) , area_range = ( 0.05 , 1.0 ) , max_attempts = 100 , scope = None ) :
"""Generates cropped _ image using a one of the bboxes randomly distorted .
See ` tf . image . sample _ distorted _ bounding _ box ... | with tf . name_scope ( scope , default_name = "distorted_bounding_box_crop" , values = [ image , bbox ] ) : # Each bounding box has shape [ 1 , num _ boxes , box coords ] and
# the coordinates are ordered [ ymin , xmin , ymax , xmax ] .
# A large fraction of image datasets contain a human - annotated bounding
# box del... |
def flow_coef_bd ( CIJ ) :
'''Computes the flow coefficient for each node and averaged over the
network , as described in Honey et al . ( 2007 ) PNAS . The flow coefficient
is similar to betweenness centrality , but works on a local
neighborhood . It is mathematically related to the clustering
coefficient (... | N = len ( CIJ )
fc = np . zeros ( ( N , ) )
total_flo = np . zeros ( ( N , ) )
max_flo = np . zeros ( ( N , ) )
# loop over nodes
for v in range ( N ) : # find neighbors - note : both incoming and outgoing connections
nb , = np . where ( CIJ [ v , : ] + CIJ [ : , v ] . T )
fc [ v ] = 0
if np . where ( nb ) ... |
def betting_market_group_update ( self , betting_market_group_id , description = None , event_id = None , rules_id = None , status = None , account = None , ** kwargs ) :
"""Update an betting market . This needs to be * * proposed * * .
: param str betting _ market _ group _ id : Id of the betting market group
... | if not account :
if "default_account" in self . config :
account = self . config [ "default_account" ]
if not account :
raise ValueError ( "You need to provide an account" )
account = Account ( account , blockchain_instance = self )
bmg = BettingMarketGroup ( betting_market_group_id )
# Do not try to up... |
def rotate ( image , angle , interpolation = cv2 . INTER_CUBIC , borderMode = cv2 . BORDER_REFLECT , borderValue = 0 ) :
'''angle [ deg ]''' | s0 , s1 = image . shape
image_center = ( s0 - 1 ) / 2. , ( s1 - 1 ) / 2.
rot_mat = cv2 . getRotationMatrix2D ( image_center , angle , 1.0 )
result = cv2 . warpAffine ( image , rot_mat , image . shape , flags = interpolation , borderMode = borderMode , borderValue = borderValue )
return result |
def is_valid_rgb_color ( value ) :
"""Checks whether the value is a valid rgb or rgba color string .
Valid colors consist of :
- rgb ( 255 , 255 , 255)
- rgba ( 23 , 34 , 45 , . 5)""" | if not value :
return False
regex = re . compile ( RGB_COLOR_REGEX )
return bool ( regex . match ( value ) ) |
def batch_delete_intents ( self , parent , intents , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None ) :
"""Deletes intents in the specified agent .
Operation < response : ` ` google . protobuf . Empty ` ` >
Example :
> > > ... | # Wrap the transport method to add retry and timeout logic .
if 'batch_delete_intents' not in self . _inner_api_calls :
self . _inner_api_calls [ 'batch_delete_intents' ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . batch_delete_intents , default_retry = self . _method_configs [ 'Batch... |
def watch ( ) :
"""Renerate documentation when it changes .""" | # Start with a clean build
sphinx_build [ '-b' , 'html' , '-E' , 'docs' , 'docs/_build/html' ] & FG
handler = ShellCommandTrick ( shell_command = 'sphinx-build -b html docs docs/_build/html' , patterns = [ '*.rst' , '*.py' ] , ignore_patterns = [ '_build/*' ] , ignore_directories = [ '.tox' ] , drop_during_process = Tr... |
def check_resource ( resource ) :
'''Check a resource availability against a linkchecker backend
The linkchecker used can be configured on a resource basis by setting
the ` resource . extras [ ' check : checker ' ] ` attribute with a key that points
to a valid ` udata . linkcheckers ` entrypoint . If not set ... | linkchecker_type = resource . extras . get ( 'check:checker' )
LinkChecker = get_linkchecker ( linkchecker_type )
if not LinkChecker :
return { 'error' : 'No linkchecker configured.' } , 503
if is_ignored ( resource ) :
return dummy_check_response ( )
result = LinkChecker ( ) . check ( resource )
if not result ... |
def head ( self , path , query = None , data = None , redirects = True ) :
"""HEAD request wrapper for : func : ` request ( ) `""" | return self . request ( 'HEAD' , path , query , None , redirects ) |
def create_access_key ( self , name , is_active = True , permitted = [ ] , options = { } ) :
"""Creates a new access key . A master key must be set first .
: param name : the name of the access key to create
: param is _ active : Boolean value dictating whether this key is currently active ( default True )
: ... | return self . api . create_access_key ( name = name , is_active = is_active , permitted = permitted , options = options ) |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( VMSFSCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'vmsfs' } )
return config |
def process_request ( self , unused_request ) :
"""Called by Django before deciding which view to execute .""" | # Compare to the first half of toplevel ( ) in context . py .
tasklets . _state . clear_all_pending ( )
# Create and install a new context .
ctx = tasklets . make_default_context ( )
tasklets . set_context ( ctx ) |
def notch ( ts , freq_hz , bandwidth_hz = 1.0 ) :
"""notch filter to remove remove a particular frequency
Adapted from code by Sturla Molden""" | orig_ndim = ts . ndim
if ts . ndim is 1 :
ts = ts [ : , np . newaxis ]
channels = ts . shape [ 1 ]
fs = ( len ( ts ) - 1.0 ) / ( ts . tspan [ - 1 ] - ts . tspan [ 0 ] )
nyq = 0.5 * fs
freq = freq_hz / nyq
bandwidth = bandwidth_hz / nyq
R = 1.0 - 3.0 * ( bandwidth / 2.0 )
K = ( ( 1.0 - 2.0 * R * np . cos ( np . pi *... |
def grid_widgets ( self ) :
"""Configure all widgets using the grid geometry manager
Automatically called by the : meth : ` _ _ init _ _ ` method .
Does not have to be called by the user except in extraordinary
cases .""" | # Categories
for index , label in enumerate ( self . _category_labels . values ( ) ) :
label . grid ( column = 0 , row = index , padx = 5 , sticky = "nw" , pady = ( 1 , 0 ) if index == 0 else 0 )
# Canvas widgets
self . _canvas_scroll . grid ( column = 1 , row = 0 , padx = ( 0 , 5 ) , pady = 5 , sticky = "nswe" )
s... |
def count_features_of_type ( self , featuretype = None ) :
"""Simple count of features .
Can be faster than " grep " , and is faster than checking the length of
results from : meth : ` gffutils . FeatureDB . features _ of _ type ` .
Parameters
featuretype : string
Feature type ( e . g . , " gene " ) to co... | c = self . conn . cursor ( )
if featuretype is not None :
c . execute ( '''
SELECT count() FROM features
WHERE featuretype = ?
''' , ( featuretype , ) )
else :
c . execute ( '''
SELECT count() FROM features
''' )
results = c . fetch... |
def complete_opt_display ( self , text , * _ ) :
"""Autocomplete for display option""" | return [ t + " " for t in DISPLAYS if t . startswith ( text ) ] |
def stop ( self ) :
"""Stop the sensor .""" | # Check that everything is running
if not self . _running :
logging . warning ( 'PhoXi not running. Aborting stop' )
return False
# Stop the subscribers
self . _color_im_sub . unregister ( )
self . _depth_im_sub . unregister ( )
self . _normal_map_sub . unregister ( )
# Disconnect from the camera
rospy . Servic... |
def get_timezones ( ) :
"""Get the supported timezones .
The list will be cached unless you set the " fresh " attribute to True .
: param fresh : Whether to get a fresh list or not
: type fresh : bool
: rtype : tuple""" | base_dir = _DIRECTORY
zones = ( )
for root , dirs , files in os . walk ( base_dir ) :
for basename in files :
zone = os . path . join ( root , basename )
if os . path . isdir ( zone ) :
continue
zone = os . path . relpath ( zone , base_dir )
with open ( os . path . join (... |
def add_string ( self , string ) :
"""Add to the working string and its length and reset eos .""" | self . string += string
self . length += len ( string )
self . eos = 0 |
def get ( self , singleSnapshot = False ) :
"""* geneate the pyephem positions *
* * Key Arguments : * *
- ` ` singleSnapshot ` ` - - just extract positions for a single pyephem snapshot ( used for unit testing )
* * Return : * *
- ` ` None ` `""" | self . log . info ( 'starting the ``get`` method' )
global xephemOE
global tileSide
global magLimit
# GRAB PARAMETERS FROM SETTINGS FILE
tileSide = float ( self . settings [ "pyephem" ] [ "atlas exposure match side" ] )
magLimit = float ( self . settings [ "pyephem" ] [ "magnitude limit" ] )
snapshotsRequired = 1
while... |
def create ( cls , name , ipv4_network = None , ipv6_network = None , comment = None ) :
"""Create the network element
: param str name : Name of element
: param str ipv4 _ network : network cidr ( optional if ipv6)
: param str ipv6 _ network : network cidr ( optional if ipv4)
: param str comment : comment ... | ipv4_network = ipv4_network if ipv4_network else None
ipv6_network = ipv6_network if ipv6_network else None
json = { 'name' : name , 'ipv4_network' : ipv4_network , 'ipv6_network' : ipv6_network , 'comment' : comment }
return ElementCreator ( cls , json ) |
def add_view_menu ( self , name ) :
"""Adds a view or menu to the backend , model view _ menu
param name :
name of the view menu to add""" | view_menu = self . find_view_menu ( name )
if view_menu is None :
try :
view_menu = self . viewmenu_model ( name = name )
view_menu . save ( )
return view_menu
except Exception as e :
log . error ( c . LOGMSG_ERR_SEC_ADD_VIEWMENU . format ( str ( e ) ) )
return view_menu |
def simple_spool_transaction ( self , from_address , to , op_return , min_confirmations = 6 ) :
"""Utililty function to create the spool transactions . Selects the inputs ,
encodes the op _ return and constructs the transaction .
Args :
from _ address ( str ) : Address originating the transaction
to ( str )... | # list of addresses to send
ntokens = len ( to )
nfees = old_div ( self . _t . estimate_fee ( ntokens , 2 ) , self . fee )
inputs = self . select_inputs ( from_address , nfees , ntokens , min_confirmations = min_confirmations )
# outputs
outputs = [ { 'address' : to_address , 'value' : self . token } for to_address in ... |
def _forgiving_issubclass ( derived_class , base_class ) :
"""Forgiving version of ` ` issubclass ` `
Does not throw any exception when arguments are not of class type""" | return ( type ( derived_class ) is ClassType and type ( base_class ) is ClassType and issubclass ( derived_class , base_class ) ) |
def get_registers ( self , cpu_id ) :
"""Gets all the registers for the given CPU .
in cpu _ id of type int
The identifier of the Virtual CPU .
out names of type str
Array containing the lowercase register names .
out values of type str
Array parallel to the names holding the register values as if the
... | if not isinstance ( cpu_id , baseinteger ) :
raise TypeError ( "cpu_id can only be an instance of type baseinteger" )
( names , values ) = self . _call ( "getRegisters" , in_p = [ cpu_id ] )
return ( names , values ) |
def __findout_range ( self , name , decl_type , recursive ) :
"""implementation details""" | if not self . _optimized :
self . _logger . debug ( 'running non optimized query - optimization has not been done' )
decls = self . declarations
if recursive :
decls = make_flatten ( self . declarations )
if decl_type :
decls = [ d for d in decls if isinstance ( d , decl_type ) ]
ret... |
def get_available_languages ( self , obj , formset ) :
"""Fetching the available inline languages as queryset .""" | if obj : # Inlines dictate language code , not the parent model .
# Hence , not looking at obj . get _ available _ languages ( ) , but see what languages
# are used by the inline objects that point to it .
filter = { 'master__{0}' . format ( formset . fk . name ) : obj }
return self . model . _parler_meta . roo... |
def load_mirteFile ( path , m , logger = None ) :
"""Loads the mirte - file at < path > into the manager < m > .""" | l = logging . getLogger ( 'load_mirteFile' ) if logger is None else logger
had = set ( )
for name , path , d in walk_mirteFiles ( path , logger ) :
if os . path . realpath ( path ) in m . loaded_mirteFiles :
continue
identifier = name
if name in had :
identifier = path
else :
had... |
def adjustButtons ( self ) :
"""Adjusts the placement of the buttons for this line edit .""" | y = 1
for btn in self . buttons ( ) :
btn . setIconSize ( self . iconSize ( ) )
btn . setFixedSize ( QSize ( self . height ( ) - 2 , self . height ( ) - 2 ) )
# adjust the location for the left buttons
left_buttons = self . _buttons . get ( Qt . AlignLeft , [ ] )
x = ( self . cornerRadius ( ) / 2.0 ) + 2
for bt... |
def list ( self , request , * args , ** kwargs ) :
"""To get an actual value for object quotas limit and usage issue a * * GET * * request against * / api / < objects > / * .
To get all quotas visible to the user issue a * * GET * * request against * / api / quotas / *""" | return super ( QuotaViewSet , self ) . list ( request , * args , ** kwargs ) |
def allclose ( a , b , align = False , rtol = 1.e-5 , atol = 1.e-8 ) :
"""Compare two molecules for numerical equality .
Args :
a ( Cartesian ) :
b ( Cartesian ) :
align ( bool ) : a and b are
prealigned along their principal axes of inertia and moved to their
barycenters before comparing .
rtol ( flo... | return np . alltrue ( isclose ( a , b , align = align , rtol = rtol , atol = atol ) ) |
def force_unroll_loops ( self , max_loop_unrolling_times ) :
"""Unroll loops globally . The resulting CFG does not contain any loop , but this method is slow on large graphs .
: param int max _ loop _ unrolling _ times : The maximum iterations of unrolling .
: return : None""" | if not isinstance ( max_loop_unrolling_times , int ) or max_loop_unrolling_times < 0 :
raise AngrCFGError ( 'Max loop unrolling times must be set to an integer greater than or equal to 0 if ' + 'loop unrolling is enabled.' )
# Traverse the CFG and try to find the beginning of loops
loop_backedges = [ ]
start = self... |
def exists_table ( self , name , database = None ) :
"""Determine if the indicated table or view exists
Parameters
name : string
database : string , default None
Returns
if _ exists : boolean""" | return bool ( self . list_tables ( like = name , database = database ) ) |
def trailing_stop_loss_replace ( self , accountID , orderID , ** kwargs ) :
"""Shortcut to replace a pending Trailing Stop Loss Order in an Account
Args :
accountID : The ID of the Account
orderID : The ID of the Take Profit Order to replace
kwargs : The arguments to create a TrailingStopLossOrderRequest
... | return self . replace ( accountID , orderID , order = TrailingStopLossOrderRequest ( ** kwargs ) ) |
def build_freeform ( self , start_x = 0 , start_y = 0 , scale = 1.0 ) :
"""Return | FreeformBuilder | object to specify a freeform shape .
The optional * start _ x * and * start _ y * arguments specify the starting
pen position in local coordinates . They will be rounded to the
nearest integer before use and ... | try :
x_scale , y_scale = scale
except TypeError :
x_scale = y_scale = scale
return FreeformBuilder . new ( self , start_x , start_y , x_scale , y_scale ) |
def fromarray ( values , labels = None , npartitions = None , engine = None ) :
"""Load images from an array .
First dimension will be used to index images ,
so remaining dimensions after the first should
be the dimensions of the images ,
e . g . ( 3 , 100 , 200 ) for 3 x ( 100 , 200 ) images
Parameters
... | from . images import Images
import bolt
if isinstance ( values , bolt . spark . array . BoltArraySpark ) :
return Images ( values )
values = asarray ( values )
if values . ndim < 2 :
raise ValueError ( 'Array for images must have at least 2 dimensions, got %g' % values . ndim )
if values . ndim == 2 :
value... |
def get_owner_access_token ( self ) :
"""Return workflow owner access token .""" | from . database import Session
db_session = Session . object_session ( self )
owner = db_session . query ( User ) . filter_by ( id_ = self . owner_id ) . first ( )
return owner . access_token |
def apply_transformation ( self , structure , return_ranked_list = False ) :
"""Apply the transformation .
Args :
structure : input structure
return _ ranked _ list ( bool ) : Whether or not multiple structures are
returned . If return _ ranked _ list is a number , that number of
structures is returned . ... | num_remove_dict = { }
total_combis = 0
for indices , frac in zip ( self . indices , self . fractions ) :
num_to_remove = len ( indices ) * frac
if abs ( num_to_remove - int ( round ( num_to_remove ) ) ) > 1e-3 :
raise ValueError ( "Fraction to remove must be consistent with " "integer amounts in structu... |
import re
def lookup_string ( target_str , search_str ) :
"""This function locates a specific substring within a larger string and returns its position . It uses regular expressions to perform a search .
Sample Input : ( ' python ' , ' python programming language ' )
Sample Output : ( 0 , 6)
Other Examples : ... | result = re . search ( target_str , search_str )
start_pos = result . start ( )
end_pos = result . end ( )
return start_pos , end_pos |
def union ( self , enumerable , key = lambda x : x ) :
"""Returns enumerable that is a union of elements between self and given
enumerable
: param enumerable : enumerable to union self to
: param key : key selector used to determine uniqueness
: return : new Enumerable object""" | if not isinstance ( enumerable , Enumerable3 ) :
raise TypeError ( u"enumerable parameter must be an instance of Enumerable" )
if self . count ( ) == 0 :
return enumerable
if enumerable . count ( ) == 0 :
return self
return self . concat ( enumerable ) . distinct ( key ) |
def policy_definition_delete ( name , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Delete a policy definition .
: param name : The name of the policy definition to delete .
CLI Example :
. . code - block : : bash
salt - call azurearm _ resource . policy _ definition _ delete testpolicy''' | result = False
polconn = __utils__ [ 'azurearm.get_client' ] ( 'policy' , ** kwargs )
try : # pylint : disable = unused - variable
policy = polconn . policy_definitions . delete ( policy_definition_name = name )
result = True
except CloudError as exc :
__utils__ [ 'azurearm.log_cloud_error' ] ( 'resource' ,... |
def parse_next ( self , ptype , m ) :
"""Parse the next packet .
: param ptype : The ( string ) type of the incoming packet
: param ` . Message ` m : The paket content""" | if ptype == MSG_KEXGSS_GROUPREQ :
return self . _parse_kexgss_groupreq ( m )
elif ptype == MSG_KEXGSS_GROUP :
return self . _parse_kexgss_group ( m )
elif ptype == MSG_KEXGSS_INIT :
return self . _parse_kexgss_gex_init ( m )
elif ptype == MSG_KEXGSS_HOSTKEY :
return self . _parse_kexgss_hostkey ( m )
el... |
def image ( name , data , step = None , max_outputs = 3 , description = None ) :
"""Write an image summary .
Arguments :
name : A name for this summary . The summary tag used for TensorBoard will
be this name prefixed by any active name scopes .
data : A ` Tensor ` representing pixel data with shape ` [ k ,... | summary_metadata = metadata . create_summary_metadata ( display_name = None , description = description )
# TODO ( https : / / github . com / tensorflow / tensorboard / issues / 2109 ) : remove fallback
summary_scope = ( getattr ( tf . summary . experimental , 'summary_scope' , None ) or tf . summary . summary_scope )
... |
def _extract_actions_unique_topics ( self , movement_counts , max_movements , cluster_topology , max_movement_size ) :
"""Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics .
Algorithm :
1 . Group actions by by topic - name : { topic : actio... | # Group actions by topic
topic_actions = defaultdict ( list )
for t_p , replica_change_cnt in movement_counts :
topic_actions [ t_p [ 0 ] ] . append ( ( t_p , replica_change_cnt ) )
# Create reduced assignment minimizing duplication of topics
extracted_actions = [ ]
curr_movements = 0
curr_size = 0
action_available... |
def publish ( self , topic , data , defer = None ) :
"""Publish a message to the given topic over http .
: param topic : the topic to publish to
: param data : bytestring data to publish
: param defer : duration in millisconds to defer before publishing
( requires nsq 0.3.6)""" | nsq . assert_valid_topic_name ( topic )
fields = { 'topic' : topic }
if defer is not None :
fields [ 'defer' ] = '{}' . format ( defer )
return self . _request ( 'POST' , '/pub' , fields = fields , body = data ) |
def getctime ( self , path ) :
"""Returns the creation time of the fake file .
Args :
path : the path to fake file .
Returns :
( int , float ) the creation time of the fake file in number of
seconds since the epoch .
Raises :
OSError : if the file does not exist .""" | try :
file_obj = self . filesystem . resolve ( path )
except IOError :
self . filesystem . raise_os_error ( errno . ENOENT )
return file_obj . st_ctime |
def list_shoulds ( options ) :
"""Construct the list of ' SHOULD ' validators to be run by the validator .""" | validator_list = [ ]
# Default : enable all
if not options . disabled and not options . enabled :
validator_list . extend ( CHECKS [ 'all' ] )
return validator_list
# - - disable
# Add SHOULD requirements to the list unless disabled
if options . disabled :
if 'all' not in options . disabled :
if 'fo... |
def pre_init ( ) :
"""The pre _ init function of the plugin . Here rafcon - classes can be extended / monkey - patched or completely substituted .
A example is given with the rafcon _ execution _ hooks _ plugin .
: return :""" | logger . info ( "Run pre-initiation hook of {} plugin." . format ( __file__ . split ( os . path . sep ) [ - 2 ] ) )
# Example : Monkey - Path rafcon . core . script . Script class to print additional log - message while execution
from rafcon . core . script import Script
old_execute_method = Script . execute
def new_ex... |
def setDragDropFilter ( self , ddFilter ) :
"""Sets the drag drop filter for this widget .
: warning The dragdropfilter is stored as a weak - reference , so using \
mutable methods will not be stored well . Things like \
instancemethods will not hold their pointer after they \
leave the scope that is being ... | if ddFilter :
self . _dragDropFilterRef = weakref . ref ( ddFilter )
else :
self . _dragDropFilterRef = None |
def validate_registry_uri ( uri : str ) -> None :
"""Raise an exception if the URI does not conform to the registry URI scheme .""" | parsed = parse . urlparse ( uri )
scheme , authority , pkg_name , query = ( parsed . scheme , parsed . netloc , parsed . path , parsed . query , )
validate_registry_uri_scheme ( scheme )
validate_registry_uri_authority ( authority )
if query :
validate_registry_uri_version ( query )
validate_package_name ( pkg_name... |
def get_byte_array ( integer ) :
"""Return the variable length bytes corresponding to the given int""" | # Operate in big endian ( unlike most of Telegram API ) since :
# > " . . . pq is a representation of a natural number
# ( in binary * big endian * format ) . . . "
# > " . . . current value of dh _ prime equals
# ( in * big - endian * byte order ) . . . "
# Reference : https : / / core . telegram . org / mtproto / aut... |
def open_file ( path , grib_errors = 'warn' , ** kwargs ) :
"""Open a GRIB file as a ` ` cfgrib . Dataset ` ` .""" | if 'mode' in kwargs :
warnings . warn ( "the `mode` keyword argument is ignored and deprecated" , FutureWarning )
kwargs . pop ( 'mode' )
stream = messages . FileStream ( path , message_class = cfmessage . CfMessage , errors = grib_errors )
return Dataset ( * build_dataset_components ( stream , ** kwargs ) ) |
def collapse_phenotypes ( self , input_phenotype_labels , output_phenotype_label , verbose = True ) :
"""Rename one or more input phenotypes to a single output phenotype
Args :
input _ phenotype _ labels ( list ) : A str name or list of names to combine
output _ phenotype _ label ( list ) : A str name to chan... | if isinstance ( input_phenotype_labels , str ) :
input_phenotype_labels = [ input_phenotype_labels ]
bad_phenotypes = set ( input_phenotype_labels ) - set ( self . phenotypes )
if len ( bad_phenotypes ) > 0 :
raise ValueError ( "Error phenotype(s) " + str ( bad_phenotypes ) + " are not in the data." )
data = se... |
def _get_ned_query_url ( self , raDeg , decDeg , arcsec ) :
"""* single ned conesearch *
* * Key Arguments : * *
* * Return : * *
- None
. . todo : :
- @ review : when complete , clean _ get _ ned _ query _ url method
- @ review : when complete add logging""" | self . log . info ( 'starting the ``_get_ned_query_url`` method' )
radArcMin = float ( arcsec ) / ( 60. )
if self . redshift == True :
z_constraint = "Available"
else :
z_constraint = "Unconstrained"
url = "http://ned.ipac.caltech.edu/cgi-bin/objsearch"
params = { "in_csys" : "Equatorial" , "in_equinox" : "J200... |
def sentinels ( self , name ) :
"""Returns a list of sentinels for ` ` name ` ` .""" | fut = self . execute ( b'SENTINELS' , name , encoding = 'utf-8' )
return wait_convert ( fut , parse_sentinel_slaves_and_sentinels ) |
def get_allEvents ( self ) :
'''Splitting this method out to get the set of events to filter allows
one to subclass for different subsets of events without copying other
logic''' | if not hasattr ( self , 'allEvents' ) :
timeFilters = { 'endTime__gte' : timezone . now ( ) }
if getConstant ( 'registration__displayLimitDays' ) or 0 > 0 :
timeFilters [ 'startTime__lte' ] = timezone . now ( ) + timedelta ( days = getConstant ( 'registration__displayLimitDays' ) )
# Get the Event l... |
def _flatten_beam_dim ( tensor ) :
"""Reshapes first two dimensions in to single dimension .
Args :
tensor : Tensor to reshape of shape [ A , B , . . . ]
Returns :
Reshaped tensor of shape [ A * B , . . . ]""" | shape = _shape_list ( tensor )
shape [ 0 ] *= shape [ 1 ]
shape . pop ( 1 )
# Remove beam dim
return tf . reshape ( tensor , shape ) |
def update_traded ( self , traded_update ) :
""": param traded _ update : [ price , size ]""" | if not traded_update :
self . traded . clear ( )
else :
self . traded . update ( traded_update ) |
async def takewhile ( source , func ) :
"""Forward an asynchronous sequence while a condition is met .
The given function takes the item as an argument and returns a boolean
corresponding to the condition to meet . The function can either be
synchronous or asynchronous .""" | iscorofunc = asyncio . iscoroutinefunction ( func )
async with streamcontext ( source ) as streamer :
async for item in streamer :
result = func ( item )
if iscorofunc :
result = await result
if not result :
return
yield item |
def get_highlighted_code ( name , code , type = 'terminal' ) :
"""If pygments are available on the system
then returned output is colored . Otherwise
unchanged content is returned .""" | import logging
try :
import pygments
pygments
except ImportError :
return code
from pygments import highlight
from pygments . lexers import guess_lexer_for_filename , ClassNotFound
from pygments . formatters import TerminalFormatter
try :
lexer = guess_lexer_for_filename ( name , code )
formatter = ... |
def res_phi_pie ( pst , logger = None , ** kwargs ) :
"""plot current phi components as a pie chart .
Parameters
pst : pyemu . Pst
logger : pyemu . Logger
kwargs : dict
accepts ' include _ zero ' as a flag to include phi groups with
only zero - weight obs ( not sure why anyone would do this , but
what... | if logger is None :
logger = Logger ( 'Default_Loggger.log' , echo = False )
logger . log ( "plot res_phi_pie" )
if "ensemble" in kwargs :
try :
res = pst_utils . res_from_en ( pst , kwargs [ 'ensemble' ] )
except :
logger . statement ( "res_1to1: could not find ensemble file {0}" . format (... |
def mean_size ( self , p , q ) :
'''> > > psd = PSDLognormal ( s = 0.5 , d _ characteristic = 5E - 6)
> > > psd . mean _ size ( 3 , 2)
4.412484512922977e - 06
Note that for the case where p = = q , a different set of formulas are
required - which do not have analytical results for many distributions .
The... | if p == q :
p -= 1e-9
q += 1e-9
pow1 = q - self . order
denominator = self . _pdf_basis_integral_definite ( d_min = self . d_minimum , d_max = self . d_excessive , n = pow1 )
root_power = p - q
pow3 = p - self . order
numerator = self . _pdf_basis_integral_definite ( d_min = self . d_minimum , d_max = self . d_... |
def set_proxy ( self , proxy_account , account = None , ** kwargs ) :
"""Set a specific proxy for account
: param bitshares . account . Account proxy _ account : Account to be
proxied
: param str account : ( optional ) the account to allow access
to ( defaults to ` ` default _ account ` ` )""" | if not account :
if "default_account" in self . config :
account = self . config [ "default_account" ]
if not account :
raise ValueError ( "You need to provide an account" )
account = Account ( account , blockchain_instance = self )
proxy = Account ( proxy_account , blockchain_instance = self )
options ... |
def makebunches ( data , commdct ) :
"""make bunches with data""" | bunchdt = { }
ddtt , dtls = data . dt , data . dtls
for obj_i , key in enumerate ( dtls ) :
key = key . upper ( )
bunchdt [ key ] = [ ]
objs = ddtt [ key ]
for obj in objs :
bobj = makeabunch ( commdct , obj , obj_i )
bunchdt [ key ] . append ( bobj )
return bunchdt |
def window_open ( dev , temp , duration ) :
"""Gets and sets the window open settings .""" | click . echo ( "Window open: %s" % dev . window_open )
if temp and duration :
click . echo ( "Setting window open conf, temp: %s duration: %s" % ( temp , duration ) )
dev . window_open_config ( temp , duration ) |
def remove_node ( self , node , stop = False ) :
"""Removes a node from the cluster .
By default , it doesn ' t also stop the node , just remove from
the known hosts of this cluster .
: param node : node to remove
: type node : : py : class : ` Node `
: param stop : Stop the node
: type stop : bool""" | if node . kind not in self . nodes :
raise NodeNotFound ( "Unable to remove node %s: invalid node type `%s`." , node . name , node . kind )
else :
try :
index = self . nodes [ node . kind ] . index ( node )
if self . nodes [ node . kind ] [ index ] :
del self . nodes [ node . kind ] ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.