idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
44,800 | def note ( self , info ) : if self . recording : if self . notes is None : raise ValueError ( "This report has already been submitted" ) self . notes . extend ( self . _to_notes ( info ) ) | Record some info to the report . |
44,801 | def store ( report , address ) : now = time . time ( ) secs = int ( now ) msecs = int ( ( now - secs ) * 1000 ) submitted_date = filename = None while True : submitted_date = '%d.%03d' % ( secs , msecs ) filename = 'report_%s.txt' % submitted_date filename = os . path . join ( DESTINATION , filename ) if not os . path ... | Stores the report on disk . |
44,802 | def application ( environ , start_response ) : def send_response ( status , body ) : if not isinstance ( body , bytes ) : body = body . encode ( 'utf-8' ) start_response ( status , [ ( 'Content-Type' , 'text/plain' ) , ( 'Content-Length' , '%d' % len ( body ) ) ] ) return [ body ] if environ [ 'REQUEST_METHOD' ] != 'PO... | WSGI interface . |
44,803 | def write ( self , pin , value ) : port , pin = self . pin_to_port ( pin ) portname = 'A' if port == 1 : portname = 'B' self . _update_register ( 'GPIO' + portname , pin , value ) self . sync ( ) | Set the pin state . Make sure you put the pin in output mode first . |
44,804 | def write_port ( self , port , value ) : if port == 'A' : self . GPIOA = value elif port == 'B' : self . GPIOB = value else : raise AttributeError ( 'Port {} does not exist, use A or B' . format ( port ) ) self . sync ( ) | Use a whole port as a bus and write a byte to it . |
44,805 | def sync ( self ) : registers = { 0x00 : 'IODIRA' , 0x01 : 'IODIRB' , 0x02 : 'IPOLA' , 0x03 : 'IPOLB' , 0x04 : 'GPINTENA' , 0x05 : 'GPINTENB' , 0x0C : 'GPPUA' , 0x0D : 'GPPUB' , 0x12 : 'GPIOA' , 0x13 : 'GPIOB' } for reg in registers : name = registers [ reg ] if getattr ( self , name ) != getattr ( self , '_' + name ) ... | Upload the changed registers to the chip |
44,806 | def get_pins ( self ) : result = [ ] for a in range ( 0 , 7 ) : result . append ( GPIOPin ( self , '_action' , { 'pin' : 'A{}' . format ( a ) } , name = 'A{}' . format ( a ) ) ) for b in range ( 0 , 7 ) : result . append ( GPIOPin ( self , '_action' , { 'pin' : 'B{}' . format ( b ) } , name = 'B{}' . format ( b ) ) ) r... | Get a list containing references to all 16 pins of the chip . |
44,807 | def read ( self ) : m = getattr ( self . chip , self . method ) return m ( ** self . arguments ) | Get the logic input level for the pin |
44,808 | def write ( self , value ) : if self . inverted : value = not value m = getattr ( self . chip , self . method ) m ( value = value , ** self . arguments ) | Set the logic output level for the pin . |
44,809 | def set_range ( self , accel = 1 , gyro = 1 ) : self . i2c_write_register ( 0x1c , accel ) self . i2c_write_register ( 0x1b , gyro ) self . accel_range = accel self . gyro_range = gyro | Set the measurement range for the accel and gyro MEMS . Higher range means less resolution . |
44,810 | def set_slave_bus_bypass ( self , enable ) : current = self . i2c_read_register ( 0x37 , 1 ) [ 0 ] if enable : current |= 0b00000010 else : current &= 0b11111101 self . i2c_write_register ( 0x37 , current ) | Put the aux i2c bus on the MPU - 6050 in bypass mode thus connecting it to the main i2c bus directly |
44,811 | def temperature ( self ) : if not self . awake : raise Exception ( "MPU6050 is in sleep mode, use wakeup()" ) raw = self . i2c_read_register ( 0x41 , 2 ) raw = struct . unpack ( '>h' , raw ) [ 0 ] return round ( ( raw / 340 ) + 36.53 , 2 ) | Read the value for the internal temperature sensor . |
44,812 | def acceleration ( self ) : if not self . awake : raise Exception ( "MPU6050 is in sleep mode, use wakeup()" ) raw = self . i2c_read_register ( 0x3B , 6 ) x , y , z = struct . unpack ( '>HHH' , raw ) scales = { self . RANGE_ACCEL_2G : 16384 , self . RANGE_ACCEL_4G : 8192 , self . RANGE_ACCEL_8G : 4096 , self . RANGE_AC... | Return the acceleration in G s |
44,813 | def _get_contents ( self ) : return [ str ( value ) if is_lazy_string ( value ) else value for value in super ( LazyNpmBundle , self ) . _get_contents ( ) ] | Create strings from lazy strings . |
44,814 | def load_calibration ( self ) : registers = self . i2c_read_register ( 0xAA , 22 ) ( self . cal [ 'AC1' ] , self . cal [ 'AC2' ] , self . cal [ 'AC3' ] , self . cal [ 'AC4' ] , self . cal [ 'AC5' ] , self . cal [ 'AC6' ] , self . cal [ 'B1' ] , self . cal [ 'B2' ] , self . cal [ 'MB' ] , self . cal [ 'MC' ] , self . ca... | Load factory calibration data from device . |
44,815 | def temperature ( self ) : ut = self . get_raw_temp ( ) x1 = ( ( ut - self . cal [ 'AC6' ] ) * self . cal [ 'AC5' ] ) >> 15 x2 = ( self . cal [ 'MC' ] << 11 ) // ( x1 + self . cal [ 'MD' ] ) b5 = x1 + x2 return ( ( b5 + 8 ) >> 4 ) / 10 | Get the temperature from the sensor . |
44,816 | def pressure ( self ) : ut = self . get_raw_temp ( ) up = self . get_raw_pressure ( ) x1 = ( ( ut - self . cal [ 'AC6' ] ) * self . cal [ 'AC5' ] ) >> 15 x2 = ( self . cal [ 'MC' ] << 11 ) // ( x1 + self . cal [ 'MD' ] ) b5 = x1 + x2 b6 = b5 - 4000 x1 = ( self . cal [ 'B2' ] * ( b6 * b6 ) >> 12 ) >> 11 x2 = ( self . ca... | Get barometric pressure in milibar |
44,817 | def switch_mode ( self , new_mode ) : packet = bytearray ( ) packet . append ( new_mode ) self . device . write ( packet ) possible_responses = { self . MODE_I2C : b'I2C1' , self . MODE_RAW : b'BBIO1' , self . MODE_SPI : b'API1' , self . MODE_UART : b'ART1' , self . MODE_ONEWIRE : b'1W01' } expected = possible_response... | Explicitly switch the Bus Pirate mode |
44,818 | def set_peripheral ( self , power = None , pullup = None , aux = None , chip_select = None ) : if power is not None : self . power = power if pullup is not None : self . pullup = pullup if aux is not None : self . aux = aux if chip_select is not None : self . chip_select = chip_select peripheral_byte = 64 if self . chi... | Set the peripheral config at runtime . If a parameter is None then the config will not be changed . |
44,819 | def _set_i2c_speed ( self , i2c_speed ) : lower_bits_mapping = { '400kHz' : 3 , '100kHz' : 2 , '50kHz' : 1 , '5kHz' : 0 , } if i2c_speed not in lower_bits_mapping : raise ValueError ( 'Invalid i2c_speed' ) speed_byte = 0b01100000 | lower_bits_mapping [ i2c_speed ] self . device . write ( bytearray ( [ speed_byte ] ) ) ... | Set I2C speed to one of 400kHz 100kHz 50kHz 5kHz |
44,820 | def config ( self , averaging = 1 , datarate = 15 , mode = MODE_NORMAL ) : averaging_conf = { 1 : 0 , 2 : 1 , 4 : 2 , 8 : 3 } if averaging not in averaging_conf . keys ( ) : raise Exception ( 'Averaging should be one of: 1,2,4,8' ) datarates = { 0.75 : 0 , 1.5 : 1 , 3 : 2 , 7.5 : 4 , 15 : 5 , 30 : 6 , 75 : 7 } if datar... | Set the base config for sensor |
44,821 | def set_resolution ( self , resolution = 1090 ) : options = { 1370 : 0 , 1090 : 1 , 820 : 2 , 660 : 3 , 440 : 4 , 390 : 5 , 330 : 6 , 230 : 7 } if resolution not in options . keys ( ) : raise Exception ( 'Resolution of {} steps is not supported' . format ( resolution ) ) self . resolution = resolution config_b = 0 conf... | Set the resolution of the sensor |
44,822 | def temperature ( self ) : result = self . i2c_read ( 2 ) value = struct . unpack ( '>H' , result ) [ 0 ] if value < 32768 : return value / 256.0 else : return ( value - 65536 ) / 256.0 | Get the temperature in degree celcius |
44,823 | def write ( self , char ) : char = str ( char ) . lower ( ) self . segments . write ( self . font [ char ] ) | Display a single character on the display |
44,824 | def get_html_theme_path ( ) : return os . path . abspath ( os . path . dirname ( os . path . dirname ( __file__ ) ) ) | Get the absolute path of the directory containing the theme files . |
44,825 | def feedback_form_url ( project , page ) : return FEEDBACK_FORM_FMT . format ( pageid = quote ( "{}: {}" . format ( project , page ) ) ) | Create a URL for feedback on a particular page in a project . |
44,826 | def update_context ( app , pagename , templatename , context , doctree ) : context [ 'feedback_form_url' ] = feedback_form_url ( app . config . project , pagename ) | Update the page rendering context to include feedback_form_url . |
44,827 | def setup ( app ) : event = 'html-page-context' if six . PY3 else b'html-page-context' app . connect ( event , update_context ) return { 'parallel_read_safe' : True , 'parallel_write_safe' : True , 'version' : __version__ , } | Sphinx extension to update the rendering context with the feedback form URL . |
44,828 | def objectsFromPEM ( pemdata ) : certificates = [ ] keys = [ ] blobs = [ b"" ] for line in pemdata . split ( b"\n" ) : if line . startswith ( b'-----BEGIN' ) : if b'CERTIFICATE' in line : blobs = certificates else : blobs = keys blobs . append ( b'' ) blobs [ - 1 ] += line blobs [ - 1 ] += b'\n' keys = [ KeyPair . load... | Load some objects from a PEM . |
44,829 | def followingPrefix ( prefix ) : prefixBytes = array ( 'B' , prefix ) changeIndex = len ( prefixBytes ) - 1 while ( changeIndex >= 0 and prefixBytes [ changeIndex ] == 0xff ) : changeIndex = changeIndex - 1 if ( changeIndex < 0 ) : return None newBytes = array ( 'B' , prefix [ 0 : changeIndex + 1 ] ) newBytes [ changeI... | Returns a String that sorts just after all Strings beginning with a prefix |
44,830 | def prefix ( rowPrefix ) : fp = Range . followingPrefix ( rowPrefix ) return Range ( srow = rowPrefix , sinclude = True , erow = fp , einclude = False ) | Returns a Range that covers all rows beginning with a prefix |
44,831 | def add_mutations_and_flush ( self , table , muts ) : if not isinstance ( muts , list ) and not isinstance ( muts , tuple ) : muts = [ muts ] cells = { } for mut in muts : cells . setdefault ( mut . row , [ ] ) . extend ( mut . updates ) self . client . updateAndFlush ( self . login , table , cells ) | Add mutations to a table without the need to create and manage a batch writer . |
44,832 | def get_context ( self ) : ctx = self . _obj . get_context ( ) return _ContextProxy ( ctx , self . _factory ) | A basic override of get_context to ensure that the appropriate proxy object is returned . |
44,833 | def set_relay_on ( self ) : if not self . get_relay_state ( ) : try : request = requests . get ( '{}/relay' . format ( self . resource ) , params = { 'state' : '1' } , timeout = self . timeout ) if request . status_code == 200 : self . data [ 'relay' ] = True except requests . exceptions . ConnectionError : raise excep... | Turn the relay on . |
44,834 | def set_relay_off ( self ) : if self . get_relay_state ( ) : try : request = requests . get ( '{}/relay' . format ( self . resource ) , params = { 'state' : '0' } , timeout = self . timeout ) if request . status_code == 200 : self . data [ 'relay' ] = False except requests . exceptions . ConnectionError : raise excepti... | Turn the relay off . |
44,835 | def get_consumption ( self ) : self . get_status ( ) try : self . consumption = self . data [ 'power' ] except TypeError : self . consumption = 0 return self . consumption | Get current power consumption in mWh . |
44,836 | def get_temperature ( self ) : try : request = requests . get ( '{}/temp' . format ( self . resource ) , timeout = self . timeout , allow_redirects = False ) self . temperature = request . json ( ) [ 'compensated' ] return self . temperature except requests . exceptions . ConnectionError : raise exceptions . MyStromCon... | Get current temperature in celsius . |
44,837 | def eval_fitness ( self , chromosome ) : score = 0 number = self . translator . translate_gene ( chromosome . genes [ 0 ] ) for factor in self . factors : if number % factor == 0 : score += 1 else : score -= 1 if score == len ( self . factors ) : min_product = functools . reduce ( lambda a , b : a * b , self . factors ... | Convert a 1 - gene chromosome into an integer and calculate its fitness by checking it against each required factor . |
44,838 | def get_status ( self ) : try : request = requests . get ( '{}/{}/' . format ( self . resource , URI ) , timeout = self . timeout ) raw_data = request . json ( ) self . data = raw_data [ self . _mac ] return self . data except ( requests . exceptions . ConnectionError , ValueError ) : raise exceptions . MyStromConnecti... | Get the details from the bulb . |
44,839 | def get_power ( self ) : self . get_status ( ) try : self . consumption = self . data [ 'power' ] except TypeError : self . consumption = 0 return self . consumption | Get current power . |
44,840 | def get_firmware ( self ) : self . get_status ( ) try : self . firmware = self . data [ 'fw_version' ] except TypeError : self . firmware = 'Unknown' return self . firmware | Get the current firmware version . |
44,841 | def get_brightness ( self ) : self . get_status ( ) try : self . brightness = self . data [ 'color' ] . split ( ';' ) [ - 1 ] except TypeError : self . brightness = 0 return self . brightness | Get current brightness . |
44,842 | def get_transition_time ( self ) : self . get_status ( ) try : self . transition_time = self . data [ 'ramp' ] except TypeError : self . transition_time = 0 return self . transition_time | Get the transition time in ms . |
44,843 | def get_color ( self ) : self . get_status ( ) try : self . color = self . data [ 'color' ] self . mode = self . data [ 'mode' ] except TypeError : self . color = 0 self . mode = '' return { 'color' : self . color , 'mode' : self . mode } | Get current color . |
44,844 | def set_color_hsv ( self , hue , saturation , value ) : try : data = "action=on&color={};{};{}" . format ( hue , saturation , value ) request = requests . post ( '{}/{}/{}' . format ( self . resource , URI , self . _mac ) , data = data , timeout = self . timeout ) if request . status_code == 200 : self . data [ 'on' ] ... | Turn the bulb on with the given values as HSV . |
44,845 | def set_rainbow ( self , duration ) : for i in range ( 0 , 359 ) : self . set_color_hsv ( i , 100 , 100 ) time . sleep ( duration / 359 ) | Turn the bulb on and create a rainbow . |
44,846 | def set_sunrise ( self , duration ) : self . set_transition_time ( duration / 100 ) for i in range ( 0 , duration ) : try : data = "action=on&color=3;{}" . format ( i ) request = requests . post ( '{}/{}/{}' . format ( self . resource , URI , self . _mac ) , data = data , timeout = self . timeout ) if request . status_... | Turn the bulb on and create a sunrise . |
44,847 | def set_flashing ( self , duration , hsv1 , hsv2 ) : self . set_transition_time ( 100 ) for step in range ( 0 , int ( duration / 2 ) ) : self . set_color_hsv ( hsv1 [ 0 ] , hsv1 [ 1 ] , hsv1 [ 2 ] ) time . sleep ( 1 ) self . set_color_hsv ( hsv2 [ 0 ] , hsv2 [ 1 ] , hsv2 [ 2 ] ) time . sleep ( 1 ) | Turn the bulb on flashing with two colors . |
44,848 | def set_off ( self ) : try : request = requests . post ( '{}/{}/{}/' . format ( self . resource , URI , self . _mac ) , data = { 'action' : 'off' } , timeout = self . timeout ) if request . status_code == 200 : pass except requests . exceptions . ConnectionError : raise exceptions . MyStromConnectionError ( ) | Turn the bulb off . |
44,849 | def load_clients ( self , path = None , apis = [ ] ) : if not path : raise Exception ( "Missing path to api swagger files" ) if type ( apis ) is not list : raise Exception ( "'apis' should be a list of api names" ) if len ( apis ) == 0 : raise Exception ( "'apis' is an empty list - Expected at least one api name" ) for... | Generate client libraries for the given apis without starting an api server |
44,850 | def load_apis ( self , path , ignore = [ ] , include_crash_api = False ) : if not path : raise Exception ( "Missing path to api swagger files" ) if type ( ignore ) is not list : raise Exception ( "'ignore' should be a list of api names" ) ignore . append ( 'pym-config' ) apis = { } log . debug ( "Searching path %s" % p... | Load all swagger files found at the given path except those whose names are in the ignore list |
44,851 | def start ( self , serve = [ ] ) : if type ( serve ) is str : serve = [ serve ] elif type ( serve ) is list : pass else : raise Exception ( "'serve' should be an api name or a list of api names" ) if len ( serve ) == 0 : raise Exception ( "You must specify at least one api to serve" ) for api_name in serve : if api_nam... | Load all apis either as local apis served by the flask app or as remote apis to be called from whithin the app s endpoints then start the app server |
44,852 | def add_error ( name = None , code = None , status = None ) : if not name or not status or not code : raise Exception ( "Can't create Exception class %s: you must set both name, status and code" % name ) myexception = type ( name , ( PyMacaronException , ) , { "code" : code , "status" : status } ) globals ( ) [ name ] ... | Create a new Exception class |
44,853 | def responsify ( error ) : assert str ( type ( error ) . __name__ ) == 'Error' if error . error in code_to_class : e = code_to_class [ error . error ] ( error . error_description ) if error . error_id : e . error_id = error . error_id if error . user_message : e . user_message = error . user_message return e . http_rep... | Take an Error model and return it as a Flask response |
44,854 | def is_error ( o ) : if hasattr ( o , 'error' ) and hasattr ( o , 'error_description' ) and hasattr ( o , 'status' ) : return True return False | True if o is an instance of a swagger Error model or a flask Response of an error model |
44,855 | def format_error ( e ) : if isinstance ( e , PyMacaronException ) : return e . to_model ( ) if isinstance ( e , PyMacaronCoreException ) and e . __class__ . __name__ == 'ValidationError' : return ValidationError ( str ( e ) ) . to_model ( ) return UnhandledServerError ( str ( e ) ) . to_model ( ) | Take an exception caught within pymacaron_core and turn it into a bravado - core Error instance |
44,856 | def raise_error ( e ) : code = e . error if code in code_to_class : raise code_to_class [ code ] ( e . error_description ) else : raise InternalServerError ( e . error_description ) | Take a bravado - core Error model and raise it as an exception |
44,857 | def http_reply ( self ) : data = { 'status' : self . status , 'error' : self . code . upper ( ) , 'error_description' : str ( self ) } if self . error_caught : data [ 'error_caught' ] = pformat ( self . error_caught ) if self . error_id : data [ 'error_id' ] = self . error_id if self . user_message : data [ 'user_messa... | Return a Flask reply object describing this error |
44,858 | def to_model ( self ) : e = ApiPool ( ) . current_server_api . model . Error ( status = self . status , error = self . code . upper ( ) , error_description = str ( self ) , ) if self . error_id : e . error_id = self . error_id if self . user_message : e . user_message = self . user_message if self . error_caught : e . ... | Return a bravado - core Error instance |
44,859 | def _list ( self , path , dim_key = None , ** kwargs ) : url_str = self . base_url + path if dim_key and dim_key in kwargs : dim_str = self . get_dimensions_url_string ( kwargs [ dim_key ] ) kwargs [ dim_key ] = dim_str if kwargs : url_str += '?%s' % parse . urlencode ( kwargs , True ) body = self . client . list ( pat... | Get a list of metrics . |
44,860 | def mapstr_to_list ( mapstr ) : maplist = [ ] with StringIO ( mapstr ) as infile : for row in infile : maplist . append ( row . strip ( ) ) return maplist | Convert an ASCII map string with rows to a list of strings 1 string per row . |
44,861 | def sprinkler_reaches_cell ( x , y , sx , sy , r ) : dx = sx - x dy = sy - y return math . sqrt ( dx ** 2 + dy ** 2 ) <= r | Return whether a cell is within the radius of the sprinkler . |
44,862 | def eval_fitness ( self , chromosome ) : sx , sy = self . translator . translate_chromosome ( chromosome ) penalty = 0 if sx >= self . w : penalty += self . w * self . h if sy >= self . h : penalty += self . w * self . h if penalty > 0 : self . fitness_cache [ chromosome . dna ] = - penalty return - penalty crops_water... | Return the number of plants reached by the sprinkler . |
44,863 | def map_sprinkler ( self , sx , sy , watered_crop = '^' , watered_field = '_' , dry_field = ' ' , dry_crop = 'x' ) : maplist = [ list ( s ) for s in self . maplist ] for y , row in enumerate ( maplist ) : for x , cell in enumerate ( row ) : if sprinkler_reaches_cell ( x , y , sx , sy , self . r ) : if cell == 'x' : cel... | Return a version of the ASCII map showing reached crop cells . |
44,864 | def index ( request , template_name = "index.html" ) : if request . GET . get ( 'ic-request' ) : counter , created = Counter . objects . get_or_create ( pk = 1 ) counter . value += 1 counter . save ( ) else : counter , created = Counter . objects . get_or_create ( pk = 1 ) print ( counter . value ) context = dict ( val... | \ The index view which basically just displays a button and increments a counter . |
44,865 | def get_fitness ( self , chromosome ) : fitness = self . fitness_cache . get ( chromosome . dna ) if fitness is None : fitness = self . eval_fitness ( chromosome ) self . fitness_cache [ chromosome . dna ] = fitness return fitness | Get the fitness score for a chromosome using the cached value if available . |
44,866 | def create_random ( cls , gene_length , n = 1 , gene_class = BinaryGene ) : assert issubclass ( gene_class , BaseGene ) chromosomes = [ ] if not hasattr ( gene_length , '__iter__' ) : gene_length = [ gene_length ] for _ in range ( n ) : genes = [ gene_class . create_random ( length ) for length in gene_length ] chromos... | Create 1 or more chromosomes with randomly generated DNA . |
44,867 | def copy ( self ) : genes = [ g . copy ( ) for g in self . genes ] return type ( self ) ( genes ) | Return a new instance of this chromosome by copying its genes . |
44,868 | def check_genes ( self ) : gene_dna_set = set ( [ g . dna for g in self . genes ] ) assert gene_dna_set == self . dna_choices_set | Assert that every DNA choice is represented by exactly one gene . |
44,869 | def populate_error_report ( data ) : call_id , call_path = '' , '' if hasattr ( stack . top , 'call_id' ) : call_id = stack . top . call_id if hasattr ( stack . top , 'call_path' ) : call_path = stack . top . call_path data [ 'call_id' ] = call_id data [ 'call_path' ] = call_path data [ 'is_ec2_instance' ] = is_ec2_ins... | Add generic stats to the error report |
44,870 | def create ( self , ** kwargs ) : url_str = self . base_url if 'tenant_id' in kwargs : url_str = url_str + '?tenant_id=%s' % kwargs [ 'tenant_id' ] del kwargs [ 'tenant_id' ] data = kwargs [ 'jsonbody' ] if 'jsonbody' in kwargs else kwargs body = self . client . create ( url = url_str , json = data ) return body | Create a metric . |
44,871 | def get_json_results ( self , response ) : try : self . most_recent_json = response . json ( ) json_results = response . json ( ) if response . status_code in [ 401 , 403 ] : raise PyMsCognitiveWebSearchException ( "CODE {code}: {message}" . format ( code = response . status_code , message = json_results [ "message" ] ... | Parses the request result and returns the JSON object . Handles all errors . |
44,872 | def search_all ( self , quota = 50 , format = 'json' ) : quota_left = quota results = [ ] while quota_left > 0 : more_results = self . _search ( quota_left , format ) if not more_results : break results += more_results quota_left = quota_left - len ( more_results ) time . sleep ( 1 ) results = results [ 0 : quota ] ret... | Returns a single list containing up to limit Result objects Will keep requesting until quota is met Will also truncate extra results to return exactly the given quota |
44,873 | def format_parameters ( params ) : if not params : return { } if len ( params ) == 1 : if params [ 0 ] . find ( ';' ) != - 1 : params = params [ 0 ] . split ( ';' ) else : params = params [ 0 ] . split ( ',' ) parameters = { } for p in params : try : ( n , v ) = p . split ( '=' , 1 ) except ValueError : msg = '%s(%s). ... | Reformat parameters into dict of format expected by the API . |
44,874 | def delete ( self , ** kwargs ) : url_str = self . base_url + '/%s' % kwargs [ 'alarm_id' ] resp = self . client . delete ( url_str ) return resp | Delete a specific alarm . |
44,875 | def history ( self , ** kwargs ) : url_str = self . base_url + '/%s/state-history' % kwargs [ 'alarm_id' ] del kwargs [ 'alarm_id' ] if kwargs : url_str = url_str + '?%s' % parse . urlencode ( kwargs , True ) resp = self . client . list ( url_str ) return resp [ 'elements' ] if type ( resp ) is dict else resp | History of a specific alarm . |
44,876 | def history_list ( self , ** kwargs ) : url_str = self . base_url + '/state-history/' if 'dimensions' in kwargs : dimstr = self . get_dimensions_url_string ( kwargs [ 'dimensions' ] ) kwargs [ 'dimensions' ] = dimstr if kwargs : url_str = url_str + '?%s' % parse . urlencode ( kwargs , True ) resp = self . client . list... | History list of alarm state . |
44,877 | def do_version ( ) : v = ApiPool . ping . model . Version ( name = ApiPool ( ) . current_server_name , version = ApiPool ( ) . current_server_api . get_version ( ) , container = get_container_version ( ) , ) log . info ( "/version: " + pprint . pformat ( v ) ) return v | Return version details of the running server api |
44,878 | def do_metric_create ( mc , args ) : fields = { } fields [ 'name' ] = args . name if args . dimensions : fields [ 'dimensions' ] = utils . format_parameters ( args . dimensions ) fields [ 'timestamp' ] = args . time fields [ 'value' ] = args . value if args . value_meta : fields [ 'value_meta' ] = utils . format_parame... | Create metric . |
44,879 | def do_metric_create_raw ( mc , args ) : try : mc . metrics . create ( ** args . jsonbody ) except ( osc_exc . ClientException , k_exc . HttpError ) as he : raise osc_exc . CommandError ( '%s\n%s' % ( he . message , he . details ) ) else : print ( 'Successfully created metric' ) | Create metric from raw json body . |
44,880 | def do_metric_name_list ( mc , args ) : fields = { } if args . dimensions : fields [ 'dimensions' ] = utils . format_dimensions_query ( args . dimensions ) if args . limit : fields [ 'limit' ] = args . limit if args . offset : fields [ 'offset' ] = args . offset if args . tenant_id : fields [ 'tenant_id' ] = args . ten... | List names of metrics . |
44,881 | def do_metric_list ( mc , args ) : fields = { } if args . name : fields [ 'name' ] = args . name if args . dimensions : fields [ 'dimensions' ] = utils . format_dimensions_query ( args . dimensions ) if args . limit : fields [ 'limit' ] = args . limit if args . offset : fields [ 'offset' ] = args . offset if args . sta... | List metrics for this tenant . |
44,882 | def do_metric_statistics ( mc , args ) : statistic_types = [ 'AVG' , 'MIN' , 'MAX' , 'COUNT' , 'SUM' ] statlist = args . statistics . split ( ',' ) for stat in statlist : if stat . upper ( ) not in statistic_types : errmsg = ( 'Invalid type, not one of [' + ', ' . join ( statistic_types ) + ']' ) raise osc_exc . Comman... | List measurement statistics for the specified metric . |
44,883 | def do_notification_show ( mc , args ) : fields = { } fields [ 'notification_id' ] = args . id try : notification = mc . notifications . get ( ** fields ) except ( osc_exc . ClientException , k_exc . HttpError ) as he : raise osc_exc . CommandError ( '%s\n%s' % ( he . message , he . details ) ) else : if args . json : ... | Describe the notification . |
44,884 | def do_notification_list ( mc , args ) : fields = { } if args . limit : fields [ 'limit' ] = args . limit if args . offset : fields [ 'offset' ] = args . offset if args . sort_by : sort_by = args . sort_by . split ( ',' ) for field in sort_by : field_values = field . lower ( ) . split ( ) if len ( field_values ) > 2 : ... | List notifications for this tenant . |
44,885 | def do_notification_delete ( mc , args ) : fields = { } fields [ 'notification_id' ] = args . id try : mc . notifications . delete ( ** fields ) except ( osc_exc . ClientException , k_exc . HttpError ) as he : raise osc_exc . CommandError ( '%s\n%s' % ( he . message , he . details ) ) else : print ( 'Successfully delet... | Delete notification . |
44,886 | def do_notification_update ( mc , args ) : fields = { } fields [ 'notification_id' ] = args . id fields [ 'name' ] = args . name fields [ 'type' ] = args . type fields [ 'address' ] = args . address if not _validate_notification_period ( args . period , args . type . upper ( ) ) : return fields [ 'period' ] = args . pe... | Update notification . |
44,887 | def do_alarm_definition_list ( mc , args ) : fields = { } if args . name : fields [ 'name' ] = args . name if args . dimensions : fields [ 'dimensions' ] = utils . format_dimensions_query ( args . dimensions ) if args . severity : if not _validate_severity ( args . severity ) : return fields [ 'severity' ] = args . sev... | List alarm definitions for this tenant . |
44,888 | def do_alarm_definition_delete ( mc , args ) : fields = { } fields [ 'alarm_id' ] = args . id try : mc . alarm_definitions . delete ( ** fields ) except ( osc_exc . ClientException , k_exc . HttpError ) as he : raise osc_exc . CommandError ( '%s\n%s' % ( he . message , he . details ) ) else : print ( 'Successfully dele... | Delete the alarm definition . |
44,889 | def do_alarm_definition_update ( mc , args ) : fields = { } fields [ 'alarm_id' ] = args . id fields [ 'name' ] = args . name fields [ 'description' ] = args . description fields [ 'expression' ] = args . expression fields [ 'alarm_actions' ] = _arg_split_patch_update ( args . alarm_actions ) fields [ 'ok_actions' ] = ... | Update the alarm definition . |
44,890 | def do_alarm_definition_patch ( mc , args ) : fields = { } fields [ 'alarm_id' ] = args . id if args . name : fields [ 'name' ] = args . name if args . description : fields [ 'description' ] = args . description if args . expression : fields [ 'expression' ] = args . expression if args . alarm_actions : fields [ 'alarm... | Patch the alarm definition . |
44,891 | def do_alarm_show ( mc , args ) : fields = { } fields [ 'alarm_id' ] = args . id try : alarm = mc . alarms . get ( ** fields ) except ( osc_exc . ClientException , k_exc . HttpError ) as he : raise osc_exc . CommandError ( '%s\n%s' % ( he . message , he . details ) ) else : if args . json : print ( utils . json_formatt... | Describe the alarm . |
44,892 | def do_alarm_update ( mc , args ) : fields = { } fields [ 'alarm_id' ] = args . id if args . state . upper ( ) not in state_types : errmsg = ( 'Invalid state, not one of [' + ', ' . join ( state_types ) + ']' ) print ( errmsg ) return fields [ 'state' ] = args . state fields [ 'lifecycle_state' ] = args . lifecycle_sta... | Update the alarm state . |
44,893 | def do_alarm_delete ( mc , args ) : fields = { } fields [ 'alarm_id' ] = args . id try : mc . alarms . delete ( ** fields ) except ( osc_exc . ClientException , k_exc . HttpError ) as he : raise osc_exc . CommandError ( '%s\n%s' % ( he . message , he . details ) ) else : print ( 'Successfully deleted alarm' ) | Delete the alarm . |
44,894 | def do_alarm_count ( mc , args ) : fields = { } if args . alarm_definition_id : fields [ 'alarm_definition_id' ] = args . alarm_definition_id if args . metric_name : fields [ 'metric_name' ] = args . metric_name if args . metric_dimensions : fields [ 'metric_dimensions' ] = utils . format_dimensions_query ( args . metr... | Count alarms . |
44,895 | def do_alarm_history ( mc , args ) : fields = { } fields [ 'alarm_id' ] = args . id if args . limit : fields [ 'limit' ] = args . limit if args . offset : fields [ 'offset' ] = args . offset try : alarm = mc . alarms . history ( ** fields ) except ( osc_exc . ClientException , k_exc . HttpError ) as he : raise osc_exc ... | Alarm state transition history . |
44,896 | def do_alarm_history_list ( mc , args ) : fields = { } if args . dimensions : fields [ 'dimensions' ] = utils . format_parameters ( args . dimensions ) if args . starttime : _translate_starttime ( args ) fields [ 'start_time' ] = args . starttime if args . endtime : fields [ 'end_time' ] = args . endtime if args . limi... | List alarms state history . |
44,897 | def do_notification_type_list ( mc , args ) : try : notification_types = mc . notificationtypes . list ( ) except ( osc_exc . ClientException , k_exc . HttpError ) as he : raise osc_exc . CommandError ( '%s\n%s' % ( he . message , he . details ) ) else : if args . json : print ( utils . json_formatter ( notification_ty... | List notification types supported by monasca . |
44,898 | def add_auth ( f ) : def add_auth_decorator ( * args , ** kwargs ) : token = get_user_token ( ) if 'headers' not in kwargs : kwargs [ 'headers' ] = { } kwargs [ 'headers' ] [ 'Authorization' ] = "Bearer %s" % token return f ( * args , ** kwargs ) return add_auth_decorator | A decorator that adds the authentication header to requests arguments |
44,899 | def generate_token ( user_id , expire_in = None , data = { } , issuer = None , iat = None ) : assert user_id , "No user_id passed to generate_token()" assert isinstance ( data , dict ) , "generate_token(data=) should be a dictionary" assert get_config ( ) . jwt_secret , "No JWT secret configured in pymacaron" if not is... | Generate a new JWT token for this user_id . Default expiration date is 1 year from creation time |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.