Best Python code snippet using tox_python
reader.py
Source:reader.py
...23 'is_obsolete',24 # TODO more tag names25)26class OBOReader(object):27 def _unescape(self, s):28 out, escape = '', False29 for char in s:30 if escape:31 if char in 'ntW':32 out += {33 'n': '\n',34 't': '\t',35 'W': ' '36 }[char]37 else:38 out += char39 escape = False40 elif char == '\\':41 escape = True42 else:43 out += char44 return out45 def read(self, fp):46 stanza = None47 header = None48 stanzas = []49 tag_value_pairs = []50 lines = iter(fp)51 while True:52 try:53 line = next(lines).strip()54 except StopIteration:55 break56 if line.startswith('['):57 # stanza58 match = RE_STANZA.match(line)59 if not match:60 raise ValueError("Bad stanza tag format")61 if stanza is not None:62 stanzas.append((stanza, tag_value_pairs))63 else:64 header = tag_value_pairs65 stanza = match.group('stanza')66 tag_value_pairs = []67 elif line.startswith('!'):68 # skip comments69 pass70 elif not line:71 # empty line. ignore72 pass73 else:74 # tag-value pair75 # 1. strip unescaped '!'s.76 # 2. if line ends with '\', read next line, then continue with #177 # 3. split at first unescaped ':' and ignore everything from first unescaped '{' or '!'78 tag, value = None, None79 part = ''80 escape, quote = False, False81 while True:82 for char in line:83 if escape:84 part += char85 escape = False86 elif char == '\\':87 part += char88 escape = True89 elif not tag and char == ':':90 tag = part91 part = ''92 elif char == '!': # and not quote? OBO Spec is not very specific on all of this.93 break # comment94 elif char == '{' and not quote:95 break # trailing modifier96 else:97 if char == '"':98 quote = not quote99 part += char100 if escape:101 try:102 line = next(lines).strip()103 except StopIteration:104 raise ParseException("Unterminated tag-value pair at end of file.", line)105 else:106 break107 #if quote:108 # raise ParseException("Unterminated quote in tag-value pair", line, tag, value)109 if tag is not None:110 value = part.strip()111 else:112 raise ParseException('Tag without value', line)113 if tag in BOOLEAN_TAG_NAMES:114 if value not in ('true', 'false'):115 raise ParseException('Tag must be one of "true", "false"', line)116 value = value == 'true'117#118 # if tag in ('union_of', 'disjoint_from'):119 # target is tag id120 elif tag == 'intersection_of':121 match = RE_RELATIONSHIP.match(value)122 if match:123 value = Relationship(self._unescape(match.group('type')),124 self._unescape(match.group('target_term')))125 # else:126 # pass # target is tag id127 elif tag == 'relationship':128 match = RE_RELATIONSHIP.match(value)129 if match:130 value = Relationship(self._unescape(match.group('type')),131 self._unescape(match.group('target_term')))132 else:133 raise ParseException("Malformatted 'relationship'", value)134 elif tag == 'xref':135 match = RE_XREF_DEFINITION.match(value)136 if match:137 value = XRef(self._unescape(match.group('name')),138 self._unescape(match.group('description') or '') or None)139 else:140 raise ParseException("Malformatted 'xref'", value)141 elif tag == 'def':142 match = RE_DESCRIPTION_XREFS.match(value)143 if match:144 description = match.group('description')145 xrefs_value = match.group('xrefs')146 xrefs = []147 xref_match = RE_XREF_DEFINITION_ITEM.match(xrefs_value)148 while xref_match:149 pos = xref_match.end(1)150 xrefs.append(XRef(self._unescape(xref_match.group('name')),151 self._unescape(xref_match.group('description') or '') or None))152 if pos == len(xrefs_value):153 break154 comma_match = RE_XREF_DEFINITION_DIVIDER.match(xrefs_value, pos)155 if not comma_match:156 raise ParseException("Malformatted 'def'", value)157 pos = comma_match.end(0)158 xref_match = RE_XREF_DEFINITION_ITEM.match(xrefs_value, pos)159 value = Definition(description, *xrefs)160 else:161 raise ParseException("Malformatted 'def'", value)162 tag_value_pairs.append((tag, value))163 if stanza is not None:164 stanzas.append((stanza, tag_value_pairs))165 else:166 header = tag_value_pairs167 ontology = Ontology()168 for name, value in header:169 if name == 'subsetdef':170 match = RE_NAME_DESCRIPTION.match(value)171 if match:172 value = TermSubset(self._unescape(match.group('name')), self._unescape(match.group('description')))173 else:174 raise ParseException("Malformatted 'subsetdef'", value)175 elif name == 'synonymtypedef':176 match = RE_SYNONYM_TYPEDEF.match(value)177 if match:178 scope = match.group('scope')179 value = SynonymType(self._unescape(match.group('name')),180 self._unescape(match.group('description')),181 scope=SynonymScope[scope] if scope else None)182 else:183 raise ParseException("Malformatted 'synonymtypedef'", value)184 ontology.add_tag(name, value)185 for stanza, tags in stanzas:186 tags_dict = defaultdict(list)187 for name, value in tags:188 tags_dict[name].append(value)189 if stanza == 'Term':190 ontology.terms.add(Term(**tags_dict))191 # TODO attach subset.192 elif stanza == 'Typedef':193 ontology.typedefs.add(Typedef(**tags_dict))194 elif stanza == 'Instance':...
res_partner.py
Source:res_partner.py
...6# License URL : <https://store.webkul.com/license.html/>7#8##########################################################################9from odoo import api, fields, models10def _unescape(text):11 ##12 # Replaces all encoded characters by urlib with plain utf8 string.13 #14 # @param text source text.15 # @return The plain text.16 from urllib.parse import unquote_plus17 try:18 text = unquote_plus(text)19 return text20 except Exception as e:21 return text22class ResPartner(models.Model):23 _inherit = 'res.partner'24 @api.model25 def create(self, vals):26 ctx = dict(self._context or {})27 ecomm_cannels = dict(self.env['connector.snippet']._get_ecomm_extensions()).keys()28 if any(key in ctx for key in ecomm_cannels):29 vals = self.customer_array(vals)30 return super().create(vals)31 def write(self, vals):32 ctx = dict(self._context or {})33 ecomm_cannels = dict(self.env['connector.snippet']._get_ecomm_extensions()).keys()34 if any(key in ctx for key in ecomm_cannels):35 vals = self.customer_array(vals)36 return super().write(vals)37 def customer_array(self, data):38 dic = {}39 stateModel = self.env['res.country.state']40 country_code = data.pop('country_code', False)41 region = data.pop('region', False)42 if country_code:43 countryObj = self.env['res.country'].search(44 [('code', '=', country_code)], limit=1)45 if countryObj:46 data['country_id'] = countryObj.id47 if region:48 region = _unescape(region)49 stateObj = stateModel.search([50 ('name', '=', region),51 ('country_id', '=', countryObj.id)52 ], limit=1)53 if stateObj:54 data['state_id'] = stateObj.id55 else:56 dic['name'] = region57 dic['country_id'] = countryObj.id58 code = region[:3].upper()59 temp = code60 stateObj = stateModel.search(61 [('code', '=ilike', code)], limit=1)62 counter = 063 while stateObj and counter < 100:64 code = temp + str(counter)65 stateObj = stateModel.search(66 [('code', '=ilike', code)], limit=1)67 counter = counter + 168 if counter == 100:69 code = region.upper()70 dic['code'] = code71 stateObj = stateModel.create(dic)72 data['state_id'] = stateObj.id73 tag = data.pop('tag', False)74 if tag:75 tag = _unescape(tag)76 tag_objs = self.env['res.partner.category'].search(77 [('name', '=', tag)], limit=1)78 if not tag_objs:79 tagId = self.env['res.partner.category'].create({'name': tag})80 else:81 tagId = tag_objs[0].id82 data['category_id'] = [(6, 0, [tagId])]83 data.pop('ecomm_id', None)84 if data.get('wk_company'):85 data['wk_company'] = _unescape(data['wk_company'])86 if data.get('name'):87 data['name'] = _unescape(data['name'])88 if data.get('email'):89 data['email'] = _unescape(data['email'])90 if data.get('street'):91 data['street'] = _unescape(data['street'])92 if data.get('street2'):93 data['street2'] = _unescape(data['street2'])94 if data.get('city'):95 data['city'] = _unescape(data['city'])96 return data97 def _handle_first_contact_creation(self):98 """ On creation of first contact for a company (or root) that has no address, assume contact address99 was meant to be company address """100 parent = self.parent_id101 address_fields = self._address_fields()102 if parent and (103 parent.is_company or not parent.parent_id) and len(104 parent.child_ids) == 1 and any(105 self[f] for f in address_fields) and not any(106 parent[f] for f in address_fields):107 addr_vals = self._update_fields_values(address_fields)108 parent.update_address(addr_vals)109 wk_company = fields.Char(string='Ecomm Company', size=128)
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!!