Best Python code snippet using pandera_python
python_parser.py
Source:python_parser.py
...725 else:726 rl.append(x.replace(search, replace))727 ret.append(rl)728 return ret729 def _check_decimal(self, lines: list[list[Scalar]]) -> list[list[Scalar]]:730 if self.decimal == parser_defaults["decimal"]:731 return lines732 return self._search_replace_num_columns(733 lines=lines, search=self.decimal, replace="."734 )735 def _clear_buffer(self) -> None:736 self.buf = []737 _implicit_index = False738 def _get_index_name(self, columns: list[Hashable]):739 """740 Try several cases to get lines:741 0) There are headers on row 0 and row 1 and their742 total summed lengths equals the length of the next line.743 Treat row 0 as columns and row 1 as indices744 1) Look for implicit index: there are more columns745 on row 1 than row 0. If this is true, assume that row746 1 lists index columns and row 0 lists normal columns.747 2) Get index from the columns if it was listed.748 """749 orig_names = list(columns)750 columns = list(columns)751 line: list[Scalar] | None752 if self._header_line is not None:753 line = self._header_line754 else:755 try:756 line = self._next_line()757 except StopIteration:758 line = None759 next_line: list[Scalar] | None760 try:761 next_line = self._next_line()762 except StopIteration:763 next_line = None764 # implicitly index_col=0 b/c 1 fewer column names765 implicit_first_cols = 0766 if line is not None:767 # leave it 0, #2442768 # Case 1769 # error: Cannot determine type of 'index_col'770 index_col = self.index_col # type: ignore[has-type]771 if index_col is not False:772 implicit_first_cols = len(line) - self.num_original_columns773 # Case 0774 if next_line is not None and self.header is not None:775 if len(next_line) == len(line) + self.num_original_columns:776 # column and index names on diff rows777 self.index_col = list(range(len(line)))778 self.buf = self.buf[1:]779 for c in reversed(line):780 columns.insert(0, c)781 # Update list of original names to include all indices.782 orig_names = list(columns)783 self.num_original_columns = len(columns)784 return line, orig_names, columns785 if implicit_first_cols > 0:786 # Case 1787 self._implicit_index = True788 if self.index_col is None:789 self.index_col = list(range(implicit_first_cols))790 index_name = None791 else:792 # Case 2793 (index_name, columns_, self.index_col) = self._clean_index_names(794 columns, self.index_col, self.unnamed_cols795 )796 return index_name, orig_names, columns797 def _rows_to_cols(self, content: list[list[Scalar]]) -> list[np.ndarray]:798 col_len = self.num_original_columns799 if self._implicit_index:800 col_len += len(self.index_col)801 max_len = max(len(row) for row in content)802 # Check that there are no rows with too many803 # elements in their row (rows with too few804 # elements are padded with NaN).805 # error: Non-overlapping identity check (left operand type: "List[int]",806 # right operand type: "Literal[False]")807 if (808 max_len > col_len809 and self.index_col is not False # type: ignore[comparison-overlap]810 and self.usecols is None811 ):812 footers = self.skipfooter if self.skipfooter else 0813 bad_lines = []814 iter_content = enumerate(content)815 content_len = len(content)816 content = []817 for (i, l) in iter_content:818 actual_len = len(l)819 if actual_len > col_len:820 if callable(self.on_bad_lines):821 new_l = self.on_bad_lines(l)822 if new_l is not None:823 content.append(new_l)824 elif (825 self.on_bad_lines == self.BadLineHandleMethod.ERROR826 or self.on_bad_lines == self.BadLineHandleMethod.WARN827 ):828 row_num = self.pos - (content_len - i + footers)829 bad_lines.append((row_num, actual_len))830 if self.on_bad_lines == self.BadLineHandleMethod.ERROR:831 break832 else:833 content.append(l)834 for row_num, actual_len in bad_lines:835 msg = (836 f"Expected {col_len} fields in line {row_num + 1}, saw "837 f"{actual_len}"838 )839 if (840 self.delimiter841 and len(self.delimiter) > 1842 and self.quoting != csv.QUOTE_NONE843 ):844 # see gh-13374845 reason = (846 "Error could possibly be due to quotes being "847 "ignored when a multi-char delimiter is used."848 )849 msg += ". " + reason850 self._alert_malformed(msg, row_num + 1)851 # see gh-13320852 zipped_content = list(lib.to_object_array(content, min_width=col_len).T)853 if self.usecols:854 assert self._col_indices is not None855 col_indices = self._col_indices856 if self._implicit_index:857 zipped_content = [858 a859 for i, a in enumerate(zipped_content)860 if (861 i < len(self.index_col)862 or i - len(self.index_col) in col_indices863 )864 ]865 else:866 zipped_content = [867 a for i, a in enumerate(zipped_content) if i in col_indices868 ]869 return zipped_content870 def _get_lines(self, rows: int | None = None):871 lines = self.buf872 new_rows = None873 # already fetched some number874 if rows is not None:875 # we already have the lines in the buffer876 if len(self.buf) >= rows:877 new_rows, self.buf = self.buf[:rows], self.buf[rows:]878 # need some lines879 else:880 rows -= len(self.buf)881 if new_rows is None:882 if isinstance(self.data, list):883 if self.pos > len(self.data):884 raise StopIteration885 if rows is None:886 new_rows = self.data[self.pos :]887 new_pos = len(self.data)888 else:889 new_rows = self.data[self.pos : self.pos + rows]890 new_pos = self.pos + rows891 new_rows = self._remove_skipped_rows(new_rows)892 lines.extend(new_rows)893 self.pos = new_pos894 else:895 new_rows = []896 try:897 if rows is not None:898 rows_to_skip = 0899 if self.skiprows is not None and self.pos is not None:900 # Only read additional rows if pos is in skiprows901 rows_to_skip = len(902 set(self.skiprows) - set(range(self.pos))903 )904 for _ in range(rows + rows_to_skip):905 # assert for mypy, data is Iterator[str] or None, would906 # error in next907 assert self.data is not None908 new_rows.append(next(self.data))909 len_new_rows = len(new_rows)910 new_rows = self._remove_skipped_rows(new_rows)911 lines.extend(new_rows)912 else:913 rows = 0914 while True:915 new_row = self._next_iter_line(row_num=self.pos + rows + 1)916 rows += 1917 if new_row is not None:918 new_rows.append(new_row)919 len_new_rows = len(new_rows)920 except StopIteration:921 len_new_rows = len(new_rows)922 new_rows = self._remove_skipped_rows(new_rows)923 lines.extend(new_rows)924 if len(lines) == 0:925 raise926 self.pos += len_new_rows927 self.buf = []928 else:929 lines = new_rows930 if self.skipfooter:931 lines = lines[: -self.skipfooter]932 lines = self._check_comments(lines)933 if self.skip_blank_lines:934 lines = self._remove_empty_lines(lines)935 lines = self._check_thousands(lines)936 return self._check_decimal(lines)937 def _remove_skipped_rows(self, new_rows: list[list[Scalar]]) -> list[list[Scalar]]:938 if self.skiprows:939 return [940 row for i, row in enumerate(new_rows) if not self.skipfunc(i + self.pos)941 ]942 return new_rows943class FixedWidthReader(abc.Iterator):944 """945 A reader of fixed-width lines.946 """947 def __init__(948 self,949 f: IO[str],950 colspecs: list[tuple[int, int]] | Literal["infer"],...
res_config.py
Source:res_config.py
...96 'module_project_mrp': fields.boolean("Project MRP"),97 'module_project': fields.boolean("Project"),98 'decimal_precision': fields.integer("Decimal precision on prices:",help="As an example, a decimal precision of 2 will allow prices like: 9.99 EUR, whereas a decimal precision of 4 will allow prices like: 0.0231 EUR per unit."),99 }100 def _check_decimal(self, cr, uid, ids, context=None):101 for decimal in self.browse(cr, uid, ids, context=context):102 if decimal.decimal_precision > 20:103 return False104 return True105 _constraints = [106 (_check_decimal, 'Digits must be between 0 to 20 ', ['decimal_precision']),107 ]108 def default_get(self, cr, uid, fields, context=None):109 ir_model_data = self.pool.get('ir.model.data')110 res = super(sale_configuration, self).default_get(cr, uid, fields, context)111 # task_work, time_unit depend on other fields112 res['task_work'] = res.get('module_project_mrp') and res.get('module_project_timesheet')113 if res.get('module_project'):114 user = self.pool.get('res.users').browse(cr, uid, uid, context)...
conversion.py
Source:conversion.py
...52 if i not in valid_values:53 raise ValueError("Invalid Octal value")54 55 return octal56def _check_decimal(decimal):57 if isinstance(decimal , str):58 if decimal.isdigit():59 decimal = int(decimal)60 else:61 raise ValueError("Invalid Decimal value")62 63 if isinstance(decimal , int) == False:64 raise ValueError("Invalid Decimal value")65 return decimal66def _check_hexadecimal(hexadecimal):67 if isinstance(hexadecimal , str):68 hexadecimal = list(hexadecimal)69 if isinstance(hexadecimal , int):70 hexadecimal = list(str(hexadecimal))71 if isinstance(hexadecimal , list) == False:72 raise SyntaxError("Values should be in list or string format!")73 74 if isinstance(hexadecimal[0] , int):75 valid_values = [0,1,2,3,4,5,6,7,8,9]76 else:77 valid_values = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','a','b','c','d','e','f']78 for i in hexadecimal:79 if i not in valid_values:80 raise ValueError("Invalid Hexadecimal value")81 82 return hexadecimal83def _check_bcd(bcd):84 bcd = _check_binary(bcd)85 if(len(bcd)%4 != 0):86 raise ValueError('Invalid BCD value : length should be multiple of 4')87 return bcd88def _check_gray(gray):89 return _check_binary(gray)90'''Binary to other bases conversion'''91def binary_to_decimal(binary):92 binary = _check_binary(binary)93 94 binary = "".join([str(i) for i in binary])95 return int(binary , 2)96def binary_to_hexadecimal(binary):97 binary = _check_binary(binary)98 99 binary = "".join([str(i) for i in binary])100 '''binary -> decimal ->hexadecimal'''101 decimal = binary_to_decimal(binary)102 hexadecimal = decimal_to_hexadecimal(decimal)103 return hexadecimal104def binary_to_octal(binary):105 binary = _check_binary(binary)106 107 binary = "".join([str(i) for i in binary])108 '''binary -> decimal ->hexadecimal'''109 decimal = binary_to_decimal(binary)110 octal = decimal_to_octal(decimal)111 return octal112'''Decimal to other bases conversion'''113def decimal_to_binary(decimal):114 decimal = _check_decimal(decimal)115 return bin(decimal).replace("0b" , "")116def decimal_to_hexadecimal(decimal):117 decimal = _check_decimal(decimal)118 return hex(decimal).replace("0x" , "")119def decimal_to_octal(decimal):120 decimal = _check_decimal(decimal)121 return oct(decimal).replace("0o" , "")122'''Octal to other bases conversion'''123def octal_to_decimal(octal):124 octal = _check_octal(octal)125 octal = "".join([str(i) for i in octal])126 return int(octal , 8)127def octal_to_binary(octal):128 octal = _check_octal(octal)129 130 '''octal -> decimal -> binary'''131 octal = "".join([str(i) for i in octal])132 decimal = octal_to_decimal(octal)133 binary = decimal_to_binary(decimal)134 return binary...
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!!