signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def ListAdapters ( self ) :
'''List all known adapters''' | adapters = [ ]
for obj in mockobject . objects . keys ( ) :
if obj . startswith ( '/org/bluez/' ) and 'dev_' not in obj :
adapters . append ( dbus . ObjectPath ( obj , variant_level = 1 ) )
return dbus . Array ( adapters , variant_level = 1 ) |
def win_login ( ) :
"""登陆界面""" | email = input ( EMAIL_INFO )
password = getpass . getpass ( PASS_INFO )
captcha_id = get_captcha_id ( )
get_capthca_pic ( captcha_id )
file = '/tmp/captcha_pic.jpg'
try :
from subprocess import call
from os . path import expanduser
call ( [ expanduser ( '~' ) + '/.iterm2/imgcat' , file ] )
except :
impo... |
def org_task ( task_key , lock_timeout = None ) :
"""Decorator to create an org task .
: param task _ key : the task key used for state storage and locking , e . g . ' do - stuff '
: param lock _ timeout : the lock timeout in seconds""" | def _org_task ( task_func ) :
def _decorator ( org_id ) :
org = apps . get_model ( "orgs" , "Org" ) . objects . get ( pk = org_id )
maybe_run_for_org ( org , task_func , task_key , lock_timeout )
return shared_task ( wraps ( task_func ) ( _decorator ) )
return _org_task |
def OnPadIntCtrl ( self , event ) :
"""Pad IntCtrl event handler""" | self . attrs [ "pad" ] = event . GetValue ( )
post_command_event ( self , self . DrawChartMsg ) |
def mask_roi_digi ( self ) :
"""Get the index of the unique magnitude tuple for each pixel in the ROI .""" | # http : / / stackoverflow . com / q / 24205045 / # 24206440
A = np . vstack ( [ self . mask_1 . mask_roi_sparse , self . mask_2 . mask_roi_sparse ] ) . T
B = self . mask_roi_unique
AA = np . ascontiguousarray ( A )
BB = np . ascontiguousarray ( B )
dt = np . dtype ( ( np . void , AA . dtype . itemsize * AA . shape [ 1... |
def check_auth ( self , all_credentials ) :
"""Update this socket ' s authentication .
Log in or out to bring this socket ' s credentials up to date with
those provided . Can raise ConnectionFailure or OperationFailure .
: Parameters :
- ` all _ credentials ` : dict , maps auth source to MongoCredential .""... | if all_credentials or self . authset :
cached = set ( itervalues ( all_credentials ) )
authset = self . authset . copy ( )
# Logout any credentials that no longer exist in the cache .
for credentials in authset - cached :
auth . logout ( credentials . source , self )
self . authset . dis... |
def decorator ( self , func ) :
"""Wrapper function to decorate a function""" | if inspect . isfunction ( func ) :
func . _methodview = self
elif inspect . ismethod ( func ) :
func . __func__ . _methodview = self
else :
raise AssertionError ( 'Can only decorate function and methods, {} given' . format ( func ) )
return func |
def inverse_transform ( self , maps ) :
"""This function transforms from cartesian to spherical spins .
Parameters
maps : a mapping object
Returns
out : dict
A dict with key as parameter name and value as numpy . array or float
of transformed values .""" | sx , sy , sz = self . _outputs
data = coordinates . cartesian_to_spherical ( maps [ sx ] , maps [ sy ] , maps [ sz ] )
out = { param : val for param , val in zip ( self . _outputs , data ) }
return self . format_output ( maps , out ) |
def RgbToHtml ( r , g , b ) :
'''Convert the color from ( r , g , b ) to # RRGGBB .
Parameters :
The Red component value [ 0 . . . 1]
The Green component value [ 0 . . . 1]
The Blue component value [ 0 . . . 1]
Returns :
A CSS string representation of this color ( # RRGGBB ) .
> > > Color . RgbToHtml ... | return '#%02x%02x%02x' % tuple ( ( min ( round ( v * 255 ) , 255 ) for v in ( r , g , b ) ) ) |
def community_post_comment_votes ( self , post_id , comment_id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / help _ center / votes # list - votes" | api_path = "/api/v2/community/posts/{post_id}/comments/{comment_id}/votes.json"
api_path = api_path . format ( post_id = post_id , comment_id = comment_id )
return self . call ( api_path , ** kwargs ) |
def string_list_to_array ( l ) :
"""Turns a Python unicode string list into a Java String array .
: param l : the string list
: type : list
: rtype : java string array
: return : JB _ Object""" | result = javabridge . get_env ( ) . make_object_array ( len ( l ) , javabridge . get_env ( ) . find_class ( "java/lang/String" ) )
for i in range ( len ( l ) ) :
javabridge . get_env ( ) . set_object_array_element ( result , i , javabridge . get_env ( ) . new_string_utf ( l [ i ] ) )
return result |
def portfolio ( self ) -> List [ PortfolioItem ] :
"""List of portfolio items of the default account .""" | account = self . wrapper . accounts [ 0 ]
return [ v for v in self . wrapper . portfolio [ account ] . values ( ) ] |
def status ( cwd , user = None , password = None , ignore_retcode = False , output_encoding = None ) :
'''. . versionchanged : : 2015.8.0
Return data has changed from a list of lists to a dictionary
Returns the changes to the repository
cwd
The path to the git checkout
user
User under which to run the g... | cwd = _expand_path ( cwd , user )
state_map = { 'M' : 'modified' , 'A' : 'new' , 'D' : 'deleted' , '??' : 'untracked' }
ret = { }
command = [ 'git' , 'status' , '-z' , '--porcelain' ]
output = _git_run ( command , cwd = cwd , user = user , password = password , ignore_retcode = ignore_retcode , output_encoding = output... |
def vcs_init ( self ) :
"""Initialize VCS repository .""" | VCS ( os . path . join ( self . outdir , self . name ) , self . pkg_data ) |
def credential_lists ( self ) :
"""Access the credential _ lists
: returns : twilio . rest . api . v2010 . account . sip . credential _ list . CredentialListList
: rtype : twilio . rest . api . v2010 . account . sip . credential _ list . CredentialListList""" | if self . _credential_lists is None :
self . _credential_lists = CredentialListList ( self . _version , account_sid = self . _solution [ 'account_sid' ] , )
return self . _credential_lists |
def _check_lookup_prop ( self , result_data ) :
"""Checks that selected lookup property can be used for this testcase .""" | if not self . _lookup_prop :
return False
if not result_data . get ( "id" ) and self . _lookup_prop != "name" :
return False
if not result_data . get ( "title" ) and self . _lookup_prop == "name" :
return False
return True |
def _rainbow_hex_chars ( self , s , freq = 0.1 , spread = 3.0 , offset = 0 ) :
"""Iterate over characters in a string to build data needed for a
rainbow effect .
Yields tuples of ( char , hexcode ) .
Arguments :
s : String to colorize .
freq : Frequency / " tightness " of colors in the rainbow .
Best re... | return ( ( c , self . _rainbow_color ( freq , offset + i / spread ) ) for i , c in enumerate ( s ) ) |
def _listen_submissions ( self ) :
"""Start listening to submissions , using a separate thread .""" | # Collect submissions in a queue
subs_queue = Queue ( maxsize = self . _n_jobs * 4 )
threads = [ ]
# type : List [ BotQueueWorker ]
try : # Create n _ jobs SubmissionThreads
for i in range ( self . _n_jobs ) :
t = BotQueueWorker ( name = 'SubmissionThread-t-{}' . format ( i ) , jobs = subs_queue , target = ... |
def run_command ( cmd_to_run ) :
"""Wrapper around subprocess that pipes the stderr and stdout from ` cmd _ to _ run `
to temporary files . Using the temporary files gets around subprocess . PIPE ' s
issues with handling large buffers .
Note : this command will block the python process until ` cmd _ to _ run ... | with tempfile . TemporaryFile ( ) as stdout_file , tempfile . TemporaryFile ( ) as stderr_file : # Run the command
popen = subprocess . Popen ( cmd_to_run , stdout = stdout_file , stderr = stderr_file )
popen . wait ( )
stderr_file . seek ( 0 )
stdout_file . seek ( 0 )
stderr = stderr_file . read ( ... |
def alpha_shape ( points , alpha ) :
"""Compute the alpha shape ( concave hull ) of a set
of points .
@ param points : Iterable container of points .
@ param alpha : alpha value to influence the
gooeyness of the border . Smaller numbers
don ' t fall inward as much as larger numbers .
Too large , and you... | if len ( points ) < 4 : # When you have a triangle , there is no sense
# in computing an alpha shape .
return geometry . MultiPoint ( list ( points ) ) . convex_hull
# coords = np . array ( [ point . coords [ 0 ] for point in points ] )
coords = np . array ( points )
print ( coords )
tri = Delaunay ( coords )
edges... |
def _shift ( tokens ) :
"""pop the next token , then peek the gid of the following""" | after = tokens . peek ( n = 1 , skip = _is_comment , drop = True )
tok = tokens . _buffer . popleft ( )
return tok [ 0 ] , tok [ 1 ] , tok [ 2 ] , after [ 0 ] |
def write_logger_id ( self , manufacturer , logger_id , extension = None , validate = True ) :
"""Write the manufacturer and logger id header line : :
writer . write _ logger _ id ( ' XXX ' , ' ABC ' , extension = ' FLIGHT : 1 ' )
# - > AXXXABCFLIGHT : 1
Some older loggers have decimal logger ids which can be... | if validate :
if not patterns . MANUFACTURER_CODE . match ( manufacturer ) :
raise ValueError ( 'Invalid manufacturer code' )
if not patterns . LOGGER_ID . match ( logger_id ) :
raise ValueError ( 'Invalid logger id' )
record = '%s%s' % ( manufacturer , logger_id )
if extension :
record = re... |
def get_auth ( self ) :
"""Gets an active token refreshing it if necessary .
: return : str valid active authentication token .""" | if self . legacy_auth ( ) :
return self . _auth
if not self . auth_expired ( ) :
return self . _auth
self . claim_new_token ( )
return self . _auth |
def gumbel_softmax_nearest_neighbor_dvq ( x , means , block_v_size , hard = False , temperature_init = 1.2 , num_samples = 1 , temperature_warmup_steps = 150000 , summary = True , num_flows = 0 , approximate_gs_entropy = False , sum_over_latents = False ) :
"""Sample from Gumbel - Softmax and compute neighbors and ... | batch_size , latent_dim , num_blocks , block_dim = common_layers . shape_list ( x )
# Combine latent _ dim and batch _ size for computing distances .
x = tf . reshape ( x , [ - 1 , num_blocks , block_dim ] )
# Compute distances using ( x - means ) * * 2 = x * * 2 + means * * 2 - 2 * x * means .
x_norm_sq = tf . reduce_... |
def unzip ( filepath , verbose = True ) :
r"""Unzip GloVE models and convert to word2vec binary models ( gensim . KeyedVectors )
The only kinds of files that are returned are " * . asc " and " * . txt " and only after renaming .""" | filepath = expand_filepath ( filepath )
filename = os . path . basename ( filepath )
tqdm_prog = tqdm if verbose else no_tqdm
z = ZipFile ( filepath )
unzip_dir = filename . split ( '.' ) [ 0 ] if filename . split ( '.' ) [ 0 ] else os . path . splitext ( filename ) [ 0 ]
unzip_dir = os . path . join ( BIGDATA_PATH , u... |
def ip ( self , value ) :
"""The ip property .
Args :
value ( string ) . the property value .""" | if value == self . _defaults [ 'ai.location.ip' ] and 'ai.location.ip' in self . _values :
del self . _values [ 'ai.location.ip' ]
else :
self . _values [ 'ai.location.ip' ] = value |
def load_cli_plugins ( cli , config_dir = None ) :
"""Load all plugins and attach them to a CLI object .""" | from . config import load_master_config
config = load_master_config ( config_dir = config_dir )
plugins = discover_plugins ( config . Plugins . dirs )
for plugin in plugins :
if not hasattr ( plugin , 'attach_to_cli' ) : # pragma : no cover
continue
logger . debug ( "Attach plugin `%s` to CLI." , _fulln... |
def _pmrapmdec ( self , * args , ** kwargs ) :
"""Calculate pmra and pmdec""" | lbdvrpmllpmbb = self . _lbdvrpmllpmbb ( * args , ** kwargs )
return coords . pmllpmbb_to_pmrapmdec ( lbdvrpmllpmbb [ : , 4 ] , lbdvrpmllpmbb [ : , 5 ] , lbdvrpmllpmbb [ : , 0 ] , lbdvrpmllpmbb [ : , 1 ] , degree = True , epoch = None ) |
def filter_duplicate ( self , url ) :
"""url去重""" | if self . filterDuplicate :
if url in self . historys :
raise Exception ( 'duplicate excepiton: %s is duplicate' % url )
else :
self . historys . add ( url )
else :
pass |
def _wait_for_pod_deletion ( self , daemonset_pods = None ) :
"""Wait until this K8sNode has evicted all its K8sPods .
: param daemonset _ pods : A list of K8sPods on this K8sNode that are managed by a K8sDaemonSet .
: return : None""" | pods = self . _pod_inventory ( )
start_time = time . time ( )
while len ( pods ) > 0 :
if len ( pods ) == len ( daemonset_pods ) :
break
pods = self . _pod_inventory ( )
self . _check_timeout ( start_time )
time . sleep ( 1 )
return |
def get_current_future_chain ( self , continuous_future , dt ) :
"""Retrieves the future chain for the contract at the given ` dt ` according
the ` continuous _ future ` specification .
Returns
future _ chain : list [ Future ]
A list of active futures , where the first index is the current
contract specif... | rf = self . _roll_finders [ continuous_future . roll_style ]
session = self . trading_calendar . minute_to_session_label ( dt )
contract_center = rf . get_contract_center ( continuous_future . root_symbol , session , continuous_future . offset )
oc = self . asset_finder . get_ordered_contracts ( continuous_future . roo... |
def fromtsv ( source = None , encoding = None , errors = 'strict' , header = None , ** csvargs ) :
"""Convenience function , as : func : ` petl . io . csv . fromcsv ` but with different
default dialect ( tab delimited ) .""" | csvargs . setdefault ( 'dialect' , 'excel-tab' )
return fromcsv ( source , encoding = encoding , errors = errors , ** csvargs ) |
def getBurstingColumnsStats ( self ) :
"""Gets statistics on the Temporal Memory ' s bursting columns . Used as a metric
of Temporal Memory ' s learning performance .
: return : mean , standard deviation , and max of Temporal Memory ' s bursting
columns over time""" | traceData = self . tm . mmGetTraceUnpredictedActiveColumns ( ) . data
resetData = self . tm . mmGetTraceResets ( ) . data
countTrace = [ ]
for x in xrange ( len ( traceData ) ) :
if not resetData [ x ] :
countTrace . append ( len ( traceData [ x ] ) )
mean = numpy . mean ( countTrace )
stdDev = numpy . std ... |
def diversity_coef_sign ( W , ci ) :
'''The Shannon - entropy based diversity coefficient measures the diversity
of intermodular connections of individual nodes and ranges from 0 to 1.
Parameters
W : NxN np . ndarray
undirected connection matrix with positive and negative weights
ci : Nx1 np . ndarray
c... | n = len ( W )
# number of nodes
_ , ci = np . unique ( ci , return_inverse = True )
ci += 1
m = np . max ( ci )
# number of modules
def entropy ( w_ ) :
S = np . sum ( w_ , axis = 1 )
# strength
Snm = np . zeros ( ( n , m ) )
# node - to - module degree
for i in range ( m ) :
Snm [ : , i ] =... |
def _choose_host ( self ) :
"""This method randomly chooses a server from the server list given as
a parameter to the parent PythonSDK
: return : The selected host to which the Sender will attempt to
connect""" | # If a host hasn ' t been chosen yet or there is only one host
if len ( self . _hosts ) == 1 or self . _http_host is None :
self . _http_host = self . _hosts [ 0 ]
else : # There is a list of hosts to choose from , pick a random one
choice = self . _http_host
while choice == self . _http_host :
choi... |
def sync ( args ) :
"""Implement the ' greg sync ' command""" | import operator
session = c . Session ( args )
if "all" in args [ "names" ] :
targetfeeds = session . list_feeds ( )
else :
targetfeeds = [ ]
for name in args [ "names" ] :
if name not in session . feeds :
print ( "You don't have a feed called {}." . format ( name ) , file = sys . stderr... |
def Run ( self ) :
"""Create FileStore and HashFileStore namespaces .""" | if not data_store . AFF4Enabled ( ) :
return
try :
filestore = aff4 . FACTORY . Create ( FileStore . PATH , FileStore , mode = "rw" , token = aff4 . FACTORY . root_token )
filestore . Close ( )
hash_filestore = aff4 . FACTORY . Create ( HashFileStore . PATH , HashFileStore , mode = "rw" , token = aff4 .... |
def CheckInputArgs ( * interfaces ) :
"""Must provide at least one interface , the last one may be repeated .""" | l = len ( interfaces )
def wrapper ( func ) :
def check_args ( self , * args , ** kw ) :
for i in range ( len ( args ) ) :
if ( l > i and interfaces [ i ] . providedBy ( args [ i ] ) ) or interfaces [ - 1 ] . providedBy ( args [ i ] ) :
continue
if l > i :
... |
def assert_has_calls ( self , calls , any_order = False ) :
"""assert the mock has been called with the specified calls .
The ` mock _ calls ` list is checked for the calls .
If ` any _ order ` is False ( the default ) then the calls must be
sequential . There can be extra calls before or after the
specifie... | expected = [ self . _call_matcher ( c ) for c in calls ]
cause = expected if isinstance ( expected , Exception ) else None
all_calls = _CallList ( self . _call_matcher ( c ) for c in self . mock_calls )
if not any_order :
if expected not in all_calls :
six . raise_from ( AssertionError ( 'Calls not found.\n... |
def binary ( self ) :
"""Get the object this function belongs to .
: return : The object this function belongs to .""" | return self . _project . loader . find_object_containing ( self . addr , membership_check = False ) |
def sky_bbox_ur ( self ) :
"""The sky coordinates of the upper - right vertex of the minimal
bounding box of the source segment , returned as a
` ~ astropy . coordinates . SkyCoord ` object .
The bounding box encloses all of the source segment pixels in
their entirety , thus the vertices are at the pixel * ... | if self . _wcs is not None :
return pixel_to_skycoord ( self . xmax . value + 0.5 , self . ymax . value + 0.5 , self . _wcs , origin = 0 )
else :
return None |
def basic_c_defines ( layout , keyboard_prefix = "KEY_" , led_prefix = "LED_" , sysctrl_prefix = "SYS_" , cons_prefix = "CONS_" , code_suffix = True , all_caps = True , space_char = "_" ) :
'''Generates a list of C defines that can be used to generate a header file
@ param layout : Layout object
@ keyboard _ pr... | # Keyboard Codes
keyboard_defines = [ ]
for code , name in layout . json ( ) [ 'to_hid_keyboard' ] . items ( ) :
new_name = "{}{}" . format ( keyboard_prefix , name . replace ( ' ' , space_char ) )
if all_caps :
new_name = new_name . upper ( )
if code_suffix :
new_name = "{}_{}" . format ( n... |
def weight_map ( self ) :
"""Return 3 - D weights map for this component as a Map object .
Returns
map : ` ~ fermipy . skymap . MapBase `""" | # EAC we need the try blocks b / c older versions of the ST don ' t have some of these functions
if isinstance ( self . like , gtutils . SummedLikelihood ) :
cmap = self . like . components [ 0 ] . logLike . countsMap ( )
try :
p_method = cmap . projection ( ) . method ( )
except AttributeError :
... |
def sample_parameter_values ( self , parameter , start = None , stop = None , sample_count = 500 , parameter_cache = 'realtime' , source = 'ParameterArchive' ) :
"""Returns parameter samples .
The query range is split in sample intervals of equal length . For
each interval a : class : ` . Sample ` is returned w... | path = '/archive/{}/parameters{}/samples' . format ( self . _instance , parameter )
now = datetime . utcnow ( )
params = { 'count' : sample_count , 'source' : source , 'start' : to_isostring ( now - timedelta ( hours = 1 ) ) , 'stop' : to_isostring ( now ) , }
if start is not None :
params [ 'start' ] = to_isostrin... |
def on_receive_request_vote_response ( self , data ) :
"""Receives response for vote request .
If the vote was granted then check if we got majority and may become Leader""" | if data . get ( 'vote_granted' ) :
self . vote_count += 1
if self . state . is_majority ( self . vote_count ) :
self . state . to_leader ( ) |
def hybrid_forward ( self , F , inputs , states = None , mask = None ) : # pylint : disable = arguments - differ
# pylint : disable = unused - argument
"""Defines the forward computation for cache cell . Arguments can be either
: py : class : ` NDArray ` or : py : class : ` Symbol ` .
Parameters
inputs : NDAr... | states_forward , states_backward = states
if mask is not None :
sequence_length = mask . sum ( axis = 1 )
outputs_forward = [ ]
outputs_backward = [ ]
for layer_index in range ( self . _num_layers ) :
if layer_index == 0 :
layer_inputs = inputs
else :
layer_inputs = outputs_forward [ layer_i... |
def update ( self , other = None , ** kwargs ) :
'''Takes the same arguments as the update method in the builtin dict
class . However , this version returns a new ImmutableDict instead of
modifying in - place .''' | copydict = ImmutableDict ( )
if other :
vallist = [ ( hash ( key ) , ( key , other [ key ] ) ) for key in other ]
else :
vallist = [ ]
if kwargs :
vallist += [ ( hash ( key ) , ( key , kwargs [ key ] ) ) for key in kwargs ]
copydict . tree = self . tree . multi_assoc ( vallist )
copydict . _length = iter_le... |
def set_vel_setpoint ( self , velocity_x , velocity_y , velocity_z , rate_yaw ) :
"""Set the velocity setpoint to use for the future motion""" | self . _queue . put ( ( velocity_x , velocity_y , velocity_z , rate_yaw ) ) |
def get_model ( self , opt_fn , emb_sz , n_hid , n_layers , ** kwargs ) :
"""Method returns a RNN _ Learner object , that wraps an instance of the RNN _ Encoder module .
Args :
opt _ fn ( Optimizer ) : the torch optimizer function to use
emb _ sz ( int ) : embedding size
n _ hid ( int ) : number of hidden i... | m = get_language_model ( self . nt , emb_sz , n_hid , n_layers , self . pad_idx , ** kwargs )
model = SingleModel ( to_gpu ( m ) )
return RNN_Learner ( self , model , opt_fn = opt_fn ) |
def render_items ( self , placeholder , items , parent_object = None , template_name = None , cachable = None ) :
"""The main rendering sequence .""" | # Unless it was done before , disable polymorphic effects .
is_queryset = False
if hasattr ( items , "non_polymorphic" ) :
is_queryset = True
if not items . polymorphic_disabled and items . _result_cache is None :
items = items . non_polymorphic ( )
# See if the queryset contained anything .
# This test... |
def snow_n ( im , voxel_size = 1 , boundary_faces = [ 'top' , 'bottom' , 'left' , 'right' , 'front' , 'back' ] , marching_cubes_area = False , alias = None ) :
r"""Analyzes an image that has been segemented into N phases and extracts all
a network for each of the N phases , including geometerical information as
... | # Get alias if provided by user
al = _create_alias_map ( im , alias = alias )
# Perform snow on each phase and merge all segmentation and dt together
snow = snow_partitioning_n ( im , r_max = 4 , sigma = 0.4 , return_all = True , mask = True , randomize = False , alias = al )
# Add boundary regions
f = boundary_faces
r... |
def true_negatives ( y , y_pred ) :
"""True - negatives
Parameters :
y : vector , shape ( n _ samples , )
The target labels .
y _ pred : vector , shape ( n _ samples , )
The predicted labels .
Returns :
tn : integer , the number of true - negatives""" | y , y_pred = convert_assert ( y , y_pred )
assert_binary_problem ( y )
return np . count_nonzero ( y_pred [ y == 0 ] == 0 ) |
def query_helper ( request , namespace , docid , configuration = None ) :
"""Does the actual query , called by query ( ) or pub _ query ( ) , not directly""" | flatargs = { 'customslicesize' : request . POST . get ( 'customslicesize' , settings . CONFIGURATIONS [ configuration ] . get ( 'customslicesize' , '50' ) ) , # for pagination of search results
}
# stupid compatibility stuff
if sys . version < '3' :
if hasattr ( request , 'body' ) :
data = json . loads ( un... |
def mustExposeRequest ( self , service_request ) :
"""Decides whether the underlying http request should be exposed as the
first argument to the method call . This is granular , looking at the
service method first , then at the service level and finally checking
the gateway .
@ rtype : C { bool }""" | expose_request = service_request . service . mustExposeRequest ( service_request )
if expose_request is None :
if self . expose_request is None :
return False
return self . expose_request
return expose_request |
def _replace_series_name ( seriesname , replacements ) :
"""Performs replacement of series name .
Allow specified replacements of series names in cases where default
filenames match the wrong series , e . g . missing year gives wrong answer ,
or vice versa . This helps the TVDB query get the right match .""" | for pat , replacement in six . iteritems ( replacements ) :
if re . match ( pat , seriesname , re . IGNORECASE | re . UNICODE ) :
return replacement
return seriesname |
def _get_task_priority ( tasks , task_priority ) :
"""Get the task ` priority ` corresponding to the given ` task _ priority ` .
If ` task _ priority ` is an integer or ' None ' , return it .
If ` task _ priority ` is a str , return the priority of the task it matches .
Otherwise , raise ` ValueError ` .""" | if task_priority is None :
return None
if is_integer ( task_priority ) :
return task_priority
if isinstance ( task_priority , basestring ) :
if task_priority in tasks :
return tasks [ task_priority ] . priority
raise ValueError ( "Unrecognized task priority '{}'" . format ( task_priority ) ) |
def same ( d1 , d2 ) :
"""! @ brief Test whether two sequences contain the same values .
Unlike a simple equality comparison , this function works as expected when the two sequences
are of different types , such as a list and bytearray . The sequences must return
compatible types from indexing .""" | if len ( d1 ) != len ( d2 ) :
return False
for i in range ( len ( d1 ) ) :
if d1 [ i ] != d2 [ i ] :
return False
return True |
def _vectorize_and_bind ( self , local_path , dest ) : # type : ( Uploader , blobxfer . models . upload . LocalPath ,
# List [ blobxfer . models . azure . StorageEntity ] ) - >
# Tuple [ blobxfer . operations . upload . UploadAction ,
# blobxfer . models . upload . LocalPath ,
# blobxfer . models . azure . StorageEntit... | if ( self . _spec . options . vectored_io . distribution_mode == blobxfer . models . upload . VectoredIoDistributionMode . Stripe and not local_path . use_stdin ) : # compute total number of slices
slices = int ( math . ceil ( local_path . total_size / self . _spec . options . vectored_io . stripe_chunk_size_bytes ... |
def qteNextWidget ( self , numSkip : int = 1 , ofsWidget : QtGui . QWidget = None , skipVisible : bool = False , skipInvisible : bool = True , skipFocusable : bool = False , skipUnfocusable : bool = True ) :
"""Return the next widget in cyclic order .
If ` ` ofsWidget ` ` is * * None * * then start counting at th... | # Check type of input arguments .
if not hasattr ( ofsWidget , '_qteAdmin' ) and ( ofsWidget is not None ) :
msg = '<ofsWidget> was probably not added with <qteAddWidget>'
msg += ' method because it lacks the <_qteAdmin> attribute.'
raise QtmacsOtherError ( msg )
# Housekeeping : remove non - existing widge... |
def aggregateLine ( requestContext , seriesList , func = 'avg' ) :
"""Takes a metric or wildcard seriesList and draws a horizontal line
based on the function applied to each series .
Note : By default , the graphite renderer consolidates data points by
averaging data points over time . If you are using the ' ... | t_funcs = { 'avg' : safeAvg , 'min' : safeMin , 'max' : safeMax }
if func not in t_funcs :
raise ValueError ( "Invalid function %s" % func )
results = [ ]
for series in seriesList :
value = t_funcs [ func ] ( series )
if value is not None :
name = 'aggregateLine(%s, %g)' % ( series . name , value )
... |
def padding_oracle_encrypt ( oracle , plaintext , block_size = 128 , pool = None ) :
"""Encrypt plaintext using an oracle function that returns ` ` True ` ` if the
provided ciphertext is correctly PKCS # 7 padded after decryption . The
cipher needs to operate in CBC mode .
Args :
oracle ( callable ) : The o... | plaintext = bytearray ( plaintext )
block_len = block_size // 8
padding_len = block_len - ( len ( plaintext ) % block_len )
plaintext . extend ( [ padding_len ] * padding_len )
ciphertext = bytearray ( )
chunk = bytearray ( os . urandom ( block_len ) )
ciphertext [ 0 : 0 ] = chunk
for plain_start in range ( len ( plain... |
def get_account_id_by_fullname ( self , fullname : str ) -> str :
"""Locates the account by fullname""" | account = self . get_by_fullname ( fullname )
return account . guid |
def run_suite ( test_classes , argv = None ) :
"""Executes multiple test classes as a suite .
This is the default entry point for running a test suite script file
directly .
Args :
test _ classes : List of python classes containing Mobly tests .
argv : A list that is then parsed as cli args . If None , de... | # Parse cli args .
parser = argparse . ArgumentParser ( description = 'Mobly Suite Executable.' )
parser . add_argument ( '-c' , '--config' , nargs = 1 , type = str , required = True , metavar = '<PATH>' , help = 'Path to the test configuration file.' )
parser . add_argument ( '--tests' , '--test_case' , nargs = '+' , ... |
def connect ( self , * args , ** kwargs ) :
"""Connect to Mambu , make the request to the REST API .
If there ' s no urlfunc to use , nothing is done here .
When done , initializes the attrs attribute of the Mambu object
by calling the init method . Please refer to that code and pydoc
for further informatio... | from copy import deepcopy
if args :
self . __args = deepcopy ( args )
if kwargs :
for k , v in kwargs . items ( ) :
self . __kwargs [ k ] = deepcopy ( v )
jsresp = { }
if not self . __urlfunc :
return
# Pagination window , Mambu restricts at most 500 elements in response
offset = self . __offset
win... |
def _generate_manager ( manager_config ) :
'''Generate a manager from a manager _ config dictionary
Parameters
manager _ config : dict
Configuration with keys class , args , and kwargs
used to generate a new datafs . manager object
Returns
manager : object
datafs . managers . MongoDBManager or
dataf... | if 'class' not in manager_config :
raise ValueError ( 'Manager not fully specified. Give ' '"class:manager_name", e.g. "class:MongoDBManager".' )
mgr_class_name = manager_config [ 'class' ]
if mgr_class_name . lower ( ) [ : 5 ] == 'mongo' :
from datafs . managers . manager_mongo import ( MongoDBManager as mgr_c... |
def set_id ( self , my_id ) :
"""Sets the opinion identifier
@ type my _ id : string
@ param my _ id : the opinion identifier""" | if self . type == 'NAF' :
self . node . set ( 'id' , my_id )
elif self . type == 'KAF' :
self . node . set ( 'oid' , my_id ) |
def validate_ok_for_replace ( replacement ) :
"""Validate a replacement document .""" | validate_is_mapping ( "replacement" , replacement )
# Replacement can be { }
if replacement and not isinstance ( replacement , RawBSONDocument ) :
first = next ( iter ( replacement ) )
if first . startswith ( '$' ) :
raise ValueError ( 'replacement can not include $ operators' ) |
def doublec ( self , j ) :
"""doublec ( j ) is TRUE < = > j , ( j - 1 ) contain a double consonant .""" | if j < ( self . k0 + 1 ) :
return 0
if self . b [ j ] != self . b [ j - 1 ] :
return 0
return self . cons ( j ) |
def _compute_raw_image_norm ( self , data ) :
"""Helper function that computes the uncorrected inverse normalization
factor of input image data . This quantity is computed as the
* sum of all pixel values * .
. . note : :
This function is intended to be overriden in a subclass if one
desires to change the... | return np . sum ( self . _data , dtype = np . float64 ) |
def download ( self , tool : Tool , force = False ) -> bool :
"""Attempts to download the Docker image for a given tool from
` DockerHub < https : / / hub . docker . com > ` _ . If the force parameter is set to
True , any existing image will be overwritten .
Returns :
` True ` if successfully downloaded , e... | return self . __installation . build . download ( tool . image , force = force ) |
def aggregate_stat ( origin_stat , new_stat ) :
"""aggregate new _ stat to origin _ stat .
Args :
origin _ stat ( dict ) : origin stat dict , will be updated with new _ stat dict .
new _ stat ( dict ) : new stat dict .""" | for key in new_stat :
if key not in origin_stat :
origin_stat [ key ] = new_stat [ key ]
elif key == "start_at" : # start datetime
origin_stat [ key ] = min ( origin_stat [ key ] , new_stat [ key ] )
else :
origin_stat [ key ] += new_stat [ key ] |
def download ( url , target_file , chunk_size = 4096 ) :
"""Simple requests downloader""" | r = requests . get ( url , stream = True )
with open ( target_file , 'w+' ) as out : # And this is why I love Armin Ronacher :
with click . progressbar ( r . iter_content ( chunk_size = chunk_size ) , int ( r . headers [ 'Content-Length' ] ) / chunk_size , label = 'Downloading...' ) as chunks :
for chunk in... |
def _worker_thread_transfer ( self ) : # type : ( Uploader ) - > None
"""Worker thread transfer
: param Uploader self : this""" | while not self . termination_check :
try :
ud , ase , offsets , data = self . _transfer_queue . get ( block = False , timeout = 0.1 )
except queue . Empty :
continue
try :
self . _process_transfer ( ud , ase , offsets , data )
except Exception as e :
with self . _upload_l... |
def cable_length ( self ) :
"""Returns cable length of connected skeleton vertices in the same
metric that this volume uses ( typically nanometers ) .""" | v1 = self . vertices [ self . edges [ : , 0 ] ]
v2 = self . vertices [ self . edges [ : , 1 ] ]
delta = ( v2 - v1 )
delta *= delta
dist = np . sum ( delta , axis = 1 )
dist = np . sqrt ( dist )
return np . sum ( dist ) |
def parse_timers ( self ) :
"""Parse the TIMER section reported in the ABINIT output files .
Returns :
: class : ` AbinitTimerParser ` object""" | filenames = list ( filter ( os . path . exists , [ task . output_file . path for task in self ] ) )
parser = AbinitTimerParser ( )
parser . parse ( filenames )
return parser |
def get_per_pixel_mean ( self , names = ( 'train' , 'test' ) ) :
"""Args :
names ( tuple [ str ] ) : the names ( ' train ' or ' test ' ) of the datasets
Returns :
a mean image of all images in the given datasets , with size 32x32x3""" | for name in names :
assert name in [ 'train' , 'test' ] , name
train_files , test_files , _ = get_filenames ( self . dir , self . cifar_classnum )
all_files = [ ]
if 'train' in names :
all_files . extend ( train_files )
if 'test' in names :
all_files . extend ( test_files )
all_imgs = [ x [ 0 ] for x in rea... |
def encode ( self , source_path , target_path , params ) : # NOQA : C901
"""Encodes a video to a specified file . All encoder specific options
are passed in using ` params ` .""" | total_time = self . get_media_info ( source_path ) [ 'duration' ]
cmds = [ self . ffmpeg_path , '-i' , source_path ]
cmds . extend ( self . params )
cmds . extend ( params )
cmds . extend ( [ target_path ] )
process = self . _spawn ( cmds )
buf = output = ''
# update progress
while True : # any more data ?
out = pr... |
def downside_risk ( returns , required_return = 0 , period = DAILY , annualization = None , out = None ) :
"""Determines the downside deviation below a threshold
Parameters
returns : pd . Series or np . ndarray or pd . DataFrame
Daily returns of the strategy , noncumulative .
- See full explanation in : fun... | allocated_output = out is None
if allocated_output :
out = np . empty ( returns . shape [ 1 : ] )
returns_1d = returns . ndim == 1
if len ( returns ) < 1 :
out [ ( ) ] = np . nan
if returns_1d :
out = out . item ( )
return out
ann_factor = annualization_factor ( period , annualization )
downside... |
def _get_fault_type_dummy_variables ( self , sites , rup , imt ) :
"""Same classification of SadighEtAl1997 . Akkar and Bommer 2010 is based
on Akkar and Bommer 2007b ; read Strong - Motion Dataset and Record
Processing on p . 514 ( Akkar and Bommer 2007b ) .""" | Fn , Fr = 0 , 0
if rup . rake >= - 135 and rup . rake <= - 45 : # normal
Fn = 1
elif rup . rake >= 45 and rup . rake <= 135 : # reverse
Fr = 1
return Fn , Fr |
def set_settings ( self , releases = None , default_release = None ) :
"""set path to storage""" | if ( self . _storage is None or getattr ( self , 'releases' , { } ) != releases or getattr ( self , 'default_release' , '' ) != default_release ) :
self . _storage = { }
self . releases = releases or { }
self . default_release = default_release |
def SensorShare ( self , sensor_id , parameters ) :
"""Share a sensor with a user
@ param sensor _ id ( int ) - Id of sensor to be shared
@ param parameters ( dictionary ) - Additional parameters for the call
@ return ( bool ) - Boolean indicating whether the ShareSensor call was successful""" | if not parameters [ 'user' ] [ 'id' ] :
parameters [ 'user' ] . pop ( 'id' )
if not parameters [ 'user' ] [ 'username' ] :
parameters [ 'user' ] . pop ( 'username' )
if self . __SenseApiCall__ ( "/sensors/{0}/users" . format ( sensor_id ) , "POST" , parameters = parameters ) :
return True
else :
self . ... |
def _update_libdata ( self , line ) :
"""Update the library meta data from the current line being parsed
Args :
line ( str ) : The current line of the of the file being parsed""" | # parse MONA Comments line
# The mona msp files contain a " comments " line that contains lots of other information normally separated
# into by " "
if re . match ( '^Comment.*$' , line , re . IGNORECASE ) :
comments = re . findall ( '"([^"]*)"' , line )
for c in comments :
self . _parse_meta_info ( c )... |
def use_plenary_assessment_part_view ( self ) :
"""Pass through to provider AssessmentPartLookupSession . use _ plenary _ assessment _ part _ view""" | self . _object_views [ 'assessment_part' ] = PLENARY
# self . _ get _ provider _ session ( ' assessment _ part _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_plenary_assessment_part_view ( )
except AttributeError :
... |
def random_tree ( n_leaves ) :
"""Randomly partition the nodes""" | def _random_subtree ( leaves ) :
if len ( leaves ) == 1 :
return leaves [ 0 ]
elif len ( leaves ) == 2 :
return ( leaves [ 0 ] , leaves [ 1 ] )
else :
split = npr . randint ( 1 , len ( leaves ) - 1 )
return ( _random_subtree ( leaves [ : split ] ) , _random_subtree ( leaves [... |
def get_html_desc ( self , markdown_inst = None ) :
"""Translates the node ' s ' desc ' property into HTML .
Any RDLFormatCode tags used in the description are converted to HTML .
The text is also fed through a Markdown processor .
The additional Markdown processing allows designers the choice to use a
more... | desc_str = self . get_property ( "desc" )
if desc_str is None :
return None
return rdlformatcode . rdlfc_to_html ( desc_str , self , md = markdown_inst ) |
def synchronize ( self , user , info ) :
'''It tries to do a group synchronization if possible
This methods should be redeclared by the developer''' | self . debug ( "Synchronize!" )
# Remove all groups from this user
user . groups . clear ( )
# For all domains found for this user
for domain in info [ 'groups' ] : # For all groups he is
for groupname in info [ 'groups' ] [ domain ] : # Lookup for that group
group = Group . objects . filter ( name = groupn... |
def create_nation_fixtures ( self ) :
"""Create national US and State Map""" | SHP_SLUG = "cb_{}_us_state_500k" . format ( self . YEAR )
DOWNLOAD_PATH = os . path . join ( self . DOWNLOAD_DIRECTORY , SHP_SLUG )
shape = shapefile . Reader ( os . path . join ( DOWNLOAD_PATH , "{}.shp" . format ( SHP_SLUG ) ) )
fields = shape . fields [ 1 : ]
field_names = [ f [ 0 ] for f in fields ]
features = [ ]
... |
def increment ( self , name , value ) :
"""Increments counter by given value .
: param name : a counter name of Increment type .
: param value : a value to add to the counter .""" | counter = self . get ( name , CounterType . Increment )
counter . count = counter . count + value if counter . count != None else value
self . _update ( ) |
def increment_frame ( self ) :
"""Increment a frame of the animation .""" | if self . current_frame < len ( self . images ) :
self . current_frame += 1
if self . current_frame >= len ( self . images ) : # Wrap back to the beginning of the animation if should _ repeat is true .
if self . should_repeat :
self . current_frame = 0
else : # Clamp the current fram... |
def normalized_indexes ( self , model_timesteps ) :
"""This function will normalize the particles locations
to the timestep of the model that was run . This is used
in output , as we should only be outputting the model timestep
that was chosen to be run .
In most cases , the length of the model _ timesteps ... | # Clean up locations
# If duplicate time instances , remove the lower index
clean_locs = [ ]
for i , loc in enumerate ( self . locations ) :
try :
if loc . time == self . locations [ i + 1 ] . time :
continue
else :
clean_locs . append ( loc )
except StandardError :
... |
async def get_webhook_info ( self ) -> types . WebhookInfo :
"""Use this method to get current webhook status . Requires no parameters .
If the bot is using getUpdates , will return an object with the url field empty .
Source : https : / / core . telegram . org / bots / api # getwebhookinfo
: return : On succ... | payload = generate_payload ( ** locals ( ) )
result = await self . request ( api . Methods . GET_WEBHOOK_INFO , payload )
return types . WebhookInfo ( ** result ) |
def get_all ( limit = '' ) :
'''Return all installed services . Use the ` ` limit ` ` param to restrict results
to services of that type .
CLI Example :
. . code - block : : bash
salt ' * ' service . get _ all
salt ' * ' service . get _ all limit = upstart
salt ' * ' service . get _ all limit = sysvinit... | limit = limit . lower ( )
if limit == 'upstart' :
return sorted ( _upstart_services ( ) )
elif limit == 'sysvinit' :
return sorted ( _sysv_services ( ) )
else :
return sorted ( _sysv_services ( ) + _upstart_services ( ) ) |
def to_epoch ( t ) :
"""Take a datetime , either as a string or a datetime . datetime object ,
and return the corresponding epoch""" | if isinstance ( t , str ) :
if '+' not in t :
t = t + '+00:00'
t = parser . parse ( t )
elif t . tzinfo is None or t . tzinfo . utcoffset ( t ) is None :
t = t . replace ( tzinfo = pytz . timezone ( 'utc' ) )
t0 = datetime . datetime ( 1970 , 1 , 1 , 0 , 0 , 0 , 0 , pytz . timezone ( 'utc' ) )
delta... |
def _get_present_locations ( match_traversals ) :
"""Return the set of locations and non - optional locations present in the given match traversals .
When enumerating the possibilities for optional traversals ,
the resulting match traversals may have sections of the query omitted .
These locations will not be... | present_locations = set ( )
present_non_optional_locations = set ( )
for match_traversal in match_traversals :
for step in match_traversal :
if step . as_block is not None :
location_name , _ = step . as_block . location . get_location_name ( )
present_locations . add ( location_name... |
def submit ( self , fn , * args , ** kwargs ) :
"""Submit an operation""" | corofn = asyncio . coroutine ( lambda : fn ( * args , ** kwargs ) )
return run_coroutine_threadsafe ( corofn ( ) , self . loop ) |
def __create_supervisor_session ( self , supervisor ) :
"""Create a new session on the supervisor service .
This is required in order to use most methods for the supervisor ,
so it is called implicitly when generating a supervisor session .""" | session_params = { 'forceLogoutSession' : self . force_logout_session , 'rollingPeriod' : self . rolling_period , 'statisticsRange' : self . statistics_range , 'shiftStart' : self . __to_milliseconds ( self . shift_start_hour , ) , 'timeZone' : self . __to_milliseconds ( self . time_zone_offset , ) , }
supervisor . set... |
def __add_default_values ( self ) :
"""Add default values if the settings info is not complete""" | self . __sp . setdefault ( 'assertionConsumerService' , { } )
self . __sp [ 'assertionConsumerService' ] . setdefault ( 'binding' , OneLogin_Saml2_Constants . BINDING_HTTP_POST )
self . __sp . setdefault ( 'attributeConsumingService' , { } )
self . __sp . setdefault ( 'singleLogoutService' , { } )
self . __sp [ 'single... |
def add ( self , connection ) :
'''Add a connection''' | key = ( connection . host , connection . port )
with self . _lock :
if key not in self . _connections :
self . _connections [ key ] = connection
self . added ( connection )
return connection
else :
return None |
def _badlink ( info , base ) :
"""Links are interpreted relative to the directory containing the link""" | tip = _resolved ( os . path . join ( base , os . path . dirname ( info . name ) ) )
return _badpath ( info . linkname , base = tip ) |
def setCols ( self , columns ) :
"""Sets the number of columns in the raster ( if rows have not been initialized , set to 1 as well )""" | self . _raster [ 1 ] = columns
if self . _raster [ 0 ] == 0 :
self . _raster [ 0 ] = 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.