signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def instruction_DEC_memory ( self , opcode , ea , m ) : """Decrement memory location"""
r = self . DEC ( m ) # log . debug ( " $ % x DEC memory value $ % x - 1 = $ % x and write it to $ % x \ t | % s " % ( # self . program _ counter , # m , r , ea , # self . cfg . mem _ info . get _ shortest ( ea ) return ea , r & 0xff
def _f90repr ( self , value ) : """Convert primitive Python types to equivalent Fortran strings ."""
if isinstance ( value , bool ) : return self . _f90bool ( value ) elif isinstance ( value , numbers . Integral ) : return self . _f90int ( value ) elif isinstance ( value , numbers . Real ) : return self . _f90float ( value ) elif isinstance ( value , numbers . Complex ) : return self . _f90complex ( va...
def run_ideal_classifier ( args = { } ) : """Create and train classifier using given parameters ."""
numObjects = args . get ( "numObjects" , 10 ) numLocations = args . get ( "numLocations" , 10 ) numFeatures = args . get ( "numFeatures" , 10 ) numPoints = args . get ( "numPoints" , 10 ) trialNum = args . get ( "trialNum" , 42 ) useLocation = args . get ( "useLocation" , 1 ) numColumns = args . get ( "numColumns" , 1 ...
async def emit ( self , record : LogRecord ) : # type : ignore """Actually log the specified logging record to the stream ."""
if self . writer is None : self . writer = await self . _init_writer ( ) try : msg = self . format ( record ) + self . terminator self . writer . write ( msg . encode ( ) ) await self . writer . drain ( ) except Exception : await self . handleError ( record )
def MODE ( self , setmode ) : """Set mode ."""
if setmode == self . BOOST_MODE : self . actionNodeData ( 'BOOST_MODE' , True ) elif setmode in [ self . AUTO_MODE , self . MANU_MODE ] : if self . getAttributeData ( "BOOST_MODE" ) : self . actionNodeData ( 'BOOST_MODE' , False ) self . actionNodeData ( 'CONTROL_MODE' , setmode )
def convert_metadata ( self ) : """Method invoked when OK button is clicked ."""
# Converter parameter converter_parameter = { } # Target exposure if self . target_exposure_combo_box . isEnabled ( ) : exposure_index = self . target_exposure_combo_box . currentIndex ( ) exposure_key = self . target_exposure_combo_box . itemData ( exposure_index , Qt . UserRole ) converter_parameter [ 'ex...
def child_task ( self ) : '''child process - this holds all the GUI elements'''
self . parent_pipe_send . close ( ) self . parent_pipe_recv . close ( ) import wx_processguard from wx_loader import wx from wxconsole_ui import ConsoleFrame app = wx . App ( False ) app . frame = ConsoleFrame ( state = self , title = self . title ) app . frame . Show ( ) app . MainLoop ( )
def process_row ( cls , data , column_map ) : """Process the row data from Rekall"""
row = { } for key , value in data . iteritems ( ) : if not value : value = '-' elif isinstance ( value , list ) : value = value [ 1 ] elif isinstance ( value , dict ) : if 'type_name' in value : if 'UnixTimeStamp' in value [ 'type_name' ] : value = datetim...
def deleteSettings ( self , groupName = None ) : """Deletes registry items from the persistent store ."""
groupName = groupName if groupName else self . settingsGroupName settings = QtCore . QSettings ( ) logger . info ( "Deleting {} from: {}" . format ( groupName , settings . fileName ( ) ) ) removeSettingsGroup ( groupName )
def get_input_score_start_range_metadata ( self ) : """Gets the metadata for the input score start range . return : ( osid . Metadata ) - metadata for the input score start range * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template metadata = dict ( self . _mdata [ 'input_score_start_range' ] ) metadata . update ( { 'existing_decimal_values' : self . _my_map [ 'inputScoreStartRange' ] } ) return Metadata ( ** metadata )
def view_slow_sources ( token , dstore , maxrows = 20 ) : """Returns the slowest sources"""
info = dstore [ 'source_info' ] . value info . sort ( order = 'calc_time' ) return rst_table ( info [ : : - 1 ] [ : maxrows ] )
def click ( self , x , y ) : """Simulate click within window screen . Args : x , y : int , pixel distance from window ( left , top ) as origin Returns : None"""
print 'click at' , x , y self . _input_left_mouse ( x , y )
def _flatten_ancestors ( self , include_part_of = True ) : """Determines and stores all ancestors of each GO term . Parameters include _ part _ of : bool , optional Whether to include ` ` part _ of ` ` relations in determining ancestors . Returns None"""
def get_all_ancestors ( term ) : ancestors = set ( ) for id_ in term . is_a : ancestors . add ( id_ ) ancestors . update ( get_all_ancestors ( self . terms [ id_ ] ) ) if include_part_of : for id_ in term . part_of : ancestors . add ( id_ ) ancestors . update ...
def cleanup_logger ( self ) : """Clean up logger to close out file handles . After this is called , writing to self . log will get logs ending up getting discarded ."""
self . log_handler . close ( ) self . log . removeHandler ( self . log_handler )
def get_terms ( self , kwargs ) : """Checks URL parameters for slug and / or version to pull the right TermsAndConditions object"""
slug = kwargs . get ( "slug" ) version = kwargs . get ( "version" ) if slug and version : terms = [ TermsAndConditions . objects . filter ( slug = slug , version_number = version ) . latest ( 'date_active' ) ] elif slug : terms = [ TermsAndConditions . get_active ( slug ) ] else : # Return a list of not agreed ...
def get_dataset_key ( self , key , ** kwargs ) : """Get the fully qualified ` DatasetID ` matching ` key ` . See ` satpy . readers . get _ key ` for more information about kwargs ."""
return get_key ( key , self . ids . keys ( ) , ** kwargs )
def compute_freq_cross ( self , csd , asd , output = 'coherence' ) : """Compute cross - spectrum , gain , phase shift and / or coherence . Parameters csd : list of dict with ' data ' key as instance of ChanFreq cross - spectral density , one channel asd : list of dict with ' data ' key as instance of ChanFr...
if output == 'coherence' : coh_list = [ ] for i in range ( len ( csd ) ) : dat = ChanFreq ( ) dat . data = empty ( 1 , dtype = 'O' ) dat . data [ 0 ] = empty ( ( 1 , csd [ i ] [ 'data' ] . number_of ( 'freq' ) [ 0 ] ) , dtype = 'f' ) dat . axis [ 'freq' ] = empty ( 1 , dtype = 'O...
def _remove_observer ( self , signal , observer ) : """Remove an observer to a valid signal . Parameters signal : str a valid signal . observer : @ func an obervation function to be removed ."""
if observer in self . _observers [ signal ] : self . _observers [ signal ] . remove ( observer )
def get_executions ( self , ** kwargs ) : """Retrieve the executions related to the current service . . . versionadded : : 1.13 : param kwargs : ( optional ) additional search keyword arguments to limit the search even further . : type kwargs : dict : return : list of ServiceExecutions associated to the cur...
return self . _client . service_executions ( service = self . id , scope = self . scope_id , ** kwargs )
def chpl_type_name ( self ) : """Returns iterator or method or ' ' depending on object type ."""
if not self . objtype . endswith ( 'method' ) : return '' elif self . objtype . startswith ( 'iter' ) : return 'iterator' elif self . objtype == 'method' : return 'method' else : return ''
def download_file ( filename : str ) : """downloads the specified project file if it exists"""
project = cd . project . get_internal_project ( ) source_directory = project . source_directory if project else None if not filename or not project or not source_directory : return '' , 204 path = os . path . realpath ( os . path . join ( source_directory , '..' , '__cauldron_downloads' , filename ) ) if not os . p...
def search_tags ( self , series_search_text = None , response_type = None , params = None ) : """Function to request the FRED tags for a series search . ` < https : / / research . stlouisfed . org / docs / api / fred / series _ search _ tags . html > ` _ : arg str series _ search _ text : The words to match aga...
path = '/series/search/tags?' params [ 'series_search_text' ] = series_search_text response_type = response_type if response_type else self . response_type if response_type != 'xml' : params [ 'file_type' ] = 'json' response = _get_request ( self . url_root , self . api_key , path , response_type , params , self . ...
def getargvalues ( frame ) : """Get information about arguments passed into a particular frame . A tuple of four things is returned : ( args , varargs , varkw , locals ) . ' args ' is a list of the argument names ( it may contain nested lists ) . ' varargs ' and ' varkw ' are the names of the * and * * argume...
args , varargs , varkw = getargs ( frame . f_code ) return args , varargs , varkw , frame . f_locals
def get_user ( self , screen_name ) : """Method to perform the usufy searches . : param screen _ name : nickname to be searched . : return : User ."""
# Connecting to the API api = self . _connectToAPI ( ) # Verifying the limits of the API self . _rate_limit_status ( api = api , mode = "get_user" ) aux = [ ] try : user = api . get_user ( screen_name ) # Iterate through the results using user . _ json aux . append ( user . _json ) except tweepy . error . T...
def load ( file = '/etc/pf.conf' , noop = False ) : '''Load a ruleset from the specific file , overwriting the currently loaded ruleset . file : Full path to the file containing the ruleset . noop : Don ' t actually load the rules , just parse them . CLI example : . . code - block : : bash salt ' * ' ...
# We cannot precisely determine if loading the ruleset implied # any changes so assume it always does . ret = { 'changes' : True } cmd = [ 'pfctl' , '-f' , file ] if noop : ret [ 'changes' ] = False cmd . append ( '-n' ) result = __salt__ [ 'cmd.run_all' ] ( cmd , output_loglevel = 'trace' , python_shell = Fals...
def check_item_type_uniqueness ( tag , previous_tags ) : """Check the uniqueness of the ' item type ' for an object ."""
fail = False # If the tag is being created . . . if not tag . id : # . . . and the new item type is different from previous item types ( for # example , different from the first of them ) , fail fail = previous_tags and tag . item_type != previous_tags [ 0 ] . item_type # If the tag is being modifying . . . else : ...
def openParametersDialog ( params , title = None ) : '''Opens a dialog to enter parameters . Parameters are passed as a list of Parameter objects Returns a dict with param names as keys and param values as values Returns None if the dialog was cancelled'''
QApplication . setOverrideCursor ( QCursor ( Qt . ArrowCursor ) ) dlg = ParametersDialog ( params , title ) dlg . exec_ ( ) QApplication . restoreOverrideCursor ( ) return dlg . values
def add_func ( self , function , outputs = None , weight = None , inputs_kwargs = False , inputs_defaults = False , filters = None , input_domain = None , await_domain = None , await_result = None , inp_weight = None , out_weight = None , description = None , inputs = None , function_id = None , ** kwargs ) : """Ad...
kwargs . update ( _call_kw ( locals ( ) ) ) self . deferred . append ( ( 'add_func' , kwargs ) ) return self
def tagfunc ( nargs = None , ndefs = None , nouts = None ) : """decorate of tagged function"""
def wrapper ( f ) : return wraps ( f ) ( FunctionWithTag ( f , nargs = nargs , nouts = nouts , ndefs = ndefs ) ) return wrapper
def _nonzero_intersection ( m , m_hat ) : """Count the number of nonzeros in and between m and m _ hat . Returns m _ nnz : number of nonzeros in m ( w / o diagonal ) m _ hat _ nnz : number of nonzeros in m _ hat ( w / o diagonal ) intersection _ nnz : number of nonzeros in intersection of m / m _ hat ( w ...
n_features , _ = m . shape m_no_diag = m . copy ( ) m_no_diag [ np . diag_indices ( n_features ) ] = 0 m_hat_no_diag = m_hat . copy ( ) m_hat_no_diag [ np . diag_indices ( n_features ) ] = 0 m_hat_nnz = len ( np . nonzero ( m_hat_no_diag . flat ) [ 0 ] ) m_nnz = len ( np . nonzero ( m_no_diag . flat ) [ 0 ] ) intersect...
def list_all_free_item_coupons ( cls , ** kwargs ) : """List FreeItemCoupons Return a list of FreeItemCoupons This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . list _ all _ free _ item _ coupons ( async = True ) >...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _list_all_free_item_coupons_with_http_info ( ** kwargs ) else : ( data ) = cls . _list_all_free_item_coupons_with_http_info ( ** kwargs ) return data
def pre_render ( self ) : """Last things to do before rendering"""
self . add_styles ( ) self . add_scripts ( ) self . root . set ( 'viewBox' , '0 0 %d %d' % ( self . graph . width , self . graph . height ) ) if self . graph . explicit_size : self . root . set ( 'width' , str ( self . graph . width ) ) self . root . set ( 'height' , str ( self . graph . height ) )
def get_and_union_features ( features ) : """Get and combine features in a : class : ` FeatureUnion ` . Args : features ( str or List [ str ] , ` ` Features ` ` or List [ ` ` Features ` ` ] , or List [ Tuple [ str , ` ` Features ` ` ] ] ) : One or more features to be used to transform blocks into a matrix of ...
if not features : raise ValueError ( 'invalid `features`: may not be null' ) if isinstance ( features , ( list , tuple ) ) : if isinstance ( features [ 0 ] , tuple ) : return FeatureUnion ( features ) elif isinstance ( features [ 0 ] , string_ ) : return FeatureUnion ( [ ( feature , get_feat...
async def dataSources ( loop = None , executor = None ) : """Returns a dictionary mapping available DSNs to their descriptions . : param loop : asyncio compatible event loop : param executor : instance of custom ThreadPoolExecutor , if not supplied default executor will be used : return dict : mapping of ds...
loop = loop or asyncio . get_event_loop ( ) sources = await loop . run_in_executor ( executor , _dataSources ) return sources
def get_channelstate_closing ( chain_state : ChainState , payment_network_id : PaymentNetworkID , token_address : TokenAddress , ) -> List [ NettingChannelState ] : """Return the state of closing channels in a token network ."""
return get_channelstate_filter ( chain_state , payment_network_id , token_address , lambda channel_state : channel . get_status ( channel_state ) == CHANNEL_STATE_CLOSING , )
def deleted_user_delete ( self , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / users # permanently - delete - user"
api_path = "/api/v2/deleted_users/{id}.json" api_path = api_path . format ( id = id ) return self . call ( api_path , method = "DELETE" , ** kwargs )
def create_application ( self , full_layout = True ) : """makes the application object and the buffers"""
layout_manager = LayoutManager ( self ) if full_layout : layout = layout_manager . create_layout ( ExampleLexer , ToolbarLexer ) else : layout = layout_manager . create_tutorial_layout ( ) buffers = { DEFAULT_BUFFER : Buffer ( is_multiline = True ) , 'description' : Buffer ( is_multiline = True , read_only = Tr...
def make_uhs ( hmap , info ) : """Make Uniform Hazard Spectra curves for each location . : param hmap : array of shape ( N , M , P ) : param info : a dictionary with keys poes , imtls , uhs _ dt : returns : a composite array containing uniform hazard spectra"""
uhs = numpy . zeros ( len ( hmap ) , info [ 'uhs_dt' ] ) for p , poe in enumerate ( info [ 'poes' ] ) : for m , imt in enumerate ( info [ 'imtls' ] ) : if imt . startswith ( ( 'PGA' , 'SA' ) ) : uhs [ str ( poe ) ] [ imt ] = hmap [ : , m , p ] return uhs
def _convert_xml_to_queue_messages ( response , decode_function , require_encryption , key_encryption_key , resolver , content = None ) : '''< ? xml version = " 1.0 " encoding = " utf - 8 " ? > < QueueMessagesList > < QueueMessage > < MessageId > string - message - id < / MessageId > < InsertionTime > inser...
if response is None or response . body is None : return None messages = list ( ) list_element = ETree . fromstring ( response . body ) for message_element in list_element . findall ( 'QueueMessage' ) : message = QueueMessage ( ) message . id = message_element . findtext ( 'MessageId' ) dequeue_count = m...
def divergence ( u , v , dx , dy ) : r"""Calculate the horizontal divergence of the horizontal wind . Parameters u : ( M , N ) ndarray x component of the wind v : ( M , N ) ndarray y component of the wind dx : float or ndarray The grid spacing ( s ) in the x - direction . If an array , there should be...
dudx = first_derivative ( u , delta = dx , axis = - 1 ) dvdy = first_derivative ( v , delta = dy , axis = - 2 ) return dudx + dvdy
def _onInstanceAttribute ( self , name , line , pos , absPosition , level ) : """Memorizes a class instance attribute"""
# Instance attributes may appear in member functions only so we already # have a function on the stack of objects . To get the class object one # more step is required so we - 1 here . attributes = self . objectsStack [ level - 1 ] . instanceAttributes for item in attributes : if item . name == name : retur...
def delete ( self , method , uri , params = None , data = None , headers = None , auth = None , timeout = None , allow_redirects = False ) : """Delete a resource ."""
response = self . request ( method , uri , params = params , data = data , headers = headers , auth = auth , timeout = timeout , allow_redirects = allow_redirects , ) if response . status_code < 200 or response . status_code >= 300 : raise self . exception ( method , uri , response , 'Unable to delete record' ) ret...
def execute_command ( self , command , tab = None ) : # TODO DBUS _ ONLY """Execute the ` command ' in the ` tab ' . If tab is None , the command will be executed in the currently selected tab . Command should end with ' \n ' , otherwise it will be appended to the string ."""
# TODO CONTEXTMENU this has to be rewriten and only serves the # dbus interface , maybe this should be moved to dbusinterface . py if not self . get_notebook ( ) . has_page ( ) : self . add_tab ( ) if command [ - 1 ] != '\n' : command += '\n' terminal = self . get_notebook ( ) . get_current_terminal ( ) termina...
def has_activity ( graph : BELGraph , node : BaseEntity ) -> bool : """Return true if over any of the node ' s edges , it has a molecular activity ."""
return _node_has_modifier ( graph , node , ACTIVITY )
def get_state_tuple ( state , state_m = None ) : """Generates a tuple that holds the state as yaml - strings and its meta data in a dictionary . The tuple consists of : [0 ] json _ str for state , [1 ] dict of child _ state tuples , [2 ] dict of model _ meta - data of self and elements [3 ] path of state ...
state_str = json . dumps ( state , cls = JSONObjectEncoder , indent = 4 , check_circular = False , sort_keys = True ) state_tuples_dict = { } if isinstance ( state , ContainerState ) : # print ( state . states , " \ n " ) for child_state_id , child_state in state . states . items ( ) : # print ( " child _ state : %...
def init_app ( self , app ) : """Do setup that requires a Flask app . : param app : The application to initialize . : type app : Flask"""
secrets = self . load_secrets ( app ) self . client_secrets = list ( secrets . values ( ) ) [ 0 ] secrets_cache = DummySecretsCache ( secrets ) # Set some default configuration options app . config . setdefault ( 'OIDC_SCOPES' , [ 'openid' , 'email' ] ) app . config . setdefault ( 'OIDC_GOOGLE_APPS_DOMAIN' , None ) app...
def _create_validate_config ( vrn_file , rm_file , rm_interval_file , base_dir , data ) : """Create a bcbio . variation configuration input for validation ."""
ref_call = { "file" : str ( rm_file ) , "name" : "ref" , "type" : "grading-ref" , "fix-sample-header" : True , "remove-refcalls" : True } a_intervals = get_analysis_intervals ( data , vrn_file , base_dir ) if a_intervals : a_intervals = shared . remove_lcr_regions ( a_intervals , [ data ] ) if rm_interval_file : ...
def main ( ) : '''main routine'''
# Load Azure app defaults try : with open ( 'azurermconfig.json' ) as config_file : config_data = json . load ( config_file ) except FileNotFoundError : sys . exit ( 'Error: Expecting azurermconfig.json in current folder' ) tenant_id = config_data [ 'tenantId' ] app_id = config_data [ 'appId' ] app_secr...
def cut_range ( string ) : """A custom argparse ' type ' to deal with sequences ranges such as 5:500. Returns a 0 - based slice corresponding to the selection defined by the slice"""
value_range = string . split ( ':' ) if len ( value_range ) == 1 : start = int ( value_range [ 0 ] ) stop = start elif len ( value_range ) == 2 : start , stop = tuple ( int ( i ) if i else None for i in value_range ) else : msg = "{0} is not a valid, 1-indexed range." . format ( string ) raise argpa...
def definition_to_json ( source ) : """Convert a bytecode . yaml file into a prepared bytecode . json . Jawa internally uses a YAML file to define all bytecode opcodes , operands , runtime exceptions , default transforms , etc . . . However since JSON is available in the python stdlib and YAML is not , we p...
try : import yaml except ImportError : click . echo ( 'The pyyaml module could not be found and is required' ' to use this command.' , err = True ) return y = yaml . load ( source ) for k , v in y . items ( ) : # We guarantee some keys should always exist to make life easier for # developers . v . setde...
def reset_logging_framework ( ) : """After fork , ensure any logging . Handler locks are recreated , as a variety of threads in the parent may have been using the logging package at the moment of fork . It is not possible to solve this problem in general ; see https : / / github . com / dw / mitogen / issue...
logging . _lock = threading . RLock ( ) # The root logger does not appear in the loggerDict . for name in [ None ] + list ( logging . Logger . manager . loggerDict ) : for handler in logging . getLogger ( name ) . handlers : handler . createLock ( ) root = logging . getLogger ( ) root . handlers = [ handler...
def _ctype_dict ( param_dict ) : """Returns ctype arrays for keys and values ( converted to strings ) in a dictionary"""
assert ( isinstance ( param_dict , dict ) ) , "unexpected type for param_dict: " + str ( type ( param_dict ) ) c_keys = c_array ( ctypes . c_char_p , [ c_str ( k ) for k in param_dict . keys ( ) ] ) c_vals = c_array ( ctypes . c_char_p , [ c_str ( str ( v ) ) for v in param_dict . values ( ) ] ) return ( c_keys , c_val...
def analyzeParameters ( expName , suite ) : """Analyze the impact of each list parameter in this experiment"""
print ( "\n================" , expName , "=====================" ) try : expParams = suite . get_params ( expName ) pprint . pprint ( expParams ) for p in [ "boost_strength" , "k" , "learning_rate" , "weight_sparsity" , "k_inference_factor" , "boost_strength_factor" , "c1_out_channels" , "c1_k" , "learning_...
def used_in_func ( statement : str , filename : str = '<string>' , mode : str = 'exec' ) : '''Parse a Python statement and analyze the symbols used . The result will be used to determine what variables a step depends upon .'''
try : return get_used_in_func ( ast . parse ( statement , filename , mode ) ) except Exception as e : raise RuntimeError ( f'Failed to parse statement: {statement} {e}' )
def send_auto ( self , payload , tries = 1 , timeout = 60 ) : '''Detect the encryption type based on the payload'''
enc = payload . get ( 'enc' , 'clear' ) load = payload . get ( 'load' , { } ) return self . send ( enc , load , tries , timeout )
def get ( self , addresses ) : """Returns the value in this context , or None , for each address in addresses . Useful for gets on the context manager . Args : addresses ( list of str ) : The addresses to return values for , if within this context . Returns : results ( list of bytes ) : The values in st...
with self . _lock : results = [ ] for add in addresses : self . validate_read ( add ) results . append ( self . _get ( add ) ) return results
def idngram2stats ( input_file , output_file , n = 3 , fof_size = 50 , verbosity = 2 , ascii_input = False ) : """Lists the frequency - of - frequencies for each of the 2 - grams , . . . , n - grams , which can enable the user to choose appropriate cut - offs , and to specify appropriate memory requirements with th...
cmd = [ 'idngram2stats' ] if n : cmd . extend ( [ '-n' , n ] ) if fof_size : cmd . extend ( [ '-fof_size' ] , fof_size ) if verbosity : cmd . extend ( [ '-verbosity' ] , verbosity ) if ascii_input : cmd . append ( [ '-ascii_input' ] ) # Ensure that every parameter is of type ' str ' cmd = [ str ( x ) fo...
def retrieve_styles ( self , asset_url_path ) : """Get style URLs from the source HTML page and specified cached asset base URL ."""
if not asset_url_path . endswith ( '/' ) : asset_url_path += '/' self . style_urls . extend ( self . _get_style_urls ( asset_url_path ) )
def start ( self , phone = lambda : input ( 'Please enter your phone (or bot token): ' ) , password = lambda : getpass . getpass ( 'Please enter your password: ' ) , * , bot_token = None , force_sms = False , code_callback = None , first_name = 'New User' , last_name = '' , max_attempts = 3 ) : """Convenience metho...
if code_callback is None : def code_callback ( ) : return input ( 'Please enter the code you received: ' ) elif not callable ( code_callback ) : raise ValueError ( 'The code_callback parameter needs to be a callable ' 'function that returns the code you received by Telegram.' ) if not phone and not bot_...
def create_project_transfer ( self , project_id , to_user_ids ) : """Send POST request to initiate transfer of a project to the specified user ids : param project _ id : str uuid of the project : param to _ users : list of user uuids to receive the project : return : requests . Response containing the success...
data = { "to_users[][id]" : to_user_ids , } return self . _post ( "/projects/" + project_id + "/transfers" , data , content_type = ContentType . form )
def get_op_statistic ( self , name ) : """Get the : class : ` ~ pywbem . OperationStatistic ` object for an operation name or create a new object if an object for that name does not exist . Parameters : name ( string ) : Name of the operation . Returns : : class : ` ~ pywbem . OperationStatistic ` : The...
if not self . enabled : return self . _disabled_stats if name not in self . _op_stats : self . _op_stats [ name ] = OperationStatistic ( self , name ) return self . _op_stats [ name ]
def to_iso8601 ( dt , tz = None ) : """Returns an ISO - 8601 representation of a given datetime instance . > > > to _ iso8601 ( datetime . datetime . now ( ) ) '2014-10-01T23:21:33.718508Z ' : param dt : a : class : ` ~ datetime . datetime ` instance : param tz : a : class : ` ~ datetime . tzinfo ` to use ;...
if tz is not None : dt = dt . replace ( tzinfo = tz ) iso8601 = dt . isoformat ( ) # Naive datetime objects usually don ' t have info about timezone . # Let ' s assume it ' s UTC and add Z to the end . if re . match ( r'.*(Z|[+-]\d{2}:\d{2})$' , iso8601 ) is None : iso8601 += 'Z' return iso8601
def github_authenticated ( cls , func ) : """Does user authentication , creates SSH keys if needed and injects " _ user " attribute into class / object bound to the decorated function . Don ' t call any other methods of this class manually , this should be everything you need ."""
def inner ( func_cls , * args , ** kwargs ) : if not cls . _gh_module : logger . warning ( 'PyGithub not installed, skipping Github auth procedures.' ) elif not func_cls . _user : # authenticate user , possibly also creating authentication for future use login = kwargs [ 'login' ] . encode ( uti...
def _align_backtrack ( fastq_file , pair_file , ref_file , out_file , names , rg_info , data ) : """Perform a BWA alignment using ' aln ' backtrack algorithm ."""
bwa = config_utils . get_program ( "bwa" , data [ "config" ] ) config = data [ "config" ] sai1_file = "%s_1.sai" % os . path . splitext ( out_file ) [ 0 ] sai2_file = "%s_2.sai" % os . path . splitext ( out_file ) [ 0 ] if pair_file else "" if not utils . file_exists ( sai1_file ) : with file_transaction ( data , s...
def create_subtask ( client , task_id , title , completed = False ) : '''Creates a subtask with the given title under the task with the given ID'''
_check_title_length ( title , client . api ) data = { 'task_id' : int ( task_id ) if task_id else None , 'title' : title , 'completed' : completed , } data = { key : value for key , value in data . items ( ) if value is not None } response = client . authenticated_request ( client . api . Endpoints . SUBTASKS , 'POST' ...
def _spoken_representation_L1 ( lst_lst_char ) : """> > > lst = [ [ ' M ' , ' O ' , ' R ' , ' S ' , ' E ' ] , [ ' C ' , ' O ' , ' D ' , ' E ' ] ] > > > _ spoken _ representation _ L1 ( lst ) ' M O R S E C O D E ' > > > lst = [ [ ] , [ ' M ' , ' O ' , ' R ' , ' S ' , ' E ' ] , [ ' C ' , ' O ' , ' D ' , ' E ' ]...
s = '' inter_char = ' ' inter_word = inter_char * 9 for i , word in enumerate ( lst_lst_char ) : if i >= 1 : s += inter_word for j , c in enumerate ( word ) : if j != 0 : s += inter_char s += _char_to_string_morse ( c ) return s
def _process_cities_file ( self , file , city_country_mapping ) : """Iterate over cities info and extract useful data"""
data = { 'all_regions' : list ( ) , 'regions' : list ( ) , 'cities' : list ( ) , 'city_region_mapping' : dict ( ) } allowed_countries = settings . IPGEOBASE_ALLOWED_COUNTRIES for geo_info in self . _line_to_dict ( file , field_names = settings . IPGEOBASE_CITIES_FIELDS ) : country_code = self . _get_country_code_fo...
def get_buffers_of_type ( self , t ) : """returns currently open buffers for a given subclass of : class : ` ~ alot . buffers . Buffer ` . : param t : Buffer class : type t : alot . buffers . Buffer : rtype : list"""
return [ x for x in self . buffers if isinstance ( x , t ) ]
def generate_password ( self ) -> list : """Generate a list of random characters ."""
characterset = self . _get_password_characters ( ) if ( self . passwordlen is None or not characterset ) : raise ValueError ( "Can't generate password: character set is " "empty or passwordlen isn't set" ) password = [ ] for _ in range ( 0 , self . passwordlen ) : password . append ( randchoice ( characterset )...
def _evaluate ( x , y , weights ) : '''get the parameters of the , needed by ' function ' through curve fitting'''
i = _validI ( x , y , weights ) xx = x [ i ] y = y [ i ] try : fitParams = _fit ( xx , y ) # bound noise fn to min defined y value : minY = function ( xx [ 0 ] , * fitParams ) fitParams = np . insert ( fitParams , 0 , minY ) fn = lambda x , minY = minY : boundedFunction ( x , * fitParams ) except Ru...
def date_this_year ( self , before_today = True , after_today = False ) : """Gets a Date object for the current year . : param before _ today : include days in current year before today : param after _ today : include days in current year after today : example Date ( ' 2012-04-04 ' ) : return Date"""
today = date . today ( ) this_year_start = today . replace ( month = 1 , day = 1 ) next_year_start = date ( today . year + 1 , 1 , 1 ) if before_today and after_today : return self . date_between_dates ( this_year_start , next_year_start ) elif not before_today and after_today : return self . date_between_dates...
def is_file_ignored ( opts , fname ) : '''If file _ ignore _ regex or file _ ignore _ glob were given in config , compare the given file path against all of them and return True on the first match .'''
if opts [ 'file_ignore_regex' ] : for regex in opts [ 'file_ignore_regex' ] : if re . search ( regex , fname ) : log . debug ( 'File matching file_ignore_regex. Skipping: %s' , fname ) return True if opts [ 'file_ignore_glob' ] : for glob in opts [ 'file_ignore_glob' ] : ...
def issue_command ( self , command , args = None , dry_run = False , comment = None ) : """Issue the given command : param str command : Either a fully - qualified XTCE name or an alias in the format ` ` NAMESPACE / NAME ` ` . : param dict args : named arguments ( if the command requires these ) : param boo...
req = rest_pb2 . IssueCommandRequest ( ) req . sequenceNumber = SequenceGenerator . next ( ) req . origin = socket . gethostname ( ) req . dryRun = dry_run if comment : req . comment = comment if args : for key in args : assignment = req . assignment . add ( ) assignment . name = key ass...
def lwd ( self , astr_startPath , ** kwargs ) : """Return the cwd in treeRecurse compatible format . : return : Return the cwd in treeRecurse compatible format ."""
if self . cd ( astr_startPath ) [ 'status' ] : self . l_lwd . append ( self . cwd ( ) ) return { 'status' : True , 'cwd' : self . cwd ( ) }
def get_output_original ( self ) : """Build the output the original way . Requires no third party libraries ."""
with open ( self . file , "r" ) as f : temp = float ( f . read ( ) . strip ( ) ) / 1000 if self . dynamic_color : perc = int ( self . percentage ( int ( temp ) , self . alert_temp ) ) if ( perc > 99 ) : perc = 99 color = self . colors [ perc ] else : color = self . color if temp < self . ale...
def get_package_data ( name , extlist ) : """Return data files for package * name * with extensions in * extlist *"""
flist = [ ] # Workaround to replace os . path . relpath ( not available until Python 2.6 ) : offset = len ( name ) + len ( os . pathsep ) for dirpath , _dirnames , filenames in os . walk ( name ) : for fname in filenames : if not fname . startswith ( '.' ) and osp . splitext ( fname ) [ 1 ] in extlist : ...
def cleanup_codra_edus ( self ) : """Remove leading / trailing ' _ ! ' from CODRA EDUs and unescape its double quotes ."""
for leafpos in self . tree . treepositions ( 'leaves' ) : edu_str = self . tree [ leafpos ] edu_str = EDU_START_RE . sub ( "" , edu_str ) edu_str = TRIPLE_ESCAPE_RE . sub ( '"' , edu_str ) edu_str = EDU_END_RE . sub ( "" , edu_str ) self . tree [ leafpos ] = edu_str
def drop_unused_terms ( self ) : '''Returns PriorFactory'''
self . term_doc_mat = self . term_doc_mat . remove_terms ( set ( self . term_doc_mat . get_terms ( ) ) - set ( self . priors . index ) ) self . _reindex_priors ( ) return self
def get_self ( self ) : """GetSelf . Read identity of the home tenant request user . : rtype : : class : ` < IdentitySelf > < azure . devops . v5_0 . identity . models . IdentitySelf > `"""
response = self . _send ( http_method = 'GET' , location_id = '4bb02b5b-c120-4be2-b68e-21f7c50a4b82' , version = '5.0' ) return self . _deserialize ( 'IdentitySelf' , response )
def default ( self , obj ) : # pylint : disable = method - hidden """Use the default behavior unless the object to be encoded has a ` strftime ` attribute ."""
if hasattr ( obj , 'strftime' ) : return obj . strftime ( "%Y-%m-%dT%H:%M:%SZ" ) elif hasattr ( obj , 'get_public_dict' ) : return obj . get_public_dict ( ) else : return json . JSONEncoder . default ( self , obj )
def transform ( odtfile , debug = False , parsable = False , outputdir = None ) : """Given an ODT file this returns a tuple containing the cnxml , a dictionary of filename - > data , and a list of errors"""
# Store mapping of images extracted from the ODT file ( and their bits ) images = { } # Log of Errors and Warnings generated # For example , the text produced by XSLT should be : # { ' level ' : ' WARNING ' , # ' msg ' : ' Headings without text between them are not allowed ' , # ' id ' : ' import - auto - id2376 ' } # ...
def download_file ( url , data_path = '.' , filename = None , size = None , chunk_size = 4096 , verbose = True ) : """Uses stream = True and a reasonable chunk size to be able to download large ( GB ) files over https"""
if filename is None : filename = dropbox_basename ( url ) file_path = os . path . join ( data_path , filename ) if url . endswith ( '?dl=0' ) : url = url [ : - 1 ] + '1' # noninteractive download if verbose : tqdm_prog = tqdm print ( 'requesting URL: {}' . format ( url ) ) else : tqdm_prog = no_...
def write_transparency ( selection ) : """writes transparency as rgba to ~ / . Xresources"""
global themefile , transparency , prefix if themefile == "" : return lines = themefile . split ( '\n' ) for line in lines : if 'background' in line . lower ( ) : try : background = line . split ( ':' ) [ 1 ] . replace ( ' ' , '' ) background = background . replace ( '\t' , '' ) ...
def _read_lnk ( tokens ) : """Read and return a tuple of the pred ' s lnk type and lnk value , if a pred lnk is specified ."""
# < FROM : TO > or < FROM # TO > or < TOK . . . > or < @ EDGE > lnk = None if tokens [ 0 ] == '<' : tokens . popleft ( ) # we just checked this is a left angle if tokens [ 0 ] == '>' : pass # empty < > brackets the same as no lnk specified # edge lnk : [ ' @ ' , EDGE , . . . ] elif t...
def authenticate ( self , credentials ) : """Log in to the server and store these credentials in ` authset ` . Can raise ConnectionFailure or OperationFailure . : Parameters : - ` credentials ` : A MongoCredential ."""
auth . authenticate ( credentials , self ) self . authset . add ( credentials )
def network_interface_create_or_update ( name , ip_configurations , subnet , virtual_network , resource_group , ** kwargs ) : '''. . versionadded : : 2019.2.0 Create or update a network interface within a specified resource group . : param name : The name of the network interface to create . : param ip _ conf...
if 'location' not in kwargs : rg_props = __salt__ [ 'azurearm_resource.resource_group_get' ] ( resource_group , ** kwargs ) if 'error' in rg_props : log . error ( 'Unable to determine location from resource group specified.' ) return False kwargs [ 'location' ] = rg_props [ 'location' ] netc...
def install ( cls , handler , fmt , programname = None , style = DEFAULT_FORMAT_STYLE ) : """Install the : class : ` ProgramNameFilter ` ( only if needed ) . : param fmt : The log format string to check for ` ` % ( programname ) ` ` . : param style : One of the characters ` ` % ` ` , ` ` { ` ` or ` ` $ ` ` ( de...
if fmt : parser = FormatStringParser ( style = style ) if not parser . contains_field ( fmt , 'programname' ) : return handler . addFilter ( cls ( programname ) )
def all ( self ) : """Return all entries : rtype : list ( dict )"""
attribute = self . _attr [ 0 ] return self . profile . data . get ( attribute , [ ] )
def to_xml ( self , tag_name = "buyer" ) : '''Returns an XMLi representation of the object . @ param tag _ name : str Tag name @ return : Element'''
for n , v in { "name" : self . name , "address" : self . address } . items ( ) : if is_empty_or_none ( v ) : raise ValueError ( "'%s' attribute cannot be empty or None." % n ) if self . __require_id and is_empty_or_none ( self . identifier ) : raise ValueError ( "identifier attribute cannot be empty or ...
def _fetch_stock_data ( self , stock_list ) : """获取股票信息"""
pool = multiprocessing . pool . ThreadPool ( len ( stock_list ) ) try : res = pool . map ( self . get_stocks_by_range , stock_list ) finally : pool . close ( ) return [ d for d in res if d is not None ]
def get_country ( similar = False , ** kwargs ) : """Get a country for pycountry"""
result_country = None try : if similar : for country in countries : if kwargs . get ( 'name' , '' ) in country . name : result_country = country break else : result_country = countries . get ( ** kwargs ) except Exception as ex : msg = ( 'Country n...
def init_from_datastore ( self ) : """Initializes batches by reading from the datastore ."""
self . _data = { } for entity in self . _datastore_client . query_fetch ( kind = self . _entity_kind_batches ) : batch_id = entity . key . flat_path [ - 1 ] self . _data [ batch_id ] = dict ( entity ) self . _data [ batch_id ] [ 'images' ] = { } for entity in self . _datastore_client . query_fetch ( kind = ...
def get_move_data ( move ) : """Return the index number for the given move name . Check moves . json in the same directory ."""
srcpath = path . dirname ( __file__ ) try : f = open ( path . join ( srcpath , 'moves.json' ) , 'r' ) except IOError : get_moves ( ) f = open ( path . join ( srcpath , 'moves.json' ) , 'r' ) finally : with f : return json . load ( f ) [ move ]
def set_readable_web_pdf ( self , value ) : '''setter'''
if isinstance ( value , ReadableWebPDF ) is False and value is not None : raise TypeError ( "The type of __readable_web_pdf must be ReadableWebPDF." ) self . __readable_web_pdf = value
def getConfiguration ( self ) : """Get the current configuration number for this device ."""
configuration = c_int ( ) mayRaiseUSBError ( libusb1 . libusb_get_configuration ( self . __handle , byref ( configuration ) , ) ) return configuration . value
def svg_data_uri ( self , xmldecl = False , encode_minimal = False , omit_charset = False , nl = False , ** kw ) : """Converts the QR Code into a SVG data URI . The XML declaration is omitted by default ( set ` ` xmldecl ` ` to ` ` True ` ` to enable it ) , further the newline is omitted by default ( set ` ` nl...
return writers . as_svg_data_uri ( self . matrix , self . _version , xmldecl = xmldecl , nl = nl , encode_minimal = encode_minimal , omit_charset = omit_charset , ** kw )
def match_via_correlation ( image , template , raw_tolerance = 1 , normed_tolerance = 0.9 ) : """Matchihng algorithm based on normalised cross correlation . Using this matching prevents false positives occuring for bright patches in the image"""
h , w = image . shape th , tw = template . shape # fft based convolution enables fast matching of large images correlation = fftconvolve ( image , template [ : : - 1 , : : - 1 ] ) # trim the returned image , fftconvolve returns an image of width : ( Temp _ w - 1 ) + Im _ w + ( Temp _ w - 1 ) , likewise height correlati...
def register_button_handler ( self , button_handler , buttons ) : """Register a handler function which will be called when a button is pressed : param button _ handler : A function which will be called when any of the specified buttons are pressed . The function is called with the Button that was pressed as t...
if not isinstance ( buttons , list ) : buttons = [ buttons ] for button in buttons : state = self . buttons . get ( button ) if state is not None : state . button_handlers . append ( button_handler ) def remove ( ) : for button_to_remove in buttons : state_to_remove = self . buttons . ge...
def get_probs ( self , sampler = None , rerun = None , store = True ) : """Get probabilities ."""
if rerun is None : rerun = sampler is not None if self . _probs is not None and not rerun : return self . _probs if sampler is None : sampler = self . vqe . sampler probs = sampler ( self . circuit , range ( self . circuit . n_qubits ) ) if store : self . _probs = probs return probs
def get_next ( self ) : """Get the billing cycle after this one . May return None"""
return BillingCycle . objects . filter ( date_range__gt = self . date_range ) . order_by ( 'date_range' ) . first ( )