idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
52,900 | def dump_orm_object_as_insert_sql ( engine : Engine , obj : object , fileobj : TextIO ) -> None : insp = inspect ( obj ) meta = MetaData ( bind = engine ) table_name = insp . mapper . mapped_table . name table = Table ( table_name , meta , autoload = True ) query = select ( table . columns ) for orm_pkcol in insp . map... | Takes a SQLAlchemy ORM object and writes INSERT SQL to replicate it to the output file - like object . |
52,901 | def next ( self ) : d = None if self . _first_results : d = succeed ( EsUtils . extract_hits ( self . _first_results ) ) self . _first_results = None elif self . _scroll_id : d = self . _scroll_next_results ( ) else : raise StopIteration ( ) return d | Fetch next page from scroll API . |
52,902 | def reformat_python_docstrings ( top_dirs : List [ str ] , correct_copyright_lines : List [ str ] , show_only : bool = True , rewrite : bool = False , process_only_filenum : int = None ) -> None : filenum = 0 for top_dir in top_dirs : for dirpath , dirnames , filenames in walk ( top_dir ) : for filename in filenames : ... | Walk a directory finding Python files and rewriting them . |
52,903 | def _read_source ( self ) -> None : with open ( self . full_path , "rt" ) as f : for linenum , line_with_nl in enumerate ( f . readlines ( ) , start = 1 ) : line_without_newline = ( line_with_nl [ : - 1 ] if line_with_nl . endswith ( NL ) else line_with_nl ) if TAB in line_without_newline : self . _warn ( "Tab characte... | Reads the source file . |
52,904 | def _debug_line ( linenum : int , line : str , extramsg : str = "" ) -> None : log . critical ( "{}Line {}: {!r}" , extramsg , linenum , line ) | Writes a debugging report on a line . |
52,905 | def rewrite_file ( self ) -> None : if not self . needs_rewriting : return self . _info ( "Rewriting file" ) with open ( self . full_path , "w" ) as outfile : self . _write ( outfile ) | Rewrites the source file . |
52,906 | def _write ( self , destination : TextIO ) -> None : for line in self . dest_lines : destination . write ( line + NL ) | Writes the converted output to a destination . |
52,907 | def contains_duplicates ( values : Iterable [ Any ] ) -> bool : for v in Counter ( values ) . values ( ) : if v > 1 : return True return False | Does the iterable contain any duplicate values? |
52,908 | def index_list_for_sort_order ( x : List [ Any ] , key : Callable [ [ Any ] , Any ] = None , reverse : bool = False ) -> List [ int ] : def key_with_user_func ( idx_val : Tuple [ int , Any ] ) : return key ( idx_val [ 1 ] ) if key : sort_key = key_with_user_func else : sort_key = itemgetter ( 1 ) index_value_list = sor... | Returns a list of indexes of x IF x WERE TO BE SORTED . |
52,909 | def sort_list_by_index_list ( x : List [ Any ] , indexes : List [ int ] ) -> None : x [ : ] = [ x [ i ] for i in indexes ] | Re - orders x by the list of indexes of x in place . |
52,910 | def unique_list ( seq : Iterable [ Any ] ) -> List [ Any ] : seen = set ( ) seen_add = seen . add return [ x for x in seq if not ( x in seen or seen_add ( x ) ) ] | Returns a list of all the unique elements in the input list . |
52,911 | def escape_newlines ( s : str ) -> str : if not s : return s s = s . replace ( "\\" , r"\\" ) s = s . replace ( "\n" , r"\n" ) s = s . replace ( "\r" , r"\r" ) return s | Escapes CR LF and backslashes . |
52,912 | def escape_tabs_newlines ( s : str ) -> str : if not s : return s s = s . replace ( "\\" , r"\\" ) s = s . replace ( "\n" , r"\n" ) s = s . replace ( "\r" , r"\r" ) s = s . replace ( "\t" , r"\t" ) return s | Escapes CR LF tab and backslashes . |
52,913 | def validate_geotweet ( self , record ) : if record and self . _validate ( 'user' , record ) and self . _validate ( 'coordinates' , record ) : return True return False | check that stream record is actual tweet with coordinates |
52,914 | def contains ( ell , p , shell_only = False ) : v = augment ( p ) _ = ell . solve ( v ) return N . allclose ( _ , 0 ) if shell_only else _ <= 0 | Check to see whether point is inside conic . |
52,915 | def major_axes ( ell ) : _ = ell [ : - 1 , : - 1 ] U , s , V = N . linalg . svd ( _ ) scalar = - ( ell . sum ( ) - _ . sum ( ) ) return N . sqrt ( s * scalar ) * V | Gets major axes of ellipsoids |
52,916 | def translate ( conic , vector ) : T = N . identity ( len ( conic ) ) T [ : - 1 , - 1 ] = - vector return conic . transform ( T ) | Translates a conic by a vector |
52,917 | def pole ( conic , plane ) : v = dot ( N . linalg . inv ( conic ) , plane ) return v [ : - 1 ] / v [ - 1 ] | Calculates the pole of a polar plane for a given conic section . |
52,918 | def projection ( self , ** kwargs ) : viewpoint = kwargs . pop ( 'viewpoint' , None ) if viewpoint is None : ndim = self . shape [ 0 ] - 1 viewpoint = N . zeros ( ndim ) plane = self . polar_plane ( viewpoint ) return self . slice ( plane , ** kwargs ) | The elliptical cut of an ellipsoidal conic describing all points of tangency to the conic as viewed from the origin . |
52,919 | def guess_file_name_stream_type_header ( args ) : ftype = None fheader = None if isinstance ( args , ( tuple , list ) ) : if len ( args ) == 2 : fname , fstream = args elif len ( args ) == 3 : fname , fstream , ftype = args else : fname , fstream , ftype , fheader = args else : fname , fstream = guess_filename_stream (... | Guess filename file stream file type file header from args . |
52,920 | def encode_params ( self , data = None , ** kwargs ) : collection_format = kwargs . get ( "collection_format" , self . collection_format ) output_str = kwargs . get ( "output_str" , self . output_str ) sort = kwargs . get ( "sort" , self . sort ) if data is None : return "" , self . content_type elif isinstance ( data ... | Encode parameters in a piece of data . Will successfully encode parameters when passed as a dict or a list of 2 - tuples . Order is retained if data is a list of 2 - tuples but arbitrary if parameters are supplied as a dict . |
52,921 | def ci ( a , which = 95 , axis = None ) : p = 50 - which / 2 , 50 + which / 2 return percentiles ( a , p , axis ) | Return a percentile range from an array of values . |
52,922 | def get_config_string_option ( parser : ConfigParser , section : str , option : str , default : str = None ) -> str : if not parser . has_section ( section ) : raise ValueError ( "config missing section: " + section ) return parser . get ( section , option , fallback = default ) | Retrieves a string value from a parser . |
52,923 | def read_config_string_options ( obj : Any , parser : ConfigParser , section : str , options : Iterable [ str ] , default : str = None ) -> None : for o in options : setattr ( obj , o , get_config_string_option ( parser , section , o , default = default ) ) | Reads config options and writes them as attributes of obj with attribute names as per options . |
52,924 | def get_config_bool_option ( parser : ConfigParser , section : str , option : str , default : bool = None ) -> bool : if not parser . has_section ( section ) : raise ValueError ( "config missing section: " + section ) return parser . getboolean ( section , option , fallback = default ) | Retrieves a boolean value from a parser . |
52,925 | def get_config_parameter ( config : ConfigParser , section : str , param : str , fn : Callable [ [ Any ] , Any ] , default : Any ) -> Any : try : value = fn ( config . get ( section , param ) ) except ( TypeError , ValueError , NoOptionError ) : log . warning ( "Configuration variable {} not found or improper in sectio... | Fetch parameter from configparser . INI file . |
52,926 | def get_config_parameter_boolean ( config : ConfigParser , section : str , param : str , default : bool ) -> bool : try : value = config . getboolean ( section , param ) except ( TypeError , ValueError , NoOptionError ) : log . warning ( "Configuration variable {} not found or improper in section [{}]; " "using default... | Get Boolean parameter from configparser . INI file . |
52,927 | def is_definition ( cursor ) : defn = cursor . get_definition ( ) return ( defn is not None ) and ( cursor . location == defn . location ) | Test if a cursor refers to a definition |
52,928 | def asymptotes ( hyp , n = 1000 ) : assert N . linalg . norm ( hyp . center ( ) ) == 0 u = N . linspace ( 0 , 2 * N . pi , n ) _ = N . ones ( len ( u ) ) angles = N . array ( [ N . cos ( u ) , N . sin ( u ) , _ ] ) . T return dot ( angles , hyp [ : - 1 , : - 1 ] ) | Gets a cone of asymptotes for hyperbola |
52,929 | def pca_to_mapping ( pca , ** extra_props ) : from . axes import sampling_axes method = extra_props . pop ( 'method' , sampling_axes ) return dict ( axes = pca . axes . tolist ( ) , covariance = method ( pca ) . tolist ( ) , ** extra_props ) | A helper to return a mapping of a PCA result set suitable for reconstructing a planar error surface in other software packages |
52,930 | def generic_service_main ( cls : Type [ WindowsService ] , name : str ) -> None : argc = len ( sys . argv ) if argc == 1 : try : print ( "Trying to start service directly..." ) evtsrc_dll = os . path . abspath ( servicemanager . __file__ ) servicemanager . PrepareToHostSingle ( cls ) servicemanager . Initialize ( name ... | Call this from your command - line entry point to manage a service . |
52,931 | def fullname ( self ) -> str : fullname = "Process {}/{} ({})" . format ( self . procnum , self . nprocs , self . details . name ) if self . running : fullname += " (PID={})" . format ( self . process . pid ) return fullname | Description of the process . |
52,932 | def debug ( self , msg : str ) -> None : if self . debugging : s = "{}: {}" . format ( self . fullname , msg ) log . debug ( s ) | If we are being verbose write a debug message to the Python disk log . |
52,933 | def open_logs ( self ) -> None : if self . details . logfile_out : self . stdout = open ( self . details . logfile_out , 'a' ) else : self . stdout = None if self . details . logfile_err : if self . details . logfile_err == self . details . logfile_out : self . stderr = subprocess . STDOUT else : self . stderr = open (... | Open Python disk logs . |
52,934 | def close_logs ( self ) -> None : if self . stdout is not None : self . stdout . close ( ) self . stdout = None if self . stderr is not None and self . stderr != subprocess . STDOUT : self . stderr . close ( ) self . stderr = None | Close Python disk logs . |
52,935 | def start ( self ) -> None : if self . running : return self . info ( "Starting: {} (with logs stdout={}, stderr={})" . format ( self . details . procargs , self . details . logfile_out , self . details . logfile_err ) ) self . open_logs ( ) creationflags = CREATE_NEW_PROCESS_GROUP if WINDOWS else 0 self . process = su... | Starts a subprocess . Optionally routes its output to our disk logs . |
52,936 | def stop ( self ) -> None : if not self . running : return try : self . wait ( timeout_s = 0 ) except subprocess . TimeoutExpired : for kill_level in self . ALL_KILL_LEVELS : tried_to_kill = self . _terminate ( level = kill_level ) if tried_to_kill : try : self . wait ( timeout_s = self . kill_timeout_sec ) break excep... | Stops a subprocess . |
52,937 | def wait ( self , timeout_s : float = None ) -> int : if not self . running : return 0 retcode = self . process . wait ( timeout = timeout_s ) if retcode is None : self . error ( "Subprocess finished, but return code was None" ) retcode = 1 elif retcode == 0 : self . info ( "Subprocess finished cleanly (return code 0).... | Wait for up to timeout_s for the child process to finish . |
52,938 | def SvcStop ( self ) -> None : self . ReportServiceStatus ( win32service . SERVICE_STOP_PENDING ) win32event . SetEvent ( self . h_stop_event ) | Called when the service is being shut down . |
52,939 | def SvcDoRun ( self ) -> None : self . debug ( "Sending PYS_SERVICE_STARTED message" ) servicemanager . LogMsg ( servicemanager . EVENTLOG_INFORMATION_TYPE , servicemanager . PYS_SERVICE_STARTED , ( self . _svc_name_ , '' ) ) self . main ( ) servicemanager . LogMsg ( servicemanager . EVENTLOG_INFORMATION_TYPE , service... | Called when the service is started . |
52,940 | def run_processes ( self , procdetails : List [ ProcessDetails ] , subproc_run_timeout_sec : float = 1 , stop_event_timeout_ms : int = 1000 , kill_timeout_sec : float = 5 ) -> None : def cleanup ( ) : self . debug ( "atexit function called: cleaning up" ) for pmgr_ in self . process_managers : pmgr_ . stop ( ) atexit .... | Run multiple child processes . |
52,941 | def disable_bool_icon ( fieldname : str , model ) -> Callable [ [ Any ] , bool ] : def func ( self , obj ) : return getattr ( obj , fieldname ) func . boolean = False func . admin_order_field = fieldname func . short_description = model . _meta . get_field ( fieldname ) . verbose_name return func | Disable boolean icons for a Django ModelAdmin field . The _meta attribute is present on Django model classes and instances . |
52,942 | def admin_view_url ( admin_site : AdminSite , obj , view_type : str = "change" , current_app : str = None ) -> str : app_name = obj . _meta . app_label . lower ( ) model_name = obj . _meta . object_name . lower ( ) pk = obj . pk viewname = "admin:{}_{}_{}" . format ( app_name , model_name , view_type ) if current_app i... | Get a Django admin site URL for an object . |
52,943 | def admin_view_fk_link ( modeladmin : ModelAdmin , obj , fkfield : str , missing : str = "(None)" , use_str : bool = True , view_type : str = "change" , current_app : str = None ) -> str : if not hasattr ( obj , fkfield ) : return missing linked_obj = getattr ( obj , fkfield ) app_name = linked_obj . _meta . app_label ... | Get a Django admin site URL for an object that s found from a foreign key in our object of interest . |
52,944 | def lowpass_filter ( data : FLOATS_TYPE , sampling_freq_hz : float , cutoff_freq_hz : float , numtaps : int ) -> FLOATS_TYPE : coeffs = firwin ( numtaps = numtaps , cutoff = normalized_frequency ( cutoff_freq_hz , sampling_freq_hz ) , pass_zero = True ) filtered_data = lfilter ( b = coeffs , a = 1.0 , x = data ) return... | Apply a low - pass filter to the data . |
52,945 | def bandpass_filter ( data : FLOATS_TYPE , sampling_freq_hz : float , lower_freq_hz : float , upper_freq_hz : float , numtaps : int ) -> FLOATS_TYPE : f1 = normalized_frequency ( lower_freq_hz , sampling_freq_hz ) f2 = normalized_frequency ( upper_freq_hz , sampling_freq_hz ) coeffs = firwin ( numtaps = numtaps , cutof... | Apply a band - pass filter to the data . |
52,946 | def ellipse ( center , covariance_matrix , level = 1 , n = 1000 ) : U , s , rotation_matrix = N . linalg . svd ( covariance_matrix ) saxes = N . sqrt ( s ) * level u = N . linspace ( 0 , 2 * N . pi , n ) data = N . column_stack ( ( saxes [ 0 ] * N . cos ( u ) , saxes [ 1 ] * N . sin ( u ) ) ) return N . dot ( data , ro... | Returns error ellipse in slope - azimuth space |
52,947 | def to_mapping ( self , ** values ) : strike , dip , rake = self . strike_dip_rake ( ) min , max = self . angular_errors ( ) try : disabled = self . disabled except AttributeError : disabled = False mapping = dict ( uid = self . hash , axes = self . axes . tolist ( ) , hyperbolic_axes = self . hyperbolic_axes . tolist ... | Create a JSON - serializable representation of the plane that is usable with the javascript frontend |
52,948 | def run_multiple_processes ( args_list : List [ List [ str ] ] , die_on_failure : bool = True ) -> None : for procargs in args_list : start_process ( procargs ) wait_for_processes ( die_on_failure = die_on_failure ) | Fire up multiple processes and wait for them to finihs . |
52,949 | def run ( self ) -> None : fd = self . _fd encoding = self . _encoding line_terminators = self . _line_terminators queue = self . _queue buf = "" while True : try : c = fd . read ( 1 ) . decode ( encoding ) except UnicodeDecodeError as e : log . warning ( "Decoding error from {!r}: {!r}" , self . _cmdargs , e ) if self... | Read lines and put them on the queue . |
52,950 | def create_nation_fixtures ( self ) : SHP_SLUG = "cb_{}_us_state_500k" . format ( self . YEAR ) DOWNLOAD_PATH = os . path . join ( self . DOWNLOAD_DIRECTORY , SHP_SLUG ) shape = shapefile . Reader ( os . path . join ( DOWNLOAD_PATH , "{}.shp" . format ( SHP_SLUG ) ) ) fields = shape . fields [ 1 : ] field_names = [ f [... | Create national US and State Map |
52,951 | def serialize ( pca , ** kwargs ) : strike , dip , rake = pca . strike_dip_rake ( ) hyp_axes = sampling_axes ( pca ) return dict ( ** kwargs , principal_axes = pca . axes . tolist ( ) , hyperbolic_axes = hyp_axes . tolist ( ) , n_samples = pca . n , strike = strike , dip = dip , rake = rake , angular_errors = [ 2 * N .... | Serialize an orientation object to a dict suitable for JSON |
52,952 | def create_groups ( orientations , * groups , ** kwargs ) : grouped = [ ] if kwargs . pop ( 'copy' , True ) : orientations = [ copy ( o ) for o in orientations ] for o in orientations : o . member_of = None try : grouped += o . members for a in o . members : a . member_of = o except AttributeError : pass def find ( uid... | Create groups of an orientation measurement dataset |
52,953 | def logistic ( x : Union [ float , np . ndarray ] , k : float , theta : float ) -> Optional [ float ] : r if x is None or k is None or theta is None : return None return 1 / ( 1 + np . exp ( - k * ( x - theta ) ) ) | r Standard logistic function . |
52,954 | def _build_from_geojson ( self , src ) : geojson = json . loads ( self . read ( src ) ) idx = index . Index ( ) data_store = { } for i , feature in enumerate ( geojson [ 'features' ] ) : feature = self . _build_obj ( feature ) idx . insert ( i , feature [ 'geometry' ] . bounds ) data_store [ i ] = feature return data_s... | Build a RTree index to disk using bounding box of each feature |
52,955 | def get ( self , point , buffer_size = 0 , multiple = False ) : lon , lat = point geohash = Geohash . encode ( lat , lon , precision = self . precision ) key = ( geohash , buffer_size , multiple ) if key in self . geohash_cache : self . hit += 1 return self . geohash_cache [ key ] self . miss += 1 lat , lon = Geohash .... | lookup state and county based on geohash of coordinates from tweet |
52,956 | def run ( in_file_nose , out_dir_unitth ) : suites = Converter . read_nose ( in_file_nose ) Converter . write_unitth ( suites , out_dir_unitth ) | Convert nose - style test reports to UnitTH - style test reports by splitting modules into separate XML files |
52,957 | def read_nose ( in_file ) : suites = { } doc_xml = minidom . parse ( in_file ) suite_xml = doc_xml . getElementsByTagName ( "testsuite" ) [ 0 ] for case_xml in suite_xml . getElementsByTagName ( 'testcase' ) : classname = case_xml . getAttribute ( 'classname' ) if classname not in suites : suites [ classname ] = [ ] ca... | Parse nose - style test reports into a dict |
52,958 | def write_unitth ( suites , out_dir ) : if not os . path . isdir ( out_dir ) : os . mkdir ( out_dir ) for classname , cases in suites . items ( ) : doc_xml = minidom . Document ( ) suite_xml = doc_xml . createElement ( 'testsuite' ) suite_xml . setAttribute ( 'name' , classname ) suite_xml . setAttribute ( 'tests' , st... | Write UnitTH - style test reports |
52,959 | def error_asymptotes ( pca , ** kwargs ) : ax = kwargs . pop ( "ax" , current_axes ( ) ) lon , lat = pca . plane_errors ( 'upper' , n = 1000 ) ax . plot ( lon , lat , '-' ) lon , lat = pca . plane_errors ( 'lower' , n = 1000 ) ax . plot ( lon , lat , '-' ) ax . plane ( * pca . strike_dip ( ) ) | Plots asymptotic error bounds for hyperbola on a stereonet . |
52,960 | def fetch_all_first_values ( session : Session , select_statement : Select ) -> List [ Any ] : rows = session . execute ( select_statement ) try : return [ row [ 0 ] for row in rows ] except ValueError as e : raise MultipleResultsFound ( str ( e ) ) | Returns a list of the first values in each row returned by a SELECT query . |
52,961 | def hyperbola ( axes , ** kwargs ) : opens_up = kwargs . pop ( 'opens_up' , True ) center = kwargs . pop ( 'center' , defaults [ 'center' ] ) th = N . linspace ( 0 , 2 * N . pi , kwargs . pop ( 'n' , 500 ) ) vals = [ N . tan ( th ) , 1 / N . cos ( th ) ] if not opens_up : vals = vals [ : : - 1 ] x = axes [ 0 ] * vals [... | Plots a hyperbola that opens along y axis |
52,962 | def __reverse_ellipse ( axes , scalar = 1 ) : ax1 = axes . copy ( ) [ : : - 1 ] * scalar center = ax1 [ 1 ] * N . sqrt ( 2 ) * scalar return ax1 , center | This method doesn t work as well |
52,963 | def if_sqlserver_disable_constraints ( session : SqlASession , tablename : str ) -> None : engine = get_engine_from_session ( session ) if is_sqlserver ( engine ) : quoted_tablename = quote_identifier ( tablename , engine ) session . execute ( "ALTER TABLE {} NOCHECK CONSTRAINT all" . format ( quoted_tablename ) ) yiel... | If we re running under SQL Server disable constraint checking for the specified table while the resource is held . |
52,964 | def if_sqlserver_disable_constraints_triggers ( session : SqlASession , tablename : str ) -> None : with if_sqlserver_disable_constraints ( session , tablename ) : with if_sqlserver_disable_triggers ( session , tablename ) : yield | If we re running under SQL Server disable triggers AND constraints for the specified table while the resource is held . |
52,965 | def get_current_revision ( database_url : str , version_table : str = DEFAULT_ALEMBIC_VERSION_TABLE ) -> str : engine = create_engine ( database_url ) conn = engine . connect ( ) opts = { 'version_table' : version_table } mig_context = MigrationContext . configure ( conn , opts = opts ) return mig_context . get_current... | Ask the database what its current revision is . |
52,966 | def upgrade_database ( alembic_config_filename : str , alembic_base_dir : str = None , starting_revision : str = None , destination_revision : str = "head" , version_table : str = DEFAULT_ALEMBIC_VERSION_TABLE , as_sql : bool = False ) -> None : if alembic_base_dir is None : alembic_base_dir = os . path . dirname ( ale... | Use Alembic to upgrade our database . |
52,967 | def stamp_allowing_unusual_version_table ( config : Config , revision : str , sql : bool = False , tag : str = None , version_table : str = DEFAULT_ALEMBIC_VERSION_TABLE ) -> None : script = ScriptDirectory . from_config ( config ) starting_rev = None if ":" in revision : if not sql : raise CommandError ( "Range revisi... | Stamps the Alembic version table with the given revision ; don t run any migrations . |
52,968 | def get_external_command_output ( command : str ) -> bytes : args = shlex . split ( command ) ret = subprocess . check_output ( args ) return ret | Takes a command - line command executes it and returns its stdout output . |
52,969 | def get_pipe_series_output ( commands : Sequence [ str ] , stdinput : BinaryIO = None ) -> bytes : processes = [ ] for i in range ( len ( commands ) ) : if i == 0 : processes . append ( subprocess . Popen ( shlex . split ( commands [ i ] ) , stdin = subprocess . PIPE , stdout = subprocess . PIPE ) ) else : processes . ... | Get the output from a piped series of commands . |
52,970 | def launch_external_file ( filename : str , raise_if_fails : bool = False ) -> None : log . info ( "Launching external file: {!r}" , filename ) try : if sys . platform . startswith ( 'linux' ) : cmdargs = [ "xdg-open" , filename ] subprocess . call ( cmdargs ) else : os . startfile ( filename ) except Exception as e : ... | Launches a file using the operating system s standard launcher . |
52,971 | def make_mysql_url ( username : str , password : str , dbname : str , driver : str = "mysqldb" , host : str = "localhost" , port : int = 3306 , charset : str = "utf8" ) -> str : return "mysql+{driver}://{u}:{p}@{host}:{port}/{db}?charset={cs}" . format ( driver = driver , host = host , port = port , db = dbname , u = u... | Makes an SQLAlchemy URL for a MySQL database . |
52,972 | def make_sqlite_url ( filename : str ) -> str : absfile = os . path . abspath ( filename ) return "sqlite://{host}/{path}" . format ( host = "" , path = absfile ) | Makes an SQLAlchemy URL for a SQLite database . |
52,973 | def atoi ( text : str ) -> Union [ int , str ] : return int ( text ) if text . isdigit ( ) else text | Converts strings to integers if they re composed of digits ; otherwise returns the strings unchanged . One way of sorting strings with numbers ; it will mean that 11 is more than 2 . |
52,974 | def _get_pretty_body ( headers , body ) : try : if CONTENT_TYPE_HEADER_NAME in headers : if XMLRenderer . DEFAULT_CONTENT_TYPE == headers [ CONTENT_TYPE_HEADER_NAME ] : xml_parsed = parseString ( body ) pretty_xml_as_string = xml_parsed . toprettyxml ( ) return pretty_xml_as_string elif JSONRenderer . DEFAULT_CONTENT_T... | Return a pretty printed body using the Content - Type header information . |
52,975 | def log_print_request ( method , url , query_params = None , headers = None , body = None ) : log_msg = '\n>>>>>>>>>>>>>>>>>>>>> Request >>>>>>>>>>>>>>>>>>> \n' log_msg += '\t> Method: %s\n' % method log_msg += '\t> Url: %s\n' % url if query_params is not None : log_msg += '\t> Query params: {}\n' . format ( str ( quer... | Log an HTTP request data in a user - friendly representation . |
52,976 | def log_print_response ( status_code , response , headers = None ) : log_msg = '\n<<<<<<<<<<<<<<<<<<<<<< Response <<<<<<<<<<<<<<<<<<\n' log_msg += '\t< Response code: {}\n' . format ( str ( status_code ) ) if headers is not None : log_msg += '\t< Headers:\n{}\n' . format ( json . dumps ( dict ( headers ) , sort_keys = ... | Log an HTTP response data in a user - friendly representation . |
52,977 | def args_kwargs_to_initdict ( args : ArgsList , kwargs : KwargsDict ) -> InitDict : return { ARGS_LABEL : args , KWARGS_LABEL : kwargs } | Converts a set of args and kwargs to an InitDict . |
52,978 | def strip_leading_underscores_from_keys ( d : Dict ) -> Dict : newdict = { } for k , v in d . items ( ) : if k . startswith ( '_' ) : k = k [ 1 : ] if k in newdict : raise ValueError ( "Attribute conflict: _{k}, {k}" . format ( k = k ) ) newdict [ k ] = v return newdict | Clones a dictionary removing leading underscores from key names . Raises ValueError if this causes an attribute conflict . |
52,979 | def verify_initdict ( initdict : InitDict ) -> None : if ( not isinstance ( initdict , dict ) or ARGS_LABEL not in initdict or KWARGS_LABEL not in initdict ) : raise ValueError ( "Not an InitDict dictionary" ) | Ensures that its parameter is a proper InitDict or raises ValueError . |
52,980 | def register_class_for_json ( cls : ClassType , method : str = METHOD_SIMPLE , obj_to_dict_fn : InstanceToDictFnType = None , dict_to_obj_fn : DictToInstanceFnType = initdict_to_instance , default_factory : DefaultFactoryFnType = None ) -> None : typename = cls . __qualname__ if obj_to_dict_fn and dict_to_obj_fn : desc... | Registers the class cls for JSON serialization . |
52,981 | def register_for_json ( * args , ** kwargs ) -> Any : if DEBUG : print ( "register_for_json: args = {}" . format ( repr ( args ) ) ) print ( "register_for_json: kwargs = {}" . format ( repr ( kwargs ) ) ) if len ( args ) == 1 and len ( kwargs ) == 0 and callable ( args [ 0 ] ) : if DEBUG : print ( "... called as @regis... | Class decorator to register classes with our JSON system . |
52,982 | def dump_map ( file : TextIO = sys . stdout ) -> None : pp = pprint . PrettyPrinter ( indent = 4 , stream = file ) print ( "Type map: " , file = file ) pp . pprint ( TYPE_MAP ) | Prints the JSON registered types map to the specified file . |
52,983 | def json_class_decoder_hook ( d : Dict ) -> Any : if TYPE_LABEL in d : typename = d . get ( TYPE_LABEL ) if typename in TYPE_MAP : if DEBUG : log . debug ( "Deserializing: {!r}" , d ) d . pop ( TYPE_LABEL ) descriptor = TYPE_MAP [ typename ] obj = descriptor . to_obj ( d ) if DEBUG : log . debug ( "... to: {!r}" , obj ... | Provides a JSON decoder that converts dictionaries to Python objects if suitable methods are found in our TYPE_MAP . |
52,984 | def json_encode ( obj : Instance , ** kwargs ) -> str : return json . dumps ( obj , cls = JsonClassEncoder , ** kwargs ) | Encodes an object to JSON using our custom encoder . |
52,985 | def json_decode ( s : str ) -> Any : try : return json . JSONDecoder ( object_hook = json_class_decoder_hook ) . decode ( s ) except json . JSONDecodeError : log . warning ( "Failed to decode JSON (returning None): {!r}" , s ) return None | Decodes an object from JSON using our custom decoder . |
52,986 | def dict_to_enum_fn ( d : Dict [ str , Any ] , enum_class : Type [ Enum ] ) -> Enum : return enum_class [ d [ 'name' ] ] | Converts an dict to a Enum . |
52,987 | def dict_to_pendulum ( d : Dict [ str , Any ] , pendulum_class : ClassType ) -> DateTime : return pendulum . parse ( d [ 'iso' ] ) | Converts a dict object back to a Pendulum . |
52,988 | def dict_to_pendulumdate ( d : Dict [ str , Any ] , pendulumdate_class : ClassType ) -> Date : return pendulum . parse ( d [ 'iso' ] ) . date ( ) | Converts a dict object back to a pendulum . Date . |
52,989 | def simple_eq ( one : Instance , two : Instance , attrs : List [ str ] ) -> bool : return all ( getattr ( one , a ) == getattr ( two , a ) for a in attrs ) | Test if two objects are equal based on a comparison of the specified attributes attrs . |
52,990 | def writelines_nl ( fileobj : TextIO , lines : Iterable [ str ] ) -> None : fileobj . write ( '\n' . join ( lines ) + '\n' ) | Writes lines plus terminating newline characters to the file . |
52,991 | def write_text ( filename : str , text : str ) -> None : with open ( filename , 'w' ) as f : print ( text , file = f ) | Writes text to a file . |
52,992 | def gen_textfiles_from_filenames ( filenames : Iterable [ str ] ) -> Generator [ TextIO , None , None ] : for filename in filenames : with open ( filename ) as f : yield f | Generates file - like objects from a list of filenames . |
52,993 | def gen_lines_from_textfiles ( files : Iterable [ TextIO ] ) -> Generator [ str , None , None ] : for file in files : for line in file : yield line | Generates lines from file - like objects . |
52,994 | def gen_lines_from_binary_files ( files : Iterable [ BinaryIO ] , encoding : str = UTF8 ) -> Generator [ str , None , None ] : for file in files : for byteline in file : line = byteline . decode ( encoding ) . strip ( ) yield line | Generates lines from binary files . Strips out newlines . |
52,995 | def gen_part_from_line ( lines : Iterable [ str ] , part_index : int , splitter : str = None ) -> Generator [ str , None , None ] : for line in lines : parts = line . split ( splitter ) yield parts [ part_index ] | Splits lines with splitter and yields a specified part by index . |
52,996 | def gen_rows_from_csv_binfiles ( csv_files : Iterable [ BinaryIO ] , encoding : str = UTF8 , skip_header : bool = False , ** csv_reader_kwargs ) -> Generator [ Iterable [ str ] , None , None ] : dialect = csv_reader_kwargs . pop ( 'dialect' , None ) for csv_file_bin in csv_files : csv_file = io . TextIOWrapper ( csv_fi... | Iterate through binary file - like objects that are CSV files in a specified encoding . Yield each row . |
52,997 | def webify_file ( srcfilename : str , destfilename : str ) -> None : with open ( srcfilename ) as infile , open ( destfilename , 'w' ) as ofile : for line_ in infile : ofile . write ( escape ( line_ ) ) | Rewrites a file from srcfilename to destfilename HTML - escaping it in the process . |
52,998 | def replace_in_file ( filename : str , text_from : str , text_to : str ) -> None : log . info ( "Amending {}: {} -> {}" , filename , repr ( text_from ) , repr ( text_to ) ) with open ( filename ) as infile : contents = infile . read ( ) contents = contents . replace ( text_from , text_to ) with open ( filename , 'w' ) ... | Replaces text in a file . |
52,999 | def is_line_in_file ( filename : str , line : str ) -> bool : assert "\n" not in line with open ( filename , "r" ) as file : for fileline in file : if fileline == line : return True return False | Detects whether a line is present within a file . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.