signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_inc ( self ) :
"""Get include directories of Visual C + + .""" | dirs = [ ]
for part in [ '' , 'atlmfc' ] :
include = os . path . join ( self . vc_dir , part , 'include' )
if os . path . isdir ( include ) :
logging . info ( _ ( 'using include: %s' ) , include )
dirs . append ( include )
else :
logging . debug ( _ ( 'include not found: %s' ) , incl... |
def current_memory_usage ( ) :
"""Returns this programs current memory usage in bytes""" | import psutil
proc = psutil . Process ( os . getpid ( ) )
# meminfo = proc . get _ memory _ info ( )
meminfo = proc . memory_info ( )
rss = meminfo [ 0 ]
# Resident Set Size / Mem Usage
vms = meminfo [ 1 ]
# Virtual Memory Size / VM Size # NOQA
return rss |
def median_slitlets_rectified ( input_image , mode = 0 , minimum_slitlet_width_mm = EMIR_MINIMUM_SLITLET_WIDTH_MM , maximum_slitlet_width_mm = EMIR_MAXIMUM_SLITLET_WIDTH_MM , debugplot = 0 ) :
"""Compute median spectrum for each slitlet .
Parameters
input _ image : HDUList object
Input 2D image .
mode : int... | image_header = input_image [ 0 ] . header
image2d = input_image [ 0 ] . data
# check image dimensions
naxis2_expected = EMIR_NBARS * EMIR_NPIXPERSLIT_RECTIFIED
naxis2 , naxis1 = image2d . shape
if naxis2 != naxis2_expected :
raise ValueError ( "NAXIS2={0} should be {1}" . format ( naxis2 , naxis2_expected ) )
# che... |
def on_delivery ( self , name , channel , method , properties , body ) :
"""Process a message from Rabbit
: param str name : The connection name
: param pika . channel . Channel channel : The message ' s delivery channel
: param pika . frames . MethodFrame method : The method frame
: param pika . spec . Bas... | message = data . Message ( name , channel , method , properties , body )
if self . is_processing :
return self . pending . append ( message )
self . invoke_consumer ( message ) |
def read_existing_paths ( bt_table ) :
"""Return the SGF filename for each existing eval record .""" | rows = bt_table . read_rows ( filter_ = row_filters . ColumnRangeFilter ( METADATA , SGF_FILENAME , SGF_FILENAME ) )
names = ( row . cell_value ( METADATA , SGF_FILENAME ) . decode ( ) for row in rows )
processed = [ os . path . splitext ( os . path . basename ( r ) ) [ 0 ] for r in names ]
return processed |
def _create_execution_context ( self ) :
"""instantiates the internal query execution context based .""" | if hasattr ( self , '_database_link' ) : # client side partitioning query
return base_execution_context . _MultiCollectionQueryExecutionContext ( self . _client , self . _options , self . _database_link , self . _query , self . _partition_key )
else :
return execution_dispatcher . _ProxyQueryExecutionContext ( ... |
def create_ve ( self , ** kwargs ) :
"""Add Ve Interface .
Args :
ve _ name : Ve name with which the Ve interface needs to be
created .
enable ( bool ) : If vrf fowarding should be enabled
or disabled . Default : ` ` True ` ` .
get ( bool ) : Get config instead of editing config . ( True , False )
rbr... | ve_name = kwargs . pop ( 've_name' , '' )
rbridge_id = kwargs . pop ( 'rbridge_id' , '1' )
enable = kwargs . pop ( 'enable' , True )
get = kwargs . pop ( 'get' , False )
callback = kwargs . pop ( 'callback' , self . _callback )
ve_args = dict ( name = ve_name , rbridge_id = rbridge_id )
if get :
enable = None
metho... |
def upload_service_version ( self , service_zip_file , mode = 'production' , service_version = 'default' , service_id = None , ** kwargs ) :
'''upload _ service _ version ( self , service _ zip _ file , mode = ' production ' , service _ version = ' default ' , service _ id = None , * * kwargs )
Upload a service v... | files = { 'service_file' : open ( service_zip_file , 'rb' ) }
url_suffix = '/services/upload/%s' % mode
if mode == 'production' :
url_suffix += '/' + service_version
if service_id :
url_suffix += '/' + service_id
if kwargs :
url_suffix = url_suffix + '?' + urlencode ( kwargs )
return self . _call_rest_api (... |
def _get_default_jp2_boxes ( self ) :
"""Create a default set of JP2 boxes .""" | # Try to create a reasonable default .
boxes = [ JPEG2000SignatureBox ( ) , FileTypeBox ( ) , JP2HeaderBox ( ) , ContiguousCodestreamBox ( ) ]
height = self . codestream . segment [ 1 ] . ysiz
width = self . codestream . segment [ 1 ] . xsiz
num_components = len ( self . codestream . segment [ 1 ] . xrsiz )
if num_comp... |
def remove_dependency ( self , p_from_todo , p_to_todo , p_leave_tags = False ) :
"""Removes a dependency between two todos .""" | dep_id = p_from_todo . tag_value ( 'id' )
if dep_id :
self . _depgraph . remove_edge ( hash ( p_from_todo ) , hash ( p_to_todo ) )
self . dirty = True
# clean dangling dependency tags
if dep_id and not p_leave_tags :
p_to_todo . remove_tag ( 'p' , dep_id )
if not self . children ( p_from_todo , True ) :... |
def pre_attention ( self , segment , query_antecedent , memory_antecedent , bias ) :
"""Called prior to self - attention , to incorporate memory items .
Args :
segment : an integer Tensor with shape [ batch ]
query _ antecedent : a Tensor with shape [ batch , length _ q , channels ]
memory _ antecedent : mu... | assert memory_antecedent is None , "We only support language modeling"
# In eval mode , batch size may be variable
memory_batch_size = tf . shape ( self . previous_vals ) [ 0 ]
current_batch_size = tf . shape ( query_antecedent ) [ 0 ]
amount_to_pad = memory_batch_size - current_batch_size
# If segment id is zero , don... |
def create_entry ( self , group , ** kwargs ) :
"""Create a new Entry object .
The group which should hold the entry is needed .
image must be an unsigned int > 0 , group a Group .
: param group : The associated group .
: keyword title :
: keyword icon :
: keyword url :
: keyword username :
: keywor... | if group not in self . groups :
raise ValueError ( "Group doesn't exist / is not bound to this database." )
uuid = binascii . hexlify ( get_random_bytes ( 16 ) )
entry = Entry ( uuid = uuid , group_id = group . id , created = util . now ( ) , modified = util . now ( ) , accessed = util . now ( ) , ** kwargs )
self ... |
def output_package ( dist ) :
"""Return string displaying package information .""" | if dist_is_editable ( dist ) :
return '%s (%s, %s)' % ( dist . project_name , dist . version , dist . location , )
return '%s (%s)' % ( dist . project_name , dist . version ) |
def addresses ( self ) :
"""Return a new raw REST interface to address resources
: rtype : : py : class : ` ns1 . rest . ipam . Adresses `""" | import ns1 . rest . ipam
return ns1 . rest . ipam . Addresses ( self . config ) |
def __ensure_suffix_stem ( t , suffix ) :
"""Ensure that the target t has the given suffix , and return the file ' s stem .""" | tpath = str ( t )
if not tpath . endswith ( suffix ) :
stem = tpath
tpath += suffix
return tpath , stem
else :
stem , ext = os . path . splitext ( tpath )
return t , stem |
def run_job ( job_ini , log_level = 'info' , log_file = None , exports = '' , username = getpass . getuser ( ) , ** kw ) :
"""Run a job using the specified config file and other options .
: param str job _ ini :
Path to calculation config ( INI - style ) files .
: param str log _ level :
' debug ' , ' info ... | job_id = logs . init ( 'job' , getattr ( logging , log_level . upper ( ) ) )
with logs . handle ( job_id , log_level , log_file ) :
job_ini = os . path . abspath ( job_ini )
oqparam = eng . job_from_file ( job_ini , job_id , username , ** kw )
kw [ 'username' ] = username
eng . run_calc ( job_id , oqpar... |
def plot ( self , varnames = None , ranefs = True , transformed = False , combined = False , hist = False , bins = 20 , kind = 'trace' ) :
'''Plots posterior distributions and sample traces .
Basically a wrapperfor pm . traceplot ( ) plus some niceties , based partly on code
from : https : / / pymc - devs . git... | def _plot_row ( data , row , title , hist = True ) : # density plot
axes [ row , 0 ] . set_title ( title )
if pma is not None :
arr = np . atleast_2d ( data . values . T ) . T
pma . kdeplot_op ( axes [ row , 0 ] , arr , bw = 4.5 )
else :
data . plot ( kind = 'kde' , ax = axes [ row ,... |
def get_variables ( self , missing_in_geno = None ) :
"""Extract the complete set of data based on missingness over all
for the current locus .
: param missing _ in _ geno : mask associated with missingness in genotype
: return : ( phenotypes , covariates , nonmissing used for this set of vars )""" | count = 0
mismatch = 0
if missing_in_geno is None :
nonmissing = numpy . invert ( self . missing [ self . idx ] )
else :
nonmissing = numpy . invert ( self . missing [ self . idx ] | missing_in_geno )
nmcount = sum ( nonmissing )
covars = numpy . zeros ( ( self . covar_count , nmcount ) )
for idx in range ( 0 ,... |
def _publish_grade ( self , score , only_if_higher = None ) :
"""Publish a grade to the runtime .""" | grade_dict = { 'value' : score . raw_earned , 'max_value' : score . raw_possible , 'only_if_higher' : only_if_higher , }
self . runtime . publish ( self , 'grade' , grade_dict ) |
def bind ( self , * args , ** kw ) :
"""Bind environment variables into this object ' s scope .""" | new_self = self . copy ( )
new_scopes = Object . translate_to_scopes ( * args , ** kw )
new_self . _scopes = tuple ( reversed ( new_scopes ) ) + new_self . _scopes
return new_self |
def lv_line_load ( network ) :
"""Checks for over - loading issues in LV grids .
Parameters
network : : class : ` ~ . grid . network . Network `
Returns
: pandas : ` pandas . DataFrame < dataframe > `
Dataframe containing over - loaded LV lines , their maximum relative
over - loading and the correspondi... | crit_lines = pd . DataFrame ( )
for lv_grid in network . mv_grid . lv_grids :
crit_lines = _line_load ( network , lv_grid , crit_lines )
if not crit_lines . empty :
logger . debug ( '==> {} line(s) in LV grids has/have load issues.' . format ( crit_lines . shape [ 0 ] ) )
else :
logger . debug ( '==> No lin... |
def set_env ( envName , envValue ) :
"""设置环境变量
: params envName : env名字
: params envValue : 值""" | os . environ [ envName ] = os . environ [ envName ] + ':' + envValue |
def get_my_credits ( self , access_token = None , user_id = None ) :
"""Get the credits by user to use in the QX Platform""" | if access_token :
self . req . credential . set_token ( access_token )
if user_id :
self . req . credential . set_user_id ( user_id )
if not self . check_credentials ( ) :
raise CredentialsError ( 'credentials invalid' )
else :
user_data_url = '/users/' + self . req . credential . get_user_id ( )
us... |
def register_get ( self , regex , callback ) :
"""Register a regex for processing HTTP GET
requests . If the callback is None , any
existing registration is removed .""" | if callback is None : # pragma : no cover
if regex in self . get_registrations :
del self . get_registrations [ regex ]
else :
self . get_registrations [ regex ] = ( re . compile ( regex ) , callback ) |
def array_to_string ( array , col_delim = ' ' , row_delim = '\n' , digits = 8 , value_format = '{}' ) :
"""Convert a 1 or 2D array into a string with a specified number
of digits and delimiter . The reason this exists is that the
basic numpy array to string conversions are surprisingly bad .
Parameters
arra... | # convert inputs to correct types
array = np . asanyarray ( array )
digits = int ( digits )
row_delim = str ( row_delim )
col_delim = str ( col_delim )
value_format = str ( value_format )
# abort for non - flat arrays
if len ( array . shape ) > 2 :
raise ValueError ( 'conversion only works on 1D/2D arrays not %s!' ... |
def write_packed ( self , outfile , rows ) :
"""Write PNG file to ` outfile ` .
The pixel data comes from ` rows ` which should be in boxed row
packed format . Each row should be a sequence of packed bytes .
Technically , this method does work for interlaced images but it
is best avoided . For interlaced im... | return self . write_passes ( outfile , rows , packed = True ) |
def project_and_to2dim ( self , pps , plane_center ) :
"""Projects the list of points pps to the plane and changes the basis from 3D to the 2D basis of the plane
: param pps : List of points to be projected
: return : : raise :""" | proj = self . projectionpoints ( pps )
[ u1 , u2 , u3 ] = self . orthonormal_vectors ( )
PP = np . array ( [ [ u1 [ 0 ] , u2 [ 0 ] , u3 [ 0 ] ] , [ u1 [ 1 ] , u2 [ 1 ] , u3 [ 1 ] ] , [ u1 [ 2 ] , u2 [ 2 ] , u3 [ 2 ] ] ] )
xypps = list ( )
for pp in proj :
xyzpp = np . dot ( pp , PP )
xypps . append ( xyzpp [ 0 ... |
def decimate ( self , target_reduction , volume_preservation = False , attribute_error = False , scalars = True , vectors = True , normals = False , tcoords = True , tensors = True , scalars_weight = 0.1 , vectors_weight = 0.1 , normals_weight = 0.1 , tcoords_weight = 0.1 , tensors_weight = 0.1 , inplace = False ) :
... | # create decimation filter
decimate = vtk . vtkQuadricDecimation ( )
# vtkDecimatePro as well
decimate . SetVolumePreservation ( volume_preservation )
decimate . SetAttributeErrorMetric ( attribute_error )
decimate . SetScalarsAttribute ( scalars )
decimate . SetVectorsAttribute ( vectors )
decimate . SetNormalsAttribu... |
def determine_hbonds_for_drawing ( self , analysis_cutoff ) :
"""Since plotting all hydrogen bonds could lead to a messy plot , a cutoff has to be imple -
mented . In this function the frequency of each hydrogen bond is summated and the total
compared against analysis cutoff - a fraction multiplied by trajector... | self . frequency = defaultdict ( int )
for traj in self . hbonds_by_type :
for bond in self . hbonds_by_type [ traj ] : # frequency [ ( residue _ atom _ idx , ligand _ atom _ name , residue _ atom _ name ) ] = frequency
# residue atom name will be used to determine if hydrogen bond is interacting with a sidecha... |
def add_text ( self , text ) :
"""Add a text node to this element .
Adding text with this method is subtly different from assigning a new
text value with : meth : ` text ` accessor , because it " appends " to rather
than replacing this element ' s set of text nodes .
: param text : text content to add to th... | if not isinstance ( text , basestring ) :
text = unicode ( text )
self . _add_text ( self . impl_node , text ) |
def get_custom_annotations_for_alias ( data_type ) :
"""Given a Stone data type , returns all custom annotations applied to it .""" | # annotations can only be applied to Aliases , but they can be wrapped in
# Nullable . also , Aliases pointing to other Aliases don ' t automatically
# inherit their custom annotations , so we might have to traverse .
result = [ ]
data_type , _ = unwrap_nullable ( data_type )
while is_alias ( data_type ) :
result .... |
def normalize_tag ( tag ) :
"""Normalize an XML element tree ` tag ` into the tuple format . The following
input formats are accepted :
* ElementTree namespaced string , e . g . ` ` { uri : bar } foo ` `
* Unnamespaced tags , e . g . ` ` foo ` `
* Two - tuples consisting of ` namespace _ uri ` and ` localpa... | if isinstance ( tag , str ) :
namespace_uri , sep , localname = tag . partition ( "}" )
if sep :
if not namespace_uri . startswith ( "{" ) :
raise ValueError ( "not a valid etree-format tag" )
namespace_uri = namespace_uri [ 1 : ]
else :
localname = namespace_uri
... |
def bulk ( iterable , index = INDEX_NAME , doc_type = DOC_TYPE , action = 'index' ) :
"""Wrapper of elasticsearch ' s bulk method
Converts an interable of models to document operations and submits them to
Elasticsearch . Returns a count of operations when done .
https : / / elasticsearch - py . readthedocs . ... | actions = compact ( dict_to_op ( to_dict ( model ) , index_name = INDEX_NAME , doc_type = DOC_TYPE , op_type = action , ) for model in iterable )
# fail fast if there are no actions
if not actions :
return 0
items , _ = es_bulk ( es_conn , actions , doc_type = doc_type , index = index )
return items |
def chain ( * args ) :
"""itertools . chain , just better""" | has_iter = partial ( hasattr , name = '__iter__' )
# check if a single iterable is being passed for
# the case that it ' s a generator of generators
if len ( args ) == 1 and hasattr ( args [ 0 ] , '__iter__' ) :
args = args [ 0 ]
for arg in args : # if the arg is iterable
if hasattr ( arg , '__iter__' ) : # ite... |
def get_lookup ( self , operator ) :
"""Look up a lookup .
: param operator : Name of the lookup operator""" | try :
return self . _lookups [ operator ]
except KeyError :
raise NotImplementedError ( "Lookup operator '{}' is not supported" . format ( operator ) ) |
def _expand_group_by_fields ( cls , model , fields ) :
"""Expand FK fields into all related object ' s fields to avoid future
lookups .
: param fields : fields to " group by "
: return : expanded fields""" | # Containers for resulting fields and related model fields
res = [ ]
related = { }
# Add own fields and populate related fields
for field_name in fields :
if '__' in field_name : # Related model field : append to related model ' s fields
fk_field_name , related_field = field_name . split ( '__' , 1 )
... |
def send ( self , text ) :
"""Send a string to the PiLite , can be simple text or a $ $ $ command""" | # print text
self . s . write ( text )
time . sleep ( 0.001 * len ( text ) ) |
def onehot_encode ( dataset , char_indices , maxlen ) :
"""One hot encode the tokens
Args :
dataset list of lists of tokens
char _ indices dictionary of { key = character , value = index to use encoding vector }
maxlen int Length of each sample
Return :
np array of shape ( samples , tokens , encoding le... | X = np . zeros ( ( len ( dataset ) , maxlen , len ( char_indices . keys ( ) ) ) )
for i , sentence in enumerate ( dataset ) :
for t , char in enumerate ( sentence ) :
X [ i , t , char_indices [ char ] ] = 1
return X |
def sort_public_keys ( pub_keys : List [ bytes ] or List [ str ] ) :
""": param pub _ keys : a list of public keys in format of bytes .
: return : sorted public keys .""" | for index , key in enumerate ( pub_keys ) :
if isinstance ( key , str ) :
pub_keys [ index ] = bytes . fromhex ( key )
return sorted ( pub_keys , key = ProgramBuilder . compare_pubkey ) |
def list_semod ( ) :
'''Return a structure listing all of the selinux modules on the system and
what state they are in
CLI Example :
. . code - block : : bash
salt ' * ' selinux . list _ semod
. . versionadded : : 2016.3.0''' | helptext = __salt__ [ 'cmd.run' ] ( 'semodule -h' ) . splitlines ( )
semodule_version = ''
for line in helptext :
if line . strip ( ) . startswith ( 'full' ) :
semodule_version = 'new'
if semodule_version == 'new' :
mdata = __salt__ [ 'cmd.run' ] ( 'semodule -lfull' ) . splitlines ( )
ret = { }
... |
def record_padding ( self , iso_size ) : # type : ( int ) - > bytes
'''A method to record padding for the ISO hybridization .
Parameters :
iso _ size - The size of the ISO , excluding the hybridization .
Returns :
A string of zeros the right size to pad the ISO .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'This IsoHybrid object is not yet initialized' )
return b'\x00' * self . _calc_cc ( iso_size ) [ 1 ] |
def get_title ( self ) :
"""Get title line from . rst file .
* * 中文文档 * *
从一个 ` ` _ filename ` ` 所指定的 . rst 文件中 , 找到顶级标题 .
也就是第一个 ` ` = = = = ` ` 或 ` ` - - - - ` ` 或 ` ` ~ ~ ~ ~ ` ` 上面一行 .""" | header_bar_char_list = "=-~+*#^"
cursor_previous_line = None
for cursor_line in textfile . readlines ( self . rst_path , strip = "both" ) :
for header_bar_char in header_bar_char_list :
if cursor_line . startswith ( header_bar_char ) :
flag_full_bar_char = cursor_line == header_bar_char * len ( ... |
def _generate_results ( self , output_dir , labels , results ) :
"""Creates multiple results files in ` output _ dir ` based on ` results ` .
For each label in ` labels ` , create three results file ,
containing those n - grams with that label that first occurred ,
only occurred , and last occurred in that la... | ngrams = { }
for idx , label in enumerate ( labels ) :
now_results = results [ results [ constants . LABEL_FIELDNAME ] == label ]
earlier_labels = labels [ : idx ]
earlier_ngrams = results [ results [ constants . LABEL_FIELDNAME ] . isin ( earlier_labels ) ] [ constants . NGRAM_FIELDNAME ] . values
late... |
def retry_mkstemp ( suffix = '' , prefix = 'tmp' , directory = None , max_retries = 3 ) :
"""Make mkstemp more robust against AFS glitches .""" | if directory is None :
directory = current_app . config [ 'CFG_TMPSHAREDDIR' ]
for retry_count in range ( 1 , max_retries + 1 ) :
try :
tmp_file_fd , tmp_file_name = tempfile . mkstemp ( suffix = suffix , prefix = prefix , dir = directory )
except OSError as e :
if e . errno == 19 and retry_... |
def encode_params ( self , data = None , ** kwargs ) :
"""Build the body for a application / json request .""" | if isinstance ( data , basestring ) :
raise ValueError ( "Data must not be a string." )
if data is None :
return b"" , self . content_type
fields = to_key_val_dict ( data or "" )
try :
body = json . dumps ( fields )
except :
body = json . dumps ( fields , encoding = 'latin-1' )
return str ( body ) . enc... |
def _parse ( self ) :
"""Checks if the CPE Name is valid .
: returns : None
: exception : ValueError - bad - formed CPE Name""" | # Check prefix and initial bracket of WFN
if self . _str [ 0 : 5 ] != CPE2_3_WFN . CPE_PREFIX :
errmsg = "Bad-formed CPE Name: WFN prefix not found"
raise ValueError ( errmsg )
# Check final backet
if self . _str [ - 1 : ] != "]" :
errmsg = "Bad-formed CPE Name: final bracket of WFN not found"
raise Val... |
def get_lines ( self ) :
"""因为历史列表动态更新 , 需要刷新""" | self . lines = [ ]
width = self . screen_width - 24
if self . state == 0 : # 播放列表
for index , i in enumerate ( self . win . playlist ) :
line = i [ 'title' ] if len ( i [ 'title' ] ) < width else i [ 'title' ] [ : width ]
line = color_func ( self . c [ 'PLAYINGSONG' ] [ 'title' ] ) ( line )
... |
def to ( self , space ) :
"""Convert color to a different color space .
: param str space : Name of the color space .
: rtype : Color
: returns : A new spectra . Color in the given color space .""" | if space == self . space :
return self
new_color = convert_color ( self . color_object , COLOR_SPACES [ space ] )
return self . __class__ ( space , * new_color . get_value_tuple ( ) ) |
def debug_lvl_from_env ( ) :
"""Read and return ` DM _ SQUARE _ DEBUG ` env var , if defined .
Raises
RuntimeError
If DM _ SQUARE _ DEBUG is not an int convertable value""" | debug_lvl = os . environ . get ( 'DM_SQUARE_DEBUG' )
if not debug_lvl :
return 0
try :
debug_lvl = int ( debug_lvl )
except ValueError : # ensure that logging is configured as this method is likely to be
# called prior to configuring logging .
setup_logging ( verbosity = 1 )
raise RuntimeError ( textwra... |
def create_powerflow_problem ( timerange , components ) :
"""Create PyPSA network object and fill with data
Parameters
timerange : Pandas DatetimeIndex
Time range to be analyzed by PF
components : dict
Returns
network : PyPSA powerflow problem object""" | # initialize powerflow problem
network , snapshots = init_pypsa_network ( timerange )
# add components to network
for component in components . keys ( ) :
network . import_components_from_dataframe ( components [ component ] , component )
return network , snapshots |
def make_counts ( n_samples = 1000 , n_features = 100 , n_informative = 2 , scale = 1.0 , chunks = 100 , random_state = None , ) :
"""Generate a dummy dataset for modeling count data .
Parameters
n _ samples : int
number of rows in the output array
n _ features : int
number of columns ( features ) in the ... | rng = dask_ml . utils . check_random_state ( random_state )
X = rng . normal ( 0 , 1 , size = ( n_samples , n_features ) , chunks = ( chunks , n_features ) )
informative_idx = rng . choice ( n_features , n_informative , chunks = n_informative )
beta = ( rng . random ( n_features , chunks = n_features ) - 1 ) * scale
in... |
def _event_duration ( vevent ) :
"""unify dtend and duration to the duration of the given vevent""" | if hasattr ( vevent , 'dtend' ) :
return vevent . dtend . value - vevent . dtstart . value
elif hasattr ( vevent , 'duration' ) and vevent . duration . value :
return vevent . duration . value
return timedelta ( 0 ) |
def poke ( library , session , address , width , data ) :
"""Writes an 8 , 16 or 32 - bit value from the specified address .
Corresponds to viPoke * functions of the VISA library .
: param library : the visa library wrapped by ctypes .
: param session : Unique logical identifier to a session .
: param addre... | if width == 8 :
return poke_8 ( library , session , address , data )
elif width == 16 :
return poke_16 ( library , session , address , data )
elif width == 32 :
return poke_32 ( library , session , address , data )
raise ValueError ( '%s is not a valid size. Valid values are 8, 16 or 32' % width ) |
def sortino_ratio ( returns , required_return = 0 , period = DAILY , annualization = None , out = None , _downside_risk = None ) :
"""Determines the Sortino ratio of a strategy .
Parameters
returns : pd . Series or np . ndarray or pd . DataFrame
Daily returns of the strategy , noncumulative .
- See full exp... | allocated_output = out is None
if allocated_output :
out = np . empty ( returns . shape [ 1 : ] )
return_1d = returns . ndim == 1
if len ( returns ) < 2 :
out [ ( ) ] = np . nan
if return_1d :
out = out . item ( )
return out
adj_returns = np . asanyarray ( _adjust_returns ( returns , required_re... |
def help ( * args ) :
"""Prints help .""" | from . import commands
parser = argparse . ArgumentParser ( prog = "%s %s" % ( __package__ , help . __name__ ) , description = help . __doc__ )
parser . add_argument ( 'COMMAND' , help = "command to show help for" , nargs = "?" , choices = __all__ )
args = parser . parse_args ( args )
if args . COMMAND :
for l in g... |
def res_layer ( self , output_channels , filter_size = 3 , stride = 1 , activation_fn = tf . nn . relu , bottle = False , trainable = True ) :
"""Residual Layer : Input - > BN , Act _ fn , Conv1 , BN , Act _ fn , Conv 2 - > Output . Return : Input + Output
If stride > 1 or number of filters changes , decrease dim... | self . count [ 'rn' ] += 1
scope = 'resnet_' + str ( self . count [ 'rn' ] )
input_channels = self . input . get_shape ( ) [ 3 ]
with tf . variable_scope ( scope ) : # Determine Additive Output if dimensions change
# Decrease Input dimension with 1 x 1 Conv Layer with stride > 1
if ( stride != 1 ) or ( input_channe... |
def match ( self , sampling_req ) :
"""Determines whether or not this sampling rule applies to the incoming
request based on some of the request ' s parameters .
Any ` ` None ` ` parameter provided will be considered an implicit match .""" | if sampling_req is None :
return False
host = sampling_req . get ( 'host' , None )
method = sampling_req . get ( 'method' , None )
path = sampling_req . get ( 'path' , None )
service = sampling_req . get ( 'service' , None )
service_type = sampling_req . get ( 'service_type' , None )
return ( not host or wildcard_m... |
async def on_isupport_maxchannels ( self , value ) :
"""Old version of CHANLIMIT .""" | if 'CHANTYPES' in self . _isupport and 'CHANLIMIT' not in self . _isupport :
self . _channel_limits = { }
prefixes = self . _isupport [ 'CHANTYPES' ]
# Assume the limit is for all types of channels . Make a single group for all types .
self . _channel_limits [ frozenset ( prefixes ) ] = int ( value )
... |
def get_historical_klines ( symbol , interval , start_str , end_str = None ) :
"""Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http : / / dateparser . readthedocs . io / en / latest /
If using offset strings for dates add " UTC " to date string e . g . " now UTC "... | # create the Binance client , no need for api key
client = Client ( "" , "" )
# init our list
output_data = [ ]
# setup the max limit
limit = 500
# convert interval to useful value in seconds
timeframe = interval_to_milliseconds ( interval )
# convert our date strings to milliseconds
start_ts = date_to_milliseconds ( s... |
def onStart ( self ) :
"""Override onStart method for npyscreen""" | curses . mousemask ( 0 )
self . paths . host_config ( )
version = Version ( )
# setup initial runtime stuff
if self . first_time [ 0 ] and self . first_time [ 1 ] != 'exists' :
system = System ( )
thr = Thread ( target = system . start , args = ( ) , kwargs = { } )
thr . start ( )
countdown = 60
whi... |
def write_to_file ( chats , chatfile ) :
"""called every time chats are modified""" | with open ( chatfile , 'w' ) as handler :
handler . write ( '\n' . join ( ( str ( id_ ) for id_ in chats ) ) ) |
def cpus ( self , cpus ) :
"""Sets the number of vCPUs this QEMU VM .
: param cpus : number of vCPUs .""" | log . info ( 'QEMU VM "{name}" [{id}] has set the number of vCPUs to {cpus}' . format ( name = self . _name , id = self . _id , cpus = cpus ) )
self . _cpus = cpus |
def trunk_mode ( self , ** kwargs ) :
"""Set trunk mode ( trunk , trunk - no - default - vlan ) .
Args :
int _ type ( str ) : Type of interface . ( gigabitethernet ,
tengigabitethernet , etc )
name ( str ) : Name of interface . ( 1/0/5 , 1/0/10 , etc )
mode ( str ) : Trunk port mode ( trunk , trunk - no -... | int_type = kwargs . pop ( 'int_type' ) . lower ( )
name = kwargs . pop ( 'name' )
mode = kwargs . pop ( 'mode' ) . lower ( )
get = kwargs . pop ( 'get' , False )
callback = kwargs . pop ( 'callback' , self . _callback )
int_types = [ 'gigabitethernet' , 'tengigabitethernet' , 'fortygigabitethernet' , 'hundredgigabiteth... |
def derivative ( self , point ) :
"""Return the derivative in ` ` point ` ` .
The derivative of the gradient is often called the Hessian .
Parameters
point : ` domain ` ` element - like `
The point that the derivative should be taken in .
Returns
derivative : ` NumericalDerivative `
Numerical estimate... | return NumericalDerivative ( self , point , method = self . method , step = np . sqrt ( self . step ) ) |
def ResolveMulti ( self , subject , attributes , timestamp = None , limit = None ) :
"""Resolves multiple attributes at once for one subject .""" | for attribute in attributes :
query , args = self . _BuildQuery ( subject , attribute , timestamp , limit )
result , _ = self . ExecuteQuery ( query , args )
for row in result :
value = self . _Decode ( attribute , row [ "value" ] )
yield ( attribute , value , row [ "timestamp" ] )
if li... |
def qteMacroData ( self , widgetObj : QtGui . QWidget = None ) :
"""Retrieve ` ` widgetObj ` ` specific data previously saved with
` ` qteSaveMacroData ` ` .
If no data has been stored previously then * * None * * is
returned .
If ` ` widgetObj ` ` is * * None * * then the calling widget
` ` self . qteWid... | # Check type of input arguments .
if not hasattr ( widgetObj , '_qteAdmin' ) and ( widgetObj is not None ) :
msg = '<widgetObj> was probably not added with <qteAddWidget>'
msg += ' method because it lacks the <_qteAdmin> attribute.'
raise QtmacsOtherError ( msg )
# If no widget was specified then use the ca... |
def update_table ( self , table , pks = [ 'id' ] ) :
"""Update records in a database table from the main dataframe""" | if self . _check_db ( ) is False :
return
try :
table = self . db [ table ]
except Exception as e :
self . err ( e , "Can not find table " + table )
if self . db is None :
msg = "Please connect a database before or provide a database url"
self . err ( msg )
return
recs = self . to_records_ ( )
f... |
def _parse_head ( heads , head_grads ) :
"""parse head gradient for backward and grad .""" | if isinstance ( heads , NDArray ) :
heads = [ heads ]
if isinstance ( head_grads , NDArray ) :
head_grads = [ head_grads ]
head_handles = c_handle_array ( heads )
if head_grads is None :
hgrad_handles = ctypes . c_void_p ( 0 )
else :
assert len ( heads ) == len ( head_grads ) , "heads and head_grads mus... |
def _recv_nack ( self , method_frame ) :
'''Receive a nack from the broker .''' | if self . _nack_listener :
delivery_tag = method_frame . args . read_longlong ( )
multiple , requeue = method_frame . args . read_bits ( 2 )
if multiple :
while self . _last_ack_id < delivery_tag :
self . _last_ack_id += 1
self . _nack_listener ( self . _last_ack_id , requeue... |
def ParseOptions ( cls , options , configuration_object ) :
"""Parses and validates options .
Args :
options ( argparse . Namespace ) : parser options .
configuration _ object ( CLITool ) : object to be configured by the argument
helper .
Raises :
BadConfigObject : when the configuration object is of th... | if not isinstance ( configuration_object , tools . CLITool ) :
raise errors . BadConfigObject ( 'Configuration object is not an instance of CLITool' )
data_location = cls . _ParseStringOption ( options , 'data_location' )
if not data_location : # Determine the source root path , which is 3 directories up from
# the... |
def cmd ( send , msg , args ) :
"""Gets a random FML post .
Syntax : { command }""" | req = get ( "http://api.fmylife.com/view/random" , params = { 'language' : 'en' , 'key' : args [ 'config' ] [ 'api' ] [ 'fmlkey' ] } )
doc = fromstring ( req . content )
send ( doc . xpath ( '//text' ) [ 0 ] . text ) |
def encrypt_file ( cls , key , in_filename , out_filename = None , chunksize = 64 * 1024 ) :
"""Encrypts a file using AES ( CBC mode ) with the
given key .
key :
The encryption key - a string that must be
either 16 , 24 or 32 bytes long . Longer keys
are more secure .
in _ filename :
Name of the input... | if not out_filename :
out_filename = in_filename + '.enc'
iv = '' . join ( chr ( random . randint ( 0 , 0xFF ) ) for _ in range ( 16 ) )
encryptor = AES . new ( key , AES . MODE_CBC , iv )
filesize = os . path . getsize ( in_filename )
with open ( in_filename , 'rb' ) as infile :
with open ( out_filename , 'wb'... |
def _pretty_time_delta ( td ) :
"""Creates a string representation of a time delta .
Parameters
td : : class : ` datetime . timedelta `
Returns
pretty _ formatted _ datetime : str""" | seconds = td . total_seconds ( )
sign_string = '-' if seconds < 0 else ''
seconds = abs ( int ( seconds ) )
days , seconds = divmod ( seconds , 86400 )
hours , seconds = divmod ( seconds , 3600 )
minutes , seconds = divmod ( seconds , 60 )
d = dict ( sign = sign_string , days = days , hours = hours , minutes = minutes ... |
def add_application ( self , application , sync = True ) :
"""add a application to this company .
: param application : the application to add on this company
: param sync : If sync = True ( default ) synchronize with Ariane server . If sync = False ,
add the application object on list to be added on next sav... | LOGGER . debug ( "Company.add_application" )
if not sync :
self . applications_2_add . append ( application )
else :
if application . id is None :
application . save ( )
if self . id is not None and application . id is not None :
params = { 'id' : self . id , 'applicationID' : application . ... |
def handle_data ( self , data ) :
'''Method called for each event by zipline . In intuition this is the
place to factorize algorithms and then call event ( )''' | self . days += 1
signals = { }
self . orderbook = { }
# Everytime but the first tick
if self . initialized and self . manager : # Keep the portfolio aware of the situation
self . manager . update ( self . portfolio , self . datetime , self . perf_tracker . cumulative_risk_metrics . to_dict ( ) )
else : # Perf _ tra... |
def fs_obj_move ( self , source , destination , flags ) :
"""Moves a file system object ( file , directory , symlink , etc ) from one
guest location to another .
This differs from : py : func : ` IGuestSession . fs _ obj _ rename ` in that it
can move accross file system boundraries . In that case it will
p... | if not isinstance ( source , basestring ) :
raise TypeError ( "source can only be an instance of type basestring" )
if not isinstance ( destination , basestring ) :
raise TypeError ( "destination can only be an instance of type basestring" )
if not isinstance ( flags , list ) :
raise TypeError ( "flags can ... |
def allowed_transitions ( constraint_type : str , labels : Dict [ int , str ] ) -> List [ Tuple [ int , int ] ] :
"""Given labels and a constraint type , returns the allowed transitions . It will
additionally include transitions for the start and end states , which are used
by the conditional random field .
P... | num_labels = len ( labels )
start_tag = num_labels
end_tag = num_labels + 1
labels_with_boundaries = list ( labels . items ( ) ) + [ ( start_tag , "START" ) , ( end_tag , "END" ) ]
allowed = [ ]
for from_label_index , from_label in labels_with_boundaries :
if from_label in ( "START" , "END" ) :
from_tag = f... |
def __get_match_result ( self , ret , ret2 ) :
"""Getting match result""" | if self . another_compare == "__MATCH_AND__" :
return ret and ret2
elif self . another_compare == "__MATCH_OR__" :
return ret or ret2
return ret |
def _filtering_result_checked ( self , by_or ) :
'''Check if post passes all / at _ least _ one ( by _ or parameter ) filter ( s ) .
Filters are evaluated on only - if - necessary ( " lazy " ) basis .''' | filters , results = it . imap ( set , ( self . feed . filters . all ( ) , self . filtering_results . values_list ( 'filter' , flat = True ) ) )
# Check if conclusion can already be made , based on cached results .
if results . issubset ( filters ) : # If at least one failed / passed test is already there , and / or out... |
def _break_reads ( self , contig , position , fout , min_read_length = 250 ) :
'''Get all reads from contig , but breaks them all at given position ( 0 - based ) in the reference . Writes to fout . Currently pproximate where it breaks ( ignores indels in the alignment )''' | sam_reader = pysam . Samfile ( self . bam , "rb" )
for read in sam_reader . fetch ( contig ) :
seqs = [ ]
if read . pos < position < read . reference_end - 1 :
split_point = position - read . pos
if split_point - 1 >= min_read_length :
sequence = mapping . aligned_read_to_read ( read... |
def get_fun_prop ( f , k ) :
"""Get the value of property ` k ` from function ` f ` .
We define properties as annotations added to a function throughout
the process of defining a function for verification , e . g . the
argument types . If ` f ` does not have a property named ` k ` , this
throws an error . I... | if not has_fun_prop ( f , k ) :
raise InternalError ( "Function %s has no property %s" % ( str ( f ) , k ) )
return getattr ( f , _FUN_PROPS ) [ k ] |
def safe_str ( value ) :
"""Returns :
* a ` str ` instance ( bytes ) in Python 2 . x , or
* a ` str ` instance ( Unicode ) in Python 3 . x .""" | if sys . version_info < ( 3 , 0 ) and isinstance ( value , unicode ) :
return value . encode ( 'utf-8' )
else :
return str ( value ) |
def run ( items , background = None ) :
"""Detect copy number variations from batched set of samples using GATK4 CNV calling .
TODO : implement germline calling with DetermineGermlineContigPloidy and GermlineCNVCaller""" | if not background :
background = [ ]
paired = vcfutils . get_paired ( items + background )
if paired :
out = _run_paired ( paired )
else :
out = items
logger . warn ( "GATK4 CNV calling currently only available for somatic samples: %s" % ", " . join ( [ dd . get_sample_name ( d ) for d in items + backgr... |
def _set_topMargin ( self , value ) :
"""value will be an int or float .
Subclasses may override this method .""" | bounds = self . bounds
if bounds is None :
self . height = value
else :
xMin , yMin , xMax , yMax = bounds
self . height = yMax + value |
def filter ( self , * filt , ** kwargs ) :
"""Filter this ` TimeSeries ` with an IIR or FIR filter
Parameters
* filt : filter arguments
1 , 2 , 3 , or 4 arguments defining the filter to be applied ,
- an ` ` Nx1 ` ` ` ~ numpy . ndarray ` of FIR coefficients
- an ` ` Nx6 ` ` ` ~ numpy . ndarray ` of SOS co... | # parse keyword arguments
filtfilt = kwargs . pop ( 'filtfilt' , False )
# parse filter
form , filt = filter_design . parse_filter ( filt , analog = kwargs . pop ( 'analog' , False ) , sample_rate = self . sample_rate . to ( 'Hz' ) . value , )
if form == 'zpk' :
try :
sos = signal . zpk2sos ( * filt )
e... |
def get_tree_type ( tree ) :
"""Return the ( sub ) tree type : ' root ' , ' nucleus ' , ' satellite ' , ' text ' or ' leaf '
Parameters
tree : nltk . tree . ParentedTree
a tree representing a rhetorical structure ( or a part of it )""" | if is_leaf_node ( tree ) :
return SubtreeType . leaf
tree_type = tree . label ( ) . lower ( ) . split ( ':' ) [ 0 ]
assert tree_type in SUBTREE_TYPES
return tree_type |
def _func_copy ( f , newcode ) :
'''Return a copy of function f with a different _ _ code _ _
Because I can ' t find proper documentation on the
correct signature of the types . FunctionType ( ) constructor ,
I pass the minimum arguments then set the important
dunder - values by direct assignment .
Note y... | newf = types . FunctionType ( newcode , f . __globals__ )
newf . __annotations__ = f . __annotations__
# newf . _ _ closure _ _ = f . _ _ closure _ _
newf . __defaults__ = f . __defaults__
newf . __doc__ = f . __doc__
newf . __name__ = f . __name__
newf . __kwdefaults__ = f . __kwdefaults__
newf . __qualname__ = f . __... |
def setSignals ( self , vehID , signals ) :
"""setSignals ( string , integer ) - > None
Sets an integer encoding the state of the vehicle ' s signals .""" | self . _connection . _sendIntCmd ( tc . CMD_SET_VEHICLE_VARIABLE , tc . VAR_SIGNALS , vehID , signals ) |
def uri_from_parts ( parts ) :
"simple function to merge three parts into an uri" | uri = "%s://%s%s" % ( parts [ 0 ] , parts [ 1 ] , parts [ 2 ] )
if parts [ 3 ] :
extra = '?' + urlencode ( parts [ 3 ] )
uri += extra
return uri |
def get_recent_posts ( blog_id , username , password , number ) :
"""metaWeblog . getRecentPosts ( blog _ id , username , password , number )
= > post structure [ ]""" | user = authenticate ( username , password )
site = Site . objects . get_current ( )
return [ post_structure ( entry , site ) for entry in Entry . objects . filter ( authors = user ) [ : number ] ] |
def _available ( name , ret ) :
'''Check if the service is available''' | avail = False
if 'service.available' in __salt__ :
avail = __salt__ [ 'service.available' ] ( name )
elif 'service.get_all' in __salt__ :
avail = name in __salt__ [ 'service.get_all' ] ( )
if not avail :
ret [ 'result' ] = False
ret [ 'comment' ] = 'The named service {0} is not available' . format ( nam... |
def arcball_map_to_sphere ( point , center , radius ) :
"""Return unit sphere coordinates from window coordinates .""" | v = numpy . array ( ( ( point [ 0 ] - center [ 0 ] ) / radius , ( center [ 1 ] - point [ 1 ] ) / radius , 0.0 ) , dtype = numpy . float64 )
n = v [ 0 ] * v [ 0 ] + v [ 1 ] * v [ 1 ]
if n > 1.0 :
v /= math . sqrt ( n )
# position outside of sphere
else :
v [ 2 ] = math . sqrt ( 1.0 - n )
return v |
def is_all_field_none ( self ) :
""": rtype : bool""" | if self . _id_ is not None :
return False
if self . _created is not None :
return False
if self . _updated is not None :
return False
if self . _action is not None :
return False
if self . _user_id is not None :
return False
if self . _monetary_account_id is not None :
return False
if self . _ob... |
def set_ground_width ( self , ground_width ) :
'''set ground width of view''' | state = self . state
state . ground_width = ground_width
state . panel . re_center ( state . width / 2 , state . height / 2 , state . lat , state . lon ) |
def all ( cls , domain = None ) :
"""Return all sites
@ param domain : The domain to filter by
@ type domain : Domain
@ rtype : list of Site""" | Site = cls
site = Session . query ( Site )
if domain :
site . filter ( Site . domain == domain )
return site . all ( ) |
def download_location ( self , location : str , max_count : Optional [ int ] = None , post_filter : Optional [ Callable [ [ Post ] , bool ] ] = None , fast_update : bool = False ) -> None :
"""Download pictures of one location .
To download the last 30 pictures with location 362629379 , do : :
loader = Instaloa... | self . context . log ( "Retrieving pictures for location {}..." . format ( location ) )
count = 1
for post in self . get_location_posts ( location ) :
if max_count is not None and count > max_count :
break
self . context . log ( '[{0:3d}] %{1} ' . format ( count , location ) , end = '' , flush = True )
... |
def pop ( self , key , default = UndefinedKey ) :
"""Remove specified key and return the corresponding value .
If key is not found , default is returned if given , otherwise ConfigMissingException is raised
This method assumes the user wants to remove the last value in the chain so it parses via parse _ key
a... | if default != UndefinedKey and key not in self :
return default
value = self . get ( key , UndefinedKey )
lst = ConfigTree . parse_key ( key )
parent = self . KEY_SEP . join ( lst [ 0 : - 1 ] )
child = lst [ - 1 ]
if parent :
self . get ( parent ) . __delitem__ ( child )
else :
self . __delitem__ ( child )
... |
def get_list ( self , name : str ) -> List [ str ] :
"""Returns all values for the given header as a list .""" | norm_name = _normalized_headers [ name ]
return self . _as_list . get ( norm_name , [ ] ) |
def assertHeader ( self , name , value = None , * args , ** kwargs ) :
"""Returns ` True ` if ` ` name ` ` was in the headers and , if ` ` value ` ` is
True , whether or not the values match , or ` False ` otherwise .""" | return name in self . raw_headers and ( True if value is None else self . raw_headers [ name ] == value ) |
def visit_Expr ( self , node : ast . Expr ) -> Any :
"""Visit the node ' s ` ` value ` ` .""" | result = self . visit ( node = node . value )
self . recomputed_values [ node ] = result
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.