signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def backend ( self ) :
'''Returns the : class : ` stdnet . BackendStructure ` .''' | session = self . session
if session is not None :
if self . _field :
return session . model ( self . _field . model ) . backend
else :
return session . model ( self ) . backend |
def purge_stream ( self , stream_id , remove_definition = False , sandbox = None ) :
"""Purge the stream
: param stream _ id : The stream identifier
: param remove _ definition : Whether to remove the stream definition as well
: param sandbox : The sandbox for this stream
: return : None""" | super ( AssetsChannel , self ) . purge_stream ( stream_id = stream_id , remove_definition = remove_definition , sandbox = sandbox ) |
def findOrCreate ( self , userItemClass , __ifnew = None , ** attrs ) :
"""Usage : :
s . findOrCreate ( userItemClass [ , function ] [ , x = 1 , y = 2 , . . . ] )
Example : :
class YourItemType ( Item ) :
a = integer ( )
b = text ( )
c = integer ( )
def f ( x ) :
print x , \" - - it ' s new ! \"
s... | andargs = [ ]
for k , v in attrs . iteritems ( ) :
col = getattr ( userItemClass , k )
andargs . append ( col == v )
if len ( andargs ) == 0 :
cond = [ ]
elif len ( andargs ) == 1 :
cond = [ andargs [ 0 ] ]
else :
cond = [ attributes . AND ( * andargs ) ]
for result in self . query ( userItemClass ,... |
def absolute_path ( string ) :
'''" Convert " a string to a string that is an absolute existing path .''' | if not os . path . isabs ( string ) :
msg = '{0!r} is not an absolute path' . format ( string )
raise argparse . ArgumentTypeError ( msg )
if not os . path . exists ( os . path . dirname ( string ) ) :
msg = 'path {0!r} does not exist' . format ( string )
raise argparse . ArgumentTypeError ( msg )
retur... |
def syncDependencies ( self , recursive = False ) :
"""Syncs the dependencies for this item to the view .
: param recurisve | < bool >""" | scene = self . viewItem ( ) . scene ( )
if not scene :
return
visible = self . viewItem ( ) . isVisible ( )
depViewItems = self . _dependencies . values ( )
depViewItems += self . _reverseDependencies . values ( )
for depViewItem in depViewItems :
if not depViewItem . scene ( ) :
scene . addItem ( depVi... |
def edit ( text = None , editor = None , env = None , require_save = True , extension = '.txt' , filename = None ) :
r"""Edits the given text in the defined editor . If an editor is given
( should be the full path to the executable but the regular operating
system search path is used for finding the executable ... | from . _termui_impl import Editor
editor = Editor ( editor = editor , env = env , require_save = require_save , extension = extension )
if filename is None :
return editor . edit ( text )
editor . edit_file ( filename ) |
def get_node ( self , name , memory = False , binary = False ) :
"""An individual node in the RabbitMQ cluster . Set " memory = true " to get
memory statistics , and " binary = true " to get a breakdown of binary
memory use ( may be expensive if there are many small binaries in the
system ) .""" | return self . _api_get ( url = '/api/nodes/{0}' . format ( name ) , params = dict ( binary = binary , memory = memory , ) , ) |
def run ( configObj , wcsmap = None ) :
"""Interface for running ` wdrizzle ` from TEAL or Python command - line .
This code performs all file ` ` I / O ` ` to set up the use of the drizzle code for
a single exposure to replicate the functionality of the original ` wdrizzle ` .""" | # Insure all output filenames specified have . fits extensions
if configObj [ 'outdata' ] [ - 5 : ] != '.fits' :
configObj [ 'outdata' ] += '.fits'
if not util . is_blank ( configObj [ 'outweight' ] ) and configObj [ 'outweight' ] [ - 5 : ] != '.fits' :
configObj [ 'outweight' ] += '.fits'
if not util . is_blan... |
def rsys2graph ( rsys , fname , output_dir = None , prog = None , save = False , ** kwargs ) :
"""Convenience function to call ` rsys2dot ` and write output to file
and render the graph
Parameters
rsys : ReactionSystem
fname : str
filename
output _ dir : str ( optional )
path to directory ( default : ... | lines = rsys2dot ( rsys , ** kwargs )
created_tempdir = False
try :
if output_dir is None :
output_dir = tempfile . mkdtemp ( )
created_tempdir = True
basename , ext = os . path . splitext ( os . path . basename ( fname ) )
outpath = os . path . join ( output_dir , fname )
dotpath = os .... |
def setWidth ( self , typeID , width ) :
"""setWidth ( string , double ) - > None
Sets the width in m of vehicles of this type .""" | self . _connection . _sendDoubleCmd ( tc . CMD_SET_VEHICLETYPE_VARIABLE , tc . VAR_WIDTH , typeID , width ) |
def run_through ( script , ensemble , roles = 1 , strict = False ) :
""": py : class : ` turberfield . dialogue . model . SceneScript ` .""" | with script as dialogue :
selection = dialogue . select ( ensemble , roles = roles )
if not any ( selection . values ( ) ) or strict and not all ( selection . values ( ) ) :
return
try :
model = dialogue . cast ( selection ) . run ( )
except ( AttributeError , ValueError ) as e :
... |
def join ( self , queue_name , * , fail_fast = False , timeout = None ) :
"""Wait for all the messages on the given queue to be
processed . This method is only meant to be used in tests
to wait for all the messages in a queue to be processed .
Raises :
QueueJoinTimeout : When the timeout elapses .
QueueNo... | try :
queues = [ self . queues [ queue_name ] , self . queues [ dq_name ( queue_name ) ] , ]
except KeyError :
raise QueueNotFound ( queue_name )
deadline = timeout and time . monotonic ( ) + timeout / 1000
while True :
for queue in queues :
timeout = deadline and deadline - time . monotonic ( )
... |
def find_any_reports ( self , usage_page = 0 , usage_id = 0 ) :
"""Find any report type referencing HID usage control / data item .
Results are returned in a dictionary mapping report _ type to usage
lists .""" | items = [ ( HidP_Input , self . find_input_reports ( usage_page , usage_id ) ) , ( HidP_Output , self . find_output_reports ( usage_page , usage_id ) ) , ( HidP_Feature , self . find_feature_reports ( usage_page , usage_id ) ) , ]
return dict ( [ ( t , r ) for t , r in items if r ] ) |
def get_lastblock ( cls , impl , working_dir ) :
"""What was the last block processed ?
Return the number on success
Return None on failure to read""" | if not cls . db_exists ( impl , working_dir ) :
return None
con = cls . db_open ( impl , working_dir )
query = 'SELECT MAX(block_id) FROM snapshots;'
rows = cls . db_query_execute ( con , query , ( ) , verbose = False )
ret = None
for r in rows :
ret = r [ 'MAX(block_id)' ]
con . close ( )
return ret |
def report_bar ( bytes_so_far , total_size , speed , eta ) :
'''This callback for the download function is used to print the download bar''' | percent = int ( bytes_so_far * 100 / total_size )
current = approximate_size ( bytes_so_far ) . center ( 9 )
total = approximate_size ( total_size ) . center ( 9 )
shaded = int ( float ( bytes_so_far ) / total_size * AVAIL_WIDTH )
sys . stdout . write ( " {0}% [{1}{2}{3}] {4}/{5} {6} eta{7}" . format ( str ( percent ) ... |
def peek ( self ) :
"""Peek at the oldest reading in this virtual stream .""" | if self . reading is None :
raise StreamEmptyError ( "peek called on virtual stream walker without any data" , selector = self . selector )
return self . reading |
def _get_class_name ( error_code ) :
"""Gets the corresponding class name for the given error code ,
this either being an integer ( thus base error name ) or str .""" | if isinstance ( error_code , int ) :
return KNOWN_BASE_CLASSES . get ( error_code , 'RPCError' + str ( error_code ) . replace ( '-' , 'Neg' ) )
return snake_to_camel_case ( error_code . replace ( 'FIRSTNAME' , 'FIRST_NAME' ) . lower ( ) , suffix = 'Error' ) |
def rightClick ( x = None , y = None , duration = 0.0 , tween = linear , pause = None , _pause = True ) :
"""Performs a right mouse button click .
This is a wrapper function for click ( ' right ' , x , y ) .
The x and y parameters detail where the mouse event happens . If None , the
current mouse position is ... | _failSafeCheck ( )
click ( x , y , 1 , 0.0 , 'right' , _pause = False )
_autoPause ( pause , _pause ) |
def histogram_pb ( tag , data , buckets = None , description = None ) :
"""Create a histogram summary protobuf .
Arguments :
tag : String tag for the summary .
data : A ` np . array ` or array - like form of any shape . Must have type
castable to ` float ` .
buckets : Optional positive ` int ` . The outpu... | bucket_count = DEFAULT_BUCKET_COUNT if buckets is None else buckets
data = np . array ( data ) . flatten ( ) . astype ( float )
if data . size == 0 :
buckets = np . array ( [ ] ) . reshape ( ( 0 , 3 ) )
else :
min_ = np . min ( data )
max_ = np . max ( data )
range_ = max_ - min_
if range_ == 0 :
... |
def objective_names ( lang = "en" ) :
"""This resource returns a list of the localized WvW objective names for
the specified language .
: param lang : The language to query the names for .
: return : A dictionary mapping the objective Ids to the names .
* Note that these are not the names displayed in the g... | params = { "lang" : lang }
cache_name = "objective_names.%(lang)s.json" % params
data = get_cached ( "wvw/objective_names.json" , cache_name , params = params )
return dict ( [ ( objective [ "id" ] , objective [ "name" ] ) for objective in data ] ) |
def launch_workflow ( seqs_fp , working_dir , mean_error , error_dist , indel_prob , indel_max , trim_length , left_trim_length , min_size , ref_fp , ref_db_fp , threads_per_sample = 1 , sim_thresh = None , coverage_thresh = None ) :
"""Launch full deblur workflow for a single post split - libraries fasta file
Pa... | logger = logging . getLogger ( __name__ )
logger . info ( '--------------------------------------------------------' )
logger . info ( 'launch_workflow for file %s' % seqs_fp )
# Step 1 : Trim sequences to specified length
output_trim_fp = join ( working_dir , "%s.trim" % basename ( seqs_fp ) )
with open ( output_trim_... |
def make_absolute ( base , relative ) :
"""Make the given ( relative ) URL absolute .
Args :
base ( str ) : The absolute URL the relative url was found on .
relative ( str ) : The ( possibly relative ) url to make absolute .
Returns :
str : The absolute URL .""" | # Python 3.4 and lower do not remove folder traversal strings .
# This was fixed in 3.5 ( https : / / docs . python . org / 3 / whatsnew / 3.5 . html # urllib )
while relative . startswith ( '/../' ) or relative . startswith ( '../' ) :
relative = relative [ 3 : ]
base_parsed = urlparse ( base )
new_path = ... |
def _validate_ding0_mv_grid_import ( grid , ding0_grid ) :
"""Verify imported data with original data from Ding0
Parameters
grid : MVGrid
MV Grid data ( eDisGo )
ding0 _ grid : ding0 . MVGridDing0
Ding0 MV grid object
Notes
The data validation excludes grid components located in aggregated load
area... | integrity_checks = [ 'branch_tee' , 'disconnection_point' , 'mv_transformer' , 'lv_station' # , ' line ' ,
]
data_integrity = { }
data_integrity . update ( { _ : { 'ding0' : None , 'edisgo' : None , 'msg' : None } for _ in integrity_checks } )
# Check number of branch tees
data_integrity [ 'branch_tee' ] [ 'ding0' ] = ... |
def status ( self , ** kwargs ) :
"""Get the status of the geo node .
Args :
* * kwargs : Extra options to send to the server ( e . g . sudo )
Raises :
GitlabAuthenticationError : If authentication is not correct
GitlabGetError : If the server failed to perform the request
Returns :
dict : The status ... | path = '/geo_nodes/%s/status' % self . get_id ( )
return self . manager . gitlab . http_get ( path , ** kwargs ) |
def get_field_values_list ( self , d ) :
"""Iterate over a ( possibly nested ) dict , and return a list
of all children queries , as a dict of the following structure :
' field ' : ' some _ field _ _ iexact ' ,
' value ' : ' some _ value ' ,
' value _ from ' : ' optional _ range _ val1 ' ,
' value _ to ' ... | fields = [ ]
children = d . get ( 'children' , [ ] )
for child in children :
if isinstance ( child , dict ) :
fields . extend ( self . get_field_values_list ( child ) )
else :
f = { 'field' : child [ 0 ] , 'value' : child [ 1 ] }
if self . _is_range ( child ) :
f [ 'value_fro... |
def _unsupported_message_type ( self ) :
"""Check if the current message matches the configured message type ( s ) .
: rtype : bool""" | if isinstance ( self . _message_type , ( tuple , list , set ) ) :
return self . message_type not in self . _message_type
return self . message_type != self . _message_type |
def _Bound_hs ( h , s ) :
"""Region definition for input h and s
Parameters
h : float
Specific enthalpy , [ kJ / kg ]
s : float
Specific entropy , [ kJ / kgK ]
Returns
region : float
IAPWS - 97 region code
References
Wagner , W ; Kretzschmar , H - J : International Steam Tables : Properties of
... | region = None
s13 = _Region1 ( 623.15 , 100 ) [ "s" ]
s13s = _Region1 ( 623.15 , Ps_623 ) [ "s" ]
sTPmax = _Region2 ( 1073.15 , 100 ) [ "s" ]
s2ab = _Region2 ( 1073.15 , 4 ) [ "s" ]
# Left point in h - s plot
smin = _Region1 ( 273.15 , 100 ) [ "s" ]
hmin = _Region1 ( 273.15 , Pmin ) [ "h" ]
# Right point in h - s plot
... |
def generate_sections ( self ) :
"""Return all hubs , slugs , and upload counts .""" | datasets = Dataset . objects . values ( 'hub_slug' ) . annotate ( upload_count = Count ( 'hub_slug' ) ) . order_by ( '-upload_count' )
return [ { 'count' : dataset [ 'upload_count' ] , 'name' : get_hub_name_from_slug ( dataset [ 'hub_slug' ] ) , 'slug' : dataset [ 'hub_slug' ] } for dataset in datasets ] |
def complement ( self , frame_bound = None ) :
r"""Return the filter that makes the frame tight .
The complementary filter is designed such that the union of a filter
bank and its complementary filter forms a tight frame .
Parameters
frame _ bound : float or None
The desired frame bound : math : ` A = B `... | def kernel ( x , * args , ** kwargs ) :
y = self . evaluate ( x )
np . power ( y , 2 , out = y )
y = np . sum ( y , axis = 0 )
if frame_bound is None :
bound = y . max ( )
elif y . max ( ) > frame_bound :
raise ValueError ( 'The chosen bound is not feasible. ' 'Choose at least {}.' .... |
def _print_summary ( case , summary ) :
"""Show some statistics from the run""" | for dof , data in summary . items ( ) :
b4b = data [ "Bit for Bit" ]
conf = data [ "Configurations" ]
stdout = data [ "Std. Out Files" ]
print ( " " + case + " " + str ( dof ) )
print ( " --------------------" )
print ( " Bit for bit matches : " + str ( b4b [ 0 ] ) + " of " + str ( b... |
def generate_psk ( self , security_key ) :
"""Generate and set a psk from the security key .""" | if not self . _psk : # Backup the real identity .
existing_psk_id = self . _psk_id
# Set the default identity and security key for generation .
self . _psk_id = 'Client_identity'
self . _psk = security_key
# Ask the Gateway to generate the psk for the identity .
self . _psk = self . request ( Ga... |
def run_sparser ( pmid_list , tmp_dir , num_cores , start_index , end_index , force_read , force_fulltext , cleanup = True , verbose = True ) :
'Run the sparser reader on the pmids in pmid _ list .' | reader_version = sparser . get_version ( )
_ , _ , _ , pmids_read , pmids_unread , _ = get_content_to_read ( pmid_list , start_index , end_index , tmp_dir , num_cores , force_fulltext , force_read , 'sparser' , reader_version )
logger . info ( 'Adjusting num cores to length of pmid_list.' )
num_cores = min ( len ( pmid... |
def get_answer ( self , question ) :
"""Asks user a question , then gets user answer
: param question : Question : to ask user
: return : User answer""" | self . last_question = str ( question ) . strip ( )
user_answer = input ( self . last_question )
return user_answer . strip ( ) |
def set_preferred_prefix_for_namespace ( self , ns_uri , prefix , add_if_not_exist = False ) :
"""Sets the preferred prefix for ns _ uri . If add _ if _ not _ exist is True ,
the prefix is added if it ' s not already registered . Otherwise ,
setting an unknown prefix as preferred is an error . The default
is ... | ni = self . __lookup_uri ( ns_uri )
if not prefix :
ni . preferred_prefix = None
elif prefix in ni . prefixes :
ni . preferred_prefix = prefix
elif add_if_not_exist :
self . add_prefix ( ns_uri , prefix , set_as_preferred = True )
else :
raise PrefixNotFoundError ( prefix ) |
def add_source ( self , filename , env_filename ) :
"""Add a source to the PEX environment .
: param filename : The source filename to add to the PEX ; None to create an empty file at
` env _ filename ` .
: param env _ filename : The destination filename in the PEX . This path
must be a relative path .""" | self . _ensure_unfrozen ( 'Adding source' )
self . _copy_or_link ( filename , env_filename , "source" ) |
def calculate_megno ( self ) :
"""Return the current MEGNO value .
Note that you need to call init _ megno ( ) before the start of the simulation .""" | if self . _calculate_megno == 0 :
raise RuntimeError ( "MEGNO cannot be calculated. Make sure to call init_megno() after adding all particles but before integrating the simulation." )
clibrebound . reb_tools_calculate_megno . restype = c_double
return clibrebound . reb_tools_calculate_megno ( byref ( self ) ) |
def add_time_step ( self , ** create_time_step_kwargs ) :
"""Creates a time - step and appends it to the list .
Args :
* * create _ time _ step _ kwargs : Forwarded to
time _ step . TimeStep . create _ time _ step .""" | ts = time_step . TimeStep . create_time_step ( ** create_time_step_kwargs )
assert isinstance ( ts , time_step . TimeStep )
self . _time_steps . append ( ts ) |
def moderate ( self , environ , request , id , action , key ) :
try :
id = self . isso . unsign ( key , max_age = 2 ** 32 )
except ( BadSignature , SignatureExpired ) :
raise Forbidden
item = self . comments . get ( id )
thread = self . threads . get ( item [ 'tid' ] )
link = local (... | |
def getPlot ( self , params ) :
"""Override this function
arguments :
params ( dict )
returns :
matplotlib . pyplot figure""" | try :
return eval ( "self." + str ( params [ 'output_id' ] ) + "(params)" )
except AttributeError :
df = self . getData ( params )
if df is None :
return None
return df . plot ( ) |
def license ( self , license_id : str , token : dict = None , prot : str = "https" ) -> dict :
"""Get details about a specific license .
: param str token : API auth token
: param str license _ id : license UUID
: param str prot : https [ DEFAULT ] or http
( use it only for dev and tracking needs ) .""" | # handling request parameters
payload = { "lid" : license_id }
# search request
license_url = "{}://v1.{}.isogeo.com/licenses/{}" . format ( prot , self . api_url , license_id )
license_req = self . get ( license_url , headers = self . header , params = payload , proxies = self . proxies , verify = self . ssl , )
# che... |
def com_google_fonts_check_metadata_unique_weight_style_pairs ( family_metadata ) :
"""METADATA . pb : check if fonts field
only contains unique style : weight pairs .""" | pairs = { }
for f in family_metadata . fonts :
styleweight = f"{f.style}:{f.weight}"
pairs [ styleweight ] = 1
if len ( set ( pairs . keys ( ) ) ) != len ( family_metadata . fonts ) :
yield FAIL , ( "Found duplicated style:weight pair" " in METADATA.pb fonts field." )
else :
yield PASS , ( "METADATA.pb ... |
def _fix_squeeze ( self , inputs , new_attr ) :
"""MXNet doesnt have a squeeze operator .
Using " split " to perform similar operation .
" split " can be slower compared to " reshape " .
This can have performance impact .
TODO : Remove this implementation once mxnet adds the support .""" | axes = new_attr . get ( 'axis' )
op = mx . sym . split ( inputs [ 0 ] , axis = axes [ 0 ] , num_outputs = 1 , squeeze_axis = 1 )
for i in axes [ 1 : ] :
op = mx . sym . split ( op , axis = i - 1 , num_outputs = 1 , squeeze_axis = 1 )
return op |
def make_python_name ( s , default = None , number_prefix = 'N' , encoding = "utf-8" ) :
"""Returns a unicode string that can be used as a legal python identifier .
: Arguments :
string
* default *
use * default * if * s * is ` ` None ` `
* number _ prefix *
string to prepend if * s * starts with a numb... | if s in ( '' , None ) :
s = default
s = str ( s )
s = re . sub ( "[^a-zA-Z0-9_]" , "_" , s )
if not re . match ( '\d' , s ) is None :
s = number_prefix + s
return unicode ( s , encoding ) |
def update_refchip_with_shift ( chip_wcs , wcslin , fitgeom = 'rscale' , rot = 0.0 , scale = 1.0 , xsh = 0.0 , ysh = 0.0 , fit = None , xrms = None , yrms = None ) :
"""Compute the matrix for the scale and rotation correction
Parameters
chip _ wcs : wcs object
HST of the input image
wcslin : wcs object
Re... | # compute the matrix for the scale and rotation correction
if fit is None :
fit = linearfit . buildFitMatrix ( rot , scale )
shift = np . asarray ( [ xsh , ysh ] ) - np . dot ( wcslin . wcs . crpix , fit ) + wcslin . wcs . crpix
fit = np . linalg . inv ( fit ) . T
cwcs = chip_wcs . deepcopy ( )
cd_eye = np . eye ( ... |
def check_upgrade_impact ( system_image , kickstart_image = None , issu = True , ** kwargs ) :
'''Display upgrade impact information without actually upgrading the device .
system _ image ( Mandatory Option )
Path on bootflash : to system image upgrade file .
kickstart _ image
Path on bootflash : to kicksta... | # Input Validation
if not isinstance ( issu , bool ) :
return 'Input Error: The [issu] parameter must be either True or False'
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; show install all impact'
if ki is not None :
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}' . format... |
def _agent_registration ( self ) :
"""Register this agent with the server .
This method registers the cfg agent with the neutron server so hosting
devices can be assigned to it . In case the server is not ready to
accept registration ( it sends a False ) then we retry registration
for ` MAX _ REGISTRATION _... | for attempts in range ( MAX_REGISTRATION_ATTEMPTS ) :
context = bc . context . get_admin_context_without_session ( )
self . send_agent_report ( self . agent_state , context )
try :
res = self . devmgr_rpc . register_for_duty ( context )
except Exception :
res = False
LOG . warnin... |
def parse ( self , argument ) :
"""Parses argument as whitespace - separated list of strings .
It also parses argument as comma - separated list of strings if requested .
Args :
argument : string argument passed in the commandline .
Returns :
[ str ] , the parsed flag value .""" | if isinstance ( argument , list ) :
return argument
elif not argument :
return [ ]
else :
if self . _comma_compat :
argument = argument . replace ( ',' , ' ' )
return argument . split ( ) |
def cli ( ctx , organism = "" , sequence = "" ) :
"""[ UNTESTED ] Get all of the sequence ' s alterations
Output :
A list of sequence alterations ( ? )""" | return ctx . gi . annotations . get_sequence_alterations ( organism = organism , sequence = sequence ) |
def _get_recursive_state ( widget , store = None , drop_defaults = False ) :
"""Gets the embed state of a widget , and all other widgets it refers to as well""" | if store is None :
store = dict ( )
state = widget . _get_embed_state ( drop_defaults = drop_defaults )
store [ widget . model_id ] = state
# Loop over all values included in state ( i . e . don ' t consider excluded values ) :
for ref in _find_widget_refs_by_state ( widget , state [ 'state' ] ) :
if ref . mode... |
def plot_emg_spect_freq ( freq_axis , power_axis , max_freq , median_freq ) :
"""Brief
A plot with frequency power spectrum of the input EMG signal is presented graphically , highlighting maximum and
median power frequency .
Description
Function intended to generate a single Bokeh figure graphically describ... | # List that store the figure handler
list_figures = [ ]
# Plotting of EMG Power Spectrum
list_figures . append ( figure ( x_axis_label = 'Frequency (Hz)' , y_axis_label = 'Relative Power (a.u.)' , ** opensignals_kwargs ( "figure" ) ) )
list_figures [ - 1 ] . line ( freq_axis , power_axis , legend = "Power Spectrum" , *... |
def fdpf ( self ) :
"""Fast Decoupled Power Flow
Returns
bool , int
Success flag , number of iterations""" | system = self . system
# general settings
self . niter = 1
iter_max = self . config . maxit
self . solved = True
tol = self . config . tol
error = tol + 1
self . iter_mis = [ ]
if ( not system . Line . Bp ) or ( not system . Line . Bpp ) :
system . Line . build_b ( )
# initialize indexing and Jacobian
# ngen = syst... |
def _can_for_object ( self , func_name , object_id , method_name ) :
"""Checks if agent can perform function for object""" | can_for_session = self . _can ( func_name )
if ( can_for_session or self . _object_catalog_session is None or self . _override_lookup_session is None ) :
return can_for_session
override_auths = self . _override_lookup_session . get_authorizations_for_agent_and_function ( self . get_effective_agent_id ( ) , self . _... |
async def post ( self , public_key ) :
"""Writes contents review""" | if settings . SIGNATURE_VERIFICATION :
super ( ) . verify ( )
try :
body = json . loads ( self . request . body )
except :
self . set_status ( 400 )
self . write ( { "error" : 400 , "reason" : "Unexpected data format. JSON required" } )
raise tornado . web . Finish
if isinstance ( body [ "message" ]... |
def explode ( col ) :
"""Returns a new row for each element in the given array or map .
Uses the default column name ` col ` for elements in the array and
` key ` and ` value ` for elements in the map unless specified otherwise .
> > > from pyspark . sql import Row
> > > eDF = spark . createDataFrame ( [ Ro... | sc = SparkContext . _active_spark_context
jc = sc . _jvm . functions . explode ( _to_java_column ( col ) )
return Column ( jc ) |
def get_no_validate ( self , key ) :
"""Return an item without validating the schema .""" | x , env = self . get_thunk_env ( key )
# Check if this is a Thunk that needs to be lazily evaluated before we
# return it .
if isinstance ( x , framework . Thunk ) :
x = framework . eval ( x , env )
return x |
def convert ( self , verbose = True ) :
""": rtype : tuple
: returns : Output containers , messages""" | input_transformer = self . _input_class ( self . _filename )
output_transformer = self . _output_class ( )
containers = input_transformer . ingest_containers ( )
output_containers = [ ]
for container in containers :
converted_container = self . _convert_container ( container , input_transformer , output_transformer... |
def from_dict ( cls , d ) :
"""Returns : CompleteDos object from dict representation .""" | tdos = Dos . from_dict ( d )
struct = Structure . from_dict ( d [ "structure" ] )
pdoss = { }
for i in range ( len ( d [ "pdos" ] ) ) :
at = struct [ i ]
orb_dos = { }
for orb_str , odos in d [ "pdos" ] [ i ] . items ( ) :
orb = orb_str
orb_dos [ orb ] = { Spin ( int ( k ) ) : v for k , v in... |
def forwards ( self , orm ) :
"Perform a ' safe ' load using Avocado ' s backup utilities ." | from avocado . core import backup
backup . safe_load ( u'0002_avocado_metadata' , backup_path = None , using = 'default' ) |
def _shuffle ( y , labels , random_state ) :
"""Return a shuffled copy of y eventually shuffle among same labels .""" | if labels is None :
ind = random_state . permutation ( len ( y ) )
else :
ind = np . arange ( len ( labels ) )
for label in np . unique ( labels ) :
this_mask = ( labels == label )
ind [ this_mask ] = random_state . permutation ( ind [ this_mask ] )
return y [ ind ] |
def _transliterate ( self , text , outFormat ) :
"""Transliterate the text to the target transliteration scheme .""" | result = [ ]
for c in text :
if c . isspace ( ) :
result . append ( c )
try :
result . append ( self [ c ] . equivalents [ outFormat . name ] )
except KeyError :
result . append ( _unrecognised ( c ) )
return result |
def get_all_integration ( self , ** kwargs ) : # noqa : E501
"""Gets a flat list of all Wavefront integrations available , along with their status # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > >... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . get_all_integration_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . get_all_integration_with_http_info ( ** kwargs )
# noqa : E501
return data |
def convert_conelp ( c , G , h , dims , A = None , b = None , ** kwargs ) :
"""Applies the clique conversion method of Fukuda et al . to the positive semidefinite blocks of a cone LP .
: param c : : py : class : ` matrix `
: param G : : py : class : ` spmatrix `
: param h : : py : class : ` matrix `
: param... | # extract linear and socp constraints
offsets = dims [ 'l' ] + sum ( dims [ 'q' ] )
G_lq = G [ : offsets , : ]
h_lq = h [ : offsets , 0 ]
# extract semidefinite blocks
G_s = G [ offsets : , : ]
h_s = h [ offsets : , 0 ]
G_converted = [ G_lq ] ;
h_converted = [ h_lq ]
G_coupling = [ ]
dims_list = [ ]
symbs = [ ]
offset ... |
def add ( self , instance , modified = True , persistent = None , force_update = False ) :
'''Add a new instance to this : class : ` SessionModel ` .
: param modified : Optional flag indicating if the ` ` instance ` ` has been
modified . By default its value is ` ` True ` ` .
: param force _ update : if ` ` i... | if instance . _meta . type == 'structure' :
return self . _add_structure ( instance )
state = instance . get_state ( )
if state . deleted :
raise ValueError ( 'State is deleted. Cannot add.' )
self . pop ( state . iid )
pers = persistent if persistent is not None else state . persistent
pkname = instance . _met... |
def assert_equal ( self , v1 , v2 , ** kwargs ) : # , desc = None , screenshot = False , safe = False ) :
"""Check v1 is equals v2 , and take screenshot if not equals
Args :
- desc ( str ) : some description
- safe ( bool ) : will omit AssertionError if set to True
- screenshot : can be type < None | True |... | is_success = v1 == v2
if is_success :
message = "assert equal success, %s == %s" % ( v1 , v2 )
else :
message = '%s not equal %s' % ( v1 , v2 )
kwargs . update ( { 'message' : message , 'success' : is_success , } )
self . _add_assert ( ** kwargs ) |
def saveProfile ( self , key , settings = None ) :
"""Writes the view settings to the persistent store
: param key : key where the setting will be read from
: param settings : optional QSettings object which can have a group already opened .""" | # logger . debug ( " Writing view settings for : { } " . format ( key ) )
if settings is None :
settings = QtCore . QSettings ( )
settings . setValue ( key , self . horizontalHeader ( ) . saveState ( ) ) |
def send_activation_email ( self , user , profile , password , site ) :
"""Custom send email method to supplied the activation link and
new generated password .""" | ctx_dict = { 'password' : password , 'site' : site , 'activation_key' : profile . activation_key , 'expiration_days' : settings . ACCOUNT_ACTIVATION_DAYS }
subject = render_to_string ( 'registration/email/emails/password_subject.txt' , ctx_dict )
# Email subject * must not * contain newlines
subject = '' . join ( subje... |
def remove ( self ) :
"""Interface to remove a migration request from the queue .
Only Permanent FAILED / 9 and PENDING / 0 requests can be removed
( running and sucessed requests cannot be removed )""" | body = request . body . read ( )
indata = cjson . decode ( body )
try :
indata = validateJSONInputNoCopy ( "migration_rqst" , indata )
return self . dbsMigrate . removeMigrationRequest ( indata )
except dbsException as he :
dbsExceptionHandler ( he . eCode , he . message , self . logger . exception , he . m... |
def convert_nb ( fname , dest_path = '.' ) :
"Convert a notebook ` fname ` to html file in ` dest _ path ` ." | from . gen_notebooks import remove_undoc_cells , remove_code_cell_jupyter_widget_state_elem
nb = read_nb ( fname )
nb [ 'cells' ] = remove_undoc_cells ( nb [ 'cells' ] )
nb [ 'cells' ] = remove_code_cell_jupyter_widget_state_elem ( nb [ 'cells' ] )
fname = Path ( fname ) . absolute ( )
dest_name = fname . with_suffix (... |
def push_notebook ( document = None , state = None , handle = None ) :
'''Update Bokeh plots in a Jupyter notebook output cells with new data
or property values .
When working the the notebook , the ` ` show ` ` function can be passed the
argument ` ` notebook _ handle = True ` ` , which will cause it to retu... | from . . protocol import Protocol
if state is None :
state = curstate ( )
if not document :
document = state . document
if not document :
warn ( "No document to push" )
return
if handle is None :
handle = state . last_comms_handle
if not handle :
warn ( "Cannot find a last shown plot to update. ... |
def convert_docx_to_text ( filename : str = None , blob : bytes = None , config : TextProcessingConfig = _DEFAULT_CONFIG ) -> str :
"""Converts a DOCX file to text .
Pass either a filename or a binary object .
Args :
filename : filename to process
blob : binary ` ` bytes ` ` object to process
config : : c... | if True :
text = ''
with get_filelikeobject ( filename , blob ) as fp :
for xml in gen_xml_files_from_docx ( fp ) :
text += docx_text_from_xml ( xml , config )
return text |
def display_modules_list ( self ) :
"""Display modules list""" | print ( "Plugins list: {}" . format ( ', ' . join ( sorted ( self . stats . getPluginsList ( enable = False ) ) ) ) )
print ( "Exporters list: {}" . format ( ', ' . join ( sorted ( self . stats . getExportsList ( enable = False ) ) ) ) ) |
def _make_request_with_auth_fallback ( self , url , headers = None , params = None ) :
"""Generic request handler for OpenStack API requests
Raises specialized Exceptions for commonly encountered error codes""" | self . log . debug ( "Request URL and Params: %s, %s" , url , params )
try :
resp = requests . get ( url , headers = headers , verify = self . _ssl_verify , params = params , timeout = DEFAULT_API_REQUEST_TIMEOUT , proxies = self . proxy_config , )
resp . raise_for_status ( )
except requests . exceptions . HTTP... |
def merge_entries_with_common_prefixes ( list_ , number_of_needed_commons = 6 ) :
"""Returns a list where sequences of post - fixed entries are shortened to their common prefix .
This might be useful in cases of several similar values ,
where the prefix is identical for several entries .
If less than ' number... | # first find common entry - sequences
prefix = None
lists_to_merge = [ ]
for entry in list_ :
newPrefix , number = split_string_at_suffix ( entry , numbers_into_suffix = True )
if entry == newPrefix or prefix != newPrefix :
lists_to_merge . append ( [ ] )
prefix = newPrefix
lists_to_merge [ ... |
def fetch_certs ( certificate_list , user_agent = None , timeout = 10 ) :
"""Fetches certificates from the authority information access extension of
an asn1crypto . crl . CertificateList object and places them into the
cert registry .
: param certificate _ list :
An asn1crypto . crl . CertificateList object... | output = [ ]
if user_agent is None :
user_agent = 'certvalidator %s' % __version__
elif not isinstance ( user_agent , str_cls ) :
raise TypeError ( 'user_agent must be a unicode string, not %s' % type_name ( user_agent ) )
for url in certificate_list . issuer_cert_urls :
request = Request ( url )
reques... |
def readGlobalFile ( self , fileStoreID , userPath = None , cache = True , mutable = False , symlink = False ) :
"""Downloads a file described by fileStoreID from the file store to the local directory .
The function first looks for the file in the cache and if found , it hardlinks to the
cached copy instead of ... | # Check that the file hasn ' t been deleted by the user
if fileStoreID in self . filesToDelete :
raise RuntimeError ( 'Trying to access a file in the jobStore you\'ve deleted: ' + '%s' % fileStoreID )
# Get the name of the file as it would be in the cache
cachedFileName = self . encodedFileID ( fileStoreID )
# setu... |
def links ( self ) :
"""Include previous and next links .""" | links = super ( OffsetLimitPaginatedList , self ) . links
if self . _page . offset + self . _page . limit < self . count :
links [ "next" ] = Link . for_ ( self . _operation , self . _ns , qs = self . _page . next_page . to_items ( ) , ** self . _context )
if self . offset > 0 :
links [ "prev" ] = Link . for_ (... |
def useful_mimetype ( text ) :
"""Check to see if the given mime type is a MIME type
which is useful in terms of how to treat this file .""" | if text is None :
return False
mimetype = normalize_mimetype ( text )
return mimetype not in [ DEFAULT , PLAIN , None ] |
def upload_from_shared_memory ( self , location , bbox , order = 'F' , cutout_bbox = None ) :
"""Upload from a shared memory array .
https : / / github . com / seung - lab / cloud - volume / wiki / Advanced - Topic : - Shared - Memory
tip : If you want to use slice notation , np . s _ [ . . . ] will help in a p... | def tobbox ( x ) :
if type ( x ) == Bbox :
return x
return Bbox . from_slices ( x )
bbox = tobbox ( bbox )
cutout_bbox = tobbox ( cutout_bbox ) if cutout_bbox else bbox . clone ( )
if not bbox . contains_bbox ( cutout_bbox ) :
raise exceptions . AlignmentError ( """
The provided cutout is no... |
def iris ( display = False ) :
"""Return the classic iris data in a nice package .""" | d = sklearn . datasets . load_iris ( )
df = pd . DataFrame ( data = d . data , columns = d . feature_names )
# pylint : disable = E1101
if display :
return df , [ d . target_names [ v ] for v in d . target ]
# pylint : disable = E1101
else :
return df , d . target |
def _create_gate_variables ( self , input_shape , dtype ) :
"""Initialize the variables used for the gates .""" | if len ( input_shape ) != 2 :
raise ValueError ( "Rank of shape must be {} not: {}" . format ( 2 , len ( input_shape ) ) )
equiv_input_size = self . _hidden_state_size + input_shape . dims [ 1 ] . value
initializer = basic . create_linear_initializer ( equiv_input_size )
self . _w_xh = tf . get_variable ( self . W_... |
def check_request ( headers : Headers ) -> str :
"""Check a handshake request received from the client .
If the handshake is valid , this function returns the ` ` key ` ` which must be
passed to : func : ` build _ response ` .
Otherwise it raises an : exc : ` ~ websockets . exceptions . InvalidHandshake `
e... | connection = sum ( [ parse_connection ( value ) for value in headers . get_all ( "Connection" ) ] , [ ] )
if not any ( value . lower ( ) == "upgrade" for value in connection ) :
raise InvalidUpgrade ( "Connection" , ", " . join ( connection ) )
upgrade = sum ( [ parse_upgrade ( value ) for value in headers . get_al... |
def fpr ( y , z ) :
"""False positive rate ` fp / ( fp + tn ) `""" | tp , tn , fp , fn = contingency_table ( y , z )
return fp / ( fp + tn ) |
def register_on_extra_data_changed ( self , callback ) :
"""Set the callback function to consume on extra data changed
events .
Callback receives a IExtraDataChangedEvent object .
Returns the callback _ id""" | event_type = library . VBoxEventType . on_extra_data_changed
return self . event_source . register_callback ( callback , event_type ) |
def is_stats_query ( query ) :
"""check if the query is a normal search or select query
: param query :
: return :""" | if not query :
return False
# remove all " enclosed strings
nq = re . sub ( r'"[^"]*"' , '' , query )
# check if there ' s | . . . . select
if re . findall ( r'\|.*\bselect\b' , nq , re . I | re . DOTALL ) :
return True
return False |
def copy ( self ) :
"""Return a new instance with the same attributes .""" | return self . __class__ ( [ b . copy ( ) for b in self . blocks ] , tuple ( self . pos ) if self . pos else None ) |
def main ( ) :
'''main routine''' | # process arguments
if len ( sys . argv ) < 4 :
usage ( )
rgname = sys . argv [ 1 ]
vmss_name = sys . argv [ 2 ]
capacity = sys . argv [ 3 ]
# Load Azure app defaults
try :
with open ( 'azurermconfig.json' ) as config_file :
config_data = json . load ( config_file )
except FileNotFoundError :
print ... |
def area_fraction_dict ( self ) :
"""Returns :
( dict ) : { hkl : area _ hkl / total area on wulff }""" | return { hkl : self . miller_area_dict [ hkl ] / self . surface_area for hkl in self . miller_area_dict . keys ( ) } |
def get_within_delta ( key , app = None ) :
"""Get a timedelta object from the application configuration following
the internal convention of : :
< Amount of Units > < Type of Units >
Examples of valid config values : :
5 days
10 minutes
: param key : The config value key without the ' SECURITY _ ' pref... | txt = config_value ( key , app = app )
values = txt . split ( )
return timedelta ( ** { values [ 1 ] : int ( values [ 0 ] ) } ) |
async def handler ( event ) :
"""# learn or # python : Tells the user to learn some Python first .""" | await asyncio . wait ( [ event . delete ( ) , event . respond ( LEARN_PYTHON , reply_to = event . reply_to_msg_id , link_preview = False ) ] ) |
def withArgs ( self , * args , ** kwargs ) : # pylint : disable = invalid - name
"""Adds a condition for when the stub is called . When the condition is met , a special
return value can be returned . Adds the specified argument ( s ) into the condition list .
For example , when the stub function is called with ... | cond_args = args if len ( args ) > 0 else None
cond_kwargs = kwargs if len ( kwargs ) > 0 else None
return _SinonStubCondition ( copy = self . _copy , cond_args = cond_args , cond_kwargs = cond_kwargs , oncall = self . _oncall ) |
def get_repository_hierarchy_session ( self , proxy ) :
"""Gets the repository hierarchy traversal session .
arg proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . repository . RepositoryHierarchySession ) - a
RepositoryHierarchySession
raise : OperationFailed - unable to complete request
raise : ... | if not self . supports_repository_hierarchy ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise
# OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . RepositoryHierarchySession ( proxy , runtime = self . _runtime )
except Attribute... |
def fetch_data ( blob , start_index , end_index , ** options ) :
"""Fetch data for blob .
Fetches a fragment of a blob up to MAX _ BLOB _ FETCH _ SIZE in length . Attempting
to fetch a fragment that extends beyond the boundaries of the blob will return
the amount of data from start _ index until the end of th... | fut = fetch_data_async ( blob , start_index , end_index , ** options )
return fut . get_result ( ) |
def next_previous ( self , photo , options = None , ** kwds ) :
"""Endpoint : / photo / < id > / nextprevious [ / < options > ] . json
Returns a dict containing the next and previous photo lists
( there may be more than one next / previous photo returned ) .
The options parameter can be used to narrow down th... | option_string = self . _build_option_string ( options )
result = self . _client . get ( "/photo/%s/nextprevious%s.json" % ( self . _extract_id ( photo ) , option_string ) , ** kwds ) [ "result" ]
value = { }
if "next" in result : # Workaround for APIv1
if not isinstance ( result [ "next" ] , list ) : # pragma : no ... |
async def async_run_command ( self , command , first_try = True ) :
"""Run a command through a Telnet connection .
Connect to the Telnet server if not currently connected , otherwise
use the existing connection .""" | await self . async_connect ( )
try :
with ( await self . _io_lock ) :
self . _writer . write ( '{}\n' . format ( "%s && %s" % ( _PATH_EXPORT_COMMAND , command ) ) . encode ( 'ascii' ) )
data = ( ( await asyncio . wait_for ( self . _reader . readuntil ( self . _prompt_string ) , 9 ) ) . split ( b'\n'... |
def climatology ( self , startclim , endclim , ** kwargs ) :
r"""Returns a climatology of observations at a user specified location for a specified time . Users must specify
at least one geographic search parameter ( ' stid ' , ' state ' , ' country ' , ' county ' , ' radius ' , ' bbox ' , ' cwa ' ,
' nwsfirezo... | self . _check_geo_param ( kwargs )
kwargs [ 'startclim' ] = startclim
kwargs [ 'endclim' ] = endclim
kwargs [ 'token' ] = self . token
return self . _get_response ( 'stations/climatology' , kwargs ) |
def get_issue ( issue_number , repo_name = None , profile = 'github' , output = 'min' ) :
'''Return information about a single issue in a named repository .
. . versionadded : : 2016.11.0
issue _ number
The number of the issue to retrieve .
repo _ name
The name of the repository from which to get the issu... | org_name = _get_config_value ( profile , 'org_name' )
if repo_name is None :
repo_name = _get_config_value ( profile , 'repo_name' )
action = '/' . join ( [ 'repos' , org_name , repo_name ] )
command = 'issues/' + six . text_type ( issue_number )
ret = { }
issue_data = _query ( profile , action = action , command =... |
def to_headers ( self , span_context ) :
"""Convert a SpanContext object to W3C Distributed Tracing headers ,
using version 0.
: type span _ context :
: class : ` ~ opencensus . trace . span _ context . SpanContext `
: param span _ context : SpanContext object .
: rtype : dict
: returns : W3C Distribute... | trace_id = span_context . trace_id
span_id = span_context . span_id
trace_options = span_context . trace_options . enabled
# Convert the trace options
trace_options = '01' if trace_options else '00'
headers = { _TRACEPARENT_HEADER_NAME : '00-{}-{}-{}' . format ( trace_id , span_id , trace_options ) , }
tracestate = spa... |
def cytherize ( args , file ) :
"""Used by core to integrate all the pieces of information , and to interface
with the user . Compiles and cleans up .""" | if isOutDated ( file ) :
if isUpdated ( file ) :
response = initiateCompilation ( args , file )
else :
response = { 'returncode' : WAIT_FOR_FIX , 'output' : '' }
else :
if args [ 'timestamp' ] :
response = { 'returncode' : SKIPPED_COMPILATION , 'output' : '' }
else :
resp... |
def _index_counter_keys ( self , counter , unknown_token , reserved_tokens , most_freq_count , min_freq ) :
"""Indexes keys of ` counter ` .
Indexes keys of ` counter ` according to frequency thresholds such as ` most _ freq _ count ` and
` min _ freq ` .""" | assert isinstance ( counter , collections . Counter ) , '`counter` must be an instance of collections.Counter.'
unknown_and_reserved_tokens = set ( reserved_tokens ) if reserved_tokens is not None else set ( )
unknown_and_reserved_tokens . add ( unknown_token )
token_freqs = sorted ( counter . items ( ) , key = lambda ... |
def insert ( self , ns , docid , raw , ** kw ) :
"""Perform a single insert operation .
{ ' docid ' : ObjectId ( ' 4e95ae77a20e6164850761cd ' ) ,
' ns ' : u ' mydb . tweets ' ,
' raw ' : { u ' h ' : - 1469300750073380169L ,
u ' ns ' : u ' mydb . tweets ' ,
u ' o ' : { u ' _ id ' : ObjectId ( ' 4e95ae77a20... | try :
self . _dest_coll ( ns ) . insert ( raw [ 'o' ] , safe = True )
except DuplicateKeyError , e :
logging . warning ( e ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.