idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
249,300 | def get_image_array ( self ) : specials_mask = self . specials_mask ( ) data = self . data . copy ( ) data [ specials_mask ] -= data [ specials_mask ] . min ( ) data [ specials_mask ] *= 255 / data [ specials_mask ] . max ( ) data [ data == self . specials [ 'His' ] ] = 255 data [ data == self . specials [ 'Hrs' ] ] = 255 return data . astype ( numpy . uint8 ) | Create an array for use in making an image . | 110 | 10 |
249,301 | def check_isis_version ( major , minor = 0 , patch = 0 ) : if ISIS_VERSION and ( major , minor , patch ) <= ISIS_VERISON_TUPLE : return msg = 'Version %s.%s.%s of isis required (%s found).' raise VersionError ( msg % ( major , minor , patch , ISIS_VERSION ) ) | Checks that the current isis version is equal to or above the suplied version . | 81 | 19 |
249,302 | def require_isis_version ( major , minor = 0 , patch = 0 ) : def decorator ( fn ) : @ wraps ( fn ) def wrapper ( * args , * * kwargs ) : check_isis_version ( major , minor , patch ) return fn ( * args , * * kwargs ) return wrapper return decorator | Decorator that ensures a function is called with a minimum isis version . | 74 | 16 |
249,303 | def write_file_list ( filename , file_list = [ ] , glob = None ) : if glob : file_list = iglob ( glob ) with open ( filename , 'w' ) as f : for line in file_list : f . write ( line + '\n' ) | Write a list of files to a file . | 64 | 9 |
249,304 | def file_variations ( filename , extensions ) : ( label , ext ) = splitext ( filename ) return [ label + extention for extention in extensions ] | Create a variation of file names . | 35 | 7 |
249,305 | def insert ( self , key , value , data = { } ) : if value < self . min_value or value > self . max_value : raise BoundsError ( 'item value out of bounds' ) item = self . Item ( key , value , data ) index = self . get_bin_index ( value ) self . bins [ index ] . append ( item ) | Insert the key into a bin based on the given value . | 80 | 12 |
249,306 | def iterkeys ( self ) : def _iterkeys ( bin ) : for item in bin : yield item . key for bin in self . bins : yield _iterkeys ( bin ) | An iterator over the keys of each bin . | 38 | 9 |
249,307 | def file_request ( self ) : response = requests . get ( self . __base_url , headers = self . __headers , stream = True ) return response . raw . read ( ) , response . headers | Request that retrieve a binary file | 44 | 6 |
249,308 | def get_signatures ( self , limit = 100 , offset = 0 , conditions = { } ) : url = self . SIGNS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all signatures | 120 | 3 |
249,309 | def get_signature ( self , signature_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . SIGNS_ID_URL % signature_id ) return connection . get_request ( ) | Get a concrete Signature | 52 | 4 |
249,310 | def count_signatures ( self , conditions = { } ) : url = self . SIGNS_COUNT_URL + '?' for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Count all signatures | 99 | 3 |
249,311 | def cancel_signature ( self , signature_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . SIGNS_CANCEL_URL % signature_id ) return connection . patch_request ( ) | Cancel a concrete Signature | 54 | 5 |
249,312 | def send_signature_reminder ( self , signature_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . SIGNS_SEND_REMINDER_URL % signature_id ) return connection . post_request ( ) | Send a reminder email | 60 | 4 |
249,313 | def get_branding ( self , branding_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . BRANDINGS_ID_URL % branding_id ) return connection . get_request ( ) | Get a concrete branding | 53 | 4 |
249,314 | def get_brandings ( self ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . BRANDINGS_URL ) return connection . get_request ( ) | Get all account brandings | 43 | 5 |
249,315 | def create_branding ( self , params ) : connection = Connection ( self . token ) connection . add_header ( 'Content-Type' , 'application/json' ) connection . set_url ( self . production , self . BRANDINGS_URL ) connection . add_params ( params , json_format = True ) return connection . post_request ( ) | Create a new branding | 77 | 4 |
249,316 | def update_branding ( self , branding_id , params ) : connection = Connection ( self . token ) connection . add_header ( 'Content-Type' , 'application/json' ) connection . set_url ( self . production , self . BRANDINGS_ID_URL % branding_id ) connection . add_params ( params ) return connection . patch_request ( ) | Update a existing branding | 81 | 4 |
249,317 | def get_templates ( self , limit = 100 , offset = 0 ) : url = self . TEMPLATES_URL + "?limit=%s&offset=%s" % ( limit , offset ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all account templates | 74 | 4 |
249,318 | def get_emails ( self , limit = 100 , offset = 0 , conditions = { } ) : url = self . EMAILS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all certified emails | 121 | 4 |
249,319 | def count_emails ( self , conditions = { } ) : url = self . EMAILS_COUNT_URL + "?" for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Count all certified emails | 112 | 4 |
249,320 | def get_email ( self , email_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . EMAILS_ID_URL % email_id ) return connection . get_request ( ) | Get a specific email | 52 | 4 |
249,321 | def count_SMS ( self , conditions = { } ) : url = self . SMS_COUNT_URL + "?" for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Count all certified sms | 110 | 5 |
249,322 | def get_SMS ( self , limit = 100 , offset = 0 , conditions = { } ) : url = self . SMS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all certified sms | 119 | 5 |
249,323 | def get_single_SMS ( self , sms_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . SMS_ID_URL % sms_id ) return connection . get_request ( ) | Get a specific sms | 55 | 5 |
249,324 | def create_SMS ( self , files , recipients , body , params = { } ) : parameters = { } parser = Parser ( ) documents = { } parser . fill_array ( documents , files , 'files' ) recipients = recipients if isinstance ( recipients , list ) else [ recipients ] index = 0 for recipient in recipients : parser . fill_array ( parameters , recipient , 'recipients[%i]' % index ) index += 1 parser . fill_array ( parameters , params , '' ) parameters [ 'body' ] = body connection = Connection ( self . token ) connection . set_url ( self . production , self . SMS_URL ) connection . add_params ( parameters ) connection . add_files ( documents ) return connection . post_request ( ) | Create a new certified sms | 163 | 6 |
249,325 | def get_users ( self , limit = 100 , offset = 0 ) : url = self . TEAM_USERS_URL + "?limit=%s&offset=%s" % ( limit , offset ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all users from your current team | 73 | 7 |
249,326 | def get_seats ( self , limit = 100 , offset = 0 ) : url = self . TEAM_SEATS_URL + "?limit=%s&offset=%s" % ( limit , offset ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all seats from your current team | 74 | 7 |
249,327 | def get_groups ( self , limit = 100 , offset = 0 ) : url = self . TEAM_GROUPS_URL + "?limit=%s&offset=%s" % ( limit , offset ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all groups from your current team | 74 | 7 |
249,328 | def get_subscriptions ( self , limit = 100 , offset = 0 , params = { } ) : url = self . SUBSCRIPTIONS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in params . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all subscriptions | 124 | 3 |
249,329 | def count_subscriptions ( self , params = { } ) : url = self . SUBSCRIPTIONS_COUNT_URL + '?' for key , value in params . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Count all subscriptions | 103 | 3 |
249,330 | def get_subscription ( self , subscription_id ) : url = self . SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get single subscription | 58 | 3 |
249,331 | def delete_subscription ( self , subscription_id ) : url = self . SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . delete_request ( ) | Delete single subscription | 58 | 3 |
249,332 | def get_contacts ( self , limit = 100 , offset = 0 , params = { } ) : url = self . CONTACTS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in params . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all account contacts | 121 | 4 |
249,333 | def get_contact ( self , contact_id ) : url = self . CONTACTS_ID_URL % contact_id connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get single contact | 55 | 3 |
249,334 | def delete_contact ( self , contact_id ) : url = self . CONTACTS_ID_URL % contact_id connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . delete_request ( ) | Delete single contact | 55 | 3 |
249,335 | def main ( ) : logging . captureWarnings ( True ) logging . basicConfig ( format = ( '%(asctime)s - %(name)s - %(levelname)s - ' + '%(message)s' ) , level = logging . INFO ) args = [ 3 , 5 , 10 , 20 ] # The default queue used by grid_map is all.q. You must specify # the `queue` keyword argument if that is not the name of your queue. intermediate_results = grid_map ( computeFactorial , args , quiet = False , max_processes = 4 , queue = 'all.q' ) # Just print the items instead of really reducing. We could always sum them. print ( "reducing result" ) for i , ret in enumerate ( intermediate_results ) : print ( "f({0}) = {1}" . format ( args [ i ] , ret ) ) | execute map example | 198 | 3 |
249,336 | def main ( ) : logging . captureWarnings ( True ) logging . basicConfig ( format = ( '%(asctime)s - %(name)s - %(levelname)s - ' + '%(message)s' ) , level = logging . INFO ) print ( "=====================================" ) print ( "======== Submit and Wait ========" ) print ( "=====================================" ) print ( "" ) functionJobs = make_jobs ( ) print ( "sending function jobs to cluster" ) print ( "" ) job_outputs = process_jobs ( functionJobs , max_processes = 4 ) print ( "results from each job" ) for ( i , result ) in enumerate ( job_outputs ) : print ( "Job {0}- result: {1}" . format ( i , result ) ) | run a set of jobs on cluster | 180 | 7 |
249,337 | def execute_cmd ( cmd , * * kwargs ) : yield '$ {}\n' . format ( ' ' . join ( cmd ) ) kwargs [ 'stdout' ] = subprocess . PIPE kwargs [ 'stderr' ] = subprocess . STDOUT proc = subprocess . Popen ( cmd , * * kwargs ) # Capture output for logging. # Each line will be yielded as text. # This should behave the same as .readline(), but splits on `\r` OR `\n`, # not just `\n`. buf = [ ] def flush ( ) : line = b'' . join ( buf ) . decode ( 'utf8' , 'replace' ) buf [ : ] = [ ] return line c_last = '' try : for c in iter ( partial ( proc . stdout . read , 1 ) , b'' ) : if c_last == b'\r' and buf and c != b'\n' : yield flush ( ) buf . append ( c ) if c == b'\n' : yield flush ( ) c_last = c finally : ret = proc . wait ( ) if ret != 0 : raise subprocess . CalledProcessError ( ret , cmd ) | Call given command yielding output line by line | 267 | 8 |
249,338 | def main ( ) : logging . basicConfig ( format = '[%(asctime)s] %(levelname)s -- %(message)s' , level = logging . DEBUG ) parser = argparse . ArgumentParser ( description = 'Synchronizes a github repository with a local repository.' ) parser . add_argument ( 'git_url' , help = 'Url of the repo to sync' ) parser . add_argument ( 'branch_name' , default = 'master' , help = 'Branch of repo to sync' , nargs = '?' ) parser . add_argument ( 'repo_dir' , default = '.' , help = 'Path to clone repo under' , nargs = '?' ) args = parser . parse_args ( ) for line in GitPuller ( args . git_url , args . branch_name , args . repo_dir ) . pull ( ) : print ( line ) | Synchronizes a github repository with a local repository . | 200 | 11 |
249,339 | def pull ( self ) : if not os . path . exists ( self . repo_dir ) : yield from self . initialize_repo ( ) else : yield from self . update ( ) | Pull selected repo from a remote git repository while preserving user changes | 40 | 12 |
249,340 | def initialize_repo ( self ) : logging . info ( 'Repo {} doesn\'t exist. Cloning...' . format ( self . repo_dir ) ) clone_args = [ 'git' , 'clone' ] if self . depth and self . depth > 0 : clone_args . extend ( [ '--depth' , str ( self . depth ) ] ) clone_args . extend ( [ '--branch' , self . branch_name ] ) clone_args . extend ( [ self . git_url , self . repo_dir ] ) yield from execute_cmd ( clone_args ) yield from execute_cmd ( [ 'git' , 'config' , 'user.email' , 'nbgitpuller@example.com' ] , cwd = self . repo_dir ) yield from execute_cmd ( [ 'git' , 'config' , 'user.name' , 'nbgitpuller' ] , cwd = self . repo_dir ) logging . info ( 'Repo {} initialized' . format ( self . repo_dir ) ) | Clones repository & sets up usernames . | 230 | 10 |
249,341 | def repo_is_dirty ( self ) : try : subprocess . check_call ( [ 'git' , 'diff-files' , '--quiet' ] , cwd = self . repo_dir ) # Return code is 0 return False except subprocess . CalledProcessError : return True | Return true if repo is dirty | 62 | 6 |
249,342 | def find_upstream_changed ( self , kind ) : output = subprocess . check_output ( [ 'git' , 'log' , '{}..origin/{}' . format ( self . branch_name , self . branch_name ) , '--oneline' , '--name-status' ] , cwd = self . repo_dir ) . decode ( ) files = [ ] for line in output . split ( '\n' ) : if line . startswith ( kind ) : files . append ( os . path . join ( self . repo_dir , line . split ( '\t' , 1 ) [ 1 ] ) ) return files | Return list of files that have been changed upstream belonging to a particular kind of change | 144 | 16 |
249,343 | def rename_local_untracked ( self ) : # Find what files have been added! new_upstream_files = self . find_upstream_changed ( 'A' ) for f in new_upstream_files : if os . path . exists ( f ) : # If there's a file extension, put the timestamp before that ts = datetime . datetime . now ( ) . strftime ( '__%Y%m%d%H%M%S' ) path_head , path_tail = os . path . split ( f ) path_tail = ts . join ( os . path . splitext ( path_tail ) ) new_file_name = os . path . join ( path_head , path_tail ) os . rename ( f , new_file_name ) yield 'Renamed {} to {} to avoid conflict with upstream' . format ( f , new_file_name ) | Rename local untracked files that would require pulls | 197 | 11 |
249,344 | def update ( self ) : # Fetch remotes, so we know we're dealing with latest remote yield from self . update_remotes ( ) # Rename local untracked files that might be overwritten by pull yield from self . rename_local_untracked ( ) # Reset local files that have been deleted. We don't actually expect users to # delete something that's present upstream and expect to keep it. This prevents # unnecessary conflicts, and also allows users to click the link again to get # a fresh copy of a file they might have screwed up. yield from self . reset_deleted_files ( ) # If there are local changes, make a commit so we can do merges when pulling # We also allow empty commits. On NFS (at least), sometimes repo_is_dirty returns a false # positive, returning True even when there are no local changes (git diff-files seems to return # bogus output?). While ideally that would not happen, allowing empty commits keeps us # resilient to that issue. if self . repo_is_dirty ( ) : yield from self . ensure_lock ( ) yield from execute_cmd ( [ 'git' , 'commit' , '-am' , 'WIP' , '--allow-empty' ] , cwd = self . repo_dir ) # Merge master into local! yield from self . ensure_lock ( ) yield from execute_cmd ( [ 'git' , 'merge' , '-Xours' , 'origin/{}' . format ( self . branch_name ) ] , cwd = self . repo_dir ) | Do the pulling if necessary | 338 | 5 |
249,345 | def _get_footer_size ( file_obj ) : file_obj . seek ( - 8 , 2 ) tup = struct . unpack ( b"<i" , file_obj . read ( 4 ) ) return tup [ 0 ] | Read the footer size in bytes which is serialized as little endian . | 54 | 16 |
249,346 | def _read_footer ( file_obj ) : footer_size = _get_footer_size ( file_obj ) if logger . isEnabledFor ( logging . DEBUG ) : logger . debug ( "Footer size in bytes: %s" , footer_size ) file_obj . seek ( - ( 8 + footer_size ) , 2 ) # seek to beginning of footer tin = TFileTransport ( file_obj ) pin = TCompactProtocolFactory ( ) . get_protocol ( tin ) fmd = parquet_thrift . FileMetaData ( ) fmd . read ( pin ) return fmd | Read the footer from the given file object and returns a FileMetaData object . | 138 | 17 |
249,347 | def _read_page_header ( file_obj ) : tin = TFileTransport ( file_obj ) pin = TCompactProtocolFactory ( ) . get_protocol ( tin ) page_header = parquet_thrift . PageHeader ( ) page_header . read ( pin ) return page_header | Read the page_header from the given fo . | 68 | 10 |
249,348 | def read_footer ( filename ) : with open ( filename , 'rb' ) as file_obj : if not _check_header_magic_bytes ( file_obj ) or not _check_footer_magic_bytes ( file_obj ) : raise ParquetFormatException ( "{0} is not a valid parquet file " "(missing magic bytes)" . format ( filename ) ) return _read_footer ( file_obj ) | Read the footer and return the FileMetaData for the specified filename . | 94 | 15 |
249,349 | def _get_offset ( cmd ) : dict_offset = cmd . dictionary_page_offset data_offset = cmd . data_page_offset if dict_offset is None or data_offset < dict_offset : return data_offset return dict_offset | Return the offset into the cmd based upon if it s a dictionary page or a data page . | 54 | 19 |
249,350 | def _read_data ( file_obj , fo_encoding , value_count , bit_width ) : vals = [ ] if fo_encoding == parquet_thrift . Encoding . RLE : seen = 0 while seen < value_count : values = encoding . read_rle_bit_packed_hybrid ( file_obj , bit_width ) if values is None : break # EOF was reached. vals += values seen += len ( values ) elif fo_encoding == parquet_thrift . Encoding . BIT_PACKED : raise NotImplementedError ( "Bit packing not yet supported" ) return vals | Read data from the file - object using the given encoding . | 143 | 12 |
249,351 | def _read_dictionary_page ( file_obj , schema_helper , page_header , column_metadata ) : raw_bytes = _read_page ( file_obj , page_header , column_metadata ) io_obj = io . BytesIO ( raw_bytes ) values = encoding . read_plain ( io_obj , column_metadata . type , page_header . dictionary_page_header . num_values ) # convert the values once, if the dictionary is associated with a converted_type. schema_element = schema_helper . schema_element ( column_metadata . path_in_schema [ - 1 ] ) return convert_column ( values , schema_element ) if schema_element . converted_type is not None else values | Read a page containing dictionary data . | 163 | 7 |
249,352 | def _dump ( file_obj , options , out = sys . stdout ) : # writer and keys are lazily loaded. We don't know the keys until we have # the first item. And we need the keys for the csv writer. total_count = 0 writer = None keys = None for row in DictReader ( file_obj , options . col ) : if not keys : keys = row . keys ( ) if not writer : writer = csv . DictWriter ( out , keys , delimiter = u'\t' , quotechar = u'\'' , quoting = csv . QUOTE_MINIMAL ) if options . format == 'csv' else JsonWriter ( out ) if options . format == 'json' else None if total_count == 0 and options . format == "csv" and not options . no_headers : writer . writeheader ( ) if options . limit != - 1 and total_count >= options . limit : return row_unicode = { k : v . decode ( "utf-8" ) if isinstance ( v , bytes ) else v for k , v in row . items ( ) } writer . writerow ( row_unicode ) total_count += 1 | Dump to fo with given options . | 260 | 8 |
249,353 | def dump ( filename , options , out = sys . stdout ) : with open ( filename , 'rb' ) as file_obj : return _dump ( file_obj , options = options , out = out ) | Dump parquet file with given filename using options to out . | 45 | 13 |
249,354 | def writerow ( self , row ) : json_text = json . dumps ( row ) if isinstance ( json_text , bytes ) : json_text = json_text . decode ( 'utf-8' ) self . _out . write ( json_text ) self . _out . write ( u'\n' ) | Write a single row . | 70 | 5 |
249,355 | def read_plain_boolean ( file_obj , count ) : # for bit packed, the count is stored shifted up. But we want to pass in a count, # so we shift up. # bit width is 1 for a single-bit boolean. return read_bitpacked ( file_obj , count << 1 , 1 , logger . isEnabledFor ( logging . DEBUG ) ) | Read count booleans using the plain encoding . | 80 | 10 |
249,356 | def read_plain_int32 ( file_obj , count ) : length = 4 * count data = file_obj . read ( length ) if len ( data ) != length : raise EOFError ( "Expected {} bytes but got {} bytes" . format ( length , len ( data ) ) ) res = struct . unpack ( "<{}i" . format ( count ) . encode ( "utf-8" ) , data ) return res | Read count 32 - bit ints using the plain encoding . | 95 | 12 |
249,357 | def read_plain_int64 ( file_obj , count ) : return struct . unpack ( "<{}q" . format ( count ) . encode ( "utf-8" ) , file_obj . read ( 8 * count ) ) | Read count 64 - bit ints using the plain encoding . | 52 | 12 |
249,358 | def read_plain_int96 ( file_obj , count ) : items = struct . unpack ( b"<" + b"qi" * count , file_obj . read ( 12 * count ) ) return [ q << 32 | i for ( q , i ) in zip ( items [ 0 : : 2 ] , items [ 1 : : 2 ] ) ] | Read count 96 - bit ints using the plain encoding . | 78 | 12 |
249,359 | def read_plain_float ( file_obj , count ) : return struct . unpack ( "<{}f" . format ( count ) . encode ( "utf-8" ) , file_obj . read ( 4 * count ) ) | Read count 32 - bit floats using the plain encoding . | 51 | 11 |
249,360 | def read_plain_byte_array ( file_obj , count ) : return [ file_obj . read ( struct . unpack ( b"<i" , file_obj . read ( 4 ) ) [ 0 ] ) for i in range ( count ) ] | Read count byte arrays using the plain encoding . | 56 | 9 |
249,361 | def read_plain ( file_obj , type_ , count ) : if count == 0 : return [ ] conv = DECODE_PLAIN [ type_ ] return conv ( file_obj , count ) | Read count items type from the fo using the plain encoding . | 43 | 12 |
249,362 | def read_unsigned_var_int ( file_obj ) : result = 0 shift = 0 while True : byte = struct . unpack ( b"<B" , file_obj . read ( 1 ) ) [ 0 ] result |= ( ( byte & 0x7F ) << shift ) if ( byte & 0x80 ) == 0 : break shift += 7 return result | Read a value using the unsigned variable int encoding . | 80 | 10 |
249,363 | def read_rle ( file_obj , header , bit_width , debug_logging ) : count = header >> 1 zero_data = b"\x00\x00\x00\x00" width = ( bit_width + 7 ) // 8 data = file_obj . read ( width ) data = data + zero_data [ len ( data ) : ] value = struct . unpack ( b"<i" , data ) [ 0 ] if debug_logging : logger . debug ( "Read RLE group with value %s of byte-width %s and count %s" , value , width , count ) for _ in range ( count ) : yield value | Read a run - length encoded run from the given fo with the given header and bit_width . | 146 | 20 |
249,364 | def read_bitpacked_deprecated ( file_obj , byte_count , count , width , debug_logging ) : raw_bytes = array . array ( ARRAY_BYTE_STR , file_obj . read ( byte_count ) ) . tolist ( ) mask = _mask_for_bits ( width ) index = 0 res = [ ] word = 0 bits_in_word = 0 while len ( res ) < count and index <= len ( raw_bytes ) : if debug_logging : logger . debug ( "index = %d" , index ) logger . debug ( "bits in word = %d" , bits_in_word ) logger . debug ( "word = %s" , bin ( word ) ) if bits_in_word >= width : # how many bits over the value is stored offset = ( bits_in_word - width ) # figure out the value value = ( word & ( mask << offset ) ) >> offset if debug_logging : logger . debug ( "offset = %d" , offset ) logger . debug ( "value = %d (%s)" , value , bin ( value ) ) res . append ( value ) bits_in_word -= width else : word = ( word << 8 ) | raw_bytes [ index ] index += 1 bits_in_word += 8 return res | Read count values from fo using the deprecated bitpacking encoding . | 285 | 12 |
249,365 | def _convert_unsigned ( data , fmt ) : num = len ( data ) return struct . unpack ( "{}{}" . format ( num , fmt . upper ( ) ) . encode ( "utf-8" ) , struct . pack ( "{}{}" . format ( num , fmt ) . encode ( "utf-8" ) , * data ) ) | Convert data from signed to unsigned in bulk . | 76 | 10 |
249,366 | def convert_column ( data , schemae ) : ctype = schemae . converted_type if ctype == parquet_thrift . ConvertedType . DECIMAL : scale_factor = Decimal ( "10e-{}" . format ( schemae . scale ) ) if schemae . type == parquet_thrift . Type . INT32 or schemae . type == parquet_thrift . Type . INT64 : return [ Decimal ( unscaled ) * scale_factor for unscaled in data ] return [ Decimal ( intbig ( unscaled ) ) * scale_factor for unscaled in data ] elif ctype == parquet_thrift . ConvertedType . DATE : return [ datetime . date . fromordinal ( d ) for d in data ] elif ctype == parquet_thrift . ConvertedType . TIME_MILLIS : return [ datetime . timedelta ( milliseconds = d ) for d in data ] elif ctype == parquet_thrift . ConvertedType . TIMESTAMP_MILLIS : return [ datetime . datetime . utcfromtimestamp ( d / 1000.0 ) for d in data ] elif ctype == parquet_thrift . ConvertedType . UTF8 : return [ codecs . decode ( item , "utf-8" ) for item in data ] elif ctype == parquet_thrift . ConvertedType . UINT_8 : return _convert_unsigned ( data , 'b' ) elif ctype == parquet_thrift . ConvertedType . UINT_16 : return _convert_unsigned ( data , 'h' ) elif ctype == parquet_thrift . ConvertedType . UINT_32 : return _convert_unsigned ( data , 'i' ) elif ctype == parquet_thrift . ConvertedType . UINT_64 : return _convert_unsigned ( data , 'q' ) elif ctype == parquet_thrift . ConvertedType . JSON : return [ json . loads ( s ) for s in codecs . iterdecode ( data , "utf-8" ) ] elif ctype == parquet_thrift . ConvertedType . BSON and bson : return [ bson . BSON ( s ) . decode ( ) for s in data ] else : logger . info ( "Converted type '%s'' not handled" , parquet_thrift . ConvertedType . _VALUES_TO_NAMES [ ctype ] ) # pylint:disable=protected-access return data | Convert known types from primitive to rich . | 550 | 9 |
249,367 | def setup_logging ( options = None ) : level = logging . DEBUG if options is not None and options . debug else logging . WARNING console = logging . StreamHandler ( ) console . setLevel ( level ) formatter = logging . Formatter ( '%(name)s: %(levelname)-8s %(message)s' ) console . setFormatter ( formatter ) logging . getLogger ( 'parquet' ) . setLevel ( level ) logging . getLogger ( 'parquet' ) . addHandler ( console ) | Configure logging based on options . | 116 | 7 |
249,368 | def main ( argv = None ) : argv = argv or sys . argv [ 1 : ] parser = argparse . ArgumentParser ( 'parquet' , description = 'Read parquet files' ) parser . add_argument ( '--metadata' , action = 'store_true' , help = 'show metadata on file' ) parser . add_argument ( '--row-group-metadata' , action = 'store_true' , help = "show per row group metadata" ) parser . add_argument ( '--no-data' , action = 'store_true' , help = "don't dump any data from the file" ) parser . add_argument ( '--limit' , action = 'store' , type = int , default = - 1 , help = 'max records to output' ) parser . add_argument ( '--col' , action = 'append' , type = str , help = 'only include this column (can be ' 'specified multiple times)' ) parser . add_argument ( '--no-headers' , action = 'store_true' , help = 'skip headers in output (only applies if ' 'format=csv)' ) parser . add_argument ( '--format' , action = 'store' , type = str , default = 'csv' , help = 'format for the output data. can be csv or json.' ) parser . add_argument ( '--debug' , action = 'store_true' , help = 'log debug info to stderr' ) parser . add_argument ( 'file' , help = 'path to the file to parse' ) args = parser . parse_args ( argv ) setup_logging ( args ) import parquet if args . metadata : parquet . dump_metadata ( args . file , args . row_group_metadata ) if not args . no_data : parquet . dump ( args . file , args ) | Run parquet utility application . | 412 | 6 |
249,369 | def is_required ( self , name ) : return self . schema_element ( name ) . repetition_type == parquet_thrift . FieldRepetitionType . REQUIRED | Return true iff the schema element with the given name is required . | 38 | 14 |
249,370 | def max_repetition_level ( self , path ) : max_level = 0 for part in path : element = self . schema_element ( part ) if element . repetition_type == parquet_thrift . FieldRepetitionType . REQUIRED : max_level += 1 return max_level | Get the max repetition level for the given schema path . | 65 | 11 |
249,371 | def execute ( self , using = None ) : if not using : using = self . getConnection ( ) insertedEntities = { } for klass in self . orders : number = self . quantities [ klass ] if klass not in insertedEntities : insertedEntities [ klass ] = [ ] for i in range ( 0 , number ) : insertedEntities [ klass ] . append ( self . entities [ klass ] . execute ( using , insertedEntities ) ) return insertedEntities | Populate the database using all the Entity classes previously added . | 105 | 12 |
249,372 | def getGenerator ( cls , locale = None , providers = None , codename = None ) : codename = codename or cls . getCodename ( locale , providers ) if codename not in cls . generators : from faker import Faker as FakerGenerator # initialize with faker.generator.Generator instance # and remember in cache cls . generators [ codename ] = FakerGenerator ( locale , providers ) cls . generators [ codename ] . seed ( cls . generators [ codename ] . randomInt ( ) ) return cls . generators [ codename ] | use a codename to cache generators | 129 | 7 |
249,373 | def _point_in_bbox ( point , bounds ) : return not ( point [ 'coordinates' ] [ 1 ] < bounds [ 0 ] or point [ 'coordinates' ] [ 1 ] > bounds [ 2 ] or point [ 'coordinates' ] [ 0 ] < bounds [ 1 ] or point [ 'coordinates' ] [ 0 ] > bounds [ 3 ] ) | valid whether the point is inside the bounding box | 81 | 10 |
249,374 | def point_in_polygon ( point , poly ) : coords = [ poly [ 'coordinates' ] ] if poly [ 'type' ] == 'Polygon' else poly [ 'coordinates' ] return _point_in_polygon ( point , coords ) | valid whether the point is located in a polygon | 59 | 10 |
249,375 | def draw_circle ( radius_in_meters , center_point , steps = 15 ) : steps = steps if steps > 15 else 15 center = [ center_point [ 'coordinates' ] [ 1 ] , center_point [ 'coordinates' ] [ 0 ] ] dist = ( radius_in_meters / 1000 ) / 6371 # convert meters to radiant rad_center = [ number2radius ( center [ 0 ] ) , number2radius ( center [ 1 ] ) ] # 15 sided circle poly = [ ] for step in range ( 0 , steps ) : brng = 2 * math . pi * step / steps lat = math . asin ( math . sin ( rad_center [ 0 ] ) * math . cos ( dist ) + math . cos ( rad_center [ 0 ] ) * math . sin ( dist ) * math . cos ( brng ) ) lng = rad_center [ 1 ] + math . atan2 ( math . sin ( brng ) * math . sin ( dist ) * math . cos ( rad_center [ 0 ] ) , math . cos ( dist ) - math . sin ( rad_center [ 0 ] ) * math . sin ( lat ) ) poly . append ( [ number2degree ( lng ) , number2degree ( lat ) ] ) return { "type" : "Polygon" , "coordinates" : [ poly ] } | get a circle shape polygon based on centerPoint and radius | 297 | 12 |
249,376 | def rectangle_centroid ( rectangle ) : bbox = rectangle [ 'coordinates' ] [ 0 ] xmin = bbox [ 0 ] [ 0 ] ymin = bbox [ 0 ] [ 1 ] xmax = bbox [ 2 ] [ 0 ] ymax = bbox [ 2 ] [ 1 ] xwidth = xmax - xmin ywidth = ymax - ymin return { 'type' : 'Point' , 'coordinates' : [ xmin + xwidth / 2 , ymin + ywidth / 2 ] } | get the centroid of the rectangle | 115 | 7 |
249,377 | def geometry_within_radius ( geometry , center , radius ) : if geometry [ 'type' ] == 'Point' : return point_distance ( geometry , center ) <= radius elif geometry [ 'type' ] == 'LineString' or geometry [ 'type' ] == 'Polygon' : point = { } # it's enough to check the exterior ring of the Polygon coordinates = geometry [ 'coordinates' ] [ 0 ] if geometry [ 'type' ] == 'Polygon' else geometry [ 'coordinates' ] for coordinate in coordinates : point [ 'coordinates' ] = coordinate if point_distance ( point , center ) > radius : return False return True | To valid whether point or linestring or polygon is inside a radius around a center | 142 | 18 |
249,378 | def area ( poly ) : poly_area = 0 # TODO: polygon holes at coordinates[1] points = poly [ 'coordinates' ] [ 0 ] j = len ( points ) - 1 count = len ( points ) for i in range ( 0 , count ) : p1_x = points [ i ] [ 1 ] p1_y = points [ i ] [ 0 ] p2_x = points [ j ] [ 1 ] p2_y = points [ j ] [ 0 ] poly_area += p1_x * p2_y poly_area -= p1_y * p2_x j = i poly_area /= 2 return poly_area | calculate the area of polygon | 146 | 8 |
249,379 | def destination_point ( point , brng , dist ) : dist = float ( dist ) / 6371 # convert dist to angular distance in radians brng = number2radius ( brng ) lon1 = number2radius ( point [ 'coordinates' ] [ 0 ] ) lat1 = number2radius ( point [ 'coordinates' ] [ 1 ] ) lat2 = math . asin ( math . sin ( lat1 ) * math . cos ( dist ) + math . cos ( lat1 ) * math . sin ( dist ) * math . cos ( brng ) ) lon2 = lon1 + math . atan2 ( math . sin ( brng ) * math . sin ( dist ) * math . cos ( lat1 ) , math . cos ( dist ) - math . sin ( lat1 ) * math . sin ( lat2 ) ) lon2 = ( lon2 + 3 * math . pi ) % ( 2 * math . pi ) - math . pi # normalise to -180 degree +180 degree return { 'type' : 'Point' , 'coordinates' : [ number2degree ( lon2 ) , number2degree ( lat2 ) ] } | Calculate a destination Point base on a base point and a distance | 255 | 14 |
249,380 | def merge_featurecollection ( * jsons ) : features = [ ] for json in jsons : if json [ 'type' ] == 'FeatureCollection' : for feature in json [ 'features' ] : features . append ( feature ) return { "type" : 'FeatureCollection' , "features" : features } | merge features into one featurecollection | 67 | 7 |
249,381 | def trace_dispatch ( self , frame , event , arg ) : if hasattr ( self , 'vimpdb' ) : return self . vimpdb . trace_dispatch ( frame , event , arg ) else : return self . _orig_trace_dispatch ( frame , event , arg ) | allow to switch to Vimpdb instance | 65 | 8 |
249,382 | def hook ( klass ) : if not hasattr ( klass , 'do_vim' ) : setupMethod ( klass , trace_dispatch ) klass . __bases__ += ( SwitcherToVimpdb , ) | monkey - patch pdb . Pdb class | 50 | 9 |
249,383 | def trace_dispatch ( self , frame , event , arg ) : if hasattr ( self , 'pdb' ) : return self . pdb . trace_dispatch ( frame , event , arg ) else : return Pdb . trace_dispatch ( self , frame , event , arg ) | allow to switch to Pdb instance | 63 | 7 |
249,384 | def get_context_data ( self , * * kwargs ) : data = { } if self . _contextual_vals . current_level == 1 and self . max_levels > 1 : data [ 'sub_menu_template' ] = self . sub_menu_template . template . name data . update ( kwargs ) return super ( ) . get_context_data ( * * data ) | Include the name of the sub menu template in the context . This is purely for backwards compatibility . Any sub menus rendered as part of this menu will call sub_menu_template on the original menu instance to get an actual Template | 88 | 46 |
249,385 | def render_from_tag ( cls , context , max_levels = None , use_specific = None , apply_active_classes = True , allow_repeating_parents = True , use_absolute_page_urls = False , add_sub_menus_inline = None , template_name = '' , * * kwargs ) : instance = cls . _get_render_prepared_object ( context , max_levels = max_levels , use_specific = use_specific , apply_active_classes = apply_active_classes , allow_repeating_parents = allow_repeating_parents , use_absolute_page_urls = use_absolute_page_urls , add_sub_menus_inline = add_sub_menus_inline , template_name = template_name , * * kwargs ) if not instance : return '' return instance . render_to_template ( ) | A template tag should call this method to render a menu . The Context instance and option values provided are used to get or create a relevant menu instance prepare it then render it and it s menu items to an appropriate template . | 201 | 44 |
249,386 | def _create_contextualvals_obj_from_context ( cls , context ) : context_processor_vals = context . get ( 'wagtailmenus_vals' , { } ) return ContextualVals ( context , context [ 'request' ] , get_site_from_request ( context [ 'request' ] ) , context . get ( 'current_level' , 0 ) + 1 , context . get ( 'original_menu_tag' , cls . related_templatetag_name ) , context . get ( 'original_menu_instance' ) , context_processor_vals . get ( 'current_page' ) , context_processor_vals . get ( 'section_root' ) , context_processor_vals . get ( 'current_page_ancestor_ids' , ( ) ) , ) | Gathers all of the contextual data needed to render a menu instance and returns it in a structure that can be conveniently referenced throughout the process of preparing the menu and menu items and for rendering . | 183 | 39 |
249,387 | def render_to_template ( self ) : context_data = self . get_context_data ( ) template = self . get_template ( ) context_data [ 'current_template' ] = template . template . name return template . render ( context_data ) | Render the current menu instance to a template and return a string | 57 | 12 |
249,388 | def get_common_hook_kwargs ( self , * * kwargs ) : opt_vals = self . _option_vals hook_kwargs = self . _contextual_vals . _asdict ( ) hook_kwargs . update ( { 'menu_instance' : self , 'menu_tag' : self . related_templatetag_name , 'parent_page' : None , 'max_levels' : self . max_levels , 'use_specific' : self . use_specific , 'apply_active_classes' : opt_vals . apply_active_classes , 'allow_repeating_parents' : opt_vals . allow_repeating_parents , 'use_absolute_page_urls' : opt_vals . use_absolute_page_urls , } ) if hook_kwargs [ 'original_menu_instance' ] is None : hook_kwargs [ 'original_menu_instance' ] = self hook_kwargs . update ( kwargs ) return hook_kwargs | Returns a dictionary of common values to be passed as keyword arguments to methods registered as hooks . | 225 | 18 |
249,389 | def get_page_children_dict ( self , page_qs = None ) : children_dict = defaultdict ( list ) for page in page_qs or self . pages_for_display : children_dict [ page . path [ : - page . steplen ] ] . append ( page ) return children_dict | Returns a dictionary of lists where the keys are path values for pages and the value is a list of children pages for that page . | 68 | 26 |
249,390 | def get_context_data ( self , * * kwargs ) : ctx_vals = self . _contextual_vals opt_vals = self . _option_vals data = self . create_dict_from_parent_context ( ) data . update ( ctx_vals . _asdict ( ) ) data . update ( { 'apply_active_classes' : opt_vals . apply_active_classes , 'allow_repeating_parents' : opt_vals . allow_repeating_parents , 'use_absolute_page_urls' : opt_vals . use_absolute_page_urls , 'max_levels' : self . max_levels , 'use_specific' : self . use_specific , 'menu_instance' : self , self . menu_instance_context_name : self , # Repeat some vals with backwards-compatible keys 'section_root' : data [ 'current_section_root_page' ] , 'current_ancestor_ids' : data [ 'current_page_ancestor_ids' ] , } ) if not ctx_vals . original_menu_instance and ctx_vals . current_level == 1 : data [ 'original_menu_instance' ] = self if 'menu_items' not in kwargs : data [ 'menu_items' ] = self . get_menu_items_for_rendering ( ) data . update ( kwargs ) return data | Return a dictionary containing all of the values needed to render the menu instance to a template including values that might be used by the sub_menu tag to render any additional levels . | 316 | 35 |
249,391 | def get_menu_items_for_rendering ( self ) : items = self . get_raw_menu_items ( ) # Allow hooks to modify the raw list for hook in hooks . get_hooks ( 'menus_modify_raw_menu_items' ) : items = hook ( items , * * self . common_hook_kwargs ) # Prime and modify the menu items accordingly items = self . modify_menu_items ( self . prime_menu_items ( items ) ) if isinstance ( items , GeneratorType ) : items = list ( items ) # Allow hooks to modify the primed/modified list hook_methods = hooks . get_hooks ( 'menus_modify_primed_menu_items' ) for hook in hook_methods : items = hook ( items , * * self . common_hook_kwargs ) return items | Return a list of menu items to be included in the context for rendering the current level of the menu . | 187 | 21 |
249,392 | def _replace_with_specific_page ( page , menu_item ) : if type ( page ) is Page : page = page . specific if isinstance ( menu_item , MenuItem ) : menu_item . link_page = page else : menu_item = page return page , menu_item | If page is a vanilla Page object replace it with a specific version of itself . Also update menu_item depending on whether it s a MenuItem object or a Page object . | 64 | 35 |
249,393 | def prime_menu_items ( self , menu_items ) : for item in menu_items : item = self . _prime_menu_item ( item ) if item is not None : yield item | A generator method that takes a list of MenuItem or Page objects and sets a number of additional attributes on each item that are useful in menu templates . | 42 | 30 |
249,394 | def get_children_for_page ( self , page ) : if self . max_levels == 1 : # If there's only a single level of pages to display, skip the # dict creation / lookup and just return the QuerySet result return self . pages_for_display return super ( ) . get_children_for_page ( page ) | Return a list of relevant child pages for a given page | 73 | 11 |
249,395 | def get_top_level_items ( self ) : menu_items = self . get_base_menuitem_queryset ( ) # Identify which pages to fetch for the top level items page_ids = tuple ( obj . link_page_id for obj in menu_items if obj . link_page_id ) page_dict = { } if page_ids : # We use 'get_base_page_queryset' here, because if hooks are being # used to modify page querysets, that should affect the top level # items also top_level_pages = self . get_base_page_queryset ( ) . filter ( id__in = page_ids ) if self . use_specific >= constants . USE_SPECIFIC_TOP_LEVEL : """ The menu is being generated with a specificity level of TOP_LEVEL or ALWAYS, so we use PageQuerySet.specific() to fetch specific page instances as efficiently as possible """ top_level_pages = top_level_pages . specific ( ) # Evaluate the above queryset to a dictionary, using IDs as keys page_dict = { p . id : p for p in top_level_pages } # Now build a list to return menu_item_list = [ ] for item in menu_items : if not item . link_page_id : menu_item_list . append ( item ) continue # skip to next if item . link_page_id in page_dict . keys ( ) : # Only return menu items for pages where the page was included # in the 'get_base_page_queryset' result item . link_page = page_dict . get ( item . link_page_id ) menu_item_list . append ( item ) return menu_item_list | Return a list of menu items with link_page objects supplemented with specific pages where appropriate . | 384 | 18 |
249,396 | def get_for_site ( cls , site ) : instance , created = cls . objects . get_or_create ( site = site ) return instance | Return the main menu instance for the provided site | 34 | 9 |
249,397 | def get_form_kwargs ( self ) : kwargs = super ( ) . get_form_kwargs ( ) if self . request . method == 'POST' : data = copy ( self . request . POST ) i = 0 while ( data . get ( '%s-%s-id' % ( settings . FLAT_MENU_ITEMS_RELATED_NAME , i ) ) ) : data [ '%s-%s-id' % ( settings . FLAT_MENU_ITEMS_RELATED_NAME , i ) ] = None i += 1 kwargs . update ( { 'data' : data , 'instance' : self . model ( ) } ) return kwargs | When the form is posted don t pass an instance to the form . It should create a new one out of the posted data . We also need to nullify any IDs posted for inline menu items so that new instances of those are created too . | 152 | 49 |
249,398 | def modify_submenu_items ( self , menu_items , current_page , current_ancestor_ids , current_site , allow_repeating_parents , apply_active_classes , original_menu_tag , menu_instance = None , request = None , use_absolute_page_urls = False , ) : if ( allow_repeating_parents and menu_items and self . repeat_in_subnav ) : """ This page should have a version of itself repeated alongside children in the subnav, so we create a new item and prepend it to menu_items. """ repeated_item = self . get_repeated_menu_item ( current_page = current_page , current_site = current_site , apply_active_classes = apply_active_classes , original_menu_tag = original_menu_tag , use_absolute_page_urls = use_absolute_page_urls , request = request , ) menu_items . insert ( 0 , repeated_item ) return menu_items | Make any necessary modifications to menu_items and return the list back to the calling menu tag to render in templates . Any additional items added should have a text and href attribute as a minimum . | 222 | 38 |
249,399 | def has_submenu_items ( self , current_page , allow_repeating_parents , original_menu_tag , menu_instance = None , request = None ) : return menu_instance . page_has_children ( self ) | When rendering pages in a menu template a has_children_in_menu attribute is added to each page letting template developers know whether or not the item has a submenu that must be rendered . | 51 | 39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.