signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def compute_stop_stats ( feed : "Feed" , dates : List [ str ] , stop_ids : Optional [ List [ str ] ] = None , headway_start_time : str = "07:00:00" , headway_end_time : str = "19:00:00" , * , split_directions : bool = False , ) -> DataFrame :
"""Compute stats for all stops for the given dates .
Optionally , restr... | dates = feed . restrict_dates ( dates )
if not dates :
return pd . DataFrame ( )
# Restrict stop times to stop IDs if specified
if stop_ids is not None :
stop_times_subset = feed . stop_times . loc [ lambda x : x [ "stop_id" ] . isin ( stop_ids ) ] . copy ( )
else :
stop_times_subset = feed . stop_times . c... |
def load_data_with_word2vec ( word2vec_list ) :
"""Loads and preprocessed data for the MR dataset .
Returns input vectors , labels , vocabulary , and inverse vocabulary .""" | # Load and preprocess data
sentences , labels = load_data_and_labels ( )
sentences_padded = pad_sentences ( sentences )
# vocabulary , vocabulary _ inv = build _ vocab ( sentences _ padded )
return build_input_data_with_word2vec ( sentences_padded , labels , word2vec_list ) |
def SetAndLoadTagFile ( self , tagging_file_path ) :
"""Sets the tag file to be used by the plugin .
Args :
tagging _ file _ path ( str ) : path of the tagging file .""" | tag_file = tagging_file . TaggingFile ( tagging_file_path )
self . _tagging_rules = tag_file . GetEventTaggingRules ( ) |
def build_fun ( self , layer = None ) :
"""Calculate the merkle root and make references between nodes in the tree .
Written in functional style purely for fun .""" | if not layer :
if not self . leaves :
raise MerkleError ( 'The tree has no leaves and cannot be calculated.' )
layer = self . leaves [ : : ]
layer = self . _build ( layer )
if len ( layer ) == 1 :
self . root = layer [ 0 ]
else :
self . build_fun ( layer = layer )
return self . root . val |
def handle_two_factor_check ( self , html : str ) -> requests . Response :
"""Handling two factor authorization request""" | action_url = get_base_url ( html )
code = input ( self . TWO_FACTOR_PROMPT ) . strip ( )
data = { 'code' : code , '_ajax' : '1' , 'remember' : '1' }
post_url = '/' . join ( ( self . LOGIN_URL , action_url ) )
return self . post ( post_url , data ) |
def get_config_paths ( config_name ) : # pragma : no test
"""Return a list of config files paths to try in order , given config file
name and possibly a user - specified path .
For Windows platforms , there are several paths that can be tried to
retrieve the netrc file . There is , however , no " standard way... | if platform . system ( ) != 'Windows' :
return [ None ]
# Now , we only treat the case of Windows
env_vars = [ [ "HOME" ] , [ "HOMEDRIVE" , "HOMEPATH" ] , [ "USERPROFILE" ] , [ "SYSTEMDRIVE" ] ]
env_dirs = [ ]
for var_list in env_vars :
var_values = [ _getenv_or_empty ( var ) for var in var_list ]
directory... |
def dir_visitor ( dirname , visitor ) :
"""_ dir _ visitor _
walk through all files in dirname , find
directories and call the callable on them .
: param dirname : Name of directory to start visiting ,
all subdirs will be visited
: param visitor : Callable invoked on each dir visited""" | visitor ( dirname )
for obj in os . listdir ( dirname ) :
obj_path = os . path . join ( dirname , obj )
if os . path . isdir ( obj_path ) :
dir_visitor ( obj_path , visitor ) |
def split_value ( val ) :
"""Splits a value * val * into its significand and decimal exponent ( magnitude ) and returns them in a
2 - tuple . * val * might also be a numpy array . Example :
. . code - block : : python
split _ value ( 1 ) # - > ( 1.0 , 0)
split _ value ( 0.123 ) # - > ( 1.23 , - 1)
split _... | val = ensure_nominal ( val )
if not is_numpy ( val ) : # handle 0 separately
if val == 0 :
return ( 0. , 0 )
mag = int ( math . floor ( math . log10 ( abs ( val ) ) ) )
sig = float ( val ) / ( 10. ** mag )
else :
log = np . zeros ( val . shape )
np . log10 ( np . abs ( val ) , out = log , wh... |
def get_colors ( img ) :
"""Returns a list of all the image ' s colors .""" | w , h = img . size
return [ color [ : 3 ] for count , color in img . convert ( 'RGB' ) . getcolors ( w * h ) ] |
def _create_configs ( cls , site ) :
"""This is going to generate the following configuration :
* wsgi . py
* < provider > . yml
* settings _ < provider > . py""" | provider = cls . name
cls . _render_config ( 'wsgi.py' , 'wsgi.py' , site )
# create yaml file
yaml_template_name = os . path . join ( provider , cls . provider_yml_name )
cls . _render_config ( cls . provider_yml_name , yaml_template_name , site )
# create requirements file
# don ' t do anything if the requirements fi... |
def remove_access_key_permissions ( self , access_key_id , permissions ) :
"""Removes a list of permissions from the existing list of permissions .
Will not remove all existing permissions unless all such permissions are included
in this list . Not to be confused with key revocation .
See also : revoke _ acce... | # Get current state via HTTPS .
current_access_key = self . get_access_key ( access_key_id )
# Copy and only change the single parameter .
payload_dict = KeenApi . _build_access_key_dict ( current_access_key )
# Turn into sets to avoid duplicates .
old_permissions = set ( payload_dict [ "permitted" ] )
removal_permissi... |
def textify ( self , nums : Collection [ int ] , sep = ' ' ) -> List [ str ] :
"Convert a list of ` nums ` to their tokens ." | return sep . join ( [ self . itos [ i ] for i in nums ] ) if sep is not None else [ self . itos [ i ] for i in nums ] |
def find_connected_sites ( bonds , am , flatten = True , logic = 'or' ) :
r"""Given an adjacency matrix , finds which sites are connected to the input
bonds .
Parameters
am : scipy . sparse matrix
The adjacency matrix of the network . Must be symmetrical such that if
sites * i * and * j * are connected , ... | if am . format != 'coo' :
raise Exception ( 'Adjacency matrix must be in COO format' )
bonds = sp . array ( bonds , ndmin = 1 )
if len ( bonds ) == 0 :
return [ ]
neighbors = sp . hstack ( ( am . row [ bonds ] , am . col [ bonds ] ) ) . astype ( sp . int64 )
if neighbors . size :
n_sites = sp . amax ( neigh... |
def storage_volume_attachments ( self ) :
"""Gets the StorageVolumeAttachments API client .
Returns :
StorageVolumeAttachments :""" | if not self . __storage_volume_attachments :
self . __storage_volume_attachments = StorageVolumeAttachments ( self . __connection )
return self . __storage_volume_attachments |
def cleanup ( self ) :
"""Move cached elements to top .""" | self . num_puts = 0
cached = [ ]
for i , url_data in enumerate ( self . queue ) :
key = url_data . cache_url
cache = url_data . aggregate . result_cache
if cache . has_result ( key ) :
cached . append ( i )
for pos in cached :
self . _move_to_top ( pos ) |
def wkt_polygon ( value ) :
"""Convert a string with a comma separated list of coordinates into
a WKT polygon , by closing the ring .""" | points = [ '%s %s' % ( lon , lat ) for lon , lat , dep in coordinates ( value ) ]
# close the linear polygon ring by appending the first coord to the end
points . append ( points [ 0 ] )
return 'POLYGON((%s))' % ', ' . join ( points ) |
def in_general_ns ( uri ) :
"""Return True iff the URI is in a well - known general RDF namespace .
URI namespaces considered well - known are RDF , RDFS , OWL , SKOS and DC .""" | RDFuri = RDF . uri
RDFSuri = RDFS . uri
for ns in ( RDFuri , RDFSuri , OWL , SKOS , DC ) :
if uri . startswith ( ns ) :
return True
return False |
def _get_on_demand_syllabus ( self , class_name ) :
"""Get the on - demand course listing webpage .""" | url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2 . format ( class_name = class_name )
page = get_page ( self . _session , url )
logging . debug ( 'Downloaded %s (%d bytes)' , url , len ( page ) )
return page |
def _set_src_ip_any ( self , v , load = False ) :
"""Setter method for src _ ip _ any , mapped from YANG variable / overlay / access _ list / type / vxlan / extended / ext _ seq / src _ ip _ any ( empty )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ src _ ip _ any is... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGBool , is_leaf = True , yang_name = "src-ip-any" , rest_name = "src-ip-any" , parent = self , choice = ( u'choice-src-ip' , u'case-src-ip-any' ) , path_helper = self . _path_helper , extmethods = self . _extmethods , regi... |
def get_message ( self , object_id = None , query = None , * , download_attachments = False ) :
"""Get one message from the query result .
A shortcut to get _ messages with limit = 1
: param object _ id : the message id to be retrieved .
: param query : applies a filter to the request such as
" displayName ... | if object_id is not None and query is not None :
raise ValueError ( 'Must provide object id or query but not both.' )
if object_id is not None :
url = self . build_url ( self . _endpoints . get ( 'message' ) . format ( id = object_id ) )
response = self . con . get ( url )
if not response :
retu... |
def match ( self , line ) :
'''Compare potentially partial criteria against line''' | entry = self . dict_from_line ( line )
for key , value in six . iteritems ( self . criteria ) :
if entry [ key ] != value :
return False
return True |
def unpack ( self , source : IO ) :
"""Read the Field from the file - like object ` fio ` .
. . note : :
Advanced usage only . You will typically never need to call this
method as it will be called for you when loading a ClassFile .
: param source : Any file - like object providing ` read ( ) `""" | self . access_flags . unpack ( source . read ( 2 ) )
self . _name_index , self . _descriptor_index = unpack ( '>HH' , source . read ( 4 ) )
self . attributes . unpack ( source ) |
def kth_smallest ( self , root , k ) :
""": type root : TreeNode
: type k : int
: rtype : int""" | count = [ ]
self . helper ( root , count )
return count [ k - 1 ] |
def handle_routine ( self , que , opts , host , target , mine = False ) :
'''Run the routine in a " Thread " , put a dict on the queue''' | opts = copy . deepcopy ( opts )
single = Single ( opts , opts [ 'argv' ] , host , mods = self . mods , fsclient = self . fsclient , thin = self . thin , mine = mine , ** target )
ret = { 'id' : single . id }
stdout , stderr , retcode = single . run ( )
# This job is done , yield
try :
data = salt . utils . json . f... |
def in_timezone ( self , tz ) : # type : ( Union [ str , Timezone ] ) - > DateTime
"""Set the instance ' s timezone from a string or object .""" | tz = pendulum . _safe_timezone ( tz )
return tz . convert ( self , dst_rule = pendulum . POST_TRANSITION ) |
def count_mismatches ( read ) :
"""look for NM : i : < N > flag to determine number of mismatches""" | if read is False :
return False
mm = [ int ( i . split ( ':' ) [ 2 ] ) for i in read [ 11 : ] if i . startswith ( 'NM:i:' ) ]
if len ( mm ) > 0 :
return sum ( mm )
else :
return False |
def make_table ( self ) :
"""Make numpy array from timeseries data .""" | num_records = np . sum ( [ 1 for frame in self . timeseries ] )
dtype = [ ( "frame" , float ) , ( "time" , float ) , ( "ligand atom id" , int ) , ( "ligand atom name" , "|U4" ) , ( "cutoff" , float ) , ( "protein atom names" , list ) , ( "protein atom ids" , list ) , ( "resid" , int ) , ( "resname" , "|U4" ) , ( "segid... |
def get_data_ttl ( self , use_cached = True ) :
"""Retrieve the dataTTL for this stream
The dataTtl is the time to live ( TTL ) in seconds for data points stored in the data stream .
A data point expires after the configured amount of time and is automatically deleted .
: param bool use _ cached : If False , ... | data_ttl_text = self . _get_stream_metadata ( use_cached ) . get ( "dataTtl" )
return int ( data_ttl_text ) |
def ack ( self ) :
"""Acknowledge this message as being processed . ,
This will remove the message from the queue .
: raises MessageStateError : If the message has already been
acknowledged / requeued / rejected .""" | if self . acknowledged :
raise self . MessageStateError ( "Message already acknowledged with state: %s" % self . _state )
self . backend . ack ( self . delivery_tag )
self . _state = "ACK" |
def print ( self ) :
"""Print self .""" | print ( '{dim}Identifier:{none} {cyan}{identifier}{none}\n' '{dim}Name:{none} {name}\n' '{dim}Description:{none}\n{description}' . format ( dim = Style . DIM , cyan = Fore . CYAN , none = Style . RESET_ALL , identifier = self . identifier , name = self . name , description = pretty_description ( self . description , in... |
def _print_message ( self , prefix , message , verbose = True ) :
'Prints a message and takes care of all sorts of nasty code' | # Load up the standard output .
output = [ '\n' , prefix , message [ 'message' ] ]
# We have some extra stuff for verbose mode .
if verbose :
verbose_output = [ ]
# Detailed problem description .
if message [ 'description' ] :
verbose_output . append ( self . _flatten_list ( message [ 'description' ... |
def NamedStar ( name ) :
"""DEPRECATED : See stars . rst for how to load a star catalog .""" | try :
hid = named_star_dict [ name ]
return hipparcos . get ( str ( hid ) )
except KeyError :
raise ValueError ( "No star named {0} known to skyfield." . format ( name ) ) |
def extract_as_epilog ( self , text , sections = None , overwrite = False , append = True ) :
"""Extract epilog sections from the a docstring
Parameters
text
The docstring to use
sections : list of str
The headers of the sections to extract . If None , the
: attr : ` epilog _ sections ` attribute is use... | if sections is None :
sections = self . epilog_sections
if ( ( not self . epilog or overwrite or append ) and sections ) :
epilog_parts = [ ]
for sec in sections :
text = docstrings . _get_section ( text , sec ) . strip ( )
if text :
epilog_parts . append ( self . format_epilog_s... |
def new ( self , ** kwargs ) :
''': param initializeFrom : ID of an existing app object from which to initialize the app
: type initializeFrom : string
: param applet : ID of the applet that the app will be created from
: type applet : string
: param name : Name of the app ( inherits from * initializeFrom *... | # TODO : add support for regionalOptions ( and deprecate top - level applet and resources )
dx_hash = { }
if 'applet' not in kwargs and 'initializeFrom' not in kwargs :
raise DXError ( "%s: One of the keyword arguments %s and %s is required" % ( self . __class__ . __name__ , 'applet' , 'initializeFrom' ) )
for fiel... |
def deserialize_object ( self , attr , ** kwargs ) :
"""Deserialize a generic object .
This will be handled as a dictionary .
: param dict attr : Dictionary to be deserialized .
: rtype : dict
: raises : TypeError if non - builtin datatype encountered .""" | if attr is None :
return None
if isinstance ( attr , ET . Element ) : # Do no recurse on XML , just return the tree as - is
return attr
if isinstance ( attr , basestring ) :
return self . deserialize_basic ( attr , 'str' )
obj_type = type ( attr )
if obj_type in self . basic_types :
return self . deseri... |
def update ( self ) :
"""Determine the number of response functions .
> > > from hydpy . models . arma import *
> > > parameterstep ( ' 1d ' )
> > > responses ( ( ( 1 . , 2 . ) , ( 1 . , ) ) , th _ 3 = ( ( 1 . , ) , ( 1 . , 2 . , 3 . ) ) )
> > > derived . nmb . update ( )
> > > derived . nmb
nmb ( 2)
... | pars = self . subpars . pars
responses = pars . control . responses
fluxes = pars . model . sequences . fluxes
self ( len ( responses ) )
fluxes . qpin . shape = self . value
fluxes . qpout . shape = self . value
fluxes . qma . shape = self . value
fluxes . qar . shape = self . value |
def from_string ( self , string_representation , resource = None ) :
"""Extracts resource data from the given string and converts them to
a new resource or updates the given resource from it .""" | stream = NativeIO ( string_representation )
return self . from_stream ( stream , resource = resource ) |
def stop ( self ) :
"""Close the ZAP socket""" | if self . zap_socket :
self . log . debug ( 'Stopping ZAP at {}' . format ( self . zap_socket . LAST_ENDPOINT ) )
super ( ) . stop ( ) |
def to_json ( self ) -> Mapping :
"""Return the properties of this : class : ` Sample ` as JSON serializable .""" | return { str ( x ) : str ( y ) for x , y in self . items ( ) } |
def _font_directories ( cls ) :
"""Return a sequence of directory paths likely to contain fonts on the
current platform .""" | if sys . platform . startswith ( 'darwin' ) :
return cls . _os_x_font_directories ( )
if sys . platform . startswith ( 'win32' ) :
return cls . _windows_font_directories ( )
raise OSError ( 'unsupported operating system' ) |
def evaluate ( self , verbose = False , decode = True , passes = None , num_threads = 1 , apply_experimental_transforms = True ) :
"""Evaluate the stored expression .
Parameters
verbose : bool , optional
Whether to print output for each Weld compilation step .
decode : bool , optional
Whether to decode th... | if isinstance ( self . weld_expr , WeldObject ) :
old_context = dict ( self . weld_expr . context )
for key in self . weld_expr . context . keys ( ) :
if LazyResult . _cache . contains ( key ) :
self . weld_expr . context [ key ] = LazyResult . _cache . get ( key )
evaluated = self . wel... |
def list_all_states_geo_zones ( cls , ** kwargs ) :
"""List StatesGeoZones
Return a list of StatesGeoZones
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . list _ all _ states _ geo _ zones ( async = True )
> > >... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _list_all_states_geo_zones_with_http_info ( ** kwargs )
else :
( data ) = cls . _list_all_states_geo_zones_with_http_info ( ** kwargs )
return data |
def main ( ) :
"""NAME
trmaq _ magic . py
DESCTIPTION
does non - linear trm acquisisiton correction
SYNTAX
trmaq _ magic . py [ - h ] [ - i ] [ command line options ]
OPTIONS
- h prints help message and quits
- i allows interactive setting of file names
- f MFILE , sets magic _ measurements input ... | meas_file = 'trmaq_measurements.txt'
tspec = "thellier_specimens.txt"
output = 'NLT_specimens.txt'
data_model_num = int ( float ( pmag . get_named_arg ( "-DM" , 3 ) ) )
if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-i' in sys . argv :
meas_file = input ( "Input magic_measurements file ... |
def contribute_to_class ( self , process , fields , name ) :
"""Register this field with a specific process .
: param process : Process descriptor instance
: param fields : Fields registry to use
: param name : Field name""" | # Use order - preserving definition namespace ( _ _ dict _ _ ) to respect the
# order of GroupField ' s fields definition .
for field_name in self . field_group . __dict__ :
if field_name . startswith ( '_' ) :
continue
field = getattr ( self . field_group , field_name )
field . contribute_to_class ... |
def _pop_index ( self , index , has_default ) :
"""Remove an element by index , or last element .""" | try :
if index is NOT_SET :
index = len ( self . _list ) - 1
key , value = self . _list . pop ( )
else :
key , value = self . _list . pop ( index )
if index < 0 :
index += len ( self . _list ) + 1
except IndexError :
if has_default :
return None , None , N... |
def read_spectral_data ( hdu ) :
"""Reads and returns the energy bin edges , fluxes and npreds from
a FITs HDU""" | ebins = read_energy_bounds ( hdu )
fluxes = np . ndarray ( ( len ( ebins ) ) )
try :
fluxes [ 0 : - 1 ] = hdu . data . field ( "E_MIN_FL" )
fluxes [ - 1 ] = hdu . data . field ( "E_MAX_FL" ) [ - 1 ]
npreds = hdu . data . field ( "NPRED" )
except :
fluxes = np . ones ( ( len ( ebins ) ) )
npreds = np... |
def transform ( request , syntax_processor_name = None , var_name = "text" ) :
"""Returns rendered HTML for source text""" | if request . method != 'POST' :
return HttpResponseNotAllowed ( "Only POST allowed" )
source = request . POST . get ( var_name )
if not source :
return HttpResponse ( '' )
processor = TextProcessor . objects . get ( name = syntax_processor_name or getattr ( settings , "DEFAULT_MARKUP" , "markdown" ) )
output = ... |
async def close_wallet ( handle : int ) -> None :
"""Closes opened wallet and frees allocated resources .
: param handle : wallet handle returned by indy _ open _ wallet .
: return : Error code""" | logger = logging . getLogger ( __name__ )
logger . debug ( "close_wallet: >>> handle: %i" , handle )
if not hasattr ( close_wallet , "cb" ) :
logger . debug ( "close_wallet: Creating callback" )
close_wallet . cb = create_cb ( CFUNCTYPE ( None , c_int32 , c_int32 ) )
c_handle = c_int32 ( handle )
await do_call ... |
def select ( self , to_select , where = None , sql_params = None ) :
'''select db entries
: param to _ select : string of fields to select
: param where : where clause ( default : None )
: param sql _ params : params for the where clause''' | if sql_params is None :
sql_params = [ ]
query = '''
SELECT %s FROM %s
''' % ( to_select , self . _name )
if where :
query = '%s WHERE %s' % ( query , where )
return self . _cursor . execute ( query , tuple ( sql_params ) ) |
def bootstrap_isc ( iscs , pairwise = False , summary_statistic = 'median' , n_bootstraps = 1000 , ci_percentile = 95 , random_state = None ) :
"""One - sample group - level bootstrap hypothesis test for ISCs
For ISCs from one more voxels or ROIs , resample subjects with replacement
to construct a bootstrap dis... | # Standardize structure of input data
iscs , n_subjects , n_voxels = _check_isc_input ( iscs , pairwise = pairwise )
# Check for valid summary statistic
if summary_statistic not in ( 'mean' , 'median' ) :
raise ValueError ( "Summary statistic must be 'mean' or 'median'" )
# Compute summary statistic for observed IS... |
async def handle_frame ( self , frame ) :
"""Handle incoming API frame , return True if this was the expected frame .""" | if not isinstance ( frame , FrameGetStateConfirmation ) :
return False
self . success = True
self . gateway_state = frame . gateway_state
self . gateway_sub_state = frame . gateway_sub_state
return True |
def run_cli ( argv = None ) :
"""Calls : func : ` wdiff ` and prints the results to STDERR .
Parses the options for : meth : ` wdiff ` with : func : ` parse _ commandline ` . If
* argv * is supplied , it is used as command line , else the actual one is used .
Return Codes
0 : okay
1 : error with arguments... | args = parse_commandline ( argv )
try :
context = get_context ( args )
settings = Settings ( args . org_file , args . new_file , ** context )
results = wdiff ( settings , args . wrap_with_html , args . fold_tags , args . hard_breaks )
print ( results )
return 0
except ContextError as err :
print... |
def fetch_binary ( self , fetch_request ) :
"""Fulfill a binary fetch request .""" | bootstrap_dir = os . path . realpath ( os . path . expanduser ( self . _bootstrap_dir ) )
bootstrapped_binary_path = os . path . join ( bootstrap_dir , fetch_request . download_path )
logger . debug ( "bootstrapped_binary_path: {}" . format ( bootstrapped_binary_path ) )
file_name = fetch_request . file_name
urls = fet... |
def generate_token ( minion_id , signature , impersonated_by_master = False ) :
'''Generate a Vault token for minion minion _ id
minion _ id
The id of the minion that requests a token
signature
Cryptographic signature which validates that the request is indeed sent
by the minion ( or the master , see impe... | log . debug ( 'Token generation request for %s (impersonated by master: %s)' , minion_id , impersonated_by_master )
_validate_signature ( minion_id , signature , impersonated_by_master )
try :
config = __opts__ [ 'vault' ]
verify = config . get ( 'verify' , None )
if config [ 'auth' ] [ 'method' ] == 'appro... |
def isAmbivalent ( self , dim = None ) :
"""Return True if any of the factors are in fact tuples .
If a dimension name is given only that dimension is tested .
> > > l = Location ( pop = 1)
> > > l . isAmbivalent ( )
False
> > > l = Location ( pop = 1 , snap = ( 100 , - 100 ) )
> > > l . isAmbivalent ( ... | if dim is not None :
try :
return isinstance ( self [ dim ] , tuple )
except KeyError : # dimension is not present , it should be 0 , so not ambivalent
return False
for dim , val in self . items ( ) :
if isinstance ( val , tuple ) :
return True
return False |
def energy_ratio_by_chunks ( x , param ) :
"""Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole
series .
Takes as input parameters the number num _ segments of segments to divide the series into and segment _ focus
which is the segment number ... | res_data = [ ]
res_index = [ ]
full_series_energy = np . sum ( x ** 2 )
for parameter_combination in param :
num_segments = parameter_combination [ "num_segments" ]
segment_focus = parameter_combination [ "segment_focus" ]
assert segment_focus < num_segments
assert num_segments > 0
res_data . append... |
def to_str ( s , encoding = None , errors = 'strict' ) :
"""Make str from any value
: param s :
: param encoding :
: param errors :
: return : str ( not unicode in Python2 , nor bytes in Python3)""" | encoding = encoding or 'utf-8'
if is_strlike ( s ) :
if six . PY2 :
return s . encode ( encoding , errors ) if isinstance ( s , unicode ) else s
else :
return s . decode ( encoding , errors ) if isinstance ( s , bytes ) else s
else :
return str ( s ) |
def update_or_create ( self , parent_id , title , body ) :
"""Update page or create a page if it is not exists
: param parent _ id :
: param title :
: param body :
: return :""" | space = self . get_page_space ( parent_id )
if self . page_exists ( space , title ) :
page_id = self . get_page_id ( space , title )
result = self . update_page ( parent_id = parent_id , page_id = page_id , title = title , body = body )
else :
result = self . create_page ( space = space , parent_id = parent... |
def connect ( self , output_name , input_method ) :
"""Connect an output to any callable object .
: param str output _ name : the output to connect . Must be one of
the ` ` ' self ' ` ` outputs in the ` ` linkages ` ` parameter .
: param callable input _ method : the thread - safe callable to invoke
when : ... | src , outbox = self . _compound_outputs [ output_name ]
self . _compound_children [ src ] . connect ( outbox , input_method ) |
def get_vnetwork_dvs_input_datacenter ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vnetwork_dvs = ET . Element ( "get_vnetwork_dvs" )
config = get_vnetwork_dvs
input = ET . SubElement ( get_vnetwork_dvs , "input" )
datacenter = ET . SubElement ( input , "datacenter" )
datacenter . text = kwargs . pop ( 'datacenter' )
callback = kwargs . pop ( 'callback' , self .... |
def get_form ( self , form_class ) :
"""Returns an instance of the form to be used in this view .""" | kwargs = self . kwargs
kwargs . update ( self . get_form_kwargs ( ) )
kwargs . update ( { 'request' : self . request , 'next_view' : WidgetCreateView } )
return form_class ( ** kwargs ) |
def _service_is_sysv ( name ) :
'''Return True if the service is a System V service ( includes those managed by
chkconfig ) ; otherwise return False .''' | try : # Look for user - execute bit in file mode .
return bool ( os . stat ( os . path . join ( '/etc/init.d' , name ) ) . st_mode & stat . S_IXUSR )
except OSError :
return False |
def gb2312_to_euc ( gb2312hex ) :
"""Convert GB2312-1980 hex ( internal representation ) to EUC - CN hex ( the
" external encoding " )""" | hi , lo = int ( gb2312hex [ : 2 ] , 16 ) , int ( gb2312hex [ 2 : ] , 16 )
hi , lo = hexd ( hi + 0x80 ) , hexd ( lo + 0x80 )
euc = "%s%s" % ( hi , lo )
assert isinstance ( euc , bytes )
return euc |
def dispatch ( self , * args , ** kwargs ) :
"""This decorator sets this view to have restricted permissions .""" | return super ( StrainCreate , self ) . dispatch ( * args , ** kwargs ) |
def modify_db_cluster ( DBClusterIdentifier = None , NewDBClusterIdentifier = None , ApplyImmediately = None , BackupRetentionPeriod = None , DBClusterParameterGroupName = None , VpcSecurityGroupIds = None , Port = None , MasterUserPassword = None , OptionGroupName = None , PreferredBackupWindow = None , PreferredMaint... | pass |
def get_etree_root ( doc , encoding = None ) :
"""Returns an instance of lxml . etree . _ Element for the given ` doc ` input .
Args :
doc : The input XML document . Can be an instance of
` ` lxml . etree . _ Element ` ` , ` ` lxml . etree . _ ElementTree ` ` , a file - like
object , or a string filename . ... | tree = get_etree ( doc , encoding )
root = tree . getroot ( )
return root |
def make_day_night_masks ( solarZenithAngle , good_mask , highAngleCutoff , lowAngleCutoff , stepsDegrees = None ) :
"""given information on the solarZenithAngle for each point ,
generate masks defining where the day , night , and mixed regions are
optionally provide the highAngleCutoff and lowAngleCutoff that ... | # if the caller passes None , we ' re only doing one step
stepsDegrees = highAngleCutoff - lowAngleCutoff if stepsDegrees is None else stepsDegrees
night_mask = ( solarZenithAngle > highAngleCutoff ) & good_mask
day_mask = ( solarZenithAngle <= lowAngleCutoff ) & good_mask
mixed_mask = [ ]
steps = list ( range ( lowAng... |
def version ( ) :
"""Return version string .""" | with open ( os . path . join ( 'curtsies' , '__init__.py' ) ) as input_file :
for line in input_file :
if line . startswith ( '__version__' ) :
return ast . parse ( line ) . body [ 0 ] . value . s |
def _delete_entity ( partition_key , row_key , if_match ) :
'''Constructs a delete entity request .''' | _validate_not_none ( 'if_match' , if_match )
_validate_not_none ( 'partition_key' , partition_key )
_validate_not_none ( 'row_key' , row_key )
request = HTTPRequest ( )
request . method = 'DELETE'
request . headers = [ _DEFAULT_ACCEPT_HEADER , ( 'If-Match' , _to_str ( if_match ) ) ]
return request |
def __make_request_headers ( self , teststep_dict , entry_json ) :
"""parse HAR entry request headers , and make teststep headers .
header in IGNORE _ REQUEST _ HEADERS will be ignored .
Args :
entry _ json ( dict ) :
" request " : {
" headers " : [
{ " name " : " Host " , " value " : " httprunner . top... | teststep_headers = { }
for header in entry_json [ "request" ] . get ( "headers" , [ ] ) :
if header [ "name" ] . lower ( ) in IGNORE_REQUEST_HEADERS :
continue
teststep_headers [ header [ "name" ] ] = header [ "value" ]
if teststep_headers :
teststep_dict [ "request" ] [ "headers" ] = teststep_heade... |
def hardware_connector_group_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
hardware = ET . SubElement ( config , "hardware" , xmlns = "urn:brocade.com:mgmt:brocade-hardware" )
connector_group = ET . SubElement ( hardware , "connector-group" )
id = ET . SubElement ( connector_group , "id" )
id . text = kwargs . pop ( 'id' )
callback = kwargs . pop ( 'callback... |
def maybe_center_plot ( result ) :
"""Embeds a possible tikz image inside a center environment .
Searches for matplotlib2tikz last commend line to detect tikz images .
Args :
result : The code execution result
Returns :
The input result if no tikzpicture was found , otherwise a centered
version .""" | begin = re . search ( '(% .* matplotlib2tikz v.*)' , result )
if begin :
result = ( '\\begin{center}\n' + result [ begin . end ( ) : ] + '\n\\end{center}' )
return result |
def _copy_and_clean_up_expectation ( self , expectation , discard_result_format_kwargs = True , discard_include_configs_kwargs = True , discard_catch_exceptions_kwargs = True , ) :
"""Returns copy of ` expectation ` without ` success _ on _ last _ run ` and other specified key - value pairs removed
Returns a copy... | new_expectation = copy . deepcopy ( expectation )
if "success_on_last_run" in new_expectation :
del new_expectation [ "success_on_last_run" ]
if discard_result_format_kwargs :
if "result_format" in new_expectation [ "kwargs" ] :
del new_expectation [ "kwargs" ] [ "result_format" ]
# discards [ "... |
def get_mapper_graph ( simplicial_complex , color_function = None , color_function_name = None , colorscale = None , custom_tooltips = None , custom_meta = None , X = None , X_names = None , lens = None , lens_names = None , ) :
"""Generate data for mapper graph visualization and annotation .
Parameters
simplic... | if not colorscale :
colorscale = default_colorscale
if not len ( simplicial_complex [ "nodes" ] ) > 0 :
raise Exception ( "A mapper graph should have more than 0 nodes. This might be because your clustering algorithm might be too sensitive and be classifying all points as noise." )
color_function = init_color_f... |
def openTypeOS2TypoLineGapFallback ( info ) :
"""Fallback to * UPM * 1.2 - ascender + descender * , or zero if that ' s negative .""" | return max ( int ( info . unitsPerEm * 1.2 ) - info . ascender + info . descender , 0 ) |
def py_resources ( ) :
"""Discovers all aomi Vault resource models . This includes
anything extending aomi . model . Mount or aomi . model . Resource .""" | aomi_mods = [ m for m , _v in iteritems ( sys . modules ) if m . startswith ( 'aomi.model' ) ]
mod_list = [ ]
mod_map = [ ]
for amod in [ sys . modules [ m ] for m in aomi_mods ] :
for _mod_bit , model in inspect . getmembers ( amod ) :
if str ( model ) in mod_list :
continue
if model ==... |
def getshapestring ( self , startrow = 1 , nrow = - 1 , rowincr = 1 ) :
"""Get the shapes of all cells in the column in string format .
( see : func : ` table . getcolshapestring ` )""" | return self . _table . getcolshapestring ( self . _column , startrow , nrow , rowincr ) |
def _probvec ( r , out ) :
"""Fill ` out ` with randomly sampled probability vectors as rows .
To be complied as a ufunc by guvectorize of Numba . The inputs must
have the same shape except the last axis ; the length of the last
axis of ` r ` must be that of ` out ` minus 1 , i . e . , if out . shape [ - 1 ] ... | n = r . shape [ 0 ]
r . sort ( )
out [ 0 ] = r [ 0 ]
for i in range ( 1 , n ) :
out [ i ] = r [ i ] - r [ i - 1 ]
out [ n ] = 1 - r [ n - 1 ] |
def _sconnect ( host = None , port = None , password = None ) :
'''Returns an instance of the redis client''' | if host is None :
host = __salt__ [ 'config.option' ] ( 'redis_sentinel.host' , 'localhost' )
if port is None :
port = __salt__ [ 'config.option' ] ( 'redis_sentinel.port' , 26379 )
if password is None :
password = __salt__ [ 'config.option' ] ( 'redis_sentinel.password' )
return redis . StrictRedis ( host ... |
def artist_undelete ( self , artist_id ) :
"""Lets you undelete artist ( Requires login ) ( UNTESTED ) ( Only Builder + ) .
Parameters :
artist _ id ( int ) :""" | return self . _get ( 'artists/{0}/undelete.json' . format ( artist_id ) , method = 'POST' , auth = True ) |
def dataframe ( self ) :
"""Returns a pandas DataFrame containing all other class properties and
values . The index for the DataFrame is the string URI that is used to
instantiate the class , such as ' 2017-11-10-21 - kansas ' .""" | if self . _away_points is None and self . _home_points is None :
return None
fields_to_include = { 'away_assist_percentage' : self . away_assist_percentage , 'away_assists' : self . away_assists , 'away_block_percentage' : self . away_block_percentage , 'away_blocks' : self . away_blocks , 'away_defensive_rating' :... |
def tag ( cwd , name , ref = 'HEAD' , message = None , opts = '' , git_opts = '' , user = None , password = None , ignore_retcode = False , output_encoding = None ) :
'''. . versionadded : : 2018.3.4
Interface to ` git - tag ( 1 ) ` _ , adds and removes tags .
cwd
The path to the main git checkout or a linked... | cwd = _expand_path ( cwd , user )
command = [ 'git' ] + _format_git_opts ( git_opts )
command . append ( 'tag' )
# Don ' t add options for annotated tags , since we ' ll automatically add them
# if a message was passed . This keeps us from blocking on input , as passing
# these options without a separate message option... |
def _watch_refresh_source ( self , event ) :
"""Refresh sources then templates""" | self . logger . info ( "Sources changed..." )
try :
self . sources = self . _get_sources ( )
self . _render_template ( self . sources )
except :
pass |
def next_tip ( self , num_tips : int = 1 ) -> Optional [ Well ] :
"""Find the next valid well for pick - up .
Determines the next valid start tip from which to retrieve the
specified number of tips . There must be at least ` num _ tips ` sequential
wells for which all wells have tips , in the same column .
... | assert num_tips > 0
columns : List [ List [ Well ] ] = self . columns ( )
drop_leading_empties = [ list ( dropwhile ( lambda x : not x . has_tip , column ) ) for column in columns ]
drop_at_first_gap = [ list ( takewhile ( lambda x : x . has_tip , column ) ) for column in drop_leading_empties ]
long_enough = [ column f... |
def is_sibling_of ( self , node ) :
""": returns : ` ` True ` ` if the node is a sibling of another node given as an
argument , else , returns ` ` False ` `
: param node :
The node that will be checked as a sibling""" | return self . get_siblings ( ) . filter ( pk = node . pk ) . exists ( ) |
def _convertTmp ( self , tmpCacheEntry ) :
"""Moves a tmp file to the upload dir , resampling it if necessary , and then deleting the tmp entries .
: param tmpCacheEntry : the cache entry .
: return :""" | from analyser . common . signal import loadSignalFromWav
tmpCacheEntry [ 'status' ] = 'converting'
logger . info ( "Loading " + tmpCacheEntry [ 'path' ] )
signal = loadSignalFromWav ( tmpCacheEntry [ 'path' ] )
logger . info ( "Loaded " + tmpCacheEntry [ 'path' ] )
if Path ( tmpCacheEntry [ 'path' ] ) . exists ( ) :
... |
def compile ( self , X , verbose = False ) :
"""method to validate and prepare data - dependent parameters
Parameters
X : array - like
Input dataset
verbose : bool
whether to show warnings
Returns
None""" | if self . feature >= X . shape [ 1 ] :
raise ValueError ( 'term requires feature {}, ' 'but X has only {} dimensions' . format ( self . feature , X . shape [ 1 ] ) )
self . edge_knots_ = gen_edge_knots ( X [ : , self . feature ] , self . dtype , verbose = verbose )
return self |
def join ( self , timeout = None ) :
"""Wait for the thread to finish , may raise an
exception ( if any is uncaught during execution ) ,
and return the value returned by the target
function .""" | rv = self . thread . join ( timeout )
if self . err :
raise self . err
return self . val |
def effective_task_id ( self ) :
"""Replace date in task id with closest date .""" | params = self . param_kwargs
if 'date' in params and is_closest_date_parameter ( self , 'date' ) :
params [ 'date' ] = self . closest ( )
task_id_parts = sorted ( [ '%s=%s' % ( k , str ( v ) ) for k , v in params . items ( ) ] )
return '%s(%s)' % ( self . task_family , ', ' . join ( task_id_parts ) )
else :... |
def set_bg_data ( self , bg_data , which_data = None ) :
"""Set background amplitude and phase data
Parameters
bg _ data : 2d ndarray ( float or complex ) , list , QPImage , or ` None `
The background data ( must be same type as ` data ` ) .
If set to ` None ` , the background data is reset .
which _ data... | if isinstance ( bg_data , QPImage ) :
if which_data is not None :
msg = "`which_data` must not be set if `bg_data` is QPImage!"
raise ValueError ( msg )
pha , amp = bg_data . pha , bg_data . amp
elif bg_data is None : # Reset phase and amplitude
amp , pha = None , None
else : # Compute phase... |
def authenticate ( self , msg : Dict , identifier : Optional [ str ] = None , signature : Optional [ str ] = None , threshold : Optional [ int ] = None , key : Optional [ str ] = None ) -> str :
"""Authenticate the client ' s message with the signature provided .
: param identifier : some unique identifier ; if N... | |
def main ( src_file , dest_file , ** kwargs ) :
"""Given an input layers file and a directory , print the compiled
XML file to stdout and save any encountered external image files
to the named directory .""" | mmap = mapnik . Map ( 1 , 1 )
# allow [ zoom ] filters to work
mmap . srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null'
load_kwargs = dict ( [ ( k , v ) for ( k , v ) in kwargs . items ( ) if k in ( 'cache_dir' , 'scale' , 'verbose' , 'datasources_cfg' , 'us... |
def _configure_context ( ctx , opts , skip = ( ) ) :
"""Configures context of public key operations
@ param ctx - context to configure
@ param opts - dictionary of options ( from kwargs of calling
function )
@ param skip - list of options which shouldn ' t be passed to
context""" | for oper in opts :
if oper in skip :
continue
if isinstance ( oper , chartype ) :
op = oper . encode ( "ascii" )
else :
op = oper
if isinstance ( opts [ oper ] , chartype ) :
value = opts [ oper ] . encode ( "ascii" )
elif isinstance ( opts [ oper ] , bintype ) :
... |
def get_parcellation ( atlas , parcel_param ) :
"Placeholder to insert your own function to return parcellation in reference space ." | parc_path = os . path . join ( atlas , 'parcellation_param{}.mgh' . format ( parcel_param ) )
parcel = nibabel . freesurfer . io . read_geometry ( parc_path )
return parcel |
def get_safe_format ( product_id = None , tile = None , entire_product = False , bands = None , data_source = DataSource . SENTINEL2_L1C ) :
"""Returns . SAFE format structure in form of nested dictionaries . Either ` ` product _ id ` ` or ` ` tile ` ` must be specified .
: param product _ id : original ESA produ... | entire_product = entire_product and product_id is None
if tile is not None :
safe_tile = SafeTile ( tile_name = tile [ 0 ] , time = tile [ 1 ] , bands = bands , data_source = data_source )
if not entire_product :
return safe_tile . get_safe_struct ( )
product_id = safe_tile . get_product_id ( )
if p... |
def source ( fname ) :
'''Acts similar to bash ' source ' or ' . ' commands .''' | rex = re . compile ( '(?:export |declare -x )?(.*?)="(.*?)"' )
out = call_out ( 'source {} && export' . format ( fname ) )
out = [ x for x in out if 'export' in x or 'declare' in x ]
out = { k : v for k , v in [ rex . match ( x ) . groups ( ) for x in out if rex . match ( x ) ] }
for k , v in out . items ( ) :
os .... |
def ipv6_acl_ipv6_access_list_standard_seq_action ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
ipv6_acl = ET . SubElement ( config , "ipv6-acl" , xmlns = "urn:brocade.com:mgmt:brocade-ipv6-access-list" )
ipv6 = ET . SubElement ( ipv6_acl , "ipv6" )
access_list = ET . SubElement ( ipv6 , "access-list" )
standard = ET . SubElement ( access_list , "standard" )
name_key = ET . SubE... |
def get_rendition ( self , output_scale = 1 , ** kwargs ) : # pylint : disable = too - many - locals
"""Get the rendition for this image , generating it if necessary .
Returns a tuple of ` ( relative _ path , width , height ) ` , where relative _ path
is relative to the static file directory ( i . e . what one ... | basename , ext = os . path . splitext ( os . path . basename ( self . _record . file_path ) )
basename = utils . make_slug ( basename )
if kwargs . get ( 'format' ) :
ext = '.' + kwargs [ 'format' ]
# The spec for building the output filename
out_spec = [ basename , self . _record . checksum [ - 10 : ] ]
out_args =... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : MemberContext for this MemberInstance
: rtype : twilio . rest . api . v2010 . account . queue . member . MemberContext""" | if self . _context is None :
self . _context = MemberContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , queue_sid = self . _solution [ 'queue_sid' ] , call_sid = self . _solution [ 'call_sid' ] , )
return self . _context |
def getaddress ( self ) :
"""Parse the next address .""" | self . commentlist = [ ]
self . gotonext ( )
oldpos = self . pos
oldcl = self . commentlist
plist = self . getphraselist ( )
self . gotonext ( )
returnlist = [ ]
if self . pos >= len ( self . field ) : # Bad email address technically , no domain .
if plist :
returnlist = [ ( SPACE . join ( self . commentlis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.