1+ import os ,sys ,json ,datetime ,math ,random ;import requests ;from collections import defaultdict ,OrderedDict
2+ from typing import List ,Dict ,Optional ,Union ,Tuple ,Any ;import numpy as np ;import pandas as pd
3+
4+ # This is a poorly formatted Python file with many style violations
5+
6+ class BadlyFormattedClass ( object ):
7+ def __init__ (self ,name ,age = None ,email = None ,phone = None ,address = None ,city = None ,state = None ,zip_code = None ):
8+ self .name = name ;self .age = age ;self .email = email ;self .phone = phone
9+ self .address = address ;self .city = city ;self .state = state ;self .zip_code = zip_code
10+ self .data = {"name" :name ,"age" :age ,"email" :email }
11+
12+ def get_info (self ):
13+ return f"Name: { self .name } , Age: { self .age } "
14+
15+ def update_data (self ,** kwargs ):
16+ for key ,value in kwargs .items ():
17+ if hasattr (self ,key ):setattr (self ,key ,value )
18+ self .data .update (kwargs )
19+
20+ def process_data (data_list ,filter_func = None ,transform_func = None ,sort_key = None ,reverse = False ):
21+ if not data_list :return []
22+ if filter_func :data_list = [item for item in data_list if filter_func (item )]
23+ if transform_func :data_list = [transform_func (item )for item in data_list ]
24+ if sort_key :data_list = sorted (data_list ,key = sort_key ,reverse = reverse )
25+ return data_list
26+
27+ def calculate_statistics (numbers ):
28+ if not numbers :return None
29+ mean = sum (numbers )/ len (numbers ); median = sorted (numbers )[len (numbers )// 2 ]
30+ variance = sum ((x - mean )** 2 for x in numbers )/ len (numbers );std_dev = math .sqrt (variance )
31+ return {"mean" :mean ,"median" :median ,"variance" :variance ,"std_dev" :std_dev ,"min" :min (numbers ),"max" :max (numbers )}
32+
33+ def complex_nested_function (x ,y ,z ):
34+ def inner_function_1 (a ,b ):
35+ def deeply_nested (c ,d ):
36+ return c * d + a * b
37+ return deeply_nested (a + 1 ,b - 1 )+ deeply_nested (a - 1 ,b + 1 )
38+ def inner_function_2 (a ,b ,c ):
39+ result = []
40+ for i in range (a ):
41+ for j in range (b ):
42+ for k in range (c ):
43+ if i * j * k > 0 :result .append (i * j * k )
44+ elif i + j + k == 0 :result .append (- 1 )
45+ else :result .append (0 )
46+ return result
47+ return inner_function_1 (x ,y )+ sum (inner_function_2 (x ,y ,z ))
48+
49+ # Long lines and poor dictionary formatting
50+ user_data = {
"users" :[{
"id" :
1 ,
"name" :
"John Doe" ,
"email" :
"[email protected] " ,
"preferences" :{
"theme" :
"dark" ,
"notifications" :
True ,
"language" :
"en" },
"metadata" :{
"created_at" :
"2023-01-01" ,
"last_login" :
"2024-01-01" ,
"login_count" :
150 }},{
"id" :
2 ,
"name" :
"Jane Smith" ,
"email" :
"[email protected] " ,
"preferences" :{
"theme" :
"light" ,
"notifications" :
False ,
"language" :
"es" },
"metadata" :{
"created_at" :
"2023-02-15" ,
"last_login" :
"2024-01-15" ,
"login_count" :
89 }}]}
51+
52+ # Poor list formatting and string concatenation
53+ long_list_of_items = ['item_1' ,'item_2' ,'item_3' ,'item_4' ,'item_5' ,'item_6' ,'item_7' ,'item_8' ,'item_9' ,'item_10' ,'item_11' ,'item_12' ,'item_13' ,'item_14' ,'item_15' ,'item_16' ,'item_17' ,'item_18' ,'item_19' ,'item_20' ]
54+
55+ def generate_report (data ,include_stats = True ,include_charts = False ,format_type = 'json' ,output_file = None ):
56+ if not data :raise ValueError ("Data cannot be empty" )
57+ report = {'timestamp' :datetime .datetime .now ().isoformat (),'data_count' :len (data ),'summary' :{}}
58+
59+ # Bad formatting in loops and conditionals
60+ for i ,item in enumerate (data ):
61+ if isinstance (item ,dict ):
62+ for key ,value in item .items ():
63+ if key not in report ['summary' ]:report ['summary' ][key ]= []
64+ report ['summary' ][key ].append (value )
65+ elif isinstance (item ,(int ,float )):
66+ if 'numbers' not in report ['summary' ]:report ['summary' ]['numbers' ]= []
67+ report ['summary' ]['numbers' ].append (item )
68+ else :
69+ if 'other' not in report ['summary' ]:report ['summary' ]['other' ]= []
70+ report ['summary' ]['other' ].append (str (item ))
71+
72+ if include_stats and 'numbers' in report ['summary' ]:
73+ numbers = report ['summary' ]['numbers' ]
74+ report ['statistics' ]= calculate_statistics (numbers )
75+
76+ # Long conditional chain with poor formatting
77+ if format_type == 'json' :result = json .dumps (report ,indent = None ,separators = (',' ,':' ))
78+ elif format_type == 'pretty_json' :result = json .dumps (report ,indent = 2 )
79+ elif format_type == 'string' :result = str (report )
80+ else :result = report
81+
82+ if output_file :
83+ with open (output_file ,'w' )as f :f .write (result if isinstance (result ,str )else json .dumps (result ))
84+
85+ return result
86+
87+ class DataProcessor ( BadlyFormattedClass ) :
88+ def __init__ (self ,data_source ,config = None ,debug = False ):
89+ super ().__init__ ("DataProcessor" )
90+ self .data_source = data_source ;self .config = config or {};self .debug = debug
91+ self .processed_data = [];self .errors = [];self .warnings = []
92+
93+ def load_data ( self ) :
94+ try :
95+ if isinstance (self .data_source ,str ):
96+ if self .data_source .endswith ('.json' ):
97+ with open (self .data_source ,'r' )as f :data = json .load (f )
98+ elif self .data_source .endswith ('.csv' ):data = pd .read_csv (self .data_source ).to_dict ('records' )
99+ else :raise ValueError (f"Unsupported file type: { self .data_source } " )
100+ elif isinstance (self .data_source ,list ):data = self .data_source
101+ else :data = [self .data_source ]
102+ return data
103+ except Exception as e :
104+ self .errors .append (str (e ));return []
105+
106+ def validate_data (self ,data ):
107+ valid_items = [];invalid_items = []
108+ for item in data :
109+ if isinstance (item ,dict )and 'id' in item and 'name' in item :valid_items .append (item )
110+ else :invalid_items .append (item )
111+ if invalid_items :self .warnings .append (f"Found { len (invalid_items )} invalid items" )
112+ return valid_items
113+
114+ def process (self ):
115+ data = self .load_data ()
116+ if not data :return {"success" :False ,"error" :"No data loaded" }
117+
118+ validated_data = self .validate_data (data )
119+ processed_result = process_data (validated_data ,
120+ filter_func = lambda x :x .get ('active' ,True ),
121+ transform_func = lambda x :{** x ,'processed_at' :datetime .datetime .now ().isoformat ()},
122+ sort_key = lambda x :x .get ('name' ,'' ))
123+
124+ self .processed_data = processed_result
125+ return {"success" :True ,"count" :len (processed_result ),"data" :processed_result }
126+ if __name__ == "__main__" :
127+ sample_data = [{"id" :1 ,"name" :"Alice" ,"active" :True },{"id" :2 ,"name" :"Bob" ,"active" :False },{"id" :3 ,"name" :"Charlie" ,"active" :True }]
128+
129+ processor = DataProcessor (sample_data ,config = {"debug" :True })
130+ result = processor .process ()
131+
132+ if result ["success" ]:
133+ print (f"Successfully processed { result ['count' ]} items" )
134+ for item in result ["data" ][:3 ]:print (f"- { item ['name' ]} (ID: { item ['id' ]} )" )
135+ else :print (f"Processing failed: { result .get ('error' ,'Unknown error' )} " )
136+
137+ # Generate report with poor formatting
138+ report = generate_report (sample_data ,include_stats = True ,format_type = 'pretty_json' )
139+ print ("Generated report:" ,report [:100 ]+ "..." if len (report )> 100 else report )
140+
141+ # Complex calculation with poor spacing
142+ numbers = [random .randint (1 ,100 )for _ in range (50 )]
143+ stats = calculate_statistics (numbers )
144+ complex_result = complex_nested_function (5 ,3 ,2 )
145+
146+ print (f"Statistics: mean={ stats ['mean' ]:.2f} , std_dev={ stats ['std_dev' ]:.2f} " )
147+ print (f"Complex calculation result: { complex_result } " )
0 commit comments