signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def upgrade ( ) :
"""Upgrade database .""" | op . create_table ( 'oauth2server_client' , sa . Column ( 'name' , sa . String ( length = 40 ) , nullable = True ) , sa . Column ( 'description' , sa . Text ( ) , nullable = True ) , sa . Column ( 'website' , sqlalchemy_utils . types . url . URLType ( ) , nullable = True ) , sa . Column ( 'user_id' , sa . Integer ( ) ,... |
def refine_cell ( self , tilde_obj ) :
'''NB only used for perovskite _ tilting app''' | try :
lattice , positions , numbers = spg . refine_cell ( tilde_obj [ 'structures' ] [ - 1 ] , symprec = self . accuracy , angle_tolerance = self . angle_tolerance )
except Exception as ex :
self . error = 'Symmetry finder error: %s' % ex
else :
self . refinedcell = Atoms ( numbers = numbers , cell = lattic... |
def set_file_limits ( n ) :
'''Set the limit on number of file descriptors
that this process can open .''' | try :
resource . setrlimit ( resource . RLIMIT_NOFILE , ( n , n ) )
return True
except ValueError :
return False |
def resample ( self , data , input_rate ) :
"""Microphone may not support our native processing sampling rate , so
resample from input _ rate to RATE _ PROCESS here for webrtcvad and
deepspeech
Args :
data ( binary ) : Input audio stream
input _ rate ( int ) : Input audio rate to resample from""" | data16 = np . fromstring ( string = data , dtype = np . int16 )
resample_size = int ( len ( data16 ) / self . input_rate * self . RATE_PROCESS )
resample = signal . resample ( data16 , resample_size )
resample16 = np . array ( resample , dtype = np . int16 )
return resample16 . tostring ( ) |
def os_path_transform ( self , s , sep = os . path . sep ) :
"""transforms any os path into unix style""" | if sep == '/' :
return s
else :
return s . replace ( sep , '/' ) |
def settings ( request ) :
"""inject few waliki ' s settings to the context to be used in templates""" | from waliki . settings import WALIKI_USE_MATHJAX
# NOQA
return { k : v for ( k , v ) in locals ( ) . items ( ) if k . startswith ( 'WALIKI' ) } |
def get_targets ( self , name = None ) :
"""Retrieve all / one target objects
: param name : name of the target to search for , None for everything
: return : A list of target objects""" | targets = [ ]
for section in self . get_sections ( ) :
if section . endswith ( u'Target' ) :
targets += [ value for value in self . _sections [ section ] ]
if name is None :
return targets
if not isinstance ( name , list ) :
name = [ name ]
return [ target for target in targets if target . name in n... |
def hasSystemPermission ( self , login , user , perm ) :
"""Parameters :
- login
- user
- perm""" | self . send_hasSystemPermission ( login , user , perm )
return self . recv_hasSystemPermission ( ) |
def connect ( self , action = None , method = None , ** kwargs ) :
"""Create a < Connect > element
: param action : Action URL
: param method : Action URL method
: param kwargs : additional attributes
: returns : < Connect > element""" | return self . nest ( Connect ( action = action , method = method , ** kwargs ) ) |
def prepare_framework ( estimator , s3_operations ) :
"""Prepare S3 operations ( specify where to upload ` source _ dir ` ) and environment variables
related to framework .
Args :
estimator ( sagemaker . estimator . Estimator ) : The framework estimator to get information from and update .
s3 _ operations (... | if estimator . code_location is not None :
bucket , key = fw_utils . parse_s3_url ( estimator . code_location )
key = os . path . join ( key , estimator . _current_job_name , 'source' , 'sourcedir.tar.gz' )
else :
bucket = estimator . sagemaker_session . _default_bucket
key = os . path . join ( estimato... |
def create_widget ( self ) :
"""Create the underlying widget .""" | d = self . declaration
self . widget = LinearLayout ( self . get_context ( ) , None , d . style ) |
def parse_error ( self , response ) :
"Parse authentication errors ." | # Check invalid credentials .
if self . check_error ( response , 'failure' , 'INVALID_DATA' ) :
raise self . CredentialsError ( self . response_message ( response , 'ERROR' ) ) |
def get_location ( opts = None , provider = None ) :
'''Return the region to use , in this order :
opts [ ' location ' ]
provider [ ' location ' ]
get _ region _ from _ metadata ( )
DEFAULT _ LOCATION''' | if opts is None :
opts = { }
ret = opts . get ( 'location' )
if ret is None and provider is not None :
ret = provider . get ( 'location' )
if ret is None :
ret = get_region_from_metadata ( )
if ret is None :
ret = DEFAULT_LOCATION
return ret |
def _replace_locals ( tok ) :
"""Replace local variables with a syntactically valid name .
Parameters
tok : tuple of int , str
ints correspond to the all caps constants in the tokenize module
Returns
t : tuple of int , str
Either the input or token or the replacement values
Notes
This is somewhat of... | toknum , tokval = tok
if toknum == tokenize . OP and tokval == '@' :
return tokenize . OP , _LOCAL_TAG
return toknum , tokval |
def is_field_method ( node ) :
"""Checks if a call to a field instance method is valid . A call is
valid if the call is a method of the underlying type . So , in a StringField
the methods from str are valid , in a ListField the methods from list are
valid and so on . . .""" | name = node . attrname
parent = node . last_child ( )
inferred = safe_infer ( parent )
if not inferred :
return False
for cls_name , inst in FIELD_TYPES . items ( ) :
if node_is_instance ( inferred , cls_name ) and hasattr ( inst , name ) :
return True
return False |
def describe_date_1d ( series ) :
"""Compute summary statistics of a date ( ` TYPE _ DATE ` ) variable ( a Series ) .
Also create histograms ( mini an full ) of its distribution .
Parameters
series : Series
The variable to describe .
Returns
Series
The description of the variable as a Series with inde... | stats = dict ( )
stats [ 'type' ] = base . TYPE_DATE
stats [ 'min' ] = series . min ( )
stats [ 'max' ] = series . max ( )
stats [ 'range' ] = stats [ 'max' ] - stats [ 'min' ]
# Histograms
stats [ 'histogram' ] = histogram ( series )
stats [ 'mini_histogram' ] = mini_histogram ( series )
return pd . Series ( stats , n... |
def parse_md_to_rst ( file ) :
"""Read Markdown file and convert to ReStructured Text .""" | try :
from m2r import parse_from_file
return parse_from_file ( file ) . replace ( "artwork/" , "http://198.27.119.65/" )
except ImportError : # m2r may not be installed in user environment
return read ( file ) |
def _sanity_check_output_source_follower_blocks ( ir_blocks ) :
"""Ensure there are no Traverse / Backtrack / Recurse blocks after an OutputSource block .""" | seen_output_source = False
for block in ir_blocks :
if isinstance ( block , OutputSource ) :
seen_output_source = True
elif seen_output_source :
if isinstance ( block , ( Backtrack , Traverse , Recurse ) ) :
raise AssertionError ( u'Found Backtrack / Traverse / Recurse ' u'after Outp... |
def _init_entry_points ( self , entry_points ) :
"""Default initialization loop .""" | logger . debug ( "registering %d entry points for registry '%s'" , len ( entry_points ) , self . registry_name , )
for entry_point in entry_points :
try :
logger . debug ( "registering entry point '%s' from '%s'" , entry_point , entry_point . dist , )
self . _init_entry_point ( entry_point )
exc... |
def set_input_by_xpath ( self , xpath , value ) :
"""Set the value of form element by xpath
: param xpath : xpath path
: param value : value which should be set to element""" | elem = self . select ( xpath ) . node ( )
if self . _lxml_form is None : # Explicitly set the default form
# which contains found element
parent = elem
while True :
parent = parent . getparent ( )
# pylint : disable = no - member
if parent . tag == 'form' :
self . _lxml_form ... |
def calculate_sum_of_differences ( array : list , size : int ) -> int :
"""This function computes the sum of the absolute differences between all pairs in the given array .
> > > calculate _ sum _ of _ differences ( [ 1 , 8 , 9 , 15 , 16 ] , 5)
74
> > > calculate _ sum _ of _ differences ( [ 1 , 2 , 3 , 4 ] ,... | total_sum = 0
for index in range ( ( size - 1 ) , - 1 , - 1 ) :
total_sum += ( ( index * array [ index ] ) - ( ( size - 1 - index ) * array [ index ] ) )
return total_sum |
async def trigger ( self , action , args ) :
"""Event trigger
: param action : event name
: param args : event arguments
: return :""" | if 'update' not in action and 'error' not in action and action . startswith ( 'pre_process' ) :
locale = await self . get_user_locale ( action , args )
self . ctx_locale . set ( locale )
return True |
def poke ( url , accesskey = None , secretkey = None , __method__ = 'GET' , ** req_args ) :
"""Poke the Rancher API . Returns a Rod object instance . Central starting
point for the cattleprod package .
: param url : The full Rancher URL to the API endpoint .
: param accesskey : The rancher access key , option... | if accesskey and secretkey :
req_args [ 'auth' ] = ( accesskey , secretkey )
tmp = requests . request ( __method__ . lower ( ) , url , ** req_args )
tmp . raise_for_status ( )
if tmp . headers . get ( 'Content-Type' ) . find ( "json" ) != - 1 :
rv = _convert_to_rod ( tmp . json ( ) , ** req_args )
else :
rv... |
def list_versions ( self , bucket_name , prefix = '' , delimiter = '' , max_results = 1000 , starting_key = '' , starting_version = '' ) :
'''a method for retrieving a list of the versions of records in a bucket
: param bucket _ name : string with name of bucket
: param prefix : [ optional ] string with value l... | title = '%s.list_versions' % self . __class__ . __name__
from datetime import datetime
from dateutil . tz import tzutc
# validate inputs
input_fields = { 'bucket_name' : bucket_name , 'prefix' : prefix , 'delimiter' : delimiter , 'max_results' : max_results , 'starting_key' : starting_key , 'starting_version' : startin... |
def delete ( self , volume_id , force = False ) :
"""delete an export""" | return self . http_delete ( '/volumes/%s/export' % volume_id , params = { 'force' : force } ) |
def bvlpdu_contents ( self , use_dict = None , as_class = dict ) :
"""Return the contents of an object as a dict .""" | return key_value_contents ( use_dict = use_dict , as_class = as_class , key_values = ( ( 'function' , 'RegisterForeignDevice' ) , ( 'ttl' , self . bvlciTimeToLive ) , ) ) |
def _get_json_response ( self , resp ) :
'''Parse a JSON response''' | if resp is not None and resp . text is not None :
try :
text = resp . text . strip ( '\n' )
if len ( text ) > 0 :
return json . loads ( text )
except ValueError as e :
if self . debug :
print ( "Could not decode JSON response: \"%s\"" % resp . text )
raise... |
def visit_wavedrom ( self , node ) :
"""Visit the wavedrom node""" | format = determine_format ( self . builder . supported_image_types )
if format is None :
raise SphinxError ( __ ( "Cannot determine a suitable output format" ) )
# Create random filename
bname = "wavedrom-{}" . format ( uuid4 ( ) )
outpath = path . join ( self . builder . outdir , self . builder . imagedir )
# Rend... |
def update ( self , status = values . unset , announce_url = values . unset , announce_method = values . unset ) :
"""Update the ConferenceInstance
: param ConferenceInstance . UpdateStatus status : The new status of the resource
: param unicode announce _ url : The URL we should call to announce something into... | return self . _proxy . update ( status = status , announce_url = announce_url , announce_method = announce_method , ) |
def cmd ( send , msg , args ) :
"""Gets a stock quote .
Syntax : { command } [ symbol ]
Powered by markit on demand ( http : / / dev . markitondemand . com )""" | parser = arguments . ArgParser ( args [ 'config' ] )
parser . add_argument ( 'stock' , nargs = '?' , default = random_stock ( ) )
try :
cmdargs = parser . parse_args ( msg )
except arguments . ArgumentException as e :
send ( str ( e ) )
return
send ( gen_stock ( cmdargs . stock ) ) |
def statistics ( self , axes = ( ) , minmaxvalues = ( ) , exclude = False , robust = True ) :
"""Calculate statistics for the image .
Statistics are returned in a dict for the given axes .
E . g . if axes [ 0,1 ] is given in a 3 - dim image , the statistics are
calculated for each plane along the 3rd axis . B... | return self . _statistics ( self . _adaptAxes ( axes ) , "" , minmaxvalues , exclude , robust ) |
import math
def nth_term_geometric_series ( first_term , series_length , common_ratio ) :
"""This function calculates the nth term of a geometric series .
Example :
nth _ term _ geometric _ series ( 1 , 5 , 2 ) = > 16
nth _ term _ geometric _ series ( 1 , 5 , 4 ) = > 256
nth _ term _ geometric _ series ( 2 ... | nth_term = first_term * math . pow ( common_ratio , ( series_length - 1 ) )
return nth_term |
def email_send ( text_template , html_template , data , subject , emails , headers = None ) :
"""Send an HTML / Plaintext email with the following fields .
text _ template : URL to a Django template for the text email ' s contents
html _ template : URL to a Django tempalte for the HTML email ' s contents
data... | text = get_template ( text_template )
html = get_template ( html_template )
text_content = text . render ( data )
html_content = html . render ( data )
subject = settings . EMAIL_SUBJECT_PREFIX + subject
headers = { } if headers is None else headers
msg = EmailMultiAlternatives ( subject , text_content , settings . EMA... |
def SetSelected ( self , node , point = None , propagate = True ) :
"""Set the given node selected in the square - map""" | if node == self . selectedNode :
return
self . selectedNode = node
self . UpdateDrawing ( )
if node :
wx . PostEvent ( self , SquareSelectionEvent ( node = node , point = point , map = self ) ) |
def get_instance_of ( self , model_cls ) :
"""Search the data to find a instance
of a model specified in the template""" | for obj in self . data . values ( ) :
if isinstance ( obj , model_cls ) :
return obj
LOGGER . error ( 'Context Not Found' )
raise Exception ( 'Context Not Found' ) |
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_interface_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_lldp_neighbor_detail = ET . Element ( "get_lldp_neighbor_detail" )
config = get_lldp_neighbor_detail
output = ET . SubElement ( get_lldp_neighbor_detail , "output" )
lldp_neighbor_detail = ET . SubElement ( output , "lldp-neighbor-detail" )
local_interface_name_key = ET . SubEleme... |
def send ( self , out , addr = _MDNS_ADDR , port = _MDNS_PORT ) :
"""Sends an outgoing packet .""" | # This is a quick test to see if we can parse the packets we generate
# temp = DNSIncoming ( out . packet ( ) )
for i in self . intf . values ( ) :
try :
return i . sendto ( out . packet ( ) , 0 , ( addr , port ) )
except :
traceback . print_exc ( )
# Ignore this , it may be a temporary ... |
def cmd_terrain_check ( self , args ) :
'''check a piece of terrain data''' | if len ( args ) >= 2 :
latlon = ( float ( args [ 0 ] ) , float ( args [ 1 ] ) )
else :
try :
latlon = self . module ( 'map' ) . click_position
except Exception :
print ( "No map available" )
return
if latlon is None :
print ( "No map click position available" )
re... |
def now ( self ) :
'''Display Taiwan Time now
顯示台灣此刻時間''' | localtime = datetime . datetime . now ( )
return localtime + datetime . timedelta ( hours = time . timezone / 60 / 60 + self . TimeZone ) |
def get_resource ( self , resource_key , ** variables ) :
"""Get a resource .
Attempts to get and return a cached version of the resource if
available , otherwise a new resource object is created and returned .
Args :
resource _ key ( ` str ` ) : Name of the type of ` Resources ` to find
variables : data ... | handle = self . make_resource_handle ( resource_key , ** variables )
return self . get_resource_from_handle ( handle , verify_repo = False ) |
def handle_receive_lockedtransfer ( channel_state : NettingChannelState , mediated_transfer : LockedTransferSignedState , ) -> EventsOrError :
"""Register the latest known transfer .
The receiver needs to use this method to update the container with a
_ valid _ transfer , otherwise the locksroot will not contai... | events : List [ Event ]
is_valid , msg , merkletree = is_valid_lockedtransfer ( mediated_transfer , channel_state , channel_state . partner_state , channel_state . our_state , )
if is_valid :
assert merkletree , 'is_valid_lock_expired should return merkletree if valid'
channel_state . partner_state . balance_pr... |
def post ( self , request , * args , ** kwargs ) :
"""Do the login and password protection .""" | self . object = self . get_object ( )
self . login ( )
if self . object . password :
entry_password = self . request . POST . get ( 'entry_password' )
if entry_password :
if entry_password == self . object . password :
self . request . session [ self . session_key % self . object . pk ] = se... |
def process_streamer ( self , streamer , callback = None ) :
"""Start streaming a streamer .
Args :
streamer ( DataStreamer ) : The streamer itself .
callback ( callable ) : An optional callable that will be called as :
callable ( index , success , highest _ id _ received _ from _ other _ side )""" | index = streamer . index
if index in self . _in_progress_streamers :
raise InternalError ( "You cannot add a streamer again until it has finished streaming." )
queue_item = QueuedStreamer ( streamer , callback )
self . _in_progress_streamers . add ( index )
self . _logger . debug ( "Streamer %d: queued to send %d r... |
def schema_from_context ( context ) :
"""Determine which schema to use .""" | item_class = context . get ( 'class' )
return ( serializer_mapping [ item_class ] if item_class else BaseSchema , context . get ( 'many' , False ) ) |
def echo_error ( root_resource , message ) :
"""Generate an error , but we get to set the error message .""" | params = dict ( message = message )
return root_resource . get ( ECHO_ERROR_PATH , params ) |
def start_log_child ( self ) :
'''Start the logging child process .''' | self . stop_log_child ( )
gconfig = yakonfig . get_global_config ( )
read_end , write_end = os . pipe ( )
pid = os . fork ( )
if pid == 0 : # We are the child
self . clear_signal_handlers ( )
os . close ( write_end )
yakonfig . clear_global_config ( )
self . log_spewer ( gconfig , read_end )
sys . e... |
def parse_partial ( self , data ) :
"""Incrementally decodes JSON data sets into Python objects .
Raises
~ ipfsapi . exceptions . DecodingError
Returns
generator""" | try : # Python 3 requires all JSON data to be a text string
lines = self . _decoder1 . decode ( data , False ) . split ( "\n" )
# Add first input line to last buffer line , if applicable , to
# handle cases where the JSON string has been chopped in half
# at the network level due to streaming
if len... |
def get_users ( self , user_ids : Iterable [ Union [ int , str ] ] ) -> Union [ "pyrogram.User" , List [ "pyrogram.User" ] ] :
"""Use this method to get information about a user .
You can retrieve up to 200 users at once .
Args :
user _ ids ( ` ` iterable ` ` ) :
A list of User identifiers ( id or username ... | is_iterable = not isinstance ( user_ids , ( int , str ) )
user_ids = list ( user_ids ) if is_iterable else [ user_ids ]
user_ids = [ self . resolve_peer ( i ) for i in user_ids ]
r = self . send ( functions . users . GetUsers ( id = user_ids ) )
users = [ ]
for i in r :
users . append ( pyrogram . User . _parse ( s... |
def iscm_md_update_dict ( self , keypath , data ) :
"""Update a metadata dictionary entry""" | current = self . metadata
for k in string . split ( keypath , "." ) :
if not current . has_key ( k ) :
current [ k ] = { }
current = current [ k ]
current . update ( data ) |
def configurations ( self ) :
"""Configurations from uwsgiconf module .""" | if self . _confs is not None :
return self . _confs
with output_capturing ( ) :
module = self . load ( self . fpath )
confs = getattr ( module , CONFIGS_MODULE_ATTR )
confs = listify ( confs )
self . _confs = confs
return confs |
def genkeyhex ( ) :
'''Generate new random Bitcoin private key , using os . urandom and
double - sha256 . Hex format .''' | while True :
key = hash256 ( hexlify ( os . urandom ( 40 ) + str ( datetime . datetime . now ( ) ) . encode ( "utf-8" ) ) )
# 40 bytes used instead of 32 , as a buffer for any slight
# lack of entropy in urandom
# Double - sha256 used instead of single hash , for entropy
# reasons as well .
# I ... |
def get_state ( self ) :
"Return the inner state minus the layer groups ." | return { 'opt_state' : self . opt . state_dict ( ) , 'lr' : self . _lr , 'wd' : self . _wd , 'beta' : self . _beta , 'mom' : self . _mom , 'opt_func' : self . opt_func , 'true_wd' : self . true_wd , 'bn_wd' : self . bn_wd } |
def find_stable_entry ( self , pH , V ) :
"""Finds stable entry at a pH , V condition
Args :
pH ( float ) : pH to find stable entry
V ( float ) : V to find stable entry
Returns :""" | energies_at_conditions = [ e . normalized_energy_at_conditions ( pH , V ) for e in self . stable_entries ]
return self . stable_entries [ np . argmin ( energies_at_conditions ) ] |
async def smap ( source , func , * more_sources ) :
"""Apply a given function to the elements of one or several
asynchronous sequences .
Each element is used as a positional argument , using the same order as
their respective sources . The generation continues until the shortest
sequence is exhausted . The ... | if more_sources :
source = zip ( source , * more_sources )
async with streamcontext ( source ) as streamer :
async for item in streamer :
yield func ( * item ) if more_sources else func ( item ) |
def do_POST ( self ) :
'''The POST command .''' | try :
ct = self . headers [ 'content-type' ]
if ct . startswith ( 'multipart/' ) :
cid = resolvers . MIMEResolver ( ct , self . rfile )
xml = cid . GetSOAPPart ( )
ps = ParsedSoap ( xml , resolver = cid . Resolve )
else :
length = int ( self . headers [ 'content-length' ] )
... |
def files ( self ) :
"""Get a generator that yields all files in the directory .""" | filelist_p = new_gp_object ( "CameraList" )
lib . gp_camera_folder_list_files ( self . _cam . _cam , self . path . encode ( ) , filelist_p , self . _cam . _ctx )
for idx in range ( lib . gp_list_count ( filelist_p ) ) :
fname = get_string ( lib . gp_list_get_name , filelist_p , idx )
yield File ( name = fname ,... |
def flash_spi_attach ( self , hspi_arg ) :
"""Send SPI attach command to enable the SPI flash pins
ESP8266 ROM does this when you send flash _ begin , ESP32 ROM
has it as a SPI command .""" | # last 3 bytes in ESP _ SPI _ ATTACH argument are reserved values
arg = struct . pack ( '<I' , hspi_arg )
if not self . IS_STUB : # ESP32 ROM loader takes additional ' is legacy ' arg , which is not
# currently supported in the stub loader or esptool . py ( as it ' s not usually needed . )
is_legacy = 0
arg += ... |
def update_user ( userid , profile = 'grafana' , orgid = None , ** kwargs ) :
'''Update an existing user .
userid
Id of the user .
login
Optional - Login of the user .
email
Optional - Email of the user .
name
Optional - Full name of the user .
orgid
Optional - Default Organization of the user .... | if isinstance ( profile , string_types ) :
profile = __salt__ [ 'config.option' ] ( profile )
response = requests . put ( '{0}/api/users/{1}' . format ( profile [ 'grafana_url' ] , userid ) , json = kwargs , auth = _get_auth ( profile ) , headers = _get_headers ( profile ) , timeout = profile . get ( 'grafana_timeo... |
def get ( self , name = None , plugin = None ) :
"""Returns commands , which can be filtered by name or plugin .
: param name : name of the command
: type name : str
: param plugin : plugin object , which registers the commands
: type plugin : instance of GwBasePattern
: return : None , single command or ... | if plugin is not None :
if name is None :
command_list = { }
for key in self . _commands . keys ( ) :
if self . _commands [ key ] . plugin == plugin :
command_list [ key ] = self . _commands [ key ]
return command_list
else :
if name in self . _command... |
def update_port_ip_address ( self ) :
"""Find the ip address that assinged to a port via DHCP
The port database will be updated with the ip address .""" | leases = None
req = dict ( ip = '0.0.0.0' )
instances = self . get_vms_for_this_req ( ** req )
if instances is None :
return
for vm in instances :
if not leases : # For the first time finding the leases file .
leases = self . _get_ip_leases ( )
if not leases : # File does not exist .
... |
def run_dead_birth_array ( run , ** kwargs ) :
"""Converts input run into an array of the format of a PolyChord
< root > _ dead - birth . txt file . Note that this in fact includes live points
remaining at termination as well as dead points .
Parameters
ns _ run : dict
Nested sampling run dict ( see data ... | nestcheck . ns_run_utils . check_ns_run ( run , ** kwargs )
threads = nestcheck . ns_run_utils . get_run_threads ( run )
samp_arrays = [ ]
ndim = run [ 'theta' ] . shape [ 1 ]
for th in threads :
samp_arr = np . zeros ( ( th [ 'theta' ] . shape [ 0 ] , ndim + 2 ) )
samp_arr [ : , : ndim ] = th [ 'theta' ]
s... |
def send ( self , message ) :
"""Write a message to the gateway .""" | if not message or not self . protocol or not self . protocol . transport :
return
if not self . can_log :
_LOGGER . debug ( 'Sending %s' , message . strip ( ) )
try :
self . protocol . transport . write ( message . encode ( ) )
except OSError as exc :
_LOGGER . error ( 'Failed writing to transport %s: %... |
def simulate_reads ( self ) :
"""Use the PacBio assembly FASTA files to generate simulated reads of appropriate forward and reverse lengths
at different depths of sequencing using randomreads . sh from the bbtools suite""" | logging . info ( 'Read simulation' )
for sample in self . metadata : # Create the simulated _ reads GenObject
sample . simulated_reads = GenObject ( )
# Iterate through all the desired depths of coverage
for depth in self . read_depths : # Create the depth GenObject
setattr ( sample . simulated_read... |
async def fetchrow ( self , * , timeout = None ) :
r"""Return the next row .
: param float timeout : Optional timeout value in seconds .
: return : A : class : ` Record ` instance .""" | self . _check_ready ( )
if self . _exhausted :
return None
recs = await self . _exec ( 1 , timeout )
if len ( recs ) < 1 :
self . _exhausted = True
return None
return recs [ 0 ] |
def extract ( self , name , example ) :
'''Extract keywords from an example path''' | # if pathlib not available do nothing
if not pathlib :
return None
# ensure example is a string
if isinstance ( example , pathlib . Path ) :
example = str ( example )
assert isinstance ( example , six . string_types ) , 'example file must be a string'
# get the template
assert name in self . lookup_names ( ) , ... |
def text_ ( s , encoding = 'latin-1' , errors = 'strict' ) :
'''If ` ` s ` ` is an instance of ` ` binary _ type ` ` , return
` ` s . decode ( encoding , errors ) ` ` , otherwise return ` ` s ` `''' | return s . decode ( encoding , errors ) if isinstance ( s , binary_type ) else s |
def wgs84_to_pixel ( lng , lat , transform , utm_epsg = None , truncate = True ) :
"""Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS . If no CRS is given it will be
calculated it automatically .
: param lng : longitude of point
: type lng : float
: param lat : latitude of p... | east , north = wgs84_to_utm ( lng , lat , utm_epsg )
row , column = utm_to_pixel ( east , north , transform , truncate = truncate )
return row , column |
def cumulative_blame ( self , branch = 'master' , by = 'committer' , limit = None , skip = None , num_datapoints = None , committer = True , ignore_globs = None , include_globs = None ) :
"""Returns a time series of cumulative blame for a collection of projects . The goal is to return a dataframe for a
collection... | blames = [ ]
for repo in self . repos :
try :
blame = repo . cumulative_blame ( branch = branch , limit = limit , skip = skip , num_datapoints = num_datapoints , committer = committer , ignore_globs = ignore_globs , include_globs = include_globs )
blames . append ( ( repo . repo_name , blame ) )
... |
def _get_longest_hit_by_ref_length ( self , nucmer_hits ) :
'''Input : list of nucmer hits . Returns the longest hit , taking hit length on the reference''' | if len ( nucmer_hits ) == 0 :
return None
max_length = None
longest_hit = None
for hit in nucmer_hits :
if max_length is None or hit . hit_length_ref > max_length :
max_length = hit . hit_length_ref
longest_hit = copy . copy ( hit )
assert longest_hit is not None
return longest_hit |
def _batched_write_command ( namespace , operation , command , docs , check_keys , opts , ctx ) :
"""Create the next batched insert , update , or delete command .""" | buf = StringIO ( )
# Save space for message length and request id
buf . write ( _ZERO_64 )
# responseTo , opCode
buf . write ( b"\x00\x00\x00\x00\xd4\x07\x00\x00" )
# Write OP _ QUERY write command
to_send , length = _batched_write_command_impl ( namespace , operation , command , docs , check_keys , opts , ctx , buf )
... |
def update_cluster_topology ( self , assignment ) :
"""Modify the cluster - topology with given assignment .
Change the replica set of partitions as in given assignment .
: param assignment : dict representing actions to be used to update the current
cluster - topology
: raises : InvalidBrokerIdError when b... | try :
for partition_name , replica_ids in six . iteritems ( assignment ) :
try :
new_replicas = [ self . brokers [ b_id ] for b_id in replica_ids ]
except KeyError :
self . log . error ( "Invalid replicas %s for topic-partition %s-%s." , ', ' . join ( [ str ( id ) for id in r... |
def y0 ( x , context = None ) :
"""Return the value of the second kind Bessel function of order 0 at x .""" | return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_y0 , ( BigFloat . _implicit_convert ( x ) , ) , context , ) |
def _get_submodules ( app , module ) :
"""Get all submodules for the given module / package
: param app : the sphinx app
: type app : : class : ` sphinx . application . Sphinx `
: param module : the module to query or module path
: type module : module | str
: returns : list of module names and boolean wh... | if inspect . ismodule ( module ) :
if hasattr ( module , '__path__' ) :
p = module . __path__
else :
return [ ]
elif isinstance ( module , str ) :
p = module
else :
raise TypeError ( "Only Module or String accepted. %s given." % type ( module ) )
logger . debug ( 'Getting submodules of %... |
def load_observations ( ( observations , regex , rename ) , path , filenames ) :
"""Returns a provisional name based dictionary of observations of the object .
Each observations is keyed on the date . ie . a dictionary of dictionaries .
@ param path : the directory where filenames are .
@ type path str
@ pa... | for filename in filenames :
if re . search ( regex , filename ) is None :
logging . error ( "Skipping {}" . format ( filename ) )
continue
obs = mpc . MPCReader ( ) . read ( os . path . join ( path , filename ) )
for ob in obs :
if "568" not in ob . observatory_code :
con... |
def close ( self , end_time = None ) :
"""Close the trace entity by setting ` end _ time `
and flip the in progress flag to False . Also decrement
parent segment ' s ref counter by 1.
: param int end _ time : Epoch in seconds . If not specified
current time will be used .""" | super ( Subsegment , self ) . close ( end_time )
self . parent_segment . decrement_ref_counter ( ) |
def category_replace ( text , replacements = UNICODE_CATEGORIES ) :
"""Remove characters from a string based on unicode classes .
This is a method for removing non - text characters ( such as punctuation ,
whitespace , marks and diacritics ) from a piece of text by class , rather
than specifying them individu... | if text is None :
return None
characters = [ ]
for character in decompose_nfkd ( text ) :
cat = category ( character )
replacement = replacements . get ( cat , character )
if replacement is not None :
characters . append ( replacement )
return u'' . join ( characters ) |
def list_user ( context , id , sort , limit , where , verbose ) :
"""list _ user ( context , id , sort , limit , where , verbose )
List users attached to a remoteci .
> > > dcictl remoteci - list - user [ OPTIONS ]
: param string id : ID of the remoteci to list the user from
[ required ]
: param string so... | result = remoteci . list_users ( context , id = id , sort = sort , limit = limit , where = where )
utils . format_output ( result , context . format , verbose = verbose ) |
def lis_to_bio_map ( folder ) :
"""Senators have a lis _ id that is used in some places . That ' s dumb . Build a
dict from lis _ id to bioguide _ id which every member of congress has .""" | logger . info ( "Opening legislator csv for lis_dct creation" )
lis_dic = { }
leg_path = "{0}/legislators.csv" . format ( folder )
logger . info ( leg_path )
with open ( leg_path , 'r' ) as csvfile :
leg_reader = csv . reader ( csvfile )
for row in leg_reader :
if row [ 22 ] :
lis_dic [ row ... |
def handlePosition ( self , msg ) :
"""handle positions changes""" | # log handler msg
self . log_msg ( "position" , msg )
# contract identifier
contract_tuple = self . contract_to_tuple ( msg . contract )
contractString = self . contractString ( contract_tuple )
# try creating the contract
self . registerContract ( msg . contract )
# new account ?
if msg . account not in self . _positi... |
def parent ( self , parent_object , limit_parent_language = True ) :
"""Return all content items which are associated with a given parent object .""" | return self . all ( ) . parent ( parent_object , limit_parent_language ) |
def plot_tree ( booster , ax = None , tree_index = 0 , figsize = None , old_graph_attr = None , old_node_attr = None , old_edge_attr = None , show_info = None , precision = None , ** kwargs ) :
"""Plot specified tree .
Note
It is preferable to use ` ` create _ tree _ digraph ( ) ` ` because of its lossless qual... | if MATPLOTLIB_INSTALLED :
import matplotlib . pyplot as plt
import matplotlib . image as image
else :
raise ImportError ( 'You must install matplotlib to plot tree.' )
for param_name in [ 'old_graph_attr' , 'old_node_attr' , 'old_edge_attr' ] :
param = locals ( ) . get ( param_name )
if param is not... |
def snapshot_get ( repository , snapshot , ignore_unavailable = False , hosts = None , profile = None ) :
'''. . versionadded : : 2017.7.0
Obtain snapshot residing in specified repository .
repository
Repository name
snapshot
Snapshot name , use _ all to obtain all snapshots in specified repository
igno... | es = _get_instance ( hosts , profile )
try :
return es . snapshot . get ( repository = repository , snapshot = snapshot , ignore_unavailable = ignore_unavailable )
except elasticsearch . TransportError as e :
raise CommandExecutionError ( "Cannot obtain details of snapshot {0} in repository {1}, server returned... |
def load ( self , model ) :
"""Load pickled DAWG from disk .""" | self . _dawg . load ( find_data ( model ) )
self . _loaded_model = True |
def save_password ( self , hashed_password ) :
"""Save the hashed password to the Glances folder .""" | # Create the glances directory
safe_makedirs ( self . password_dir )
# Create / overwrite the password file
with open ( self . password_file , 'wb' ) as file_pwd :
file_pwd . write ( b ( hashed_password ) ) |
def unicode_convert ( obj ) :
"""Converts unicode objects to anscii .
Args :
obj ( object ) : The object to convert .
Returns :
The object converted to anscii , if possible . For ` ` dict ` ` and ` ` list ` ` , the object type is maintained .""" | try :
if isinstance ( obj , dict ) :
return { unicode_convert ( key ) : unicode_convert ( value ) for key , value in obj . items ( ) }
elif isinstance ( obj , list ) :
return [ unicode_convert ( element ) for element in obj ]
elif isinstance ( obj , str ) :
return obj
elif isinst... |
def process_or_validate_features ( features , num_dimensions = None , feature_type_map = { } ) :
"""Puts features into a standard form from a number of different possible forms .
The standard form is a list of 2 - tuples of ( name , datatype ) pairs . The name
is a string and the datatype is an object as define... | original_features = copy ( features )
if num_dimensions is not None and not isinstance ( num_dimensions , _integer_types ) :
raise TypeError ( "num_dimensions must be None, an integer or a long, not '%s'" % str ( type ( num_dimensions ) ) )
def raise_type_error ( additional_msg ) :
raise TypeError ( "Error proc... |
def _show ( self , pk ) :
"""show function logic , override to implement different logic
returns show and related list widget""" | pages = get_page_args ( )
page_sizes = get_page_size_args ( )
orders = get_order_args ( )
item = self . datamodel . get ( pk , self . _base_filters )
if not item :
abort ( 404 )
widgets = self . _get_show_widget ( pk , item )
self . update_redirect ( )
return self . _get_related_views_widgets ( item , orders = orde... |
def phrase_contains_special_keys ( expansion : model . Expansion ) -> bool :
"""Determine if the expansion contains any special keys , including those resulting from any processed macros
( < script > , < file > , etc ) . If any are found , the phrase cannot be undone .
Python Zen : » In the face of ambiguity , ... | found_special_keys = KEY_FIND_RE . findall ( expansion . string . lower ( ) )
return bool ( found_special_keys ) |
def find_by_ast ( line , version_token = "__version__" ) : # type : ( str , str ) - > Optional [ str ]
"""Safer way to ' execute ' python code to get a simple value
: param line :
: param version _ token :
: return :""" | if not line :
return ""
# clean up line .
simplified_line = simplify_line ( line )
if simplified_line . startswith ( version_token ) :
try :
tree = ast . parse ( simplified_line )
# type : Any
if hasattr ( tree . body [ 0 ] . value , "s" ) :
return unicode ( tree . body [ 0 ]... |
async def async_get_connected_devices ( self ) :
"""Retrieve data from ASUSWRT .
Calls various commands on the router and returns the superset of all
responses . Some commands will not work on some routers .""" | devices = { }
dev = await self . async_get_wl ( )
devices . update ( dev )
dev = await self . async_get_arp ( )
devices . update ( dev )
dev = await self . async_get_neigh ( devices )
devices . update ( dev )
if not self . mode == 'ap' :
dev = await self . async_get_leases ( devices )
devices . update ( dev )
r... |
def decorator ( d ) :
"""Creates a proper decorator .
If the default for the first ( function ) argument is None , creates a
version which be invoked as either @ decorator or @ decorator ( kwargs . . . ) .
See examples below .""" | defaults = d . __defaults__
if defaults and defaults [ 0 ] is None : # Can be applied as @ decorator or @ decorator ( kwargs ) because
# first argument is None
def decorate ( fn = None , ** kwargs ) :
if fn is None :
return _functools . partial ( decorate , ** kwargs )
else :
... |
def rename_afw_states ( afw : dict , suffix : str ) :
"""Side effect on input ! Renames all the states of the AFW
adding a * * suffix * * .
It is an utility function used during testing to avoid automata to have
states with names in common .
Avoid suffix that can lead to special name like " as " , " and " ,... | conversion_dict = { }
new_states = set ( )
new_accepting = set ( )
for state in afw [ 'states' ] :
conversion_dict [ state ] = '' + suffix + state
new_states . add ( '' + suffix + state )
if state in afw [ 'accepting_states' ] :
new_accepting . add ( '' + suffix + state )
afw [ 'states' ] = new_stat... |
def Scan ( self , scan_context , auto_recurse = True , scan_path_spec = None ) :
"""Scans for supported formats .
Args :
scan _ context ( SourceScannerContext ) : source scanner context .
auto _ recurse ( Optional [ bool ] ) : True if the scan should automatically
recurse as far as possible .
scan _ path ... | if not scan_context :
raise ValueError ( 'Invalid scan context.' )
scan_context . updated = False
if scan_path_spec :
scan_node = scan_context . GetScanNode ( scan_path_spec )
else :
scan_node = scan_context . GetUnscannedScanNode ( )
if scan_node :
self . _ScanNode ( scan_context , scan_node , auto_rec... |
def set_default_style ( style ) :
"""Sets default global style to be used by ` ` prettyprinter . cpprint ` ` .
: param style : the style to set , either subclass of
` ` pygments . styles . Style ` ` or one of ` ` ' dark ' ` ` , ` ` ' light ' ` `""" | global default_style
if style == 'dark' :
style = default_dark_style
elif style == 'light' :
style = default_light_style
if not issubclass ( style , Style ) :
raise TypeError ( "style must be a subclass of pygments.styles.Style or " "one of 'dark', 'light'. Got {}" . format ( repr ( style ) ) )
default_styl... |
def reporter ( self ) :
"""Creates a report of the results""" | # Create the path in which the reports are stored
make_path ( self . reportpath )
data = 'Strain,Gene,PercentIdentity,Length,FoldCoverage\n'
with open ( os . path . join ( self . reportpath , self . analysistype + '.csv' ) , 'w' ) as report :
for sample in self . runmetadata . samples :
data += sample . nam... |
def get_error ( self , i = None , unit = None , uncover = None , trail = None , linebreak = None , sort_by_indep = None ) :
"""access the error for a given value of i ( independent - variable ) depending
on which effects ( i . e . uncover ) are enabled .""" | return self . get_value ( i = i , unit = unit , uncover = uncover , trail = trail , linebreak = linebreak , sort_by_indep = sort_by_indep , attr = '_error' ) |
def to_native_types ( self , slicer = None , na_rep = '' , quoting = None , ** kwargs ) :
"""convert to our native types format , slicing if desired""" | values = self . values
if slicer is not None : # Categorical is always one dimension
values = values [ slicer ]
mask = isna ( values )
values = np . array ( values , dtype = 'object' )
values [ mask ] = na_rep
# we are expected to return a 2 - d ndarray
return values . reshape ( 1 , len ( values ) ) |
def _recursive_hypernyms ( self , hypernyms ) :
"""Finds all the hypernyms of the synset transitively .
Notes
Internal method . Do not call directly .
Parameters
hypernyms : set of Synsets
An set of hypernyms met so far .
Returns
set of Synsets
Returns the input set .""" | hypernyms |= set ( self . hypernyms ( ) )
for synset in self . hypernyms ( ) :
hypernyms |= synset . _recursive_hypernyms ( hypernyms )
return hypernyms |
def get_addresses_details ( address_list , coin_symbol = 'btc' , txn_limit = None , api_key = None , before_bh = None , after_bh = None , unspent_only = False , show_confidence = False , confirmations = 0 , include_script = False ) :
'''Batch version of get _ address _ details method''' | for address in address_list :
assert is_valid_address_for_coinsymbol ( b58_address = address , coin_symbol = coin_symbol ) , address
assert isinstance ( show_confidence , bool ) , show_confidence
kwargs = dict ( addrs = ';' . join ( [ str ( addr ) for addr in address_list ] ) )
url = make_url ( coin_symbol , ** kwa... |
def _ScanVolumeSystemRootNode ( self , scan_context , scan_node , auto_recurse = True ) :
"""Scans a volume system root node for supported formats .
Args :
scan _ context ( SourceScannerContext ) : source scanner context .
scan _ node ( SourceScanNode ) : source scan node .
auto _ recurse ( Optional [ bool ... | if scan_node . type_indicator == definitions . TYPE_INDICATOR_VSHADOW : # For VSS add a scan node for the current volume .
path_spec = self . ScanForFileSystem ( scan_node . path_spec . parent )
if path_spec :
scan_context . AddScanNode ( path_spec , scan_node . parent_node )
# Determine the path specif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.