signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def line_width ( line ) : """计算本行在输出到命令行后所占的宽度 calculate the width of output in terminal"""
if six . PY2 : assert isinstance ( line , unicode ) _line = width_cal_preprocess ( line ) result = sum ( map ( get_char_width , _line ) ) return result
def _get_app_config ( self , app_name ) : """Returns an app config for the given name , not by label ."""
matches = [ app_config for app_config in apps . get_app_configs ( ) if app_config . name == app_name ] if not matches : return return matches [ 0 ]
def _splitlines_preserving_trailing_newline ( str ) : '''Returns a list of the lines in the string , breaking at line boundaries and preserving a trailing newline ( if present ) . Essentially , this works like ` ` str . striplines ( False ) ` ` but preserves an empty line at the end . This is equivalent to th...
lines = str . splitlines ( ) if str . endswith ( '\n' ) or str . endswith ( '\r' ) : lines . append ( '' ) return lines
def get_config_input_with_inactive ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_config = ET . Element ( "get_config" ) config = get_config input = ET . SubElement ( get_config , "input" ) with_inactive = ET . SubElement ( input , "with-inactive" , xmlns = "http://tail-f.com/ns/netconf/inactive/1.0" ) callback = kwargs . pop ( 'callback' , self . _callback ) r...
def get_or_create_candidate ( self , row , party , race ) : """Gets or creates the Candidate object for the given row of AP data . In order to tie with live data , this will synthesize the proper AP candidate id . This function also calls ` get _ or _ create _ person ` to get a Person object to pass to Djan...
person = self . get_or_create_person ( row ) id_components = row [ "id" ] . split ( "-" ) candidate_id = "{0}-{1}" . format ( id_components [ 1 ] , id_components [ 2 ] ) defaults = { "party" : party , "incumbent" : row . get ( "incumbent" ) } if person . last_name == "None of these candidates" : candidate_id = "{0}...
async def communicate ( self , data_id = None , run_sync = False , save_settings = True ) : """Scan database for resolving Data objects and process them . This is submitted as a task to the manager ' s channel workers . : param data _ id : Optional id of Data object which ( + its children ) should be processe...
executor = getattr ( settings , 'FLOW_EXECUTOR' , { } ) . get ( 'NAME' , 'resolwe.flow.executors.local' ) logger . debug ( __ ( "Manager sending communicate command on '{}' triggered by Data with id {}." , state . MANAGER_CONTROL_CHANNEL , data_id , ) ) saved_settings = self . state . settings_override if save_settings...
def readlink ( path ) : '''Equivalent to os . readlink ( )'''
if six . PY3 or not salt . utils . platform . is_windows ( ) : return os . readlink ( path ) if not HAS_WIN32FILE : log . error ( 'Cannot read %s, missing required modules' , path ) reparse_data = _get_reparse_data ( path ) if not reparse_data : # Reproduce * NIX behavior when os . readlink is performed on a pa...
def retryable_http_error ( e ) : """Determine if an error encountered during an HTTP download is likely to go away if we try again ."""
if isinstance ( e , urllib . error . HTTPError ) and e . code in ( '503' , '408' , '500' ) : # The server returned one of : # 503 Service Unavailable # 408 Request Timeout # 500 Internal Server Error return True if isinstance ( e , BadStatusLine ) : # The server didn ' t return a valid response at all return Tr...
def getOverlayColor ( self , ulOverlayHandle ) : """Gets the color tint of the overlay quad ."""
fn = self . function_table . getOverlayColor pfRed = c_float ( ) pfGreen = c_float ( ) pfBlue = c_float ( ) result = fn ( ulOverlayHandle , byref ( pfRed ) , byref ( pfGreen ) , byref ( pfBlue ) ) return result , pfRed . value , pfGreen . value , pfBlue . value
def atualizar_software_sat ( self ) : """Sobrepõe : meth : ` ~ satcfe . base . FuncoesSAT . atualizar _ software _ sat ` . : return : Uma resposta SAT padrão . : rtype : satcfe . resposta . padrao . RespostaSAT"""
retorno = super ( ClienteSATLocal , self ) . atualizar_software_sat ( ) return RespostaSAT . atualizar_software_sat ( retorno )
def predict ( self , X , break_ties = "random" , return_probs = False , ** kwargs ) : """Predicts int labels for an input X on all tasks Args : X : The input for the predict _ proba method break _ ties : A tie - breaking policy return _ probs : Return the predicted probabilities as well Returns : Y _ p ...
Y_s = self . predict_proba ( X , ** kwargs ) self . _check ( Y_s , typ = list ) self . _check ( Y_s [ 0 ] , typ = np . ndarray ) Y_p = [ ] for Y_ts in Y_s : Y_tp = self . _break_ties ( Y_ts , break_ties ) Y_p . append ( Y_tp . astype ( np . int ) ) if return_probs : return Y_p , Y_s else : return Y_p
def load_xml ( self , xmlfile ) : """Load model definition from XML . Parameters xmlfile : str Name of the input XML file ."""
self . logger . info ( 'Loading XML' ) for c in self . components : c . load_xml ( xmlfile ) for name in self . like . sourceNames ( ) : self . update_source ( name ) self . _fitcache = None self . logger . info ( 'Finished Loading XML' )
def dispatch ( self , request , * args , ** kwargs ) : # type : ( HttpRequest , object , object ) - > HttpResponse """Inspect the HTTP method and delegate to the view method . This is the default implementation of the : py : class : ` django . views . View ` method , which will inspect the HTTP method in the ...
return super ( SkillAdapter , self ) . dispatch ( request )
def decrypt ( self , data , oaep_hash_fn_name = None , mgf1_hash_fn_name = None ) : """Decrypt a data that used PKCS1 OAEP protocol : param data : data to decrypt : param oaep _ hash _ fn _ name : hash function name to use with OAEP : param mgf1 _ hash _ fn _ name : hash function name to use with MGF1 padding...
if self . __private_key is None : raise ValueError ( 'Unable to call this method. Private key must be set' ) if oaep_hash_fn_name is None : oaep_hash_fn_name = self . __class__ . __default_oaep_hash_function_name__ if mgf1_hash_fn_name is None : mgf1_hash_fn_name = self . __class__ . __default_mgf1_hash_fun...
def strptime ( string , timezone = 0 ) : """necessary because of 24:00 end of day labeling"""
year = int ( string [ 0 : 4 ] ) month = int ( string [ 5 : 7 ] ) day = int ( string [ 8 : 10 ] ) hour = int ( string [ - 5 : - 3 ] ) minute = int ( string [ - 2 : ] ) ts = datetime . datetime ( year , month , day ) + datetime . timedelta ( hours = hour , minutes = minute ) - datetime . timedelta ( hours = timezone ) re...
def file_type ( filename , param = 'rb' ) : """returns the type of file , e . g . , gz , bz2 , normal"""
magic_dict = { b"\x1f\x8b\x08" : "gz" , b"\x42\x5a\x68" : "bz2" , b"\x50\x4b\x03\x04" : "zip" } if param . startswith ( 'w' ) : return filename . split ( '.' ) [ - 1 ] max_len = max ( len ( x ) for x in magic_dict ) with open ( filename , 'rb' ) as f : file_start = f . read ( max_len ) for magic , filetype in l...
def contains_circle ( self , pt , radius ) : """Is the circle completely inside this rect ?"""
return ( self . l < pt . x - radius and self . r > pt . x + radius and self . t < pt . y - radius and self . b > pt . y + radius )
def create_product ( self , name , location = 'GLO' , unit = 'kg' , ** kwargs ) : """Create a new product in the model database"""
new_product = item_factory ( name = name , location = location , unit = unit , type = 'product' , ** kwargs ) if not self . exists_in_database ( new_product [ 'code' ] ) : self . add_to_database ( new_product ) # print ( ' { } added to database ' . format ( name ) ) return self . get_exchange ( name ) else ...
def setMinGap ( self , typeID , minGap ) : """setMinGap ( string , double ) - > None Sets the offset ( gap to front vehicle if halting ) of vehicles of this type ."""
self . _connection . _sendDoubleCmd ( tc . CMD_SET_VEHICLETYPE_VARIABLE , tc . VAR_MINGAP , typeID , minGap )
def create_new ( projectname ) : """Name of the project"""
git_url = "https://github.com/moluwole/Bast_skeleton" path = os . path . abspath ( '.' ) + "/" + projectname if not os . path . exists ( path ) : os . makedirs ( path ) click . echo ( Fore . GREEN + ' ___ ___ __________' ) click . echo ( Fore . GREEN + ' / _ )/ _ | / __/_ __/' ) click . echo ( Fore . GREEN ...
def prepend_zeros_to_lists ( ls ) : """Takes a list of lists and appends 0s to the beggining of each sub _ list until they are all the same length . Used for sign - extending binary numbers ."""
longest = max ( [ len ( l ) for l in ls ] ) for i in range ( len ( ls ) ) : while len ( ls [ i ] ) < longest : ls [ i ] . insert ( 0 , "0" )
def file_is_attached ( self , url ) : '''return true if at least one book has file with the given url as attachment'''
body = self . _get_search_field ( '_attachments.url' , url ) return self . es . count ( index = self . index_name , body = body ) [ 'count' ] > 0
def routing_monitoring ( self ) : """Return route table for the engine , including gateway , networks and type of route ( dynamic , static ) . Calling this can take a few seconds to retrieve routes from the engine . Find all routes for engine resource : : > > > engine = Engine ( ' sg _ vm ' ) > > > for ...
try : result = self . make_request ( EngineCommandFailed , resource = 'routing_monitoring' ) return Route ( result ) except SMCConnectionError : raise EngineCommandFailed ( 'Timed out waiting for routes' )
def summarizeReads ( file_handle , file_type ) : """open a fasta or fastq file , prints number of of reads , average length of read , total number of bases , longest , shortest and median read , total number and average of individual base ( A , T , G , C , N ) ."""
base_counts = defaultdict ( int ) read_number = 0 total_length = 0 length_list = [ ] records = SeqIO . parse ( file_handle , file_type ) for record in records : total_length += len ( record ) read_number += 1 length_list . append ( len ( record ) ) for base in record : base_counts [ base ] += 1 ...
async def ListModels ( self , tag ) : '''tag : str Returns - > typing . Sequence [ ~ UserModel ]'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'ModelManager' , request = 'ListModels' , version = 5 , params = _params ) _params [ 'tag' ] = tag reply = await self . rpc ( msg ) return reply
def get_widget ( self , request ) : """Table view is not able to get form field from reverse relation . Therefore this widget returns similar form field as direct relation ( ModelChoiceField ) . Because there is used " RestrictedSelectWidget " it is returned textarea or selectox with choices according to coun...
return self . _update_widget_choices ( forms . ModelChoiceField ( widget = RestrictedSelectWidget , queryset = self . field . related_model . _default_manager . all ( ) ) . widget )
def versions_from_parentdir ( parentdir_prefix , root , verbose ) : """Try to determine the version from the parent directory name . Source tarballs conventionally unpack into a directory that includes both the project name and a version string . We will also support searching up two directory levels for an a...
rootdirs = [ ] for i in range ( 3 ) : dirname = os . path . basename ( root ) if dirname . startswith ( parentdir_prefix ) : return { "version" : dirname [ len ( parentdir_prefix ) : ] , "full-revisionid" : None , "dirty" : False , "error" : None , "date" : None } else : rootdirs . append ( ...
def RetryUpload ( self , job , job_id , error ) : """Retry the BigQuery upload job . Using the same job id protects us from duplicating data on the server . If we fail all of our retries we raise . Args : job : BigQuery job object job _ id : ID string for this upload job error : errors . HttpError objec...
if self . IsErrorRetryable ( error ) : retry_count = 0 sleep_interval = config . CONFIG [ "BigQuery.retry_interval" ] while retry_count < config . CONFIG [ "BigQuery.retry_max_attempts" ] : time . sleep ( sleep_interval . seconds ) logging . info ( "Retrying job_id: %s" , job_id ) re...
def select_directory ( self ) : """Select directory"""
self . redirect_stdio . emit ( False ) directory = getexistingdirectory ( self . main , _ ( "Select directory" ) , getcwd_or_home ( ) ) if directory : self . chdir ( directory ) self . redirect_stdio . emit ( True )
def check_overlap ( self , other , wavelengths = None , threshold = 0.01 ) : """Check for wavelength overlap between two spectra . Only wavelengths where ` ` self ` ` throughput is non - zero are considered . Example of full overlap : : | - - - - - other - - - - - | | - - - - - self - - - - - | Examples...
if not isinstance ( other , BaseSpectrum ) : raise exceptions . SynphotError ( 'other must be spectrum or bandpass.' ) # Special cases where no sampling wavelengths given and # one of the inputs is continuous . if wavelengths is None : if other . waveset is None : return 'full' if self . waveset is ...
def open_files ( subseqs ) : """Open file statements ."""
print ( ' . open_files' ) lines = Lines ( ) lines . add ( 1 , 'cpdef open_files(self, int idx):' ) for seq in subseqs : lines . add ( 2 , 'if self._%s_diskflag:' % seq . name ) lines . add ( 3 , 'self._%s_file = fopen(str(self._%s_path).encode(), ' '"rb+")' % ( 2 * ( seq . name , ) ) ) if seq . N...
def open ( filename , frame = 'unspecified' ) : """Create a PointCloud from data saved in a file . Parameters filename : : obj : ` str ` The file to load data from . frame : : obj : ` str ` The frame to apply to the created PointCloud . Returns : obj : ` PointCloud ` A PointCloud created from the da...
data = BagOfPoints . load_data ( filename ) return PointCloud ( data , frame )
def func ( f , xmin , xmax , step = None ) : """Create sample points from function < f > , which must be a single - parameter function that returns a number ( e . g . , math . sin ) . Parameters < xmin > and < xmax > specify the first and last X values , and < step > specifies the sampling interval . > > > ...
data = [ ] x = xmin if not step : step = ( xmax - xmin ) / 100.0 while x < xmax : data . append ( ( x , f ( x ) ) ) x += step return data
def preferred_ordinal ( cls , attr_name ) : """Returns an ordering value for a particular attribute key . Unrecognized attributes and OIDs will be sorted lexically at the end . : return : An orderable value ."""
attr_name = cls . map ( attr_name ) if attr_name in cls . preferred_order : ordinal = cls . preferred_order . index ( attr_name ) else : ordinal = len ( cls . preferred_order ) return ( ordinal , attr_name )
def _read_page ( file_obj , page_header , column_metadata ) : """Read the data page from the given file - object and convert it to raw , uncompressed bytes ( if necessary ) ."""
bytes_from_file = file_obj . read ( page_header . compressed_page_size ) codec = column_metadata . codec if codec is not None and codec != parquet_thrift . CompressionCodec . UNCOMPRESSED : if column_metadata . codec == parquet_thrift . CompressionCodec . SNAPPY : raw_bytes = snappy . decompress ( bytes_fro...
def _rudimentary_get_command ( self , args ) : """Rudimentary parsing to get the command"""
nouns = [ ] command_names = self . commands_loader . command_table . keys ( ) for arg in args : if arg and arg [ 0 ] != '-' : nouns . append ( arg ) else : break def _find_args ( args ) : search = ' ' . join ( args ) . lower ( ) return next ( ( x for x in command_names if x . startswith ...
def get_editor_widget ( self , request , plugins , plugin ) : """Returns the Django form Widget to be used for the text area"""
cancel_url_name = self . get_admin_url_name ( 'delete_on_cancel' ) cancel_url = reverse ( 'admin:%s' % cancel_url_name ) render_plugin_url_name = self . get_admin_url_name ( 'render_plugin' ) render_plugin_url = reverse ( 'admin:%s' % render_plugin_url_name ) action_token = self . get_action_token ( request , plugin ) ...
def projection_matrix ( w ) : '''Return the projection matrix of a direction w .'''
return np . identity ( 3 ) - np . dot ( np . reshape ( w , ( 3 , 1 ) ) , np . reshape ( w , ( 1 , 3 ) ) )
def on_message ( self , client , userdata , msg ) : """Callback when the MQTT client received a new message . : param client : the MQTT client . : param userdata : unused . : param msg : the MQTT message ."""
if msg is None : return self . log_info ( "New message on topic {}" . format ( msg . topic ) ) self . log_debug ( "Payload {}" . format ( msg . payload ) ) if msg . payload is None or len ( msg . payload ) == 0 : pass if msg . payload : payload = json . loads ( msg . payload . decode ( 'utf-8' ) ) site_...
def to_example ( dictionary ) : """Helper : build tf . Example from ( string - > int / float / str list ) dictionary ."""
features = { } for ( k , v ) in six . iteritems ( dictionary ) : if not v : raise ValueError ( "Empty generated field: %s" % str ( ( k , v ) ) ) if isinstance ( v [ 0 ] , six . integer_types ) : features [ k ] = tf . train . Feature ( int64_list = tf . train . Int64List ( value = v ) ) elif ...
def run_continuous ( self , scale ) : """Return a continuous solution to the RGE as ` RGsolution ` instance ."""
if scale == self . scale_in : raise ValueError ( "The scale must be different from the input scale" ) elif scale < self . scale_in : scale_min = scale scale_max = self . scale_in elif scale > self . scale_in : scale_max = scale scale_min = self . scale_in fun = rge . smeft_evolve_continuous ( C_in =...
def Spitzglass_low ( SG , Tavg , L = None , D = None , P1 = None , P2 = None , Q = None , Ts = 288.7 , Ps = 101325. , Zavg = 1 , E = 1. ) : r'''Calculation function for dealing with flow of a compressible gas in a pipeline with the Spitzglass ( low pressure drop ) formula . Can calculate any of the following , ...
c3 = 1.181102362204724409448818897637795275591 # 0.03 / inch or 150/127 c4 = 0.09144 c5 = 125.1060 if Q is None and ( None not in [ L , D , P1 , P2 ] ) : return c5 * Ts / Ps * D ** 2.5 * E * ( ( ( P1 - P2 ) * 2 * ( Ps + 1210. ) ) / ( L * SG * Tavg * Zavg * ( 1 + c4 / D + c3 * D ) ) ) ** 0.5 elif D is None and ( Non...
def _get_login_page ( self ) : """Go to the login page ."""
try : raw_res = yield from self . _session . get ( HOME_URL , timeout = self . _timeout ) except OSError : raise PyHydroQuebecError ( "Can not connect to login page" ) # Get login url content = yield from raw_res . text ( ) soup = BeautifulSoup ( content , 'html.parser' ) form_node = soup . find ( 'form' , { 'n...
def _Backward1_T_Ph ( P , h ) : """Backward equation for region 1 , T = f ( P , h ) Parameters P : float Pressure , [ MPa ] h : float Specific enthalpy , [ kJ / kg ] Returns T : float Temperature , [ K ] References IAPWS , Revised Release on the IAPWS Industrial Formulation 1997 for the Thermo...
I = [ 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 2 , 2 , 3 , 3 , 4 , 5 , 6 ] J = [ 0 , 1 , 2 , 6 , 22 , 32 , 0 , 1 , 2 , 3 , 4 , 10 , 32 , 10 , 32 , 10 , 32 , 32 , 32 , 32 ] n = [ - 0.23872489924521e3 , 0.40421188637945e3 , 0.11349746881718e3 , - 0.58457616048039e1 , - 0.15285482413140e-3 , - 0.10866707695377e...
def is_namespace_preordered ( self , namespace_id_hash ) : """Given a namespace preorder hash , determine if it is preordered at the current block ."""
namespace_preorder = self . get_namespace_preorder ( namespace_id_hash ) if namespace_preorder is None : return False else : return True
def get_scale_fac ( fig , fiducial_width = 8 , fiducial_height = 7 ) : """Gets a factor to scale fonts by for the given figure . The scale factor is relative to a figure with dimensions ( ` fiducial _ width ` , ` fiducial _ height ` ) ."""
width , height = fig . get_size_inches ( ) return ( width * height / ( fiducial_width * fiducial_height ) ) ** 0.5
def as_dict ( self ) : """Return the constructor arguments as a dictionary ( effectively the kwargs to the constructor ) . : return : dict of constructor arguments : rtype : dict"""
return { 'pip_version' : self . _pip_version , 'pip_url' : self . _pip_url , 'pip_requirement' : self . _pip_requirement , 'pkg_resources_version' : self . _pkg_resources_version , 'pkg_resources_url' : self . _pkg_resources_url , 'git_tag' : self . _git_tag , 'git_commit' : self . _git_commit , 'git_remotes' : self . ...
def _construct_grover_circuit ( self ) -> None : """Constructs an instance of Grover ' s Algorithm , using initialized values . : return : None"""
oracle = Program ( ) oracle_name = "GROVER_ORACLE" oracle . defgate ( oracle_name , self . unitary_function_mapping ) oracle . inst ( tuple ( [ oracle_name ] + self . qubits ) ) self . grover_circuit = self . oracle_grover ( oracle , self . qubits )
def create_or_update_detail ( self , request ) : """Implements Create / Update an object completely given an id maps to PUT / api / object / : id in rest semantics : param request : rip . Request : return : rip . Response"""
pipeline = crud_pipeline_factory . create_or_update_detail_pipeline ( configuration = self . configuration ) return pipeline ( request = request )
def cli_forms ( self , * args ) : """List all available form definitions"""
forms = [ ] missing = [ ] for key , item in schemastore . items ( ) : if 'form' in item and len ( item [ 'form' ] ) > 0 : forms . append ( key ) else : missing . append ( key ) self . log ( 'Schemata with form:' , forms ) self . log ( 'Missing forms:' , missing )
def to_naf ( self ) : """Converts the element to KAF"""
if self . type == 'KAF' : # # convert all the properties for node in self . node . findall ( 'properties/property' ) : node . set ( 'id' , node . get ( 'pid' ) ) del node . attrib [ 'pid' ]
def potential_radiation ( dates , lon , lat , timezone , terrain_slope = 0 , terrain_slope_azimuth = 0 , cloud_fraction = 0 , split = False ) : """Calculate potential shortwave radiation for a specific location and time . This routine calculates global radiation as described in : Liston , G . E . and Elder , K ...
solar_constant = 1367. days_per_year = 365.25 tropic_of_cancer = np . deg2rad ( 23.43697 ) solstice = 173.0 dates = pd . DatetimeIndex ( dates ) dates_hour = np . array ( dates . hour ) dates_minute = np . array ( dates . minute ) day_of_year = np . array ( dates . dayofyear ) # compute solar decline in rad solar_decli...
def _correct_for_light_travel_time ( observer , target ) : """Return a light - time corrected astrometric position and velocity . Given an ` observer ` that is a ` Barycentric ` position somewhere in the solar system , compute where in the sky they will see the body ` target ` , by computing the light - time ...
t = observer . t ts = t . ts cposition = observer . position . au cvelocity = observer . velocity . au_per_d tposition , tvelocity , gcrs_position , message = target . _at ( t ) distance = length_of ( tposition - cposition ) light_time0 = 0.0 t_tdb = t . tdb for i in range ( 10 ) : light_time = distance / C_AUDAY ...
def keys_at ( self , depth , counter = 1 ) : """Iterate keys at specified depth ."""
if depth < 1 : yield ROOT else : if counter == depth : for key in self . keys ( ) : yield key else : counter += 1 for dict_tree in self . values ( ) : for key in dict_tree . keys_at ( depth , counter ) : yield key
def set ( self , value ) : """Sets the value of the object : param value : A byte string"""
if not isinstance ( value , byte_cls ) : raise TypeError ( unwrap ( ''' %s value must be a byte string, not %s ''' , type_name ( self ) , type_name ( value ) ) ) self . _bytes = value self . contents = value self . _header = None if self . _indefinite : self . _indefinite = False...
def check_frequencies ( feed : "Feed" , * , as_df : bool = False , include_warnings : bool = False ) -> List : """Analog of : func : ` check _ agency ` for ` ` feed . frequencies ` ` ."""
table = "frequencies" problems = [ ] # Preliminary checks if feed . frequencies is None : return problems f = feed . frequencies . copy ( ) problems = check_for_required_columns ( problems , table , f ) if problems : return format_problems ( problems , as_df = as_df ) if include_warnings : problems = check_...
def prepack ( self , namedstruct , skip_self = False , skip_sub = False ) : '''Run prepack'''
if not skip_sub and self . header is not None and hasattr ( self . header , 'fullprepack' ) : self . header . fullprepack ( namedstruct . _seqs [ 0 ] ) Parser . prepack ( self , namedstruct , skip_self , skip_sub )
def _create_parsing_plan ( self , desired_type : Type [ T ] , filesystem_object : PersistedObject , logger : Logger , log_only_last : bool = False ) -> ParsingPlan [ T ] : """Creates a parsing plan to parse the given filesystem object into the given desired _ type . This overrides the method in AnyParser , in ord...
# build the parsing plan logger . debug ( '(B) ' + get_parsing_plan_log_str ( filesystem_object , desired_type , log_only_last = log_only_last , parser = self ) ) return CascadingParser . CascadingParsingPlan ( desired_type , filesystem_object , self , self . _parsers_list , logger = logger )
def pull_byte ( self , stack_pointer ) : """pulled a byte from stack"""
addr = stack_pointer . value byte = self . memory . read_byte ( addr ) # log . info ( # log . error ( # " % x | \ tpull $ % x from % s stack at $ % x \ t | % s " , # self . last _ op _ address , byte , stack _ pointer . name , addr , # self . cfg . mem _ info . get _ shortest ( self . last _ op _ address ) # FIXME : se...
def export ( * pools , ** kwargs ) : '''. . versionadded : : 2015.5.0 Export storage pools pools : string One or more storage pools to export force : boolean Force export of storage pools CLI Example : . . code - block : : bash salt ' * ' zpool . export myzpool . . . [ force = True | False ] salt ...
# # Configure pool # NOTE : initialize the defaults flags = [ ] targets = [ ] # NOTE : set extra config based on kwargs if kwargs . get ( 'force' , False ) : flags . append ( '-f' ) # NOTE : append the pool name and specifications targets = list ( pools ) # # Export pools res = __salt__ [ 'cmd.run_all' ] ( __utils_...
def check_type_of_param_list_elements ( param_list ) : """Ensures that all elements of param _ list are ndarrays or None . Raises a helpful ValueError if otherwise ."""
try : assert isinstance ( param_list [ 0 ] , np . ndarray ) assert all ( [ ( x is None or isinstance ( x , np . ndarray ) ) for x in param_list ] ) except AssertionError : msg = "param_list[0] must be a numpy array." msg_2 = "All other elements must be numpy arrays or None." total_msg = msg + "\n" +...
def media_type_str ( mediatype ) : """Convert internal API media type to string ."""
if mediatype == const . MEDIA_TYPE_UNKNOWN : return 'Unknown' if mediatype == const . MEDIA_TYPE_VIDEO : return 'Video' if mediatype == const . MEDIA_TYPE_MUSIC : return 'Music' if mediatype == const . MEDIA_TYPE_TV : return 'TV' return 'Unsupported'
def __create_price_for ( self , commodity : Commodity , price : PriceModel ) : """Creates a new Price entry in the book , for the given commodity"""
logging . info ( "Adding a new price for %s, %s, %s" , commodity . mnemonic , price . datetime . strftime ( "%Y-%m-%d" ) , price . value ) # safety check . Compare currencies . sec_svc = SecurityAggregate ( self . book , commodity ) currency = sec_svc . get_currency ( ) if currency != price . currency : raise Value...
def subscribe_notice ( self , access_token ) : """doc : http : / / open . youku . com / docs / doc ? id = 31"""
url = 'https://openapi.youku.com/v2/users/subscribe/notice.json' params = { 'client_id' : self . client_id , 'access_token' : access_token } r = requests . get ( url , params = params ) check_error ( r ) return r . json ( )
def make_article_info ( self ) : """The Article Info contains the ( self ) Citation , Editors , Dates , Copyright , Funding Statement , Competing Interests Statement , Correspondence , and Footnotes . Maybe more . . . This content follows the Heading and precedes the Main segment in the output . This func...
body = self . main . getroot ( ) . find ( 'body' ) # Create a div for ArticleInfo , exposing it to linking and formatting article_info_div = etree . Element ( 'div' , { 'id' : 'ArticleInfo' } ) body . insert ( 1 , article_info_div ) # Creation of the self Citation article_info_div . append ( self . make_article_info_ci...
def call_copy_numbers ( seg_file , work_dir , data ) : """Call copy numbers from a normalized and segmented input file ."""
out_file = os . path . join ( work_dir , "%s-call.seg" % dd . get_sample_name ( data ) ) if not utils . file_exists ( out_file ) : with file_transaction ( data , out_file ) as tx_out_file : params = [ "-T" , "CallCopyRatioSegments" , "-I" , seg_file , "-O" , tx_out_file ] _run_with_memory_scaling ( ...
def storeIDToWebID ( key , storeid ) : """Takes a key ( int ) and storeid ( int ) and produces a webid ( a 16 - character str suitable for including in URLs )"""
i = key ^ storeid l = list ( '%0.16x' % ( i , ) ) for nybbleid in range ( 0 , 8 ) : a , b = _swapat ( key , nybbleid ) _swap ( l , a , b ) return '' . join ( l )
async def remove ( request : web . Request ) -> web . Response : """Remove a public key from authorized _ keys DELETE / server / ssh _ keys / : key _ md5 _ hexdigest - > 200 OK if the key was found - > 404 Not Found otherwise"""
requested_hash = request . match_info [ 'key_md5' ] new_keys : List [ str ] = [ ] found = False for keyhash , key in get_keys ( ) : if keyhash == requested_hash : found = True else : new_keys . append ( key ) if not found : return web . json_response ( data = { 'error' : 'invalid-key-hash' ,...
def merge_unique_identities ( db , from_uuid , to_uuid ) : """Merge one unique identity into another . Use this function to join ' from _ uuid ' unique identity into ' to _ uuid ' . Identities and enrollments related to ' from _ uuid ' will be assigned to ' to _ uuid ' . In addition , ' from _ uuid ' will be ...
with db . connect ( ) as session : fuid = find_unique_identity ( session , from_uuid ) tuid = find_unique_identity ( session , to_uuid ) if not fuid : raise NotFoundError ( entity = from_uuid ) if from_uuid == to_uuid : return if not tuid : raise NotFoundError ( entity = to_u...
def copyFile ( input , output , replace = None ) : """Copy a file whole from input to output ."""
_found = findFile ( output ) if not _found or ( _found and replace ) : shutil . copy2 ( input , output )
def ensure_utf8 ( str_or_unicode ) : """tests , if the input is ` ` str ` ` or ` ` unicode ` ` . if it is ` ` unicode ` ` , it will be encoded from ` ` unicode ` ` to ` ` utf - 8 ` ` . otherwise , the input string is returned ."""
if isinstance ( str_or_unicode , str ) : return str_or_unicode elif isinstance ( str_or_unicode , unicode ) : return str_or_unicode . encode ( 'utf-8' ) else : raise ValueError ( "Input '{0}' should be a string or unicode, but it is of " "type {1}" . format ( str_or_unicode , type ( str_or_unicode ) ) )
def list_get ( self , num_iids , fields = [ ] , session = None ) : '''taobao . items . list . get 批量获取商品信息 查看非公开属性时需要用户登录'''
request = TOPRequest ( 'taobao.items.list.get' ) request [ 'num_iids' ] = num_iids if not fields : item = Item ( ) fields = item . fields request [ 'fields' ] = fields self . create ( self . execute ( request , session ) ) return self . items
def _initialize_expectations ( self , config = None , data_asset_name = None ) : """Instantiates ` _ expectations _ config ` as empty by default or with a specified expectation ` config ` . In addition , this always sets the ` default _ expectation _ args ` to : ` include _ config ` : False , ` catch _ except...
if config != None : # ! ! ! Should validate the incoming config with jsonschema here # Copy the original so that we don ' t overwrite it by accident # Pandas incorrectly interprets this as an attempt to create a column and throws up a warning . Suppress it # since we are subclassing . with warnings . catch_warnings...
def filterAll ( self , ** kwargs ) : '''filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children . Results must match ALL the filter criteria . for ANY , use the * Or methods For just the nodes in this collection , use " filter " or " filterAnd " on a TagCol...
if canFilterTags is False : raise NotImplementedError ( 'filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.' ) allNodes = self . getAllNodes ( ) filterableNodes = FilterableTagCollection ( allNodes ) return filt...
def fold ( self , elems ) : """Perform constant folding . If the result of applying the operator to the elements would be a fixed constant value , returns the result of applying the operator to the operands . Otherwise , returns an instance of ` ` Instructions ` ` containing the instructions necessary to ap...
cond , if_true , if_false = elems if isinstance ( cond , Constant ) : return [ if_true if cond . value else if_false ] return [ Instructions ( [ cond , JumpIfNot ( len ( if_true ) + 2 ) , pop , if_true , Jump ( len ( if_false ) + 1 ) , pop , if_false ] ) ]
def adaptive_gaussian_prior_builder ( getter , name , * args , ** kwargs ) : """A pre - canned builder for adaptive scalar gaussian prior distributions . Given a true ` getter ` function and arguments forwarded from ` tf . get _ variable ` , return a distribution object for a scalar - valued adaptive gaussian p...
kwargs [ "shape" ] = ( ) loc_var = getter ( name + "_prior_loc" , * args , ** kwargs ) kwargs [ "initializer" ] = scale_variable_initializer ( 0.01 ) scale_var = getter ( name + "_prior_scale" , * args , ** kwargs ) prior = tfp . distributions . Normal ( loc = loc_var , scale = tf . nn . softplus ( scale_var ) , name =...
def get_config_value ( self , section , name = None , config_file = None ) : """Returns configuration value for a given [ ` ` section ` ` ] and ` ` name ` ` . : param section : Section we want to retrieve value from : param name : Name of configuration we want to retrieve : param config _ file : A path to fil...
if config_file is None : config_file = [ ] elif isinstance ( config_file , basestring ) : config_file = [ config_file ] config = self . _repo . ui for path in config_file : config . readconfig ( path ) return config . config ( section , name )
def hex_timestamp_to_datetime ( hex_timestamp ) : """Converts hex timestamp to a datetime object . > > > hex _ timestamp _ to _ datetime ( ' 558BBCF9 ' ) datetime . datetime ( 2015 , 6 , 25 , 8 , 34 , 1) > > > hex _ timestamp _ to _ datetime ( ' 0x558BBCF9 ' ) datetime . datetime ( 2015 , 6 , 25 , 8 , 34 , ...
if not hex_timestamp . startswith ( '0x' ) : hex_timestamp = '0x{0}' . format ( hex_timestamp ) return datetime . fromtimestamp ( int ( hex_timestamp , 16 ) )
def show_network ( self , network , ** _params ) : """Fetches information of a certain network ."""
return self . get ( self . network_path % ( network ) , params = _params )
def auprc ( y_true , y_pred ) : """Area under the precision - recall curve"""
y_true , y_pred = _mask_value_nan ( y_true , y_pred ) precision , recall , _ = skm . precision_recall_curve ( y_true , y_pred ) return skm . auc ( recall , precision )
def range_is_obj ( rng , rdfclass ) : """Test to see if range for the class should be an object or a litteral"""
if rng == 'rdfs_Literal' : return False if hasattr ( rdfclass , rng ) : mod_class = getattr ( rdfclass , rng ) for item in mod_class . cls_defs [ 'rdf_type' ] : try : if issubclass ( getattr ( rdfclass , item ) , rdfclass . rdfs_Literal ) : return False except Att...
def content ( self , path = None , overwrite = True , encoding = 'utf-8' ) : """Downloads file to the specified path or as temporary file and reads the file content in memory . Should not be used on very large files . : param path : Path for file download If omitted tmp file will be used . : param overwrite...
if path : self . download ( wait = True , path = path , overwrite = overwrite ) with io . open ( path , 'r' , encoding = encoding ) as fp : return fp . read ( ) with tempfile . NamedTemporaryFile ( ) as tmpfile : self . download ( wait = True , path = tmpfile . name , overwrite = overwrite ) wit...
def fixminimized ( self , alphabet ) : """After pyfst minimization , all unused arcs are removed , and all sink states are removed . However this may break compatibility . Args : alphabet ( list ) : The input alphabet Returns : None"""
endstate = len ( list ( self . states ) ) for state in self . states : for char in alphabet : found = 0 for arc in state . arcs : if self . isyms . find ( arc . ilabel ) == char : found = 1 break if found == 0 : self . add_arc ( state ....
def query_disease_comment ( ) : """Returns list of diseases comments by query parameters tags : - Query functions parameters : - name : comment in : query type : string required : false description : Comment on disease linked to UniProt entry default : ' % mutations % ' - name : entry _ name i...
args = get_args ( request_args = request . args , allowed_str_args = [ 'comment' , 'entry_name' ] , allowed_int_args = [ 'limit' ] ) return jsonify ( query . disease_comment ( ** args ) )
def invers ( self ) : """Return the invers matrix , if it can be calculated : return : Returns a new Matrix containing the invers : rtype : Matrix : raise : Raises an : py : exc : ` ValueError ` if the matrix is not inversible : note : Only a squared matrix with a determinant ! = 0 can be inverted . : tod...
if self . _columns != self . _rows : raise ValueError ( "A square matrix is needed" ) mArray = self . get_array ( False ) appList = [ 0 ] * self . _columns # add identity matrix to array in order to use gauss jordan algorithm for col in xrange ( self . _columns ) : mArray . append ( appList [ : ] ) mArray [...
def network_sampling ( n , filename , directory = None , snowball = False , user = None ) : """Selects a few users and exports a CSV of indicators for them . TODO : Returns the network / graph between the selected users . Parameters n : int Number of users to select . filename : string File to export to...
if snowball : if user is None : raise ValueError ( "Must specify a starting user from whom to initiate the snowball" ) else : users , agenda = [ user ] , [ user ] while len ( agenda ) > 0 : parent = agenda . pop ( ) dealphebetized_network = sorted ( parent . netwo...
def execute ( self , query , params = None , cursor = None ) : """Execute query in pool . Returns future yielding closed cursor . You can get rows , lastrowid , etc from the cursor . : param cursor : cursor class ( Cursor , DictCursor . etc . ) : return : Future of cursor : rtype : Future"""
conn = yield self . _get_conn ( ) try : cur = conn . cursor ( cursor ) yield cur . execute ( query , params ) yield cur . close ( ) except : self . _close_conn ( conn ) raise else : self . _put_conn ( conn ) raise Return ( cur )
def add_state_editor ( self , state_m ) : """Triggered whenever a state is selected . : param state _ m : The selected state model ."""
state_identifier = self . get_state_identifier ( state_m ) if state_identifier in self . closed_tabs : state_editor_ctrl = self . closed_tabs [ state_identifier ] [ 'controller' ] state_editor_view = state_editor_ctrl . view handler_id = self . closed_tabs [ state_identifier ] [ 'source_code_changed_handler...
def security_group_update ( secgroup = None , auth = None , ** kwargs ) : '''Update a security group secgroup Name , ID or Raw Object of the security group to update name New name for the security group description New description for the security group CLI Example : . . code - block : : bash salt...
cloud = get_operator_cloud ( auth ) kwargs = _clean_kwargs ( keep_name = True , ** kwargs ) return cloud . update_security_group ( secgroup , ** kwargs )
def from_pretrained ( cls , pretrained_model_name_or_path , cache_dir = None , * inputs , ** kwargs ) : """Instantiate a PreTrainedBertModel from a pre - trained model file . Download and cache the pre - trained model file if needed ."""
if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHIVE_MAP : vocab_file = PRETRAINED_VOCAB_ARCHIVE_MAP [ pretrained_model_name_or_path ] if '-cased' in pretrained_model_name_or_path and kwargs . get ( 'do_lower_case' , True ) : logger . warning ( "The pre-trained model you are loading is a cased m...
def download_file ( self , remote , local ) : """Downloads a file : param remote : remote file name : param local : local file name : return :"""
file = open ( local , 'wb' ) try : self . download ( remote , file ) finally : file . close ( )
def eigb ( A , y0 , eps , rmax = 150 , nswp = 20 , max_full_size = 1000 , verb = 1 ) : """Approximate computation of minimal eigenvalues in tensor train format This function uses alternating least - squares algorithm for the computation of several minimal eigenvalues . If you want maximal eigenvalues , just sen...
ry = y0 . r . copy ( ) lam = tt_eigb . tt_block_eig . tt_eigb ( y0 . d , A . n , A . m , A . tt . r , A . tt . core , y0 . core , ry , eps , rmax , ry [ y0 . d ] , 0 , nswp , max_full_size , verb ) y = tensor ( ) y . d = y0 . d y . n = A . n . copy ( ) y . r = ry y . core = tt_eigb . tt_block_eig . result_core . copy (...
def parse ( self , response , metadata_type ) : """Parses RETS metadata using the STANDARD - XML format : param response : requests Response object : param metadata _ type : string : return parsed : list"""
xml = xmltodict . parse ( response . text ) self . analyze_reply_code ( xml_response_dict = xml ) base = xml . get ( 'RETS' , { } ) . get ( 'METADATA' , { } ) . get ( metadata_type , { } ) if metadata_type == 'METADATA-SYSTEM' : syst = base . get ( 'System' , base . get ( 'SYSTEM' ) ) if not syst : rais...
def strip_ansi ( text , c1 = False , osc = False ) : '''Strip ANSI escape sequences from a portion of text . https : / / stackoverflow . com / a / 38662876/450917 Arguments : line : str osc : bool - include OSC commands in the strippage . c1 : bool - include C1 commands in the strippage . Notes : Enab...
text = ansi_csi0_finder . sub ( '' , text ) if osc : text = ansi_osc0_finder . sub ( '' , text ) if c1 : text = ansi_csi1_finder . sub ( '' , text ) # go first , less destructive if osc : text = ansi_osc1_finder . sub ( '' , text ) return text
def _load_cell ( args , cell_body ) : """Implements the BigQuery load magic used to load data from GCS to a table . The supported syntax is : % bq load < optional args > Args : args : the arguments following ' % bq load ' . cell _ body : optional contents of the cell interpreted as YAML or JSON . Return...
env = google . datalab . utils . commands . notebook_environment ( ) config = google . datalab . utils . commands . parse_config ( cell_body , env , False ) or { } parameters = config . get ( 'parameters' ) or [ ] if parameters : jsonschema . validate ( { 'parameters' : parameters } , BigQuerySchema . QUERY_PARAMS_...
def _lookup_user_data ( self , * args , ** kwargs ) : """Generic function for looking up values in a user - specific dictionary . Use as follows : : _ lookup _ user _ data ( ' path ' , ' to ' , ' desired ' , ' value ' , ' in ' , ' dictionary ' , default = < default value > , data _ kind = ' customization ' ...
user_data = self . get_user_data ( ) data_kind = kwargs . get ( 'data_kind' , 'customization' ) try : del ( kwargs [ 'data_kind' ] ) except KeyError , err : pass default_value = kwargs [ 'default' ] result = get_dict ( user_data , data_kind , * args , ** kwargs ) try : result = int ( result ) except : p...
def writeRecord ( self , f ) : """This is nearly identical to the original the FAU tag is the only tag not writen in the same place , doing so would require changing the parser and lots of extra logic ."""
if self . bad : raise BadPubmedRecord ( "This record cannot be converted to a file as the input was malformed.\nThe original line number (if any) is: {} and the original file is: '{}'" . format ( self . _sourceLine , self . _sourceFile ) ) else : authTags = { } for tag in authorBasedTags : for val i...
def parameters ( self , namespaced = False ) : """returns the exception varlink error parameters"""
if namespaced : return json . loads ( json . dumps ( self . args [ 0 ] [ 'parameters' ] ) , object_hook = lambda d : SimpleNamespace ( ** d ) ) else : return self . args [ 0 ] . get ( 'parameters' )
def batch_eval ( self , exprs , n , extra_constraints = ( ) , solver = None , model_callback = None ) : """Evaluate one or multiple expressions . : param exprs : A list of expressions to evaluate . : param n : Number of different solutions to return . : param extra _ constraints : Extra constraints ( as ASTs ...
if self . _solver_required and solver is None : raise BackendError ( "%s requires a solver for batch evaluation" % self . __class__ . __name__ ) converted_exprs = [ self . convert ( ex ) for ex in exprs ] return self . _batch_eval ( converted_exprs , n , extra_constraints = self . convert_list ( extra_constraints )...
def move_by_offset ( self , xoffset , yoffset ) : """Moving the mouse to an offset from current mouse position . : Args : - xoffset : X offset to move to , as a positive or negative integer . - yoffset : Y offset to move to , as a positive or negative integer ."""
if self . _driver . w3c : self . w3c_actions . pointer_action . move_by ( xoffset , yoffset ) self . w3c_actions . key_action . pause ( ) else : self . _actions . append ( lambda : self . _driver . execute ( Command . MOVE_TO , { 'xoffset' : int ( xoffset ) , 'yoffset' : int ( yoffset ) } ) ) return self