signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def ui_extensions ( self ) :
"""Provides access to UI extensions management methods .
API reference : https : / / www . contentful . com / developers / docs / references / content - management - api / # / reference / ui - extensions
: return : : class : ` EnvironmentUIExtensionsProxy < contentful _ management .... | return EnvironmentUIExtensionsProxy ( self . _client , self . space . id , self . id ) |
def _save_config ( jira_url , username , password , error_reporting ) :
"""Saves the username and password to the config""" | # Delete what is there before we re - write . New user means new everything
os . path . exists ( _config ) and os . remove ( _config )
config = ConfigParser . SafeConfigParser ( )
config . read ( _config )
if not config . has_section ( 'jira' ) :
config . add_section ( 'jira' )
if 'http' not in jira_url :
jira_... |
def get_all_access_keys ( self , user_name , marker = None , max_items = None ) :
"""Get all access keys associated with an account .
: type user _ name : string
: param user _ name : The username of the user
: type marker : string
: param marker : Use this only when paginating results and only in
follow ... | params = { 'UserName' : user_name }
if marker :
params [ 'Marker' ] = marker
if max_items :
params [ 'MaxItems' ] = max_items
return self . get_response ( 'ListAccessKeys' , params , list_marker = 'AccessKeyMetadata' ) |
def get_queryset ( self ) :
"""Optionally restricts the returned purchases analysis track to
a given analysis and / or a given item ,
by filtering against ` analysis ` and ` item ` query parameters in the URL .
The query parameters values should be the uuid of the analysis or of the item""" | queryset = self . model . objects . all ( )
analysis_uuid = self . request . query_params . get ( 'analysis' , None )
item_uuid = self . request . query_params . get ( 'item' , None )
if analysis_uuid is not None :
queryset = queryset . filter ( analysis__uuid__startswith = analysis_uuid )
if item_uuid is not None ... |
def parse_host ( hosts ) :
"""Parsing the hosts parameter ,
* currently support only one host
: param hosts : the hosts json to parse
: return : the full host and the authentication if exists""" | hosts = EsParser . _normalize_hosts ( hosts )
host = hosts [ 0 ]
host_name = host [ HostParsing . HOST ]
host_port = host [ HostParsing . PORT ]
auth = None
if HostParsing . HTTP_AUTH in host :
http_auth = host [ HostParsing . HTTP_AUTH ]
user_pass = http_auth . split ( ':' )
auth = ( user_pass [ 0 ] , user... |
def messages ( self ) :
'''a generator yielding the : class : ` Message ` structures in the index''' | # the file contains the fixed - size file header followed by
# fixed - size message structures . start after the file header and
# then simply return the message structures in sequence until the
# end of the file .
offset = self . LENGTH
while offset < len ( self . mmap ) :
yield Message ( mm = self . mmap , offset... |
def build_precache_map ( config ) :
"""Build a mapping of contexts and models from the configuration""" | precache_map = { }
ss_name = config [ 'ores' ] [ 'scoring_system' ]
for context in config [ 'scoring_systems' ] [ ss_name ] [ 'scoring_contexts' ] :
precache_map [ context ] = { }
for model in config [ 'scoring_contexts' ] [ context ] . get ( 'precache' , [ ] ) :
precached_config = config [ 'scoring_con... |
def cli ( ctx , verbose ) :
"""ChemDataExtractor command line interface .""" | log . debug ( 'ChemDataExtractor v%s' % __version__ )
logging . basicConfig ( level = logging . DEBUG if verbose else logging . INFO )
logging . getLogger ( 'requests' ) . setLevel ( logging . WARN )
ctx . obj = { } |
def split ( self , value = 10 , unit = None ) : # noqa : F811
"""Splits Flights in several legs .
By default , Flights are split if no value is given during 10 minutes .""" | if type ( value ) == int and unit is None : # default value is 10 m
unit = "m"
for data in _split ( self . data , value , unit ) :
yield self . __class__ ( data ) |
def set_value ( request , name , value ) :
"""For manual shortcut links to perform set value actions""" | obj = service . system . namespace . get ( name , None )
if not obj or service . read_only :
raise Http404
obj . status = value
if service . redirect_from_setters :
return HttpResponseRedirect ( reverse ( 'set_ready' , args = ( name , value ) ) )
else :
return set_ready ( request , name , value ) |
def get_network_for_participant ( self , participant ) :
"""Find a network for a participant .
If no networks are available , None will be returned . By default
participants can participate only once in each network and participants
first complete networks with ` role = " practice " ` before doing all other
... | key = participant . id
networks_with_space = ( Network . query . filter_by ( full = False ) . order_by ( Network . id ) . all ( ) )
networks_participated_in = [ node . network_id for node in Node . query . with_entities ( Node . network_id ) . filter_by ( participant_id = participant . id ) . all ( ) ]
legal_networks =... |
def format_grib_name ( self , selected_variable ) :
"""Assigns name to grib2 message number with name ' unknown ' . Names based on NOAA grib2 abbreviations .
Args :
selected _ variable ( str ) : name of selected variable for loading
Names :
3 : LCDC : Low Cloud Cover
4 : MCDC : Medium Cloud Cover
5 : HC... | names = self . unknown_names
units = self . unknown_units
for key , value in names . items ( ) :
if selected_variable == value :
Id = key
u = units [ key ]
return Id , u |
def canonizePath ( path ) :
"""Returns the absolute , normalized , real path of something .
This takes care of symbolic links , redundant separators , etc .""" | return os . path . abspath ( os . path . normpath ( os . path . realpath ( path ) ) ) |
def EasyProgressMeter ( title , current_value , max_value , * args , orientation = None , bar_color = ( None , None ) , button_color = None , size = DEFAULT_PROGRESS_BAR_SIZE , border_width = None ) :
'''A ONE - LINE progress meter . Add to your code where ever you need a meter . No need for a second
function cal... | local_border_width = DEFAULT_PROGRESS_BAR_BORDER_WIDTH if not border_width else border_width
# STATIC VARIABLE !
# This is a very clever form of static variable using a function attribute
# If the variable doesn ' t yet exist , then it will create it and initialize with the 3rd parameter
EasyProgressMeter . Data = geta... |
def create_theta ( self ) :
"""Returns the set of inner angles ( between 0 and pi )
reconstructed from point coordinates .
Also returns the corners corresponding to each entry of theta .""" | import itertools
from pylocus . basics_angles import from_0_to_pi
theta = np . empty ( ( self . M , ) )
corners = np . empty ( ( self . M , 3 ) )
k = 0
indices = np . arange ( self . N )
for triangle in itertools . combinations ( indices , 3 ) :
for counter , idx in enumerate ( triangle ) :
corner = idx
... |
def get_link_mappings ( link_id , link_2_id = None , ** kwargs ) :
"""Get all the resource attribute mappings in a network . If another network
is specified , only return the mappings between the two networks .""" | qry = db . DBSession . query ( ResourceAttrMap ) . filter ( or_ ( and_ ( ResourceAttrMap . resource_attr_id_a == ResourceAttr . id , ResourceAttr . link_id == link_id ) , and_ ( ResourceAttrMap . resource_attr_id_b == ResourceAttr . id , ResourceAttr . link_id == link_id ) ) )
if link_2_id is not None :
aliased_ra ... |
def is_valid ( self , qstr = None ) :
"""Return True if string is valid""" | if qstr is None :
qstr = self . currentText ( )
return is_module_or_package ( to_text_string ( qstr ) ) |
def _render ( self , contexts , partials ) :
"""render section""" | val = self . _lookup ( self . value , contexts )
if not val : # false value
return EMPTYSTRING
# normally json has types : number / string / list / map
# but python has more , so we decide that map and string should not iterate
# by default , other do .
if hasattr ( val , "__iter__" ) and not isinstance ( val , ( s... |
def get_parent_dir ( name ) :
"""Get the parent directory of a filename .""" | parent_dir = os . path . dirname ( os . path . dirname ( name ) )
if parent_dir :
return parent_dir
return os . path . abspath ( '.' ) |
def _handle_content ( self , relpath , params ) :
"""Render file content for pretty display .""" | abspath = os . path . normpath ( os . path . join ( self . _root , relpath ) )
if os . path . isfile ( abspath ) :
with open ( abspath , 'rb' ) as infile :
content = infile . read ( )
else :
content = 'No file found at {}' . format ( abspath ) . encode ( 'utf-8' )
content_type = mimetypes . guess_type (... |
def read ( self , cnt = None ) :
"""Read all or specified amount of data from archive entry .""" | # sanitize cnt
if cnt is None or cnt < 0 :
cnt = self . _remain
elif cnt > self . _remain :
cnt = self . _remain
if cnt == 0 :
return EMPTY
# actual read
data = self . _read ( cnt )
if data :
self . _md_context . update ( data )
self . _remain -= len ( data )
if len ( data ) != cnt :
raise BadRa... |
def encry_decry_chunk ( chunk , key , algo , bool_encry , assoc_data ) :
"""When bool _ encry is True , encrypt a chunk of the file with the key and a randomly generated nonce . When it is False ,
the function extract the nonce from the cipherchunk ( first 16 bytes ) , and decrypt the rest of the chunk .
: para... | engine = botan . cipher ( algo = algo , encrypt = bool_encry )
engine . set_key ( key = key )
engine . set_assoc_data ( assoc_data )
if bool_encry is True :
nonce = generate_nonce_timestamp ( )
engine . start ( nonce = nonce )
return nonce + engine . finish ( chunk )
else :
nonce = chunk [ : __nonce_len... |
def get_published ( name , config_path = _DEFAULT_CONFIG_PATH , endpoint = '' , prefix = None ) :
'''Get the details of a published repository .
: param str name : The distribution name of the published repository .
: param str config _ path : The path to the configuration file for the aptly instance .
: para... | _validate_config ( config_path )
ret = dict ( )
sources = list ( )
cmd = [ 'publish' , 'show' , '-config={}' . format ( config_path ) , name ]
if prefix :
cmd . append ( '{}:{}' . format ( endpoint , prefix ) )
cmd_ret = _cmd_run ( cmd )
ret = _parse_show_output ( cmd_ret = cmd_ret )
if ret :
log . debug ( 'Fou... |
def get_tunnel_statistics_input_page_cursor ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_tunnel_statistics = ET . Element ( "get_tunnel_statistics" )
config = get_tunnel_statistics
input = ET . SubElement ( get_tunnel_statistics , "input" )
page_cursor = ET . SubElement ( input , "page-cursor" )
page_cursor . text = kwargs . pop ( 'page_cursor' )
callback = kwargs . p... |
def get_fipscode ( self , obj ) :
"""County FIPS code""" | if obj . division . level . name == DivisionLevel . COUNTY :
return obj . division . code
return None |
def ekacld ( handle , segno , column , dvals , entszs , nlflgs , rcptrs , wkindx ) :
"""Add an entire double precision column to an EK segment .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ekacld _ c . html
: param handle : EK file handle .
: type handle : int
: param seg... | handle = ctypes . c_int ( handle )
segno = ctypes . c_int ( segno )
column = stypes . stringToCharP ( column )
dvals = stypes . toDoubleVector ( dvals )
entszs = stypes . toIntVector ( entszs )
nlflgs = stypes . toIntVector ( nlflgs )
rcptrs = stypes . toIntVector ( rcptrs )
wkindx = stypes . toIntVector ( wkindx )
lib... |
def add_ipv4addr ( self , ipv4addr ) :
"""Add an IPv4 address to the host .
: param str ipv4addr : The IP address to add .
: raises : ValueError""" | for addr in self . ipv4addrs :
if ( ( isinstance ( addr , dict ) and addr [ 'ipv4addr' ] == ipv4addr ) or ( isinstance ( addr , HostIPv4 ) and addr . ipv4addr == ipv4addr ) ) :
raise ValueError ( 'Already exists' )
self . ipv4addrs . append ( { 'ipv4addr' : ipv4addr } ) |
def read_block ( self , size = None , from_date = None ) :
"""Read author commits by Quarter , Org and Project .
: param from _ date : not used here . Incremental mode not supported yet .
: param size : not used here .
: return : DataFrame with commit count per author , split by quarter , org and project .""" | # Get quarters corresponding to All items ( Incremental mode NOT SUPPORTED )
quarters = self . __quarters ( )
for quarter in quarters :
logger . info ( self . __log_prefix + " Quarter: " + str ( quarter ) )
date_range = { self . _timeframe_field : { 'gte' : quarter . start_time , 'lte' : quarter . end_time } }
... |
def get_dependencies ( self , module ) :
'''get _ dependencies
High - level api : Get dependency infomationa of a module .
Parameters
module : ` str `
Module name that is inquired about .
Returns
tuple
A tuple with two elements : a set of imports and a set of depends .''' | imports = set ( )
for m in list ( filter ( lambda i : i . get ( 'id' ) == module , self . dependencies . findall ( './module' ) ) ) :
imports . update ( set ( i . get ( 'module' ) for i in m . findall ( './imports/import' ) ) )
depends = set ( )
for m in self . dependencies . getchildren ( ) :
if list ( filter ... |
def set_from_config_file ( self , filename ) :
"""Loads lint config from a ini - style config file""" | if not os . path . exists ( filename ) :
raise LintConfigError ( u"Invalid file path: {0}" . format ( filename ) )
self . _config_path = os . path . abspath ( filename )
try :
parser = ConfigParser ( )
parser . read ( filename )
for section_name in parser . sections ( ) :
for option_name , optio... |
def create_recordings_dictionary ( list_selected , pronunciation_dictionary_filename , out_dictionary_filename , htk_trace , additional_dictionary_filenames = [ ] ) :
"""Create a pronunciation dictionary specific to a list of recordings""" | temp_words_fd , temp_words_file = tempfile . mkstemp ( )
words = set ( )
for recording in list_selected :
words |= set ( [ w . upper ( ) for w in get_words_from_recording ( recording ) ] )
with codecs . open ( temp_words_file , 'w' , 'utf-8' ) as f :
f . writelines ( [ u'{}\n' . format ( w ) for w in sorted ( l... |
def do_execute ( self ) :
"""The actual execution of the actor .
: return : None if successful , otherwise error message
: rtype : str""" | result = None
data = self . input . payload
pltdataset . line_plot ( data , atts = self . resolve_option ( "attributes" ) , percent = float ( self . resolve_option ( "percent" ) ) , seed = int ( self . resolve_option ( "seed" ) ) , title = self . resolve_option ( "title" ) , outfile = self . resolve_option ( "outfile" ... |
def _wrap_callback_parse_stream_data ( subscription , on_data , message ) :
"""Wraps an ( optional ) user callback to parse StreamData
from a WebSocket data message""" | if ( message . type == message . DATA and message . data . type == yamcs_pb2 . STREAM_DATA ) :
stream_data = getattr ( message . data , 'streamData' )
on_data ( StreamData ( stream_data ) ) |
def build_address_distance ( number = None , street = None , city = None , state = None , zip_code = None ) :
"""Construct a composite distance appropriate for matching address data . NOTE :
this utility function does not guarantee that the output composite distance
will work with a particular dataset and model... | # # Validate inputs
for param in [ number , street , city , state , zip_code ] :
if param is not None and not isinstance ( param , str ) :
raise TypeError ( "All inputs must be strings. Each parameter is " + "intended to be the name of an SFrame column." )
# # Figure out features for levenshtein distance .
... |
def update_or_create ( cls , with_status = False , ** kwargs ) :
"""Update or create static netlink . DNS entry differences are not
resolved , instead any entries provided will be the final state
for this netlink . If the intent is to add / remove DNS entries
you can use the : meth : ` ~ domain _ server _ add... | dns_address = kwargs . pop ( 'domain_server_address' , [ ] )
element , updated , created = super ( StaticNetlink , cls ) . update_or_create ( with_status = True , defer_update = True , ** kwargs )
if not created :
if dns_address :
new_entries = RankedDNSAddress ( [ ] )
new_entries . add ( dns_addres... |
def render ( self , xml , context , raise_on_errors = True ) :
"""Render xml string and apply XSLT transfomation with context""" | if xml :
self . xml = xml
# render XSL
self . render_xsl ( self . root , context )
# create root XSL sheet
xsl_ns = self . namespaces [ 'xsl' ]
rootName = etree . QName ( xsl_ns , 'stylesheet' )
root = etree . Element ( rootName , nsmap = { 'xsl' : xsl_ns } )
sheet = etree . ElementTree ... |
def orderLattice ( self , beamline ) :
"""ordering element type appearance sequence for each element of beamline
e . g . after getFullBeamline ,
lattice list [ ' q ' , ' Q01 ' , ' B11 ' , ' Q02 ' , ' B22 ' ] will return :
[ ( u ' q ' , u ' CHARGE ' , 1 ) ,
( u ' q01 ' , u ' QUAD ' , 1 ) ,
( u ' b11 ' , u ... | ele_name_list = self . getFullBeamline ( beamline , extend = True )
ele_type_list = [ self . getElementType ( ele ) for ele in ele_name_list ]
order_list = [ 0 ] * len ( ele_name_list )
ele_type_dict_uniq = dict ( zip ( ele_type_list , order_list ) )
for idx in xrange ( len ( ele_name_list ) ) :
etype = ele_type_li... |
def all_fields ( self ) :
"""Returns a list of all fields . Subtype fields come before this type ' s
fields .""" | fields = [ ]
if self . parent_type :
fields . extend ( self . parent_type . all_fields )
fields . extend ( [ f for f in self . fields ] )
return fields |
def get_safe_type ( self ) :
"""Determines the type of ESA product .
In 2016 ESA changed structure and naming of data . Therefore the class must
distinguish between old product type and compact ( new ) product type .
: return : type of ESA product
: rtype : constants . EsaSafeType
: raises : ValueError""" | product_type = self . product_id . split ( '_' ) [ 1 ]
if product_type . startswith ( 'MSI' ) :
return EsaSafeType . COMPACT_TYPE
if product_type in [ 'OPER' , 'USER' ] :
return EsaSafeType . OLD_TYPE
raise ValueError ( 'Unrecognized product type of product id {}' . format ( self . product_id ) ) |
def new ( self , length , file_type , parent , log_block_size ) : # type : ( int , str , Optional [ UDFFileEntry ] , int ) - > None
'''A method to create a new UDF File Entry .
Parameters :
length - The ( starting ) length of this UDF File Entry ; this is ignored
if this is a symlink .
file _ type - The typ... | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'UDF File Entry already initialized' )
if file_type not in ( 'dir' , 'file' , 'symlink' ) :
raise pycdlibexception . PyCdlibInternalError ( "UDF File Entry file type must be one of 'dir', 'file', or 'symlink'" )
self . desc_tag = UDFTag ( ... |
def get_actions_from_items ( self , items ) :
"""Reimplemented OneColumnTree method""" | fromcursor_act = create_action ( self , text = _ ( 'Go to cursor position' ) , icon = ima . icon ( 'fromcursor' ) , triggered = self . go_to_cursor_position )
fullpath_act = create_action ( self , text = _ ( 'Show absolute path' ) , toggled = self . toggle_fullpath_mode )
fullpath_act . setChecked ( self . show_fullpat... |
def recon_all ( subj_id , anatomies ) :
'''Run the ` ` recon _ all ` ` script''' | if not environ_setup :
setup_freesurfer ( )
if isinstance ( anatomies , basestring ) :
anatomies = [ anatomies ]
nl . run ( [ os . path . join ( freesurfer_home , 'bin' , 'recon-all' ) , '-all' , '-subjid' , subj_id ] + [ [ '-i' , anat ] for anat in anatomies ] ) |
def send_raw ( self , message ) :
"""Sends a raw binary message to the Pebble . No processing will be applied , but any transport framing should be
omitted .
: param message : The message to send to the pebble .
: type message : bytes""" | if self . log_protocol_level :
logger . log ( self . log_protocol_level , "-> %s" , hexlify ( message ) . decode ( ) )
self . transport . send_packet ( message ) |
def setup_versioneer ( ) :
"""Generate ( temporarily ) versioneer . py file in project root directory
: return :""" | try : # assume versioneer . py was generated using " versioneer install " command
import versioneer
versioneer . get_version ( )
except ImportError : # it looks versioneer . py is missing
# lets assume that versioneer package is installed
# and versioneer binary is present in $ PATH
import subprocess
tr... |
def create_ntlm_session ( self , alias , url , auth , headers = { } , cookies = { } , timeout = None , proxies = None , verify = False , debug = 0 , max_retries = 3 , backoff_factor = 0.10 , disable_warnings = 0 ) :
"""Create Session : create a HTTP session to a server
` ` url ` ` Base url of the server
` ` ali... | if not HttpNtlmAuth :
raise AssertionError ( 'Requests NTLM module not loaded' )
elif len ( auth ) != 3 :
raise AssertionError ( 'Incorrect number of authentication arguments' ' - expected 3, got {}' . format ( len ( auth ) ) )
else :
ntlm_auth = HttpNtlmAuth ( '{}\\{}' . format ( auth [ 0 ] , auth [ 1 ] ) ... |
def K_pc_1 ( self ) :
'Koopman operator on the modified basis ( PC | 1)' | self . _check_estimated ( )
if not self . _estimation_finished :
self . _finish_estimation ( )
return self . _K |
def _split_dimension ( text ) :
"""Returns the number and unit from the given piece of text as a pair .
> > > _ split _ dimension ( ' 1pt ' )
(1 , ' pt ' )
> > > _ split _ dimension ( ' 1 pt ' )
(1 , ' pt ' )
> > > _ split _ dimension ( ' 1 \t pt ' )
(1 , ' pt ' )
> > > _ split _ dimension ( ' 1 \t pt... | match = _dimension_finder . match ( text )
if not match :
raise DimensionError ( "Can't parse dimension '%s'." % text )
number = match . group ( 1 )
unit = match . group ( 4 )
if '.' in number :
return ( float ( number ) , unit )
else :
return ( int ( number ) , unit ) |
def rescan_all ( host ) :
'''List scsi devices
CLI Example :
. . code - block : : bash
salt ' * ' scsi . rescan _ all 0''' | if os . path . isdir ( '/sys/class/scsi_host/host{0}' . format ( host ) ) :
cmd = 'echo "- - -" > /sys/class/scsi_host/host{0}/scan' . format ( host )
else :
return 'Host {0} does not exist' . format ( host )
return __salt__ [ 'cmd.run' ] ( cmd ) . splitlines ( ) |
def handle_notification ( self , data ) :
"""Handle Callback from a Bluetooth ( GATT ) request .""" | _LOGGER . debug ( "Received notification from the device.." )
if data [ 0 ] == PROP_INFO_RETURN and data [ 1 ] == 1 :
_LOGGER . debug ( "Got status: %s" % codecs . encode ( data , 'hex' ) )
status = Status . parse ( data )
_LOGGER . debug ( "Parsed status: %s" , status )
self . _raw_mode = status . mode... |
def validate ( src , ** kwargs ) :
"""Validate OCRD - ZIP
SRC must exist an be an OCRD - ZIP , either a ZIP file or a directory .""" | resolver = Resolver ( )
validator = OcrdZipValidator ( resolver , src )
report = validator . validate ( ** kwargs )
print ( report )
if not report . is_valid :
sys . exit ( 1 ) |
def get_choices ( self ) :
"""stub""" | # ideally would return a displayText object in text . . . except for legacy
# use cases like OEA , it expects a text string .
choices = { }
# for region _ name , region _ choices in self . my _ osid _ object . object _ map [ ' choices ' ] . items ( ) :
for region_name , region_choices in self . my_osid_object . _my_map... |
def _get_edges ( self ) :
"""Compute the edges for the reference graph .
The function returns a set of tuples ( id ( a ) , id ( b ) , ref ) if a
references b with the referent ' ref ' .""" | idset = set ( [ id ( x ) for x in self . objects ] )
self . edges = set ( [ ] )
for n in self . objects :
refset = set ( [ id ( x ) for x in get_referents ( n ) ] )
for ref in refset . intersection ( idset ) :
label = ''
members = None
if isinstance ( n , dict ) :
members = n... |
def models_to_table ( obj , params = True ) :
r"""Converts a ModelsDict object to a ReST compatible table
Parameters
obj : OpenPNM object
Any object that has a ` ` models ` ` attribute
params : boolean
Indicates whether or not to include a list of parameter
values in the table . Set to False for just a ... | if not hasattr ( obj , 'models' ) :
raise Exception ( 'Received object does not have any models' )
row = '+' + '-' * 4 + '+' + '-' * 22 + '+' + '-' * 18 + '+' + '-' * 26 + '+'
fmt = '{0:1s} {1:2s} {2:1s} {3:20s} {4:1s} {5:16s} {6:1s} {7:24s} {8:1s}'
lines = [ ]
lines . append ( row )
lines . append ( fmt . format (... |
def first_older_than_second ( version_a , version_b ) :
"""Tests for the NSS version string in the first parameter being less
recent than the second ( a < b ) . Tag order is RTM > RC > BETA > * .
Works with hg tags like " NSS _ 3_7_9 _ RTM " and version strings reported by
nsINSSVersion , like " 3.18 Basic EC... | a = nssversion . to_ints ( version_a )
b = nssversion . to_ints ( version_b )
# must be of equal length
assert len ( a ) == len ( b )
# Compare each version component , bail out on difference
for i in xrange ( len ( a ) ) :
if b [ i ] < a [ i ] :
return False
if b [ i ] > a [ i ] :
return True
r... |
def output_best_scores ( self , best_epoch_str : str ) -> None :
"""Output best scores to the filesystem""" | BEST_SCORES_FILENAME = "best_scores.txt"
with open ( os . path . join ( self . exp_dir , BEST_SCORES_FILENAME ) , "w" , encoding = ENCODING ) as best_f :
print ( best_epoch_str , file = best_f , flush = True ) |
def register ( linter ) :
"""Register all transforms with the linter .""" | MANAGER . register_transform ( astroid . Call , transform_declare )
MANAGER . register_transform ( astroid . Module , transform_conf_module ) |
def is_finalized ( self ) :
"""Return True if the bundle is installed .""" | return self . state == self . STATES . FINALIZED or self . state == self . STATES . INSTALLED |
def make_dist ( toxinidir , toxdir , package ) :
"""zip up the package into the toxdir .""" | dist = os . path . join ( toxdir , "dist" )
# Suppress warnings .
success = safe_shell_out ( [ "python" , "setup.py" , "sdist" , "--quiet" , "--formats=zip" , "--dist-dir" , dist ] , cwd = toxinidir )
if success :
return os . path . join ( dist , package + ".zip" ) |
def inverse_unit_transform ( self , x , ** kwargs ) :
"""Go from the parameter value to the unit coordinate using the cdf .""" | if len ( kwargs ) > 0 :
self . update ( ** kwargs )
return self . distribution . cdf ( x , * self . args , loc = self . loc , scale = self . scale ) |
def handle_data_sending ( self , source_file , source_len , info_cb = DEFAULT_MESSAGE_CALLBACK , progress_callback = None , timeout_ms = None ) :
"""Handles the protocol for sending data to the device .
Arguments :
source _ file : File - object to read from for the device .
source _ len : Amount of data , in ... | accepted_size = self . _accept_responses ( 'DATA' , info_cb , timeout_ms = timeout_ms )
accepted_size = binascii . unhexlify ( accepted_size [ : 8 ] )
accepted_size , = struct . unpack ( '>I' , accepted_size )
if accepted_size != source_len :
raise usb_exceptions . FastbootTransferError ( 'Device refused to downloa... |
def get_excel_workbook ( api_data , result_info_key , identifier_keys ) :
"""Generates an Excel workbook object given api _ data returned by the Analytics API
Args :
api _ data : Analytics API data as a list of dicts ( one per identifier )
result _ info _ key : the key in api _ data dicts that contains the da... | cleaned_data = [ ]
for item_data in api_data :
result_info = item_data . pop ( result_info_key , { } )
cleaned_item_data = { }
if 'meta' in item_data :
meta = item_data . pop ( 'meta' )
cleaned_item_data [ 'meta' ] = meta
for key in item_data :
cleaned_item_data [ key ] = item_da... |
def cdpop ( ) :
"""Return the last directory .
Returns absolute path to new working directory .""" | if len ( _cdhist ) >= 1 :
old = _cdhist . pop ( )
# Pop from history .
os . chdir ( old )
return old
else :
return pwd ( ) |
def predict_from_variants ( self , variants , transcript_expression_dict = None , gene_expression_dict = None ) :
"""Predict epitopes from a Variant collection , filtering options , and
optional gene and transcript expression data .
Parameters
variants : varcode . VariantCollection
transcript _ expression _... | # pre - filter variants by checking if any of the genes or
# transcripts they overlap have sufficient expression .
# I ' m tolerating the redundancy of this code since it ' s much cheaper
# to filter a variant * before * trying to predict its impact / effect
# on the protein sequence .
variants = apply_variant_expressi... |
async def has_started ( self ) :
"""Whether the handler has completed all start up processes such as
establishing the connection , session , link and authentication , and
is not ready to process messages .
* * This function is now deprecated and will be removed in v2.0 + . * *
: rtype : bool""" | # pylint : disable = protected - access
timeout = False
auth_in_progress = False
if self . _handler . _connection . cbs :
timeout , auth_in_progress = await self . _handler . _auth . handle_token_async ( )
if timeout :
raise EventHubError ( "Authorization timeout." )
if auth_in_progress :
return False
if no... |
def groups ( self ) :
"""Return an iterator over ( name , value ) pairs for groups only .
Examples
> > > import zarr
> > > g1 = zarr . group ( )
> > > g2 = g1 . create _ group ( ' foo ' )
> > > g3 = g1 . create _ group ( ' bar ' )
> > > d1 = g1 . create _ dataset ( ' baz ' , shape = 100 , chunks = 10)
... | for key in sorted ( listdir ( self . _store , self . _path ) ) :
path = self . _key_prefix + key
if contains_group ( self . _store , path ) :
yield key , Group ( self . _store , path = path , read_only = self . _read_only , chunk_store = self . _chunk_store , cache_attrs = self . attrs . cache , synchro... |
def from_api_repr ( cls , resource ) :
"""Factory : construct a table given its API representation
Args :
resource ( Dict [ str , object ] ) :
Table resource representation from the API
Returns :
google . cloud . bigquery . table . Table : Table parsed from ` ` resource ` ` .
Raises :
KeyError :
If ... | from google . cloud . bigquery import dataset
if ( "tableReference" not in resource or "tableId" not in resource [ "tableReference" ] ) :
raise KeyError ( "Resource lacks required identity information:" '["tableReference"]["tableId"]' )
project_id = resource [ "tableReference" ] [ "projectId" ]
table_id = resource ... |
def message_handler ( stream , type_ , from_ , cb ) :
"""Context manager to temporarily register a callback to handle messages on a
: class : ` StanzaStream ` .
: param stream : Stanza stream to register the coroutine at
: type stream : : class : ` StanzaStream `
: param type _ : Message type to listen for ... | stream . register_message_callback ( type_ , from_ , cb , )
try :
yield
finally :
stream . unregister_message_callback ( type_ , from_ , ) |
def increase_priority ( self , infohash_list ) :
"""Increase priority of torrents .
: param infohash _ list : Single or list ( ) of infohashes .""" | data = self . _process_infohash_list ( infohash_list )
return self . _post ( 'command/increasePrio' , data = data ) |
def _wns_send ( uri , data , wns_type = "wns/toast" , application_id = None ) :
"""Sends a notification data and authentication to WNS .
: param uri : str : The device ' s unique notification URI
: param data : dict : The notification data to be sent .
: return :""" | access_token = _wns_authenticate ( application_id = application_id )
content_type = "text/xml"
if wns_type == "wns/raw" :
content_type = "application/octet-stream"
headers = { # content _ type is " text / xml " ( toast / badge / tile ) | " application / octet - stream " ( raw )
"Content-Type" : content_type , "Auth... |
def protocols ( self ) :
"""Returns a list of available load balancing protocols .""" | if self . _protocols is None :
uri = "/loadbalancers/protocols"
resp , body = self . method_get ( uri )
self . _protocols = [ proto [ "name" ] for proto in body [ "protocols" ] ]
return self . _protocols |
def update ( self ) :
"""Fetch and parse stats""" | self . frontends = [ ]
self . backends = [ ]
self . listeners = [ ]
csv = [ l for l in self . _fetch ( ) . strip ( ' #' ) . split ( '\n' ) if l ]
if self . failed :
return
# read fields header to create keys
self . fields = [ f for f in csv . pop ( 0 ) . split ( ',' ) if f ]
# add frontends and backends first
for l... |
def compareKmerProfiles ( profileFN1 , profileFN2 ) :
'''This function takes two kmer profiles and compare them for similarity .
@ param profileFN1 - the first kmer - profile to compare to
@ param profileFN2 - the second kmer - profile to compare to
@ return - a tuple of the form ( 1 - norm , 2 - norm , sum o... | fp1 = open ( profileFN1 , 'r' )
fp2 = open ( profileFN2 , 'r' )
oneNorm = 0
twoNorm = 0
sumDeltas = 0
dotProduct = 0
tot1 = float ( fp1 . readline ( ) . strip ( '\n' ) . split ( ',' ) [ 1 ] )
tot2 = float ( fp2 . readline ( ) . strip ( '\n' ) . split ( ',' ) [ 1 ] )
( seq1 , count1 ) = parseProfileLine ( fp1 )
( seq2 ,... |
def get_pythainlp_data_path ( ) -> str :
"""Return full path where PyThaiNLP keeps its ( downloaded ) data""" | path = os . path . join ( os . path . expanduser ( "~" ) , PYTHAINLP_DATA_DIR )
if not os . path . exists ( path ) :
os . makedirs ( path )
return path |
def to_unicode ( value ) :
"""Returns a unicode string from a string , using UTF - 8 to decode if needed .
This function comes from ` Tornado ` _ .
: param value :
A unicode or string to be decoded .
: returns :
The decoded string .""" | if isinstance ( value , str ) :
return value . decode ( 'utf-8' )
assert isinstance ( value , unicode )
return value |
def run ( ) :
"""Run cpp coverage .""" | import json
import os
import sys
from . import coverage , report
args = coverage . create_args ( sys . argv [ 1 : ] )
if args . verbose :
print ( 'encodings: {}' . format ( args . encodings ) )
yml = parse_yaml_config ( args )
if not args . repo_token : # try get token from yaml first
args . repo_token = yml . ... |
def list_ranges ( self , share_name , directory_name , file_name , start_range = None , end_range = None , timeout = None ) :
'''Retrieves the valid ranges for a file .
: param str share _ name :
Name of existing share .
: param str directory _ name :
The path to the directory .
: param str file _ name : ... | _validate_not_none ( 'share_name' , share_name )
_validate_not_none ( 'file_name' , file_name )
request = HTTPRequest ( )
request . method = 'GET'
request . host = self . _get_host ( )
request . path = _get_path ( share_name , directory_name , file_name )
request . query = [ ( 'comp' , 'rangelist' ) , ( 'timeout' , _in... |
def to_generics ( instruments , weights ) :
"""Map tradeable instruments to generics given weights and tradeable
instrument holdings . This is solving the equation Ax = b where A is the
weights , and b is the instrument holdings . When Ax = b has no solution we
solve for x ' such that Ax ' is closest to b in ... | if not isinstance ( weights , dict ) :
weights = { "" : weights }
allocations = [ ]
unmapped_instr = instruments . index
for key in weights :
w = weights [ key ]
# may not always have instrument holdings for a set of weights so allow
# weights to be a superset of instruments , drop values where no
#... |
def update_entry_attributes ( sender , instance , ** kwargs ) :
"""Updates attributes for Entry instance corresponding to
specified instance .
: param sender : the sending class .
: param instance : the instance being saved .""" | from . . models import Entry
entry = Entry . objects . get_for_model ( instance ) [ 0 ]
default_url = getattr ( instance , 'get_absolute_url' , '' )
entry . title = getattr ( instance , 'title' , str ( instance ) )
entry . url = getattr ( instance , 'url' , default_url )
entry . live = bool ( getattr ( instance , 'live... |
def parse_selection ( lexer : Lexer ) -> SelectionNode :
"""Selection : Field or FragmentSpread or InlineFragment""" | return ( parse_fragment if peek ( lexer , TokenKind . SPREAD ) else parse_field ) ( lexer ) |
def intervals ( self , reverse , thr = 0 ) :
"""return a list of ( 0 - based half - open ) intervals representing the match regions of the cigar
for example 4MD4M2DM with reverse = False will produce [ ( 0,4 ) , ( 5,9 ) , ( 11,12 ) ]
4MD4M2DM with reverse = True will produce [ ( 0,1 ) , ( 3,7 ) , ( 8,12 ) ] ( =... | d = [ ( thr , thr ) ]
dl = 0
for tup in self . cigar_iter ( reverse ) :
if tup [ 1 ] == "D" :
dl = tup [ 0 ]
else :
s = d [ - 1 ] [ 1 ] + dl
d . append ( ( s , s + tup [ 0 ] ) )
assert d [ 0 ] == ( thr , thr )
# assert that nr . of Ms in the interval = = sum of produced intervals
assert ... |
def parse_content ( self , content ) :
"""All child classes inherit this function to parse XML file automatically .
It will call the function : func : ` parse _ dom ` by default to
parser all necessary data to : attr : ` data ` and the : attr : ` xmlns ` ( the
default namespace ) is ready for this function ."... | self . dom = self . xmlns = None
self . data = { }
# ignore empty xml file
if len ( content ) > 3 :
self . raw = '\n' . join ( content )
self . dom = ET . fromstring ( self . raw )
self . xmlns = self . dom . tag . strip ( "{" ) . split ( "}" ) [ 0 ] if all ( c in self . dom . tag for c in [ "{" , "}" ] ) e... |
def preprocess ( string ) :
"""Preprocess string to transform all diacritics and remove other special characters than appropriate
: param string :
: return :""" | string = unicode ( string , encoding = "utf-8" )
# convert diacritics to simpler forms
string = regex1 . sub ( lambda x : accents [ x . group ( ) ] , string )
# remove all rest of the unwanted characters
return regex2 . sub ( '' , string ) . encode ( 'utf-8' ) |
async def chunks ( source , n ) :
"""Generate chunks of size ` ` n ` ` from an asynchronous sequence .
The chunks are lists , and the last chunk might contain less than ` ` n ` `
elements .""" | async with streamcontext ( source ) as streamer :
async for first in streamer :
xs = select . take ( create . preserve ( streamer ) , n - 1 )
yield [ first ] + await aggregate . list ( xs ) |
def _get_connection ( self ) :
"""Returns our cached LDAPObject , which may or may not be bound .""" | if self . _connection is None :
uri = self . settings . SERVER_URI
if callable ( uri ) :
if func_supports_parameter ( uri , "request" ) :
uri = uri ( self . _request )
else :
warnings . warn ( "Update AUTH_LDAP_SERVER_URI callable %s.%s to accept " "a positional `request`... |
def get_icon ( brain_or_object , html_tag = True ) :
"""Get the icon of the content object
: param brain _ or _ object : A single catalog brain or content object
: type brain _ or _ object : ATContentType / DexterityContentType / CatalogBrain
: param html _ tag : A value of ' True ' returns the HTML tag , els... | # Manual approach , because ` plone . app . layout . getIcon ` does not reliable
# work for Bika Contents coming from other catalogs than the
# ` portal _ catalog `
portal_types = get_tool ( "portal_types" )
fti = portal_types . getTypeInfo ( brain_or_object . portal_type )
icon = fti . getIcon ( )
if not icon :
re... |
def flush_evicted_objects_unsafe ( ) :
"""This removes some critical state from the Redis shards .
In a multitenant environment , this will flush metadata for all jobs , which
may be undesirable .
This removes all of the metadata for objects that have been evicted . This
can be used to try to address out - ... | ray . worker . global_worker . check_connected ( )
for shard_index in range ( len ( ray . global_state . redis_clients ) ) :
_flush_evicted_objects_unsafe_shard ( shard_index ) |
def is20 ( msg ) :
"""Check if a message is likely to be BDS code 2,0
Args :
msg ( String ) : 28 bytes hexadecimal message string
Returns :
bool : True or False""" | if allzeros ( msg ) :
return False
d = hex2bin ( data ( msg ) )
if d [ 0 : 8 ] != '00100000' :
return False
cs = cs20 ( msg )
if '#' in cs :
return False
return True |
def nohtml ( s ) :
"""Return copy of ` ` s ` ` that will not treat ` ` ' < . . . > ' ` ` as DOT HTML string in quoting .
Args :
s : String in which leading ` ` ' < ' ` ` and trailing ` ` ' > ' ` ` should be treated as literal .
Raises :
TypeError : If ` ` s ` ` is not a ` ` str ` ` on Python 3 , or a ` ` st... | try :
subcls = NOHTML [ type ( s ) ]
except KeyError :
raise TypeError ( '%r does not have one of the required types: %r' % ( s , list ( NOHTML ) ) )
return subcls ( s ) |
def exists ( self , share_name , directory_name = None , file_name = None , timeout = None , snapshot = None ) :
'''Returns a boolean indicating whether the share exists if only share name is
given . If directory _ name is specificed a boolean will be returned indicating
if the directory exists . If file _ name... | _validate_not_none ( 'share_name' , share_name )
try :
if file_name is not None :
self . get_file_properties ( share_name , directory_name , file_name , timeout = timeout , snapshot = snapshot )
elif directory_name is not None :
self . get_directory_properties ( share_name , directory_name , tim... |
def _replace_greek_characters ( line ) :
"""Replace greek characters in a string .""" | for greek_char , replacement in iteritems ( _GREEK_REPLACEMENTS ) :
try :
line = line . replace ( greek_char , replacement )
except UnicodeDecodeError :
current_app . logger . exception ( "Unicode decoding error." )
return ""
return line |
def format_image ( self , image , image_format , ** kwargs ) :
"""Returns an image in the request format""" | if image_format in ( 'png' , 'jpg' , 'jpeg' , 'gif' , 'bmp' , 'webp' ) :
if image_format != 'webp' and FORCE_WEBP : # Always return WebP when supported by the browser
accept = self . request . META [ 'HTTP_ACCEPT' ] . split ( ',' )
if 'image/webp' in accept :
image = image . convert ( 'R... |
def fix_colocation_after_import ( input_map , absolute_import_scope ) :
"""Fixes colocation attributes after import according to input _ map .
This function is meant to be called after importing a GraphDef , in order
to rewrite colocate _ with constrains analogous to how inputs to ops
are rewritten by input _... | attr_map = _build_colocation_attr_map ( input_map , absolute_import_scope )
_apply_colocation_attr_map ( attr_map , absolute_import_scope ) |
def get_bool ( self , key , default = None ) :
"""Same as : meth : ` dict . get ` , but the value is converted to a bool .
The boolean value is considered , respectively , : obj : ` True ` or
: obj : ` False ` if the string is equal , ignoring case , to
` ` ' true ' ` ` or ` ` ' false ' ` ` .""" | v = self . get ( key , default )
if v != default :
v = v . strip ( ) . lower ( )
if v == 'true' :
v = True
elif v == 'false' :
v = False
elif default is None :
raise RuntimeError ( "invalid bool string: %s" % v )
else :
v = default
return v |
def readinto ( self , buf , * , start = 0 , end = None ) :
"""Read into ` ` buf ` ` from the device . The number of bytes read will be the
length of ` ` buf ` ` .
If ` ` start ` ` or ` ` end ` ` is provided , then the buffer will be sliced
as if ` ` buf [ start : end ] ` ` . This will not cause an allocation ... | if end is None :
end = len ( buf )
for i in range ( start , end ) :
buf [ i ] = self . _readbyte ( ) |
def native ( self ) :
"""The native Python datatype representation of this value
: return :
An integer or None""" | if self . contents is None :
return None
if self . _native is None :
self . _native = int_from_bytes ( self . _merge_chunks ( ) )
return self . _native |
def clear ( self , delete_thumbnails = False ) :
"""We can clear the database more efficiently using the prefix here rather
than calling : meth : ` _ delete _ raw ` .""" | prefix = settings . THUMBNAIL_KEY_PREFIX
for key in self . _find_keys_raw ( prefix ) :
self . cache . delete ( key )
KVStoreModel . objects . filter ( key__startswith = prefix ) . delete ( )
if delete_thumbnails :
self . delete_all_thumbnail_files ( ) |
def blockwise_inner_join ( data , left , foreign_key , right , force_repeat = None , foreign_key_name = None ) :
"""Perform a blockwise inner join .
Perform a blockwise inner join from names specified in ` ` left ` ` to
` ` right ` ` via ` ` foreign _ key ` ` : left - > foreign _ key - > right .
Parameters
... | if isinstance ( foreign_key , string_types ) :
foreign_key = data [ foreign_key ]
return _blockwise_inner_join ( data , left , foreign_key , right , force_repeat , foreign_key_name ) |
def _process_response ( response ) :
"""Make the request and handle exception processing""" | # Read the response as JSON
try :
data = response . json ( )
except ValueError :
_log_and_raise_exception ( 'Invalid response' , response . text )
# Default case , Got proper response
if response . status_code == 200 :
return { 'headers' : response . headers , 'data' : data }
return _raise_error_from_respon... |
def conf_from_dict ( conf_dict ) :
'''Creates a configuration dictionary from a dictionary .
: param conf _ dict : The configuration dictionary .''' | conf = Config ( filename = conf_dict . get ( '__file__' , '' ) )
for k , v in six . iteritems ( conf_dict ) :
if k . startswith ( '__' ) :
continue
elif inspect . ismodule ( v ) :
continue
conf [ k ] = v
return conf |
def ensureGeoIndex ( self , fields ) :
"""Creates a geo index if it does not already exist , and returns it""" | data = { "type" : "geo" , "fields" : fields , }
ind = Index ( self , creationData = data )
self . indexes [ "geo" ] [ ind . infos [ "id" ] ] = ind
return ind |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.