Best Python code snippet using localstack_python
sx1509_config.py
Source:sx1509_config.py
...20 f = open(fname, 'w')21 f.write(data)22 f.close()23#------------------------------------------------------------------------------24def gen_tag(tag, content=None, attrib=None):25 """generate a <tag attribute>content</tag> string"""26 if attrib is None and content is None:27 return '<%s/>' % tag28 elif attrib is None:29 return '<%s>%s</%s>' % (tag, content, tag)30 elif content is None:31 return '<%s %s/>' % (tag, attrib)32 return '<%s %s>%s</%s>' % (tag, attrib, content, tag)33def indent(s):34 items = s.split('\n')35 items.insert(0, '')36 items.append('')37 return '\n '.join(items)[:-2]38#------------------------------------------------------------------------------39class sx1509(object):40 def __init__(self, name, uuid):41 self.name = name42 self.uuid = uuid43 self.keys = False44 self.rows = 045 self.cols = 046 self.row_bits = 047 self.col_bits = 048 self.debounce = '4ms'49 self.cfg = []50 self.alloc = [None,] * _num_io_pins51 def set_usage(self, i, s):52 """set the usage of an io pin"""53 pr_error('bad io pin: %d' % i, i not in range(_num_io_pins))54 if self.alloc[i] is None:55 self.alloc[i] = s56 return True57 return False58 def print_usage(self):59 """return a string for the pin usage"""60 s = []61 for i in range(_num_io_pins):62 usage = self.alloc[i]63 if usage is None:64 usage = 'not used'65 s.append('// pin %d: %s' % (i, usage))66 return '\n'.join(s)67 def key_scanning(self, rows, cols, debounce):68 """configure for key scanning"""69 pr_error('bad key scan rows: %d' % rows, rows not in (1, 2, 3, 4, 5, 6, 7, 8))70 pr_error('bad key scan cols: %d' % cols, cols not in (1, 2, 3, 4, 5, 6, 7, 8))71 self.keys = True72 self.rows = rows73 self.cols = cols74 self.debounce = debounce75 self.row_bits = (1 << rows) - 176 self.col_bits = (1 << cols) - 177 for i in range(self.rows):78 good = self.set_usage(i, 'key row %d' % i)79 pr_error('row pin already used: %d' % i, not good)80 for i in range(self.cols):81 good = self.set_usage(8 + i, 'key col %d' % i)82 pr_error('col pin already used: %d' % i, not good)83 def wr(self, name, default, val):84 if val != default:85 self.cfg.append(('SX1509_%s' % name, val))86 def eol(self):87 """end of list"""88 self.cfg.append(('0xff', 0))89 def CLOCK(self):90 # use the internal 2 MHz clock91 val = (2 << 5) # internal 2MHz oscillator92 val |= (1 << 4) # oscio = oscout93 val |= (0 << 0) # oscout = 094 self.wr('CLOCK', 0, val)95 def MISC(self):96 # setup the led clock divider97 val = (1 << 4)98 self.wr('MISC', 0, val)99 def DIR_A(self):100 val = 0xff # default inputs101 if self.keys:102 # rows are outputs on bank A (0..rows-1)103 val &= ~self.row_bits104 self.wr('DIR_A', 0xff, val)105 def DIR_B(self):106 val = 0xff # default inputs107 if self.keys:108 # columns are inputs on bank B (8..8+cols-1)109 val |= self.col_bits110 self.wr('DIR_B', 0xff, val)111 def OPEN_DRAIN_A(self):112 val = 0 # default off113 if self.keys:114 # rows are open drain115 val |= self.row_bits116 self.wr('OPEN_DRAIN_A', 0, val)117 def PULL_UP_B(self):118 val = 0 # default off119 if self.keys:120 # columns are pull ups121 val |= self.col_bits122 self.wr('PULL_UP_B', 0, val)123 def DEBOUNCE_CONFIG(self, ms):124 vals = {'0.5ms':0, '1ms':1, '2ms':2, '4ms':3, '8ms':4, '16ms':5, '32ms':6, '64ms':7,}125 pr_error('invalid debounce time', ms not in vals)126 self.wr('DEBOUNCE_CONFIG', 0, vals[ms])127 def DEBOUNCE_ENABLE_B(self):128 val = 0 # default off129 if self.keys:130 # columns are debounced inputs131 val |= self.col_bits132 self.wr('DEBOUNCE_ENABLE_B', 0, val)133 def KEY_CONFIG_1(self, sleep, scan):134 val = 0135 if self.keys:136 # auto sleep time137 vals = {'off':0, '128ms':1, '256ms':2, '512ms':3, '1s':4, '2s':5, '4s':6, '8s':7,}138 pr_error('invalid auto sleep time', sleep not in vals)139 val |= vals[sleep] << 4140 # row scan time141 vals = {'1ms':0, '2ms':1, '4ms':2, '8ms':3, '16ms':4, '32ms':5, '64ms':6, '128ms':7,}142 pr_error('invalid scan time', scan not in vals)143 val |= vals[scan]144 self.wr('KEY_CONFIG_1', 0, val)145 def KEY_CONFIG_2(self):146 val = 0147 if self.keys:148 val |= (self.rows - 1) << 3149 val |= (self.cols - 1)150 self.wr('KEY_CONFIG_2', 0, val)151 def gen_declaration(self):152 """generate driver declaration code"""153 # clock154 self.CLOCK()155 self.MISC()156 # IO bank A157 self.DIR_A()158 self.OPEN_DRAIN_A()159 # IO bank B160 self.DIR_B()161 self.PULL_UP_B()162 # input debouncing163 self.DEBOUNCE_CONFIG(self.debounce)164 self.DEBOUNCE_ENABLE_B()165 # key configuration166 # note: we are not using the hw based key scanning at this time 167 #self.KEY_CONFIG_1('1s', '8ms')168 #self.KEY_CONFIG_2()169 # terminate the register value list170 self.eol()171 s = []172 s.append(self.print_usage())173 s.append('const struct sx1509_cfg config[%d] = {' % len(self.cfg))174 s.extend([' {%s, 0x%02x},' % x for x in self.cfg])175 s.append('};')176 s.append('struct sx1509_state state;')177 return '\n'.join(s)178 def gen_krate(self):179 """generate the krate function call(s)"""180 s = []181 if self.keys:182 s.append('sx1509_key(&state, &outlet_key);')183 return '\n'.join(s)184 def gen_description(self):185 """generate the description string"""186 s = []187 s.append('SX1509 Driver: %s' % self.name)188 if self.keys:189 s.append(' %dx%d keyboard matrix scanner' % (self.rows, self.cols))190 return '\n'.join(s)191 def gen_includes(self):192 """generate the include file declaration"""193 s = []194 # See: https://github.com/axoloti/axoloti/issues/378195 s.append(gen_tag('include', './%s' % _base_driver))196 #s.append(gen_tag('include', './%s.h' % self.name))197 return '\n'.join(s)198 def gen_attribs(self):199 """generate the driver attributes"""200 adrs = [gen_tag('string', '0x%02x' % x) for x in _device_adr]201 adrs = indent('\n'.join(adrs))202 m_entries = gen_tag('MenuEntries', adrs)203 c_entries = gen_tag('CEntries', adrs)204 return gen_tag('combo', indent(m_entries + '\n' + c_entries), 'name="adr"')205 def gen_outlets(self):206 """generate the driver outlets"""207 outlets = []208 if self.keys:209 outlets.append(gen_tag('int32', None, 'name="key"'))210 return '\n'.join(outlets)211 def gen_depends(self):212 """generate the driver dependencies"""213 return gen_tag('depend', 'I2CD1')214 def gen_axo(self):215 """generate the axo file"""216 s = []217 s.append(gen_tag('sDescription', self.gen_description()))218 s.append(gen_tag('author', 'Jason Harris'))219 s.append(gen_tag('license', 'BSD'))220 s.append(gen_tag('inlets'))221 s.append(gen_tag('outlets', indent(self.gen_outlets())))222 s.append(gen_tag('displays'))223 s.append(gen_tag('params'))224 s.append(gen_tag('attribs', indent(self.gen_attribs())))225 s.append(gen_tag('includes', indent(self.gen_includes())))226 s.append(gen_tag('depends', indent(self.gen_depends())))227 s.append(gen_tag('code.declaration', '<![CDATA[' + self.gen_declaration() + ']]>'))228 s.append(gen_tag('code.init', '<![CDATA[' + 'sx1509_init(&state, &config[0], attr_adr);' + ']]>'))229 s.append(gen_tag('code.dispose', '<![CDATA[' + 'sx1509_dispose(&state);' + ']]>'))230 s.append(gen_tag('code.krate', '<![CDATA[' + self.gen_krate() + ']]>'))231 s = gen_tag('obj.normal', indent('\n'.join(s)), 'id="%s" uuid="%s"' % (self.name, self.uuid))232 s = gen_tag('objdefs', indent(s), 'appVersion="1.0.12"')233 return s + '\n'234 def gen_h(self):235 """generate the object *.h file"""236 # read the base driver code237 # See: https://github.com/axoloti/axoloti/issues/378238 f = open(_base_driver, 'r')239 drv = f.read()240 f.close()241 s = [drv,]242 # add the krate function(s)243 defname = 'DEADSY_%s_H' % self.name.upper()244 s.append('')245 s.append('#ifndef %s' % defname)246 s.append('#define %s' % defname)...
BG.py
Source:BG.py
1#!/usr/bin/env python32# coding=utf-83import arrow4from bs4 import BeautifulSoup5import requests6TYPE_MAPPING = { # Real values around midnight7 u'ÐÐЦ': 'nuclear', # 20008 u'ÐондензаÑионни ТÐЦ': 'coal', # 18009 u'ТоплоÑикаÑионни ТÐЦ': 'gas', # 14610 u'ÐаводÑки ТÐЦ': 'gas', # 14711 u'ÐÐЦ': 'hydro', # 712 u'Ðалки ÐÐЦ': 'hydro', # 7413 u'ÐÑÐЦ': 'wind', # 48814 u'ФÐЦ': 'solar', # 015 u'Ðио ТÐЦ': 'biomass', # 2916 u'Ð¢Ð¾Ð²Ð°Ñ Ð Ð': 'consumption', # 317517}18def time_string_converter(ts):19 """Converts time strings into aware datetime objects."""20 dt_naive = arrow.get(ts, 'DD.MM.YYYY HH:mm:ss')21 dt_aware = dt_naive.replace(tzinfo='Europe/Sofia').datetime22 return dt_aware23def fetch_production(zone_key='BG', session=None, target_datetime=None, logger=None) -> dict:24 """Requests the last known production mix (in MW) of a given country."""25 if target_datetime:26 raise NotImplementedError('This parser is not yet able to parse past dates')27 r = session or requests.session()28 url = 'http://www.eso.bg/doc?124'29 response = r.get(url)30 html = response.text31 soup = BeautifulSoup(html, 'html.parser')32 try:33 time_div = soup.find("div", {"class": "dashboardCaptionDiv"})34 bold = time_div.find('b')35 except AttributeError:36 raise LookupError('No data currently available for Bulgaria.')37 time_string = bold.string38 dt = time_string_converter(time_string)39 table = soup.find("table", {"class": "table-condensed"})40 rows = table.findChildren("tr")41 datapoints = []42 for row in rows[1:-1]:43 gen_tag = row.find("td")44 gen = gen_tag.text45 val_tag = gen_tag.findNext("td")46 val = float(val_tag.find("b").text)47 datapoints.append((TYPE_MAPPING[gen], val))48 production = {}49 for k, v in datapoints:50 production[k] = production.get(k, 0.0) + v51 data = {52 'zoneKey': zone_key,53 'production': production,54 'storage': {},55 'source': 'eso.bg',56 'datetime': dt57 }58 return data59if __name__ == '__main__':60 """Main method, never used by the Electricity Map backend, but handy for testing."""61 print('fetch_production() ->')...
t_gen_tag.py
Source:t_gen_tag.py
1from f_utils import u_tester2from f_html.c_element import Element3from f_html import gen_tag456class TestGenTag:78 def __init__(self):9 u_tester.print_start(__file__)10 TestGenTag.__tester_comment()11 TestGenTag.__tester_doctype()12 TestGenTag.__tester_html()13 TestGenTag.__tester_head()14 TestGenTag.__tester_h()15 u_tester.print_finish(__file__)1617 @staticmethod18 def __tester_comment():19 ele = gen_tag.comment('comment')20 p0 = str(ele) == '<!-- comment -->'21 u_tester.run(p0)2223 @staticmethod24 def __tester_doctype():25 ele = gen_tag.doctype()26 p0 = str(ele) == '<!DOCTYPE html>'27 u_tester.run(p0)2829 @staticmethod30 def __tester_html():31 ele = gen_tag.html()32 p0 = str(ele) == '<html lang="en">\n</html>'33 u_tester.run(p0)3435 @staticmethod36 def __tester_head():37 ele = gen_tag.head()38 p0 = str(ele) == '<head>\n</head>'39 ele = gen_tag.head(title='Title')40 p1 = str(ele) == '<head>\n\t<title>\n\t\tTitle\n\t</title>\n</head>'41 u_tester.run(p0, p1)4243 @staticmethod44 def __tester_h():45 ele_h = gen_tag.h(1)46 p0 = str(ele_h) == '<h1>\n</h1>'47 ele_text = Element(content='This is Header')48 ele_h.nest(ele_text)49 p1 = str(ele_h) == '<h1>\n\tThis is Header\n</h1>'50 u_tester.run(p0, p1)515253if __name__ == '__main__':
...
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!!