idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
242,800
def get ( self ) : if self . timer ( ) > self . deadline : self . value = None return self . value
Returns existing value or None if deadline has expired .
242,801
def set ( self , value ) : self . deadline = self . timer ( ) + self . duration self . value = value
Set new value and reset the deadline for expiration .
242,802
def sig_encode ( r , s ) : r = util . assuan_serialize ( util . num2bytes ( r , 32 ) ) s = util . assuan_serialize ( util . num2bytes ( s , 32 ) ) return b'(7:sig-val(5:ecdsa(1:r32:' + r + b')(1:s32:' + s + b')))'
Serialize ECDSA signature data into GPG S - expression .
242,803
def parse_ecdh ( line ) : prefix , line = line . split ( b' ' , 1 ) assert prefix == b'D' exp , leftover = keyring . parse ( keyring . unescape ( line ) ) log . debug ( 'ECDH s-exp: %r' , exp ) assert not leftover label , exp = exp assert label == b'enc-val' assert exp [ 0 ] == b'ecdh' items = exp [ 1 : ] log . debug (...
Parse ECDH request and return remote public key .
242,804
def handle_getinfo ( self , conn , args ) : result = None if args [ 0 ] == b'version' : result = self . version elif args [ 0 ] == b's2k_count' : result = '{}' . format ( 64 << 20 ) . encode ( 'ascii' ) else : log . warning ( 'Unknown GETINFO command: %s' , args ) if result : keyring . sendline ( conn , b'D ' + result ...
Handle some of the GETINFO messages .
242,805
def handle_scd ( self , conn , args ) : reply = { ( b'GETINFO' , b'version' ) : self . version , } . get ( args ) if reply is None : raise AgentError ( b'ERR 100696144 No such device <SCD>' ) keyring . sendline ( conn , b'D ' + reply )
No support for smart - card device protocol .
242,806
def get_identity ( self , keygrip ) : keygrip_bytes = binascii . unhexlify ( keygrip ) pubkey_dict , user_ids = decode . load_by_keygrip ( pubkey_bytes = self . pubkey_bytes , keygrip = keygrip_bytes ) user_id = user_ids [ 0 ] [ 'value' ] . decode ( 'utf-8' ) curve_name = protocol . get_curve_name_by_oid ( pubkey_dict ...
Returns device . interface . Identity that matches specified keygrip .
242,807
def pksign ( self , conn ) : log . debug ( 'signing %r digest (algo #%s)' , self . digest , self . algo ) identity = self . get_identity ( keygrip = self . keygrip ) r , s = self . client . sign ( identity = identity , digest = binascii . unhexlify ( self . digest ) ) result = sig_encode ( r , s ) log . debug ( 'result...
Sign a message digest using a private EC key .
242,808
def pkdecrypt ( self , conn ) : for msg in [ b'S INQUIRE_MAXLEN 4096' , b'INQUIRE CIPHERTEXT' ] : keyring . sendline ( conn , msg ) line = keyring . recvline ( conn ) assert keyring . recvline ( conn ) == b'END' remote_pubkey = parse_ecdh ( line ) identity = self . get_identity ( keygrip = self . keygrip ) ec_point = s...
Handle decryption using ECDH .
242,809
def have_key ( self , * keygrips ) : for keygrip in keygrips : try : self . get_identity ( keygrip = keygrip ) break except KeyError as e : log . warning ( 'HAVEKEY(%s) failed: %s' , keygrip , e ) else : raise AgentError ( b'ERR 67108881 No secret key <GPG Agent>' )
Check if any keygrip corresponds to a TREZOR - based key .
242,810
def set_hash ( self , algo , digest ) : self . algo = algo self . digest = digest
Set algorithm ID and hexadecimal digest for next operation .
242,811
def handle ( self , conn ) : keyring . sendline ( conn , b'OK' ) for line in keyring . iterlines ( conn ) : parts = line . split ( b' ' ) command = parts [ 0 ] args = tuple ( parts [ 1 : ] ) if command == b'BYE' : return elif command == b'KILLAGENT' : keyring . sendline ( conn , b'OK' ) raise AgentStop ( ) if command n...
Handle connection from GPG binary using the ASSUAN protocol .
242,812
def connect ( self ) : log . critical ( 'NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!' ) log . critical ( 'ONLY FOR DEBUGGING AND TESTING!!!' ) self . secexp = 1 self . sk = ecdsa . SigningKey . from_secret_exponent ( secexp = self . secexp , curve = ecdsa . curves . NIST256p , hashfunc = hashlib . sha256 ) self . vk...
Return dummy connection .
242,813
def create_identity ( user_id , curve_name ) : result = interface . Identity ( identity_str = 'gpg://' , curve_name = curve_name ) result . identity_dict [ 'host' ] = user_id return result
Create GPG identity for hardware device .
242,814
def pubkey ( self , identity , ecdh = False ) : with self . device : pubkey = self . device . pubkey ( ecdh = ecdh , identity = identity ) return formats . decompress_pubkey ( pubkey = pubkey , curve_name = identity . curve_name )
Return public key as VerifyingKey object .
242,815
def sign ( self , identity , digest ) : log . info ( 'please confirm GPG signature on %s for "%s"...' , self . device , identity . to_string ( ) ) if identity . curve_name == formats . CURVE_NIST256 : digest = digest [ : 32 ] log . debug ( 'signing digest: %s' , util . hexlify ( digest ) ) with self . device : sig = se...
Sign the digest and return a serialized signature .
242,816
def ecdh ( self , identity , pubkey ) : log . info ( 'please confirm GPG decryption on %s for "%s"...' , self . device , identity . to_string ( ) ) with self . device : return self . device . ecdh ( pubkey = pubkey , identity = identity )
Derive shared secret using ECDH from remote public key .
242,817
def connect ( self ) : transport = self . _defs . find_device ( ) if not transport : raise interface . NotFoundError ( '{} not connected' . format ( self ) ) log . debug ( 'using transport: %s' , transport ) for _ in range ( 5 ) : connection = self . _defs . Client ( transport = transport , ui = self . ui , state = sel...
Enumerate and connect to the first available interface .
242,818
def string_to_identity ( identity_str ) : m = _identity_regexp . match ( identity_str ) result = m . groupdict ( ) log . debug ( 'parsed identity: %s' , result ) return { k : v for k , v in result . items ( ) if v }
Parse string into Identity dictionary .
242,819
def identity_to_string ( identity_dict ) : result = [ ] if identity_dict . get ( 'proto' ) : result . append ( identity_dict [ 'proto' ] + '://' ) if identity_dict . get ( 'user' ) : result . append ( identity_dict [ 'user' ] + '@' ) result . append ( identity_dict [ 'host' ] ) if identity_dict . get ( 'port' ) : resul...
Dump Identity dictionary into its string representation .
242,820
def items ( self ) : return [ ( k , unidecode . unidecode ( v ) ) for k , v in self . identity_dict . items ( ) ]
Return a copy of identity_dict items .
242,821
def to_bytes ( self ) : s = identity_to_string ( self . identity_dict ) return unidecode . unidecode ( s ) . encode ( 'ascii' )
Transliterate Unicode into ASCII .
242,822
def get_curve_name ( self , ecdh = False ) : if ecdh : return formats . get_ecdh_curve_name ( self . curve_name ) else : return self . curve_name
Return correct curve name for device operations .
242,823
def serve ( handler , sock_path , timeout = UNIX_SOCKET_TIMEOUT ) : ssh_version = subprocess . check_output ( [ 'ssh' , '-V' ] , stderr = subprocess . STDOUT ) log . debug ( 'local SSH version: %r' , ssh_version ) environ = { 'SSH_AUTH_SOCK' : sock_path , 'SSH_AGENT_PID' : str ( os . getpid ( ) ) } device_mutex = threa...
Start the ssh - agent server on a UNIX - domain socket .
242,824
def run_server ( conn , command , sock_path , debug , timeout ) : ret = 0 try : handler = protocol . Handler ( conn = conn , debug = debug ) with serve ( handler = handler , sock_path = sock_path , timeout = timeout ) as env : if command : ret = server . run_process ( command = command , environ = env ) else : signal ....
Common code for run_agent and run_git below .
242,825
def handle_connection_error ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : try : return func ( * args , ** kwargs ) except device . interface . NotFoundError as e : log . error ( 'Connection error (try unplugging and replugging your device): %s' , e ) return 1 return wrapper
Fail with non - zero exit code .
242,826
def parse_config ( contents ) : for identity_str , curve_name in re . findall ( r'\<(.*?)\|(.*?)\>' , contents ) : yield device . interface . Identity ( identity_str = identity_str , curve_name = curve_name )
Parse config file into a list of Identity objects .
242,827
def main ( device_type ) : args = create_agent_parser ( device_type = device_type ) . parse_args ( ) util . setup_logging ( verbosity = args . verbose , filename = args . log_file ) public_keys = None filename = None if args . identity . startswith ( '/' ) : filename = args . identity contents = open ( filename , 'rb' ...
Run ssh - agent using given hardware client factory .
242,828
def parse_public_keys ( self ) : public_keys = [ formats . import_public_key ( pk ) for pk in self . public_keys ( ) ] for pk , identity in zip ( public_keys , self . identities ) : pk [ 'identity' ] = identity return public_keys
Parse SSH public keys into dictionaries .
242,829
def public_keys_as_files ( self ) : if not self . public_keys_tempfiles : for pk in self . public_keys ( ) : f = tempfile . NamedTemporaryFile ( prefix = 'trezor-ssh-pubkey-' , mode = 'w' ) f . write ( pk ) f . flush ( ) self . public_keys_tempfiles . append ( f ) return self . public_keys_tempfiles
Store public keys as temporary SSH identity files .
242,830
def sign ( self , blob , identity ) : conn = self . conn_factory ( ) return conn . sign_ssh_challenge ( blob = blob , identity = identity )
Sign a given blob using the specified identity on the device .
242,831
def packet ( tag , blob ) : assert len ( blob ) < 2 ** 32 if len ( blob ) < 2 ** 8 : length_type = 0 elif len ( blob ) < 2 ** 16 : length_type = 1 else : length_type = 2 fmt = [ '>B' , '>H' , '>L' ] [ length_type ] leading_byte = 0x80 | ( tag << 2 ) | ( length_type ) return struct . pack ( '>B' , leading_byte ) + util ...
Create small GPG packet .
242,832
def subpacket ( subpacket_type , fmt , * values ) : blob = struct . pack ( fmt , * values ) if values else fmt return struct . pack ( '>B' , subpacket_type ) + blob
Create GPG subpacket .
242,833
def subpacket_prefix_len ( item ) : n = len ( item ) if n >= 8384 : prefix = b'\xFF' + struct . pack ( '>L' , n ) elif n >= 192 : n = n - 192 prefix = struct . pack ( 'BB' , ( n // 256 ) + 192 , n % 256 ) else : prefix = struct . pack ( 'B' , n ) return prefix + item
Prefix subpacket length according to RFC 4880 section - 5 . 2 . 3 . 1 .
242,834
def subpackets ( * items ) : prefixed = [ subpacket_prefix_len ( item ) for item in items ] return util . prefix_len ( '>H' , b'' . join ( prefixed ) )
Serialize several GPG subpackets .
242,835
def mpi ( value ) : bits = value . bit_length ( ) data_size = ( bits + 7 ) // 8 data_bytes = bytearray ( data_size ) for i in range ( data_size ) : data_bytes [ i ] = value & 0xFF value = value >> 8 data_bytes . reverse ( ) return struct . pack ( '>H' , bits ) + bytes ( data_bytes )
Serialize multipresicion integer using GPG format .
242,836
def keygrip_nist256 ( vk ) : curve = vk . curve . curve gen = vk . curve . generator g = ( 4 << 512 ) | ( gen . x ( ) << 256 ) | gen . y ( ) point = vk . pubkey . point q = ( 4 << 512 ) | ( point . x ( ) << 256 ) | point . y ( ) return _compute_keygrip ( [ [ 'p' , util . num2bytes ( curve . p ( ) , size = 32 ) ] , [ 'a...
Compute keygrip for NIST256 curve public keys .
242,837
def keygrip_ed25519 ( vk ) : return _compute_keygrip ( [ [ 'p' , util . num2bytes ( 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED , size = 32 ) ] , [ 'a' , b'\x01' ] , [ 'b' , util . num2bytes ( 0x2DFC9311D490018C7338BF8688861767FF8FF5B2BEBE27548A14B235ECA6874A , size = 32 ) ] , [ 'g' , util . num2...
Compute keygrip for Ed25519 public keys .
242,838
def keygrip_curve25519 ( vk ) : return _compute_keygrip ( [ [ 'p' , util . num2bytes ( 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED , size = 32 ) ] , [ 'a' , b'\x01\xDB\x41' ] , [ 'b' , b'\x01' ] , [ 'g' , util . num2bytes ( 0x04000000000000000000000000000000000000000000000000000000000000000920ae1...
Compute keygrip for Curve25519 public keys .
242,839
def get_curve_name_by_oid ( oid ) : for curve_name , info in SUPPORTED_CURVES . items ( ) : if info [ 'oid' ] == oid : return curve_name raise KeyError ( 'Unknown OID: {!r}' . format ( oid ) )
Return curve name matching specified OID or raise KeyError .
242,840
def make_signature ( signer_func , data_to_sign , public_algo , hashed_subpackets , unhashed_subpackets , sig_type = 0 ) : header = struct . pack ( '>BBBB' , 4 , sig_type , public_algo , 8 ) hashed = subpackets ( * hashed_subpackets ) unhashed = subpackets ( * unhashed_subpackets ) tail = b'\x04\xff' + struct . pack ( ...
Create new GPG signature .
242,841
def data ( self ) : header = struct . pack ( '>BLB' , 4 , self . created , self . algo_id ) oid = util . prefix_len ( '>B' , self . curve_info [ 'oid' ] ) blob = self . curve_info [ 'serialize' ] ( self . verifying_key ) return header + oid + blob + self . ecdh_packet
Data for packet creation .
242,842
def create_subkey ( primary_bytes , subkey , signer_func , secret_bytes = b'' ) : subkey_packet = protocol . packet ( tag = ( 7 if secret_bytes else 14 ) , blob = ( subkey . data ( ) + secret_bytes ) ) packets = list ( decode . parse_packets ( io . BytesIO ( primary_bytes ) ) ) primary , user_id , signature = packets [...
Export new subkey to GPG primary key .
242,843
def verify_gpg_version ( ) : existing_gpg = keyring . gpg_version ( ) . decode ( 'ascii' ) required_gpg = '>=2.1.11' msg = 'Existing GnuPG has version "{}" ({} required)' . format ( existing_gpg , required_gpg ) if not semver . match ( existing_gpg , required_gpg ) : log . error ( msg )
Make sure that the installed GnuPG is not too old .
242,844
def check_output ( args ) : log . debug ( 'run: %s' , args ) out = subprocess . check_output ( args = args ) . decode ( 'utf-8' ) log . debug ( 'out: %r' , out ) return out
Runs command and returns the output as string .
242,845
def check_call ( args , stdin = None , env = None ) : log . debug ( 'run: %s%s' , args , ' {}' . format ( env ) if env else '' ) subprocess . check_call ( args = args , stdin = stdin , env = env )
Runs command and verifies its success .
242,846
def write_file ( path , data ) : with open ( path , 'w' ) as f : log . debug ( 'setting %s contents:\n%s' , path , data ) f . write ( data ) return f
Writes data to specified path .
242,847
def run_agent ( device_type ) : p = argparse . ArgumentParser ( ) p . add_argument ( '--homedir' , default = os . environ . get ( 'GNUPGHOME' ) ) p . add_argument ( '-v' , '--verbose' , default = 0 , action = 'count' ) p . add_argument ( '--server' , default = False , action = 'store_true' , help = 'Use stdin/stdout fo...
Run a simple GPG - agent server .
242,848
def find_device ( ) : try : return get_transport ( os . environ . get ( "TREZOR_PATH" ) ) except Exception as e : log . debug ( "Failed to find a Trezor device: %s" , e )
Selects a transport based on TREZOR_PATH environment variable .
242,849
def _convert_public_key ( ecdsa_curve_name , result ) : if ecdsa_curve_name == 'nist256p1' : if ( result [ 64 ] & 1 ) != 0 : result = bytearray ( [ 0x03 ] ) + result [ 1 : 33 ] else : result = bytearray ( [ 0x02 ] ) + result [ 1 : 33 ] else : result = result [ 1 : ] keyX = bytearray ( result [ 0 : 32 ] ) keyY = bytearr...
Convert Ledger reply into PublicKey object .
242,850
def connect ( self ) : try : return comm . getDongle ( ) except comm . CommException as e : raise interface . NotFoundError ( '{} not connected: "{}"' . format ( self , e ) )
Enumerate and connect to the first USB HID interface .
242,851
def pubkey ( self , identity , ecdh = False ) : curve_name = identity . get_curve_name ( ecdh ) path = _expand_path ( identity . get_bip32_address ( ecdh ) ) if curve_name == 'nist256p1' : p2 = '01' else : p2 = '02' apdu = '800200' + p2 apdu = binascii . unhexlify ( apdu ) apdu += bytearray ( [ len ( path ) + 1 , len (...
Get PublicKey object for specified BIP32 address and elliptic curve .
242,852
def download_setuptools ( version = DEFAULT_VERSION , download_base = DEFAULT_URL , to_dir = os . curdir , delay = 15 ) : to_dir = os . path . abspath ( to_dir ) try : from urllib . request import urlopen except ImportError : from urllib2 import urlopen tgz_name = "distribute-%s.tar.gz" % version url = download_base + ...
Download distribute from a specified location and return its filename
242,853
def tokenize ( stream , separator ) : for value in stream : for token in value . split ( separator ) : if token : yield token . strip ( )
Tokenize and yield query parameter values .
242,854
def build_query ( self , ** filters ) : applicable_filters = [ ] applicable_exclusions = [ ] for param , value in filters . items ( ) : excluding_term = False param_parts = param . split ( "__" ) base_param = param_parts [ 0 ] negation_keyword = constants . DRF_HAYSTACK_NEGATION_KEYWORD if len ( param_parts ) > 1 and p...
Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields that have been registered in view . fields .
242,855
def build_query ( self , ** filters ) : field_facets = { } date_facets = { } query_facets = { } facet_serializer_cls = self . view . get_facet_serializer_class ( ) if self . view . lookup_sep == ":" : raise AttributeError ( "The %(cls)s.lookup_sep attribute conflicts with the HaystackFacetFilter " "query parameter pars...
Creates a dict of dictionaries suitable for passing to the SearchQuerySet facet date_facet or query_facet method . All key word arguments should be wrapped in a list .
242,856
def parse_field_options ( self , * options ) : defaults = { } for option in options : if isinstance ( option , six . text_type ) : tokens = [ token . strip ( ) for token in option . split ( self . view . lookup_sep ) ] for token in tokens : if not len ( token . split ( ":" ) ) == 2 : warnings . warn ( "The %s token is ...
Parse the field options query string and return it as a dictionary .
242,857
def build_query ( self , ** filters ) : applicable_filters = None filters = dict ( ( k , filters [ k ] ) for k in chain ( self . D . UNITS . keys ( ) , [ constants . DRF_HAYSTACK_SPATIAL_QUERY_PARAM ] ) if k in filters ) distance = dict ( ( k , v ) for k , v in filters . items ( ) if k in self . D . UNITS . keys ( ) ) ...
Build queries for geo spatial filtering .
242,858
def merge_dict ( a , b ) : if not isinstance ( b , dict ) : return b result = deepcopy ( a ) for key , val in six . iteritems ( b ) : if key in result and isinstance ( result [ key ] , dict ) : result [ key ] = merge_dict ( result [ key ] , val ) elif key in result and isinstance ( result [ key ] , list ) : result [ ke...
Recursively merges and returns dict a with dict b . Any list values will be combined and returned sorted .
242,859
def get_queryset ( self , index_models = [ ] ) : if self . queryset is not None and isinstance ( self . queryset , self . object_class ) : queryset = self . queryset . all ( ) else : queryset = self . object_class ( ) . _clone ( ) if len ( index_models ) : queryset = queryset . models ( * index_models ) elif len ( self...
Get the list of items for this view . Returns self . queryset if defined and is a self . object_class instance .
242,860
def get_object ( self ) : queryset = self . get_queryset ( ) if "model" in self . request . query_params : try : app_label , model = map ( six . text_type . lower , self . request . query_params [ "model" ] . split ( "." , 1 ) ) ctype = ContentType . objects . get ( app_label = app_label , model = model ) queryset = se...
Fetch a single document from the data store according to whatever unique identifier is available for that document in the SearchIndex .
242,861
def more_like_this ( self , request , pk = None ) : obj = self . get_object ( ) . object queryset = self . filter_queryset ( self . get_queryset ( ) ) . more_like_this ( obj ) page = self . paginate_queryset ( queryset ) if page is not None : serializer = self . get_serializer ( page , many = True ) return self . get_p...
Sets up a detail route for more - like - this results . Note that you ll need backend support in order to take advantage of this .
242,862
def filter_facet_queryset ( self , queryset ) : for backend in list ( self . facet_filter_backends ) : queryset = backend ( ) . filter_queryset ( self . request , queryset , self ) if self . load_all : queryset = queryset . load_all ( ) return queryset
Given a search queryset filter it with whichever facet filter backends in use .
242,863
def get_facet_serializer ( self , * args , ** kwargs ) : assert "objects" in kwargs , "`objects` is a required argument to `get_facet_serializer()`" facet_serializer_class = self . get_facet_serializer_class ( ) kwargs [ "context" ] = self . get_serializer_context ( ) kwargs [ "context" ] . update ( { "objects" : kwarg...
Return the facet serializer instance that should be used for serializing faceted output .
242,864
def get_facet_serializer_class ( self ) : if self . facet_serializer_class is None : raise AttributeError ( "%(cls)s should either include a `facet_serializer_class` attribute, " "or override %(cls)s.get_facet_serializer_class() method." % { "cls" : self . __class__ . __name__ } ) return self . facet_serializer_class
Return the class to use for serializing facets . Defaults to using self . facet_serializer_class .
242,865
def get_facet_objects_serializer ( self , * args , ** kwargs ) : facet_objects_serializer_class = self . get_facet_objects_serializer_class ( ) kwargs [ "context" ] = self . get_serializer_context ( ) return facet_objects_serializer_class ( * args , ** kwargs )
Return the serializer instance which should be used for serializing faceted objects .
242,866
def bind ( self , field_name , parent ) : assert self . source != field_name , ( "It is redundant to specify `source='%s'` on field '%s' in " "serializer '%s', because it is the same as the field name. " "Remove the `source` keyword argument." % ( field_name , self . __class__ . __name__ , parent . __class__ . __name__...
Initializes the field name and parent for the field instance . Called when a field is added to the parent serializer instance . Taken from DRF and modified to support drf_haystack multiple index functionality .
242,867
def _get_default_field_kwargs ( model , field ) : kwargs = { } try : field_name = field . model_attr or field . index_fieldname model_field = model . _meta . get_field ( field_name ) kwargs . update ( get_field_kwargs ( field_name , model_field ) ) delete_attrs = [ "allow_blank" , "choices" , "model_field" , "allow_uni...
Get the required attributes from the model field in order to instantiate a REST Framework serializer field .
242,868
def _get_index_class_name ( self , index_cls ) : cls_name = index_cls . __name__ aliases = self . Meta . index_aliases return aliases . get ( cls_name , cls_name . split ( '.' ) [ - 1 ] )
Converts in index model class to a name suitable for use as a field name prefix . A user may optionally specify custom aliases via an index_aliases attribute on the Meta class
242,869
def get_fields ( self ) : fields = self . Meta . fields exclude = self . Meta . exclude ignore_fields = self . Meta . ignore_fields indices = self . Meta . index_classes declared_fields = copy . deepcopy ( self . _declared_fields ) prefix_field_names = len ( indices ) > 1 field_mapping = OrderedDict ( ) for index_cls i...
Get the required fields for serializing the result .
242,870
def to_representation ( self , instance ) : if self . Meta . serializers : ret = self . multi_serializer_representation ( instance ) else : ret = super ( HaystackSerializer , self ) . to_representation ( instance ) prefix_field_names = len ( getattr ( self . Meta , "index_classes" ) ) > 1 current_index = self . _get_in...
If we have a serializer mapping use that . Otherwise use standard serializer behavior Since we might be dealing with multiple indexes some fields might not be valid for all results . Do not render the fields which don t belong to the search result .
242,871
def get_narrow_url ( self , instance ) : text = instance [ 0 ] request = self . context [ "request" ] query_params = request . GET . copy ( ) page_query_param = self . get_paginate_by_param ( ) if page_query_param and page_query_param in query_params : del query_params [ page_query_param ] selected_facets = set ( query...
Return a link suitable for narrowing on the current item .
242,872
def to_representation ( self , field , instance ) : self . parent_field = field return super ( FacetFieldSerializer , self ) . to_representation ( instance )
Set the parent_field property equal to the current field on the serializer class so that each field can query it to see what kind of attribute they are processing .
242,873
def get_fields ( self ) : field_mapping = OrderedDict ( ) for field , data in self . instance . items ( ) : field_mapping . update ( { field : self . facet_dict_field_class ( child = self . facet_list_field_class ( child = self . facet_field_serializer_class ( data ) ) , required = False ) } ) if self . serialize_objec...
This returns a dictionary containing the top most fields dates fields and queries .
242,874
def get_objects ( self , instance ) : view = self . context [ "view" ] queryset = self . context [ "objects" ] page = view . paginate_queryset ( queryset ) if page is not None : serializer = view . get_facet_objects_serializer ( page , many = True ) return OrderedDict ( [ ( "count" , self . get_count ( queryset ) ) , (...
Return a list of objects matching the faceted result .
242,875
def get_document_field ( instance ) : for name , field in instance . searchindex . fields . items ( ) : if field . document is True : return name
Returns which field the search index has marked as it s document = True field .
242,876
def apply_filters ( self , queryset , applicable_filters = None , applicable_exclusions = None ) : if applicable_filters : queryset = queryset . filter ( applicable_filters ) if applicable_exclusions : queryset = queryset . exclude ( applicable_exclusions ) return queryset
Apply constructed filters and excludes and return the queryset
242,877
def build_filters ( self , view , filters = None ) : query_builder = self . get_query_builder ( backend = self , view = view ) return query_builder . build_query ( ** ( filters if filters else { } ) )
Get the query builder instance and return constructed query filters .
242,878
def filter_queryset ( self , request , queryset , view ) : applicable_filters , applicable_exclusions = self . build_filters ( view , filters = self . get_request_filters ( request ) ) return self . apply_filters ( queryset = queryset , applicable_filters = self . process_filters ( applicable_filters , queryset , view ...
Return the filtered queryset .
242,879
def get_query_builder ( self , * args , ** kwargs ) : query_builder = self . get_query_builder_class ( ) return query_builder ( * args , ** kwargs )
Return the query builder class instance that should be used to build the query which is passed to the search engine backend .
242,880
def apply_filters ( self , queryset , applicable_filters = None , applicable_exclusions = None ) : for field , options in applicable_filters [ "field_facets" ] . items ( ) : queryset = queryset . facet ( field , ** options ) for field , options in applicable_filters [ "date_facets" ] . items ( ) : queryset = queryset ....
Apply faceting to the queryset
242,881
def __convert_to_df ( a , val_col = None , group_col = None , val_id = None , group_id = None ) : if not group_col : group_col = 'groups' if not val_col : val_col = 'vals' if isinstance ( a , DataFrame ) : x = a . copy ( ) if not { group_col , val_col } . issubset ( a . columns ) : raise ValueError ( 'Specify correct c...
Hidden helper method to create a DataFrame with input data for further processing .
242,882
def posthoc_tukey_hsd ( x , g , alpha = 0.05 ) : result = pairwise_tukeyhsd ( x , g , alpha = 0.05 ) groups = np . array ( result . groupsunique , dtype = np . str ) groups_len = len ( groups ) vs = np . zeros ( ( groups_len , groups_len ) , dtype = np . int ) for a in result . summary ( ) [ 1 : ] : a0 = str ( a [ 0 ] ...
Pairwise comparisons with TukeyHSD confidence intervals . This is a convenience function to make statsmodels pairwise_tukeyhsd method more applicable for further use .
242,883
def posthoc_mannwhitney ( a , val_col = None , group_col = None , use_continuity = True , alternative = 'two-sided' , p_adjust = None , sort = True ) : x , _val_col , _group_col = __convert_to_df ( a , val_col , group_col ) if not sort : x [ _group_col ] = Categorical ( x [ _group_col ] , categories = x [ _group_col ] ...
Pairwise comparisons with Mann - Whitney rank test .
242,884
def posthoc_wilcoxon ( a , val_col = None , group_col = None , zero_method = 'wilcox' , correction = False , p_adjust = None , sort = False ) : x , _val_col , _group_col = __convert_to_df ( a , val_col , group_col ) if not sort : x [ _group_col ] = Categorical ( x [ _group_col ] , categories = x [ _group_col ] . unique...
Pairwise comparisons with Wilcoxon signed - rank test . It is a non - parametric version of the paired T - test for use with non - parametric ANOVA .
242,885
def shutdown_waits_for ( coro , loop = None ) : loop = loop or get_event_loop ( ) fut = loop . create_future ( ) async def coro_proxy ( ) : try : result = await coro except ( CancelledError , Exception ) as e : set_fut_done = partial ( fut . set_exception , e ) else : set_fut_done = partial ( fut . set_result , result ...
Prevent coro from being cancelled during the shutdown sequence .
242,886
def run ( coro : 'Optional[Coroutine]' = None , * , loop : Optional [ AbstractEventLoop ] = None , shutdown_handler : Optional [ Callable [ [ AbstractEventLoop ] , None ] ] = None , executor_workers : int = 10 , executor : Optional [ Executor ] = None , use_uvloop : bool = False ) -> None : logger . debug ( 'Entering r...
Start up the event loop and wait for a signal to shut down .
242,887
def command ( self , * args , ** kwargs ) : if len ( args ) == 1 and isinstance ( args [ 0 ] , collections . Callable ) : return self . _generate_command ( args [ 0 ] ) else : def _command ( func ) : return self . _generate_command ( func , * args , ** kwargs ) return _command
Convenient decorator simply creates corresponding command
242,888
def _generate_command ( self , func , name = None , ** kwargs ) : func_pointer = name or func . __name__ storm_config = get_storm_config ( ) aliases , additional_kwarg = None , None if 'aliases' in storm_config : for command , alias_list in six . iteritems ( storm_config . get ( "aliases" ) ) : if func_pointer == comma...
Generates a command parser for given func .
242,889
def execute ( self , arg_list ) : arg_map = self . parser . parse_args ( arg_list ) . __dict__ command = arg_map . pop ( self . _COMMAND_FLAG ) return command ( ** arg_map )
Main function to parse and dispatch commands by given arg_list
242,890
def add ( name , connection_uri , id_file = "" , o = [ ] , config = None ) : storm_ = get_storm_instance ( config ) try : if '@' in name : raise ValueError ( 'invalid value: "@" cannot be used in name.' ) user , host , port = parse ( connection_uri , user = get_default ( "user" , storm_ . defaults ) , port = get_defaul...
Adds a new entry to sshconfig .
242,891
def clone ( name , clone_name , config = None ) : storm_ = get_storm_instance ( config ) try : if '@' in name : raise ValueError ( 'invalid value: "@" cannot be used in name.' ) storm_ . clone_entry ( name , clone_name ) print ( get_formatted_message ( '{0} added to your ssh config. you can connect ' 'it by typing "ssh...
Clone an entry to the sshconfig .
242,892
def move ( name , entry_name , config = None ) : storm_ = get_storm_instance ( config ) try : if '@' in name : raise ValueError ( 'invalid value: "@" cannot be used in name.' ) storm_ . clone_entry ( name , entry_name , keep_original = False ) print ( get_formatted_message ( '{0} moved in ssh config. you can ' 'connect...
Move an entry to the sshconfig .
242,893
def edit ( name , connection_uri , id_file = "" , o = [ ] , config = None ) : storm_ = get_storm_instance ( config ) try : if ',' in name : name = " " . join ( name . split ( "," ) ) user , host , port = parse ( connection_uri , user = get_default ( "user" , storm_ . defaults ) , port = get_default ( "port" , storm_ . ...
Edits the related entry in ssh config .
242,894
def update ( name , connection_uri = "" , id_file = "" , o = [ ] , config = None ) : storm_ = get_storm_instance ( config ) settings = { } if id_file != "" : settings [ 'identityfile' ] = id_file for option in o : k , v = option . split ( "=" ) settings [ k ] = v try : storm_ . update_entry ( name , ** settings ) print...
Enhanced version of the edit command featuring multiple edits using regular expressions to match entries
242,895
def delete ( name , config = None ) : storm_ = get_storm_instance ( config ) try : storm_ . delete_entry ( name ) print ( get_formatted_message ( 'hostname "{0}" deleted successfully.' . format ( name ) , 'success' ) ) except ValueError as error : print ( get_formatted_message ( error , 'error' ) , file = sys . stderr ...
Deletes a single host .
242,896
def list ( config = None ) : storm_ = get_storm_instance ( config ) try : result = colored ( 'Listing entries:' , 'white' , attrs = [ "bold" , ] ) + "\n\n" result_stack = "" for host in storm_ . list_entries ( True ) : if host . get ( "type" ) == 'entry' : if not host . get ( "host" ) == "*" : result += " {0} -> {1}...
Lists all hosts from ssh config .
242,897
def search ( search_text , config = None ) : storm_ = get_storm_instance ( config ) try : results = storm_ . search_host ( search_text ) if len ( results ) == 0 : print ( 'no results found.' ) if len ( results ) > 0 : message = 'Listing results for {0}:\n' . format ( search_text ) message += "" . join ( results ) print...
Searches entries by given search text .
242,898
def delete_all ( config = None ) : storm_ = get_storm_instance ( config ) try : storm_ . delete_all_entries ( ) print ( get_formatted_message ( 'all entries deleted.' , 'success' ) ) except Exception as error : print ( get_formatted_message ( str ( error ) , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Deletes all hosts from ssh config .
242,899
def backup ( target_file , config = None ) : storm_ = get_storm_instance ( config ) try : storm_ . backup ( target_file ) except Exception as error : print ( get_formatted_message ( str ( error ) , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Backups the main ssh configuration into target file .