signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def backprop ( self , input_data , targets , cache = None ) :
"""Backpropagate through the logistic layer .
* * Parameters : * *
input _ data : ` ` GPUArray ` `
Inpute data to compute activations for .
targets : ` ` GPUArray ` `
The target values of the units .
cache : list of ` ` GPUArray ` `
Cache o... | if cache is not None :
activations = cache
else :
activations = self . feed_forward ( input_data , prediction = False )
if activations . shape != targets . shape :
raise ValueError ( 'Activations (shape = %s) and targets (shape = %s) are different sizes' % ( activations . shape , targets . shape ) )
delta =... |
def write ( self ) -> None :
"""Call method | NetCDFFile . write | of all handled | NetCDFFile | objects .""" | if self . folders :
init = hydpy . pub . timegrids . init
timeunits = init . firstdate . to_cfunits ( 'hours' )
timepoints = init . to_timepoints ( 'hours' )
for folder in self . folders . values ( ) :
for file_ in folder . values ( ) :
file_ . write ( timeunits , timepoints ) |
def unload_ipython_extension ( ip ) :
"""Unload me as an IPython extension
Use : % unload _ ext wurlitzer""" | if not getattr ( ip , 'kernel' ) :
return
ip . events . unregister ( 'pre_execute' , sys_pipes_forever )
ip . events . unregister ( 'post_execute' , stop_sys_pipes ) |
def audit_ghosts ( self ) :
"""compare the list of configured jobs with the jobs in the state""" | print_header = True
for app_name in self . _get_ghosts ( ) :
if print_header :
print_header = False
print ( "Found the following in the state database but not " "available as a configured job:" )
print "\t%s" % ( app_name , ) |
def remove_empty_dirs ( path = None ) :
"""Recursively delete empty directories ; return True if everything was deleted .""" | if not path :
path = settings . MEDIA_ROOT
if not os . path . isdir ( path ) :
return False
listdir = [ os . path . join ( path , filename ) for filename in os . listdir ( path ) ]
if all ( list ( map ( remove_empty_dirs , listdir ) ) ) :
os . rmdir ( path )
return True
else :
return False |
def _prepare_files ( self , encoding ) :
"""private function to prepare content for paramType = form with File""" | content_type = 'multipart/form-data'
if self . __op . consumes and content_type not in self . __op . consumes :
raise errs . SchemaError ( 'content type {0} does not present in {1}' . format ( content_type , self . __op . consumes ) )
boundary = uuid4 ( ) . hex
content_type += '; boundary={0}'
content_type = conten... |
def tell ( self , msg , action , learnas = '' ) :
"""Tell what type of we are to process and what should be done
with that message . This includes setting or removing a local
or a remote database ( learning , reporting , forgetting , revoking ) .""" | action = _check_action ( action )
mode = learnas . upper ( )
headers = { 'Message-class' : '' , 'Set' : 'local' , }
if action == 'learn' :
if mode == 'SPAM' :
headers [ 'Message-class' ] = 'spam'
elif mode in [ 'HAM' , 'NOTSPAM' , 'NOT_SPAM' ] :
headers [ 'Message-class' ] = 'ham'
else :
... |
def map_lazy ( self , target : Callable , map_iter : Sequence [ Any ] = None , * , map_args : Sequence [ Sequence [ Any ] ] = None , args : Sequence = None , map_kwargs : Sequence [ Mapping [ str , Any ] ] = None , kwargs : Mapping = None , pass_state : bool = False , num_chunks : int = None , ) -> SequenceTaskResult :... | if num_chunks is None :
num_chunks = multiprocessing . cpu_count ( )
lengths = [ len ( i ) for i in ( map_iter , map_args , map_kwargs ) if i is not None ]
assert ( lengths ) , "At least one of `map_iter`, `map_args`, or `map_kwargs` must be provided as a non-empty Sequence."
length = min ( lengths )
assert ( lengt... |
def get_multiple_devices ( self , rids ) :
"""Implements the ' Get Multiple Devices ' API .
Param rids : a python list object of device rids .
http : / / docs . exosite . com / portals / # get - multiple - devices""" | headers = { 'User-Agent' : self . user_agent ( ) , 'Content-Type' : self . content_type ( ) }
headers . update ( self . headers ( ) )
url = self . portals_url ( ) + '/users/_this/devices/' + str ( rids ) . replace ( "'" , "" ) . replace ( ' ' , '' )
# print ( " URL : { 0 } " . format ( url ) )
r = requests . get ( url ... |
def prod ( self ) :
"""Summary
Returns :
TYPE : Description""" | return LazyOpResult ( grizzly_impl . aggr ( self . expr , "*" , 1 , self . weld_type ) , self . weld_type , 0 ) |
def url ( self , var , default = NOTSET ) :
""": rtype : urlparse . ParseResult""" | return self . get_value ( var , cast = urlparse , default = default , parse_default = True ) |
def _require_min_api_version ( self , version ) :
"""Raise an exception if the version of the api is less than the given version .
@ param version : The minimum required version .""" | actual_version = self . _get_resource_root ( ) . version
version = max ( version , self . _api_version ( ) )
if actual_version < version :
raise Exception ( "API version %s is required but %s is in use." % ( version , actual_version ) ) |
def _validator ( key , val , env ) :
"""Validates the given value to be either ' 0 ' or ' 1 ' .
This is usable as ' validator ' for SCons ' Variables .""" | if not env [ key ] in ( True , False ) :
raise SCons . Errors . UserError ( 'Invalid value for boolean option %s: %s' % ( key , env [ key ] ) ) |
def check_convert_string ( obj , name = None , no_leading_trailing_whitespace = True , no_whitespace = False , no_newline = True , whole_word = False , min_len = 1 , max_len = 0 ) :
"""Ensures the provided object can be interpreted as a unicode string , optionally with
additional restrictions imposed . By default... | if not name :
name = 'Argument'
obj = ensure_unicode ( obj , name = name )
if no_whitespace :
if _PATTERN_WHITESPACE . match ( obj ) :
raise ValueError ( '%s cannot contain whitespace' % name )
elif no_leading_trailing_whitespace and _PATTERN_LEAD_TRAIL_WHITESPACE . match ( obj ) :
raise ValueError ... |
def plus ( self , a ) :
"""Add .""" | return Vector ( self . x + a . x , self . y + a . y , self . z + a . z ) |
def setup ( self , timezone = None ) : # pylint : disable = arguments - differ
"""Sets up the _ timezone attribute .
Args :
timezone : Timezone name ( optional )""" | self . _timezone = timezone
self . _output_path = tempfile . mkdtemp ( ) |
def db_wb010 ( self , value = None ) :
"""Corresponds to IDD Field ` db _ wb010 `
mean coincident dry - bulb temperature to
Wet - bulb temperature corresponding to 1.0 % annual cumulative frequency of occurrence
Args :
value ( float ) : value for IDD Field ` db _ wb010 `
Unit : C
if ` value ` is None it... | if value is not None :
try :
value = float ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type float ' 'for field `db_wb010`' . format ( value ) )
self . _db_wb010 = value |
def get ( self , layer , where = "1 = 1" , fields = [ ] , count_only = False , srid = '4326' ) :
"""Gets a layer and returns it as honest to God GeoJSON .
WHERE 1 = 1 causes us to get everything . We use OBJECTID in the WHERE clause
to paginate , so don ' t use OBJECTID in your WHERE clause unless you ' re goin... | base_where = where
# By default we grab all of the fields . Technically I think
# we can just do " * " for all fields , but I found this was buggy in
# the KMZ mode . I ' d rather be explicit .
fields = fields or self . enumerate_layer_fields ( layer )
jsobj = self . get_json ( layer , where , fields , count_only , sri... |
def _connected ( self , link_uri ) :
"""This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded .""" | print ( 'Connected to %s' % link_uri )
self . _is_link_open = True
self . _connect_event . set ( ) |
def signals_blocker ( instance , attribute , * args , ** kwargs ) :
"""Blocks given instance signals before calling the given attribute with given arguments and then unblocks the signals .
: param instance : Instance object .
: type instance : QObject
: param attribute : Attribute to call .
: type attribute... | value = None
try :
hasattr ( instance , "blockSignals" ) and instance . blockSignals ( True )
value = attribute ( * args , ** kwargs )
finally :
hasattr ( instance , "blockSignals" ) and instance . blockSignals ( False )
return value |
def sqllab ( self ) :
"""SQL Editor""" | d = { 'defaultDbId' : config . get ( 'SQLLAB_DEFAULT_DBID' ) , 'common' : self . common_bootsrap_payload ( ) , }
return self . render_template ( 'superset/basic.html' , entry = 'sqllab' , bootstrap_data = json . dumps ( d , default = utils . json_iso_dttm_ser ) , ) |
def read_until_done ( self , command , timeout = None ) :
"""Yield messages read until we receive a ' DONE ' command .
Read messages of the given command until we receive a ' DONE ' command . If a
command different than the requested one is received , an AdbProtocolError
is raised .
Args :
command : The c... | message = self . read_message ( timeout )
while message . command != 'DONE' :
message . assert_command_is ( command )
yield message
message = self . read_message ( timeout ) |
def convert_vec2_to_vec4 ( scale , data ) :
"""transforms an array of 2d coords into 4d""" | it = iter ( data )
while True :
yield next ( it ) * scale
yield next ( it ) * scale
yield 0.0
yield 1.0 |
def parse_spss_datafile ( path , ** kwargs ) :
"""Parse spss data file
Arguments :
path { str } - - path al fichero de cabecera .
* * kwargs { [ dict ] } - - otros argumentos que puedan llegar""" | data_clean = [ ]
with codecs . open ( path , 'r' , kwargs . get ( 'encoding' , 'latin-1' ) ) as file_ :
raw_file = file_ . read ( )
data_clean = raw_file . split ( '\r\n' )
return exclude_empty_values ( data_clean ) |
def decorate_function ( self , name , decorator ) :
"""Decorate function with given name with given decorator .
: param str name : Name of the function .
: param callable decorator : Decorator callback .""" | self . functions [ name ] = decorator ( self . functions [ name ] ) |
def _original_images ( self , ** kwargs ) :
"""A list of the original images .
: returns : A list of the original images .
: rtype : : class : ` typing . Sequence ` \ [ : class : ` Image ` ]""" | def test ( image ) :
if not image . original :
return False
for filter , value in kwargs . items ( ) :
if getattr ( image , filter ) != value :
return False
return True
if Session . object_session ( self . instance ) is None :
images = [ ]
for image , store in self . _sto... |
def set_tolerance_value ( self , tolerance ) :
"""stub""" | # include index because could be multiple response / tolerance pairs
if not isinstance ( tolerance , float ) :
raise InvalidArgument ( 'tolerance value must be a decimal' )
self . add_decimal_value ( tolerance , 'tolerance' ) |
def check_internet_on ( secrets_file_path ) :
"""If internet on and USB unplugged , returns true . Else , continues to wait . . .""" | while True :
if internet_on ( ) is True and not os . path . exists ( secrets_file_path ) :
break
else :
print ( "Turn on your internet and unplug your USB to continue..." )
time . sleep ( 10 )
return True |
def _extract_parameters_from_properties ( properties ) :
"""Extracts parameters from properties .""" | new_properties = { }
parameters = [ ]
for key , value in six . iteritems ( properties ) :
if key . startswith ( _PARAMETER_PREFIX ) :
parameters . append ( ( key . replace ( _PARAMETER_PREFIX , "" ) , value ) )
else :
new_properties [ key ] = value
return new_properties , sorted ( parameters ) |
def authenticate_ldap ( self , username , password ) :
"""Get user by username and password and their permissions .
: param username : Username . String with a minimum 3 and maximum of 45 characters
: param password : User password . String with a minimum 3 and maximum of 45 characters
: return : Following di... | user_map = dict ( )
user_map [ 'username' ] = username
user_map [ 'password' ] = password
code , xml = self . submit ( { 'user' : user_map } , 'POST' , 'authenticate/ldap/' )
return self . response ( code , xml ) |
def create ( cls , train_ds , valid_ds , test_ds = None , path : PathOrStr = '.' , bs : int = 32 , val_bs : int = None , pad_idx = 1 , pad_first = True , device : torch . device = None , no_check : bool = False , backwards : bool = False , ** dl_kwargs ) -> DataBunch :
"Function that transform the ` datasets ` in a... | datasets = cls . _init_ds ( train_ds , valid_ds , test_ds )
val_bs = ifnone ( val_bs , bs )
collate_fn = partial ( pad_collate , pad_idx = pad_idx , pad_first = pad_first , backwards = backwards )
train_sampler = SortishSampler ( datasets [ 0 ] . x , key = lambda t : len ( datasets [ 0 ] [ t ] [ 0 ] . data ) , bs = bs ... |
def _Triple ( S ) :
"""Procedure to calculate the triple point pressure and temperature for
seawater
Parameters
S : float
Salinity , [ kg / kg ]
Returns
prop : dict
Dictionary with the triple point properties :
* Tt : Triple point temperature , [ K ]
* Pt : Triple point pressure , [ MPa ]
Refere... | def f ( parr ) :
T , P = parr
pw = _Region1 ( T , P )
gw = pw [ "h" ] - T * pw [ "s" ]
pv = _Region2 ( T , P )
gv = pv [ "h" ] - T * pv [ "s" ]
gih = _Ice ( T , P ) [ "g" ]
ps = SeaWater . _saline ( T , P , S )
return - ps [ "g" ] + S * ps [ "gs" ] - gw + gih , - ps [ "g" ] + S * ps [ "g... |
def get_secret ( self , filename , secret , type_ = None ) :
"""Checks to see whether a secret is found in the collection .
: type filename : str
: param filename : the file to search in .
: type secret : str
: param secret : secret hash of secret to search for .
: type type _ : str
: param type _ : typ... | if filename not in self . data :
return None
if type_ : # Optimized lookup , because we know the type of secret
# ( and therefore , its hash )
tmp_secret = PotentialSecret ( type_ , filename , secret = 'will be overriden' )
tmp_secret . secret_hash = secret
if tmp_secret in self . data [ filename ] :
... |
def get_copy_folder_location ( ) :
"""Try to locate the Copy folder .
Returns :
( str ) Full path to the current Copy folder""" | copy_settings_path = 'Library/Application Support/Copy Agent/config.db'
copy_home = None
copy_settings = os . path . join ( os . environ [ 'HOME' ] , copy_settings_path )
if os . path . isfile ( copy_settings ) :
database = sqlite3 . connect ( copy_settings )
if database :
cur = database . cursor ( )
... |
def save ( obj , filename , protocol = 4 ) :
"""Serialize an object to disk using pickle protocol .
Args :
obj : The object to serialize .
filename : Path to the output file .
protocol : Version of the pickle protocol .""" | with open ( filename , 'wb' ) as f :
pickle . dump ( obj , f , protocol = protocol ) |
def group ( iterable , key ) :
"""groupby which sorts the input , discards the key and returns the output
as a sequence of lists .""" | for _ , grouped in groupby ( sorted ( iterable , key = key ) , key = key ) :
yield list ( grouped ) |
def write_ndjson ( filename , data_iterable , append = False , ** kwargs ) :
"""Generator that writes newline - delimited json to a file and returns items
from an iterable .""" | write_mode = "ab" if append else "wb"
logger . info ( "writing to file {}" . format ( filename ) )
with codecs . open ( filename , write_mode , "utf-8" ) as outfile :
for item in data_iterable :
outfile . write ( json . dumps ( item ) + "\n" )
yield item |
def _onShortcutCutLine ( self ) :
"""Cut selected lines to the clipboard""" | lines = self . lines [ self . _selectedLinesSlice ( ) ]
self . _onShortcutCopyLine ( )
self . _onShortcutDeleteLine ( ) |
def time_partitioning ( self ) :
"""google . cloud . bigquery . table . TimePartitioning : Specifies time - based
partitioning for the destination table .""" | prop = self . _get_sub_prop ( "timePartitioning" )
if prop is not None :
prop = TimePartitioning . from_api_repr ( prop )
return prop |
def snmp_server_user_auth_password ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
snmp_server = ET . SubElement ( config , "snmp-server" , xmlns = "urn:brocade.com:mgmt:brocade-snmp" )
user = ET . SubElement ( snmp_server , "user" )
username_key = ET . SubElement ( user , "username" )
username_key . text = kwargs . pop ( 'username' )
auth_password = ET . SubElement... |
def fix_tag ( value ) :
"""Make a FIX tag value from string , bytes , or integer .""" | if sys . version_info [ 0 ] == 2 :
return bytes ( value )
else :
if type ( value ) == bytes :
return value
elif type ( value ) == str :
return value . encode ( 'ASCII' )
return str ( value ) . encode ( 'ASCII' ) |
def facts ( ) :
'''Displays the facts gathered during the connection .
These facts are also stored in Salt grains .
CLI Example :
. . code - block : : bash
salt ' device _ name ' junos . facts''' | ret = { }
try :
ret [ 'facts' ] = __proxy__ [ 'junos.get_serialized_facts' ] ( )
ret [ 'out' ] = True
except Exception as exception :
ret [ 'message' ] = 'Could not display facts due to "{0}"' . format ( exception )
ret [ 'out' ] = False
return ret |
def get_numeric_score_increment_metadata ( self ) :
"""Gets the metadata for the lowest numeric score .
return : ( osid . Metadata ) - metadata for the lowest numeric score
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template
metadata = dict ( self . _mdata [ 'numeric_score_increment' ] )
metadata . update ( { 'existing_decimal_values' : self . _my_map [ 'numericScoreIncrement' ] } )
return Metadata ( ** metadata ) |
def bump_version ( ctx , new_version , version_part = None , dry_run = False ) :
"""Bump version ( to prepare a new release ) .""" | version_part = version_part or "minor"
if dry_run :
ctx = DryRunContext ( ctx )
ctx . run ( "bumpversion --new-version={} {}" . format ( new_version , version_part ) ) |
def _edges_classify_intersection9 ( ) :
"""The edges for the curved polygon intersection used below .
Helper for : func : ` classify _ intersection9 ` .""" | edges1 = ( bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 32.0 , 30.0 ] , [ 20.0 , 25.0 ] ] ) ) , bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 30.0 , 25.0 , 20.0 ] , [ 25.0 , 20.0 , 20.0 ] ] ) ) , bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 20.0 , 25.0 , 30.0 ] , [ 20.0 , 20.0 , 15.0 ] ]... |
def add ( self , item_numid , collect_type , shared , session ) :
'''taobao . favorite . add 添加收藏夹
根据用户昵称和收藏目标的数字id以及收藏目标的类型 , 实现收藏行为''' | request = TOPRequest ( 'taobao.favorite.add' )
request [ 'item_numid' ] = item_numid
request [ 'collect_type' ] = collect_type
request [ 'shared' ] = shared
self . create ( self . execute ( request , session ) )
return self . result |
def get_theme_style ( theme ) :
"""read - in theme style info and populate styleMap ( dict of with mpl . rcParams )
and clist ( list of hex codes passed to color cylcler )
: : Arguments : :
theme ( str ) : theme name
: : Returns : :
styleMap ( dict ) : dict containing theme - specific colors for figure pr... | styleMap , clist = get_default_jtstyle ( )
if theme == 'default' :
return styleMap , clist
syntaxVars = [ '@yellow:' , '@orange:' , '@red:' , '@magenta:' , '@violet:' , '@blue:' , '@cyan:' , '@green:' ]
get_hex_code = lambda line : line . split ( ':' ) [ - 1 ] . split ( ';' ) [ 0 ] [ - 7 : ]
themeFile = os . path .... |
def is_same ( self , DataStruct ) :
"""判断是否相同""" | if self . type == DataStruct . type and self . if_fq == DataStruct . if_fq :
return True
else :
return False |
def forwards ( self , orm ) :
"Write your forwards methods here ." | for qde_xtf in orm [ 'xtf.QualifiedDublinCoreElement' ] . objects . all ( ) . order_by ( 'id' ) :
qde = orm . QualifiedDublinCoreElement ( )
qde . content = qde_xtf . content
qde . term = qde_xtf . term
qde . qualifier = qde_xtf . qualifier
# import pdb ; pdb . set _ trace ( )
c = orm [ 'content... |
def native ( self , value , context = None ) :
"""Convert a value from a foriegn type ( i . e . web - safe ) to Python - native .""" | value = super ( ) . native ( value , context )
if value is None :
return
try :
return self . ingress ( value )
except Exception as e :
raise Concern ( "Unable to transform incoming value: {0}" , str ( e ) ) |
def states_close ( state0 : State , state1 : State , tolerance : float = TOLERANCE ) -> bool :
"""Returns True if states are almost identical .
Closeness is measured with the metric Fubini - Study angle .""" | return vectors_close ( state0 . vec , state1 . vec , tolerance ) |
def send ( self , topic , value = None , key = None , headers = None , partition = None , timestamp_ms = None ) :
"""Publish a message to a topic .
Arguments :
topic ( str ) : topic where the message will be published
value ( optional ) : message value . Must be type bytes , or be
serializable to bytes via ... | assert value is not None or self . config [ 'api_version' ] >= ( 0 , 8 , 1 ) , ( 'Null messages require kafka >= 0.8.1' )
assert not ( value is None and key is None ) , 'Need at least one: key or value'
key_bytes = value_bytes = None
try :
self . _wait_on_metadata ( topic , self . config [ 'max_block_ms' ] / 1000.0... |
def traceroute ( self , destination , source = c . TRACEROUTE_SOURCE , ttl = c . TRACEROUTE_TTL , timeout = c . TRACEROUTE_TIMEOUT , vrf = c . TRACEROUTE_VRF , ) :
"""Executes traceroute on the device and returns a dictionary with the result .
: param destination : Host or IP Address of the destination
: param ... | raise NotImplementedError |
def do_get_next ( endpoint , access_token ) :
'''Do an HTTP GET request , follow the nextLink chain and return JSON .
Args :
endpoint ( str ) : Azure Resource Manager management endpoint .
access _ token ( str ) : A valid Azure authentication token .
Returns :
HTTP response . JSON body .''' | headers = { "Authorization" : 'Bearer ' + access_token }
headers [ 'User-Agent' ] = get_user_agent ( )
looping = True
value_list = [ ]
vm_dict = { }
while looping :
get_return = requests . get ( endpoint , headers = headers ) . json ( )
if not 'value' in get_return :
return get_return
if not 'nextLi... |
def required_types ( self ) :
"""Set of names of types which the Command depends on .""" | required_types = set ( x . type for x in self . params )
required_types . add ( self . type )
required_types . discard ( None )
return required_types |
def _query_by_distro ( self , table_name ) :
"""Query for download data broken down by OS distribution , for one day .
: param table _ name : table name to query against
: type table _ name : str
: return : dict of download information by distro ; keys are project name ,
values are a dict of distro names to... | logger . info ( 'Querying for downloads by distro in table %s' , table_name )
q = "SELECT file.project, details.distro.name, " "details.distro.version, COUNT(*) as dl_count " "%s " "%s " "GROUP BY file.project, details.distro.name, " "details.distro.version;" % ( self . _from_for_table ( table_name ) , self . _where_fo... |
def parse_frame ( self , buf : bytes ) -> List [ Tuple [ bool , Optional [ int ] , bytearray , Optional [ bool ] ] ] :
"""Return the next frame from the socket .""" | frames = [ ]
if self . _tail :
buf , self . _tail = self . _tail + buf , b''
start_pos = 0
buf_length = len ( buf )
while True : # read header
if self . _state == WSParserState . READ_HEADER :
if buf_length - start_pos >= 2 :
data = buf [ start_pos : start_pos + 2 ]
start_pos += ... |
def partitioning_type ( self ) :
"""Union [ str , None ] : Time partitioning of the table if it is
partitioned ( Defaults to : data : ` None ` ) .""" | warnings . warn ( "This method will be deprecated in future versions. Please use " "TableListItem.time_partitioning.type_ instead." , PendingDeprecationWarning , stacklevel = 2 , )
if self . time_partitioning is not None :
return self . time_partitioning . type_ |
def is_whitelisted ( self , addrinfo ) :
"""Returns if a result of ` ` socket . getaddrinfo ` ` is in the socket address
whitelist .""" | # For details about the ` ` getaddrinfo ` ` struct , see the Python docs :
# http : / / docs . python . org / library / socket . html # socket . getaddrinfo
family , socktype , proto , canonname , sockaddr = addrinfo
address , port = sockaddr [ : 2 ]
return address in self . socket_address_whitelist |
def minimum ( self ) :
"""Returns the minimum value for this ruler . If the cached value is None ,
then a default value will be specified based on the ruler type .
: return < variant >""" | if ( self . _minimum is not None ) :
return self . _minimum
rtype = self . rulerType ( )
if ( rtype == XChartRuler . Type . Number ) :
self . _minimum = 0
elif ( rtype == XChartRuler . Type . Date ) :
self . _minimum = QDate . currentDate ( )
elif ( rtype == XChartRuler . Type . Datetime ) :
self . _min... |
def _no_auto_update_getter ( self ) :
""": class : ` bool ` . Boolean controlling whether the : meth : ` start _ update `
method is automatically called by the : meth : ` update ` method
Examples
You can disable the automatic update via
> > > with data . no _ auto _ update :
. . . data . update ( time = 1... | if getattr ( self , '_no_auto_update' , None ) is not None :
return self . _no_auto_update
else :
self . _no_auto_update = utils . _TempBool ( )
return self . _no_auto_update |
def check_member_state ( self ) :
"""Verify that all RS members have an acceptable state .""" | bad_states = ( 0 , 3 , 4 , 5 , 6 , 9 )
try :
rs_status = self . run_command ( 'replSetGetStatus' )
bad_members = [ member for member in rs_status [ 'members' ] if member [ 'state' ] in bad_states ]
if bad_members :
return False
except pymongo . errors . AutoReconnect : # catch ' No replica set prima... |
def find_token_type ( self , request ) :
"""Token type identification .
RFC 6749 does not provide a method for easily differentiating between
different token types during protected resource access . We estimate
the most likely token type ( if any ) by asking each known token type
to give an estimation based... | estimates = sorted ( ( ( t . estimate_type ( request ) , n ) for n , t in self . tokens . items ( ) ) , reverse = True )
return estimates [ 0 ] [ 1 ] if len ( estimates ) else None |
def _apply_with_random_selector ( x , func , num_cases ) :
"""Computes func ( x , sel ) , with sel sampled from [ 0 . . . num _ cases - 1 ] .
Args :
x : input Tensor .
func : Python function to apply .
num _ cases : Python int32 , number of cases to sample sel from .
Returns :
The result of func ( x , s... | sel = tf . random_uniform ( [ ] , maxval = num_cases , dtype = tf . int32 )
# Pass the real x only to one of the func calls .
return control_flow_ops . merge ( [ func ( control_flow_ops . switch ( x , tf . equal ( sel , case ) ) [ 1 ] , case ) for case in range ( num_cases ) ] ) [ 0 ] |
def _check_stringify_year_row ( self , row_index ) :
'''Checks the given row to see if it is labeled year data and fills any blank years within that
data .''' | table_row = self . table [ row_index ]
# State trackers
prior_year = None
for column_index in range ( self . start [ 1 ] + 1 , self . end [ 1 ] ) :
current_year = table_row [ column_index ]
# Quit if we see
if not self . _check_years ( current_year , prior_year ) :
return
# Only copy when we see... |
def is_mag_data ( mdat ) :
'''is _ mag _ data ( dat ) yields True if the given data is a valid set of magnification data and False
otherwise .
Note that this does not return True for all valid return values of the mag _ data ( ) function :
specifically , if the mag _ data ( ) function yields a list of mag - d... | if not pimms . is_map ( mdat ) :
return False
for k in [ 'surface_coordinates' , 'visual_coordinates' , 'mesh' , 'submesh' , 'mask' , 'retinotopy_data' , 'masked_data' , 'surface_areas' , 'visual_areas' ] :
if k not in mdat :
return False
return True |
def _filter_startswith ( self , term , field_name , field_type , is_not ) :
"""Returns a startswith query on the un - stemmed term .
Assumes term is not a list .""" | if field_type == 'text' :
if len ( term . split ( ) ) == 1 :
term = '^ %s*' % term
query = self . backend . parse_query ( term )
else :
term = '^ %s' % term
query = self . _phrase_query ( term . split ( ) , field_name , field_type )
else :
term = '^%s*' % term
query = sel... |
def search ( self , search_string ) :
"""Searches for a given string through the resources ' labels .
: param search _ string :
: return : an instance of ` HucitAuthor ` or ` HucitWork ` .""" | query = """
SELECT ?s ?label ?type
WHERE {
?s a ?type .
?s rdfs:label ?label .
?label bif:contains "'%s'" .
}
""" % search_string
response = self . _session . default_store . execute_sparql ( query )
results = [ ( result [ 's' ] [ 'value' ] , result [ ... |
async def _maybe_release_last_part ( self ) -> None :
"""Ensures that the last read body part is read completely .""" | if self . _last_part is not None :
if not self . _last_part . at_eof ( ) :
await self . _last_part . release ( )
self . _unread . extend ( self . _last_part . _unread )
self . _last_part = None |
def draw_image ( self , img_filename : str , x : float , y : float , w : float , h : float ) -> None :
"""Draws the given image .""" | pass |
def restoreSettings ( self , settings ) :
"""Restores the settings for this logger from the inputed settings .
: param < QtCore . QSettings >""" | val = unwrapVariant ( settings . value ( 'format' ) )
if val :
self . setFormatText ( val )
levels = unwrapVariant ( settings . value ( 'levels' ) )
if levels :
self . setActiveLevels ( map ( int , levels . split ( ',' ) ) )
logger_levels = unwrapVariant ( settings . value ( 'loggerLevels' ) )
if logger_levels ... |
def put_everything_together ( self ) :
"""All of the elements of the final SVG file are put together in the correct order ( e . g . lines are placed behind plots
and the molecule ) .""" | molecule_list = [ self . filestart ] + [ self . white_circles ] + [ self . draw_molecule ] + [ self . draw . draw_hbonds ] + [ self . draw . draw_pi_lines ] + [ self . draw . draw_saltbridges ] + [ self . draw . cloud ] + [ self . draw_plots ] + [ self . end_symbol ]
self . final_molecule = "" . join ( map ( str , mole... |
def set_artefact_path ( self , path_to_zip_file ) :
"""Set the route to the local file to deploy
: param path _ to _ zip _ file :
: return :""" | self . config [ "deploy" ] [ "deploy_file" ] = path_to_zip_file
return { 'ZipFile' : self . build . read ( self . config [ "deploy" ] [ "deploy_file" ] ) } |
def getopt ( self , p , default = None ) :
"""Returns the first option value stored that matches p or default .""" | for k , v in self . pairs :
if k == p :
return v
return default |
def read_sql ( sql , con , index_col = None , coerce_float = True , params = None , parse_dates = None , columns = None , chunksize = None , partition_column = None , lower_bound = None , upper_bound = None , max_sessions = None , ) :
"""Read SQL query or database table into a DataFrame .
Args :
sql : string or... | _ , _ , _ , kwargs = inspect . getargvalues ( inspect . currentframe ( ) )
return DataFrame ( query_compiler = ExperimentalBaseFactory . read_sql ( ** kwargs ) ) |
def clenshaw ( a , alpha , beta , t ) :
"""Clenshaw ' s algorithm for evaluating
S ( t ) = \\ sum a _ k P _ k ( alpha , beta ) ( t )
where P _ k ( alpha , beta ) is the kth orthogonal polynomial defined by the
recurrence coefficients alpha , beta .
See < https : / / en . wikipedia . org / wiki / Clenshaw _ ... | n = len ( alpha )
assert len ( beta ) == n
assert len ( a ) == n + 1
try :
b = numpy . empty ( ( n + 1 , ) + t . shape )
except AttributeError : # ' float ' object has no attribute ' shape '
b = numpy . empty ( n + 1 )
# b [ 0 ] is unused , can be any value
# TODO shift the array
b [ 0 ] = 1.0
b [ n ] = a [ n ]... |
def __get_request ( self , host , soup ) :
"""Build a request from the given soup form .
Args :
host str : The URL of the current queue item .
soup ( obj ) : The BeautifulSoup form .
Returns :
: class : ` nyawc . http . Request ` : The new Request .""" | url = URLHelper . make_absolute ( host , self . __trim_grave_accent ( soup [ "action" ] ) ) if soup . has_attr ( "action" ) else host
method_original = soup [ "method" ] if soup . has_attr ( "method" ) else "get"
method = "post" if method_original . lower ( ) == "post" else "get"
data = self . __get_form_data ( soup )
... |
def get_file ( self , fax_id , ** kwargs ) : # noqa : E501
"""get a file # noqa : E501
Get your fax archive file using it ' s id . # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . get _ file ( fax _ i... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return self . get_file_with_http_info ( fax_id , ** kwargs )
# noqa : E501
else :
( data ) = self . get_file_with_http_info ( fax_id , ** kwargs )
# noqa : E501
return data |
def _sync_table ( self , columns ) :
"""Lazy load , create or adapt the table structure in the database .""" | if self . _table is None : # Load an existing table from the database .
self . _reflect_table ( )
if self . _table is None : # Create the table with an initial set of columns .
if not self . _auto_create :
raise DatasetException ( "Table does not exist: %s" % self . name )
# Keep the lock scope smal... |
def crosscorr ( self , signal , lag = 0 ) :
"""Cross correlate series data against another signal .
Parameters
signal : array
Signal to correlate against ( must be 1D ) .
lag : int
Range of lags to consider , will cover ( - lag , + lag ) .""" | from scipy . linalg import norm
s = asarray ( signal )
s = s - mean ( s )
s = s / norm ( s )
if size ( s ) != size ( self . index ) :
raise Exception ( 'Size of signal to cross correlate with, %g, ' 'does not match size of series' % size ( s ) )
# created a matrix with lagged signals
if lag is not 0 :
shifts = ... |
def to_csv ( self , path_or_buf = None , sep = "," , na_rep = '' , float_format = None , columns = None , header = True , index = True , index_label = None , mode = 'w' , encoding = None , compression = 'infer' , quoting = None , quotechar = '"' , line_terminator = None , chunksize = None , tupleize_cols = None , date_... | df = self if isinstance ( self , ABCDataFrame ) else self . to_frame ( )
if tupleize_cols is not None :
warnings . warn ( "The 'tupleize_cols' parameter is deprecated and " "will be removed in a future version" , FutureWarning , stacklevel = 2 )
else :
tupleize_cols = False
from pandas . io . formats . csvs imp... |
def bytes ( self ) :
"""Returns the provided data as bytes .""" | if self . _filename :
with open ( self . _filename , "rb" ) as f :
return f . read ( )
else :
return self . _bytes |
def request ( self , url , method = 'GET' , params = None , data = None , expected_response_code = 200 , headers = None ) :
"""Make a HTTP request to the InfluxDB API .
: param url : the path of the HTTP request , e . g . write , query , etc .
: type url : str
: param method : the HTTP method for the request ... | url = "{0}/{1}" . format ( self . _baseurl , url )
if headers is None :
headers = self . _headers
if params is None :
params = { }
if isinstance ( data , ( dict , list ) ) :
data = json . dumps ( data )
# Try to send the request more than once by default ( see # 103)
retry = True
_try = 0
while retry :
... |
def make_requests_session ( ) :
""": returns : requests session
: rtype : : class : ` requests . Session `""" | session = requests . Session ( )
version = __import__ ( 'steam' ) . __version__
ua = "python-steam/{0} {1}" . format ( version , session . headers [ 'User-Agent' ] )
session . headers [ 'User-Agent' ] = ua
return session |
def fetch_html ( self , msg_nums ) :
"""Given a message number that we found with imap _ search ,
get the text / html content .
@ Params
msg _ nums - message number to get html message for
@ Returns
HTML content of message matched by message number""" | if not msg_nums :
raise Exception ( "Invalid Message Number!" )
return self . __imap_fetch_content_type ( msg_nums , self . HTML ) |
def dataset_generator ( filepath , dataset , chunk_size = 1 , start_idx = None , end_idx = None ) :
"""Generate example dicts .""" | encoder = dna_encoder . DNAEncoder ( chunk_size = chunk_size )
with h5py . File ( filepath , "r" ) as h5_file : # Get input keys from h5 _ file
src_keys = [ s % dataset for s in [ "%s_in" , "%s_na" , "%s_out" ] ]
src_values = [ h5_file [ k ] for k in src_keys ]
inp_data , mask_data , out_data = src_values
... |
def offset ( self , value ) :
"""Allows for skipping a specified number of results in query . Useful
for pagination .""" | self . _query = self . _query . skip ( value )
return self |
def receive ( self , data ) :
"""receive ( data ) - > List of decoded messages .
Processes : obj : ` data ` , which must be a bytes - like object ,
and returns a ( possibly empty ) list with : class : ` bytes ` objects ,
each containing a decoded message .
Any non - terminated SLIP packets in : obj : ` data... | # Empty data indicates that the data reception is complete .
# To force a buffer flush , an END byte is added , so that the
# current contents of _ recv _ buffer will form a complete message .
if not data :
data = END
self . _recv_buffer += data
# The following situations can occur :
# 1 ) _ recv _ buffer is empty ... |
def bs_plot_data ( self , zero_to_efermi = True ) :
"""Get the data nicely formatted for a plot
Args :
zero _ to _ efermi : Automatically subtract off the Fermi energy from the
eigenvalues and plot .
Returns :
dict : A dictionary of the following format :
ticks : A dict with the ' distances ' at which t... | distance = [ ]
energy = [ ]
if self . _bs . is_metal ( ) :
zero_energy = self . _bs . efermi
else :
zero_energy = self . _bs . get_vbm ( ) [ 'energy' ]
if not zero_to_efermi :
zero_energy = 0.0
for b in self . _bs . branches :
if self . _bs . is_spin_polarized :
energy . append ( { str ( Spin . ... |
def getexptimeimg ( self , chip ) :
"""Notes
Return an array representing the exposure time per pixel for the detector .
This method will be overloaded for IR detectors which have their own
EXP arrays , namely , WFC3 / IR and NICMOS images .
: units :
None
Returns
exptimeimg : numpy array
The method... | sci_chip = self . _image [ self . scienceExt , chip ]
if sci_chip . _wtscl_par == 'expsq' :
wtscl = sci_chip . _exptime * sci_chip . _exptime
else :
wtscl = sci_chip . _exptime
return np . ones ( sci_chip . image_shape , dtype = sci_chip . image_dtype ) * wtscl |
def listwrap ( value ) :
"""PERFORMS THE FOLLOWING TRANSLATION
None - > [ ]
value - > [ value ]
[ . . . ] - > [ . . . ] ( unchanged list )
# # MOTIVATION # #
OFTEN IT IS NICE TO ALLOW FUNCTION PARAMETERS TO BE ASSIGNED A VALUE ,
OR A list - OF - VALUES , OR NULL . CHECKING FOR WHICH THE CALLER USED IS
... | if value == None :
return FlatList ( )
elif is_list ( value ) :
return wrap ( value )
elif isinstance ( value , set ) :
return wrap ( list ( value ) )
else :
return wrap ( [ unwrap ( value ) ] ) |
def main ( arguments = None ) :
"""* The main function used when ` ` cl _ utils . py ` ` is run as a single script from the cl , or when installed as a cl command *""" | # setup the command - line util settings
su = tools ( arguments = arguments , docString = __doc__ , logLevel = "WARNING" , options_first = False , projectName = "polyglot" )
arguments , settings , log , dbConn = su . setup ( )
# unpack remaining cl arguments using ` exec ` to setup the variable names
# automatically
fo... |
def asarray_ndim ( a , * ndims , ** kwargs ) :
"""Ensure numpy array .
Parameters
a : array _ like
* ndims : int , optional
Allowed values for number of dimensions .
* * kwargs
Passed through to : func : ` numpy . array ` .
Returns
a : numpy . ndarray""" | allow_none = kwargs . pop ( 'allow_none' , False )
kwargs . setdefault ( 'copy' , False )
if a is None and allow_none :
return None
a = np . array ( a , ** kwargs )
if a . ndim not in ndims :
if len ( ndims ) > 1 :
expect_str = 'one of %s' % str ( ndims )
else : # noinspection PyUnresolvedReferences... |
def cartesian_to_helicity ( vector , numeric = False ) :
r"""This function takes vectors from the cartesian basis to the helicity basis .
For instance , we can check what are the vectors of the helicity basis .
> > > from sympy import pi
> > > em = polarization _ vector ( phi = 0 , theta = 0 , alpha = 0 , bet... | if numeric :
vector = list ( vector )
vector [ 0 ] = nparray ( vector [ 0 ] )
vector [ 1 ] = nparray ( vector [ 1 ] )
vector [ 2 ] = nparray ( vector [ 2 ] )
v = [ ( vector [ 0 ] - 1j * vector [ 1 ] ) / npsqrt ( 2 ) , vector [ 2 ] , - ( vector [ 0 ] + 1j * vector [ 1 ] ) / npsqrt ( 2 ) ]
v = npa... |
def get_submission_archive ( self , submissions , sub_folders , aggregations , archive_file = None ) :
""": param submissions : a list of submissions
: param sub _ folders : possible values :
[ ] : put all submissions in /
[ ' taskid ' ] : put all submissions for each task in a different directory / taskid / ... | tmpfile = archive_file if archive_file is not None else tempfile . TemporaryFile ( )
tar = tarfile . open ( fileobj = tmpfile , mode = 'w:gz' )
for submission in submissions :
submission = self . get_input_from_submission ( submission )
submission_yaml = io . BytesIO ( inginious . common . custom_yaml . dump ( ... |
def modify ( self , ** params ) :
"""https : / / developers . coinbase . com / api # modify - an - account""" | data = self . api_client . update_account ( self . id , ** params )
self . update ( data )
return data |
def write_file ( self , path , contents ) :
"""Write a file of any type to the destination path . Useful for files like
robots . txt , manifest . json , and so on .
Args :
path ( str ) : The name of the file to write to .
contents ( str or bytes ) : The contents to write .""" | path = self . _get_dist_path ( path )
if not os . path . isdir ( os . path . dirname ( path ) ) :
os . makedirs ( os . path . dirname ( path ) )
if isinstance ( contents , bytes ) :
mode = 'wb+'
else :
mode = 'w'
with open ( path , mode ) as file :
file . write ( contents ) |
def write ( self , string ) :
"""Erase newline from a string and write to the logger .""" | string = string . rstrip ( )
if string : # Don ' t log empty lines
self . logger . critical ( string ) |
def symmetric_decrypt_HMAC ( cyphertext , key , hmac_secret ) :
""": raises : : class : ` RuntimeError ` when HMAC verification fails""" | iv = symmetric_decrypt_iv ( cyphertext , key )
message = symmetric_decrypt_with_iv ( cyphertext , key , iv )
hmac = hmac_sha1 ( hmac_secret , iv [ - 3 : ] + message )
if iv [ : 13 ] != hmac [ : 13 ] :
raise RuntimeError ( "Unable to decrypt message. HMAC does not match." )
return message |
def build_bond ( iface , ** settings ) :
'''Create a bond script in / etc / modprobe . d with the passed settings
and load the bonding kernel module .
CLI Example :
. . code - block : : bash
salt ' * ' ip . build _ bond bond0 mode = balance - alb''' | deb_major = __grains__ [ 'osrelease' ] [ : 1 ]
opts = _parse_settings_bond ( settings , iface )
try :
template = JINJA . get_template ( 'conf.jinja' )
except jinja2 . exceptions . TemplateNotFound :
log . error ( 'Could not load template conf.jinja' )
return ''
data = template . render ( { 'name' : iface , ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.