idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
227,600 | def _delegate ( self , path ) : # type: (Text) -> Optional[FS] for _name , fs in self . iterate_fs ( ) : if fs . exists ( path ) : return fs return None | Get a filesystem which has a given path . | 48 | 9 |
227,601 | def _delegate_required ( self , path ) : # type: (Text) -> FS fs = self . _delegate ( path ) if fs is None : raise errors . ResourceNotFound ( path ) return fs | Check that there is a filesystem with the given path . | 46 | 11 |
227,602 | def _writable_required ( self , path ) : # type: (Text) -> FS if self . write_fs is None : raise errors . ResourceReadOnly ( path ) return self . write_fs | Check that path is writeable . | 44 | 7 |
227,603 | def make_stream ( name , # type: Text bin_file , # type: RawIOBase mode = "r" , # type: Text buffering = - 1 , # type: int encoding = None , # type: Optional[Text] errors = None , # type: Optional[Text] newline = "" , # type: Optional[Text] line_buffering = False , # type: bool * * kwargs # type: Any ) : # type: (...) -> IO reading = "r" in mode writing = "w" in mode appending = "a" in mode binary = "b" in mode if "+" in mode : reading = True writing = True encoding = None if binary else ( encoding or "utf-8" ) io_object = RawWrapper ( bin_file , mode = mode , name = name ) # type: io.IOBase if buffering >= 0 : if reading and writing : io_object = io . BufferedRandom ( typing . cast ( io . RawIOBase , io_object ) , buffering or io . DEFAULT_BUFFER_SIZE , ) elif reading : io_object = io . BufferedReader ( typing . cast ( io . RawIOBase , io_object ) , buffering or io . DEFAULT_BUFFER_SIZE , ) elif writing or appending : io_object = io . BufferedWriter ( typing . cast ( io . RawIOBase , io_object ) , buffering or io . DEFAULT_BUFFER_SIZE , ) if not binary : io_object = io . TextIOWrapper ( io_object , encoding = encoding , errors = errors , newline = newline , line_buffering = line_buffering , ) return io_object | Take a Python 2 . x binary file and return an IO Stream . | 375 | 14 |
227,604 | def line_iterator ( readable_file , size = None ) : # type: (IO[bytes], Optional[int]) -> Iterator[bytes] read = readable_file . read line = [ ] byte = b"1" if size is None or size < 0 : while byte : byte = read ( 1 ) line . append ( byte ) if byte in b"\n" : yield b"" . join ( line ) del line [ : ] else : while byte and size : byte = read ( 1 ) size -= len ( byte ) line . append ( byte ) if byte in b"\n" or not size : yield b"" . join ( line ) del line [ : ] | Iterate over the lines of a file . | 145 | 9 |
227,605 | def validate_openbin_mode ( mode , _valid_chars = frozenset ( "rwxab+" ) ) : # type: (Text, Union[Set[Text], FrozenSet[Text]]) -> None if "t" in mode : raise ValueError ( "text mode not valid in openbin" ) if not mode : raise ValueError ( "mode must not be empty" ) if mode [ 0 ] not in "rwxa" : raise ValueError ( "mode must start with 'r', 'w', 'a' or 'x'" ) if not _valid_chars . issuperset ( mode ) : raise ValueError ( "mode '{}' contains invalid characters" . format ( mode ) ) | Check mode parameter of ~fs . base . FS . openbin is valid . | 157 | 16 |
227,606 | def _compare ( info1 , info2 ) : # type: (Info, Info) -> bool # Check filesize has changed if info1 . size != info2 . size : return True # Check modified dates date1 = info1 . modified date2 = info2 . modified return date1 is None or date2 is None or date1 > date2 | Compare two Info objects to see if they should be copied . | 75 | 12 |
227,607 | def parse_fs_url ( fs_url ) : # type: (Text) -> ParseResult match = _RE_FS_URL . match ( fs_url ) if match is None : raise ParseError ( "{!r} is not a fs2 url" . format ( fs_url ) ) fs_name , credentials , url1 , url2 , path = match . groups ( ) if not credentials : username = None # type: Optional[Text] password = None # type: Optional[Text] url = url2 else : username , _ , password = credentials . partition ( ":" ) username = unquote ( username ) password = unquote ( password ) url = url1 url , has_qs , qs = url . partition ( "?" ) resource = unquote ( url ) if has_qs : _params = parse_qs ( qs , keep_blank_values = True ) params = { k : unquote ( v [ 0 ] ) for k , v in six . iteritems ( _params ) } else : params = { } return ParseResult ( fs_name , username , password , resource , params , path ) | Parse a Filesystem URL and return a ParseResult . | 244 | 13 |
227,608 | def seek ( self , offset , whence = Seek . set ) : # type: (int, SupportsInt) -> int _whence = int ( whence ) if _whence == Seek . current : offset += self . _pos if _whence == Seek . current or _whence == Seek . set : if offset < 0 : raise ValueError ( "Negative seek position {}" . format ( offset ) ) elif _whence == Seek . end : if offset > 0 : raise ValueError ( "Positive seek position {}" . format ( offset ) ) offset += self . _end else : raise ValueError ( "Invalid whence ({}, should be {}, {} or {})" . format ( _whence , Seek . set , Seek . current , Seek . end ) ) if offset < self . _pos : self . _f = self . _zip . open ( self . name ) # type: ignore self . _pos = 0 self . read ( offset - self . _pos ) return self . _pos | Change stream position . | 214 | 4 |
227,609 | def _iter_walk ( self , fs , # type: FS path , # type: Text namespaces = None , # type: Optional[Collection[Text]] ) : # type: (...) -> Iterator[Tuple[Text, Optional[Info]]] if self . search == "breadth" : return self . _walk_breadth ( fs , path , namespaces = namespaces ) else : return self . _walk_depth ( fs , path , namespaces = namespaces ) | Get the walk generator . | 104 | 5 |
227,610 | def _check_open_dir ( self , fs , path , info ) : # type: (FS, Text, Info) -> bool if self . exclude_dirs is not None and fs . match ( self . exclude_dirs , info . name ) : return False if self . filter_dirs is not None and not fs . match ( self . filter_dirs , info . name ) : return False return self . check_open_dir ( fs , path , info ) | Check if a directory should be considered in the walk . | 103 | 11 |
227,611 | def _check_scan_dir ( self , fs , path , info , depth ) : # type: (FS, Text, Info, int) -> bool if self . max_depth is not None and depth >= self . max_depth : return False return self . check_scan_dir ( fs , path , info ) | Check if a directory contents should be scanned . | 68 | 9 |
227,612 | def check_file ( self , fs , info ) : # type: (FS, Info) -> bool if self . exclude is not None and fs . match ( self . exclude , info . name ) : return False return fs . match ( self . filter , info . name ) | Check if a filename should be included . | 58 | 8 |
227,613 | def _scan ( self , fs , # type: FS dir_path , # type: Text namespaces = None , # type: Optional[Collection[Text]] ) : # type: (...) -> Iterator[Info] try : for info in fs . scandir ( dir_path , namespaces = namespaces ) : yield info except FSError as error : if not self . on_error ( dir_path , error ) : six . reraise ( type ( error ) , error ) | Get an iterator of Info objects for a directory path . | 106 | 11 |
227,614 | def _make_walker ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Walker walker = self . walker_class ( * args , * * kwargs ) return walker | Create a walker instance . | 51 | 6 |
227,615 | def dirs ( self , path = "/" , * * kwargs ) : # type: (Text, **Any) -> Iterator[Text] walker = self . _make_walker ( * * kwargs ) return walker . dirs ( self . fs , path = path ) | Walk a filesystem yielding absolute paths to directories . | 64 | 9 |
227,616 | def info ( self , path = "/" , # type: Text namespaces = None , # type: Optional[Collection[Text]] * * kwargs # type: Any ) : # type: (...) -> Iterator[Tuple[Text, Info]] walker = self . _make_walker ( * * kwargs ) return walker . info ( self . fs , path = path , namespaces = namespaces ) | Walk a filesystem yielding path and Info of resources . | 91 | 10 |
227,617 | def remove_empty ( fs , path ) : # type: (FS, Text) -> None path = abspath ( normpath ( path ) ) try : while path not in ( "" , "/" ) : fs . removedir ( path ) path = dirname ( path ) except DirectoryNotEmpty : pass | Remove all empty parents . | 64 | 5 |
227,618 | def copy_file_data ( src_file , dst_file , chunk_size = None ) : # type: (IO, IO, Optional[int]) -> None _chunk_size = 1024 * 1024 if chunk_size is None else chunk_size read = src_file . read write = dst_file . write # The 'or None' is so that it works with binary and text files for chunk in iter ( lambda : read ( _chunk_size ) or None , None ) : write ( chunk ) | Copy data from one file object to another . | 110 | 9 |
227,619 | def get_intermediate_dirs ( fs , dir_path ) : # type: (FS, Text) -> List[Text] intermediates = [ ] with fs . lock ( ) : for path in recursepath ( abspath ( dir_path ) , reverse = True ) : try : resource = fs . getinfo ( path ) except ResourceNotFound : intermediates . append ( abspath ( path ) ) else : if resource . is_dir : break raise errors . DirectoryExpected ( dir_path ) return intermediates [ : : - 1 ] [ : - 1 ] | Get a list of non - existing intermediate directories . | 123 | 10 |
227,620 | def prettify_json ( json_string ) : try : data = json . loads ( json_string ) html = '<pre>' + json . dumps ( data , sort_keys = True , indent = 4 ) + '</pre>' except : html = json_string return mark_safe ( html ) | Given a JSON string it returns it as a safe formatted HTML | 67 | 12 |
227,621 | def purge_objects ( self , request ) : def truncate_table ( model ) : if settings . TRUNCATE_TABLE_SQL_STATEMENT : from django . db import connection sql = settings . TRUNCATE_TABLE_SQL_STATEMENT . format ( db_table = model . _meta . db_table ) cursor = connection . cursor ( ) cursor . execute ( sql ) else : model . objects . all ( ) . delete ( ) modeladmin = self opts = modeladmin . model . _meta # Check that the user has delete permission for the actual model if not request . user . is_superuser : raise PermissionDenied if not modeladmin . has_delete_permission ( request ) : raise PermissionDenied # If the user has already confirmed or cancelled the deletion, # (eventually) do the deletion and return to the change list view again. if request . method == 'POST' : if 'btn-confirm' in request . POST : try : n = modeladmin . model . objects . count ( ) truncate_table ( modeladmin . model ) modeladmin . message_user ( request , _ ( "Successfully removed %d rows" % n ) , messages . SUCCESS ) except Exception as e : modeladmin . message_user ( request , _ ( u'ERROR' ) + ': %r' % e , messages . ERROR ) else : modeladmin . message_user ( request , _ ( "Action cancelled by user" ) , messages . SUCCESS ) return HttpResponseRedirect ( reverse ( 'admin:%s_%s_changelist' % ( opts . app_label , opts . model_name ) ) ) context = { "title" : _ ( "Purge all %s ... are you sure?" ) % opts . verbose_name_plural , "opts" : opts , "app_label" : opts . app_label , } # Display the confirmation page return render ( request , 'admin/easyaudit/purge_confirmation.html' , context ) | Removes all objects in this table . This action first displays a confirmation page ; next it deletes all objects and redirects back to the change list . | 447 | 31 |
227,622 | def get_model_list ( class_list ) : for idx , item in enumerate ( class_list ) : if isinstance ( item , six . string_types ) : model_class = apps . get_model ( item ) class_list [ idx ] = model_class | Receives a list of strings with app_name . model_name format and turns them into classes . If an item is already a class it ignores it . | 62 | 33 |
227,623 | def should_audit ( instance ) : # do not audit any model listed in UNREGISTERED_CLASSES for unregistered_class in UNREGISTERED_CLASSES : if isinstance ( instance , unregistered_class ) : return False # only audit models listed in REGISTERED_CLASSES (if it's set) if len ( REGISTERED_CLASSES ) > 0 : for registered_class in REGISTERED_CLASSES : if isinstance ( instance , registered_class ) : break else : return False # all good return True | Returns True or False to indicate whether the instance should be audited or not depending on the project settings . | 116 | 21 |
227,624 | def _m2m_rev_field_name ( model1 , model2 ) : m2m_field_names = [ rel . get_accessor_name ( ) for rel in model1 . _meta . get_fields ( ) if rel . many_to_many and rel . auto_created and rel . related_model == model2 ] return m2m_field_names [ 0 ] | Gets the name of the reverse m2m accessor from model1 to model2 | 87 | 18 |
227,625 | def print_gpustat ( json = False , debug = False , * * kwargs ) : try : gpu_stats = GPUStatCollection . new_query ( ) except Exception as e : sys . stderr . write ( 'Error on querying NVIDIA devices.' ' Use --debug flag for details\n' ) if debug : try : import traceback traceback . print_exc ( file = sys . stderr ) except Exception : # NVMLError can't be processed by traceback: # https://bugs.python.org/issue28603 # as a workaround, simply re-throw the exception raise e sys . exit ( 1 ) if json : gpu_stats . print_json ( sys . stdout ) else : gpu_stats . print_formatted ( sys . stdout , * * kwargs ) | Display the GPU query results into standard output . | 181 | 9 |
227,626 | def fetch_list ( cls , client , ids ) : results = [ ] request_url = "https://api.robinhood.com/options/instruments/" for _ids in chunked_list ( ids , 50 ) : params = { "ids" : "," . join ( _ids ) } data = client . get ( request_url , params = params ) partial_results = data [ "results" ] while data [ "next" ] : data = client . get ( data [ "next" ] ) partial_results . extend ( data [ "results" ] ) results . extend ( partial_results ) return results | fetch instruments by ids | 138 | 6 |
227,627 | def in_chain ( cls , client , chain_id , expiration_dates = [ ] ) : request_url = "https://api.robinhood.com/options/instruments/" params = { "chain_id" : chain_id , "expiration_dates" : "," . join ( expiration_dates ) } data = client . get ( request_url , params = params ) results = data [ 'results' ] while data [ 'next' ] : data = client . get ( data [ 'next' ] ) results . extend ( data [ 'results' ] ) return results | fetch all option instruments in an options chain - expiration_dates = optionally scope | 129 | 16 |
227,628 | def generate_by_deltas ( cls , options , width , put_inner_lte_delta , call_inner_lte_delta ) : raise Exception ( "Not Implemented starting at the 0.3.0 release" ) # # put credit spread # put_options_unsorted = list ( filter ( lambda x : x [ 'type' ] == 'put' , options ) ) put_options = cls . sort_by_strike_price ( put_options_unsorted ) deltas_as_strings = [ x [ 'delta' ] for x in put_options ] deltas = cls . strings_to_np_array ( deltas_as_strings ) put_inner_index = np . argmin ( deltas >= put_inner_lte_delta ) - 1 put_outer_index = put_inner_index - width put_inner_leg = cls . gen_leg ( put_options [ put_inner_index ] [ "instrument" ] , "sell" ) put_outer_leg = cls . gen_leg ( put_options [ put_outer_index ] [ "instrument" ] , "buy" ) # # call credit spread # call_options_unsorted = list ( filter ( lambda x : x [ 'type' ] == 'call' , options ) ) call_options = cls . sort_by_strike_price ( call_options_unsorted ) deltas_as_strings = [ x [ 'delta' ] for x in call_options ] x = np . array ( deltas_as_strings ) deltas = x . astype ( np . float ) # because deep ITM call options have a delta that comes up as NaN, # but are approximately 0.99 or 1.0, I'm replacing Nan with 1.0 # so np.argmax is able to walk up the index until it finds # "call_inner_lte_delta" # @TODO change this so (put credit / call credit) spreads work the same where_are_NaNs = np . isnan ( deltas ) deltas [ where_are_NaNs ] = 1.0 call_inner_index = np . argmax ( deltas <= call_inner_lte_delta ) call_outer_index = call_inner_index + width call_inner_leg = cls . gen_leg ( call_options [ call_inner_index ] [ "instrument" ] , "sell" ) call_outer_leg = cls . gen_leg ( call_options [ call_outer_index ] [ "instrument" ] , "buy" ) legs = [ put_outer_leg , put_inner_leg , call_inner_leg , call_outer_leg ] # # price calcs # price = ( - Decimal ( put_options [ put_outer_index ] [ 'adjusted_mark_price' ] ) + Decimal ( put_options [ put_inner_index ] [ 'adjusted_mark_price' ] ) + Decimal ( call_options [ call_inner_index ] [ 'adjusted_mark_price' ] ) - Decimal ( call_options [ call_outer_index ] [ 'adjusted_mark_price' ] ) ) # # provide max bid ask spread diff # ic_options = [ put_options [ put_outer_index ] , put_options [ put_inner_index ] , call_options [ call_inner_index ] , call_options [ call_outer_index ] ] max_bid_ask_spread = cls . max_bid_ask_spread ( ic_options ) return { "legs" : legs , "price" : price , "max_bid_ask_spread" : max_bid_ask_spread } | totally just playing around ideas for the API . | 840 | 10 |
227,629 | def fetch ( cls , client , _id , symbol ) : url = "https://api.robinhood.com/options/chains/" params = { "equity_instrument_ids" : _id , "state" : "active" , "tradability" : "tradable" } data = client . get ( url , params = params ) def filter_func ( x ) : return x [ "symbol" ] == symbol results = list ( filter ( filter_func , data [ "results" ] ) ) return results [ 0 ] | fetch option chain for instrument | 120 | 6 |
227,630 | def authenticate ( self ) : if "username" in self . options and "password" in self . options : self . login_oauth2 ( self . options [ "username" ] , self . options [ "password" ] , self . options . get ( 'mfa_code' ) ) elif "access_token" in self . options : if "refresh_token" in self . options : self . access_token = self . options [ "access_token" ] self . refresh_token = self . options [ "refresh_token" ] self . __set_account_info ( ) else : self . authenticated = False return self . authenticated | Authenticate using data in options | 142 | 6 |
227,631 | def get ( self , url = None , params = None , retry = True ) : headers = self . _gen_headers ( self . access_token , url ) attempts = 1 while attempts <= HTTP_ATTEMPTS_MAX : try : res = requests . get ( url , headers = headers , params = params , timeout = 15 , verify = self . certs ) res . raise_for_status ( ) return res . json ( ) except requests . exceptions . RequestException as e : attempts += 1 if res . status_code in [ 400 ] : raise e elif retry and res . status_code in [ 403 ] : self . relogin_oauth2 ( ) | Execute HTTP GET | 145 | 4 |
227,632 | def _gen_headers ( self , bearer , url ) : headers = { "Accept" : "*/*" , "Accept-Encoding" : "gzip, deflate" , "Accept-Language" : ( "en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " + "nl;q=0.6, it;q=0.5" ) , "User-Agent" : ( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/68.0.3440.106 Safari/537.36" ) , } if bearer : headers [ "Authorization" ] = "Bearer {0}" . format ( bearer ) if url == "https://api.robinhood.com/options/orders/" : headers [ "Content-Type" ] = "application/json; charset=utf-8" return headers | Generate headders adding in Oauth2 bearer token if present | 233 | 14 |
227,633 | def logout_oauth2 ( self ) : url = "https://api.robinhood.com/oauth2/revoke_token/" data = { "client_id" : CLIENT_ID , "token" : self . refresh_token , } res = self . post ( url , payload = data ) if res is None : self . account_id = None self . account_url = None self . access_token = None self . refresh_token = None self . mfa_code = None self . scope = None self . authenticated = False return True else : raise AuthenticationError ( "fast_arrow could not log out." ) | Logout for given Oauth2 bearer token | 138 | 9 |
227,634 | def fetch ( cls , client , symbol ) : assert ( type ( symbol ) is str ) url = ( "https://api.robinhood.com/instruments/?symbol={0}" . format ( symbol ) ) data = client . get ( url ) return data [ "results" ] [ 0 ] | fetch data for stock | 67 | 5 |
227,635 | def gen_df ( cls , options , width , spread_type = "call" , spread_kind = "buy" ) : assert type ( width ) is int assert spread_type in [ "call" , "put" ] assert spread_kind in [ "buy" , "sell" ] # get CALLs or PUTs options = list ( filter ( lambda x : x [ "type" ] == spread_type , options ) ) coef = ( 1 if spread_type == "put" else - 1 ) shift = width * coef df = pd . DataFrame . from_dict ( options ) df [ 'expiration_date' ] = pd . to_datetime ( df [ 'expiration_date' ] , format = "%Y-%m-%d" ) df [ 'adjusted_mark_price' ] = pd . to_numeric ( df [ 'adjusted_mark_price' ] ) df [ 'strike_price' ] = pd . to_numeric ( df [ 'strike_price' ] ) df . sort_values ( [ "expiration_date" , "strike_price" ] , inplace = True ) for k , v in df . groupby ( "expiration_date" ) : sdf = v . shift ( shift ) df . loc [ v . index , "strike_price_shifted" ] = sdf [ "strike_price" ] df . loc [ v . index , "delta_shifted" ] = sdf [ "delta" ] df . loc [ v . index , "volume_shifted" ] = sdf [ "volume" ] df . loc [ v . index , "open_interest_shifted" ] = sdf [ "open_interest" ] df . loc [ v . index , "instrument_shifted" ] = sdf [ "instrument" ] df . loc [ v . index , "adjusted_mark_price_shift" ] = sdf [ "adjusted_mark_price" ] if spread_kind == "sell" : df . loc [ v . index , "margin" ] = abs ( sdf [ "strike_price" ] - v [ "strike_price" ] ) else : df . loc [ v . index , "margin" ] = 0.0 if spread_kind == "buy" : df . loc [ v . index , "premium_adjusted_mark_price" ] = ( v [ "adjusted_mark_price" ] - sdf [ "adjusted_mark_price" ] ) elif spread_kind == "sell" : df . loc [ v . index , "premium_adjusted_mark_price" ] = ( sdf [ "adjusted_mark_price" ] - v [ "adjusted_mark_price" ] ) return df | Generate Pandas Dataframe of Vertical | 608 | 8 |
227,636 | def quote_by_instruments ( cls , client , ids ) : base_url = "https://api.robinhood.com/instruments" id_urls = [ "{}/{}/" . format ( base_url , _id ) for _id in ids ] return cls . quotes_by_instrument_urls ( client , id_urls ) | create instrument urls fetch return results | 87 | 7 |
227,637 | def quotes_by_instrument_urls ( cls , client , urls ) : instruments = "," . join ( urls ) params = { "instruments" : instruments } url = "https://api.robinhood.com/marketdata/quotes/" data = client . get ( url , params = params ) results = data [ "results" ] while "next" in data and data [ "next" ] : data = client . get ( data [ "next" ] ) results . extend ( data [ "results" ] ) return results | fetch and return results | 120 | 5 |
227,638 | def all ( cls , client , * * kwargs ) : max_date = kwargs [ 'max_date' ] if 'max_date' in kwargs else None max_fetches = kwargs [ 'max_fetches' ] if 'max_fetches' in kwargs else None url = 'https://api.robinhood.com/options/positions/' params = { } data = client . get ( url , params = params ) results = data [ "results" ] if is_max_date_gt ( max_date , results [ - 1 ] [ 'updated_at' ] [ 0 : 10 ] ) : return results if max_fetches == 1 : return results fetches = 1 while data [ "next" ] : fetches = fetches + 1 data = client . get ( data [ "next" ] ) results . extend ( data [ "results" ] ) if is_max_date_gt ( max_date , results [ - 1 ] [ 'updated_at' ] [ 0 : 10 ] ) : return results if max_fetches and ( fetches >= max_fetches ) : return results return results | fetch all option positions | 254 | 5 |
227,639 | def mergein_marketdata_list ( cls , client , option_positions ) : ids = cls . _extract_ids ( option_positions ) mds = OptionMarketdata . quotes_by_instrument_ids ( client , ids ) results = [ ] for op in option_positions : # @TODO optimize this so it's better than O(n^2) md = [ x for x in mds if x [ 'instrument' ] == op [ 'option' ] ] [ 0 ] # there is no overlap in keys so this is fine merged_dict = dict ( list ( op . items ( ) ) + list ( md . items ( ) ) ) results . append ( merged_dict ) return results | Fetch and merge in Marketdata for each option position | 161 | 11 |
227,640 | def evaluateRawString ( self , escaped ) : unescaped = [ ] hexdigit = None escape = False for char in escaped : number = ord ( char ) if hexdigit is not None : if hexdigit : number = ( int ( hexdigit , 16 ) << 4 ) + int ( char , 16 ) hexdigit = None else : hexdigit = char continue if escape : escape = False try : number = self . ESCAPE_CHARS [ number ] except KeyError : if number == 120 : hexdigit = '' continue raise ValueError ( 'Unknown escape character %c' % char ) elif number == 92 : # '\' escape = True continue unescaped . append ( number ) return unescaped | Evaluates raw Python string like ast . literal_eval does | 149 | 13 |
227,641 | def subnode_parse ( self , node , pieces = None , indent = 0 , ignore = [ ] , restrict = None ) : if pieces is not None : old_pieces , self . pieces = self . pieces , pieces else : old_pieces = [ ] if type ( indent ) is int : indent = indent * ' ' if len ( indent ) > 0 : pieces = '' . join ( self . pieces ) i_piece = pieces [ : len ( indent ) ] if self . pieces [ - 1 : ] == [ '' ] : self . pieces = [ pieces [ len ( indent ) : ] ] + [ '' ] elif self . pieces != [ ] : self . pieces = [ pieces [ len ( indent ) : ] ] self . indent += len ( indent ) for n in node . childNodes : if restrict is not None : if n . nodeType == n . ELEMENT_NODE and n . tagName in restrict : self . parse ( n ) elif n . nodeType != n . ELEMENT_NODE or n . tagName not in ignore : self . parse ( n ) if len ( indent ) > 0 : self . pieces = shift ( self . pieces , indent , i_piece ) self . indent -= len ( indent ) old_pieces . extend ( self . pieces ) self . pieces = old_pieces | Parse the subnodes of a given node . Subnodes with tags in the ignore list are ignored . If pieces is given use this as target for the parse results instead of self . pieces . Indent all lines by the amount given in indent . Note that the initial content in pieces is not indented . The final result is in any case added to self . pieces . | 282 | 77 |
227,642 | def surround_parse ( self , node , pre_char , post_char ) : self . add_text ( pre_char ) self . subnode_parse ( node ) self . add_text ( post_char ) | Parse the subnodes of a given node . Subnodes with tags in the ignore list are ignored . Prepend pre_char and append post_char to the output in self . pieces . | 47 | 41 |
227,643 | def get_specific_subnodes ( self , node , name , recursive = 0 ) : children = [ x for x in node . childNodes if x . nodeType == x . ELEMENT_NODE ] ret = [ x for x in children if x . tagName == name ] if recursive > 0 : for x in children : ret . extend ( self . get_specific_subnodes ( x , name , recursive - 1 ) ) return ret | Given a node and a name return a list of child ELEMENT_NODEs that have a tagName matching the name . Search recursively for recursive levels . | 97 | 34 |
227,644 | def get_specific_nodes ( self , node , names ) : nodes = [ ( x . tagName , x ) for x in node . childNodes if x . nodeType == x . ELEMENT_NODE and x . tagName in names ] return dict ( nodes ) | Given a node and a sequence of strings in names return a dictionary containing the names as keys and child ELEMENT_NODEs that have a tagName equal to the name . | 60 | 36 |
227,645 | def add_text ( self , value ) : if isinstance ( value , ( list , tuple ) ) : self . pieces . extend ( value ) else : self . pieces . append ( value ) | Adds text corresponding to value into self . pieces . | 41 | 10 |
227,646 | def start_new_paragraph ( self ) : if self . pieces [ - 1 : ] == [ '' ] : # respect special marker return elif self . pieces == [ ] : # first paragraph, add '\n', override with '' self . pieces = [ '\n' ] elif self . pieces [ - 1 ] [ - 1 : ] != '\n' : # previous line not ended self . pieces . extend ( [ ' \n' , '\n' ] ) else : #default self . pieces . append ( '\n' ) | Make sure to create an empty line . This is overridden if the previous text ends with the special marker . In that case nothing is done . | 118 | 29 |
227,647 | def add_line_with_subsequent_indent ( self , line , indent = 4 ) : if isinstance ( line , ( list , tuple ) ) : line = '' . join ( line ) line = line . strip ( ) width = self . textwidth - self . indent - indent wrapped_lines = textwrap . wrap ( line [ indent : ] , width = width ) for i in range ( len ( wrapped_lines ) ) : if wrapped_lines [ i ] != '' : wrapped_lines [ i ] = indent * ' ' + wrapped_lines [ i ] self . pieces . append ( line [ : indent ] + '\n' . join ( wrapped_lines ) [ indent : ] + ' \n' ) | Add line of text and wrap such that subsequent lines are indented by indent spaces . | 155 | 17 |
227,648 | def extract_text ( self , node ) : if not isinstance ( node , ( list , tuple ) ) : node = [ node ] pieces , self . pieces = self . pieces , [ '' ] for n in node : for sn in n . childNodes : self . parse ( sn ) ret = '' . join ( self . pieces ) self . pieces = pieces return ret | Return the string representation of the node or list of nodes by parsing the subnodes but returning the result as a string instead of adding it to self . pieces . Note that this allows extracting text even if the node is in the ignore list . | 79 | 49 |
227,649 | def get_function_signature ( self , node ) : name = self . extract_text ( self . get_specific_subnodes ( node , 'name' ) ) if self . with_type_info : argsstring = self . extract_text ( self . get_specific_subnodes ( node , 'argsstring' ) ) else : argsstring = [ ] param_id = 1 for n_param in self . get_specific_subnodes ( node , 'param' ) : declname = self . extract_text ( self . get_specific_subnodes ( n_param , 'declname' ) ) if not declname : declname = 'arg' + str ( param_id ) defval = self . extract_text ( self . get_specific_subnodes ( n_param , 'defval' ) ) if defval : defval = '=' + defval argsstring . append ( declname + defval ) param_id = param_id + 1 argsstring = '(' + ', ' . join ( argsstring ) + ')' type = self . extract_text ( self . get_specific_subnodes ( node , 'type' ) ) function_definition = name + argsstring if type != '' and type != 'void' : function_definition = function_definition + ' -> ' + type return '`' + function_definition + '` ' | Returns the function signature string for memberdef nodes . | 302 | 10 |
227,650 | def handle_typical_memberdefs_no_overload ( self , signature , memberdef_nodes ) : for n in memberdef_nodes : self . add_text ( [ '\n' , '%feature("docstring") ' , signature , ' "' , '\n' ] ) if self . with_function_signature : self . add_line_with_subsequent_indent ( self . get_function_signature ( n ) ) self . subnode_parse ( n , pieces = [ ] , ignore = [ 'definition' , 'name' ] ) self . add_text ( [ '";' , '\n' ] ) | Produce standard documentation for memberdef_nodes . | 146 | 11 |
227,651 | def handle_typical_memberdefs ( self , signature , memberdef_nodes ) : if len ( memberdef_nodes ) == 1 or not self . with_overloaded_functions : self . handle_typical_memberdefs_no_overload ( signature , memberdef_nodes ) return self . add_text ( [ '\n' , '%feature("docstring") ' , signature , ' "' , '\n' ] ) if self . with_function_signature : for n in memberdef_nodes : self . add_line_with_subsequent_indent ( self . get_function_signature ( n ) ) self . add_text ( '\n' ) self . add_text ( [ 'Overloaded function' , '\n' , '-------------------' ] ) for n in memberdef_nodes : self . add_text ( '\n' ) self . add_line_with_subsequent_indent ( '* ' + self . get_function_signature ( n ) ) self . subnode_parse ( n , pieces = [ ] , indent = 4 , ignore = [ 'definition' , 'name' ] ) self . add_text ( [ '";' , '\n' ] ) | Produces docstring entries containing an Overloaded function section with the documentation for each overload if the function is overloaded and self . with_overloaded_functions is set . Else produce normal documentation . | 278 | 40 |
227,652 | def do_memberdef ( self , node ) : prot = node . attributes [ 'prot' ] . value id = node . attributes [ 'id' ] . value kind = node . attributes [ 'kind' ] . value tmp = node . parentNode . parentNode . parentNode compdef = tmp . getElementsByTagName ( 'compounddef' ) [ 0 ] cdef_kind = compdef . attributes [ 'kind' ] . value if cdef_kind in ( 'file' , 'namespace' , 'class' , 'struct' ) : # These cases are now handled by `handle_typical_memberdefs` return if prot != 'public' : return first = self . get_specific_nodes ( node , ( 'definition' , 'name' ) ) name = self . extract_text ( first [ 'name' ] ) if name [ : 8 ] == 'operator' : # Don't handle operators yet. return if not 'definition' in first or kind in [ 'variable' , 'typedef' ] : return data = self . extract_text ( first [ 'definition' ] ) self . add_text ( '\n' ) self . add_text ( [ '/* where did this entry come from??? */' , '\n' ] ) self . add_text ( '%feature("docstring") %s "\n%s' % ( data , data ) ) for n in node . childNodes : if n not in first . values ( ) : self . parse ( n ) self . add_text ( [ '";' , '\n' ] ) | Handle cases outside of class struct file or namespace . These are now dealt with by handle_overloaded_memberfunction . Do these even exist??? | 347 | 29 |
227,653 | def do_header ( self , node ) : data = self . extract_text ( node ) self . add_text ( '\n/*\n %s \n*/\n' % data ) # If our immediate sibling is a 'description' node then we # should comment that out also and remove it from the parent # node's children. parent = node . parentNode idx = parent . childNodes . index ( node ) if len ( parent . childNodes ) >= idx + 2 : nd = parent . childNodes [ idx + 2 ] if nd . nodeName == 'description' : nd = parent . removeChild ( nd ) self . add_text ( '\n/*' ) self . subnode_parse ( nd ) self . add_text ( '\n*/\n' ) | For a user defined section def a header field is present which should not be printed as such so we comment it in the output . | 179 | 26 |
227,654 | def visiblename ( name , all = None , obj = None ) : # Certain special names are redundant or internal. # XXX Remove __initializing__? if name in { '__author__' , '__builtins__' , '__cached__' , '__credits__' , '__date__' , '__doc__' , '__file__' , '__spec__' , '__loader__' , '__module__' , '__name__' , '__package__' , '__path__' , '__qualname__' , '__slots__' , '__version__' } : return 0 if name . endswith ( "_swigregister" ) : return 0 if name . startswith ( "__swig" ) : return 0 # Private names are hidden, but special names are displayed. if name . startswith ( '__' ) and name . endswith ( '__' ) : return 1 # Namedtuples have public fields and methods with a single leading underscore if name . startswith ( '_' ) and hasattr ( obj , '_fields' ) : return True if all is not None : # only document that which the programmer exported in __all__ return name in all else : return not name . startswith ( '_' ) | Decide whether to show documentation on a variable . | 285 | 10 |
227,655 | def _download_file ( uri , bulk_api ) : resp = requests . get ( uri , headers = bulk_api . headers ( ) , stream = True ) with tempfile . TemporaryFile ( "w+b" ) as f : for chunk in resp . iter_content ( chunk_size = None ) : f . write ( chunk ) f . seek ( 0 ) yield f | Download the bulk API result file for a single batch | 83 | 10 |
227,656 | def _load_mapping ( self , mapping ) : mapping [ "oid_as_pk" ] = bool ( mapping . get ( "fields" , { } ) . get ( "Id" ) ) job_id , local_ids_for_batch = self . _create_job ( mapping ) result = self . _wait_for_job ( job_id ) # We store inserted ids even if some batches failed self . _store_inserted_ids ( mapping , job_id , local_ids_for_batch ) return result | Load data for a single step . | 118 | 7 |
227,657 | def _create_job ( self , mapping ) : job_id = self . bulk . create_insert_job ( mapping [ "sf_object" ] , contentType = "CSV" ) self . logger . info ( " Created bulk job {}" . format ( job_id ) ) # Upload batches local_ids_for_batch = { } for batch_file , local_ids in self . _get_batches ( mapping ) : batch_id = self . bulk . post_batch ( job_id , batch_file ) local_ids_for_batch [ batch_id ] = local_ids self . logger . info ( " Uploaded batch {}" . format ( batch_id ) ) self . bulk . close_job ( job_id ) return job_id , local_ids_for_batch | Initiate a bulk insert and upload batches to run in parallel . | 175 | 14 |
227,658 | def _get_batches ( self , mapping , batch_size = 10000 ) : action = mapping . get ( "action" , "insert" ) fields = mapping . get ( "fields" , { } ) . copy ( ) static = mapping . get ( "static" , { } ) lookups = mapping . get ( "lookups" , { } ) record_type = mapping . get ( "record_type" ) # Skip Id field on insert if action == "insert" and "Id" in fields : del fields [ "Id" ] # Build the list of fields to import columns = [ ] columns . extend ( fields . keys ( ) ) columns . extend ( lookups . keys ( ) ) columns . extend ( static . keys ( ) ) if record_type : columns . append ( "RecordTypeId" ) # default to the profile assigned recordtype if we can't find any # query for the RT by developer name query = ( "SELECT Id FROM RecordType WHERE SObjectType='{0}'" "AND DeveloperName = '{1}' LIMIT 1" ) record_type_id = self . sf . query ( query . format ( mapping . get ( "sf_object" ) , record_type ) ) [ "records" ] [ 0 ] [ "Id" ] query = self . _query_db ( mapping ) total_rows = 0 batch_num = 1 def start_batch ( ) : batch_file = io . BytesIO ( ) writer = unicodecsv . writer ( batch_file ) writer . writerow ( columns ) batch_ids = [ ] return batch_file , writer , batch_ids batch_file , writer , batch_ids = start_batch ( ) for row in query . yield_per ( batch_size ) : total_rows += 1 # Add static values to row pkey = row [ 0 ] row = list ( row [ 1 : ] ) + list ( static . values ( ) ) if record_type : row . append ( record_type_id ) writer . writerow ( [ self . _convert ( value ) for value in row ] ) batch_ids . append ( pkey ) # Yield and start a new file every [batch_size] rows if not total_rows % batch_size : batch_file . seek ( 0 ) self . logger . info ( " Processing batch {}" . format ( batch_num ) ) yield batch_file , batch_ids batch_file , writer , batch_ids = start_batch ( ) batch_num += 1 # Yield result file for final batch if batch_ids : batch_file . seek ( 0 ) yield batch_file , batch_ids self . logger . info ( " Prepared {} rows for import to {}" . format ( total_rows , mapping [ "sf_object" ] ) ) | Get data from the local db | 604 | 6 |
227,659 | def _query_db ( self , mapping ) : model = self . models [ mapping . get ( "table" ) ] # Use primary key instead of the field mapped to SF Id fields = mapping . get ( "fields" , { } ) . copy ( ) if mapping [ "oid_as_pk" ] : del fields [ "Id" ] id_column = model . __table__ . primary_key . columns . keys ( ) [ 0 ] columns = [ getattr ( model , id_column ) ] for f in fields . values ( ) : columns . append ( model . __table__ . columns [ f ] ) lookups = mapping . get ( "lookups" , { } ) . copy ( ) for lookup in lookups . values ( ) : lookup [ "aliased_table" ] = aliased ( self . metadata . tables [ "{}_sf_ids" . format ( lookup [ "table" ] ) ] ) columns . append ( lookup [ "aliased_table" ] . columns . sf_id ) query = self . session . query ( * columns ) if "record_type" in mapping and hasattr ( model , "record_type" ) : query = query . filter ( model . record_type == mapping [ "record_type" ] ) if "filters" in mapping : filter_args = [ ] for f in mapping [ "filters" ] : filter_args . append ( text ( f ) ) query = query . filter ( * filter_args ) for sf_field , lookup in lookups . items ( ) : # Outer join with lookup ids table: # returns main obj even if lookup is null key_field = get_lookup_key_field ( lookup , sf_field ) value_column = getattr ( model , key_field ) query = query . outerjoin ( lookup [ "aliased_table" ] , lookup [ "aliased_table" ] . columns . id == value_column , ) # Order by foreign key to minimize lock contention # by trying to keep lookup targets in the same batch lookup_column = getattr ( model , key_field ) query = query . order_by ( lookup_column ) self . logger . info ( str ( query ) ) return query | Build a query to retrieve data from the local db . | 482 | 11 |
227,660 | def _store_inserted_ids ( self , mapping , job_id , local_ids_for_batch ) : id_table_name = self . _reset_id_table ( mapping ) conn = self . session . connection ( ) for batch_id , local_ids in local_ids_for_batch . items ( ) : try : results_url = "{}/job/{}/batch/{}/result" . format ( self . bulk . endpoint , job_id , batch_id ) # Download entire result file to a temporary file first # to avoid the server dropping connections with _download_file ( results_url , self . bulk ) as f : self . logger . info ( " Downloaded results for batch {}" . format ( batch_id ) ) self . _store_inserted_ids_for_batch ( f , local_ids , id_table_name , conn ) self . logger . info ( " Updated {} for batch {}" . format ( id_table_name , batch_id ) ) except Exception : # pragma: nocover # If we can't download one result file, # don't let that stop us from downloading the others self . logger . error ( "Could not download batch results: {}" . format ( batch_id ) ) continue self . session . commit ( ) | Get the job results and store inserted SF Ids in a new table | 284 | 14 |
227,661 | def _reset_id_table ( self , mapping ) : if not hasattr ( self , "_initialized_id_tables" ) : self . _initialized_id_tables = set ( ) id_table_name = "{}_sf_ids" . format ( mapping [ "table" ] ) if id_table_name not in self . _initialized_id_tables : if id_table_name in self . metadata . tables : self . metadata . remove ( self . metadata . tables [ id_table_name ] ) id_table = Table ( id_table_name , self . metadata , Column ( "id" , Unicode ( 255 ) , primary_key = True ) , Column ( "sf_id" , Unicode ( 18 ) ) , ) if id_table . exists ( ) : id_table . drop ( ) id_table . create ( ) self . _initialized_id_tables . add ( id_table_name ) return id_table_name | Create an empty table to hold the inserted SF Ids | 212 | 11 |
227,662 | def _get_mapping_for_table ( self , table ) : for mapping in self . mappings . values ( ) : if mapping [ "table" ] == table : return mapping | Returns the first mapping for a table name | 40 | 8 |
227,663 | def _load_config ( self ) : if ( self . config ) : # any config being pre-set at init will short circuit out, but not a plain {} return # Verify that we're in a project repo_root = self . repo_root if not repo_root : raise NotInProject ( "No git repository was found in the current path. You must be in a git repository to set up and use CCI for a project." ) # Verify that the project's root has a config file if not self . config_project_path : raise ProjectConfigNotFound ( "The file {} was not found in the repo root: {}. Are you in a CumulusCI Project directory?" . format ( self . config_filename , repo_root ) ) # Load the project's yaml config file with open ( self . config_project_path , "r" ) as f_config : project_config = ordered_yaml_load ( f_config ) if project_config : self . config_project . update ( project_config ) # Load the local project yaml config file if it exists if self . config_project_local_path : with open ( self . config_project_local_path , "r" ) as f_local_config : local_config = ordered_yaml_load ( f_local_config ) if local_config : self . config_project_local . update ( local_config ) # merge in any additional yaml that was passed along if self . additional_yaml : additional_yaml_config = ordered_yaml_load ( self . additional_yaml ) if additional_yaml_config : self . config_additional_yaml . update ( additional_yaml_config ) self . config = merge_config ( OrderedDict ( [ ( "global_config" , self . config_global ) , ( "global_local" , self . config_global_local ) , ( "project_config" , self . config_project ) , ( "project_local_config" , self . config_project_local ) , ( "additional_yaml" , self . config_additional_yaml ) , ] ) ) | Loads the configuration from YAML if no override config was passed in initially . | 469 | 17 |
227,664 | def init_sentry ( self , ) : if not self . use_sentry : return sentry_config = self . keychain . get_service ( "sentry" ) tags = { "repo" : self . repo_name , "branch" : self . repo_branch , "commit" : self . repo_commit , "cci version" : cumulusci . __version__ , } tags . update ( self . config . get ( "sentry_tags" , { } ) ) env = self . config . get ( "sentry_environment" , "CumulusCI CLI" ) self . sentry = raven . Client ( dsn = sentry_config . dsn , environment = env , tags = tags , processors = ( "raven.processors.SanitizePasswordsProcessor" , ) , ) | Initializes sentry . io error logging for this session | 183 | 11 |
227,665 | def get_previous_version ( self ) : gh = self . get_github_api ( ) repo = gh . repository ( self . repo_owner , self . repo_name ) most_recent = None for release in repo . releases ( ) : # Return the second release that matches the release prefix if release . tag_name . startswith ( self . project__git__prefix_release ) : if most_recent is None : most_recent = release else : return LooseVersion ( self . get_version_for_tag ( release . tag_name ) ) | Query GitHub releases to find the previous production release | 122 | 9 |
227,666 | def get_static_dependencies ( self , dependencies = None , include_beta = None ) : if not dependencies : dependencies = self . project__dependencies if not dependencies : return [ ] static_dependencies = [ ] for dependency in dependencies : if "github" not in dependency : static_dependencies . append ( dependency ) else : static = self . process_github_dependency ( dependency , include_beta = include_beta ) static_dependencies . extend ( static ) return static_dependencies | Resolves the project - > dependencies section of cumulusci . yml to convert dynamic github dependencies into static dependencies by inspecting the referenced repositories | 106 | 28 |
227,667 | def _init_logger ( self ) : if self . flow : self . logger = self . flow . logger . getChild ( self . __class__ . __name__ ) else : self . logger = logging . getLogger ( __name__ ) | Initializes self . logger | 54 | 5 |
227,668 | def _init_options ( self , kwargs ) : self . options = self . task_config . options if self . options is None : self . options = { } if kwargs : self . options . update ( kwargs ) # Handle dynamic lookup of project_config values via $project_config.attr for option , value in list ( self . options . items ( ) ) : try : if value . startswith ( "$project_config." ) : attr = value . replace ( "$project_config." , "" , 1 ) self . options [ option ] = getattr ( self . project_config , attr , None ) except AttributeError : pass | Initializes self . options | 144 | 5 |
227,669 | def _log_begin ( self ) : self . logger . info ( "Beginning task: %s" , self . __class__ . __name__ ) if self . salesforce_task and not self . flow : self . logger . info ( "%15s %s" , "As user:" , self . org_config . username ) self . logger . info ( "%15s %s" , "In org:" , self . org_config . org_id ) self . logger . info ( "" ) | Log the beginning of the task execution | 108 | 7 |
227,670 | def _poll ( self ) : while True : self . poll_count += 1 self . _poll_action ( ) if self . poll_complete : break time . sleep ( self . poll_interval_s ) self . _poll_update_interval ( ) | poll for a result in a loop | 57 | 7 |
227,671 | def _poll_update_interval ( self ) : # Increase by 1 second every 3 polls if old_div ( self . poll_count , 3 ) > self . poll_interval_level : self . poll_interval_level += 1 self . poll_interval_s += 1 self . logger . info ( "Increased polling interval to %d seconds" , self . poll_interval_s ) | update the polling interval to be used next iteration | 88 | 9 |
227,672 | def get_project_config ( self , * args , * * kwargs ) : warnings . warn ( "BaseGlobalConfig.get_project_config is pending deprecation" , DeprecationWarning , ) return self . project_config_class ( self , * args , * * kwargs ) | Returns a ProjectConfig for the given project | 66 | 8 |
227,673 | def _load_config ( self ) : # load the global config with open ( self . config_global_path , "r" ) as f_config : config = ordered_yaml_load ( f_config ) self . config_global = config # Load the local config if self . config_global_local_path : config = ordered_yaml_load ( open ( self . config_global_local_path , "r" ) ) self . config_global_local = config self . config = merge_config ( OrderedDict ( [ ( "global_config" , self . config_global ) , ( "global_local" , self . config_global_local ) , ] ) ) | Loads the local configuration | 152 | 5 |
227,674 | def username ( self ) : username = self . config . get ( "username" ) if not username : username = self . userinfo__preferred_username return username | Username for the org connection . | 35 | 7 |
227,675 | def timestamp_file ( ) : config_dir = os . path . join ( os . path . expanduser ( "~" ) , BaseGlobalConfig . config_local_dir ) if not os . path . exists ( config_dir ) : os . mkdir ( config_dir ) timestamp_file = os . path . join ( config_dir , "cumulus_timestamp" ) try : with open ( timestamp_file , "r+" ) as f : yield f except IOError : # file does not exist with open ( timestamp_file , "w+" ) as f : yield f | Opens a file for tracking the time of the last version check | 128 | 13 |
227,676 | def pass_config ( func = None , * * config_kw ) : def decorate ( func ) : def new_func ( * args , * * kw ) : config = load_config ( * * config_kw ) func ( config , * args , * * kw ) return functools . update_wrapper ( new_func , func ) if func is None : return decorate else : return decorate ( func ) | Decorator which passes the CCI config object as the first arg to a click command . | 92 | 19 |
227,677 | def list_commands ( self , ctx ) : config = load_config ( * * self . load_config_kwargs ) services = self . _get_services_config ( config ) return sorted ( services . keys ( ) ) | list the services that can be configured | 51 | 7 |
227,678 | def parse_api_datetime ( value ) : dt = datetime . strptime ( value [ 0 : DATETIME_LEN ] , API_DATE_FORMAT ) offset_str = value [ DATETIME_LEN : ] assert offset_str in [ "+0000" , "Z" ] , "The Salesforce API returned a weird timezone." return dt | parse a datetime returned from the salesforce API . | 86 | 11 |
227,679 | def removeXmlElement ( name , directory , file_pattern , logger = None ) : for path , dirs , files in os . walk ( os . path . abspath ( directory ) ) : for filename in fnmatch . filter ( files , file_pattern ) : filepath = os . path . join ( path , filename ) remove_xml_element_file ( name , filepath ) | Recursively walk a directory and remove XML elements | 83 | 10 |
227,680 | def remove_xml_element_file ( name , path ) : ET . register_namespace ( "" , "http://soap.sforce.com/2006/04/metadata" ) tree = elementtree_parse_file ( path ) tree = remove_xml_element ( name , tree ) return tree . write ( path , encoding = UTF8 , xml_declaration = True ) | Remove XML elements from a single file | 83 | 7 |
227,681 | def remove_xml_element_string ( name , content ) : ET . register_namespace ( "" , "http://soap.sforce.com/2006/04/metadata" ) tree = ET . fromstring ( content ) tree = remove_xml_element ( name , tree ) clean_content = ET . tostring ( tree , encoding = UTF8 ) return clean_content | Remove XML elements from a string | 82 | 6 |
227,682 | def remove_xml_element ( name , tree ) : # root = tree.getroot() remove = tree . findall ( ".//{{http://soap.sforce.com/2006/04/metadata}}{}" . format ( name ) ) if not remove : return tree parent_map = { c : p for p in tree . iter ( ) for c in p } for elem in remove : parent = parent_map [ elem ] parent . remove ( elem ) return tree | Removes XML elements from an ElementTree content tree | 105 | 10 |
227,683 | def temporary_dir ( ) : d = tempfile . mkdtemp ( ) try : with cd ( d ) : yield d finally : if os . path . exists ( d ) : shutil . rmtree ( d ) | Context manager that creates a temporary directory and chdirs to it . | 48 | 14 |
227,684 | def in_directory ( filepath , dirpath ) : filepath = os . path . realpath ( filepath ) dirpath = os . path . realpath ( dirpath ) return filepath == dirpath or filepath . startswith ( os . path . join ( dirpath , "" ) ) | Returns a boolean for whether filepath is contained in dirpath . | 64 | 13 |
227,685 | def log_progress ( iterable , logger , batch_size = 10000 , progress_message = "Processing... ({})" , done_message = "Done! (Total: {})" , ) : i = 0 for x in iterable : yield x i += 1 if not i % batch_size : logger . info ( progress_message . format ( i ) ) logger . info ( done_message . format ( i ) ) | Log progress while iterating . | 91 | 6 |
227,686 | def login_url ( self , org = None ) : if org is None : org = self . org else : org = self . keychain . get_org ( org ) return org . start_url | Returns the login url which will automatically log into the target Salesforce org . By default the org_name passed to the library constructor is used but this can be overridden with the org option to log into a different org . | 43 | 45 |
227,687 | def run_task ( self , task_name , * * options ) : task_config = self . project_config . get_task ( task_name ) class_path = task_config . class_path logger . console ( "\n" ) task_class , task_config = self . _init_task ( class_path , options , task_config ) return self . _run_task ( task_class , task_config ) | Runs a named CumulusCI task for the current project with optional support for overriding task options via kwargs . | 94 | 24 |
227,688 | def run_task_class ( self , class_path , * * options ) : logger . console ( "\n" ) task_class , task_config = self . _init_task ( class_path , options , TaskConfig ( ) ) return self . _run_task ( task_class , task_config ) | Runs a CumulusCI task class with task options via kwargs . | 68 | 16 |
227,689 | def get_task ( self , name ) : config = getattr ( self , "tasks__{}" . format ( name ) ) if not config : raise TaskNotFoundError ( "Task not found: {}" . format ( name ) ) return TaskConfig ( config ) | Returns a TaskConfig | 58 | 4 |
227,690 | def get_flow ( self , name ) : config = getattr ( self , "flows__{}" . format ( name ) ) if not config : raise FlowNotFoundError ( "Flow not found: {}" . format ( name ) ) return FlowConfig ( config ) | Returns a FlowConfig | 57 | 4 |
227,691 | def render ( self ) : release_notes = [ ] for parser in self . parsers : parser_content = parser . render ( ) if parser_content is not None : release_notes . append ( parser_content ) return u"\r\n\r\n" . join ( release_notes ) | Returns the rendered release notes from all parsers as a string | 66 | 12 |
227,692 | def _update_release_content ( self , release , content ) : if release . body : new_body = [ ] current_parser = None is_start_line = False for parser in self . parsers : parser . replaced = False # update existing sections for line in release . body . splitlines ( ) : if current_parser : if current_parser . _is_end_line ( current_parser . _process_line ( line ) ) : parser_content = current_parser . render ( ) if parser_content : # replace existing section with new content new_body . append ( parser_content + "\r\n" ) current_parser = None for parser in self . parsers : if ( parser . _render_header ( ) . strip ( ) == parser . _process_line ( line ) . strip ( ) ) : parser . replaced = True current_parser = parser is_start_line = True break else : is_start_line = False if is_start_line : continue if current_parser : continue else : # preserve existing sections new_body . append ( line . strip ( ) ) # catch section without end line if current_parser : new_body . append ( current_parser . render ( ) ) # add new sections at bottom for parser in self . parsers : parser_content = parser . render ( ) if parser_content and not parser . replaced : new_body . append ( parser_content + "\r\n" ) content = u"\r\n" . join ( new_body ) return content | Merge existing and new release content . | 330 | 8 |
227,693 | def get_flow ( self , name , options = None ) : config = self . project_config . get_flow ( name ) callbacks = self . callback_class ( ) coordinator = FlowCoordinator ( self . project_config , config , name = name , options = options , skip = None , callbacks = callbacks , ) return coordinator | Get a primed and readytogo flow coordinator . | 74 | 10 |
227,694 | def _get_env ( self ) : env = { } for k , v in os . environ . items ( ) : k = k . decode ( ) if isinstance ( k , bytes ) else k v = v . decode ( ) if isinstance ( v , bytes ) else v env [ k ] = v return list ( env . items ( ) ) | loads the environment variables as unicode if ascii | 76 | 11 |
227,695 | def import_class ( path ) : components = path . split ( "." ) module = components [ : - 1 ] module = "." . join ( module ) mod = __import__ ( module , fromlist = [ native_str ( components [ - 1 ] ) ] ) return getattr ( mod , native_str ( components [ - 1 ] ) ) | Import a class from a string module class path | 75 | 9 |
227,696 | def parse_datetime ( dt_str , format ) : t = time . strptime ( dt_str , format ) return datetime ( t [ 0 ] , t [ 1 ] , t [ 2 ] , t [ 3 ] , t [ 4 ] , t [ 5 ] , t [ 6 ] , pytz . UTC ) | Create a timezone - aware datetime object from a datetime string . | 73 | 15 |
227,697 | def process_list_arg ( arg ) : if isinstance ( arg , list ) : return arg elif isinstance ( arg , basestring ) : args = [ ] for part in arg . split ( "," ) : args . append ( part . strip ( ) ) return args | Parse a string into a list separated by commas with whitespace stripped | 60 | 15 |
227,698 | def decode_to_unicode ( content ) : if content and not isinstance ( content , str ) : try : # Try to decode ISO-8859-1 to unicode return content . decode ( "ISO-8859-1" ) except UnicodeEncodeError : # Assume content is unicode already return content return content | decode ISO - 8859 - 1 to unicode when using sf api | 70 | 16 |
227,699 | def _find_or_create_version ( self , product ) : tag = self . options [ "tag" ] label = self . project_config . get_version_for_tag ( tag ) result = self . _call_api ( "GET" , "/versions" , params = { "product" : product [ "id" ] , "label" : label } ) if len ( result [ "data" ] ) == 0 : version = self . _call_api ( "POST" , "/versions" , json = { "product" : product [ "url" ] , "label" : label , "description" : self . options . get ( "description" , "" ) , "is_production" : True , "commit_ish" : tag , "is_listed" : False , } , ) self . logger . info ( "Created {}" . format ( version [ "url" ] ) ) else : version = result [ "data" ] [ 0 ] self . logger . info ( "Found {}" . format ( version [ "url" ] ) ) return version | Create a Version in MetaDeploy if it doesn t already exist | 232 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.