idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
33,900
def assert_raises_regex ( exception , regex , msg_fmt = "{msg}" ) : def test ( exc ) : compiled = re . compile ( regex ) if not exc . args : msg = "{} without message" . format ( exception . __name__ ) fail ( msg_fmt . format ( msg = msg , text = None , pattern = compiled . pattern , exc_type = exception , exc_name = e...
Fail unless an exception with a message that matches a regular expression is raised within the context .
33,901
def assert_raises_errno ( exception , errno , msg_fmt = "{msg}" ) : def check_errno ( exc ) : if errno != exc . errno : msg = "wrong errno: {!r} != {!r}" . format ( errno , exc . errno ) fail ( msg_fmt . format ( msg = msg , exc_type = exception , exc_name = exception . __name__ , expected_errno = errno , actual_errno ...
Fail unless an exception with a specific errno is raised with the context .
33,902
def assert_succeeds ( exception , msg_fmt = "{msg}" ) : class _AssertSucceeds ( object ) : def __enter__ ( self ) : pass def __exit__ ( self , exc_type , exc_val , exc_tb ) : if exc_type and issubclass ( exc_type , exception ) : msg = exception . __name__ + " was unexpectedly raised" fail ( msg_fmt . format ( msg = msg...
Fail if a specific exception is raised within the context .
33,903
def assert_warns_regex ( warning_type , regex , msg_fmt = "{msg}" ) : def test ( warning ) : return re . search ( regex , str ( warning . message ) ) is not None context = AssertWarnsRegexContext ( warning_type , regex , msg_fmt ) context . add_test ( test ) return context
Fail unless a warning with a message is issued inside the context .
33,904
def assert_json_subset ( first , second ) : if not isinstance ( second , ( dict , list , str , bytes ) ) : raise TypeError ( "second must be dict, list, str, or bytes" ) if isinstance ( second , bytes ) : second = second . decode ( "utf-8" ) if isinstance ( second , _Str ) : parsed_second = json_loads ( second ) else :...
Assert that a JSON object or array is a subset of another JSON object or array .
33,905
def get_data ( self , data_key , key = '' ) : flag = False extracted = self . get ( data_key , - 1 ) if extracted != - 1 : try : data , expired , noc , ncalls = self . _from_bytes ( extracted , key = key ) flag = True except ValueError : return None , flag if noc : ncalls += 1 self [ data_key ] = self . _to_bytes ( dat...
Get the data from the cache .
33,906
def encode_safely ( self , data ) : encoder = self . base_encoder result = settings . null try : result = encoder ( pickle . dumps ( data ) ) except : warnings . warn ( "Data could not be serialized." , RuntimeWarning ) return result
Encode the data .
33,907
def decode_safely ( self , encoded_data ) : decoder = self . base_decoder result = settings . null try : result = pickle . loads ( decoder ( encoded_data ) ) except : warnings . warn ( "Could not load and deserialize the data." , RuntimeWarning ) return result
Inverse for the encode_safely function .
33,908
def get_function_hash ( self , func , args = None , kwargs = None , ttl = None , key = None , noc = None ) : base_hash = settings . HASH_FUNCTION ( ) if PY3 : base_hash . update ( func . __name__ . encode ( settings . DEFAULT_ENCODING ) ) else : base_hash . update ( func . __name__ ) if args : for a in args : if PY3 : ...
Compute the hash of the function to be evaluated .
33,909
def to_bytes ( obj ) : if PY3 : if isinstance ( obj , str ) : return obj . encode ( settings . DEFAULT_ENCODING ) else : return obj if isinstance ( obj , bytes ) else b'' else : if isinstance ( obj , str ) : return obj else : return obj . encode ( settings . DEFAULT_ENCODING ) if isinstance ( obj , unicode ) else ''
Ensures that the obj is of byte - type .
33,910
def padding ( s , bs = AES . block_size ) : s = to_bytes ( s ) if len ( s ) % bs == 0 : res = s + b'' . join ( map ( to_bytes , [ random . SystemRandom ( ) . choice ( string . ascii_lowercase + string . digits ) for _ in range ( bs - 1 ) ] ) ) + to_bytes ( chr ( 96 - bs ) ) elif len ( s ) % bs > 0 and len ( s ) > bs : ...
Fills a bytes - like object with arbitrary symbols to make its length divisible by bs .
33,911
def stop ( self ) : self . _stop_thread . set ( ) with self . _lock : self . receive_socket . shutdown ( socket . SHUT_RDWR ) self . receive_socket . close ( ) self . send_socket . shutdown ( socket . SHUT_RDWR ) self . send_socket . close ( )
Called to stop the reveiver thread .
33,912
def send_code ( self , data , acknowledge = True ) : if "protocol" not in data : raise ValueError ( 'Pilight data to send does not contain a protocol info. ' 'Check the pilight-send doku!' , str ( data ) ) message = { "action" : "send" , "code" : data , } self . send_socket . sendall ( json . dumps ( message ) . encode...
Send a RF code known to the pilight - daemon .
33,913
def setup ( self ) : from simple_httpfs import HttpFs if not op . exists ( self . http_directory ) : os . makedirs ( self . http_directory ) if not op . exists ( self . https_directory ) : os . makedirs ( self . https_directory ) if not op . exists ( self . diskcache_directory ) : os . makedirs ( self . diskcache_direc...
Set up filesystem in user space for http and https so that we can retrieve tiles from remote sources .
33,914
def start ( self , log_file = "/tmp/hgserver.log" , log_level = logging . INFO ) : for puid in list ( self . processes . keys ( ) ) : print ( "terminating:" , puid ) self . processes [ puid ] . terminate ( ) del self . processes [ puid ] self . app = create_app ( self . tilesets , __name__ , log_file = log_file , log_l...
Start a lightweight higlass server .
33,915
def stop ( self ) : self . fuse_process . teardown ( ) for uuid in self . processes : self . processes [ uuid ] . terminate ( )
Stop this server so that the calling process can exit
33,916
def tileset_info ( self , uid ) : url = "http://{host}:{port}/api/v1/tileset_info/?d={uid}" . format ( host = self . host , port = self . port , uid = uid ) req = requests . get ( url ) if req . status_code != 200 : raise ServerError ( "Error fetching tileset_info:" , req . content ) content = json . loads ( req . cont...
Return the tileset info for the given tileset
33,917
def chromsizes ( self , uid ) : url = "http://{host}:{port}/api/v1/chrom-sizes/?id={uid}" . format ( host = self . host , port = self . port , uid = uid ) req = requests . get ( url ) if req . status_code != 200 : raise ServerError ( "Error fetching chromsizes:" , req . content ) return req . content
Return the chromosome sizes from the given filename
33,918
def display ( views , location_sync = [ ] , zoom_sync = [ ] , host = 'localhost' , server_port = None ) : from . server import Server from . client import ViewConf tilesets = [ ] for view in views : for track in view . tracks : if track . tracks : for track1 in track . tracks : if track1 . tileset : tilesets += [ track...
Instantiate a HiGlass display with the given views
33,919
def view ( tilesets ) : from . server import Server from . client import View curr_view = View ( ) server = Server ( ) server . start ( tilesets ) for ts in tilesets : if ( ts . track_type is not None and ts . track_position is not None ) : curr_view . add_track ( ts . track_type , ts . track_position , api_url = serve...
Create a higlass viewer that displays the specified tilesets
33,920
def change_attributes ( self , ** kwargs ) : new_track = Track ( self . viewconf [ 'type' ] ) new_track . position = self . position new_track . tileset = self . tileset new_track . viewconf = json . loads ( json . dumps ( self . viewconf ) ) new_track . viewconf = { ** new_track . viewconf , ** kwargs } return new_tra...
Change an attribute of this track and return a new copy .
33,921
def change_options ( self , ** kwargs ) : new_options = json . loads ( json . dumps ( self . viewconf [ 'options' ] ) ) new_options = { ** new_options , ** kwargs } return self . change_attributes ( options = new_options )
Change one of the track s options in the viewconf
33,922
def add_track ( self , * args , ** kwargs ) : new_track = Track ( * args , ** kwargs ) self . tracks = self . tracks + [ new_track ]
Add a track to a position .
33,923
def to_dict ( self ) : viewconf = json . loads ( json . dumps ( self . viewconf ) ) for track in self . tracks : if track . position is None : raise ValueError ( "Track has no position: {}" . format ( track . viewconf [ "type" ] ) ) viewconf [ "tracks" ] [ track . position ] += [ track . to_dict ( ) ] return viewconf
Convert the existing track to a JSON representation .
33,924
def add_view ( self , * args , ** kwargs ) : new_view = View ( * args , ** kwargs ) for view in self . views : if view . uid == new_view . uid : raise ValueError ( "View with this uid already exists" ) self . views += [ new_view ] return new_view
Add a new view
33,925
def _slugify ( string ) : words = re . split ( r'[\W]' , string ) clean_words = [ w for w in words if w != '' ] return '-' . join ( clean_words ) . lower ( )
This is not as good as a proper slugification function but the input space is limited
33,926
def slugify_argument ( func ) : @ six . wraps ( func ) def wrapped ( * args , ** kwargs ) : if "slugify" in kwargs and kwargs [ 'slugify' ] : return _slugify ( func ( * args , ** kwargs ) ) else : return func ( * args , ** kwargs ) return wrapped
Wraps a function that returns a string adding the slugify argument .
33,927
def capitalize_argument ( func ) : @ six . wraps ( func ) def wrapped ( * args , ** kwargs ) : if "capitalize" in kwargs and kwargs [ 'capitalize' ] : return func ( * args , ** kwargs ) . title ( ) else : return func ( * args , ** kwargs ) return wrapped
Wraps a function that returns a string adding the capitalize argument .
33,928
def datetime ( past = True , random = random ) : def year ( ) : if past : return random . choice ( range ( 1950 , 2005 ) ) else : return _datetime . datetime . now ( ) . year + random . choice ( range ( 1 , 50 ) ) def month ( ) : return random . choice ( range ( 1 , 12 ) ) def day ( ) : return random . choice ( range (...
Returns a random datetime from the past ... or the future!
33,929
def a_noun ( random = random , * args , ** kwargs ) : return inflectify . a ( noun ( random = random ) )
Return a noun but with an a in front of it . Or an an depending!
33,930
def plural ( random = random , * args , ** kwargs ) : return inflectify . plural ( random . choice ( nouns ) )
Return a plural noun .
33,931
def lastname ( random = random , * args , ** kwargs ) : types = [ "{noun}" , "{adjective}" , "{noun}{second_noun}" , "{adjective}{noun}" , "{adjective}{plural}" , "{noun}{verb}" , "{noun}{container}" , "{verb}{noun}" , "{adjective}{verb}" , "{noun}{adjective}" , "{noun}{firstname}" , "{noun}{title}" , "{adjective}{titl...
Return a first name!
33,932
def numberwang ( random = random , * args , ** kwargs ) : n = random . randint ( 2 , 150 ) return inflectify . number_to_words ( n )
Return a number that is spelled out .
33,933
def things ( random = random , * args , ** kwargs ) : return inflectify . join ( [ a_thing ( random = random ) , a_thing ( random = random ) , a_thing ( random = random ) ] )
Return a set of things .
33,934
def name ( random = random , * args , ** kwargs ) : if random . choice ( [ True , True , True , False ] ) : return firstname ( random = random ) + " " + lastname ( random = random ) elif random . choice ( [ True , False ] ) : return title ( random = random ) + " " + firstname ( random = random ) + " " + lastname ( rand...
Return someone s name
33,935
def domain ( random = random , * args , ** kwargs ) : words = random . choice ( [ noun ( random = random ) , thing ( random = random ) , adjective ( random = random ) + noun ( random = random ) , ] ) return _slugify ( words ) + tld ( random = random )
Return a domain
33,936
def email ( random = random , * args , ** kwargs ) : if 'name' in kwargs and kwargs [ 'name' ] : words = kwargs [ 'name' ] else : words = random . choice ( [ noun ( random = random ) , name ( random = random ) , name ( random = random ) + "+spam" , ] ) return _slugify ( words ) + "@" + domain ( random = random )
Return an e - mail address
33,937
def phone_number ( random = random , * args , ** kwargs ) : return random . choice ( [ '555-{number}{other_number}{number}{other_number}' , '1-604-555-{number}{other_number}{number}{other_number}' , '864-70-555-{number}{other_number}{number}{other_number}' , '867-5309' ] ) . format ( number = number ( random = random )...
Return a phone number
33,938
def sentence ( random = random , * args , ** kwargs ) : if 'name' in kwargs and kwargs [ 'name' ] : nm = kwargs ( name ) elif random . choice ( [ True , False , False ] ) : nm = name ( capitalize = True , random = random ) else : nm = random . choice ( people ) def type_one ( ) : return "{name} will {verb} {thing}." . ...
Return a whole sentence
33,939
def paragraph ( random = random , length = 10 , * args , ** kwargs ) : return " " . join ( [ sentence ( random = random ) for x in range ( 0 , length ) ] )
Produces a paragraph of text .
33,940
def markdown ( random = random , length = 10 , * args , ** kwargs ) : def title_sentence ( ) : return "\n" + "#" * random . randint ( 1 , 5 ) + " " + sentence ( capitalize = True , random = random ) def embellish ( word ) : return random . choice ( [ word , word , word , "**" + word + "**" , "_" + word + "_" ] ) def ra...
Produces a bunch of markdown text .
33,941
def company ( random = random , * args , ** kwargs ) : return random . choice ( [ "faculty of applied {noun}" , "{noun}{second_noun} studios" , "{noun}{noun}{noun} studios" , "{noun}shop" , "{noun} studies department" , "the law offices of {lastname}, {noun}, and {other_lastname}" , "{country} ministry of {plural}" , "...
Produce a company name
33,942
def country ( random = random , * args , ** kwargs ) : return random . choice ( [ "{country}" , "{direction} {country}" ] ) . format ( country = random . choice ( countries ) , direction = direction ( random = random ) )
Produce a country name
33,943
def city ( random = random , * args , ** kwargs ) : return random . choice ( [ "{direction} {noun}{city_suffix}" , "{noun}{city_suffix}" , "{adjective}{noun}{city_suffix}" , "{plural}{city_suffix}" , "{adjective}{city_suffix}" , "liver{noun}" , "birming{noun}" , "{noun}{city_suffix} {direction}" ] ) . format ( directio...
Produce a city name
33,944
def postal_code ( random = random , * args , ** kwargs ) : return random . choice ( [ "{letter}{number}{letter} {other_number}{other_letter}{other_number}" , "{number}{other_number}{number}{number}{other_number}" , "{number}{letter}{number}{other_number}{other_letter}" ] ) . format ( number = number ( random = random )...
Produce something that vaguely resembles a postal code
33,945
def street ( random = random , * args , ** kwargs ) : return random . choice ( [ "{noun} {street_type}" , "{adjective}{verb} {street_type}" , "{direction} {adjective}{verb} {street_type}" , "{direction} {noun} {street_type}" , "{direction} {lastname} {street_type}" , ] ) . format ( noun = noun ( random = random ) , las...
Produce something that sounds like a street name
33,946
def address ( random = random , * args , ** kwargs ) : return random . choice ( [ "{number}{other_number}{number}{other_number} {street}" , "{number}{other_number} {street}" , "{numberwang} {street}" , "apt {numberwang}, {number}{other_number}{other_number} {street}" , "apt {number}{other_number}{number}, {numberwang} ...
A street name plus a number!
33,947
def image ( random = random , width = 800 , height = 600 , https = False , * args , ** kwargs ) : target_fn = noun if width + height > 300 : target_fn = thing if width + height > 2000 : target_fn = sentence s = "" if https : s = "s" if random . choice ( [ True , False ] ) : return "http{s}://dummyimage.com/{width}x{hei...
Generate the address of a placeholder image .
33,948
def decode_copy_value ( value ) : if value == POSTGRES_COPY_NULL_VALUE : return None if '\\' not in value : return value return DECODE_REGEX . sub ( unescape_single_character , value )
Decodes value received as part of Postgres COPY command .
33,949
def unescape_single_character ( match ) : try : return DECODE_MAP [ match . group ( 0 ) ] except KeyError : value = match . group ( 0 ) if value == '\\' : raise ValueError ( "Unterminated escape sequence encountered" ) raise ValueError ( "Unrecognized escape sequence encountered: {}" . format ( value ) )
Unescape a single escape sequence found by regular expression .
33,950
def run ( url , output , config ) : parsed_url = urlparse . urlparse ( url ) db_module_path = SUPPORTED_DATABASE_MODULES . get ( parsed_url . scheme ) if not db_module_path : raise ValueError ( "Unsupported database scheme: '%s'" % ( parsed_url . scheme , ) ) db_module = importlib . import_module ( db_module_path ) ses...
Extracts database dump from given database URL and outputs sanitized copy of it into given stream .
33,951
def sanitize ( url , config ) : if url . scheme not in ( "postgres" , "postgresql" , "postgis" ) : raise ValueError ( "Unsupported database type: '%s'" % ( url . scheme , ) ) process = subprocess . Popen ( ( "pg_dump" , "--encoding=utf-8" , "--quote-all-identifiers" , "--dbname" , url . geturl ( ) . replace ( 'postgis:...
Obtains dump of an Postgres database by executing pg_dump command and sanitizes it s output .
33,952
def parse_column_names ( text ) : return tuple ( re . sub ( r"^\"(.*)\"$" , r"\1" , column_name . strip ( ) ) for column_name in text . split ( "," ) )
Extracts column names from a string containing quoted and comma separated column names .
33,953
def get_mysqldump_args_and_env_from_url ( url ) : args = [ "--complete-insert" , "--extended-insert" , "--net_buffer_length=10240" , "-h" , url . hostname , ] env = { } if url . port is not None : args . extend ( ( "-P" , six . text_type ( url . port ) ) ) if url . username : args . extend ( ( "-u" , url . username ) )...
Constructs list of command line arguments and dictionary of environment variables that can be given to mysqldump executable to obtain database dump of the database described in given URL .
33,954
def decode_mysql_literal ( text ) : if MYSQL_NULL_PATTERN . match ( text ) : return None if MYSQL_BOOLEAN_PATTERN . match ( text ) : return text . lower ( ) == "true" if MYSQL_FLOAT_PATTERN . match ( text ) : return float ( text ) if MYSQL_INT_PATTERN . match ( text ) : return int ( text ) if MYSQL_STRING_PATTERN . mat...
Attempts to decode given MySQL literal into Python value .
33,955
def decode_mysql_string_literal ( text ) : assert text . startswith ( "'" ) assert text . endswith ( "'" ) text = text [ 1 : - 1 ] return MYSQL_STRING_ESCAPE_SEQUENCE_PATTERN . sub ( unescape_single_character , text , )
Removes quotes and decodes escape sequences from given MySQL string literal returning the result .
33,956
def wait_for ( self , text , seconds ) : found = False stream = self . stream start_time = time . time ( ) while not found : if time . time ( ) - start_time > seconds : break stream . data_available . wait ( 0.5 ) stream . data_unoccupied . clear ( ) while stream . data : line = stream . data . pop ( 0 ) value = line ....
Returns True when the specified text has appeared in a line of the output or False when the specified number of seconds have passed without that occurring .
33,957
def command_executor ( self ) : ip_address = self . ip_address if self . ip_address else '127.0.0.1' return 'http://{}:{}/wd/hub' . format ( ip_address , self . port )
Get the appropriate command executor URL for the Selenium server running in the Docker container .
33,958
def start ( self ) : if self . container_id is not None : msg = 'The Docker container is already running with ID {}' raise Exception ( msg . format ( self . container_id ) ) process = Popen ( [ 'docker ps | grep ":{}"' . format ( self . port ) ] , shell = True , stdout = PIPE ) ( grep_output , _grep_error ) = process ....
Start the Docker container
33,959
def stop ( self ) : if self . container_id is None : raise Exception ( 'No Docker Selenium container was running' ) check_call ( [ 'docker' , 'stop' , self . container_id ] ) self . container_id = None
Stop the Docker container
33,960
def hash_text_to_ints ( value , bit_lengths = ( 16 , 16 , 16 , 16 ) ) : hash_value = hash_text ( value ) hex_lengths = [ x // 4 for x in bit_lengths ] hex_ranges = ( ( sum ( hex_lengths [ 0 : i ] ) , sum ( hex_lengths [ 0 : ( i + 1 ) ] ) ) for i in range ( len ( hex_lengths ) ) ) return tuple ( int ( hash_value [ a : b...
Hash a text value to a sequence of integers .
33,961
def hash_text ( value , hasher = hashlib . sha256 , encoding = 'utf-8' ) : return hash_bytes ( value . encode ( encoding ) , hasher )
Generate a hash for a text value .
33,962
def hash_bytes ( value , hasher = hashlib . sha256 ) : return hmac . new ( get_secret ( ) , value , hasher ) . hexdigest ( )
Generate a hash for a bytes value .
33,963
def _initialize_session ( ) : sys_random = random . SystemRandom ( ) _thread_local_storage . secret_key = b'' . join ( int2byte ( sys_random . randint ( 0 , 255 ) ) for _ in range ( SECRET_KEY_BITS // 8 ) )
Generate a new session key and store it to thread local storage .
33,964
def _get_proxy_object ( self , obj , ProxyKlass , proxy_klass_attribute ) : proxy_object = obj if not isinstance ( obj , ProxyKlass ) : proxy_object = ProxyKlass ( ** { proxy_klass_attribute : obj } ) return proxy_object
Returns the proxy object for an input object
33,965
def from_file ( cls , filename ) : instance = cls ( ) with open ( filename , "rb" ) as file_stream : config_data = yaml . load ( file_stream ) instance . load ( config_data ) return instance
Reads configuration from given path to a file in local file system and returns parsed version of it .
33,966
def load ( self , config_data ) : if not isinstance ( config_data , dict ) : raise ConfigurationError ( "Configuration data is %s instead of dict." % ( type ( config_data ) , ) ) self . load_addon_packages ( config_data ) self . load_sanitizers ( config_data )
Loads sanitizers according to rulesets defined in given already parsed configuration file .
33,967
def load_addon_packages ( self , config_data ) : section_config = config_data . get ( "config" ) if not isinstance ( section_config , dict ) : if section_config is None : return raise ConfigurationError ( "'config' is %s instead of dict" % ( type ( section_config ) , ) , ) section_addons = section_config . get ( "addon...
Loads the module paths from which the configuration will attempt to load sanitizers from . These must be stored as a list of strings under config . addons section of the configuration data .
33,968
def load_sanitizers ( self , config_data ) : section_strategy = config_data . get ( "strategy" ) if not isinstance ( section_strategy , dict ) : if section_strategy is None : return raise ConfigurationError ( "'strategy' is %s instead of dict" % ( type ( section_strategy ) , ) , ) for table_name , column_data in six . ...
Loads sanitizers possibly defined in the configuration under dictionary called strategy which should contain mapping of database tables with column names mapped into sanitizer function names .
33,969
def find_sanitizer ( self , name ) : name_parts = name . split ( "." ) if len ( name_parts ) < 2 : raise ConfigurationError ( "Unable to separate module name from function name in '%s'" % ( name , ) , ) module_name_suffix = "." . join ( name_parts [ : - 1 ] ) function_name = "sanitize_%s" % ( name_parts [ - 1 ] , ) mod...
Searches for a sanitizer function with given name . The name should contain two parts separated from each other with a dot the first part being the module name while the second being name of the function contained in the module when it s being prefixed with sanitize_ .
33,970
def find_sanitizer_from_module ( module_name , function_name ) : try : module = importlib . import_module ( module_name ) except ImportError : return None callback = getattr ( module , function_name , None ) if callback is None : return None if callable ( callback ) : return callback raise ConfigurationError ( "'%s' in...
Attempts to find sanitizer function from given module . If the module cannot be imported or function with given name does not exist in it nothing will be returned by this method . Otherwise the found sanitizer function will be returned .
33,971
def get_sanitizer_for ( self , table_name , column_name ) : sanitizer_key = "%s.%s" % ( table_name , column_name ) return self . sanitizers . get ( sanitizer_key )
Get sanitizer for given table and column name .
33,972
def sanitize ( self , table_name , column_name , value ) : sanitizer_callback = self . get_sanitizer_for ( table_name , column_name ) return sanitizer_callback ( value ) if sanitizer_callback else value
Sanitizes given value extracted from the database according to the sanitation configuration .
33,973
def add_arguments ( self , parser ) : test_command = TestCommand ( ) test_command . add_arguments ( parser ) for option in OPTIONS : parser . add_argument ( * option [ 0 ] , ** option [ 1 ] )
Command line arguments for Django 1 . 8 +
33,974
def clean ( ) : screenshot_dir = settings . SELENIUM_SCREENSHOT_DIR if screenshot_dir and os . path . isdir ( screenshot_dir ) : rmtree ( screenshot_dir , ignore_errors = True )
Clear out any old screenshots
33,975
def verify_appium_is_running ( self ) : process = Popen ( [ 'ps -e | grep "Appium"' ] , shell = True , stdout = PIPE ) ( grep_output , _grep_error ) = process . communicate ( ) lines = grep_output . split ( '\n' ) for line in lines : if 'Appium.app' in line : self . stdout . write ( 'Appium is already running' ) return...
Verify that Appium is running so it can be used for local iOS tests .
33,976
def save ( self , obj ) : if isinstance ( obj , self . np . ndarray ) and not obj . dtype . hasobject : if obj . shape == ( ) : obj_c_contiguous = obj . flatten ( ) elif obj . flags . c_contiguous : obj_c_contiguous = obj elif obj . flags . f_contiguous : obj_c_contiguous = obj . T else : obj_c_contiguous = obj . flatt...
Subclass the save method to hash ndarray subclass rather than pickling them . Off course this is a total abuse of the Pickler class .
33,977
def sanitize_random ( value ) : if not value : return value return '' . join ( random . choice ( CHARACTERS ) for _ in range ( len ( value ) ) )
Random string of same length as the given value .
33,978
def sanitize ( url , config ) : if url . scheme != "mysql" : raise ValueError ( "Unsupported database type: '%s'" % ( url . scheme , ) ) args , env = get_mysqldump_args_and_env_from_url ( url = url ) process = subprocess . Popen ( args = [ "mysqldump" ] + args , env = env , stdout = subprocess . PIPE , ) return sanitiz...
Obtains dump of MySQL database by executing mysqldump command and sanitizes it output .
33,979
def sanitize_from_stream ( stream , config ) : for line in io . TextIOWrapper ( stream , encoding = "utf-8" ) : line = line . rstrip ( "\n" ) if not config : yield line continue insert_into_match = INSERT_INTO_PATTERN . match ( line ) if not insert_into_match : yield line continue table_name = insert_into_match . group...
Reads dump of MySQL database from given stream and sanitizes it .
33,980
def parse_column_names ( text ) : return tuple ( re . sub ( r"^`(.*)`$" , r"\1" , column_data . strip ( ) ) for column_data in text . split ( "," ) )
Extracts column names from a string containing quoted and comma separated column names of a table .
33,981
def parse_values ( text ) : assert text . startswith ( "(" ) pos = 1 values = [ ] text_len = len ( text ) while pos < text_len : match = VALUE_PATTERN . match ( text , pos ) if not match : break value = match . group ( 1 ) values . append ( decode_mysql_literal ( value . strip ( ) ) ) pos += len ( value ) + 1 if match ...
Parses values from a string containing values from extended format INSERT INTO statement . Values will be yielded from the function as tuples with one tuple per row in the table .
33,982
def persist ( self ) : if self . hash : with open ( self . file_name , 'wb' ) as f : pickle . dump ( self . object_property , f ) return True return False
a private method that persists an object to the filesystem
33,983
def load ( self ) : if self . is_persisted : with open ( self . file_name , 'rb' ) as f : self . object_property = pickle . load ( f )
a private method that loads an object from the filesystem
33,984
def _switch_tz_offset_sql ( self , field_name , tzname ) : field_name = self . quote_name ( field_name ) if settings . USE_TZ : if pytz is None : from django . core . exceptions import ImproperlyConfigured raise ImproperlyConfigured ( "This query requires pytz, " "but it isn't installed." ) tz = pytz . timezone ( tznam...
Returns the SQL that will convert field_name to UTC from tzname .
33,985
def datetime_trunc_sql ( self , lookup_type , field_name , tzname ) : field_name = self . _switch_tz_offset_sql ( field_name , tzname ) reference_date = '0' if lookup_type in [ 'minute' , 'second' ] : reference_date = "CONVERT(datetime2, CONVERT(char(4), {field_name}, 112) + '0101', 112)" . format ( field_name = field_...
Given a lookup_type of year month day hour minute or second returns the SQL that truncates the given datetime field field_name to a datetime object with only the given specificity and a tuple of parameters .
33,986
def last_insert_id ( self , cursor , table_name , pk_name ) : table_name = self . quote_name ( table_name ) cursor . execute ( "SELECT CAST(IDENT_CURRENT(%s) as bigint)" , [ table_name ] ) return cursor . fetchone ( ) [ 0 ]
Given a cursor object that has just performed an INSERT statement into a table that has an auto - incrementing ID returns the newly created ID .
33,987
def quote_name ( self , name ) : if name . startswith ( self . left_sql_quote ) and name . endswith ( self . right_sql_quote ) : return name return '%s%s%s' % ( self . left_sql_quote , name , self . right_sql_quote )
Returns a quoted version of the given table index or column name . Does not quote the given name if it s already been quoted .
33,988
def last_executed_query ( self , cursor , sql , params ) : return super ( DatabaseOperations , self ) . last_executed_query ( cursor , cursor . last_sql , cursor . last_params )
Returns a string of the query last executed by the given cursor with placeholders replaced with actual values .
33,989
def adapt_datetimefield_value ( self , value ) : if value is None : return None if self . connection . _DJANGO_VERSION >= 14 and settings . USE_TZ : if timezone . is_aware ( value ) : value = value . astimezone ( timezone . utc ) if not self . connection . features . supports_microsecond_precision : value = value . rep...
Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns .
33,990
def adapt_timefield_value ( self , value ) : if value is None : return None if isinstance ( value , string_types ) : return datetime . datetime ( * ( time . strptime ( value , '%H:%M:%S' ) [ : 6 ] ) ) return datetime . datetime ( 1900 , 1 , 1 , value . hour , value . minute , value . second )
Transform a time value to an object compatible with what is expected by the backend driver for time columns .
33,991
def convert_values ( self , value , field ) : if value is None : return None if field and field . get_internal_type ( ) == 'DateTimeField' : if isinstance ( value , string_types ) and value : value = parse_datetime ( value ) return value elif field and field . get_internal_type ( ) == 'DateField' : if isinstance ( valu...
Coerce the value returned by the database backend into a consistent type that is compatible with the field type .
33,992
def _is_auto_field ( self , cursor , table_name , column_name ) : cursor . execute ( "SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')" , ( self . connection . ops . quote_name ( table_name ) , column_name ) ) return cursor . fetchall ( ) [ 0 ] [ 0 ]
Checks whether column is Identity
33,993
def get_table_description ( self , cursor , table_name , identity_check = True ) : columns = [ [ c [ 3 ] , c [ 4 ] , None , c [ 6 ] , c [ 6 ] , c [ 8 ] , c [ 10 ] ] for c in cursor . columns ( table = table_name ) ] items = [ ] for column in columns : if identity_check and self . _is_auto_field ( cursor , table_name , ...
Returns a description of the table with DB - API cursor . description interface .
33,994
def _break ( s , find ) : i = s . find ( find ) return s [ : i ] , s [ i : ]
Break a string s into the part before the substring to find and the part including and after the substring .
33,995
def _fix_aggregates ( self ) : try : select = self . query . annotation_select except AttributeError : select = self . query . aggregate_select for alias , aggregate in select . items ( ) : if not hasattr ( aggregate , 'sql_function' ) : continue if aggregate . sql_function == 'AVG' : select [ alias ] . sql_template = ...
MSSQL doesn t match the behavior of the other backends on a few of the aggregate functions ; different return type behavior different function names etc .
33,996
def _fix_slicing_order ( self , outer_fields , inner_select , order , inner_table_name ) : if order is None : meta = self . query . get_meta ( ) column = meta . pk . db_column or meta . pk . get_attname ( ) order = '{0}.{1} ASC' . format ( inner_table_name , self . connection . ops . quote_name ( column ) , ) else : al...
Apply any necessary fixes to the outer_fields inner_select and order strings due to slicing .
33,997
def _alias_columns ( self , sql ) : qn = self . connection . ops . quote_name outer = list ( ) inner = list ( ) names_seen = list ( ) paren_depth , paren_buf = 0 , [ '' ] parens , i = { } , 0 for ch in sql : if ch == '(' : i += 1 paren_depth += 1 paren_buf . append ( '' ) elif ch == ')' : paren_depth -= 1 key = '_place...
Return tuple of SELECT and FROM clauses aliasing duplicate column names .
33,998
def _fix_insert ( self , sql , params ) : meta = self . query . get_meta ( ) if meta . has_auto_field : if hasattr ( self . query , 'fields' ) : fields = self . query . fields auto_field = meta . auto_field else : fields = self . query . columns auto_field = meta . auto_field . db_column or meta . auto_field . column a...
Wrap the passed SQL with IDENTITY_INSERT statements and apply other necessary fixes .
33,999
def head ( line , n : int ) : global counter counter += 1 if counter > n : raise cbox . Stop ( ) return line
returns the first n lines