idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
31,500 | def get_handler ( self , options ) : handler_module = import_module ( sources [ options [ self . _source_param ] ] , self . _package_name ) return handler_module . CurrencyHandler ( self . log ) | Return the specified handler |
31,501 | def check_rates ( self , rates , base ) : if "rates" not in rates : raise RuntimeError ( "%s: 'rates' not found in results" % self . name ) if "base" not in rates or rates [ "base" ] != base or base not in rates [ "rates" ] : self . log ( logging . WARNING , "%s: 'base' not found in results" , self . name ) self . rate... | Local helper function for validating rates response |
31,502 | def get_ratefactor ( self , base , code ) : self . get_latestcurrencyrates ( base ) try : ratefactor = self . rates [ "rates" ] [ code ] except KeyError : raise RuntimeError ( "%s: %s not found" % ( self . name , code ) ) if base == self . base : return ratefactor else : return self . ratechangebase ( ratefactor , self... | Return the Decimal currency exchange rate factor of code compared to 1 base unit or RuntimeError |
31,503 | def get_currencysymbol ( self , code ) : if not self . _symbols : symbolpath = os . path . join ( self . _dir , 'currencies.json' ) with open ( symbolpath , encoding = 'utf8' ) as df : self . _symbols = json . load ( df ) return self . _symbols . get ( code ) | Retrieve the currency symbol from the local file |
31,504 | def ratechangebase ( self , ratefactor , current_base , new_base ) : if self . _multiplier is None : self . log ( logging . WARNING , "CurrencyHandler: changing base ourselves" ) if Decimal ( 1 ) != self . get_ratefactor ( current_base , current_base ) : raise RuntimeError ( "CurrencyHandler: current baserate: %s not 1... | Local helper function for changing currency base returns new rate in new base Defaults to ROUND_HALF_EVEN |
31,505 | def disallowed_table ( * tables ) : return not bool ( settings . WHITELIST . issuperset ( tables ) ) if settings . WHITELIST else bool ( settings . BLACKLIST . intersection ( tables ) ) | Returns True if a set of tables is in the blacklist or if a whitelist is set any of the tables is not in the whitelist . False otherwise . |
31,506 | def invalidate ( * tables , ** kwargs ) : backend = get_backend ( ) db = kwargs . get ( 'using' , 'default' ) if backend . _patched : for t in map ( resolve_table , tables ) : backend . keyhandler . invalidate_table ( t , db ) | Invalidate the current generation for one or more tables . The arguments can be either strings representing database table names or models . Pass in kwarg using to set the database . |
31,507 | def gen_key ( self , * values ) : key = md5 ( ) KeyGen . _recursive_convert ( values , key ) return key . hexdigest ( ) | Generate a key from one or more values . |
31,508 | def get_generation ( self , * tables , ** kwargs ) : db = kwargs . get ( 'db' , 'default' ) if len ( tables ) > 1 : return self . get_multi_generation ( tables , db ) return self . get_single_generation ( tables [ 0 ] , db ) | Get the generation key for any number of tables . |
31,509 | def get_single_generation ( self , table , db = 'default' ) : key = self . keygen . gen_table_key ( table , db ) val = self . cache_backend . get ( key , None , db ) if val is None : val = self . keygen . random_generator ( ) self . cache_backend . set ( key , val , settings . MIDDLEWARE_SECONDS , db ) return val | Creates a random generation value for a single table name |
31,510 | def get_multi_generation ( self , tables , db = 'default' ) : generations = [ ] for table in tables : generations . append ( self . get_single_generation ( table , db ) ) key = self . keygen . gen_multi_key ( generations , db ) val = self . cache_backend . get ( key , None , db ) if val is None : val = self . keygen . ... | Takes a list of table names and returns an aggregate value for the generation |
31,511 | def sql_key ( self , generation , sql , params , order , result_type , using = 'default' ) : suffix = self . keygen . gen_key ( sql , params , order , result_type ) using = settings . DB_CACHE_KEYS [ using ] return '%s_%s_query_%s.%s' % ( self . prefix , using , generation , suffix ) | Return the specific cache key for the sql query described by the pieces of the query and the generation key . |
31,512 | def unpatch ( self ) : if not self . _patched : return for func in self . _read_compilers + self . _write_compilers : func . execute_sql = self . _original [ func ] self . cache_backend . unpatch ( ) self . _patched = False | un - applies this patch . |
31,513 | def memoize_nullary ( f ) : def func ( ) : if not hasattr ( func , 'retval' ) : func . retval = f ( ) return func . retval return func | Memoizes a function that takes no arguments . The memoization lasts only as long as we hold a reference to the returned function . |
31,514 | def currency_context ( context ) : request = context [ 'request' ] currency_code = memoize_nullary ( lambda : get_currency_code ( request ) ) context [ 'CURRENCIES' ] = Currency . active . all ( ) context [ 'CURRENCY_CODE' ] = currency_code context [ 'CURRENCY' ] = memoize_nullary ( lambda : get_currency ( currency_cod... | Use instead of context processor Context variables are only valid within the block scope |
31,515 | def currencies ( self ) : try : resp = self . client . get ( self . ENDPOINT_CURRENCIES ) except requests . exceptions . RequestException as e : raise OpenExchangeRatesClientException ( e ) return resp . json ( ) | Fetches current currency data of the service |
31,516 | def historical ( self , date , base = 'USD' ) : try : resp = self . client . get ( self . ENDPOINT_HISTORICAL % date . strftime ( "%Y-%m-%d" ) , params = { 'base' : base } ) resp . raise_for_status ( ) except requests . exceptions . RequestException as e : raise OpenExchangeRatesClientException ( e ) return resp . json... | Fetches historical exchange rate data from service |
31,517 | def calculate ( price , to_code , ** kwargs ) : qs = kwargs . get ( 'qs' , get_active_currencies_qs ( ) ) kwargs [ 'qs' ] = qs default_code = qs . default ( ) . code return convert ( price , default_code , to_code , ** kwargs ) | Converts a price in the default currency to another currency |
31,518 | def convert ( amount , from_code , to_code , decimals = 2 , qs = None ) : if from_code == to_code : return amount if qs is None : qs = get_active_currencies_qs ( ) from_ , to = qs . get ( code = from_code ) , qs . get ( code = to_code ) amount = D ( amount ) * ( to . factor / from_ . factor ) return price_rounding ( am... | Converts from any currency to any currency |
31,519 | def price_rounding ( price , decimals = 2 ) : try : exponent = D ( '.' + decimals * '0' ) except InvalidOperation : exponent = D ( ) return price . quantize ( exponent , rounding = ROUND_UP ) | Takes a decimal price and rounds to a number of decimal places |
31,520 | def get_currencies ( self ) : try : resp = get ( self . endpoint ) resp . raise_for_status ( ) except exceptions . RequestException as e : self . log ( logging . ERROR , "%s: Problem whilst contacting endpoint:\n%s" , self . name , e ) else : with open ( self . _cached_currency_file , 'wb' ) as fd : fd . write ( resp .... | Downloads xml currency data or if not available tries to use cached file copy |
31,521 | def _check_doc ( self , root ) : if ( root . tag != 'ISO_4217' or root [ 0 ] . tag != 'CcyTbl' or root [ 0 ] [ 0 ] . tag != 'CcyNtry' or not root . attrib [ 'Pblshd' ] or len ( root [ 0 ] ) < 270 ) : raise TypeError ( "%s: XML %s appears to be invalid" % ( self . name , self . _cached_currency_file ) ) return datetime ... | Validates the xml tree and returns the published date |
31,522 | def get_allcurrencycodes ( self ) : foundcodes = [ ] codeelements = self . currencies [ 0 ] . iter ( 'Ccy' ) for codeelement in codeelements : code = codeelement . text if code not in foundcodes : foundcodes += [ code ] yield code | Return an iterable of distinct 3 character ISO 4217 currency codes |
31,523 | def celery_enable_all ( ) : from celery . signals import task_prerun , task_postrun , task_failure task_prerun . connect ( prerun_handler ) task_postrun . connect ( postrun_handler ) task_failure . connect ( postrun_handler ) | Enable johnny - cache in all celery tasks clearing the local - store after each task . |
31,524 | def celery_task_wrapper ( f ) : from celery . utils import fun_takes_kwargs @ wraps ( f , assigned = available_attrs ( f ) ) def newf ( * args , ** kwargs ) : backend = get_backend ( ) was_patched = backend . _patched get_backend ( ) . patch ( ) supported_keys = fun_takes_kwargs ( f , kwargs ) new_kwargs = dict ( ( key... | Provides a task wrapper for celery that sets up cache and ensures that the local store is cleared after completion |
31,525 | def _get_backend ( ) : enabled = [ n for n , c in sorted ( CACHES . items ( ) ) if c . get ( 'JOHNNY_CACHE' , False ) ] if len ( enabled ) > 1 : warn ( "Multiple caches configured for johnny-cache; using %s." % enabled [ 0 ] ) if enabled : return get_cache ( enabled [ 0 ] ) if CACHE_BACKEND : backend = get_cache ( CACH... | Returns the actual django cache object johnny is configured to use . This relies on the settings only ; the actual active cache can theoretically be changed at runtime . |
31,526 | def add_arguments ( self , parser ) : parser . add_argument ( self . _source_param , ** self . _source_kwargs ) parser . add_argument ( '--base' , '-b' , action = 'store' , help = 'Supply the base currency as code or a settings variable name. ' 'The default is taken from settings CURRENCIES_BASE or SHOP_DEFAULT_CURRENC... | Add command arguments |
31,527 | def get_base ( self , option ) : if option : if option . isupper ( ) : if len ( option ) > 3 : return getattr ( settings , option ) , True elif len ( option ) == 3 : return option , True raise ImproperlyConfigured ( "Invalid currency code found: %s" % option ) for attr in ( 'CURRENCIES_BASE' , 'SHOP_DEFAULT_CURRENCY' )... | Parse the base command option . Can be supplied as a 3 character code or a settings variable name If base is not supplied looks for settings CURRENCIES_BASE and SHOP_DEFAULT_CURRENCY |
31,528 | def set ( self , key , val , timeout = None , using = None ) : if timeout is None : timeout = self . timeout if self . is_managed ( using = using ) and self . _patched_var : self . local [ key ] = val else : self . cache_backend . set ( key , val , timeout ) | Set will be using the generational key so if another thread bumps this key the localstore version will still be invalid . If the key is bumped during a transaction it will be new to the global cache on commit so it will still be a bump . |
31,529 | def _flush ( self , commit = True , using = None ) : if commit : if self . _uses_savepoints ( ) : self . _commit_all_savepoints ( using ) c = self . local . mget ( '%s_%s_*' % ( self . prefix , self . _trunc_using ( using ) ) ) for key , value in c . items ( ) : self . cache_backend . set ( key , value , self . timeout... | Flushes the internal cache either to the memcache or rolls back |
31,530 | def clear ( self , pat = None ) : if pat is None : return self . __dict__ . clear ( ) expr = re . compile ( fnmatch . translate ( pat ) ) for key in tuple ( self . keys ( ) ) : if isinstance ( key , string_types ) : if expr . match ( key ) : del self . __dict__ [ key ] | Minor diversion with built - in dict here ; clear can take a glob style expression and remove keys based on that expression . |
31,531 | def get_bulkcurrencies ( self ) : start = r'YAHOO\.Finance\.CurrencyConverter\.addCurrencies\(' _json = r'\[[^\]]*\]' try : resp = get ( self . currencies_url ) resp . raise_for_status ( ) except exceptions . RequestException as e : self . log ( logging . ERROR , "%s Deprecated: API withdrawn in February 2018:\n%s" , s... | Get the supported currencies Scraped from a JSON object on the html page in javascript tag |
31,532 | def get_bulkrates ( self ) : try : resp = get ( self . bulk_url ) resp . raise_for_status ( ) except exceptions . RequestException as e : raise RuntimeError ( e ) return resp . json ( ) | Get & format the rates dict |
31,533 | def get_singlerate ( self , base , code ) : try : url = self . onerate_url % ( base , code ) resp = get ( url ) resp . raise_for_status ( ) except exceptions . HTTPError as e : self . log ( logging . ERROR , "%s: problem with %s:\n%s" , self . name , url , e ) return None rate = resp . text . rstrip ( ) if rate == 'N/A... | Get a single rate used as fallback |
31,534 | def get_baserate ( self ) : rateslist = self . rates [ 'list' ] [ 'resources' ] for rate in rateslist : rateobj = rate [ 'resource' ] [ 'fields' ] if rateobj [ 'symbol' ] . partition ( '=' ) [ 0 ] == rateobj [ 'name' ] : return rateobj [ 'name' ] raise RuntimeError ( "%s: baserate not found" % self . name ) | Helper function to populate the base rate |
31,535 | def get_ratefactor ( self , base , code ) : raise RuntimeError ( "%s Deprecated: API withdrawn in February 2018" % self . name ) try : rate = self . get_rate ( code ) except RuntimeError : return self . get_singlerate ( base , code ) self . check_ratebase ( rate ) ratefactor = Decimal ( rate [ 'price' ] ) if base == se... | Return the Decimal currency exchange rate factor of code compared to 1 base unit or RuntimeError Yahoo currently uses USD as base currency but here we detect it with get_baserate |
31,536 | def header ( heading_text , header_level , style = "atx" ) : if not isinstance ( header_level , int ) : raise TypeError ( "header_level must be int" ) if style not in [ "atx" , "setext" ] : raise ValueError ( "Invalid style %s (choose 'atx' or 'setext')" % style ) if style == "atx" : if not 1 <= header_level <= 6 : rai... | Return a header of specified level . |
31,537 | def code_block ( text , language = "" ) : if language : return "```" + language + "\n" + text + "\n```" return "\n" . join ( [ " " + item for item in text . split ( "\n" ) ] ) | Return a code block . |
31,538 | def image ( alt_text , link_url , title = "" ) : image_string = "" if title : image_string += ' "' + esc_format ( title ) + '"' return image_string | Return an inline image . |
31,539 | def ordered_list ( text_array ) : text_list = [ ] for number , item in enumerate ( text_array ) : text_list . append ( ( esc_format ( number + 1 ) + "." ) . ljust ( 3 ) + " " + esc_format ( item ) ) return "\n" . join ( text_list ) | Return an ordered list from an array . |
31,540 | def task_list ( task_array ) : tasks = [ ] for item , completed in task_array : task = "- [ ] " + esc_format ( item ) if completed : task = task [ : 3 ] + "X" + task [ 4 : ] tasks . append ( task ) return "\n" . join ( tasks ) | Return a task list . |
31,541 | def table ( big_array ) : number_of_columns = len ( big_array ) number_of_rows_in_column = [ len ( column ) for column in big_array ] max_cell_size = [ len ( max ( column , key = len ) ) for column in big_array ] table = [ ] row_array = [ column [ 0 ] for column in big_array ] table . append ( table_row ( row_array , p... | Return a formatted table generated from arrays representing columns . The function requires a 2 - dimensional array where each array is a column of the table . This will be used to generate a formatted table in string format . The number of items in each columns does not need to be consitent . |
31,542 | def compare ( sig1 , sig2 ) : if isinstance ( sig1 , six . text_type ) : sig1 = sig1 . encode ( "ascii" ) if isinstance ( sig2 , six . text_type ) : sig2 = sig2 . encode ( "ascii" ) if not isinstance ( sig1 , six . binary_type ) : raise TypeError ( "First argument must be of string, unicode or bytes type not " "'%s'" %... | Computes the match score between two fuzzy hash signatures . |
31,543 | def hash ( buf , encoding = "utf-8" ) : if isinstance ( buf , six . text_type ) : buf = buf . encode ( encoding ) if not isinstance ( buf , six . binary_type ) : raise TypeError ( "Argument must be of string, unicode or bytes type not " "'%r'" % type ( buf ) ) result = ffi . new ( "char[]" , binding . lib . FUZZY_MAX_R... | Compute the fuzzy hash of a buffer |
31,544 | def hash_from_file ( filename ) : if not os . path . exists ( filename ) : raise IOError ( "Path not found" ) if not os . path . isfile ( filename ) : raise IOError ( "File not found" ) if not os . access ( filename , os . R_OK ) : raise IOError ( "File is not readable" ) result = ffi . new ( "char[]" , binding . lib .... | Compute the fuzzy hash of a file . |
31,545 | def digest ( self , elimseq = False , notrunc = False ) : if self . _state == ffi . NULL : raise InternalError ( "State object is NULL" ) flags = ( binding . lib . FUZZY_FLAG_ELIMSEQ if elimseq else 0 ) | ( binding . lib . FUZZY_FLAG_NOTRUNC if notrunc else 0 ) result = ffi . new ( "char[]" , binding . lib . FUZZY_MAX_... | Obtain the fuzzy hash . |
31,546 | def load_css ( self ) : icons = dict ( ) common_prefix = None parser = tinycss . make_parser ( 'page3' ) stylesheet = parser . parse_stylesheet_file ( self . css_file ) is_icon = re . compile ( "\.(.*):before,?" ) for rule in stylesheet . rules : selector = rule . selector . as_css ( ) if not is_icon . match ( selector... | Creates a dict of all icons available in CSS file and finds out what s their common prefix . |
31,547 | def export_icon ( self , icon , size , color = 'black' , scale = 'auto' , filename = None , export_dir = 'exported' ) : org_size = size size = max ( 150 , size ) image = Image . new ( "RGBA" , ( size , size ) , color = ( 0 , 0 , 0 , 0 ) ) draw = ImageDraw . Draw ( image ) if scale == 'auto' : scale_factor = 1 else : sc... | Exports given icon with provided parameters . |
31,548 | def basic_distance ( trig_pin , echo_pin , celsius = 20 ) : speed_of_sound = 331.3 * math . sqrt ( 1 + ( celsius / 273.15 ) ) GPIO . setup ( trig_pin , GPIO . OUT ) GPIO . setup ( echo_pin , GPIO . IN ) GPIO . output ( trig_pin , GPIO . LOW ) time . sleep ( 0.1 ) GPIO . output ( trig_pin , True ) time . sleep ( 0.00001... | Return an unformatted distance in cm s as read directly from RPi . GPIO . |
31,549 | def raw_distance ( self , sample_size = 11 , sample_wait = 0.1 ) : if self . unit == 'imperial' : self . temperature = ( self . temperature - 32 ) * 0.5556 elif self . unit == 'metric' : pass else : raise ValueError ( 'Wrong Unit Type. Unit Must be imperial or metric' ) speed_of_sound = 331.3 * math . sqrt ( 1 + ( self... | Return an error corrected unrounded distance in cm of an object adjusted for temperature in Celcius . The distance calculated is the median value of a sample of sample_size readings . |
31,550 | def main ( ) : trig_pin = 17 echo_pin = 27 hole_depth = 80 value = sensor . Measurement ( trig_pin , echo_pin ) raw_measurement = value . raw_distance ( ) liquid_depth = value . depth_metric ( raw_measurement , hole_depth ) print ( "Depth = {} centimeters" . format ( liquid_depth ) ) | Calculate the depth of a liquid in centimeters using a HCSR04 sensor and a Raspberry Pi |
31,551 | def main ( ) : trig_pin = 17 echo_pin = 27 value = sensor . Measurement ( trig_pin , echo_pin ) raw_measurement = value . raw_distance ( sample_size = 5 , sample_wait = 0.03 ) metric_distance = value . distance_metric ( raw_measurement ) print ( "The Distance = {} centimeters" . format ( metric_distance ) ) | Calculate the distance of an object in centimeters using a HCSR04 sensor and a Raspberry Pi . This script allows for a quicker reading by decreasing the number of samples and forcing the readings to be taken at quicker intervals . |
31,552 | def main ( ) : trig , echo , speed , samples = get_args ( ) print ( 'trig pin = gpio {}' . format ( trig ) ) print ( 'echo pin = gpio {}' . format ( echo ) ) print ( 'speed = {}' . format ( speed ) ) print ( 'samples = {}' . format ( samples ) ) print ( '' ) value = sensor . Measurement ( trig , echo ) raw_distance = v... | Main function to run the sensor with passed arguments |
31,553 | def main ( ) : trig_pin = 17 echo_pin = 27 hole_depth = 31.5 value = sensor . Measurement ( trig_pin , echo_pin , temperature = 68 , unit = 'imperial' , round_to = 2 ) raw_measurement = value . raw_distance ( ) liquid_depth = value . depth_imperial ( raw_measurement , hole_depth ) print ( "Depth = {} inches" . format (... | Calculate the depth of a liquid in inches using a HCSR04 sensor and a Raspberry Pi |
31,554 | def main ( ) : trig_pin = 17 echo_pin = 27 value = sensor . Measurement ( trig_pin , echo_pin , temperature = 68 , unit = 'imperial' , round_to = 2 ) raw_measurement = value . raw_distance ( ) imperial_distance = value . distance_imperial ( raw_measurement ) print ( "The Distance = {} inches" . format ( imperial_distan... | Calculate the distance of an object in inches using a HCSR04 sensor and a Raspberry Pi |
31,555 | def read ( self ) : try : buf = os . read ( self . _fd , 8 ) except OSError as e : raise LEDError ( e . errno , "Reading LED brightness: " + e . strerror ) try : os . lseek ( self . _fd , 0 , os . SEEK_SET ) except OSError as e : raise LEDError ( e . errno , "Rewinding LED brightness: " + e . strerror ) return int ( bu... | Read the brightness of the LED . |
31,556 | def write ( self , brightness ) : if not isinstance ( brightness , ( bool , int ) ) : raise TypeError ( "Invalid brightness type, should be bool or int." ) if isinstance ( brightness , bool ) : brightness = self . _max_brightness if brightness else 0 else : if not 0 <= brightness <= self . _max_brightness : raise Value... | Set the brightness of the LED to brightness . |
31,557 | def close ( self ) : if self . _fd is None : return try : os . close ( self . _fd ) except OSError as e : raise LEDError ( e . errno , "Closing LED: " + e . strerror ) self . _fd = None | Close the sysfs LED . |
31,558 | def transfer ( self , address , messages ) : if not isinstance ( messages , list ) : raise TypeError ( "Invalid messages type, should be list of I2C.Message." ) elif len ( messages ) == 0 : raise ValueError ( "Invalid messages data, should be non-zero length." ) cmessages = ( _CI2CMessage * len ( messages ) ) ( ) for i... | Transfer messages to the specified I2C address . Modifies the messages array with the results of any read transactions . |
31,559 | def read ( self , length , timeout = None ) : data = b"" while True : if timeout is not None : ( rlist , _ , _ ) = select . select ( [ self . _fd ] , [ ] , [ ] , timeout ) if self . _fd not in rlist : break try : data += os . read ( self . _fd , length - len ( data ) ) except OSError as e : raise SerialError ( e . errn... | Read up to length number of bytes from the serial port with an optional timeout . |
31,560 | def write ( self , data ) : if not isinstance ( data , ( bytes , bytearray , list ) ) : raise TypeError ( "Invalid data type, should be bytes, bytearray, or list." ) if isinstance ( data , list ) : data = bytearray ( data ) try : return os . write ( self . _fd , data ) except OSError as e : raise SerialError ( e . errn... | Write data to the serial port and return the number of bytes written . |
31,561 | def poll ( self , timeout = None ) : p = select . poll ( ) p . register ( self . _fd , select . POLLIN | select . POLLPRI ) events = p . poll ( int ( timeout * 1000 ) ) if len ( events ) > 0 : return True return False | Poll for data available for reading from the serial port . |
31,562 | def flush ( self ) : try : termios . tcdrain ( self . _fd ) except termios . error as e : raise SerialError ( e . errno , "Flushing serial port: " + e . strerror ) | Flush the write buffer of the serial port blocking until all bytes are written . |
31,563 | def input_waiting ( self ) : buf = array . array ( 'I' , [ 0 ] ) try : fcntl . ioctl ( self . _fd , termios . TIOCINQ , buf , True ) except OSError as e : raise SerialError ( e . errno , "Querying input waiting: " + e . strerror ) return buf [ 0 ] | Query the number of bytes waiting to be read from the serial port . |
31,564 | def output_waiting ( self ) : buf = array . array ( 'I' , [ 0 ] ) try : fcntl . ioctl ( self . _fd , termios . TIOCOUTQ , buf , True ) except OSError as e : raise SerialError ( e . errno , "Querying output waiting: " + e . strerror ) return buf [ 0 ] | Query the number of bytes waiting to be written to the serial port . |
31,565 | def read ( self ) : try : buf = os . read ( self . _fd , 2 ) except OSError as e : raise GPIOError ( e . errno , "Reading GPIO: " + e . strerror ) try : os . lseek ( self . _fd , 0 , os . SEEK_SET ) except OSError as e : raise GPIOError ( e . errno , "Rewinding GPIO: " + e . strerror ) if buf [ 0 ] == b"0" [ 0 ] : retu... | Read the state of the GPIO . |
31,566 | def write ( self , value ) : if not isinstance ( value , bool ) : raise TypeError ( "Invalid value type, should be bool." ) try : if value : os . write ( self . _fd , b"1\n" ) else : os . write ( self . _fd , b"0\n" ) except OSError as e : raise GPIOError ( e . errno , "Writing GPIO: " + e . strerror ) try : os . lseek... | Set the state of the GPIO to value . |
31,567 | def poll ( self , timeout = None ) : if not isinstance ( timeout , ( int , float , type ( None ) ) ) : raise TypeError ( "Invalid timeout type, should be integer, float, or None." ) p = select . epoll ( ) p . register ( self . _fd , select . EPOLLIN | select . EPOLLET | select . EPOLLPRI ) for _ in range ( 2 ) : events... | Poll a GPIO for the edge event configured with the . edge property . |
31,568 | def read32 ( self , offset ) : if not isinstance ( offset , ( int , long ) ) : raise TypeError ( "Invalid offset type, should be integer." ) offset = self . _adjust_offset ( offset ) self . _validate_offset ( offset , 4 ) return struct . unpack ( "=L" , self . mapping [ offset : offset + 4 ] ) [ 0 ] | Read 32 - bits from the specified offset in bytes relative to the base physical address of the MMIO region . |
31,569 | def read ( self , offset , length ) : if not isinstance ( offset , ( int , long ) ) : raise TypeError ( "Invalid offset type, should be integer." ) offset = self . _adjust_offset ( offset ) self . _validate_offset ( offset , length ) return bytes ( self . mapping [ offset : offset + length ] ) | Read a string of bytes from the specified offset in bytes relative to the base physical address of the MMIO region . |
31,570 | def write8 ( self , offset , value ) : if not isinstance ( offset , ( int , long ) ) : raise TypeError ( "Invalid offset type, should be integer." ) if not isinstance ( value , ( int , long ) ) : raise TypeError ( "Invalid value type, should be integer." ) if value < 0 or value > 0xff : raise ValueError ( "Value out of... | Write 8 - bits to the specified offset in bytes relative to the base physical address of the MMIO region . |
31,571 | def write ( self , offset , data ) : if not isinstance ( offset , ( int , long ) ) : raise TypeError ( "Invalid offset type, should be integer." ) if not isinstance ( data , ( bytes , bytearray , list ) ) : raise TypeError ( "Invalid data type, expected bytes, bytearray, or list." ) offset = self . _adjust_offset ( off... | Write a string of bytes to the specified offset in bytes relative to the base physical address of the MMIO region . |
31,572 | def close ( self ) : if self . mapping is None : return self . mapping . close ( ) self . mapping = None self . _fd = None | Unmap the MMIO object s mapped physical memory . |
31,573 | def pointer ( self ) : return ctypes . cast ( ctypes . pointer ( ctypes . c_uint8 . from_buffer ( self . mapping , 0 ) ) , ctypes . c_void_p ) | Get a ctypes void pointer to the memory mapped region . |
31,574 | def transfer ( self , data ) : if not isinstance ( data , ( bytes , bytearray , list ) ) : raise TypeError ( "Invalid data type, should be bytes, bytearray, or list." ) try : buf = array . array ( 'B' , data ) except OverflowError : raise ValueError ( "Invalid data bytes." ) buf_addr , buf_len = buf . buffer_info ( ) s... | Shift out data and return shifted in data . |
31,575 | def ensure_session_key ( request ) : key = request . session . session_key if key is None : request . session . save ( ) request . session . modified = True key = request . session . session_key return key | Given a request return a session key that will be used . There may already be a session key associated but if there is not we force the session to create itself and persist between requests for the client behind the given request . |
31,576 | def add_proxy_auth ( possible_proxy_url , proxy_auth ) : if possible_proxy_url == 'DIRECT' : return possible_proxy_url parsed = urlparse ( possible_proxy_url ) return '{0}://{1}:{2}@{3}' . format ( parsed . scheme , proxy_auth . username , proxy_auth . password , parsed . netloc ) | Add a username and password to a proxy URL if the input value is a proxy URL . |
31,577 | def get_proxies ( self , url ) : hostname = urlparse ( url ) . hostname if hostname is None : hostname = "" value_from_js_func = self . pac . find_proxy_for_url ( url , hostname ) if value_from_js_func in self . _cache : return self . _cache [ value_from_js_func ] config_values = parse_pac_value ( self . pac . find_pro... | Get the proxies that are applicable to a given URL according to the PAC file . |
31,578 | def get_proxy ( self , url ) : proxies = self . get_proxies ( url ) for proxy in proxies : if proxy == 'DIRECT' or proxy not in self . _offline_proxies : return proxy | Get a proxy to use for a given URL excluding any banned ones . |
31,579 | def get_proxy_for_requests ( self , url ) : proxy = self . get_proxy ( url ) if not proxy : raise ProxyConfigExhaustedError ( url ) return proxy_parameter_for_requests ( proxy ) | Get proxy configuration for a given URL in a form ready to use with the Requests library . |
31,580 | def isInNet ( host , pattern , mask ) : host_ip = host if is_ipv4_address ( host ) else dnsResolve ( host ) if not host_ip or not is_ipv4_address ( pattern ) or not is_ipv4_address ( mask ) : return False return _address_in_network ( host_ip , pattern , mask ) | Pattern and mask specification is done the same way as for SOCKS configuration . |
31,581 | def _get_ssh_config ( config_path = '~/.ssh/config' ) : ssh_config = paramiko . SSHConfig ( ) try : with open ( os . path . realpath ( os . path . expanduser ( config_path ) ) ) as f : ssh_config . parse ( f ) except IOError : pass return ssh_config | Extract the configuration located at config_path . |
31,582 | def openbin ( self , path , mode = 'r' , buffering = - 1 , ** options ) : self . check ( ) _path = self . validatepath ( path ) _mode = Mode ( mode ) _mode . validate_bin ( ) with self . _lock : if _mode . exclusive : if self . exists ( _path ) : raise errors . FileExists ( path ) else : _mode = Mode ( '' . join ( set ... | Open a binary file - like object . |
31,583 | def platform ( self ) : uname_sys = self . _exec_command ( "uname -s" ) sysinfo = self . _exec_command ( "sysinfo" ) if uname_sys is not None : if uname_sys == b"FreeBSD" : return "freebsd" elif uname_sys == b"Darwin" : return "darwin" elif uname_sys == b"Linux" : return "linux" elif uname_sys . startswith ( b"CYGWIN" ... | The platform the server is running on . |
31,584 | def locale ( self ) : if self . platform in ( "linux" , "darwin" , "freebsd" ) : locale = self . _exec_command ( 'echo $LANG' ) if locale is not None : return locale . split ( b'.' ) [ - 1 ] . decode ( 'ascii' ) . lower ( ) return None | The locale the server is running on . |
31,585 | def _exec_command ( self , cmd ) : _ , out , err = self . _client . exec_command ( cmd , timeout = self . _timeout ) return out . read ( ) . strip ( ) if not err . read ( ) . strip ( ) else None | Run a command on the remote SSH server . |
31,586 | def _make_info ( self , name , stat_result , namespaces ) : info = { 'basic' : { 'name' : name , 'is_dir' : stat . S_ISDIR ( stat_result . st_mode ) } } if 'details' in namespaces : info [ 'details' ] = self . _make_details_from_stat ( stat_result ) if 'stat' in namespaces : info [ 'stat' ] = { k : getattr ( stat_resul... | Create an Info object from a stat result . |
31,587 | def value ( self ) : if len ( self . __dict__ [ 'values' ] ) == 1 and current_app . config [ 'FORCE_ATTRIBUTE_VALUE_AS_LIST' ] is False : return self . __dict__ [ 'values' ] [ 0 ] else : return self . __dict__ [ 'values' ] | Return single value or list of values from the attribute . If FORCE_ATTRIBUTE_VALUE_AS_LIST is True always return a list with values . |
31,588 | def append ( self , value ) : if self . __dict__ [ 'values' ] : self . __dict__ [ 'changetype' ] = MODIFY_REPLACE self . __dict__ [ 'values' ] . append ( value ) | Add another value to the attribute |
31,589 | def authenticate ( self , username , password , attribute = None , base_dn = None , search_filter = None , search_scope = SUBTREE ) : valid_dn = False try : parse_dn ( username ) valid_dn = True except LDAPInvalidDnError : pass if valid_dn is False : user_filter = '({0}={1})' . format ( attribute , username ) if search... | Attempts to bind a user to the LDAP server . |
31,590 | def get ( self , ldap_dn ) : self . base_dn = ldap_dn self . sub_tree = BASE return self . first ( ) | Return an LDAP entry by DN |
31,591 | def filter ( self , * query_filter ) : for query in query_filter : self . query . append ( query ) return self | Set the query filter to perform the query with |
31,592 | def all ( self , components_in_and = True ) : self . components_in_and = components_in_and return [ obj for obj in iter ( self ) ] | Return all of the results of a query in a list |
31,593 | def set_monitor ( module ) : def monitor ( name , tensor , track_data = True , track_grad = True ) : module . monitored_vars [ name ] = { 'tensor' : tensor , 'track_data' : track_data , 'track_grad' : track_grad , } module . monitor = monitor | Defines the monitor method on the module . |
31,594 | def set_monitoring ( module ) : def monitoring ( is_monitoring , track_data = None , track_grad = None , track_update = None , track_update_ratio = None ) : module . is_monitoring = is_monitoring module . track_data = track_data if track_data is not None else module . track_data module . track_grad = track_grad if trac... | Defines the monitoring method on the module . |
31,595 | def grad_hook ( module , name , writer , bins ) : def hook ( grad ) : writer . add_histogram ( '{}/grad' . format ( name . replace ( '.' , '/' ) ) , grad . detach ( ) . cpu ( ) . numpy ( ) , module . global_step - 1 , bins = bins ) return hook | Factory for grad_hook closures |
31,596 | def remove_grad_hooks ( module , input ) : for hook in list ( module . param_hooks . keys ( ) ) : module . param_hooks [ hook ] . remove ( ) module . param_hooks . pop ( hook ) for hook in list ( module . var_hooks . keys ( ) ) : module . var_hooks [ hook ] . remove ( ) module . var_hooks . pop ( hook ) | Remove gradient hooks to all of the parameters and monitored vars |
31,597 | def get_monitor_forward_and_backward ( summary_writer , bins ) : def monitor_forward_and_backward ( module , input , output ) : if module . is_monitoring : param_names = [ name for name , _ in module . named_parameters ( ) ] for name , param in zip ( param_names , module . parameters ( ) ) : if module . track_grad and ... | Get the method for monitoring the forward values of the network |
31,598 | def commit ( experiment_name , time ) : try : sh . git . commit ( '-a' , m = '"auto commit tracked files for new experiment: {} on {}"' . format ( experiment_name , time ) , allow_empty = True ) commit_hash = sh . git ( 'rev-parse' , 'HEAD' ) . strip ( ) return commit_hash except : return '<Unable to commit>' | Try to commit repo exactly as it is when starting the experiment for reproducibility . |
31,599 | def json ( self ) : return json . dumps ( self . dict_rules , sort_keys = True , indent = 2 , separators = ( ',' , ': ' ) ) | Output the security rules as a json string . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.