signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def siret ( self , max_sequential_digits = 2 ) : """Generates a siret number ( 14 digits ) . It is in fact the result of the concatenation of a siren number ( 9 digits ) , a sequential number ( 4 digits ) and a control number ( 1 digit ) concatenation . If $ max _ sequential _ digits is invalid , it is set to...
if max_sequential_digits > 4 or max_sequential_digits <= 0 : max_sequential_digits = 2 sequential_number = str ( self . random_number ( max_sequential_digits ) ) . zfill ( 4 ) return self . numerify ( self . siren ( ) + ' ' + sequential_number + '#' )
def _check_all_metadata_found ( metadata , items ) : """Print warning if samples in CSV file are missing in folder"""
for name in metadata : seen = False for sample in items : check_file = sample [ "files" ] [ 0 ] if sample . get ( "files" ) else sample [ "vrn_file" ] if isinstance ( name , ( tuple , list ) ) : if check_file . find ( name [ 0 ] ) > - 1 : seen = True elif chec...
def logic_subset ( self , op = None ) : """Return set of logicnets , filtered by the type ( s ) of logic op provided as op . If no op is specified , the full set of logicnets associated with the Block are returned . This is helpful for getting all memories of a block for example ."""
if op is None : return self . logic else : return set ( x for x in self . logic if x . op in op )
def season_id ( x ) : """takes in 4 - digit years and returns API formatted seasonID Input Values : YYYY Used in :"""
if len ( str ( x ) ) == 4 : try : return "" . join ( [ "2" , str ( x ) ] ) except ValueError : raise ValueError ( "Enter the four digit year for the first half of the desired season" ) else : raise ValueError ( "Enter the four digit year for the first half of the desired season" )
def solar_irradiation ( latitude , longitude , Z , moment , surface_tilt , surface_azimuth , T = None , P = None , solar_constant = 1366.1 , atmos_refract = 0.5667 , albedo = 0.25 , linke_turbidity = None , extraradiation_method = 'spencer' , airmass_model = 'kastenyoung1989' , cache = None ) : r'''Calculates the a...
# Atmospheric refraction at sunrise / sunset ( 0.5667 deg is an often used value ) from fluids . optional import spa from fluids . optional . irradiance import ( get_relative_airmass , get_absolute_airmass , ineichen , get_relative_airmass , get_absolute_airmass , get_total_irradiance ) # try : # import pvlib # except ...
def printAllColorsToConsole ( cls ) : '''A simple enumeration of the colors to the console to help decide : )'''
for elem in cls . __dict__ : # ignore specials such as _ _ class _ _ or _ _ module _ _ if not elem . startswith ( "__" ) : color_fmt = cls . __dict__ [ elem ] if isinstance ( color_fmt , six . string_types ) and color_fmt != "BOLD" and color_fmt != "DIM" and color_fmt != "UNDER" and color_fmt != "IN...
def calc_mdl ( yx_dist , y_dist ) : """Function calculates mdl with given label distributions . yx _ dist : list of dictionaries - for every split it contains a dictionary with label distributions y _ dist : dictionary - all label distributions Reference : Igor Kononenko . On biases in estimating multi - va...
prior = multinomLog2 ( y_dist . values ( ) ) prior += multinomLog2 ( [ len ( y_dist . keys ( ) ) - 1 , sum ( y_dist . values ( ) ) ] ) post = 0 for x_val in yx_dist : post += multinomLog2 ( [ x_val . get ( c , 0 ) for c in y_dist . keys ( ) ] ) post += multinomLog2 ( [ len ( y_dist . keys ( ) ) - 1 , sum ( x_va...
def use_plenary_repository_view ( self ) : """Pass through to provider AssetRepositorySession . use _ plenary _ repository _ view"""
self . _repository_view = PLENARY # self . _ get _ provider _ session ( ' asset _ repository _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_plenary_repository_view ( ) except AttributeError : pass
def update_datetime ( value , range = None ) : """Updates ( drifts ) a Date value within specified range defined : param value : a Date value to drift . : param range : ( optional ) a range in milliseconds . Default : 10 days : return : an updated DateTime value ."""
range = range if range != None else 10 if range < 0 : return value days = RandomFloat . next_float ( - range , range ) return value + datetime . timedelta ( days )
def getInstance ( cls , * args ) : '''Returns a singleton instance of the class'''
if not cls . __singleton : cls . __singleton = DriverManager ( * args ) return cls . __singleton
def convert_widgets ( self ) : """During form initialization , some widgets have to be replaced by a counterpart suitable to be rendered the AngularJS way ."""
warnings . warn ( "Will be removed after dropping support for Django-1.10" , PendingDeprecationWarning ) widgets_module = getattr ( self , 'widgets_module' , 'djng.widgets' ) for field in self . base_fields . values ( ) : if hasattr ( field , 'get_converted_widget' ) : new_widget = field . get_converted_wid...
def negative_binomial ( k = 1 , p = 1 , shape = _Null , dtype = _Null , ctx = None , out = None , ** kwargs ) : """Draw random samples from a negative binomial distribution . Samples are distributed according to a negative binomial distribution parametrized by * k * ( limit of unsuccessful experiments ) and * p...
return _random_helper ( _internal . _random_negative_binomial , _internal . _sample_negative_binomial , [ k , p ] , shape , dtype , ctx , out , kwargs )
def get_ZXY_data ( Data , zf , xf , yf , FractionOfSampleFreq = 1 , zwidth = 10000 , xwidth = 5000 , ywidth = 5000 , filterImplementation = "filtfilt" , timeStart = None , timeEnd = None , NPerSegmentPSD = 1000000 , MakeFig = True , show_fig = True ) : """Given a Data object and the frequencies of the z , x and y p...
if timeStart == None : timeStart = Data . timeStart if timeEnd == None : timeEnd = Data . timeEnd time = Data . time . get_array ( ) StartIndex = _np . where ( time == take_closest ( time , timeStart ) ) [ 0 ] [ 0 ] EndIndex = _np . where ( time == take_closest ( time , timeEnd ) ) [ 0 ] [ 0 ] SAMPLEFREQ = Data...
def draw ( self , parent , box ) : '''redraw the text'''
import wx if self . textctrl is None : self . textctrl = wx . TextCtrl ( parent , style = wx . TE_MULTILINE | wx . TE_READONLY ) self . textctrl . WriteText ( self . text ) self . _resize ( ) box . Add ( self . textctrl , flag = wx . LEFT , border = 0 ) box . Layout ( )
def parse_requirements ( strs ) : """Yield ` ` Requirement ` ` objects for each specification in ` strs ` ` strs ` must be a string , or a ( possibly - nested ) iterable thereof ."""
# create a steppable iterator , so we can handle \ - continuations lines = iter ( yield_lines ( strs ) ) for line in lines : # Drop comments - - a hash without a space may be in a URL . if ' #' in line : line = line [ : line . find ( ' #' ) ] # If there is a line continuation , drop it , and append the ...
def draw ( self ) : """Return an ASCII representation of the network ."""
str_wires = [ [ "-" ] * 7 * self . depth ] str_wires [ 0 ] [ 0 ] = "0" str_wires [ 0 ] [ 1 ] = " o" str_spaces = [ ] for i in range ( 1 , self . dimension ) : str_wires . append ( [ "-" ] * 7 * self . depth ) str_spaces . append ( [ " " ] * 7 * self . depth ) str_wires [ i ] [ 0 ] = str ( i ) str_wires ...
def add_agent ( self , agent ) : """Add an INDRA Agent and its conditions to the Nugget ."""
agent_id = self . add_node ( agent . name ) self . add_typing ( agent_id , 'agent' ) # Handle bound conditions for bc in agent . bound_conditions : # Here we make the assumption that the binding site # is simply named after the binding partner if bc . is_bound : test_type = 'is_bnd' else : test_...
def generate_const ( self ) : """Means that value is valid when is equeal to const definition . . . code - block : : python ' const ' : 42, Only valid value is 42 in this example ."""
const = self . _definition [ 'const' ] if isinstance ( const , str ) : const = '"{}"' . format ( const ) with self . l ( 'if {variable} != {}:' , const ) : self . l ( 'raise JsonSchemaException("{name} must be same as const definition")' )
def xpathNextNamespace ( self , cur ) : """Traversal function for the " namespace " direction the namespace axis contains the namespace nodes of the context node ; the order of nodes on this axis is implementation - defined ; the axis will be empty unless the context node is an element We keep the XML names...
if cur is None : cur__o = None else : cur__o = cur . _o ret = libxml2mod . xmlXPathNextNamespace ( self . _o , cur__o ) if ret is None : raise xpathError ( 'xmlXPathNextNamespace() failed' ) __tmp = xmlNode ( _obj = ret ) return __tmp
def create_dset_to3d ( prefix , file_list , file_order = 'zt' , num_slices = None , num_reps = None , TR = None , slice_order = 'alt+z' , only_dicoms = True , sort_filenames = False ) : '''manually create dataset by specifying everything ( not recommended , but necessary when autocreation fails ) If ` num _ slice...
tags = { 'num_rows' : ( 0x0028 , 0x0010 ) , 'num_reps' : ( 0x0020 , 0x0105 ) , 'TR' : ( 0x0018 , 0x0080 ) } with nl . notify ( 'Trying to create dataset %s' % prefix ) : if os . path . exists ( prefix ) : nl . notify ( 'Error: file "%s" already exists!' % prefix , level = nl . level . error ) return...
def callback ( self , request , ** kwargs ) : """Called from the Service when the user accept to activate it : param request : request object : return : callback url : rtype : string , path to the template"""
access_token = Pocket . get_access_token ( consumer_key = self . consumer_key , code = request . session [ 'request_token' ] ) kwargs = { 'access_token' : access_token } return super ( ServicePocket , self ) . callback ( request , ** kwargs )
def create_upload_url ( success_path , max_bytes_per_blob = None , max_bytes_total = None , ** options ) : """Create upload URL for POST form . Args : success _ path : Path within application to call when POST is successful and upload is complete . max _ bytes _ per _ blob : The maximum size in bytes that a...
fut = create_upload_url_async ( success_path , max_bytes_per_blob = max_bytes_per_blob , max_bytes_total = max_bytes_total , ** options ) return fut . get_result ( )
def run_forever ( lcdproc = '' , mpd = '' , lcdproc_screen = DEFAULT_LCD_SCREEN_NAME , lcdproc_charset = DEFAULT_LCDPROC_CHARSET , lcdd_debug = False , pattern = '' , patterns = [ ] , refresh = DEFAULT_REFRESH , backlight_on = DEFAULT_BACKLIGHT_ON , priority_playing = DEFAULT_PRIORITY , priority_not_playing = DEFAULT_P...
# Compute host / ports lcd_conn = _make_hostport ( lcdproc , 'localhost' , 13666 ) mpd_conn = _make_hostport ( mpd , 'localhost' , 6600 ) # Prepare auto - retry retry_config = utils . AutoRetryConfig ( retry_attempts = retry_attempts , retry_backoff = retry_backoff , retry_wait = retry_wait ) # Setup MPD client mpd_cli...
def pass_allowedremoterelieve_v1 ( self ) : """Update the outlet link sequence | dam _ outlets . R | ."""
flu = self . sequences . fluxes . fastaccess sen = self . sequences . senders . fastaccess sen . r [ 0 ] += flu . allowedremoterelieve
def ListProfilers ( self ) : """Lists information about the available profilers ."""
table_view = views . ViewsFactory . GetTableView ( self . _views_format_type , column_names = [ 'Name' , 'Description' ] , title = 'Profilers' ) profilers_information = sorted ( profiling . ProfilingArgumentsHelper . PROFILERS_INFORMATION . items ( ) ) for name , description in profilers_information : table_view . ...
def pull_requests ( self ) : '''Looks for any of the following pull request formats in the description field : pr12345 , pr 2345 , PR2345 , PR 2345'''
pr_numbers = re . findall ( r"[pP][rR]\s?[0-9]+" , self . description ) pr_numbers += re . findall ( re . compile ( "pull\s?request\s?[0-9]+" , re . IGNORECASE ) , self . description ) # Remove Duplicates pr_numbers = [ re . sub ( '[^0-9]' , '' , p ) for p in pr_numbers ] return pr_numbers
def first_interval_starting ( self , start : datetime . datetime ) -> Optional [ Interval ] : """Returns our first interval that starts with the ` ` start ` ` parameter , or ` ` None ` ` ."""
for i in self . intervals : if i . start == start : return i return None
def dpar ( self , cl = 1 ) : """Return dpar - style executable assignment for parameter Default is to write CL version of code ; if cl parameter is false , writes Python executable code instead . Note that dpar doesn ' t even work for arrays in the CL , so we just use Python syntax here ."""
sval = list ( map ( self . toString , self . value , len ( self . value ) * [ 1 ] ) ) for i in range ( len ( sval ) ) : if sval [ i ] == "" : sval [ i ] = "None" s = "%s = [%s]" % ( self . name , ', ' . join ( sval ) ) return s
def is_starred ( self ) : """Check to see if this gist is starred by the authenticated user . : returns : bool - - True if it is starred , False otherwise"""
url = self . _build_url ( 'star' , base_url = self . _api ) return self . _boolean ( self . _get ( url ) , 204 , 404 )
def follower_num ( self ) : """获取问题关注人数 . : return : 问题关注人数 : rtype : int"""
follower_num_block = self . soup . find ( 'div' , class_ = 'zg-gray-normal' ) # 无人关注时 找不到对应block , 直接返回0 ( 感谢知乎用户 段晓晨 提出此问题 ) if follower_num_block is None or follower_num_block . strong is None : return 0 return int ( follower_num_block . strong . text )
def login_open_sheet ( oauth_key_file , spreadsheet ) : """Connect to Google Docs spreadsheet and return the first worksheet ."""
try : scope = [ 'https://spreadsheets.google.com/feeds' ] credentials = ServiceAccountCredentials . from_json_keyfile_name ( oauth_key_file , scope ) gc = gspread . authorize ( credentials ) worksheet = gc . open ( spreadsheet ) . sheet1 return worksheet except Exception as ex : print ( 'Unable ...
def history ( self , dates = None , linreg_since = None , lin_reg_days = 20 ) : '''Works only on a Result that has _ start and _ end columns . : param dates : list of dates to query : param linreg _ since : estimate future values using linear regression . : param lin _ reg _ days : number of past days to use ...
dates = dates or self . get_dates_range ( ) vals = [ self . on_date ( dt , only_count = True ) for dt in dates ] ret = Series ( vals , index = dates ) if linreg_since is not None : ret = self . _linreg_future ( ret , linreg_since , lin_reg_days ) return ret . sort_index ( )
def cartesian_to_axial ( x , y , size , orientation , aspect_scale = 1 ) : '''Map Cartesion * ( x , y ) * points to axial * ( q , r ) * coordinates of enclosing tiles . This function was adapted from : https : / / www . redblobgames . com / grids / hexagons / # pixel - to - hex Args : x ( array [ float ] ...
HEX_FLAT = [ 2.0 / 3.0 , 0.0 , - 1.0 / 3.0 , np . sqrt ( 3.0 ) / 3.0 ] HEX_POINTY = [ np . sqrt ( 3.0 ) / 3.0 , - 1.0 / 3.0 , 0.0 , 2.0 / 3.0 ] coords = HEX_FLAT if orientation == 'flattop' else HEX_POINTY x = x / size * ( aspect_scale if orientation == "pointytop" else 1 ) y = - y / size / ( aspect_scale if orientatio...
def run ( self ) : """Run the multiopt parser"""
self . parser = MultioptOptionParser ( usage = "%prog <command> [options] [args]" , prog = self . clsname , version = self . version , option_list = self . global_options , description = self . desc_short , commands = self . command_set , epilog = self . footer ) try : self . options , self . args = self . parser ....
def set_password ( sender , ** kwargs ) : """Encrypts password of the user ."""
if sender . model_class . __name__ == 'User' : usr = kwargs [ 'object' ] if not usr . password . startswith ( '$pbkdf2' ) : usr . set_password ( usr . password ) usr . save ( )
def transfer_image ( self , image_id_or_slug , region_id ) : """This method allows you to transfer an image to a specified region . Required parameters image _ id : Numeric , this is the id of the image you would like to transfer . region _ id Numeric , this is the id of the region to which you would like...
if not image_id_or_slug : msg = 'image_id_or_slug is required to transfer an image!' raise DOPException ( msg ) if not region_id : raise DOPException ( 'region_id is required to transfer an image!' ) params = { 'region_id' : region_id } json = self . request ( '/images/%s/transfer' % image_id_or_slug , meth...
def _email ( name , * , allow_unverified = False ) : """This decorator is used to turn an e function into an email sending function ! The name parameter is the name of the email we ' re going to be sending ( used to locate the templates on the file system ) . The allow _ unverified kwarg flags whether we will...
def inner ( fn ) : @ functools . wraps ( fn ) def wrapper ( request , user_or_users , ** kwargs ) : if isinstance ( user_or_users , ( list , set ) ) : recipients = user_or_users else : recipients = [ user_or_users ] context = fn ( request , user_or_users , ** kwar...
def filepath_to_unicode_strings ( self , filepath ) : """Read text out of an input file . The default just reads the text , converts to unicode and yields one unicode string . Subclasses can override this function in order to preprocess , and can yield any number of strings . Args : filepath : a string ...
f = tf . gfile . Open ( filepath ) b = f . read ( ) yield text_encoder . to_unicode_ignore_errors ( b )
def downfile ( self , remotefile , localpath = '' ) : '''Usage : downfile < remotefile > [ localpath ] - download a remote file . remotefile - remote file at Baidu Yun ( after app root directory at Baidu Yun ) localpath - local path . if it ends with ' / ' or ' \\ ' , it specifies the local directory if it ...
localfile = localpath if not localpath : localfile = os . path . basename ( remotefile ) elif localpath [ - 1 ] == '\\' or localpath [ - 1 ] == '/' or os . path . isdir ( localpath ) : # localfile = os . path . join ( localpath , os . path . basename ( remotefile ) ) localfile = joinpath ( localpath , os . path...
async def stepper_config ( self , command ) : """This method configures 4 pins for stepper motor operation . This is a FirmataPlus feature . : param command : { " method " : " stepper _ config " , " params " : [ STEPS _ PER _ REVOLUTION , [ PIN1 , PIN2 , PIN3 , PIN4 ] ] } : returns : No message returned ."""
steps_per_revs = int ( command [ 0 ] ) pins = command [ 1 ] pin1 = int ( pins [ 0 ] ) pin2 = int ( pins [ 1 ] ) pin3 = int ( pins [ 2 ] ) pin4 = int ( pins [ 3 ] ) await self . core . stepper_config ( steps_per_revs , [ pin1 , pin2 , pin3 , pin4 ] )
def calc_area_under_PSD ( self , lowerFreq , upperFreq ) : """Sums the area under the PSD from lowerFreq to upperFreq . Parameters lowerFreq : float The lower limit of frequency to sum from upperFreq : float The upper limit of frequency to sum to Returns AreaUnderPSD : float The area under the PSD f...
Freq_startAreaPSD = take_closest ( self . freqs , lowerFreq ) index_startAreaPSD = int ( _np . where ( self . freqs == Freq_startAreaPSD ) [ 0 ] [ 0 ] ) Freq_endAreaPSD = take_closest ( self . freqs , upperFreq ) index_endAreaPSD = int ( _np . where ( self . freqs == Freq_endAreaPSD ) [ 0 ] [ 0 ] ) AreaUnderPSD = sum (...
def update ( self , unique_name = values . unset , callback_method = values . unset , callback_url = values . unset , friendly_name = values . unset , rate_plan = values . unset , status = values . unset , commands_callback_method = values . unset , commands_callback_url = values . unset , sms_fallback_method = values ...
return self . _proxy . update ( unique_name = unique_name , callback_method = callback_method , callback_url = callback_url , friendly_name = friendly_name , rate_plan = rate_plan , status = status , commands_callback_method = commands_callback_method , commands_callback_url = commands_callback_url , sms_fallback_metho...
def _post_resource ( self , body ) : """Create new resources and associated attributes . Example : acs . post _ resource ( [ " resourceIdentifier " : " masaya " , " parents " : [ ] , " attributes " : [ " issuer " : " default " , " name " : " country " , " value " : " Nicaragua " The issuer is effe...
assert isinstance ( body , ( list ) ) , "POST for requires body to be a list" uri = self . _get_resource_uri ( ) return self . service . _post ( uri , body )
def add_put ( self , * args , ** kwargs ) : """Shortcut for add _ route with method PUT"""
return self . add_route ( hdrs . METH_PUT , * args , ** kwargs )
def removeFriend ( self , user ) : """Remove the specified user from all sharing . Parameters : user ( str ) : MyPlexUser , username , email of the user to be added ."""
user = self . user ( user ) url = self . FRIENDUPDATE if user . friend else self . REMOVEINVITE url = url . format ( userId = user . id ) return self . query ( url , self . _session . delete )
def ext_pillar ( minion_id , pillar , # pylint : disable = W0613 key = None , only = ( ) ) : '''Read pillar data from Foreman via its API .'''
url = __opts__ [ 'foreman.url' ] user = __opts__ [ 'foreman.user' ] password = __opts__ [ 'foreman.password' ] api = __opts__ [ 'foreman.api' ] verify = __opts__ [ 'foreman.verifyssl' ] certfile = __opts__ [ 'foreman.certfile' ] keyfile = __opts__ [ 'foreman.keyfile' ] cafile = __opts__ [ 'foreman.cafile' ] lookup_para...
def plot_fit ( self , intervals = True , ** kwargs ) : """Plots the fit of the Gaussian process model to the data Parameters beta : np . array Contains untransformed starting values for latent variables intervals : Boolean Whether to plot uncertainty intervals or not Returns None ( plots the fit of th...
import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) date_index = self . index [ self . max_lag : ] expectation = self . expected_values ( self . latent_variables . get_z_values ( ) ) variance = self . variance_values ( self . latent_variables . get_z_values ( ) ) up...
def find_all ( self , pattern ) : """Return the subset of this RcParams dictionary whose keys match , using : func : ` re . search ` , the given ` ` pattern ` ` . Parameters pattern : str pattern as suitable for re . compile Returns RcParams RcParams instance with entries that match the given ` patter...
pattern_re = re . compile ( pattern ) ret = RcParams ( ) ret . defaultParams = self . defaultParams ret . update ( ( key , value ) for key , value in self . items ( ) if pattern_re . search ( key ) ) return ret
def ReadUntilClose ( self ) : """Yield packets until a Close packet is received ."""
while True : cmd , data = self . ReadUntil ( b'CLSE' , b'WRTE' ) if cmd == b'CLSE' : self . _Send ( b'CLSE' , arg0 = self . local_id , arg1 = self . remote_id ) break if cmd != b'WRTE' : if cmd == b'FAIL' : raise usb_exceptions . AdbCommandFailureException ( 'Command fail...
def set ( self , mode = None ) : """Set the coloring mode If enabled , some objects ( like case run Status ) are printed in color to easily spot failures , errors and so on . By default the feature is enabled when script is attached to a terminal . Possible values are : : COLOR = 0 . . . COLOR _ OFF . . . ....
# Detect from the environment if no mode given ( only once ) if mode is None : # Nothing to do if already detected if self . _mode is not None : return # Detect from the environment variable COLOR try : mode = int ( os . environ [ "COLOR" ] ) except StandardError : mode = COLOR_A...
def getAllReceivers ( sender = Any , signal = Any ) : """Get list of all receivers from global tables This gets all receivers which should receive the given signal from sender , each receiver should be produced only once by the resulting generator"""
receivers = { } for set in ( # Get receivers that receive * this * signal from * this * sender . getReceivers ( sender , signal ) , # Add receivers that receive * any * signal from * this * sender . getReceivers ( sender , Any ) , # Add receivers that receive * this * signal from * any * sender . getReceivers ( Any , s...
def _bytes_to_human ( self , B ) : '''Return the given bytes as a human friendly KB , MB , GB , or TB string'''
KB = float ( 1024 ) MB = float ( KB ** 2 ) # 1,048,576 GB = float ( KB ** 3 ) # 1,073,741,824 TB = float ( KB ** 4 ) # 1,099,511,627,776 if B < KB : return '{0} B' . format ( B ) B = float ( B ) if KB <= B < MB : return '{0:.2f} KB' . format ( B / KB ) elif MB <= B < GB : return '{0:.2f} MB' . format ( B / ...
def get_function ( self ) : """Gets the ` ` Function ` ` for this authorization . return : ( osid . authorization . Function ) - the function raise : OperationFailed - unable to complete request * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . learning . Activity . get _ objective if not bool ( self . _my_map [ 'functionId' ] ) : raise errors . IllegalState ( 'function empty' ) mgr = self . _get_provider_manager ( 'AUTHORIZATION' ) if not mgr . supports_function_lookup ( ) : raise errors . OperationFailed ( 'Aut...
def parse ( self ) : """Parses everyting into a datastructure that looks like : result = [ { ' origin _ filename ' : ' ' , ' result _ filename ' : ' ' , ' origin _ lines ' : [ ] , / / all lines of the original file ' result _ lines ' : [ ] , / / all lines of the newest file ' added _ lines ' : [ ] , / /...
result = [ ] z = None before_line_number , after_line_number = 0 , 0 position = 0 for line in self . diff_text . splitlines ( ) : # New File match = re . search ( r'diff .*a/(?P<origin_filename>.*) ' r'b/(?P<result_filename>.*)' , line ) if match is not None : if z is not None : result . app...
def create ( fc_layers = None , dropout = None , pretrained = True ) : """Vel factory function"""
def instantiate ( ** _ ) : return Resnet34 ( fc_layers , dropout , pretrained ) return ModelFactory . generic ( instantiate )
def _backtracking ( problem , assignment , domains , variable_chooser , values_sorter , inference = True ) : '''Internal recursive backtracking algorithm .'''
from simpleai . search . arc import arc_consistency_3 if len ( assignment ) == len ( problem . variables ) : return assignment pending = [ v for v in problem . variables if v not in assignment ] variable = variable_chooser ( problem , pending , domains ) values = values_sorter ( problem , assignment , variable , do...
def quickstart ( hosts , func , only_authenticate = False , ** kwargs ) : """Like quickrun ( ) , but automatically logs into the host before passing the connection to the callback function . : type hosts : Host | list [ Host ] : param hosts : A list of Host objects . : type func : function : param func : ...
if only_authenticate : quickrun ( hosts , autoauthenticate ( ) ( func ) , ** kwargs ) else : quickrun ( hosts , autologin ( ) ( func ) , ** kwargs )
def get_coordination_symmetry_measures ( self , only_minimum = True , all_csms = True , optimization = None ) : """Returns the continuous symmetry measures of the current local geometry in a dictionary . : return : the continuous symmetry measures of the current local geometry in a dictionary ."""
test_geometries = self . allcg . get_implemented_geometries ( len ( self . local_geometry . coords ) ) if len ( self . local_geometry . coords ) == 1 : if len ( test_geometries ) == 0 : return { } result_dict = { 'S:1' : { 'csm' : 0.0 , 'indices' : [ 0 ] , 'algo' : 'EXPLICIT' , 'local2perfect_map' : { 0...
def to_dlpack_for_write ( data ) : """Returns a reference view of NDArray that represents as DLManagedTensor until all previous read / write operations on the current array are finished . Parameters data : NDArray input data . Returns PyCapsule ( the pointer of DLManagedTensor ) a reference view of ND...
check_call ( _LIB . MXNDArrayWaitToWrite ( data . handle ) ) dlpack = DLPackHandle ( ) check_call ( _LIB . MXNDArrayToDLPack ( data . handle , ctypes . byref ( dlpack ) ) ) return ctypes . pythonapi . PyCapsule_New ( dlpack , _c_str_dltensor , _c_dlpack_deleter )
def experiments ( auth , label = None , project = None , subject = None ) : '''Retrieve Experiment tuples for experiments returned by this function . Example : > > > import yaxil > > > auth = yaxil . XnatAuth ( url = ' . . . ' , username = ' . . . ' , password = ' . . . ' ) > > > yaxil . experiment ( auth ,...
if subject and ( label or project ) : raise ValueError ( 'cannot provide subject with label or project' ) url = '{0}/data/experiments' . format ( auth . url . rstrip ( '/' ) ) logger . debug ( 'issuing http request %s' , url ) # compile query string columns = [ 'ID' , 'label' , 'project' , 'xnat:subjectassessordata...
def _calc_sampleset ( w1 , w2 , step , minimal ) : """Calculate sampleset for each model ."""
if minimal : arr = [ w1 - step , w1 , w2 , w2 + step ] else : arr = np . arange ( w1 - step , w2 + step + step , step ) return arr
def trigger_on_off ( request , trigger_id ) : """enable / disable the status of the trigger then go back home : param request : request object : param trigger _ id : the trigger ID to switch the status to True or False : type request : HttpRequest object : type trigger _ id : int : return render : rtype...
now = arrow . utcnow ( ) . to ( settings . TIME_ZONE ) . format ( 'YYYY-MM-DD HH:mm:ssZZ' ) trigger = get_object_or_404 ( TriggerService , pk = trigger_id ) if trigger . status : title = 'disabled' title_trigger = _ ( 'Set this trigger on' ) btn = 'success' trigger . status = False else : title = _ ...
def BuscarLocalidades ( self , cod_prov , cod_localidad = None , consultar = True ) : "Devuelve la localidad o la consulta en AFIP ( uso interno )"
# si no se especifíca cod _ localidad , es util para reconstruir la cache import wslpg_datos as datos if not str ( cod_localidad ) in datos . LOCALIDADES and consultar : d = self . ConsultarLocalidadesPorProvincia ( cod_prov , sep = None ) try : # actualizar el diccionario persistente ( shelve ) datos ...
def TransformerEncoder ( vocab_size , num_classes = 10 , feature_depth = 512 , feedforward_depth = 2048 , num_layers = 6 , num_heads = 8 , dropout = 0.1 , max_len = 2048 , mode = 'train' ) : """Transformer encoder . Args : vocab _ size : int : vocab size num _ classes : how many classes on output feature _ ...
input_embedding = layers . Serial ( layers . Embedding ( feature_depth , vocab_size ) , layers . Dropout ( rate = dropout , mode = mode ) , layers . PositionalEncoding ( max_len = max_len ) ) return layers . Serial ( layers . Branch ( ) , # Branch input to create embedding and mask . layers . Parallel ( input_embedding...
async def message_field ( self , msg , field , fvalue = None ) : """Dumps / Loads message field : param msg : : param field : : param fvalue : explicit value for dump : return :"""
fname , ftype , params = field [ 0 ] , field [ 1 ] , field [ 2 : ] try : self . tracker . push_field ( fname ) if self . writing : await self . _dump_message_field ( self . iobj , msg , field , fvalue = fvalue ) else : await self . _load_message_field ( self . iobj , msg , field ) self ....
def _cast_empty_df_dtypes ( schema_fields , df ) : """Cast any columns in an empty dataframe to correct type . In an empty dataframe , pandas cannot choose a dtype unless one is explicitly provided . The _ bqschema _ to _ nullsafe _ dtypes ( ) function only provides dtypes when the dtype safely handles null v...
if not df . empty : raise ValueError ( "DataFrame must be empty in order to cast non-nullsafe dtypes" ) dtype_map = { "BOOLEAN" : bool , "INTEGER" : np . int64 } for field in schema_fields : column = str ( field [ "name" ] ) if field [ "mode" ] . upper ( ) == "REPEATED" : continue dtype = dtype_...
def _set_bpdu_mac ( self , v , load = False ) : """Setter method for bpdu _ mac , mapped from YANG variable / interface / port _ channel / spanning _ tree / bpdu _ mac ( enumeration ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ bpdu _ mac is considered as a private ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'0100.0ccc.cccd' : { } , u'0304.0800.0700' : { } } , ) , is_leaf = True , yang_name = "bpdu-mac" , rest_name = "bpdu-mac" , pare...
def x_lower_limit ( self , limit = None ) : """Returns or sets ( if a value is provided ) the value at which the x - axis should start . By default this is zero ( unless there are negative values ) . : param limit : If given , the chart ' s x _ lower _ limit will be set to this . : raises ValueError : if yo...
if limit is None : if self . _x_lower_limit is None : if self . smallest_x ( ) < 0 : if self . smallest_x ( ) == self . largest_x ( ) : return int ( self . smallest_x ( ) - 1 ) else : return self . smallest_x ( ) else : return 0 ...
async def remove_key ( request : web . Request ) -> web . Response : """Remove a key . DELETE / wifi / keys / : id - > 200 OK { message : ' Removed key keyfile . pem ' }"""
keys_dir = CONFIG [ 'wifi_keys_dir' ] available_keys = os . listdir ( keys_dir ) requested_hash = request . match_info [ 'key_uuid' ] if requested_hash not in available_keys : return web . json_response ( { 'message' : 'No such key file {}' . format ( requested_hash ) } , status = 404 ) key_path = os . path . join ...
def mcc ( x , axis = 0 , autocorrect = False ) : """Matthews correlation Parameters x : ndarray dataset of binary [ 0,1 ] values axis : int , optional Variables as columns is the default ( axis = 0 ) . If variables are in the rows use axis = 1 autocorrect : bool , optional If all predictions are Tru...
# transpose if axis < > 0 if axis is not 0 : x = x . T # read dimensions and n , c = x . shape # check if enough variables provided if c < 2 : raise Exception ( "Only " + str ( c ) + " variables provided. Min. 2 required." ) # allocate variables r = np . ones ( ( c , c ) ) p = np . zeros ( ( c , c ) ) # compute...
def close ( self ) : """Close this pipe object . Future calls to ` read ` after the buffer has been emptied will return immediately with an empty string ."""
self . _lock . acquire ( ) try : self . _closed = True self . _cv . notifyAll ( ) if self . _event is not None : self . _event . set ( ) finally : self . _lock . release ( )
def p_always_ff ( self , p ) : 'always _ ff : ALWAYS _ FF senslist always _ statement'
p [ 0 ] = AlwaysFF ( p [ 2 ] , p [ 3 ] , lineno = p . lineno ( 1 ) )
def get_face_fun_on ( self ) : """determine extend fmt"""
command = const . CMD_OPTIONS_RRQ command_string = b'FaceFunOn\x00' response_size = 1024 cmd_response = self . __send_command ( command , command_string , response_size ) if cmd_response . get ( 'status' ) : response = ( self . __data . split ( b'=' , 1 ) [ - 1 ] . split ( b'\x00' ) [ 0 ] ) return safe_cast ( r...
def resolve ( self , var , context ) : """Resolves a variable out of context if it ' s not in quotes"""
if var is None : return var if var [ 0 ] in ( '"' , "'" ) and var [ - 1 ] == var [ 0 ] : return var [ 1 : - 1 ] else : return template . Variable ( var ) . resolve ( context )
def get_commission_coeff ( self , code ) : """当前无法区分是百分比还是按手数收费 , 不过可以拿到以后自行判断"""
return max ( self . get_code ( code ) . get ( 'commission_coeff_peramount' ) , self . get_code ( code ) . get ( 'commission_coeff_pervol' ) )
def check_keystore_json ( jsondata : Dict ) -> bool : """Check if ` ` jsondata ` ` has the structure of a keystore file version 3. Note that this test is not complete , e . g . it doesn ' t check key derivation or cipher parameters . Copied from https : / / github . com / vbuterin / pybitcointools Args : js...
if 'crypto' not in jsondata and 'Crypto' not in jsondata : return False if 'version' not in jsondata : return False if jsondata [ 'version' ] != 3 : return False crypto = jsondata . get ( 'crypto' , jsondata . get ( 'Crypto' ) ) if 'cipher' not in crypto : return False if 'ciphertext' not in crypto : ...
def write_table ( table , path , column_styles = None , cell_styles = None ) : """Exporta una tabla en el formato deseado ( CSV o XLSX ) . La extensión del archivo debe ser " . csv " o " . xlsx " , y en función de ella se decidirá qué método usar para escribirlo . Args : table ( list of dicts ) : Tabla...
assert isinstance ( path , string_types ) , "`path` debe ser un string" assert isinstance ( table , list ) , "`table` debe ser una lista de dicts" # si la tabla está vacía , no escribe nada if len ( table ) == 0 : logger . warning ( "Tabla vacia: no se genera ninguna archivo." ) return # Sólo sabe escribir l...
def drop_modifiers ( sentence_str ) : """Given a string , drop the modifiers and return a string without them"""
tdoc = textacy . Doc ( sentence_str , lang = 'en_core_web_lg' ) new_sent = tdoc . text unusual_char = '形' for tag in tdoc : if tag . dep_ . endswith ( 'mod' ) : # Replace the tag new_sent = new_sent [ : tag . idx ] + unusual_char * len ( tag . text ) + new_sent [ tag . idx + len ( tag . text ) : ] new_sent ...
def inflate_dtype ( arr , names ) : """Create structured dtype from a 2d ndarray with unstructured dtype ."""
arr = np . asanyarray ( arr ) if has_structured_dt ( arr ) : return arr . dtype s_dt = arr . dtype dt = [ ( n , s_dt ) for n in names ] dt = np . dtype ( dt ) return dt
def run ( self ) : """Run the simulation ."""
# Define the resource requirements of each component in the simulation . vertices_resources = { # Every component runs on exactly one core and consumes a certain # amount of SDRAM to hold configuration data . component : { Cores : 1 , SDRAM : component . _get_config_size ( ) } for component in self . _components } # Wo...
def widen ( self ) : """Increase the interval size ."""
t , h = self . time , self . half_duration h *= self . scaling_coeff_x self . set_interval ( ( t - h , t + h ) )
def _get_cpu_info_from_proc_cpuinfo ( ) : '''Returns the CPU info gathered from / proc / cpuinfo . Returns { } if / proc / cpuinfo is not found .'''
try : # Just return { } if there is no cpuinfo if not DataSource . has_proc_cpuinfo ( ) : return { } returncode , output = DataSource . cat_proc_cpuinfo ( ) if returncode != 0 : return { } # Various fields vendor_id = _get_field ( False , output , None , '' , 'vendor_id' , 'vendor id...
def _parse_path ( path_args ) : """Parses positional arguments into key path with kinds and IDs . : type path _ args : tuple : param path _ args : A tuple from positional arguments . Should be alternating list of kinds ( string ) and ID / name parts ( int or string ) . : rtype : : class : ` list ` of : cl...
if len ( path_args ) == 0 : raise ValueError ( "Key path must not be empty." ) kind_list = path_args [ : : 2 ] id_or_name_list = path_args [ 1 : : 2 ] # Dummy sentinel value to pad incomplete key to even length path . partial_ending = object ( ) if len ( path_args ) % 2 == 1 : id_or_name_list += ( partial_endin...
def samtools_view ( self , file_name , param , postpend = "" ) : """Run samtools view , with flexible parameters and post - processing . This is used internally to implement the various count _ reads functions . : param str file _ name : file _ name : param str param : String of parameters to pass to samtools...
cmd = "{} view {} {} {}" . format ( self . tools . samtools , param , file_name , postpend ) return subprocess . check_output ( cmd , shell = True )
async def sunion ( self , keys , * args ) : "Return the union of sets specified by ` ` keys ` `"
args = list_or_args ( keys , args ) return await self . execute_command ( 'SUNION' , * args )
def get_sampletypes ( self ) : """Returns the available SampleTypes of the system"""
query = { "portal_type" : "SampleType" , "sort_on" : "sortable_title" , "sort_order" : "ascending" , "is_active" : True , } results = api . search ( query , "bika_setup_catalog" ) return map ( api . get_object , results )
def remove ( self , rel_path , propagate = False ) : '''Delete the file from the cache , and from the upstream'''
repo_path = os . path . join ( self . cache_dir , rel_path ) c = self . database . cursor ( ) c . execute ( "DELETE FROM files WHERE path = ?" , ( rel_path , ) ) if os . path . exists ( repo_path ) : os . remove ( repo_path ) self . database . commit ( ) if self . upstream and propagate : self . upstream . rem...
async def initialize ( self ) : '''Initialize static data like images and flavores and set it as object property'''
flavors = await self . _list_flavors ( ) images = await self . _list_images ( ) self . flavors_map = bidict ( ) self . images_map = bidict ( ) self . images_details = { } for flavor in flavors : self . flavors_map . put ( flavor [ 'id' ] , flavor [ 'name' ] , on_dup_key = 'OVERWRITE' , on_dup_val = 'OVERWRITE' ) fo...
def validate_read ( self , kwargs ) : """we don ' t support start , stop kwds in Sparse"""
kwargs = super ( ) . validate_read ( kwargs ) if 'start' in kwargs or 'stop' in kwargs : raise NotImplementedError ( "start and/or stop are not supported " "in fixed Sparse reading" ) return kwargs
def __gen_primary_text_file ( self ) : """generate the PAULA file that contains the primary text of the document graph . ( PAULA documents can have more than one primary text , but discoursegraphs only works with documents that are based on exactly one primary text . ) Example < ? xml version = " 1.0 " st...
paula_id = '{0}.{1}.text' . format ( self . corpus_name , self . name ) E , tree = gen_paula_etree ( paula_id ) tree . append ( E . body ( get_text ( self . dg ) ) ) self . files [ paula_id ] = tree self . file2dtd [ paula_id ] = PaulaDTDs . text return paula_id
def _check_arg ( self , arg ) : """Check individual argument ( list / tuple / string / etc )"""
if isinstance ( arg , list ) : return self . _get_dependencies_from_args ( arg ) elif isinstance ( arg , dict ) : return self . _get_dependencies_from_kwargs ( arg ) if not is_dependency_name ( arg ) : return set ( ) return set ( [ arg [ 1 : ] ] )
def addVariantSet ( self ) : """Adds a new VariantSet into this repo ."""
self . _openRepo ( ) dataset = self . _repo . getDatasetByName ( self . _args . datasetName ) dataUrls = self . _args . dataFiles name = self . _args . name if len ( dataUrls ) == 1 : if self . _args . name is None : name = getNameFromPath ( dataUrls [ 0 ] ) if os . path . isdir ( dataUrls [ 0 ] ) : # R...
def _cacheAllJobs ( self ) : """Downloads all jobs in the current job store into self . jobCache ."""
logger . debug ( 'Caching all jobs in job store' ) self . _jobCache = { jobGraph . jobStoreID : jobGraph for jobGraph in self . _jobStore . jobs ( ) } logger . debug ( '{} jobs downloaded.' . format ( len ( self . _jobCache ) ) )
def tuning_ranges ( self ) : """A dictionary describing the ranges of all tuned hyperparameters . The keys are the names of the hyperparameter , and the values are the ranges ."""
out = { } for _ , ranges in self . description ( ) [ 'HyperParameterTuningJobConfig' ] [ 'ParameterRanges' ] . items ( ) : for param in ranges : out [ param [ 'Name' ] ] = param return out
def _read_para_echo_response_unsigned ( self , code , cbit , clen , * , desc , length , version ) : """Read HIP ECHO _ RESPONSE _ UNSIGNED parameter . Structure of HIP ECHO _ RESPONSE _ UNSIGNED parameter [ RFC 7401 ] : 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | Type | Length ...
_data = self . _read_fileng ( clen ) echo_response_unsigned = dict ( type = desc , critical = cbit , length = clen , data = _data , ) _plen = length - clen if _plen : self . _read_fileng ( _plen ) return echo_response_unsigned
def add_node_to_network ( self , node , network ) : """Add node to the chain and receive transmissions ."""
network . add_node ( node ) parents = node . neighbors ( direction = "from" ) if len ( parents ) : parent = parents [ 0 ] parent . transmit ( ) node . receive ( )
def execute ( self , slave_id , route_map ) : """Execute the Modbus function registered for a route . : param slave _ id : Slave id . : param eindpoint : Instance of modbus . route . Map ."""
for index , value in enumerate ( self . values ) : address = self . starting_address + index endpoint = route_map . match ( slave_id , self . function_code , address ) try : endpoint ( slave_id = slave_id , address = address , value = value , function_code = self . function_code ) # route _ map ...
def audio_stream_capture ( self , httptype = None , channel = None , path_file = None ) : """Params : path _ file - path to output file channel : - integer httptype - type string ( singlepart or multipart ) singlepart : HTTP content is a continuos flow of audio packets multipart : HTTP content type is mul...
if httptype is None and channel is None : raise RuntimeError ( "Requires htttype and channel" ) ret = self . command ( 'audio.cgi?action=getAudio&httptype={0}&channel={1}' . format ( httptype , channel ) ) if path_file : with open ( path_file , 'wb' ) as out_file : shutil . copyfileobj ( ret . raw , out...
def _meet ( intervals_hier , labels_hier , frame_size ) : '''Compute the ( sparse ) least - common - ancestor ( LCA ) matrix for a hierarchical segmentation . For any pair of frames ` ` ( s , t ) ` ` , the LCA is the deepest level in the hierarchy such that ` ` ( s , t ) ` ` are contained within a single se...
frame_size = float ( frame_size ) # Figure out how many frames we need n_start , n_end = _hierarchy_bounds ( intervals_hier ) n = int ( ( _round ( n_end , frame_size ) - _round ( n_start , frame_size ) ) / frame_size ) # Initialize the meet matrix meet_matrix = scipy . sparse . lil_matrix ( ( n , n ) , dtype = np . uin...
def RelaxNGSetSchema ( self , schema ) : """Use RelaxNG to validate the document as it is processed . Activation is only possible before the first Read ( ) . if @ schema is None , then RelaxNG validation is desactivated . @ The @ schema should not be freed until the reader is deallocated or its use has been...
if schema is None : schema__o = None else : schema__o = schema . _o ret = libxml2mod . xmlTextReaderRelaxNGSetSchema ( self . _o , schema__o ) return ret