signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def dns_name ( self ) :
"""Get the DNS name for this machine . This is a best guess based on the
addresses available in current data .
May return None if no suitable address is found .""" | for scope in [ 'public' , 'local-cloud' ] :
addresses = self . safe_data [ 'addresses' ] or [ ]
addresses = [ address for address in addresses if address [ 'scope' ] == scope ]
if addresses :
return addresses [ 0 ] [ 'value' ]
return None |
def check_version ( url = VERSION_URL ) :
"""Returns the version string for the latest SDK .""" | for line in get ( url ) :
if 'release:' in line :
return line . split ( ':' ) [ - 1 ] . strip ( ' \'"\r\n' ) |
def initialize_create_state_map ( self ) :
"""This is a mapping of create result message string to state .""" | self . fabric_state_map = { fw_const . INIT_STATE_STR : fw_const . OS_IN_NETWORK_STATE , fw_const . OS_IN_NETWORK_CREATE_FAIL : fw_const . OS_IN_NETWORK_STATE , fw_const . OS_IN_NETWORK_CREATE_SUCCESS : fw_const . OS_OUT_NETWORK_STATE , fw_const . OS_OUT_NETWORK_CREATE_FAIL : fw_const . OS_OUT_NETWORK_STATE , fw_const ... |
def reload ( data : Any ) -> Any :
"""Dump and load yaml data .
This is useful to avoid many anchor parsing bugs . When you edit a yaml config , reload it to make sure
the changes are propagated to anchor expansions .
: param data : data to be reloaded
: return : reloaded data""" | return yaml . load ( yaml . dump ( data , Dumper = ruamel . yaml . RoundTripDumper ) , Loader = ruamel . yaml . RoundTripLoader ) |
def multiply ( self , data , fill_value = 0. ) :
"""Multiply the aperture mask with the input data , taking any edge
effects into account .
The result is a mask - weighted cutout from the data .
Parameters
data : array _ like or ` ~ astropy . units . Quantity `
The 2D array to multiply with the aperture m... | cutout = self . cutout ( data , fill_value = fill_value )
if cutout is None :
return None
else :
return cutout * self . data |
def getFileSecurity ( self , fileName , securityInformation , securityDescriptor , lengthSecurityDescriptorBuffer , lengthNeeded , dokanFileInfo , ) :
"""Get security attributes of a file .
: param fileName : name of file to get security for
: type fileName : ctypes . c _ wchar _ p
: param securityInformation... | return self . operations ( 'getFileSecurity' , fileName ) |
def from_string ( cls , cl_function , dependencies = ( ) ) :
"""Parse the given CL function into a SimpleCLFunction object .
Args :
cl _ function ( str ) : the function we wish to turn into an object
dependencies ( list or tuple of CLLibrary ) : The list of CL libraries this function depends on
Returns :
... | return_type , function_name , parameter_list , body = split_cl_function ( cl_function )
return SimpleCLFunction ( return_type , function_name , parameter_list , body , dependencies = dependencies ) |
def create ( name , level , devices , metadata = 'default' , test_mode = False , ** kwargs ) :
'''Create a RAID device .
. . versionchanged : : 2014.7.0
. . warning : :
Use with CAUTION , as this function can be very destructive if not used
properly !
CLI Examples :
. . code - block : : bash
salt ' * ... | opts = [ ]
raid_devices = len ( devices )
for key in kwargs :
if not key . startswith ( '__' ) :
opts . append ( '--{0}' . format ( key ) )
if kwargs [ key ] is not True :
opts . append ( six . text_type ( kwargs [ key ] ) )
if key == 'spare-devices' :
raid_devices -= int ( k... |
def get_data ( session = None , day = None , year = None ) :
"""Get data for day ( 1-25 ) and year ( > = 2015)
User ' s session cookie is needed ( puzzle inputs differ by user )""" | if session is None :
user = default_user ( )
else :
user = User ( token = session )
if day is None :
day = current_day ( )
log . info ( "current day=%s" , day )
if year is None :
year = most_recent_year ( )
log . info ( "most recent year=%s" , year )
puzzle = Puzzle ( year = year , day = day , u... |
def _make_color_fn ( color ) :
"""Create a function that set the foreground color .""" | def _color ( text = "" ) :
return ( _color_sep + color + _color_sep2 + text + _color_sep + "default" + _color_sep2 )
return _color |
def generate_pdfa_ps ( target_filename , icc = 'sRGB' ) :
"""Create a Postscript pdfmark file for Ghostscript PDF / A conversion
A pdfmark file is a small Postscript program that provides some information
Ghostscript needs to perform PDF / A conversion . The only information we put
in specifies that we want t... | if icc == 'sRGB' :
icc_profile = SRGB_ICC_PROFILE
else :
raise NotImplementedError ( "Only supporting sRGB" )
# pdfmark must contain the full path to the ICC profile , and pdfmark must be
# also encoded in ASCII . ocrmypdf can be installed anywhere , including to
# paths that have a non - ASCII character in the... |
def and_raises ( self , * errors ) :
"Expects an error or more to be raised from the given expectation ." | for error in errors :
self . __expect ( Expectation . raises , error ) |
def parse_simple_value ( self , stream ) :
"""SimpleValue : : = Integer
| FloatingPoint
| Exponential
| BinaryNum
| OctalNum
| HexadecimalNum
| DateTimeValue
| QuotedString
| UnquotedString""" | if self . has_quoted_string ( stream ) :
return self . parse_quoted_string ( stream )
if self . has_binary_number ( stream ) :
return self . parse_binary_number ( stream )
if self . has_octal_number ( stream ) :
return self . parse_octal_number ( stream )
if self . has_decimal_number ( stream ) :
return... |
def add_subprocesses ( self , procdict ) :
"""Adds a dictionary of subproceses to this process .
Calls : func : ` add _ subprocess ` for every process given in the
input - dictionary . It can also pass a single process , which will
be given the name * default * .
: param procdict : a dictionary with process... | if isinstance ( procdict , Process ) :
try :
name = procdict . name
except :
name = 'default'
self . add_subprocess ( name , procdict )
else :
for name , proc in procdict . items ( ) :
self . add_subprocess ( name , proc ) |
def get_chain_details ( self , pdb_id , chain = None , internal_function_call = False , pfam_scop_mapping = { } ) :
'''Returns a dict pdb _ id - > chain ( s ) - > chain and SCOPe details .
This is the main function for getting details for a PDB chain . If there is an associated SCOPe entry for this
chain then t... | query = '''
SELECT DISTINCT scop_node.id AS scop_node_id, scop_node.*, pdb_entry.code, pdb_chain_id, pdb_chain.chain, pdb_chain.is_polypeptide, pdb_entry.description AS ChainDescription, pdb_release.resolution
FROM `link_pdb`
INNER JOIN scop_node on node_id=scop_node.id
I... |
def update_value ( self , offset , value ) :
"""Update the binary value currently stored for this config value .
Returns :
int : An opaque error code that can be returned from a set _ config rpc""" | if offset + len ( value ) > self . total_size :
return Error . INPUT_BUFFER_TOO_LONG
if len ( self . current_value ) < offset :
self . current_value += bytearray ( offset - len ( self . current_value ) )
if len ( self . current_value ) > offset :
self . current_value = self . current_value [ : offset ]
self... |
def call ( self , inputs ) :
"""Call ` Layer ` .""" | # if context . executing _ eagerly ( ) :
# if not self . initialized :
# self . _ data _ dep _ init ( inputs )
self . _compute_weights ( )
# Recompute weights for each forward pass
output = self . layer . call ( inputs )
return output |
def main ( ) :
"""Use processes and Netmiko to connect to each of the devices . Execute
' show version ' on each device . Use a queue to pass the output back to the parent process .
Record the amount of time required to do this .""" | start_time = datetime . now ( )
output_q = Queue ( maxsize = 20 )
procs = [ ]
for a_device in devices :
my_proc = Process ( target = show_version_queue , args = ( a_device , output_q ) )
my_proc . start ( )
procs . append ( my_proc )
# Make sure all processes have finished
for a_proc in procs :
a_proc .... |
def set_enable ( cls , target , enable = True ) :
"""( Dis | En ) able annotated interceptors .""" | interceptors = cls . get_annotations ( target )
for interceptor in interceptors :
setattr ( interceptor , Interceptor . ENABLE , enable ) |
def unregister_message_handler ( self , target_or_handler ) :
"""Unregister a mpv script message handler for the given script message target name .
You can also call the ` ` unregister _ mpv _ messages ` ` function attribute set on the handler function when it is
registered .""" | if isinstance ( target_or_handler , str ) :
del self . _message_handlers [ target_or_handler ]
else :
for key , val in self . _message_handlers . items ( ) :
if val == target_or_handler :
del self . _message_handlers [ key ] |
def toProtocolElement ( self ) :
"""Converts this VariantAnnotationSet into its GA4GH protocol equivalent .""" | protocolElement = protocol . VariantAnnotationSet ( )
protocolElement . id = self . getId ( )
protocolElement . variant_set_id = self . _variantSet . getId ( )
protocolElement . name = self . getLocalId ( )
protocolElement . analysis . CopyFrom ( self . getAnalysis ( ) )
self . serializeAttributes ( protocolElement )
r... |
def native_types ( code ) :
"""Convert code elements from strings to native Python types .""" | out = [ ]
for c in code :
if isconstant ( c , quoted = True ) :
if isstring ( c , quoted = True ) :
v = c [ 1 : - 1 ]
elif isbool ( c ) :
v = to_bool ( c )
elif isnumber ( c ) :
v = c
else :
raise CompileError ( "Unknown type %s: %s" % ... |
def _block ( self , count ) :
"""Round up a byte count by BLOCKSIZE and return it ,
e . g . _ block ( 834 ) = > 1024.""" | blocks , remainder = divmod ( count , BLOCKSIZE )
if remainder :
blocks += 1
return blocks * BLOCKSIZE |
def list_encoder ( values , instance , field : Field ) :
"""Encodes an iterable of a given field into a database - compatible format .""" | return [ field . to_db_value ( element , instance ) for element in values ] |
def login_with_token ( refresh_token , team = None ) :
"""Authenticate using an existing token .""" | # Get an access token and a new refresh token .
_check_team_id ( team )
auth = _update_auth ( team , refresh_token )
url = get_registry_url ( team )
contents = _load_auth ( )
contents [ url ] = auth
_save_auth ( contents )
_clear_session ( team ) |
def get_frame ( self , outdata , frames , timedata , status ) :
"""Callback function for the audio stream . Don ' t use directly .""" | if not self . keep_listening :
raise sd . CallbackStop
try :
chunk = self . queue . get_nowait ( )
# Check if the chunk contains the expected number of frames
# The callback function raises a ValueError otherwise .
if chunk . shape [ 0 ] == frames :
outdata [ : ] = chunk
else :
o... |
def before_content ( self ) :
"""Build up prefix history for nested elements
The following keys are used in : py : attr : ` self . env . ref _ context ` :
dn : prefixes
Stores the prefix history . With each nested element , we add the
prefix to a list of prefixes . When we exit that object ' s nesting
lev... | super ( DotNetObjectNested , self ) . before_content ( )
if self . names :
( _ , prefix ) = self . names . pop ( )
try :
self . env . ref_context [ 'dn:prefixes' ] . append ( prefix )
except ( AttributeError , KeyError ) :
self . env . ref_context [ 'dn:prefixes' ] = [ prefix ]
finally :... |
def splash ( self ) :
"""Draw splash screen""" | dirname = os . path . split ( os . path . abspath ( __file__ ) ) [ 0 ]
try :
splash = open ( os . path . join ( dirname , "splash" ) , "r" ) . readlines ( )
except IOError :
return
width = len ( max ( splash , key = len ) )
y = int ( self . y_grid / 2 ) - len ( splash )
x = int ( self . x_grid / 2 ) - int ( wid... |
def _detect_sudo ( self , _execnet = None ) :
"""` ` sudo ` ` detection has to create a different connection to the remote
host so that we can reliably ensure that ` ` getuser ( ) ` ` will return the
right information .
After getting the user info it closes the connection and returns
a boolean""" | exc = _execnet or execnet
gw = exc . makegateway ( self . _make_connection_string ( self . hostname , use_sudo = False ) )
channel = gw . remote_exec ( 'import getpass; channel.send(getpass.getuser())' )
result = channel . receive ( )
gw . exit ( )
if result == 'root' :
return False
self . logger . debug ( 'connect... |
def merge_dicts ( * dicts , ** kwargs ) :
"""Merges dicts and kwargs into one dict""" | result = { }
for d in dicts :
result . update ( d )
result . update ( kwargs )
return result |
def lines_iter ( self ) :
'''Returns contents of the Dockerfile as an array , where each line in the file is an element in the array .
: return : list''' | # Convert unicode chars to string
byte_to_string = lambda x : x . strip ( ) . decode ( u'utf-8' ) if isinstance ( x , bytes ) else x . strip ( )
# Read the entire contents of the Dockerfile , decoding each line , and return the result as an array
with open ( self . docker_file_path , u'r' ) as f :
for line in f :
... |
def remove_tab ( self , tab = 0 ) :
"""Removes the tab by index .""" | # pop it from the list
t = self . tabs . pop ( tab )
# remove it from the gui
self . _widget . removeTab ( tab )
# return it in case someone cares
return t |
def get_unpermitted_fields ( self ) :
"""Gives unpermitted fields for current context / user .
Returns :
List of unpermitted field names .""" | return ( self . _unpermitted_fields if self . _is_unpermitted_fields_set else self . _apply_cell_filters ( self . _context ) ) |
def view ( request , namespace , docid ) :
"""The initial view , does not provide the document content yet""" | if flat . users . models . hasreadpermission ( request . user . username , namespace , request ) :
if 'autodeclare' in settings . CONFIGURATIONS [ request . session [ 'configuration' ] ] :
if flat . users . models . haswritepermission ( request . user . username , namespace , request ) :
for ann... |
def wait_until_element_clickable ( self , element , timeout = None ) :
"""Search element and wait until it is clickable
: param element : PageElement or element locator as a tuple ( locator _ type , locator _ value ) to be found
: param timeout : max time to wait
: returns : the web element if it is clickable... | return self . _wait_until ( self . _expected_condition_find_element_clickable , element , timeout ) |
def _save_stdin ( self , stdin ) :
"""Creates a temporary dir ( self . temp _ dir ) and saves the given input
stream to a file within that dir . Returns the path to the file . The dir
is removed in the _ _ del _ _ method .""" | self . temp_dir = TemporaryDirectory ( )
file_path = os . path . join ( self . temp_dir . name , 'dataset' )
try :
with open ( file_path , 'w' ) as f :
for line in stdin :
f . write ( line )
except TypeError :
self . temp_dir . cleanup ( )
raise ValueError ( 'Could not read stdin' )
retu... |
def channels ( self ) :
"""0 means unknown""" | assert self . parsed_frames , "no frame parsed yet"
b_index = self . _fixed_header_key [ 6 ]
if b_index == 7 :
return 8
elif b_index > 7 :
return 0
else :
return b_index |
def get_d1str ( self , goobj , reverse = False ) :
"""Get D1 - string representing all parent terms which are depth - 01 GO terms .""" | return "" . join ( sorted ( self . get_parents_letters ( goobj ) , reverse = reverse ) ) |
def handle_typed_values ( val , type_name , value_type ) :
"""Translate typed values into the appropriate python object .
Takes an element name , value , and type and returns a list
with the string value ( s ) properly converted to a python type .
TypedValues are handled in ucar . ma2 . DataType in netcdfJava... | if value_type in [ 'byte' , 'short' , 'int' , 'long' ] :
try :
val = [ int ( v ) for v in re . split ( '[ ,]' , val ) if v ]
except ValueError :
log . warning ( 'Cannot convert "%s" to int. Keeping type as str.' , val )
elif value_type in [ 'float' , 'double' ] :
try :
val = [ float ... |
def exec_pg_success ( self , cmd ) :
"""Execute a command inside a running container as the postgres user ,
asserting success .""" | result = self . inner ( ) . exec_run ( cmd , user = 'postgres' )
assert result . exit_code == 0 , result . output . decode ( 'utf-8' )
return result |
def add_lrn ( self , name , input_name , output_name , alpha , beta , local_size , k = 1.0 ) :
"""Add a LRN ( local response normalization ) layer . Please see the LRNLayerParams message in Core ML neural network
protobuf for more information about the operation of this layer . Supports " across " channels normal... | spec = self . spec
nn_spec = self . nn_spec
# Add a new layer
spec_layer = nn_spec . layers . add ( )
spec_layer . name = name
spec_layer . input . append ( input_name )
spec_layer . output . append ( output_name )
spec_layer_params = spec_layer . lrn
spec_layer_params . alpha = alpha
spec_layer_params . beta = beta
sp... |
def galcenrect_to_vxvyvz ( vXg , vYg , vZg , vsun = [ 0. , 1. , 0. ] , Xsun = 1. , Zsun = 0. , _extra_rot = True ) :
"""NAME :
galcenrect _ to _ vxvyvz
PURPOSE :
transform rectangular Galactocentric coordinates to XYZ coordinates ( wrt Sun ) for velocities
INPUT :
vXg - Galactocentric x - velocity
vYg -... | dgc = nu . sqrt ( Xsun ** 2. + Zsun ** 2. )
costheta , sintheta = Xsun / dgc , Zsun / dgc
if isinstance ( Xsun , nu . ndarray ) :
zero = nu . zeros ( len ( Xsun ) )
one = nu . ones ( len ( Xsun ) )
Carr = nu . rollaxis ( nu . array ( [ [ - costheta , zero , - sintheta ] , [ zero , one , zero ] , [ - nu . si... |
def all_variables ( self ) :
"""A flat tuple of all symbols taken in order from the following :
1 . ` scipy _ data _ fitting . Fit . free _ variables `
2 . ` scipy _ data _ fitting . Fit . independent `
3 . ` scipy _ data _ fitting . Fit . fitting _ parameters `
4 . ` scipy _ data _ fitting . Fit . fixed _ ... | variables = [ ]
variables . extend ( self . free_variables )
variables . append ( self . independent [ 'symbol' ] )
variables . extend ( [ param [ 'symbol' ] for param in self . fitting_parameters ] )
variables . extend ( [ param [ 'symbol' ] for param in self . fixed_parameters ] )
variables . extend ( [ const [ 'symb... |
def encode_filename ( filename , from_encoding = 'utf-8' , to_encoding = None ) :
"""> > > print encode _ filename ( ' \xe4 \xb8 \xad \xe5 \x9b \xbd . doc ' )
\xd6 \xd0 \xb9 \xfa . doc
> > > f = unicode ( ' \xe4 \xb8 \xad \xe5 \x9b \xbd . doc ' , ' utf - 8 ' )
> > > print encode _ filename ( f )
\xd6 \xd0 \... | import sys
to_encoding = to_encoding or sys . getfilesystemencoding ( )
from_encoding = from_encoding or sys . getfilesystemencoding ( )
if not isinstance ( filename , unicode ) :
try :
f = unicode ( filename , from_encoding )
except UnicodeDecodeError :
try :
f = unicode ( filename ... |
def rgba_floats_tuple ( self , x ) :
"""Provides the color corresponding to value ` x ` in the
form of a tuple ( R , G , B , A ) with float values between 0 . and 1.""" | if x <= self . index [ 0 ] :
return self . colors [ 0 ]
if x >= self . index [ - 1 ] :
return self . colors [ - 1 ]
i = len ( [ u for u in self . index if u < x ] )
# 0 < i < n .
return tuple ( self . colors [ i - 1 ] ) |
def run_with_time_limit ( self , cmd , time_limit = SUBMISSION_TIME_LIMIT ) :
"""Runs docker command and enforces time limit .
Args :
cmd : list with the command line arguments which are passed to docker
binary after run
time _ limit : time limit , in seconds . Negative value means no limit .
Returns :
... | if time_limit < 0 :
return self . run_without_time_limit ( cmd )
container_name = str ( uuid . uuid4 ( ) )
cmd = [ DOCKER_BINARY , 'run' , DOCKER_NVIDIA_RUNTIME , '--detach' , '--name' , container_name ] + cmd
logging . info ( 'Docker command: %s' , ' ' . join ( cmd ) )
logging . info ( 'Time limit %d seconds' , ti... |
def unregister ( self , model = None ) :
'''Unregister a ` ` model ` ` if provided , otherwise it unregister all
registered models . Return a list of unregistered model managers or ` ` None ` `
if no managers were removed .''' | if model is not None :
try :
manager = self . _registered_models . pop ( model )
except KeyError :
return
if self . _registered_names . get ( manager . _meta . name ) == manager :
self . _registered_names . pop ( manager . _meta . name )
return [ manager ]
else :
managers = l... |
def MakeExponentialPmf ( lam , high , n = 200 ) :
"""Makes a PMF discrete approx to an exponential distribution .
lam : parameter lambda in events per unit time
high : upper bound
n : number of values in the Pmf
returns : normalized Pmf""" | pmf = Pmf ( )
for x in numpy . linspace ( 0 , high , n ) :
p = EvalExponentialPdf ( x , lam )
pmf . Set ( x , p )
pmf . Normalize ( )
return pmf |
def get ( key , default = - 1 ) :
"""Backport support for original codes .""" | if isinstance ( key , int ) :
return Transport ( key )
if key not in Transport . _member_map_ :
extend_enum ( Transport , key , default )
return Transport [ key ] |
def download_file ( url , file_path , mkdir = False ) :
"""Write a string of data to file .
Args :
url : A string to a valid URL .
file _ path : Full path to intended download location ( e . g . c : / ladybug / testPts . pts )
mkdir : Set to True to create the directory if doesn ' t exist ( Default : False ... | folder , fname = os . path . split ( file_path )
return download_file_by_name ( url , folder , fname , mkdir ) |
def resolve_identifiers ( self , subject_context ) :
"""ensures that a subject _ context has identifiers and if it doesn ' t will
attempt to locate them using heuristics""" | session = subject_context . session
identifiers = subject_context . resolve_identifiers ( session )
if ( not identifiers ) :
msg = ( "No identity (identifier_collection) found in the " "subject_context. Looking for a remembered identity." )
logger . debug ( msg )
identifiers = self . get_remembered_identit... |
def getTime ( self ) :
"""Actually , this function creates a time stamp vector
based on the number of samples and sample rate .""" | T = 1 / float ( self . samp [ self . nrates - 1 ] )
endtime = self . endsamp [ self . nrates - 1 ] * T
t = numpy . linspace ( 0 , endtime , self . endsamp [ self . nrates - 1 ] )
return t |
def apps_installation_create ( self , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / apps # install - app" | api_path = "/api/v2/apps/installations.json"
return self . call ( api_path , method = "POST" , data = data , ** kwargs ) |
def _get_dsp_from_bfs ( self , outputs , bfs_graphs = None ) :
"""Returns the sub - dispatcher induced by the workflow from outputs .
: param outputs :
Ending data nodes .
: type outputs : list [ str ] , iterable , optional
: param bfs _ graphs :
A dictionary with directed graphs where evaluate the
brea... | bfs = bfs_graphs [ NONE ] if bfs_graphs is not None else self . dmap
# Get sub dispatcher breadth - first - search graph .
dsp = self . get_sub_dsp_from_workflow ( sources = outputs , graph = bfs , reverse = True , _update_links = False )
# Namespace shortcuts .
succ , nodes , pred = dsp . dmap . succ , dsp . nodes , d... |
def build_maya_environment ( config , env = None , arg_paths = None ) :
"""Construct maya environment .""" | maya_env = MayaEnvironment ( )
maya_env . exclude_pattern = config . get_list ( Config . PATTERNS , 'exclude' )
maya_env . icon_extensions = config . get_list ( Config . PATTERNS , 'icon_ext' )
env = get_environment_paths ( config , env )
if not env and arg_paths is None :
return logger . info ( 'Using maya factory... |
def log_start_finish ( msg , logger , level = logging . DEBUG ) :
"""A context manager to log messages with " start : " and " finish : "
prefixes before and after a block .
Parameters
msg : str
Will be prefixed with " start : " and " finish : " .
logger : logging . Logger
level : int , optional
Level ... | logger . log ( level , 'start: ' + msg )
yield
logger . log ( level , 'finish: ' + msg ) |
def add_to_line_plot ( ax , x , y , color = '0.' , label = '' ) :
'''This function takes an axes and adds one line to it''' | plt . sca ( ax )
plt . plot ( x , y , color = color , label = label )
return ax |
def disassemble ( self , start = None , end = None , arch_mode = None ) :
"""Disassemble native instructions .
Args :
start ( int ) : Start address .
end ( int ) : End address .
arch _ mode ( int ) : Architecture mode .
Returns :
( int , Instruction , int ) : A tuple of the form ( address , assembler in... | if arch_mode is None :
arch_mode = self . binary . architecture_mode
curr_addr = start if start else self . binary . ea_start
end_addr = end if end else self . binary . ea_end
while curr_addr < end_addr : # Fetch the instruction .
encoding = self . __fetch_instr ( curr_addr )
# Decode it .
asm_instr = s... |
def gen_classdefs ( self ) -> str :
"""Create class definitions for all non - mixin classes in the model
Note that apply _ to classes are transformed to mixins""" | return '\n' . join ( [ self . gen_classdef ( k , v ) for k , v in self . schema . classes . items ( ) if not v . mixin ] ) |
def _fw_rule_create ( self , drvr_name , data , cache ) :
"""Firewall Rule create routine .
This function updates its local cache with rule parameters .
It checks if local cache has information about the Policy
associated with the rule . If not , it means a restart has happened .
It retrieves the policy ass... | tenant_id = data . get ( 'firewall_rule' ) . get ( 'tenant_id' )
fw_rule = data . get ( 'firewall_rule' )
rule = self . _fw_rule_decode_store ( data )
fw_pol_id = fw_rule . get ( 'firewall_policy_id' )
rule_id = fw_rule . get ( 'id' )
if tenant_id not in self . fwid_attr :
self . fwid_attr [ tenant_id ] = FwMapAttr... |
def set_representative_sequence ( self , force_rerun = False ) :
"""Automatically consolidate loaded sequences ( manual , UniProt , or KEGG ) and set a single representative sequence .
Manually set representative sequences override all existing mappings . UniProt mappings override KEGG mappings
except when KEGG... | # TODO : rethink use of multiple database sources - may lead to inconsistency with genome sources
successfully_mapped_counter = 0
for g in tqdm ( self . genes ) :
repseq = g . protein . set_representative_sequence ( force_rerun = force_rerun )
if repseq :
if repseq . sequence_file :
successf... |
def check_is_table ( func ) :
"""Decorator that will check whether the " table _ name " keyword argument
to the wrapped function matches a registered Orca table .""" | @ wraps ( func )
def wrapper ( ** kwargs ) :
if not orca . is_table ( kwargs [ 'table_name' ] ) :
abort ( 404 )
return func ( ** kwargs )
return wrapper |
def get_piles ( allgenes ) :
"""Before running uniq , we need to compute all the piles . The piles are a set
of redundant features we want to get rid of . Input are a list of GffLines
features . Output are list of list of features distinct " piles " .""" | from jcvi . utils . range import Range , range_piles
ranges = [ Range ( a . seqid , a . start , a . end , 0 , i ) for i , a in enumerate ( allgenes ) ]
for pile in range_piles ( ranges ) :
yield [ allgenes [ x ] for x in pile ] |
def convert_tstamp ( response ) :
"""Convert a Stripe API timestamp response ( unix epoch ) to a native datetime .
: rtype : datetime""" | if response is None : # Allow passing None to convert _ tstamp ( )
return response
# Overrides the set timezone to UTC - I think . . .
tz = timezone . utc if settings . USE_TZ else None
return datetime . datetime . fromtimestamp ( response , tz ) |
def is_name_registered ( self , name ) :
"""Given the fully - qualified name , is it registered , not revoked , and not expired
at the current block ?""" | name_rec = self . get_name ( name )
# won ' t return the name if expired
if name_rec is None :
return False
if name_rec [ 'revoked' ] :
return False
return True |
def add_path_segment ( self , value ) :
"""Add a new path segment to the end of the current string
: param string value : the new path segment to use
Example : :
> > > u = URL ( ' http : / / example . com / foo / ' )
> > > u . add _ path _ segment ( ' bar ' ) . as _ string ( )
' http : / / example . com /... | segments = self . path_segments ( ) + ( to_unicode ( value ) , )
return self . path_segments ( segments ) |
def get_max_item ( self , expand = False ) :
"""The current largest item id
Fetches data from URL :
https : / / hacker - news . firebaseio . com / v0 / maxitem . json
Args :
expand ( bool ) : Flag to indicate whether to transform all
IDs into objects .
Returns :
` int ` if successful .""" | url = urljoin ( self . base_url , 'maxitem.json' )
response = self . _get_sync ( url )
if expand :
return self . get_item ( response )
else :
return response |
def render ( self , surf ) :
"""Draw the button on the surface .""" | if not self . flags & self . NO_SHADOW :
circle ( surf , self . center + self . _bg_delta , self . width / 2 , LIGHT_GREY )
circle ( surf , self . center + self . _front_delta , self . width / 2 , self . _get_color ( ) )
self . text . center = self . center + self . _front_delta
self . text . render ( surf ) |
def setup_locale ( lc_all : str , first_weekday : int = None , * , lc_collate : str = None , lc_ctype : str = None , lc_messages : str = None , lc_monetary : str = None , lc_numeric : str = None , lc_time : str = None ) -> str :
"""Shortcut helper to setup locale for backend application .
: param lc _ all : Local... | if first_weekday is not None :
calendar . setfirstweekday ( first_weekday )
locale . setlocale ( locale . LC_COLLATE , lc_collate or lc_all )
locale . setlocale ( locale . LC_CTYPE , lc_ctype or lc_all )
locale . setlocale ( locale . LC_MESSAGES , lc_messages or lc_all )
locale . setlocale ( locale . LC_MONETARY , ... |
def get_nonvaried_cfg_lbls ( cfg_list , default_cfg = None , mainkey = '_cfgname' ) :
r"""TODO : this might only need to return a single value . Maybe not if the names
are different .
Args :
cfg _ list ( list ) :
default _ cfg ( None ) : ( default = None )
Returns :
list : cfglbl _ list
CommandLine : ... | try :
cfgname_list = [ cfg [ mainkey ] for cfg in cfg_list ]
except KeyError :
cfgname_list = [ '' ] * len ( cfg_list )
nonvaried_cfg = partition_varied_cfg_list ( cfg_list , default_cfg ) [ 0 ]
cfglbl_list = [ get_cfg_lbl ( nonvaried_cfg , name ) for name in cfgname_list ]
return cfglbl_list |
def image ( self , height = 1 , module_width = 1 , add_quiet_zone = True ) :
"""Get the barcode as PIL . Image .
By default the image is one pixel high and the number of modules pixels wide , with 10 empty modules added to
each side to act as the quiet zone . The size can be modified by setting height and modul... | if Image is None :
raise Code128 . MissingDependencyError ( "PIL module is required to use image method." )
modules = list ( self . modules )
if add_quiet_zone : # Add ten space modules to each side of the barcode .
modules = [ 1 ] * self . quiet_zone + modules + [ 1 ] * self . quiet_zone
width = len ( modules ... |
def info_cmd ( ) :
"""Print basic information about StagYY run .""" | sdat = stagyydata . StagyyData ( conf . core . path )
lsnap = sdat . snaps . last
lstep = sdat . steps . last
print ( 'StagYY run in {}' . format ( sdat . path ) )
if lsnap . geom . threed :
dimension = '{} x {} x {}' . format ( lsnap . geom . nxtot , lsnap . geom . nytot , lsnap . geom . nztot )
elif lsnap . geom ... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : TaskActionsContext for this TaskActionsInstance
: rtype : twilio . rest . autopilot . v1 . assistant . task . task _ actio... | if self . _context is None :
self . _context = TaskActionsContext ( self . _version , assistant_sid = self . _solution [ 'assistant_sid' ] , task_sid = self . _solution [ 'task_sid' ] , )
return self . _context |
def align_orthologous_genes_pairwise ( self , gapopen = 10 , gapextend = 0.5 ) :
"""For each gene in the base strain , run a pairwise alignment for all orthologous gene sequences to it .""" | for ref_gene in tqdm ( self . reference_gempro . genes ) :
if len ( ref_gene . protein . sequences ) > 1 :
alignment_dir = op . join ( self . sequences_by_gene_dir , ref_gene . id )
if not op . exists ( alignment_dir ) :
os . mkdir ( alignment_dir )
ref_gene . protein . pairwise_... |
def _updateItemComboBoxIndex ( self , item , column , num ) :
"""Callback for comboboxes : notifies us that a combobox for the given item and column has changed""" | item . _combobox_current_index [ column ] = num
item . _combobox_current_value [ column ] = item . _combobox_option_list [ column ] [ num ] [ 0 ] |
def register_listener_handle ( wxbot ) :
"""wechat _ sender 向 wxpy 注册控制消息 handler""" | from wxpy import TEXT
@ wxbot . bot . register ( wxbot . default_receiver , TEXT , except_self = False )
def sender_command_handle ( msg ) :
command_dict = { MESSAGE_REPORT_COMMAND : timeout_message_report ( ) , MESSAGE_STATUS_COMMAND : generate_run_info ( ) }
message = command_dict . get ( msg . text , None )
... |
def set_functions ( self , what , allfuncs ) :
"""Set the cards in the ` ` what ` ` builder to ` ` allfuncs ` `
: param what : a string , ' trigger ' , ' prereq ' , or ' action '
: param allfuncs : a sequence of triples of ( name , sourcecode , signature ) as taken by my
` ` get _ function _ cards ` ` method ... | setattr ( getattr ( self , '_{}_builder' . format ( what ) ) , 'decks' , self . get_functions_cards ( what , allfuncs ) ) |
def unregister_iq_request_handler ( self , type_ , payload_cls ) :
"""Unregister a coroutine previously registered with
: meth : ` register _ iq _ request _ handler ` .
: param type _ : IQ type to react to ( must be a request type ) .
: type type _ : : class : ` ~ structs . IQType `
: param payload _ cls : ... | type_ = self . _coerce_enum ( type_ , structs . IQType )
del self . _iq_request_map [ type_ , payload_cls ]
self . _logger . debug ( "iq request coroutine unregistered: type=%r, payload=%r" , type_ , payload_cls ) |
def shuffle_batch ( self , texts , labels = None , seed = None ) :
"""Shuffle a list of samples , as well as the labels if specified
Parameters
texts : list - like
List of samples to shuffle
labels : list - like ( optional )
List of labels to shuffle , should be correspondent to the samples given
seed :... | if seed != None :
random . seed ( seed )
index_shuf = list ( range ( len ( texts ) ) )
random . shuffle ( index_shuf )
texts = [ texts [ x ] for x in index_shuf ]
if labels == None :
return texts
labels = [ labels [ x ] for x in index_shuf ]
return texts , labels |
def is_error ( self ) :
"""Return true if the colum is a dimension""" | from ambry . valuetype . core import ROLE
return self . role == ROLE . ERROR |
def _determine_api_url ( self , platform , service , action ) :
"""This returns the Adyen API endpoint based on the provided platform ,
service and action .
Args :
platform ( str ) : Adyen platform , ie ' live ' or ' test ' .
service ( str ) : API service to place request through .
action ( str ) : the AP... | base_uri = settings . BASE_PAL_URL . format ( platform )
if service == "Recurring" :
api_version = settings . API_RECURRING_VERSION
elif service == "Payout" :
api_version = settings . API_PAYOUT_VERSION
else :
api_version = settings . API_PAYMENT_VERSION
return '/' . join ( [ base_uri , service , api_versio... |
def find_related_imports ( self , fullname ) :
"""Return a list of non - stdlib modules that are directly imported by
` fullname ` , plus their parents .
The list is determined by retrieving the source code of
` fullname ` , compiling it , and examining all IMPORT _ NAME ops .
: param fullname : Fully quali... | related = self . _related_cache . get ( fullname )
if related is not None :
return related
modpath , src , _ = self . get_module_source ( fullname )
if src is None :
return [ ]
maybe_names = list ( self . generate_parent_names ( fullname ) )
co = compile ( src , modpath , 'exec' )
for level , modname , namelist... |
def imagetransformer_ae_imagenet ( ) :
"""For 64x64 ImageNet . ~ 56M trainable variables .""" | hparams = imagetransformer_ae_cifar ( )
hparams . max_length = int ( 64 * 64 * 3 )
hparams . img_len = 64
hparams . num_heads = 4
# Heads are expensive on TPUs .
# Reduce architecture from 32x32 CIFAR - 10 in order to fit in memory .
hparams . num_decoder_layers = 8
hparams . num_compress_steps = 2
return hparams |
def one_of ( * args ) :
"Verifies that only one of the arguments is not None" | for i , arg in enumerate ( args ) :
if arg is not None :
for argh in args [ i + 1 : ] :
if argh is not None :
raise OperationError ( "Too many parameters" )
else :
return
raise OperationError ( "Insufficient parameters" ) |
def _get_validated_stages ( stages ) :
"""Validates stages of the workflow as a list of dictionaries .""" | if not isinstance ( stages , list ) :
raise WorkflowBuilderException ( "Stages must be specified as a list of dictionaries" )
validated_stages = [ ]
for index , stage in enumerate ( stages ) :
validated_stages . append ( _get_validated_stage ( stage , index ) )
return validated_stages |
def convert_inputfiles ( cls , folder = None , inputfile = None , session = None , lod_threshold = None , qtls_file = 'qtls.csv' , matrix_file = 'qtls_matrix.csv' , map_file = 'map.csv' ) :
"""Convert the input files present in the given folder or
inputfile .
This method creates the matrix representation of the... | if folder is None and inputfile is None :
raise MQ2Exception ( 'You must specify either a folder or an ' 'input file' )
if folder is not None : # pragma : no cover
if not os . path . isdir ( folder ) :
raise MQ2Exception ( 'The specified folder is actually ' 'not a folder' )
else :
inputfile... |
def import_attribute ( self , path ) :
"""Import an attribute from a module .""" | module = '.' . join ( path . split ( '.' ) [ : - 1 ] )
function = path . split ( '.' ) [ - 1 ]
module = importlib . import_module ( module )
return getattr ( module , function ) |
def signature_algo ( self ) :
""": return :
A unicode string of " rsassa _ pkcs1v15 " , " rsassa _ pss " , " dsa " or
" ecdsa " """ | algorithm = self [ 'algorithm' ] . native
algo_map = { 'md2_rsa' : 'rsassa_pkcs1v15' , 'md5_rsa' : 'rsassa_pkcs1v15' , 'sha1_rsa' : 'rsassa_pkcs1v15' , 'sha224_rsa' : 'rsassa_pkcs1v15' , 'sha256_rsa' : 'rsassa_pkcs1v15' , 'sha384_rsa' : 'rsassa_pkcs1v15' , 'sha512_rsa' : 'rsassa_pkcs1v15' , 'rsassa_pkcs1v15' : 'rsassa_... |
def convert ( self ) :
"""User - facing conversion method . Returns pandoc document as a list of
lines .""" | lines = [ ]
pages = self . flatten_pages ( self . config [ 'pages' ] )
f_exclude = mkdocs_pandoc . filters . exclude . ExcludeFilter ( exclude = self . exclude )
f_include = mkdocs_pandoc . filters . include . IncludeFilter ( base_path = self . config [ 'docs_dir' ] , encoding = self . encoding )
# First , do the proce... |
def rmean ( self ) :
"""Calculates the mean rank of a TT - vector .""" | if not _np . all ( self . n ) :
return 0
# Solving quadratic equation ar ^ 2 + br + c = 0;
a = _np . sum ( self . n [ 1 : - 1 ] )
b = self . n [ 0 ] + self . n [ - 1 ]
c = - _np . sum ( self . n * self . r [ 1 : ] * self . r [ : - 1 ] )
D = b ** 2 - 4 * a * c
r = 0.5 * ( - b + _np . sqrt ( D ) ) / a
return r |
def start ( client , container , interactive = True , stdout = None , stderr = None , stdin = None , logs = None ) :
"""Present the PTY of the container inside the current process .
This is just a wrapper for PseudoTerminal ( client , container ) . start ( )""" | operation = RunOperation ( client , container , interactive = interactive , stdout = stdout , stderr = stderr , stdin = stdin , logs = logs )
PseudoTerminal ( client , operation ) . start ( ) |
def setIsochronous ( self , endpoint , buffer_or_len , callback = None , user_data = None , timeout = 0 , iso_transfer_length_list = None ) :
"""Setup transfer for isochronous use .
endpoint
Endpoint to submit transfer to . Defines transfer direction ( see
ENDPOINT _ OUT and ENDPOINT _ IN ) ) .
buffer _ or ... | if self . __submitted :
raise ValueError ( 'Cannot alter a submitted transfer' )
num_iso_packets = self . __num_iso_packets
if num_iso_packets == 0 :
raise TypeError ( 'This transfer canot be used for isochronous I/O. ' 'You must get another one with a non-zero iso_packets ' 'parameter.' )
if self . __doomed :
... |
def get_path_from_stream ( strm ) :
"""Try to get file path from given file or file - like object ' strm ' .
: param strm : A file or file - like object
: return : Path of given file or file - like object or None
: raises : ValueError
> > > assert _ _ file _ _ = = get _ path _ from _ stream ( open ( _ _ fil... | if not is_file_stream ( strm ) :
raise ValueError ( "Given object does not look a file/file-like " "object: %r" % strm )
path = getattr ( strm , "name" , None )
if path is not None :
try :
return normpath ( path )
except ( TypeError , ValueError ) :
pass
return None |
def gaussian_noise ( x , severity = 1 ) :
"""Gaussian noise corruption to images .
Args :
x : numpy array , uncorrupted image , assumed to have uint8 pixel in [ 0,255 ] .
severity : integer , severity of corruption .
Returns :
numpy array , image with uint8 pixels in [ 0,255 ] . Added Gaussian noise .""" | c = [ .08 , .12 , 0.18 , 0.26 , 0.38 ] [ severity - 1 ]
x = np . array ( x ) / 255.
x_clip = np . clip ( x + np . random . normal ( size = x . shape , scale = c ) , 0 , 1 ) * 255
return around_and_astype ( x_clip ) |
def is_quoted ( value ) :
'''Return a single or double quote , if a string is wrapped in extra quotes .
Otherwise return an empty string .''' | ret = ''
if isinstance ( value , six . string_types ) and value [ 0 ] == value [ - 1 ] and value . startswith ( ( '\'' , '"' ) ) :
ret = value [ 0 ]
return ret |
def set_style ( self , input_feeds ) :
"""Set target style variables .
Expected usage :
style _ loss = StyleLoss ( style _ layers )
init _ op = tf . global _ variables _ initializer ( )
init _ op . run ( )
feeds = { . . . session . run ( ) ' feeds ' argument that will make ' style _ layers '
tensors eva... | sess = tf . get_default_session ( )
computed = sess . run ( self . input_grams , input_feeds )
for v , g in zip ( self . target_vars , computed ) :
v . load ( g ) |
def check_elastic ( self ) :
'''Checks if we need to break moderation in order to maintain our desired
throttle limit
@ return : True if we need to break moderation''' | if self . elastic and self . elastic_kick_in == self . limit :
value = self . redis_conn . zcard ( self . window_key )
if self . limit - value > self . elastic_buffer :
return True
return False |
def stop_ec2_instance ( client , resource ) :
"""Stop an EC2 Instance
This function will attempt to stop a running instance .
Args :
client ( : obj : ` boto3 . session . Session . client ` ) : A boto3 client object
resource ( : obj : ` Resource ` ) : The resource object to stop
Returns :
` ActionStatus ... | instance = EC2Instance . get ( resource . id )
if instance . state in ( 'stopped' , 'terminated' ) :
return ActionStatus . IGNORED , { }
client . stop_instances ( InstanceIds = [ resource . id ] )
return ActionStatus . SUCCEED , { 'instance_type' : resource . instance_type , 'public_ip' : resource . public_ip } |
def get_month_from_date_str ( date_str , lang = DEFAULT_DATE_LANG ) :
"""Find the month name for the given locale , in the given string .
Returns a tuple ` ` ( number _ of _ month , abbr _ name ) ` ` .""" | date_str = date_str . lower ( )
with calendar . different_locale ( LOCALES [ lang ] ) :
month_abbrs = list ( calendar . month_abbr )
for seq , abbr in enumerate ( month_abbrs ) :
if abbr and abbr . lower ( ) in date_str :
return seq , abbr
return ( ) |
def schema ( self , table ) :
"""Print the table schema
Parameters
table : str
The table name""" | try :
pprint ( self . query ( "PRAGMA table_info({})" . format ( table ) , fmt = 'table' ) )
except ValueError :
print ( 'Table {} not found' . format ( table ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.