idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
14,500 | def _get_origin ( event ) : if event . preferred_origin ( ) is not None : origin = event . preferred_origin ( ) elif len ( event . origins ) > 0 : origin = event . origins [ 0 ] else : raise IndexError ( 'No origin set, cannot constrain' ) return origin | Get the origin of an event . |
14,501 | def read_parameters ( infile = '../parameters/EQcorrscan_parameters.txt' ) : try : import ConfigParser except ImportError : import configparser as ConfigParser import ast f = open ( infile , 'r' ) print ( 'Reading parameters with the following header:' ) for line in f : if line [ 0 ] == '#' : print ( line . rstrip ( '\... | Read the default parameters from file . |
14,502 | def write ( self , outfile = '../parameters/EQcorrscan_parameters.txt' , overwrite = False ) : outpath = os . sep . join ( outfile . split ( os . sep ) [ 0 : - 1 ] ) if len ( outpath ) > 0 and not os . path . isdir ( outpath ) : msg = ' ' . join ( [ os . path . join ( outfile . split ( os . sep ) [ 0 : - 1 ] ) , 'does ... | Function to write the parameters to a file - user readable . |
14,503 | def _check_daylong ( tr ) : if len ( np . nonzero ( tr . data ) [ 0 ] ) < 0.5 * len ( tr . data ) : qual = False else : qual = True return qual | Check the data quality of the daylong file . |
14,504 | def shortproc ( st , lowcut , highcut , filt_order , samp_rate , debug = 0 , parallel = False , num_cores = False , starttime = None , endtime = None , seisan_chan_names = False , fill_gaps = True ) : if isinstance ( st , Trace ) : tracein = True st = Stream ( st ) else : tracein = False if highcut and highcut >= 0.5 *... | Basic function to bandpass and downsample . |
14,505 | def dayproc ( st , lowcut , highcut , filt_order , samp_rate , starttime , debug = 0 , parallel = True , num_cores = False , ignore_length = False , seisan_chan_names = False , fill_gaps = True ) : if isinstance ( st , Trace ) : st = Stream ( st ) tracein = True else : tracein = False if highcut and highcut >= 0.5 * sa... | Wrapper for dayproc to parallel multiple traces in a stream . |
14,506 | def _zero_pad_gaps ( tr , gaps , fill_gaps = True ) : start_in , end_in = ( tr . stats . starttime , tr . stats . endtime ) for gap in gaps : stream = Stream ( ) if gap [ 'starttime' ] > tr . stats . starttime : stream += tr . slice ( tr . stats . starttime , gap [ 'starttime' ] ) . copy ( ) if gap [ 'endtime' ] < tr .... | Replace padded parts of trace with zeros . |
14,507 | def _fill_gaps ( tr ) : tr = tr . split ( ) gaps = tr . get_gaps ( ) tr = tr . detrend ( ) . merge ( fill_value = 0 ) [ 0 ] gaps = [ { 'starttime' : gap [ 4 ] , 'endtime' : gap [ 5 ] } for gap in gaps ] return gaps , tr | Interpolate through gaps and work - out where gaps are . |
14,508 | def find_peaks2_short ( arr , thresh , trig_int , debug = 0 , starttime = False , samp_rate = 1.0 , full_peaks = False ) : if not starttime : starttime = UTCDateTime ( 0 ) image = np . copy ( arr ) image = np . abs ( image ) debug_print ( "Threshold: {0}\tMax: {1}" . format ( thresh , max ( image ) ) , 2 , debug ) imag... | Determine peaks in an array of data above a certain threshold . |
14,509 | def multi_find_peaks ( arr , thresh , trig_int , debug = 0 , starttime = False , samp_rate = 1.0 , parallel = True , full_peaks = False , cores = None ) : peaks = [ ] if not parallel : for sub_arr , arr_thresh in zip ( arr , thresh ) : peaks . append ( find_peaks2_short ( arr = sub_arr , thresh = arr_thresh , trig_int ... | Wrapper for find - peaks for multiple arrays . |
14,510 | def coin_trig ( peaks , stachans , samp_rate , moveout , min_trig , trig_int ) : triggers = [ ] for stachan , _peaks in zip ( stachans , peaks ) : for peak in _peaks : trigger = ( peak [ 1 ] , peak [ 0 ] , '.' . join ( stachan ) ) triggers . append ( trigger ) coincidence_triggers = [ ] for i , master in enumerate ( tr... | Find network coincidence triggers within peaks of detection statistics . |
14,511 | def _finalise_figure ( fig , ** kwargs ) : title = kwargs . get ( "title" ) or None show = kwargs . get ( "show" ) or False save = kwargs . get ( "save" ) or False savefile = kwargs . get ( "savefile" ) or "EQcorrscan_figure.png" return_fig = kwargs . get ( "return_figure" ) or False if title : fig . suptitle ( title )... | Internal function to wrap up a figure . |
14,512 | def chunk_data ( tr , samp_rate , state = 'mean' ) : trout = tr . copy ( ) x = np . arange ( len ( tr . data ) ) y = tr . data chunksize = int ( round ( tr . stats . sampling_rate / samp_rate ) ) numchunks = int ( y . size // chunksize ) ychunks = y [ : chunksize * numchunks ] . reshape ( ( - 1 , chunksize ) ) xchunks ... | Downsample data for plotting . |
14,513 | def xcorr_plot ( template , image , shift = None , cc = None , cc_vec = None , ** kwargs ) : import matplotlib . pyplot as plt if cc is None or shift is None : if not isinstance ( cc_vec , np . ndarray ) : print ( 'Given cc: %s and shift: %s' % ( cc , shift ) ) raise IOError ( 'Must provide either cc_vec, or cc and shi... | Plot a template overlying an image aligned by correlation . |
14,514 | def triple_plot ( cccsum , cccsum_hist , trace , threshold , ** kwargs ) : import matplotlib . pyplot as plt if len ( cccsum ) != len ( trace . data ) : print ( 'cccsum is: ' + str ( len ( cccsum ) ) + ' trace is: ' + str ( len ( trace . data ) ) ) msg = ' ' . join ( [ 'cccsum and trace must have the' , 'same number of... | Plot a seismogram correlogram and histogram . |
14,515 | def peaks_plot ( data , starttime , samp_rate , peaks = [ ( 0 , 0 ) ] , ** kwargs ) : import matplotlib . pyplot as plt npts = len ( data ) t = np . arange ( npts , dtype = np . float32 ) / ( samp_rate * 3600 ) fig = plt . figure ( ) ax1 = fig . add_subplot ( 111 ) ax1 . plot ( t , data , 'k' ) ax1 . scatter ( peaks [ ... | Plot peaks to check that the peak finding routine is running correctly . |
14,516 | def threeD_gridplot ( nodes , ** kwargs ) : from mpl_toolkits . mplot3d import Axes3D import matplotlib . pyplot as plt lats = [ ] longs = [ ] depths = [ ] for node in nodes : lats . append ( float ( node [ 0 ] ) ) longs . append ( float ( node [ 1 ] ) ) depths . append ( float ( node [ 2 ] ) ) fig = plt . figure ( ) a... | Plot in a series of grid points in 3D . |
14,517 | def interev_mag ( times , mags , size = ( 10.5 , 7.5 ) , ** kwargs ) : import matplotlib . pyplot as plt info = [ ( times [ i ] , mags [ i ] ) for i in range ( len ( times ) ) ] info . sort ( key = lambda tup : tup [ 0 ] ) times = [ x [ 0 ] for x in info ] mags = [ x [ 1 ] for x in info ] fig , axes = plt . subplots ( ... | Plot inter - event times against magnitude . |
14,518 | def obspy_3d_plot ( inventory , catalog , size = ( 10.5 , 7.5 ) , ** kwargs ) : nodes = [ ] for ev in catalog : nodes . append ( ( ev . preferred_origin ( ) . latitude , ev . preferred_origin ( ) . longitude , ev . preferred_origin ( ) . depth / 1000 ) ) all_stas = [ ] for net in inventory : for sta in net : if len ( s... | Plot obspy Inventory and obspy Catalog classes in three dimensions . |
14,519 | def threeD_seismplot ( stations , nodes , size = ( 10.5 , 7.5 ) , ** kwargs ) : import matplotlib . pyplot as plt from mpl_toolkits . mplot3d import Axes3D stalats , stalongs , staelevs = zip ( * stations ) evlats , evlongs , evdepths = zip ( * nodes ) _evlongs = [ ] for evlong in evlongs : if evlong < 0 : evlong = flo... | Plot seismicity and stations in a 3D movable zoomable space . |
14,520 | def noise_plot ( signal , noise , normalise = False , ** kwargs ) : import matplotlib . pyplot as plt n_traces = 0 for tr in signal : try : noise . select ( id = tr . id ) [ 0 ] except IndexError : continue n_traces += 1 fig , axes = plt . subplots ( n_traces , 2 , sharex = True ) if len ( signal ) > 1 : axes = axes . ... | Plot signal and noise fourier transforms and the difference . |
14,521 | def spec_trace ( traces , cmap = None , wlen = 0.4 , log = False , trc = 'k' , tralpha = 0.9 , size = ( 10 , 13 ) , fig = None , ** kwargs ) : import matplotlib . pyplot as plt if isinstance ( traces , Stream ) : traces . sort ( [ 'station' , 'channel' ] ) if not fig : fig = plt . figure ( ) for i , tr in enumerate ( t... | Plots seismic data with spectrogram behind . |
14,522 | def _spec_trace ( trace , cmap = None , wlen = 0.4 , log = False , trc = 'k' , tralpha = 0.9 , size = ( 10 , 2.5 ) , axes = None , title = None ) : import matplotlib . pyplot as plt if not axes : fig = plt . figure ( figsize = size ) ax1 = fig . add_subplot ( 111 ) else : ax1 = axes trace . spectrogram ( wlen = wlen , ... | Function to plot a trace over that traces spectrogram . |
14,523 | def subspace_detector_plot ( detector , stachans , size , ** kwargs ) : import matplotlib . pyplot as plt if stachans == 'all' and not detector . multiplex : stachans = detector . stachans elif detector . multiplex : stachans = [ ( 'multi' , ' ' ) ] if np . isinf ( detector . dimension ) : msg = ' ' . join ( [ 'Infinit... | Plotting for the subspace detector class . |
14,524 | def subspace_fc_plot ( detector , stachans , size , ** kwargs ) : import matplotlib . pyplot as plt if stachans == 'all' and not detector . multiplex : stachans = detector . stachans elif detector . multiplex : stachans = [ ( 'multi' , ' ' ) ] pfs = [ ] for x in range ( 1 , len ( stachans ) ) : if len ( stachans ) % x ... | Plot the fractional energy capture of the detector for all events in the design set |
14,525 | def _match_filter_plot ( stream , cccsum , template_names , rawthresh , plotdir , plot_format , i ) : import matplotlib . pyplot as plt plt . ioff ( ) stream_plot = copy . deepcopy ( stream [ 0 ] ) stream_plot = _plotting_decimation ( stream_plot , 10e5 , 4 ) cccsum_plot = Trace ( cccsum ) cccsum_plot . stats . samplin... | Plotting function for match_filter . |
14,526 | def _plotting_decimation ( trace , max_len = 10e5 , decimation_step = 4 ) : trace_len = trace . stats . npts while trace_len > max_len : trace . decimate ( decimation_step ) trace_len = trace . stats . npts return trace | Decimate data until required length reached . |
14,527 | def make_images_responsive ( app , doctree ) : for fig in doctree . traverse ( condition = nodes . figure ) : if 'thumbnail' in fig [ 'classes' ] : continue for img in fig . traverse ( condition = nodes . image ) : img [ 'classes' ] . append ( 'img-responsive' ) | Add Bootstrap img - responsive class to images . |
14,528 | def _manual_overrides ( _cache_date = None ) : log = logging . getLogger ( 'ciu' ) request = requests . get ( "https://raw.githubusercontent.com/brettcannon/" "caniusepython3/master/caniusepython3/overrides.json" ) if request . status_code == 200 : log . info ( "Overrides loaded from GitHub and cached" ) overrides = re... | Read the overrides file . |
14,529 | def supports_py3 ( project_name ) : log = logging . getLogger ( "ciu" ) log . info ( "Checking {} ..." . format ( project_name ) ) request = requests . get ( "https://pypi.org/pypi/{}/json" . format ( project_name ) ) if request . status_code >= 400 : log = logging . getLogger ( "ciu" ) log . warning ( "problem fetchin... | Check with PyPI if a project supports Python 3 . |
14,530 | def check ( requirements_paths = [ ] , metadata = [ ] , projects = [ ] ) : dependencies = [ ] dependencies . extend ( projects_ . projects_from_requirements ( requirements_paths ) ) dependencies . extend ( projects_ . projects_from_metadata ( metadata ) ) dependencies . extend ( projects ) manual_overrides = pypi . man... | Return True if all of the specified dependencies have been ported to Python 3 . |
14,531 | def projects_from_cli ( args ) : description = ( 'Determine if a set of project dependencies will work with ' 'Python 3' ) parser = argparse . ArgumentParser ( description = description ) req_help = 'path(s) to a pip requirements file (e.g. requirements.txt)' parser . add_argument ( '--requirements' , '-r' , nargs = '+... | Take arguments through the CLI can create a list of specified projects . |
14,532 | def message ( blockers ) : if not blockers : encoding = getattr ( sys . stdout , 'encoding' , '' ) if encoding : encoding = encoding . lower ( ) if encoding == 'utf-8' : flair = "\U0001F389 " else : flair = '' return [ flair + 'You have 0 projects blocking you from using Python 3!' ] flattened_blockers = set ( ) for b... | Create a sequence of key messages based on what is blocking . |
14,533 | def pprint_blockers ( blockers ) : pprinted = [ ] for blocker in sorted ( blockers , key = lambda x : tuple ( reversed ( x ) ) ) : buf = [ blocker [ 0 ] ] if len ( blocker ) > 1 : buf . append ( ' (which is blocking ' ) buf . append ( ', which is blocking ' . join ( blocker [ 1 : ] ) ) buf . append ( ')' ) pprinted . a... | Pretty print blockers into a sequence of strings . |
14,534 | def check ( projects ) : log = logging . getLogger ( 'ciu' ) log . info ( '{0} top-level projects to check' . format ( len ( projects ) ) ) print ( 'Finding and checking dependencies ...' ) blockers = dependencies . blockers ( projects ) print ( '' ) for line in message ( blockers ) : print ( line ) print ( '' ) for li... | Check the specified projects for Python 3 compatibility . |
14,535 | def reasons_to_paths ( reasons ) : blockers = set ( reasons . keys ( ) ) - set ( reasons . values ( ) ) paths = set ( ) for blocker in blockers : path = [ blocker ] parent = reasons [ blocker ] while parent : if parent in path : raise CircularDependencyError ( dict ( parent = parent , blocker = blocker , path = path ) ... | Calculate the dependency paths to the reasons of the blockers . |
14,536 | def dependencies ( project_name ) : log = logging . getLogger ( 'ciu' ) log . info ( 'Locating dependencies for {}' . format ( project_name ) ) located = distlib . locators . locate ( project_name , prereleases = True ) if not located : log . warning ( '{0} not found' . format ( project_name ) ) return None return { pa... | Get the dependencies for a project . |
14,537 | def projects_from_requirements ( requirements ) : log = logging . getLogger ( 'ciu' ) valid_reqs = [ ] for requirements_path in requirements : with io . open ( requirements_path ) as file : requirements_text = file . read ( ) requirements_text = re . sub ( r"\\s*" , "" , requirements_text ) requirements_text = re . sub... | Extract the project dependencies from a Requirements specification . |
14,538 | def projects_from_metadata ( metadata ) : projects = [ ] for data in metadata : meta = distlib . metadata . Metadata ( fileobj = io . StringIO ( data ) ) projects . extend ( pypi . just_name ( project ) for project in meta . run_requires ) return frozenset ( map ( packaging . utils . canonicalize_name , projects ) ) | Extract the project dependencies from a metadata spec . |
14,539 | def locateOnScreen ( image , minSearchTime = 0 , ** kwargs ) : start = time . time ( ) while True : try : screenshotIm = screenshot ( region = None ) retVal = locate ( image , screenshotIm , ** kwargs ) try : screenshotIm . fp . close ( ) except AttributeError : pass if retVal or time . time ( ) - start > minSearchTime... | minSearchTime - amount of time in seconds to repeat taking screenshots and trying to locate a match . The default of 0 performs a single search . |
14,540 | def getDetails ( self , ip_address = None ) : raw_details = self . _requestDetails ( ip_address ) raw_details [ 'country_name' ] = self . countries . get ( raw_details . get ( 'country' ) ) raw_details [ 'ip_address' ] = ipaddress . ip_address ( raw_details . get ( 'ip' ) ) raw_details [ 'latitude' ] , raw_details [ 'l... | Get details for specified IP address as a Details object . |
14,541 | def _requestDetails ( self , ip_address = None ) : if ip_address not in self . cache : url = self . API_URL if ip_address : url += '/' + ip_address response = requests . get ( url , headers = self . _get_headers ( ) , ** self . request_options ) if response . status_code == 429 : raise RequestQuotaExceededError ( ) res... | Get IP address data by sending request to IPinfo API . |
14,542 | def _get_headers ( self ) : headers = { 'user-agent' : 'IPinfoClient/Python{version}/1.0' . format ( version = sys . version_info [ 0 ] ) , 'accept' : 'application/json' } if self . access_token : headers [ 'authorization' ] = 'Bearer {}' . format ( self . access_token ) return headers | Built headers for request to IPinfo API . |
14,543 | def _read_country_names ( self , countries_file = None ) : if not countries_file : countries_file = os . path . join ( os . path . dirname ( __file__ ) , self . COUNTRY_FILE_DEFAULT ) with open ( countries_file ) as f : countries_json = f . read ( ) return json . loads ( countries_json ) | Read list of countries from specified country file or default file . |
14,544 | def is_secure_option ( self , section , option ) : if not self . has_section ( section ) : return False if not self . has_option ( section , option ) : return False if ConfigParser . get ( self , section , option ) == self . _secure_placeholder : return True return False | Test an option to see if it is secured or not . |
14,545 | def items ( self , section ) : items = [ ] for k , v in ConfigParser . items ( self , section ) : if self . is_secure_option ( section , k ) : v = self . get ( section , k ) if v == '!!False!!' : v = False items . append ( ( k , v ) ) return items | Get all items for a section . Subclassed to ensure secure items come back with the unencrypted data . |
14,546 | def set ( self , section , option , value ) : if not value : value = '!!False!!' if self . is_secure_option ( section , option ) : self . set_secure ( section , option , value ) else : ConfigParser . set ( self , section , option , value ) | Set an option value . Knows how to set options properly marked as secure . |
14,547 | def set_secure ( self , section , option , value ) : if self . keyring_available : s_option = "%s%s" % ( section , option ) self . _unsaved [ s_option ] = ( 'set' , value ) value = self . _secure_placeholder ConfigParser . set ( self , section , option , value ) | Set an option and mark it as secure . |
14,548 | def get ( self , section , option , * args ) : if self . is_secure_option ( section , option ) and self . keyring_available : s_option = "%s%s" % ( section , option ) if self . _unsaved . get ( s_option , [ '' ] ) [ 0 ] == 'set' : res = self . _unsaved [ s_option ] [ 1 ] else : res = keyring . get_password ( self . key... | Get option value from section . If an option is secure populates the plain text . |
14,549 | def remove_option ( self , section , option ) : if self . is_secure_option ( section , option ) and self . keyring_available : s_option = "%s%s" % ( section , option ) self . _unsaved [ s_option ] = ( 'delete' , None ) ConfigParser . remove_option ( self , section , option ) | Removes the option from ConfigParser as well as the secure storage backend |
14,550 | def encrypt_account ( self , id ) : for key in self . secured_field_names : value = self . parser . get ( id , key ) self . parser . set_secure ( id , key , value ) return self | Make sure that certain fields are encrypted . |
14,551 | def is_encrypted_account ( self , id ) : for key in self . secured_field_names : if not self . parser . is_secure_option ( id , key ) : return False return True | Are all fields for the account id encrypted? |
14,552 | def save ( self ) : with open ( self . file_name , 'w' ) as fp : self . parser . write ( fp ) return self | Save changes to config file |
14,553 | def authenticate ( self , username = None , password = None ) : u = self . username p = self . password if username and password : u = username p = password client = self . client ( ) query = client . authenticated_query ( username = u , password = p ) res = client . post ( query ) ofx = BeautifulSoup ( res , 'lxml' ) ... | Test the authentication credentials |
14,554 | def download ( self , days = 60 ) : days_ago = datetime . datetime . now ( ) - datetime . timedelta ( days = days ) as_of = time . strftime ( "%Y%m%d" , days_ago . timetuple ( ) ) query = self . _download_query ( as_of = as_of ) response = self . institution . client ( ) . post ( query ) return StringIO ( response ) | Downloaded OFX response for the given time range |
14,555 | def combined_download ( accounts , days = 60 ) : client = Client ( institution = None ) out_file = StringIO ( ) out_file . write ( client . header ( ) ) out_file . write ( '<OFX>' ) for a in accounts : ofx = a . download ( days = days ) . read ( ) stripped = ofx . partition ( '<OFX>' ) [ 2 ] . partition ( '</OFX>' ) [ ... | Download OFX files and combine them into one |
14,556 | def bank_account_query ( self , number , date , account_type , bank_id ) : return self . authenticated_query ( self . _bareq ( number , date , account_type , bank_id ) ) | Bank account statement request |
14,557 | def credit_card_account_query ( self , number , date ) : return self . authenticated_query ( self . _ccreq ( number , date ) ) | CC Statement request |
14,558 | def _do_post ( self , query , extra_headers = [ ] ) : i = self . institution logging . debug ( 'posting data to %s' % i . url ) garbage , path = splittype ( i . url ) host , selector = splithost ( path ) h = HTTPSConnection ( host , timeout = 60 ) h . putrequest ( 'POST' , selector , skip_host = True , skip_accept_enco... | Do a POST to the Institution . |
14,559 | def _build_raw_headers ( self , headers : Dict ) -> Tuple : raw_headers = [ ] for k , v in headers . items ( ) : raw_headers . append ( ( k . encode ( 'utf8' ) , v . encode ( 'utf8' ) ) ) return tuple ( raw_headers ) | Convert a dict of headers to a tuple of tuples |
14,560 | async def _request_mock ( self , orig_self : ClientSession , method : str , url : 'Union[URL, str]' , * args : Tuple , ** kwargs : Dict ) -> 'ClientResponse' : url = normalize_url ( merge_params ( url , kwargs . get ( 'params' ) ) ) url_str = str ( url ) for prefix in self . _passthrough : if url_str . startswith ( pre... | Return mocked response object or raise connection error . |
14,561 | def normalize_url ( url : 'Union[URL, str]' ) -> 'URL' : url = URL ( url ) return url . with_query ( urlencode ( sorted ( parse_qsl ( url . query_string ) ) ) ) | Normalize url to make comparisons . |
14,562 | def promote_alert_to_case ( self , alert_id ) : req = self . url + "/api/alert/{}/createCase" . format ( alert_id ) try : return requests . post ( req , headers = { 'Content-Type' : 'application/json' } , proxies = self . proxies , auth = self . auth , verify = self . cert , data = json . dumps ( { } ) ) except request... | This uses the TheHiveAPI to promote an alert to a case |
14,563 | def prepare ( * , operation = 'CREATE' , signers = None , recipients = None , asset = None , metadata = None , inputs = None ) : return prepare_transaction ( operation = operation , signers = signers , recipients = recipients , asset = asset , metadata = metadata , inputs = inputs , ) | Prepares a transaction payload ready to be fulfilled . |
14,564 | def send_async ( self , transaction , headers = None ) : return self . transport . forward_request ( method = 'POST' , path = self . path , json = transaction , params = { 'mode' : 'async' } , headers = headers ) | Submit a transaction to the Federation with the mode async . |
14,565 | def retrieve ( self , txid , headers = None ) : path = self . path + txid return self . transport . forward_request ( method = 'GET' , path = path , headers = None ) | Retrieves the transaction with the given id . |
14,566 | def get ( self , public_key , spent = None , headers = None ) : return self . transport . forward_request ( method = 'GET' , path = self . path , params = { 'public_key' : public_key , 'spent' : spent } , headers = headers , ) | Get transaction outputs by public key . The public_key parameter must be a base58 encoded ed25519 public key associated with transaction output ownership . |
14,567 | def retrieve ( self , block_height , headers = None ) : path = self . path + block_height return self . transport . forward_request ( method = 'GET' , path = path , headers = None ) | Retrieves the block with the given block_height . |
14,568 | def get ( self , * , search , limit = 0 , headers = None ) : return self . transport . forward_request ( method = 'GET' , path = self . path , params = { 'search' : search , 'limit' : limit } , headers = headers ) | Retrieves the assets that match a given text search string . |
14,569 | def prepare_create_transaction ( * , signers , recipients = None , asset = None , metadata = None ) : if not isinstance ( signers , ( list , tuple ) ) : signers = [ signers ] elif isinstance ( signers , tuple ) : signers = list ( signers ) if not recipients : recipients = [ ( signers , 1 ) ] elif not isinstance ( recip... | Prepares a CREATE transaction payload ready to be fulfilled . |
14,570 | def prepare_transfer_transaction ( * , inputs , recipients , asset , metadata = None ) : if not isinstance ( inputs , ( list , tuple ) ) : inputs = ( inputs , ) if not isinstance ( recipients , ( list , tuple ) ) : recipients = [ ( [ recipients ] , 1 ) ] if isinstance ( recipients , tuple ) : recipients = [ ( list ( re... | Prepares a TRANSFER transaction payload ready to be fulfilled . |
14,571 | def fulfill_transaction ( transaction , * , private_keys ) : if not isinstance ( private_keys , ( list , tuple ) ) : private_keys = [ private_keys ] if isinstance ( private_keys , tuple ) : private_keys = list ( private_keys ) transaction_obj = Transaction . from_dict ( transaction ) try : signed_transaction = transact... | Fulfills the given transaction . |
14,572 | def normalize_url ( node ) : if not node : node = DEFAULT_NODE elif '://' not in node : node = '//{}' . format ( node ) parts = urlparse ( node , scheme = 'http' , allow_fragments = False ) port = parts . port if parts . port else _get_default_port ( parts . scheme ) netloc = '{}:{}' . format ( parts . hostname , port ... | Normalizes the given node url |
14,573 | def normalize_node ( node , headers = None ) : headers = { } if headers is None else headers if isinstance ( node , str ) : url = normalize_url ( node ) return { 'endpoint' : url , 'headers' : headers } url = normalize_url ( node [ 'endpoint' ] ) node_headers = node . get ( 'headers' , { } ) return { 'endpoint' : url ,... | Normalizes given node as str or dict with headers |
14,574 | def normalize_nodes ( * nodes , headers = None ) : if not nodes : return ( normalize_node ( DEFAULT_NODE , headers ) , ) normalized_nodes = ( ) for node in nodes : normalized_nodes += ( normalize_node ( node , headers ) , ) return normalized_nodes | Normalizes given dict or array of driver nodes |
14,575 | def request ( self , method , * , path = None , json = None , params = None , headers = None , timeout = None , backoff_cap = None , ** kwargs ) : backoff_timedelta = self . get_backoff_timedelta ( ) if timeout is not None and timeout < backoff_timedelta : raise TimeoutError if backoff_timedelta > 0 : time . sleep ( ba... | Performs an HTTP request with the given parameters . |
14,576 | def pick ( self , connections ) : if len ( connections ) == 1 : return connections [ 0 ] def key ( conn ) : return ( datetime . min if conn . backoff_time is None else conn . backoff_time ) return min ( * connections , key = key ) | Picks a connection with the earliest backoff time . |
14,577 | def forward_request ( self , method , path = None , json = None , params = None , headers = None ) : error_trace = [ ] timeout = self . timeout backoff_cap = NO_TIMEOUT_BACKOFF_CAP if timeout is None else timeout / 2 while timeout is None or timeout > 0 : connection = self . connection_pool . get_connection ( ) start =... | Makes HTTP requests to the configured nodes . |
14,578 | def inputs_valid ( self , outputs = None ) : if self . operation == Transaction . CREATE : return self . _inputs_valid ( [ 'dummyvalue' for _ in self . inputs ] ) elif self . operation == Transaction . TRANSFER : return self . _inputs_valid ( [ output . fulfillment . condition_uri for output in outputs ] ) else : allow... | Validates the Inputs in the Transaction against given Outputs . |
14,579 | def _input_valid ( input_ , operation , message , output_condition_uri = None ) : ccffill = input_ . fulfillment try : parsed_ffill = Fulfillment . from_uri ( ccffill . serialize_uri ( ) ) except ( TypeError , ValueError , ParsingError , ASN1DecodeError , ASN1EncodeError ) : return False if operation == Transaction . C... | Validates a single Input against a single Output . |
14,580 | def read ( self ) : self . found_visible = False is_multi_quote_header = self . MULTI_QUOTE_HDR_REGEX_MULTILINE . search ( self . text ) if is_multi_quote_header : self . text = self . MULTI_QUOTE_HDR_REGEX . sub ( is_multi_quote_header . groups ( ) [ 0 ] . replace ( '\n' , '' ) , self . text ) self . text = re . sub (... | Creates new fragment for each line and labels as a signature quote or hidden . |
14,581 | def reply ( self ) : reply = [ ] for f in self . fragments : if not ( f . hidden or f . quoted ) : reply . append ( f . content ) return '\n' . join ( reply ) | Captures reply message within email |
14,582 | def _scan_line ( self , line ) : is_quote_header = self . QUOTE_HDR_REGEX . match ( line ) is not None is_quoted = self . QUOTED_REGEX . match ( line ) is not None is_header = is_quote_header or self . HEADER_REGEX . match ( line ) is not None if self . fragment and len ( line . strip ( ) ) == 0 : if self . SIG_REGEX .... | Reviews each line in email message and determines fragment type |
14,583 | def finish ( self ) : self . lines . reverse ( ) self . _content = '\n' . join ( self . lines ) self . lines = None | Creates block of content with lines belonging to fragment . |
14,584 | def check_in_out_dates ( self ) : if self . checkout and self . checkin : if self . checkin < self . date_order : raise ValidationError ( _ ( 'Check-in date should be greater than \ the current date.' ) ) if self . checkout < self . checkin : raise ValidationError ( _ ( 'Check-ou... | When date_order is less then check - in date or Checkout date should be greater than the check - in date . |
14,585 | def send_reservation_maill ( self ) : assert len ( self . _ids ) == 1 , 'This is for a single id at a time.' ir_model_data = self . env [ 'ir.model.data' ] try : template_id = ( ir_model_data . get_object_reference ( 'hotel_reservation' , 'mail_template_hotel_reservation' ) [ 1 ] ) except ValueError : template_id = Fal... | This function opens a window to compose an email template message loaded by default . |
14,586 | def walk ( filesystem , top , topdown = True , onerror = None , followlinks = False ) : def do_walk ( top_dir , top_most = False ) : top_dir = filesystem . normpath ( top_dir ) if not top_most and not followlinks and filesystem . islink ( top_dir ) : return try : top_contents = _classify_directory_contents ( filesystem... | Perform an os . walk operation over the fake filesystem . |
14,587 | def inode ( self ) : if self . _inode is None : self . stat ( follow_symlinks = False ) return self . _inode | Return the inode number of the entry . |
14,588 | def walk ( self , top , topdown = True , onerror = None , followlinks = False ) : return walk ( self . filesystem , top , topdown , onerror , followlinks ) | Perform a walk operation over the fake filesystem . |
14,589 | def add ( clss , func , deprecated_name ) : @ Deprecator ( func . __name__ , deprecated_name ) def _old_function ( * args , ** kwargs ) : return func ( * args , ** kwargs ) setattr ( clss , deprecated_name , _old_function ) | Add the deprecated version of a member function to the given class . Gives a deprecation warning on usage . |
14,590 | def init_module ( filesystem ) : FakePath . filesystem = filesystem FakePathlibModule . PureWindowsPath . _flavour = _FakeWindowsFlavour ( filesystem ) FakePathlibModule . PurePosixPath . _flavour = _FakePosixFlavour ( filesystem ) | Initializes the fake module with the fake file system . |
14,591 | def splitroot ( self , path , sep = None ) : if sep is None : sep = self . filesystem . path_separator if self . filesystem . is_windows_fs : return self . _splitroot_with_drive ( path , sep ) return self . _splitroot_posix ( path , sep ) | Split path into drive root and rest . |
14,592 | def casefold_parts ( self , parts ) : if self . filesystem . is_windows_fs : return [ p . lower ( ) for p in parts ] return parts | Return the lower - case version of parts for a Windows filesystem . |
14,593 | def resolve ( self , path , strict ) : if self . filesystem . is_windows_fs : return self . _resolve_windows ( path , strict ) return self . _resolve_posix ( path , strict ) | Make the path absolute resolving any symlinks . |
14,594 | def open ( self , mode = 'r' , buffering = - 1 , encoding = None , errors = None , newline = None ) : if self . _closed : self . _raise_closed ( ) return FakeFileOpen ( self . filesystem , use_io = True ) ( self . _path ( ) , mode , buffering , encoding , errors , newline ) | Open the file pointed by this path and return a fake file object . |
14,595 | def touch ( self , mode = 0o666 , exist_ok = True ) : if self . _closed : self . _raise_closed ( ) if self . exists ( ) : if exist_ok : self . filesystem . utime ( self . _path ( ) , None ) else : self . filesystem . raise_os_error ( errno . EEXIST , self . _path ( ) ) else : fake_file = self . open ( 'w' ) fake_file .... | Create a fake file for the path with the given access mode if it doesn t exist . |
14,596 | def _copy_module ( old ) : saved = sys . modules . pop ( old . __name__ , None ) new = __import__ ( old . __name__ ) sys . modules [ old . __name__ ] = saved return new | Recompiles and creates new module object . |
14,597 | def contents ( self ) : if not IS_PY2 and isinstance ( self . byte_contents , bytes ) : return self . byte_contents . decode ( self . encoding or locale . getpreferredencoding ( False ) , errors = self . errors ) return self . byte_contents | Return the contents as string with the original encoding . |
14,598 | def set_large_file_size ( self , st_size ) : self . _check_positive_int ( st_size ) if self . st_size : self . size = 0 if self . filesystem : self . filesystem . change_disk_usage ( st_size , self . name , self . st_dev ) self . st_size = st_size self . _byte_contents = None | Sets the self . st_size attribute and replaces self . content with None . |
14,599 | def _set_initial_contents ( self , contents ) : contents = self . _encode_contents ( contents ) changed = self . _byte_contents != contents st_size = len ( contents ) if self . _byte_contents : self . size = 0 current_size = self . st_size or 0 self . filesystem . change_disk_usage ( st_size - current_size , self . nam... | Sets the file contents and size . Called internally after initial file creation . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.