signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def register_peer ( self , connection_id , endpoint ) :
"""Registers a connected connection _ id .
Args :
connection _ id ( str ) : A unique identifier which identifies an
connection on the network server socket .
endpoint ( str ) : The publically reachable endpoint of the new
peer""" | with self . _lock :
if len ( self . _peers ) < self . _maximum_peer_connectivity :
self . _peers [ connection_id ] = endpoint
self . _topology . set_connection_status ( connection_id , PeerStatus . PEER )
LOGGER . debug ( "Added connection_id %s with endpoint %s, " "connected identities are ... |
def _remove_non_serializable_store_entries ( store : dict ) :
"""This function is called if there are non - serializable items in the global script storage .
This function removes all such items .""" | removed_key_list = [ ]
for key , value in store . items ( ) :
if not ( _is_serializable ( key ) and _is_serializable ( value ) ) :
_logger . info ( "Remove non-serializable item from the global script store. Key: '{}', Value: '{}'. " "This item cannot be saved and therefore will be lost." . format ( key , v... |
def read ( self , given_file ) :
"""Read given _ file to self . contents
Will ignoring duplicate lines if self . unique is True
Will sort self . contents after reading file if self . sorted is True""" | if self . unique is not False and self . unique is not True :
raise AttributeError ( "Attribute 'unique' is not True or False." )
self . filename = str . strip ( given_file )
self . log ( 'Read-only opening {0}' . format ( self . filename ) )
with open ( self . filename , 'r' ) as handle :
for line in handle :
... |
def remove_root_metadata ( docgraph ) :
"""removes the ` ` metadata ` ` attribute of the root node of a document graph .
this is necessary for some exporters , as the attribute may contain
( nested ) dictionaries .""" | docgraph . node [ docgraph . root ] . pop ( 'metadata' , None )
# delete metadata from the generic root node ( which probably only exists
# when we merge graphs on the command line , cf . issue # 89
if 'discoursegraph:root_node' in docgraph . node :
docgraph . node [ 'discoursegraph:root_node' ] . pop ( 'metadata' ... |
def dot_v3 ( v , w ) :
"""Return the dotproduct of two vectors .""" | return sum ( [ x * y for x , y in zip ( v , w ) ] ) |
def _random_helper ( random , sampler , params , shape , dtype , kwargs ) :
"""Helper function for random generators .""" | if isinstance ( params [ 0 ] , Symbol ) :
for i in params [ 1 : ] :
assert isinstance ( i , Symbol ) , "Distribution parameters must all have the same type, but got " "both %s and %s." % ( type ( params [ 0 ] ) , type ( i ) )
return sampler ( * params , shape = shape , dtype = dtype , ** kwargs )
elif i... |
def wait_for ( predicate , timeout_seconds = 120 , sleep_seconds = 1 , ignore_exceptions = True , inverse_predicate = False , noisy = False , required_consecutive_success_count = 1 ) :
"""waits or spins for a predicate , returning the result .
Predicate is a function that returns a truthy or falsy value .
An ex... | count = 0
start_time = time_module . time ( )
timeout = Deadline . create_deadline ( timeout_seconds )
while True :
try :
result = predicate ( )
except Exception as e :
if ignore_exceptions :
if noisy :
logger . exception ( "Ignoring error during wait." )
else... |
def outer_horizontal_border_top ( self ) :
"""The complete outer top horizontal border section , including left and right margins .
Returns :
str : The top menu border .""" | return u"{lm}{lv}{hz}{rv}" . format ( lm = ' ' * self . margins . left , lv = self . border_style . top_left_corner , rv = self . border_style . top_right_corner , hz = self . outer_horizontals ( ) ) |
def static_filename ( self , repo : str , branch : str , relative_path : Union [ str , Path ] , * , depth : DepthDefinitionType = 1 , reference : ReferenceDefinitionType = None ) -> Path :
"""Returns an absolute path to where a file from the repo was cloned to .
: param repo : Repo URL
: param branch : Branch n... | self . validate_repo_url ( repo )
depth = self . validate_depth ( depth )
reference = self . validate_reference ( reference )
if not isinstance ( relative_path , Path ) :
relative_path = Path ( relative_path )
_ , repo_path = self . get_files ( repo , branch , depth = depth , reference = reference )
result = repo_p... |
def clean_exit ( self , dwExitCode = 0 , bWait = False , dwTimeout = None ) :
"""Injects a new thread to call ExitProcess ( ) .
Optionally waits for the injected thread to finish .
@ warning : Setting C { bWait } to C { True } when the process is frozen by a
debug event will cause a deadlock in your debugger ... | if not dwExitCode :
dwExitCode = 0
pExitProcess = self . resolve_label ( 'kernel32!ExitProcess' )
aThread = self . start_thread ( pExitProcess , dwExitCode )
if bWait :
aThread . wait ( dwTimeout ) |
def _root ( name = '' , all_roots = False ) :
'''Return the container root directory . Starting with systemd 219 , new
images go into / var / lib / machines .''' | if _sd_version ( ) >= 219 :
if all_roots :
return [ os . path . join ( x , name ) for x in ( '/var/lib/machines' , '/var/lib/container' ) ]
else :
return os . path . join ( '/var/lib/machines' , name )
else :
ret = os . path . join ( '/var/lib/container' , name )
if all_roots :
r... |
def get_class_alias ( klass_or_alias ) :
"""Finds the L { ClassAlias } that is registered to C { klass _ or _ alias } .
If a string is supplied and no related L { ClassAlias } is found , the alias is
loaded via L { load _ class } .
@ raise UnknownClassAlias : Unknown alias""" | if isinstance ( klass_or_alias , python . str_types ) :
try :
return CLASS_CACHE [ klass_or_alias ]
except KeyError :
return load_class ( klass_or_alias )
try :
return CLASS_CACHE [ klass_or_alias ]
except KeyError :
raise UnknownClassAlias ( 'Unknown alias for %r' % ( klass_or_alias , )... |
def delete ( id ) :
"""Delete a post .
Ensures that the post exists and that the logged in user is the
author of the post .""" | post = get_post ( id )
db . session . delete ( post )
db . session . commit ( )
return redirect ( url_for ( "blog.index" ) ) |
async def full_dispatch_request ( self , request_context : Optional [ RequestContext ] = None , ) -> Response :
"""Adds pre and post processing to the request dispatching .
Arguments :
request _ context : The request context , optional as Flask
omits this argument .""" | await self . try_trigger_before_first_request_functions ( )
await request_started . send ( self )
try :
result = await self . preprocess_request ( request_context )
if result is None :
result = await self . dispatch_request ( request_context )
except Exception as error :
result = await self . handle... |
def bugreport ( dest_file = "default.log" ) :
"""Prints dumpsys , dumpstate , and logcat data to the screen , for the purposes of bug reporting
: return : result of _ exec _ command ( ) execution""" | adb_full_cmd = [ v . ADB_COMMAND_PREFIX , v . ADB_COMMAND_BUGREPORT ]
try :
dest_file_handler = open ( dest_file , "w" )
except IOError :
print ( "IOError: Failed to create a log file" )
# We have to check if device is available or not before executing this command
# as adb bugreport will wait - for - device in... |
def search_tasks ( self , * queries ) :
"""Return a list of tasks that match some search criteria .
. . note : : Example queries can be found
` here < https : / / todoist . com / Help / timeQuery > ` _ .
. . note : : A standard set of queries are available
in the : class : ` pytodoist . todoist . Query ` cl... | queries = json . dumps ( queries )
response = API . query ( self . api_token , queries )
_fail_if_contains_errors ( response )
query_results = response . json ( )
tasks = [ ]
for result in query_results :
if 'data' not in result :
continue
all_tasks = result [ 'data' ]
if result [ 'type' ] == Query ... |
def get_electrode_node ( self , electrode ) :
"""For a given electrode ( e . g . from a config . dat file ) , return the true
node number as in self . nodes [ ' sorted ' ]""" | elec_node_raw = int ( self . electrodes [ electrode - 1 ] [ 0 ] )
if ( self . header [ 'cutmck' ] ) :
elec_node = self . nodes [ 'rev_cutmck_index' ] [ elec_node_raw ]
else :
elec_node = elec_node_raw - 1
return int ( elec_node ) |
def _cleanup_temporary_files ( self ) : # type : ( Downloader ) - > None
"""Cleanup temporary files in case of an exception or interrupt .
This function is not thread - safe .
: param Downloader self : this""" | # iterate through dd map and cleanup files
for key in self . _dd_map :
dd = self . _dd_map [ key ]
try :
dd . cleanup_all_temporary_files ( )
except Exception as e :
logger . exception ( e ) |
def run_later ( self , callable_ , timeout , * args , ** kwargs ) :
"""Schedules the specified callable for delayed execution .
Returns a TimerTask instance that can be used to cancel pending
execution .""" | self . lock . acquire ( )
try :
if self . die :
raise RuntimeError ( 'This timer has been shut down and ' 'does not accept new jobs.' )
job = TimerTask ( callable_ , * args , ** kwargs )
self . _jobs . append ( ( job , time . time ( ) + timeout ) )
self . _jobs . sort ( key = lambda j : j [ 1 ] ... |
def _collapse_default ( self , entry ) :
"""Collapses the list structure in entry to a single string representing the default
value assigned to a variable or its dimensions .""" | if isinstance ( entry , tuple ) or isinstance ( entry , list ) :
sets = [ ]
i = 0
while i < len ( entry ) :
if isinstance ( entry [ i ] , str ) and i + 1 < len ( entry ) and isinstance ( entry [ i + 1 ] , list ) :
sets . append ( ( entry [ i ] , entry [ i + 1 ] ) )
i += 2
... |
def cmyk ( self ) :
"""CMYK : all returned in range 0.0 - 1.0""" | c , m , y = self . cmy
k = min ( c , m , y )
# Handle division by zero in case of black = 1
if k != 1 :
c = ( c - k ) / ( 1 - k )
m = ( m - k ) / ( 1 - k )
y = ( y - k ) / ( 1 - k )
else :
c , m , y = 1 , 1 , 1
cmyk = ( c , m , y , k )
# Apply bound and return
return tuple ( map ( lambda x : self . _app... |
def envGet ( self , name , default = None , conv = None ) :
"""Return value for environment variable or None .
@ param name : Name of environment variable .
@ param default : Default value if variable is undefined .
@ param conv : Function for converting value to desired type .
@ return : Value of environme... | if self . _env . has_key ( name ) :
if conv is not None :
return conv ( self . _env . get ( name ) )
else :
return self . _env . get ( name )
else :
return default |
def verify_recipient ( self , recipient ) :
"""Verify that I ' m the recipient of the assertion
: param recipient : A URI specifying the entity or location to which an
attesting entity can present the assertion .
: return : True / False""" | if not self . conv_info :
return True
_info = self . conv_info
try :
if recipient == _info [ 'entity_id' ] :
return True
except KeyError :
pass
try :
if recipient in self . return_addrs :
return True
except KeyError :
pass
return False |
def control_surface_send ( self , target , idSurface , mControl , bControl , force_mavlink1 = False ) :
'''Control for surface ; pending and order to origin .
target : The system setting the commands ( uint8 _ t )
idSurface : ID control surface send 0 : throttle 1 : aileron 2 : elevator 3 : rudder ( uint8 _ t )... | return self . send ( self . control_surface_encode ( target , idSurface , mControl , bControl ) , force_mavlink1 = force_mavlink1 ) |
def link ( obj_files , out_file = None , shared = False , CompilerRunner_ = None , cwd = None , cplus = False , fort = False , ** kwargs ) :
"""Link object files .
Parameters
obj _ files : iterable of path strings
out _ file : path string ( optional )
path to executable / shared library , if missing
it wi... | if out_file is None :
out_file , ext = os . path . splitext ( os . path . basename ( obj_files [ - 1 ] ) )
if shared :
out_file += sharedext
if not CompilerRunner_ :
if fort :
CompilerRunner_ , extra_kwargs , vendor = get_mixed_fort_c_linker ( vendor = kwargs . get ( 'vendor' , None ) , meta... |
def find_nearest ( self , hex_code , system , filter_set = None ) :
"""Find a color name that ' s most similar to a given sRGB hex code .
In normalization terms , this method implements " normalize an arbitrary sRGB value
to a well - defined color name " .
Args :
system ( string ) : The color system . Curre... | if system not in self . _colors_by_system_hex :
raise ValueError ( "%r is not a registered color system. Try one of %r" % ( system , self . _colors_by_system_hex . keys ( ) ) )
hex_code = hex_code . lower ( ) . strip ( )
# Try direct hit ( fast path )
if hex_code in self . _colors_by_system_hex [ system ] :
col... |
def network_from_bbox ( lat_min = None , lng_min = None , lat_max = None , lng_max = None , bbox = None , network_type = 'walk' , two_way = True , timeout = 180 , memory = None , max_query_area_size = 50 * 1000 * 50 * 1000 , custom_osm_filter = None ) :
"""Make a graph network from a bounding lat / lon box composed... | start_time = time . time ( )
if bbox is not None :
assert isinstance ( bbox , tuple ) and len ( bbox ) == 4 , 'bbox must be a 4 element tuple'
assert ( lat_min is None ) and ( lng_min is None ) and ( lat_max is None ) and ( lng_max is None ) , 'lat_min, lng_min, lat_max and lng_max must be None ' 'if you are us... |
def file_arg ( arg ) :
"""Parses a file argument , i . e . starts with file : / /""" | prefix = 'file://'
if arg . startswith ( prefix ) :
return os . path . abspath ( arg [ len ( prefix ) : ] )
else :
msg = 'Invalid file argument "{}", does not begin with "file://"'
raise argparse . ArgumentTypeError ( msg . format ( arg ) ) |
def read ( self ) :
"""Read the project config file""" | # - - If no project finel found , just return
if not isfile ( PROJECT_FILENAME ) :
print ( 'Info: No {} file' . format ( PROJECT_FILENAME ) )
return
# - - Read stored board
board = self . _read_board ( )
# - - Update board
self . board = board
if not board :
print ( 'Error: invalid {} project file' . format... |
def stash_state ( ) :
"""Builds a list of all currently pressed scan codes , releases them and returns
the list . Pairs well with ` restore _ state ` and ` restore _ modifiers ` .""" | # TODO : stash caps lock / numlock / scrollock state .
with _pressed_events_lock :
state = sorted ( _pressed_events )
for scan_code in state :
_os_keyboard . release ( scan_code )
return state |
def p_iteration_statement_6 ( self , p ) :
"""iteration _ statement : FOR LPAREN VAR identifier initializer _ noin IN expr RPAREN statement""" | vardecl = self . asttypes . VarDeclNoIn ( identifier = p [ 4 ] , initializer = p [ 5 ] )
vardecl . setpos ( p , 3 )
p [ 0 ] = self . asttypes . ForIn ( item = vardecl , iterable = p [ 7 ] , statement = p [ 9 ] )
p [ 0 ] . setpos ( p ) |
def sg_upconv1d ( tensor , opt ) :
r"""Applies 1 - D a up convolution ( or convolution transpose ) .
Args :
tensor : A 3 - D ` Tensor ` ( automatically passed by decorator ) .
opt :
size : A positive ` integer ` representing ` [ kernel width ] ` . As a default it is set to 4
stride : A positive ` integer ... | # default options
opt += tf . sg_opt ( size = 4 , stride = 2 , pad = 'SAME' )
opt . size = [ opt . size , 1 ]
opt . stride = [ 1 , opt . stride , 1 , 1 ]
# parameter tf . sg _ initializer
w = tf . sg_initializer . he_uniform ( 'W' , ( opt . size [ 0 ] , opt . size [ 1 ] , opt . dim , opt . in_dim ) , regularizer = opt ... |
def get_subpackages ( name ) :
"""Return subpackages of package * name *""" | splist = [ ]
for dirpath , _dirnames , _filenames in os . walk ( name ) :
if osp . isfile ( osp . join ( dirpath , '__init__.py' ) ) :
splist . append ( "." . join ( dirpath . split ( os . sep ) ) )
return splist |
def do_sqlite_connect ( dbapi_connection , connection_record ) :
"""Ensure SQLite checks foreign key constraints .
For further details see " Foreign key support " sections on
https : / / docs . sqlalchemy . org / en / latest / dialects / sqlite . html # foreign - key - support""" | # Enable foreign key constraint checking
cursor = dbapi_connection . cursor ( )
cursor . execute ( 'PRAGMA foreign_keys=ON' )
cursor . close ( ) |
def src_file ( self ) :
"""Get the latest src _ uri for a stage 3 tarball .
Returns ( str ) :
Latest src _ uri from gentoo ' s distfiles mirror .""" | try :
src_uri = ( curl [ Gentoo . _LATEST_TXT ] | tail [ "-n" , "+3" ] | cut [ "-f1" , "-d " ] ) ( ) . strip ( )
except ProcessExecutionError as proc_ex :
src_uri = "NOT-FOUND"
LOG . error ( "Could not determine latest stage3 src uri: %s" , str ( proc_ex ) )
return src_uri |
def add_teardown_callback ( self , callback : Callable , pass_exception : bool = False ) -> None :
"""Add a callback to be called when this context closes .
This is intended for cleanup of resources , and the list of callbacks is processed in the
reverse order in which they were added , so the last added callba... | assert check_argument_types ( )
self . _check_closed ( )
self . _teardown_callbacks . append ( ( callback , pass_exception ) ) |
def construct_latent_tower ( self , images , time_axis ) :
"""Create the latent tower .""" | # No latent in the first phase
first_phase = tf . less ( self . get_iteration_num ( ) , self . hparams . num_iterations_1st_stage )
# use all frames by default but this allows more
# predicted frames at inference time
latent_num_frames = self . hparams . latent_num_frames
tf . logging . info ( "Creating latent tower wi... |
def json_processor ( entity ) :
'''Unserialize raw POST data in JSON format to a Python data structure .
: param entity : raw POST data''' | if six . PY2 :
body = entity . fp . read ( )
else : # https : / / github . com / cherrypy / cherrypy / pull / 1572
contents = BytesIO ( )
body = entity . fp . read ( fp_out = contents )
contents . seek ( 0 )
body = salt . utils . stringutils . to_unicode ( contents . read ( ) )
del contents
try ... |
def guess_mime ( filename ) :
"""Guess the MIME type of given filename using file ( 1 ) and if that
fails by looking at the filename extension with the Python mimetypes
module .
The result of this function is cached .""" | mime , encoding = guess_mime_file ( filename )
if mime is None :
mime , encoding = guess_mime_mimedb ( filename )
assert mime is not None or encoding is None
return mime , encoding |
def download ( self , url , destination_path ) :
"""Download url to given path .
Returns Promise - > sha256 of downloaded file .
Args :
url : address of resource to download .
destination _ path : ` str ` , path to directory where to download the resource .
Returns :
Promise obj - > ( ` str ` , int ) : ... | self . _pbar_url . update_total ( 1 )
future = self . _executor . submit ( self . _sync_download , url , destination_path )
return promise . Promise . resolve ( future ) |
def compare ( self , reference_ids : Iterable , query_profiles : Iterable [ Iterable ] , method : Optional ) -> SimResult :
"""Given two lists of entities ( classes , individuals ) ,
resolves them to some type ( phenotypes , go terms , etc ) and
returns their similarity""" | pass |
def set_published_date ( self , date = None ) :
"""Set the published date of a IOC to the current date .
User may specify the date they want to set as well .
: param date : Date value to set the published date to . This should be in the xsdDate form .
This defaults to the current date if it is not provided . ... | if date :
match = re . match ( DATE_REGEX , date )
if not match :
raise IOCParseError ( 'Published date is not valid. Must be in the form YYYY-MM-DDTHH:MM:SS' )
ioc_et . set_root_published_date ( self . root , date )
return True |
def edit ( self , text ) :
"""Edit a text using an external editor .""" | if isinstance ( text , unicode ) :
text = text . encode ( self . _encoding )
if self . _editor is None :
printer . p ( 'Warning: no editor found, skipping edit' )
return text
with tempfile . NamedTemporaryFile ( mode = 'w+' , suffix = 'kolekto-edit' ) as ftmp :
ftmp . write ( text )
ftmp . flush ( )... |
def open ( self , visible = False ) :
"""Dispatches the matlab COM client .
Note : If this method fails , try running matlab with the - regserver flag .""" | if self . client :
raise MatlabConnectionError ( 'Matlab(TM) COM client is still active. Use close to ' 'close it' )
self . client = win32com . client . Dispatch ( 'matlab.application' )
self . client . visible = visible |
def guess_encoding ( text , default = DEFAULT_ENCODING ) :
"""Guess string encoding .
Given a piece of text , apply character encoding detection to
guess the appropriate encoding of the text .""" | result = chardet . detect ( text )
return normalize_result ( result , default = default ) |
def _set_current_page ( self , current_page ) :
"""Get the current page for the request .
: param current _ page : The current page of results
: type current _ page : int
: rtype : int""" | if not current_page :
self . resolve_current_page ( )
if not self . _is_valid_page_number ( current_page ) :
return 1
return current_page |
def to_pascal_case ( s ) :
"""Transform underscore separated string to pascal case""" | return re . sub ( r'(?!^)_([a-zA-Z])' , lambda m : m . group ( 1 ) . upper ( ) , s . capitalize ( ) ) |
def untokenize_without_newlines ( tokens ) :
"""Return source code based on tokens .""" | text = ''
last_row = 0
last_column = - 1
for t in tokens :
token_string = t [ 1 ]
( start_row , start_column ) = t [ 2 ]
( end_row , end_column ) = t [ 3 ]
if start_row > last_row :
last_column = 0
if ( ( start_column > last_column or token_string == '\n' ) and not text . endswith ( ' ' ) ) ... |
def _assemble_headers ( self , method , user_headers = None ) :
"""Takes the supplied headers and adds in any which
are defined at a client level and then returns
the result .
: param user _ headers : a ` dict ` containing headers defined at the
request level , optional .
: return : a ` dict ` instance""" | headers = copy . deepcopy ( user_headers or { } )
if method not in ( 'GET' , 'HEAD' ) :
headers . setdefault ( 'Content-Type' , 'application/json' )
return headers |
def merged ( ) : # type : ( ) - > None
"""Cleanup a remotely merged branch .""" | develop = conf . get ( 'git.devel_branch' , 'develop' )
master = conf . get ( 'git.master_branch' , 'master' )
branch = git . current_branch ( refresh = True )
common . assert_branch_type ( 'hotfix' )
# Pull master with the merged hotfix
common . git_checkout ( master )
common . git_pull ( master )
# Merge to develop
c... |
def notify ( self , data ) :
"""Notify this channel of inbound data""" | string_channels = { ChannelIdentifiers . de_registrations , ChannelIdentifiers . registrations_expired }
if data [ 'channel' ] in string_channels :
message = { 'device_id' : data [ "value" ] , 'channel' : data [ "channel" ] }
else :
message = DeviceStateChanges . _map_endpoint_data ( data )
return super ( Devic... |
def setup_path ( invoke_minversion = None ) :
"""Setup python search and add ` ` TASKS _ VENDOR _ DIR ` ` ( if available ) .""" | # print ( " INVOKE . tasks : setup _ path " )
if not os . path . isdir ( TASKS_VENDOR_DIR ) :
print ( "SKIP: TASKS_VENDOR_DIR=%s is missing" % TASKS_VENDOR_DIR )
return
elif os . path . abspath ( TASKS_VENDOR_DIR ) in sys . path : # - - SETUP ALREADY DONE :
# return
pass
use_vendor_bundles = os . environ . ... |
def wait_condition_spec ( self ) :
"""Spec for a wait _ condition block""" | from harpoon . option_spec import image_objs
formatted_string = formatted ( string_spec ( ) , formatter = MergedOptionStringFormatter )
return create_spec ( image_objs . WaitCondition , harpoon = formatted ( overridden ( "{harpoon}" ) , formatter = MergedOptionStringFormatter ) , timeout = defaulted ( integer_spec ( ) ... |
def NewRow ( self , value = "" ) :
"""Fetches a new , empty row , with headers populated .
Args :
value : Initial value to set each row entry to .
Returns :
A Row ( ) object .""" | newrow = self . row_class ( )
newrow . row = self . size + 1
newrow . table = self
headers = self . _Header ( )
for header in headers :
newrow [ header ] = value
return newrow |
def base ( number , input_base = 10 , output_base = 10 , max_depth = 10 , string = False , recurring = True ) :
"""Converts a number from any base to any another .
Args :
number ( tuple | str | int ) : The number to convert .
input _ base ( int ) : The base to convert from ( defualt 10 ) .
output _ base ( i... | # Convert number to tuple representation .
if type ( number ) == int or type ( number ) == float :
number = str ( number )
if type ( number ) == str :
number = represent_as_tuple ( number )
# Check that the number is valid for the input base .
if not check_valid ( number , input_base ) :
raise ValueError
# ... |
def invite_user ( self , user_id ) :
"""Invite a user to this room .
Returns :
boolean : Whether invitation was sent .""" | try :
self . client . api . invite_user ( self . room_id , user_id )
return True
except MatrixRequestError :
return False |
def _send_head ( self ) :
self . _transport . write ( "{} {} HTTP/1.1\r\n" . format ( self . _method , self . _url ) . encode ( ) )
for header in self . _headers :
self . _transport . write ( "{}:{}\r\n" . format ( header , self . _headers [ header ] ) . encode ( ) )
self . _transport . write ( b"\r... | |
def sync ( self , rules : list ) :
"""Synchronizes the given ruleset with the
one on the server and adds the not yet
existing rules to the server .
: type rules : collections . Iterable [ Rule ]""" | self . client = self . connect ( )
try :
server_rules = set ( self . server_rules )
rules = set ( rules )
to_remove_rules = server_rules . difference ( rules )
to_add_rules = rules . difference ( server_rules )
for to_remove_rule in to_remove_rules :
stdin , stdout , stderr = self . client .... |
def get_rdataset ( self , rdclass , rdtype , covers = dns . rdatatype . NONE , create = False ) :
"""Get an rdataset matching the specified properties in the
current node .
None is returned if an rdataset of the specified type and
class does not exist and I { create } is not True .
@ param rdclass : The cla... | try :
rds = self . find_rdataset ( rdclass , rdtype , covers , create )
except KeyError :
rds = None
return rds |
def execute ( self , ** kwargs ) :
"""Execute the API request and return data
Parameters
kwargs :
passed to requests . post ( )
Returns
response : list , str
data object from JSON decoding process if format = = ' json ' ,
else return raw string ( ie format = = ' csv ' | ' xml ' )""" | r = post ( self . url , data = self . payload , ** kwargs )
# Raise if we need to
self . raise_for_status ( r )
content = self . get_content ( r )
return content , r . headers |
def _parse_udevadm_info ( udev_info ) :
'''Parse the info returned by udevadm command .''' | devices = [ ]
dev = { }
for line in ( line . strip ( ) for line in udev_info . splitlines ( ) ) :
if line :
line = line . split ( ':' , 1 )
if len ( line ) != 2 :
continue
query , data = line
if query == 'E' :
if query not in dev :
dev [ query ... |
def calculate_shannon_entropy ( self , data ) :
"""Returns the entropy of a given string .
Borrowed from : http : / / blog . dkbza . org / 2007/05 / scanning - data - for - entropy - anomalies . html .
: param data : string . The word to analyze .
: returns : float , between 0.0 and 8.0""" | if not data : # pragma : no cover
return 0
entropy = 0
for x in self . charset :
p_x = float ( data . count ( x ) ) / len ( data )
if p_x > 0 :
entropy += - p_x * math . log ( p_x , 2 )
return entropy |
def check ( self ) :
"""Basic checks that don ' t depend on any context .
Adapted from Bicoin Code : main . cpp""" | self . _check_tx_inout_count ( )
self . _check_txs_out ( )
self . _check_txs_in ( )
# Size limits
self . _check_size_limit ( ) |
def get_form_label ( self , request = None , obj = None , model = None , form = None ) :
"""Returns a customized form label , if condition is met ,
otherwise returns the default form label .
* condition is an instance of CustomLabelCondition .""" | label = form . base_fields [ self . field ] . label
condition = self . condition_cls ( request = request , obj = obj , model = model )
if condition . check ( ) :
additional_opts = condition . get_additional_options ( request = request , obj = obj , model = model )
visit_datetime = ""
if obj :
visit_... |
def create_diagnostic_request ( self , message_id , mode , bus = None , pid = None , frequency = None , payload = None , wait_for_ack = True , wait_for_first_response = False , decoded_type = None ) :
"""Send a new diagnostic message request to the VI
Required :
message _ id - The message ID ( arbitration ID ) ... | request = self . _build_diagnostic_request ( message_id , mode , bus , pid , frequency , payload , decoded_type )
diag_response_receiver = None
if wait_for_first_response :
diag_response_receiver = self . _prepare_response_receiver ( request , DiagnosticResponseReceiver )
request [ 'action' ] = 'add'
ack_responses ... |
def attribute_circle ( self , EdgeAttribute = None , network = None , NodeAttribute = None , nodeList = None , singlePartition = None , spacing = None , verbose = False ) :
"""Execute the Attribute Circle Layout on a network .
: param EdgeAttribute ( string , optional ) : The name of the edge column
containing ... | network = check_network ( self , network , verbose = verbose )
PARAMS = set_param ( [ "EdgeAttribute" , "network" , "NodeAttribute" , "nodeList" , "singlePartition" , "spacing" ] , [ EdgeAttribute , network , NodeAttribute , nodeList , singlePartition , spacing ] )
response = api ( url = self . __url + "/attribute-circ... |
def zhang_huang_solar_split ( altitudes , doys , cloud_cover , relative_humidity , dry_bulb_present , dry_bulb_t3_hrs , wind_speed , atm_pressure , use_disc = False ) :
"""Calculate direct and diffuse solar irradiance using the Zhang - Huang model .
By default , this function uses the DIRINT method ( aka . Perez ... | # Calculate global horizontal irradiance using the original zhang - huang model
glob_ir = [ ]
for i in range ( len ( altitudes ) ) :
ghi = zhang_huang_solar ( altitudes [ i ] , cloud_cover [ i ] , relative_humidity [ i ] , dry_bulb_present [ i ] , dry_bulb_t3_hrs [ i ] , wind_speed [ i ] )
glob_ir . append ( gh... |
def policy_map_clss_span_session ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
policy_map = ET . SubElement ( config , "policy-map" , xmlns = "urn:brocade.com:mgmt:brocade-policer" )
po_name_key = ET . SubElement ( policy_map , "po-name" )
po_name_key . text = kwargs . pop ( 'po_name' )
clss = ET . SubElement ( policy_map , "class" )
cl_name_key = ET . SubElemen... |
def sort ( self , ascending = True ) :
"""Sort all values in this SArray .
Sort only works for sarray of type str , int and float , otherwise TypeError
will be raised . Creates a new , sorted SArray .
Parameters
ascending : boolean , optional
If true , the sarray values are sorted in ascending order , oth... | from . sframe import SFrame as _SFrame
if self . dtype not in ( int , float , str , datetime . datetime ) :
raise TypeError ( "Only sarray with type (int, float, str, datetime.datetime) can be sorted" )
sf = _SFrame ( )
sf [ 'a' ] = self
return sf . sort ( 'a' , ascending ) [ 'a' ] |
def items ( self ) :
"""ITERATE THROUGH ALL coord , value PAIRS""" | for c in self . _all_combos ( ) :
_ , value = _getitem ( self . cube , c )
yield c , value |
def normal_range ( mean , sd , treshold = 1.28 ) :
"""Returns a bottom and a top limit on a normal distribution portion based on a treshold .
Parameters
treshold : float
maximum deviation ( in terms of standart deviation ) . Rule of thumb of a gaussian distribution : 2.58 = keeping 99 % , 2.33 = keeping 98 % ... | bottom = mean - sd * treshold
top = mean + sd * treshold
return ( bottom , top ) |
async def clear ( self , namespace = None , _conn = None ) :
"""Clears the cache in the cache namespace . If an alternative namespace is given , it will
clear those ones instead .
: param namespace : str alternative namespace to use
: param timeout : int or float in seconds specifying maximum timeout
for th... | start = time . monotonic ( )
ret = await self . _clear ( namespace , _conn = _conn )
logger . debug ( "CLEAR %s %d (%.4f)s" , namespace , ret , time . monotonic ( ) - start )
return ret |
def layers_path ( self ) :
"""Directory with all the layers ( docker save ) .""" | if self . _layers_path is None :
self . _layers_path = os . path . join ( self . tmpdir , "layers" )
return self . _layers_path |
def simplify_multigraph ( multigraph , time = False ) :
"""Simplifies a graph by condensing multiple edges between the same node pair
into a single edge , with a weight attribute equal to the number of edges .
Parameters
graph : networkx . MultiGraph
E . g . a coauthorship graph .
time : bool
If True , ... | graph = nx . Graph ( )
for node in multigraph . nodes ( data = True ) :
u = node [ 0 ]
node_attribs = node [ 1 ]
graph . add_node ( u , node_attribs )
for v in multigraph [ u ] :
edges = multigraph . get_edge_data ( u , v )
# Dict .
edge_attribs = { 'weight' : len ( edges ) }
... |
def setInstrument ( self , instrument , override_analyses = False ) :
"""Sets the specified instrument to the Analysis from the
Worksheet . Only sets the instrument if the Analysis
allows it , according to its Analysis Service and Method .
If an analysis has already assigned an instrument , it won ' t
be ov... | analyses = [ an for an in self . getAnalyses ( ) if ( not an . getInstrument ( ) or override_analyses ) and an . isInstrumentAllowed ( instrument ) ]
total = 0
for an in analyses : # An analysis can be done using differents Methods .
# Un method can be supported by more than one Instrument ,
# but not all instruments s... |
def word_for_char ( string_matrix : List [ List [ str ] ] , character : str ) -> List [ str ] :
"""Diagnostic function , collect the words where a character appears
: param string _ matrix : a data matrix : a list wrapping a list of strings , with each sublist being a sentence .
: param character :
: return :... | return [ word for sentence in string_matrix for word in sentence if character in word ] |
def set_xaxis ( self , param , unit = None , label = None ) :
"""Sets the value of use on the x axis
: param param : value to use on the xaxis , should be a variable or function of the objects in objectList . ie ' R '
for the radius variable and ' calcDensity ( ) ' for the calcDensity function
: param unit : ... | if unit is None :
unit = self . _getParLabelAndUnit ( param ) [ 1 ]
# use the default unit defined in this class
self . _xaxis_unit = unit
self . _xaxis = self . _set_axis ( param , unit )
if label is None :
self . xlabel = self . _gen_label ( param , unit )
else :
self . xlabel = label |
def dens_pacl_solution ( ConcAluminum , temp ) :
"""Return the density of the PACl solution .
From Stock Tank Mixing report Fall 2013:
https : / / confluence . cornell . edu / download / attachments / 137953883/20131213 _ Research _ Report . pdf""" | return ( ( 0.492 * ConcAluminum * PACl . MolecWeight / ( PACl . AluminumMPM * MOLEC_WEIGHT_ALUMINUM ) ) + pc . density_water ( temp ) . magnitude ) |
def parse ( self , text ) :
"""Parse a string of SVG < path > data .""" | gen = self . lexer . lex ( text )
next_val_fn = partial ( next , * ( gen , ) )
token = next_val_fn ( )
return self . rule_svg_path ( next_val_fn , token ) |
def from_array ( array ) :
"""Deserialize a new Sticker from a given dictionary .
: return : new Sticker instance .
: rtype : Sticker""" | if array is None or not array :
return None
# end if
assert_type_or_raise ( array , dict , parameter_name = "array" )
from pytgbot . api_types . receivable . media import PhotoSize
from pytgbot . api_types . receivable . stickers import MaskPosition
data = { }
data [ 'file_id' ] = u ( array . get ( 'file_id' ) )
da... |
def _save_results ( self , output_dir , label , results , ngrams , type_label ) :
"""Saves ` results ` filtered by ` label ` and ` ngram ` to ` output _ dir ` .
: param output _ dir : directory to save results to
: type output _ dir : ` str `
: param label : catalogue label of results , used in saved filename... | path = os . path . join ( output_dir , '{}-{}.csv' . format ( label , type_label ) )
results [ results [ constants . NGRAM_FIELDNAME ] . isin ( ngrams ) ] . to_csv ( path , encoding = 'utf-8' , float_format = '%d' , index = False ) |
def HSV_to_RGB ( cobj , target_rgb , * args , ** kwargs ) :
"""HSV to RGB conversion .
H values are in degrees and are 0 to 360.
S values are a percentage , 0.0 to 1.0.
V values are a percentage , 0.0 to 1.0.""" | H = cobj . hsv_h
S = cobj . hsv_s
V = cobj . hsv_v
h_floored = int ( math . floor ( H ) )
h_sub_i = int ( h_floored / 60 ) % 6
var_f = ( H / 60.0 ) - ( h_floored // 60 )
var_p = V * ( 1.0 - S )
var_q = V * ( 1.0 - var_f * S )
var_t = V * ( 1.0 - ( 1.0 - var_f ) * S )
if h_sub_i == 0 :
rgb_r = V
rgb_g = var_t
... |
def take_screen_shot ( self , screen_id , address , width , height , bitmap_format ) :
"""Takes a screen shot of the requested size and format and copies it to the
buffer allocated by the caller and pointed to by @ a address .
The buffer size must be enough for a 32 bits per pixel bitmap ,
i . e . width * hei... | if not isinstance ( screen_id , baseinteger ) :
raise TypeError ( "screen_id can only be an instance of type baseinteger" )
if not isinstance ( address , basestring ) :
raise TypeError ( "address can only be an instance of type basestring" )
if not isinstance ( width , baseinteger ) :
raise TypeError ( "wid... |
def maybe_zero_out_padding ( inputs , kernel_size , nonpadding_mask ) :
"""If necessary , zero out inputs to a conv for padding positions .
Args :
inputs : a Tensor with shape [ batch , length , . . . ]
kernel _ size : an integer or pair of integers
nonpadding _ mask : a Tensor with shape [ batch , length ]... | if ( kernel_size != 1 and kernel_size != ( 1 , 1 ) and nonpadding_mask is not None ) :
while nonpadding_mask . get_shape ( ) . ndims < inputs . get_shape ( ) . ndims :
nonpadding_mask = tf . expand_dims ( nonpadding_mask , - 1 )
return inputs * nonpadding_mask
return inputs |
def handle_current_state ( self ) :
'''Check to see if the current hydrated state and the saved state are different .
If they are , then persist the current state in the database by saving the model instance .''' | if getattr ( self , '_current_state_hydrated_changed' , False ) and self . save_on_change :
new_base_state = json . dumps ( getattr ( self , '_current_state_hydrated' , { } ) )
if new_base_state != self . base_state :
self . base_state = new_base_state
self . save ( ) |
def divisor_count_type ( num ) :
"""This Python function determines if the count of divisors of a given number is odd or even .
Examples :
> > > divisor _ count _ type ( 10)
' Even '
> > > divisor _ count _ type ( 100)
' Odd '
> > > divisor _ count _ type ( 125)
' Even '
: param num : The input numb... | import math
divisor_count = 0
for i in range ( 1 , int ( math . sqrt ( num ) ) + 2 ) :
if num % i == 0 :
if num // i == i :
divisor_count += 1
else :
divisor_count += 2
return 'Even' if divisor_count % 2 == 0 else 'Odd' |
def num_pending ( self , work_spec_name ) :
'''Get the number of pending work units for some work spec .
These are work units that some worker is currently working on
( hopefully ; it could include work units assigned to workers that
died and that have not yet expired ) .''' | return self . registry . len ( WORK_UNITS_ + work_spec_name , priority_min = time . time ( ) ) |
def build_assets ( args ) :
"""Build the longclaw assets""" | # Get the path to the JS directory
asset_path = path . join ( path . dirname ( longclaw . __file__ ) , 'client' )
try : # Move into client dir
curdir = os . path . abspath ( os . curdir )
os . chdir ( asset_path )
print ( 'Compiling assets....' )
subprocess . check_call ( [ 'npm' , 'install' ] )
sub... |
def is_serializable_type ( type_ ) :
"""Return ` True ` if the given type ' s instances conform to the Serializable protocol .
: rtype : bool""" | if not inspect . isclass ( type_ ) :
return Serializable . is_serializable ( type_ )
return issubclass ( type_ , Serializable ) or hasattr ( type_ , '_asdict' ) |
def put ( self , key , value ) :
'''Stores the object ` value ` named by ` key ` self .
Writes to both ` ` cache _ datastore ` ` and ` ` child _ datastore ` ` .''' | self . cache_datastore . put ( key , value )
self . child_datastore . put ( key , value ) |
def add_binary ( self , data , address = 0 , overwrite = False ) :
"""Add given data at given address . Set ` overwrite ` to ` ` True ` ` to
allow already added data to be overwritten .""" | address *= self . word_size_bytes
self . _segments . add ( _Segment ( address , address + len ( data ) , bytearray ( data ) , self . word_size_bytes ) , overwrite ) |
def prompt_y_or_n ( self , prompt ) :
"""Wrapper around prompt _ input for simple yes / no queries .""" | ch = self . prompt_input ( prompt , key = True )
if ch in ( ord ( 'Y' ) , ord ( 'y' ) ) :
return True
elif ch in ( ord ( 'N' ) , ord ( 'n' ) , None ) :
return False
else :
self . flash ( )
return False |
def load_section ( self , section ) :
"""Loads the contents of a # Section . The ` section . identifier ` is the name
of the object that we need to load .
# Arguments
section ( Section ) : The section to load . Fill the ` section . title ` and
` section . content ` values . Optionally , ` section . loader _... | assert section . identifier is not None
obj , scope = import_object_with_scope ( section . identifier )
if '.' in section . identifier :
default_title = section . identifier . rsplit ( '.' , 1 ) [ 1 ]
else :
default_title = section . identifier
section . title = getattr ( obj , '__name__' , default_title )
sect... |
def is_sequential ( self ) :
"""Check if residues that sequence site is composed of are in sequential order .
: return : If sequence site is in valid sequential order ( True ) or not ( False ) .
: rtype : : py : obj : ` True ` or : py : obj : ` False `""" | seq_ids = tuple ( int ( residue [ "Seq_ID" ] ) for residue in self )
return seq_ids == tuple ( range ( int ( seq_ids [ 0 ] ) , int ( seq_ids [ - 1 ] ) + 1 ) ) |
def _normalize_assets ( self , assets ) :
"""Perform asset normalization . For some reason , assets that are sometimes
present in lectures , have " @ 1 " at the end of their id . Such " uncut "
asset id when fed to OPENCOURSE _ ASSETS _ URL results in error that says :
" Routing error : ' get - all ' not impl... | new_assets = [ ]
for asset in assets : # For example : giAxucdaEeWJTQ5WTi8YJQ @ 1
if len ( asset ) == 24 : # Turn it into : giAxucdaEeWJTQ5WTi8YJQ
asset = asset [ : - 2 ]
new_assets . append ( asset )
return new_assets |
def timezone ( zone ) :
r'''Return a datetime . tzinfo implementation for the given timezone
> > > from datetime import datetime , timedelta
> > > utc = timezone ( ' UTC ' )
> > > eastern = timezone ( ' US / Eastern ' )
> > > eastern . zone
' US / Eastern '
> > > timezone ( u ' US / Eastern ' ) is easte... | if zone . upper ( ) == 'UTC' :
return utc
try :
zone = zone . encode ( 'US-ASCII' )
except UnicodeEncodeError : # All valid timezones are ASCII
raise UnknownTimeZoneError ( zone )
zone = _unmunge_zone ( zone )
if zone not in _tzinfo_cache :
if resource_exists ( zone ) :
_tzinfo_cache [ zone ] = ... |
def watch ( self , path , func = None , delay = 0 , ignore = None ) :
"""Add a task to watcher .
: param path : a filepath or directory path or glob pattern
: param func : the function to be executed when file changed
: param delay : Delay sending the reload message . Use ' forever ' to
not send it . This i... | self . _tasks [ path ] = { 'func' : func , 'delay' : delay , 'ignore' : ignore , } |
def buffer_iter ( self , block_size = 1024 ) :
"""Iterate through chunks of the vertices , and indices buffers seamlessly .
. . note : :
To see a usage example , look at the : class : ` ShapeBuffer ` description .""" | streams = ( self . vert_data , self . idx_data , )
# Chain streams seamlessly
for stream in streams :
stream . seek ( 0 )
while True :
chunk = stream . read ( block_size )
if chunk :
yield chunk
else :
break |
def bss_eval_sources ( reference_sources , estimated_sources , compute_permutation = True ) :
"""BSS Eval v3 bss _ eval _ sources
Wrapper to ` ` bss _ eval ` ` with the right parameters .
The call to this function is not recommended . See the description for the
` ` bsseval _ sources ` ` parameter of ` ` bss ... | ( sdr , isr , sir , sar , perm ) = bss_eval ( reference_sources , estimated_sources , window = np . inf , hop = np . inf , compute_permutation = compute_permutation , filters_len = 512 , framewise_filters = True , bsseval_sources_version = True )
return ( sdr , sir , sar , perm ) |
def sumnum ( * args ) :
'''Computes the sum of the provided numbers''' | print ( '%s = %f' % ( ' + ' . join ( args ) , sum ( float ( arg ) for arg in args ) ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.