Best Python code snippet using localstack_python
rm.py
Source:rm.py
...101 twelve_select = 5102 else:103 twelve_select = None104 slider_position = self.chan0.value105 temperature = self._remap_range(slider_position, 0, 65535, 0, 18500)106 if temperature > 0:107 temperature = math.log(temperature)108 temperature = int(temperature) / 10109 return {'genre':twelve_select, 'tense':tense, 'temperature':temperature}110 def find_rumour(self, genre, tense, temperature):111 """Get a rumour from the store that matches the given criteria112 Parameters:113 genre (int):114 temperature (float): in the range 0..1115 Returns:116 r (dict): a random rumour matching the criteria117 """118 genre = str(genre)119 if genre in ('3','4'):120 genre += tense121 temperature = str(temperature)122 print(genre, 'in', self.rumour_store.keys())123 print(temperature, 'in', self.rumour_store[genre].keys())124 print('entries:', len(self.rumour_store[genre][temperature]))125 return self.rumour_store[genre][temperature].pop()126 def print_rumour(self, r):127 """take a cleaned rumour and send it to the printer128 Parameters:129 r (dict): dictionary of rumour info, containing at least keys 130 of title, body, genre, temperature131 """132 if not self.printer:133 return False # printer hasn't been initialised yet134 135 r = self.clean_rumour(r)136 title, body = r['title'], r['body']137 # clean up strings138 title = re.sub(r'[^A-Za-z\s0-9,.;:.!\'"&\[\]\(\)]', '', r['title']).strip()139 print('==>', title)140 body = re.sub(r'[^A-Za-z\s0-9,.;:.!]', '', r['body']).strip()141 print('-->', body)142 self.printer.feed(2)143 144 # Test character double-height on & off145 self.printer.justify = adafruit_thermal_printer.JUSTIFY_CENTER146 self.printer.underline = adafruit_thermal_printer.UNDERLINE_THIN147 self.printer.print('Rumour from the Rumour Mill')148 self.printer.underline = None149 self.printer.feed(2)150 self.printer.justify = adafruit_thermal_printer.JUSTIFY_LEFT151 self.printer.double_height = True152 self.printer.print("\n".join(self.tw.wrap(text=title)))153 self.printer.double_height = False154 self.printer.feed(1)155 self.printer.size = adafruit_thermal_printer.SIZE_SMALL156 self.printer.print("\n".join(self.tw.wrap(text=body)))157 self.printer.feed(1)158 self.printer.justify = adafruit_thermal_printer.JUSTIFY_CENTER159 self.printer.underline = adafruit_thermal_printer.UNDERLINE_THIN160 self.printer.print('Rumour from the Rumour Mill')161 self.printer.underline = None162 self.printer.feed(1)163# self.printer.justify = adafruit_thermal_printer.JUSTIFY_CENTER164# self.barcode_string = (str(r['genre']) + 'x')[:2]+str(r['temperature'])165# self.printer.setBarcodeHeight(30)166# self.printer.printBarcode(barcode_string.upper(), printer.CODE39)167 self.printer.feed(2)168 self.printer.justify = adafruit_thermal_printer.JUSTIFY_LEFT169 if isinstance(r['genre'], int):170 genrename = self.GENRES[r['genre']]171 tense = None172 else:173 genrename = self.GENRES[int(r['genre'][0])]174 tense = r['genre'][1:]175 176 self.printer.print('Wackiness: ' + str(r['temperature'] * 10) + '/10')177 self.printer.print('Genre: ' + genrename)178 if tense:179 self.printer.print('Time: ' + tense)180 else:181 self.printer.print('No flux capacitor for this genre')182 self.printer.feed(1)183 self.printer.justify = adafruit_thermal_printer.JUSTIFY_RIGHT184 metainfo = 'METAINFO: '185 for k in r.keys():186 if k not in ('text', 'body', 'title'):187 metainfo += '#' + str(k) + '@' + str(r[k])188 self.printer.print(metainfo)189 self.printer.bold = True190 self.printer.justify = adafruit_thermal_printer.JUSTIFY_CENTER191 self.printer.print('-- END OF RUMOUR --')192 self.printer.feed(3)193# printer.sleep() # Tell printer to sleep194# printer.wake() # Call wake() before printing again, even if reset195# printer.setDefault() # Restore printer to defaults196 197 def clean_rumour(self, rumour):198 """ take a rumour object, and clean it up199 """200 text = rumour['text']201 strip_strings = ('Share this article', 'RELATED ARTICLES', 202 'Story highlights', '(CNN)', '>', 203 "Chat with us in Facebook Messenger. Find out what's happening in the world as it unfolds.",204 'JUST WATCHED', 'MUST WATCH', 'Read More', 'Watch more!', 'SPONSORED:',205 'Getty Images')206 for s in strip_strings:207 text = text.replace(s, '')208 text = re.sub(r'By [A-Za-z]+ [A-Za-z]+, .+?\n ', '', text)209 text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', '\1', text) # markdown210 if ' Text: ' in text:211 fulltitle, body = text.split(' Text: ')212 title = fulltitle.replace(rumour['prefix'], '').strip()213 elif ' Title: ' in text:214 fulltitle, body = text.split(' Title: ')215 title = fulltitle.replace(rumour['prefix'], '').strip()216 else:217 title = text.split('\n')[1].strip()218 body = text.replace(rumour['prefix'], '').replace(title, '').strip()219 title_sents = nltk.sent_tokenize(title)220 if len(title_sents) > 1:221 title = title_sents[0]222 body = ' '.join(title_sents[1:]) + ' ' + body223 if not title.strip():224 if 'cnn.com' in rumour['prefix']:225 lines = body.split("\n")226 title = lines[0]227 body = "\n".join(lines[1:]).strip()228 else:229 body_sents = nltk.sent_tokenize(body)230 title = body_sents[0]231 body = ' '.join(body_sents[1:])232 if "\n" in title:233 title_lines = title.split("\n")234 title = title_lines[0]235 body = '\n'.join(title_lines[1:]) + "\n" + body236 rumour['body'] = body.strip()237 rumour['title'] = title.strip()238 #rumour['text'] = text239 return rumour240 def init_pi(self):241 GPIO.setmode(GPIO.BCM)242 import os243 import digitalio244 import adafruit_mcp3xxx.mcp3008 as MCP245 import adafruit_mcp3xxx.analog_in246 # Creates spi bus247 self.spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)248 # Creates chip select249 self.cs = digitalio.DigitalInOut(board.D22)250 # Creates mcp object251 self.mcp = MCP.MCP3008(self.spi, self.cs)252 # Creates analog input channel on pin 0253 self.chan0 = adafruit_mcp3xxx.analog_in.AnalogIn(self.mcp, MCP.P0)254 # Assigns channels to inputs for switches (toggle and 12 step)255 GPIO.setup(self.toggleup, GPIO.IN, pull_up_down=GPIO.PUD_UP)256 GPIO.setup(self.toggledown, GPIO.IN, pull_up_down=GPIO.PUD_UP)257 GPIO.setup(self.twlvStepOne, GPIO.IN, pull_up_down=GPIO.PUD_UP)258 GPIO.setup(self.twlvStepTwo, GPIO.IN, pull_up_down=GPIO.PUD_UP)259 GPIO.setup(self.twlvStepThree, GPIO.IN, pull_up_down=GPIO.PUD_UP)260 GPIO.setup(self.twlvStepFour, GPIO.IN, pull_up_down=GPIO.PUD_UP)261 GPIO.setup(self.twlvStepFive, GPIO.IN, pull_up_down=GPIO.PUD_UP)262 GPIO.setup(self.twlvStepSix, GPIO.IN, pull_up_down=GPIO.PUD_UP)263 def init_printer(self):264 import serial265 266 self.thermal_printer = adafruit_thermal_printer.get_printer_class(2.69) # corresponds to printer firmware267 self.uart = serial.Serial("/dev/serial0", baudrate=19200, timeout=3000)268 self.printer = self.thermal_printer(self.uart, auto_warm_up=False)269 self.printer.warm_up()270 def _remap_range(self, value, left_min, left_max, right_min, right_max):271 left_span = left_max - left_min272 right_span = right_max - right_min273 274 valueScaled = int(value - left_min) / int(left_span)...
MechClassesPi.py
Source:MechClassesPi.py
...42 # volume when the pot has moved a significant amount43 # on a 16-bit ADC44 self.tolerance = 25045 @staticmethod46 def _remap_range(value, left_min, left_max, right_min, right_max):47 """ This remaps a value from original (left) range to new (right) range. """48 # Figure out how 'wide' each range is49 left_span = left_max - left_min50 right_span = right_max - right_min51 # Convert the left range into a 0-1 range (int)52 value_scaled = int(value - left_min) / int(left_span)53 # Convert the 0-1 range into a value in the right range.54 return int(right_min + (value_scaled * right_span))55 def WatchVol(self):56 """ Infinite loop to read and change volume57 using a Pot and an ADC (mcp3008)."""58 # this keeps track of the last potentiometer value59 last_read = 060 while True:61 # we'll assume that the pot didn't move62 trim_pot_changed = False63 # read the analog pin64 trim_pot = self.chan0.value65 # how much has it changed since the last read?66 pot_adjust = abs(trim_pot - last_read)67 if pot_adjust > self.tolerance:68 trim_pot_changed = True69 if trim_pot_changed:70 # convert 16bit adc0 (0-65535) trim pot read into 0-100 volume level71 set_volume = self._remap_range(trim_pot, 0, 65535, 0, 100)72 # set OS volume playback volume73 # print('Volume = {volume}%'.format(volume=set_volume))74 set_vol_cmd = ('sudo amixer cset numid=1 -- {volume}% > /dev/null'.format(volume=set_volume))75 system(set_vol_cmd)76 # save the potentiometer reading for the next loop77 last_read = trim_pot78 # hang out and do nothing for a half second79 sleep(0.5)80class MailBoxLCD:81 def __init__(self, lcd_columns=16, lcd_rows=2):82 # Define LCD column and row size for 16x2 LCD.83 self.lcd_columns = lcd_columns84 self.lcd_rows = lcd_rows85 # Initialize the LCD using the pins...
MCP3008_Basic_Init.py
Source:MCP3008_Basic_Init.py
...23 print('Raw ADC Value: ', self.chan0.value)24 print('ADC Voltage: ' + str(self.chan0.voltage) + 'V')25 self.threshold = 25026 @staticmethod27 def _remap_range(value, left_min, left_max, right_min, right_max):28 """ This remaps a value from original (left) range to new (right) range. """29 # Figure out how 'wide' each range is30 left_span = left_max - left_min31 right_span = right_max - right_min32 # Convert the left range into a 0-1 range (int)33 value_scaled = int(value - left_min) / int(left_span)34 # Convert the 0-1 range into a value in the right range.35 return int(right_min + (value_scaled * right_span))36 def ReadPotValue(self):37 # this keeps track of the last potentiometer value38 last_read = 039 while True:40 # we'll assume that the pot didn't move41 trim_pot_changed = False42 # read the analog pin43 trim_pot = self.chan0.value44 # how much has it changed since the last read?45 pot_adjust = abs(trim_pot - last_read)46 if pot_adjust > self.threshold:47 trim_pot_changed = True48 if trim_pot_changed:49 # convert 16bit adc0 (0-65535) trim pot read into 0-100 volume level50 trim_pot_value = self._remap_range(trim_pot, 0, 65535, 0, 100)51 print(trim_pot_value)52 # save the potentiometer reading for the next loop53 last_read = trim_pot54 # hang out and do nothing for a half second55 sleep(0.5)56if __name__ == "__main__":57 adc = ADCChipInit(board.D22)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!