idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
241,800
def create_agent_signer ( user_id ) : sock = connect_to_agent ( env = os . environ ) keygrip = get_keygrip ( user_id ) def sign ( digest ) : """Sign the digest and return an ECDSA/RSA/DSA signature.""" return sign_digest ( sock = sock , keygrip = keygrip , digest = digest ) return sign
Sign digest with existing GPG keys using gpg - agent tool .
91
14
241,801
def msg_name ( code ) : ids = { v : k for k , v in COMMANDS . items ( ) } return ids [ code ]
Convert integer message code into a string name .
34
10
241,802
def _legacy_pubs ( buf ) : leftover = buf . read ( ) if leftover : log . warning ( 'skipping leftover: %r' , leftover ) code = util . pack ( 'B' , msg_code ( 'SSH_AGENT_RSA_IDENTITIES_ANSWER' ) ) num = util . pack ( 'L' , 0 ) # no SSH v1 keys return util . frame ( code , num )
SSH v1 public keys are not supported .
95
10
241,803
def handle ( self , msg ) : debug_msg = ': {!r}' . format ( msg ) if self . debug else '' log . debug ( 'request: %d bytes%s' , len ( msg ) , debug_msg ) buf = io . BytesIO ( msg ) code , = util . recv ( buf , '>B' ) if code not in self . methods : log . warning ( 'Unsupported command: %s (%d)' , msg_name ( code ) , co...
Handle SSH message from the SSH client and return the response .
194
12
241,804
def list_pubs ( self , buf ) : assert not buf . read ( ) keys = self . conn . parse_public_keys ( ) code = util . pack ( 'B' , msg_code ( 'SSH2_AGENT_IDENTITIES_ANSWER' ) ) num = util . pack ( 'L' , len ( keys ) ) log . debug ( 'available keys: %s' , [ k [ 'name' ] for k in keys ] ) for i , k in enumerate ( keys ) : lo...
SSH v2 public keys are serialized and returned .
181
12
241,805
def sign_message ( self , buf ) : key = formats . parse_pubkey ( util . read_frame ( buf ) ) log . debug ( 'looking for %s' , key [ 'fingerprint' ] ) blob = util . read_frame ( buf ) assert util . read_frame ( buf ) == b'' assert not buf . read ( ) for k in self . conn . parse_public_keys ( ) : if ( k [ 'fingerprint' ]...
SSH v2 public key authentication is performed .
404
10
241,806
def recv ( conn , size ) : try : fmt = size size = struct . calcsize ( fmt ) except TypeError : fmt = None try : _read = conn . recv except AttributeError : _read = conn . read res = io . BytesIO ( ) while size > 0 : buf = _read ( size ) if not buf : raise EOFError size = size - len ( buf ) res . write ( buf ) res = re...
Receive bytes from connection socket or stream .
119
9
241,807
def bytes2num ( s ) : res = 0 for i , c in enumerate ( reversed ( bytearray ( s ) ) ) : res += c << ( i * 8 ) return res
Convert MSB - first bytes to an unsigned integer .
42
12
241,808
def num2bytes ( value , size ) : res = [ ] for _ in range ( size ) : res . append ( value & 0xFF ) value = value >> 8 assert value == 0 return bytes ( bytearray ( list ( reversed ( res ) ) ) )
Convert an unsigned integer to MSB - first bytes with specified size .
58
15
241,809
def frame ( * msgs ) : res = io . BytesIO ( ) for msg in msgs : res . write ( msg ) msg = res . getvalue ( ) return pack ( 'L' , len ( msg ) ) + msg
Serialize MSB - first length - prefixed frame .
51
12
241,810
def split_bits ( value , * bits ) : result = [ ] for b in reversed ( bits ) : mask = ( 1 << b ) - 1 result . append ( value & mask ) value = value >> b assert value == 0 result . reverse ( ) return result
Split integer value into list of ints according to bits list .
56
13
241,811
def readfmt ( stream , fmt ) : size = struct . calcsize ( fmt ) blob = stream . read ( size ) return struct . unpack ( fmt , blob )
Read and unpack an object from stream using a struct format string .
38
14
241,812
def setup_logging ( verbosity , filename = None ) : levels = [ logging . WARNING , logging . INFO , logging . DEBUG ] level = levels [ min ( verbosity , len ( levels ) - 1 ) ] logging . root . setLevel ( level ) fmt = logging . Formatter ( '%(asctime)s %(levelname)-12s %(message)-100s ' '[%(filename)s:%(lineno)d]' ) hd...
Configure logging for this tool .
173
7
241,813
def which ( cmd ) : try : # For Python 3 from shutil import which as _which except ImportError : # For Python 2 from backports . shutil_which import which as _which # pylint: disable=relative-import full_path = _which ( cmd ) if full_path is None : raise OSError ( 'Cannot find {!r} in $PATH' . format ( cmd ) ) log . de...
Return full path to specified command or raise OSError if missing .
114
15
241,814
def readfmt ( self , fmt ) : size = struct . calcsize ( fmt ) blob = self . read ( size ) obj , = struct . unpack ( fmt , blob ) return obj
Read a specified object using a struct format string .
42
10
241,815
def read ( self , size = None ) : blob = self . s . read ( size ) if size is not None and len ( blob ) < size : raise EOFError if self . _captured : self . _captured . write ( blob ) return blob
Read size bytes from stream .
56
6
241,816
def get ( self ) : if self . timer ( ) > self . deadline : self . value = None return self . value
Returns existing value or None if deadline has expired .
26
10
241,817
def set ( self , value ) : self . deadline = self . timer ( ) + self . duration self . value = value
Set new value and reset the deadline for expiration .
26
10
241,818
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 .
93
14
241,819
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 .
126
12
241,820
def handle_getinfo ( self , conn , args ) : result = None if args [ 0 ] == b'version' : result = self . version elif args [ 0 ] == b's2k_count' : # Use highest number of S2K iterations. # https://www.gnupg.org/documentation/manuals/gnupg/OpenPGP-Options.html # https://tools.ietf.org/html/rfc4880#section-3.7.1.3 result ...
Handle some of the GETINFO messages .
171
8
241,821
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 .
80
9
241,822
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 ) # We assume the first user ID is used to generate TREZOR-based GPG keys. user_id = user_ids [ 0 ] [ 'value' ] . decode...
Returns device . interface . Identity that matches specified keygrip .
300
13
241,823
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 .
126
10
241,824
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 .
152
8
241,825
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 .
96
16
241,826
def set_hash ( self , algo , digest ) : self . algo = algo self . digest = digest
Set algorithm ID and hexadecimal digest for next operation .
25
13
241,827
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 .
177
13
241,828
def connect ( self ) : log . critical ( 'NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!' ) log . critical ( 'ONLY FOR DEBUGGING AND TESTING!!!' ) # The code below uses HARD-CODED secret key - and should be used ONLY # for GnuPG integration tests (e.g. when no real device is available). # pylint: disable=attribute-defin...
Return dummy connection .
176
4
241,829
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 .
55
8
241,830
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 .
64
9
241,831
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 ] # sign the first 256 bits log . debug ( 'signing digest: %s' , util . hexlify ( digest ) ) wit...
Sign the digest and return a serialized signature .
142
10
241,832
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 .
67
13
241,833
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 ) : # Retry a few times in case of PIN failures connection = self . _defs . Client ( transpor...
Enumerate and connect to the first available interface .
211
11
241,834
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 .
71
7
241,835
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 .
164
9
241,836
def items ( self ) : return [ ( k , unidecode . unidecode ( v ) ) for k , v in self . identity_dict . items ( ) ]
Return a copy of identity_dict items .
37
9
241,837
def to_bytes ( self ) : s = identity_to_string ( self . identity_dict ) return unidecode . unidecode ( s ) . encode ( 'ascii' )
Transliterate Unicode into ASCII .
42
7
241,838
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 .
47
8
241,839
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 .
252
14
241,840
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 .
114
12
241,841
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 .
86
8
241,842
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 .
63
11
241,843
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 .
647
10
241,844
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 .
69
9
241,845
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 .
98
9
241,846
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 .
38
12
241,847
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 .
122
6
241,848
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 .
50
7
241,849
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 .
95
21
241,850
def subpackets ( * items ) : prefixed = [ subpacket_prefix_len ( item ) for item in items ] return util . prefix_len ( '>H' , b'' . join ( prefixed ) )
Serialize several GPG subpackets .
49
9
241,851
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 .
93
11
241,852
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 .
239
13
241,853
def keygrip_ed25519 ( vk ) : # pylint: disable=line-too-long return _compute_keygrip ( [ [ 'p' , util . num2bytes ( 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED , size = 32 ) ] , # nopep8 [ 'a' , b'\x01' ] , [ 'b' , util . num2bytes ( 0x2DFC9311D490018C7338BF8688861767FF8FF5B2BEBE27548A14B235ECA68...
Compute keygrip for Ed25519 public keys .
294
12
241,854
def keygrip_curve25519 ( vk ) : # pylint: disable=line-too-long return _compute_keygrip ( [ [ 'p' , util . num2bytes ( 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED , size = 32 ) ] , # nopep8 [ 'a' , b'\x01\xDB\x41' ] , [ 'b' , b'\x01' ] , [ 'g' , util . num2bytes ( 0x040000000000000000000000000000...
Compute keygrip for Curve25519 public keys .
254
12
241,855
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 .
71
12
241,856
def make_signature ( signer_func , data_to_sign , public_algo , hashed_subpackets , unhashed_subpackets , sig_type = 0 ) : # pylint: disable=too-many-arguments header = struct . pack ( '>BBBB' , 4 , # version sig_type , # rfc4880 (section-5.2.1) public_algo , 8 ) # hash_alg (SHA256) hashed = subpackets ( * hashed_subpa...
Create new GPG signature .
301
6
241,857
def data ( self ) : header = struct . pack ( '>BLB' , 4 , # version self . created , # creation self . algo_id ) # public key algorithm 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 .
100
5
241,858
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 .
629
10
241,859
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 .
100
13
241,860
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 .
58
10
241,861
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 .
66
9
241,862
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 .
49
7
241,863
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 .
692
9
241,864
def find_device ( ) : try : return get_transport ( os . environ . get ( "TREZOR_PATH" ) ) except Exception as e : # pylint: disable=broad-except log . debug ( "Failed to find a Trezor device: %s" , e )
Selects a transport based on TREZOR_PATH environment variable .
68
14
241,865
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 .
179
10
241,866
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 .
49
13
241,867
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 .
200
15
241,868
def download_setuptools ( version = DEFAULT_VERSION , download_base = DEFAULT_URL , to_dir = os . curdir , delay = 15 ) : # making sure we use the absolute path to_dir = os . path . abspath ( to_dir ) try : from urllib . request import urlopen except ImportError : from urllib2 import urlopen tgz_name = "distribute-%s.t...
Download distribute from a specified location and return its filename
249
10
241,869
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 .
35
8
241,870
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 ] # only test against field without lookup negation_keyword = constants . DRF_HAYSTACK_NEGATIO...
Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields that have been registered in view . fields .
672
26
241,871
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 par...
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 .
513
38
241,872
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 .
207
14
241,873
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 .
369
7
241,874
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 .
128
23
241,875
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 .
129
27
241,876
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 .
396
24
241,877
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 .
138
29
241,878
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 .
80
17
241,879
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" : kwar...
Return the facet serializer instance that should be used for serializing faceted output .
156
17
241,880
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 .
102
23
241,881
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 .
85
16
241,882
def bind ( self , field_name , parent ) : # In order to enforce a consistent style, we error if a redundant # 'source' argument has been used. For example: # my_field = serializer.CharField(source='my_field') assert self . source != field_name , ( "It is redundant to specify `source='%s'` on field '%s' in " "serializer...
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 .
304
43
241,883
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 ) ) # Remove stuff we don't care about! delete_attrs = [ "allow_blank" , "c...
Get the required attributes from the model field in order to instantiate a REST Framework serializer field .
156
20
241,884
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
66
36
241,885
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 ( ) # overlapping f...
Get the required fields for serializing the result .
472
10
241,886
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 .
328
48
241,887
def get_narrow_url ( self , instance ) : text = instance [ 0 ] request = self . context [ "request" ] query_params = request . GET . copy ( ) # Never keep the page query parameter in narrowing urls. # It will raise a NotFound exception when trying to paginate a narrowed queryset. page_query_param = self . get_paginate_...
Return a link suitable for narrowing on the current item .
283
11
241,888
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 .
39
33
241,889
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 .
121
14
241,890
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 .
173
11
241,891
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 .
35
16
241,892
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
73
11
241,893
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 .
55
11
241,894
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 .
115
7
241,895
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 .
48
23
241,896
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
151
8
241,897
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 .
500
15
241,898
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 .
261
35
241,899
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 .
416
11