ADAPT-Chase commited on
Commit
d06176b
·
verified ·
1 Parent(s): 743debb

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/serena-new/test/resources/repos/php/test_repo/simple_var.php +4 -0
  2. projects/ui/serena-new/test/resources/repos/python/test_repo/.gitignore +1 -0
  3. projects/ui/serena-new/test/resources/repos/python/test_repo/custom_test/__init__.py +3 -0
  4. projects/ui/serena-new/test/resources/repos/python/test_repo/custom_test/advanced_features.py +475 -0
  5. projects/ui/serena-new/test/resources/repos/python/test_repo/examples/__init__.py +3 -0
  6. projects/ui/serena-new/test/resources/repos/python/test_repo/examples/user_management.py +141 -0
  7. projects/ui/serena-new/test/resources/repos/python/test_repo/ignore_this_dir_with_postfix/ignored_module.py +141 -0
  8. projects/ui/serena-new/test/resources/repos/python/test_repo/scripts/__init__.py +3 -0
  9. projects/ui/serena-new/test/resources/repos/python/test_repo/scripts/run_app.py +164 -0
  10. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/__init__.py +0 -0
  11. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/complex_types.py +23 -0
  12. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/models.py +246 -0
  13. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/name_collisions.py +34 -0
  14. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/nested.py +16 -0
  15. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/nested_base.py +75 -0
  16. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/overloaded.py +88 -0
  17. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/services.py +78 -0
  18. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/utils.py +123 -0
  19. projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/variables.py +96 -0
  20. projects/ui/serena-new/test/resources/repos/r/test_repo/.Rbuildignore +3 -0
projects/ui/serena-new/test/resources/repos/php/test_repo/simple_var.php ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ <?php
2
+ $localVar = "test";
3
+ echo $localVar;
4
+ ?>
projects/ui/serena-new/test/resources/repos/python/test_repo/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ ignore_this_dir*/
projects/ui/serena-new/test/resources/repos/python/test_repo/custom_test/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Custom test package for testing code parsing capabilities.
3
+ """
projects/ui/serena-new/test/resources/repos/python/test_repo/custom_test/advanced_features.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Advanced Python features for testing code parsing capabilities.
3
+
4
+ This module contains various advanced Python code patterns to ensure
5
+ that the code parser can correctly handle them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import os
12
+ from abc import ABC, abstractmethod
13
+ from collections.abc import Callable, Iterable
14
+ from contextlib import contextmanager
15
+ from dataclasses import dataclass, field
16
+ from enum import Enum, Flag, IntEnum, auto
17
+ from functools import wraps
18
+ from typing import (
19
+ Annotated,
20
+ Any,
21
+ ClassVar,
22
+ Final,
23
+ Generic,
24
+ Literal,
25
+ NewType,
26
+ Protocol,
27
+ TypedDict,
28
+ TypeVar,
29
+ )
30
+
31
+ # Type variables for generics
32
+ T = TypeVar("T")
33
+ K = TypeVar("K")
34
+ V = TypeVar("V")
35
+
36
+ # Custom types using NewType
37
+ UserId = NewType("UserId", str)
38
+ ItemId = NewType("ItemId", int)
39
+
40
+ # Type aliases
41
+ PathLike = str | os.PathLike
42
+ JsonDict = dict[str, Any]
43
+
44
+
45
+ # TypedDict
46
+ class UserDict(TypedDict):
47
+ """TypedDict representing user data."""
48
+
49
+ id: str
50
+ name: str
51
+ email: str
52
+ age: int
53
+ roles: list[str]
54
+
55
+
56
+ # Enums
57
+ class Status(Enum):
58
+ """Status enum for process states."""
59
+
60
+ PENDING = "pending"
61
+ RUNNING = "running"
62
+ COMPLETED = "completed"
63
+ FAILED = "failed"
64
+
65
+
66
+ class Priority(IntEnum):
67
+ """Priority levels for tasks."""
68
+
69
+ LOW = 0
70
+ MEDIUM = 5
71
+ HIGH = 10
72
+ CRITICAL = auto()
73
+
74
+
75
+ class Permissions(Flag):
76
+ """Permission flags for access control."""
77
+
78
+ NONE = 0
79
+ READ = 1
80
+ WRITE = 2
81
+ EXECUTE = 4
82
+ ALL = READ | WRITE | EXECUTE
83
+
84
+
85
+ # Abstract class with various method types
86
+ class BaseProcessor(ABC):
87
+ """Abstract base class for processors with various method patterns."""
88
+
89
+ # Class variable with type annotation
90
+ DEFAULT_TIMEOUT: ClassVar[int] = 30
91
+ MAX_RETRIES: Final[int] = 3
92
+
93
+ def __init__(self, name: str, config: dict[str, Any] | None = None):
94
+ self.name = name
95
+ self.config = config or {}
96
+ self._status = Status.PENDING
97
+
98
+ @property
99
+ def status(self) -> Status:
100
+ """Status property getter."""
101
+ return self._status
102
+
103
+ @status.setter
104
+ def status(self, value: Status) -> None:
105
+ """Status property setter."""
106
+ if not isinstance(value, Status):
107
+ raise TypeError(f"Expected Status enum, got {type(value)}")
108
+ self._status = value
109
+
110
+ @abstractmethod
111
+ def process(self, data: Any) -> Any:
112
+ """Process the input data."""
113
+
114
+ @classmethod
115
+ def create_from_config(cls, config: dict[str, Any]) -> BaseProcessor:
116
+ """Factory classmethod."""
117
+ name = config.get("name", "default")
118
+ return cls(name=name, config=config)
119
+
120
+ @staticmethod
121
+ def validate_config(config: dict[str, Any]) -> bool:
122
+ """Static method for config validation."""
123
+ return "name" in config
124
+
125
+ def __str__(self) -> str:
126
+ return f"{self.__class__.__name__}(name={self.name})"
127
+
128
+
129
+ # Concrete implementation of abstract class
130
+ class DataProcessor(BaseProcessor):
131
+ """Concrete implementation of BaseProcessor."""
132
+
133
+ def __init__(self, name: str, config: dict[str, Any] | None = None, priority: Priority = Priority.MEDIUM):
134
+ super().__init__(name, config)
135
+ self.priority = priority
136
+ self.processed_count = 0
137
+
138
+ def process(self, data: Any) -> Any:
139
+ """Process the data."""
140
+
141
+ # Nested function definition
142
+ def transform(item: Any) -> Any:
143
+ # Nested function within a nested function
144
+ def apply_rules(x: Any) -> Any:
145
+ return x
146
+
147
+ return apply_rules(item)
148
+
149
+ # Lambda function
150
+ normalize = lambda x: x / max(x) if hasattr(x, "__iter__") and len(x) > 0 else x # noqa: F841
151
+
152
+ result = transform(data)
153
+ self.processed_count += 1
154
+ return result
155
+
156
+ # Method with complex type hints
157
+ def batch_process(self, items: list[str | dict[str, Any] | tuple[Any, ...]]) -> dict[str, list[Any]]:
158
+ """Process multiple items in a batch."""
159
+ results: dict[str, list[Any]] = {"success": [], "error": []}
160
+
161
+ for item in items:
162
+ try:
163
+ result = self.process(item)
164
+ results["success"].append(result)
165
+ except Exception as e:
166
+ results["error"].append((item, str(e)))
167
+
168
+ return results
169
+
170
+ # Generator method
171
+ def process_stream(self, data_stream: Iterable[T]) -> Iterable[T]:
172
+ """Process a stream of data, yielding results as they're processed."""
173
+ for item in data_stream:
174
+ yield self.process(item)
175
+
176
+ # Async method
177
+ async def async_process(self, data: Any) -> Any:
178
+ """Process data asynchronously."""
179
+ await asyncio.sleep(0.1)
180
+ return self.process(data)
181
+
182
+ # Method with function parameters
183
+ def apply_transform(self, data: Any, transform_func: Callable[[Any], Any]) -> Any:
184
+ """Apply a custom transform function to the data."""
185
+ return transform_func(data)
186
+
187
+
188
+ # Dataclass
189
+ @dataclass
190
+ class Task:
191
+ """Task dataclass for tracking work items."""
192
+
193
+ id: str
194
+ name: str
195
+ status: Status = Status.PENDING
196
+ priority: Priority = Priority.MEDIUM
197
+ metadata: dict[str, Any] = field(default_factory=dict)
198
+ dependencies: list[str] = field(default_factory=list)
199
+ created_at: float | None = None
200
+
201
+ def __post_init__(self):
202
+ if self.created_at is None:
203
+ import time
204
+
205
+ self.created_at = time.time()
206
+
207
+ def has_dependencies(self) -> bool:
208
+ """Check if task has dependencies."""
209
+ return len(self.dependencies) > 0
210
+
211
+
212
+ # Generic class
213
+ class Repository(Generic[T]):
214
+ """Generic repository for managing collections of items."""
215
+
216
+ def __init__(self):
217
+ self.items: dict[str, T] = {}
218
+
219
+ def add(self, id: str, item: T) -> None:
220
+ """Add an item to the repository."""
221
+ self.items[id] = item
222
+
223
+ def get(self, id: str) -> T | None:
224
+ """Get an item by id."""
225
+ return self.items.get(id)
226
+
227
+ def remove(self, id: str) -> bool:
228
+ """Remove an item by id."""
229
+ if id in self.items:
230
+ del self.items[id]
231
+ return True
232
+ return False
233
+
234
+ def list_all(self) -> list[T]:
235
+ """List all items."""
236
+ return list(self.items.values())
237
+
238
+
239
+ # Type with Protocol (structural subtyping)
240
+ class Serializable(Protocol):
241
+ """Protocol for objects that can be serialized to dict."""
242
+
243
+ def to_dict(self) -> dict[str, Any]: ...
244
+
245
+
246
+ #
247
+ # Decorator function
248
+ def log_execution(func: Callable) -> Callable:
249
+ """Decorator to log function execution."""
250
+
251
+ @wraps(func)
252
+ def wrapper(*args, **kwargs):
253
+ print(f"Executing {func.__name__}")
254
+ result = func(*args, **kwargs)
255
+ print(f"Finished {func.__name__}")
256
+ return result
257
+
258
+ return wrapper
259
+
260
+
261
+ # Context manager
262
+ @contextmanager
263
+ def transaction_context(name: str = "default"):
264
+ """Context manager for transaction-like operations."""
265
+ print(f"Starting transaction: {name}")
266
+ try:
267
+ yield name
268
+ print(f"Committing transaction: {name}")
269
+ except Exception as e:
270
+ print(f"Rolling back transaction: {name}, error: {e}")
271
+ raise
272
+
273
+
274
+ # Function with complex parameter annotations
275
+ def advanced_search(
276
+ query: str,
277
+ filters: dict[str, Any] | None = None,
278
+ sort_by: str | None = None,
279
+ sort_order: Literal["asc", "desc"] = "asc",
280
+ page: int = 1,
281
+ page_size: int = 10,
282
+ include_metadata: bool = False,
283
+ ) -> tuple[list[dict[str, Any]], int]:
284
+ """
285
+ Advanced search function with many parameters.
286
+
287
+ Returns search results and total count.
288
+ """
289
+ results = []
290
+ total = 0
291
+ # Simulating search functionality
292
+ return results, total
293
+
294
+
295
+ # Class with nested classes
296
+ class OuterClass:
297
+ """Outer class with nested classes and methods."""
298
+
299
+ class NestedClass:
300
+ """Nested class inside OuterClass."""
301
+
302
+ def __init__(self, value: Any):
303
+ self.value = value
304
+
305
+ def get_value(self) -> Any:
306
+ """Get the stored value."""
307
+ return self.value
308
+
309
+ class DeeplyNestedClass:
310
+ """Deeply nested class for testing parser depth capabilities."""
311
+
312
+ def deep_method(self) -> str:
313
+ """Method in deeply nested class."""
314
+ return "deep"
315
+
316
+ def __init__(self, name: str):
317
+ self.name = name
318
+ self.nested = self.NestedClass(name)
319
+
320
+ def get_nested(self) -> NestedClass:
321
+ """Get the nested class instance."""
322
+ return self.nested
323
+
324
+ # Method with nested functions
325
+ def process_with_nested(self, data: Any) -> Any:
326
+ """Method demonstrating deeply nested function definitions."""
327
+
328
+ def level1(x: Any) -> Any:
329
+ """First level nested function."""
330
+
331
+ def level2(y: Any) -> Any:
332
+ """Second level nested function."""
333
+
334
+ def level3(z: Any) -> Any:
335
+ """Third level nested function."""
336
+ return z
337
+
338
+ return level3(y)
339
+
340
+ return level2(x)
341
+
342
+ return level1(data)
343
+
344
+
345
+ # Metaclass example
346
+ class Meta(type):
347
+ """Metaclass example for testing advanced class handling."""
348
+
349
+ def __new__(mcs, name, bases, attrs):
350
+ print(f"Creating class: {name}")
351
+ return super().__new__(mcs, name, bases, attrs)
352
+
353
+ def __init__(cls, name, bases, attrs):
354
+ print(f"Initializing class: {name}")
355
+ super().__init__(name, bases, attrs)
356
+
357
+
358
+ class WithMeta(metaclass=Meta):
359
+ """Class that uses a metaclass."""
360
+
361
+ def __init__(self, value: str):
362
+ self.value = value
363
+
364
+
365
+ # Factory function that creates and returns instances
366
+ def create_processor(processor_type: str, name: str, config: dict[str, Any] | None = None) -> BaseProcessor:
367
+ """Factory function that creates and returns processor instances."""
368
+ if processor_type == "data":
369
+ return DataProcessor(name, config)
370
+ else:
371
+ raise ValueError(f"Unknown processor type: {processor_type}")
372
+
373
+
374
+ # Nested decorator example
375
+ def with_retry(max_retries: int = 3):
376
+ """Decorator factory that creates a retry decorator."""
377
+
378
+ def decorator(func):
379
+ @wraps(func)
380
+ def wrapper(*args, **kwargs):
381
+ for attempt in range(max_retries):
382
+ try:
383
+ return func(*args, **kwargs)
384
+ except Exception as e:
385
+ if attempt == max_retries - 1:
386
+ raise
387
+ print(f"Retrying {func.__name__} after error: {e}")
388
+ return None
389
+
390
+ return wrapper
391
+
392
+ return decorator
393
+
394
+
395
+ @with_retry(max_retries=5)
396
+ def unreliable_operation(data: Any) -> Any:
397
+ """Function that might fail and uses the retry decorator."""
398
+ import random
399
+
400
+ if random.random() < 0.5:
401
+ raise RuntimeError("Random failure")
402
+ return data
403
+
404
+
405
+ # Complex type annotation with Annotated
406
+ ValidatedString = Annotated[str, "A string that has been validated"]
407
+ PositiveInt = Annotated[int, lambda x: x > 0]
408
+
409
+
410
+ def process_validated_data(data: ValidatedString, count: PositiveInt) -> list[str]:
411
+ """Process data with Annotated type hints."""
412
+ return [data] * count
413
+
414
+
415
+ # Example of forward references and string literals in type annotations
416
+ class TreeNode:
417
+ """Tree node with forward reference to itself in annotations."""
418
+
419
+ def __init__(self, value: Any):
420
+ self.value = value
421
+ self.children: list[TreeNode] = []
422
+
423
+ def add_child(self, child: TreeNode) -> None:
424
+ """Add a child node."""
425
+ self.children.append(child)
426
+
427
+ def traverse(self) -> list[Any]:
428
+ """Traverse the tree and return all values."""
429
+ result = [self.value]
430
+ for child in self.children:
431
+ result.extend(child.traverse())
432
+ return result
433
+
434
+
435
+ # Main entry point for demonstration
436
+ def main() -> None:
437
+ """Main function demonstrating the use of various features."""
438
+ # Create processor
439
+ processor = DataProcessor("test-processor", {"debug": True})
440
+
441
+ # Create tasks
442
+ task1 = Task(id="task1", name="First Task")
443
+ task2 = Task(id="task2", name="Second Task", dependencies=["task1"])
444
+
445
+ # Create repository
446
+ repo: Repository[Task] = Repository()
447
+ repo.add(task1.id, task1)
448
+ repo.add(task2.id, task2)
449
+
450
+ # Process some data
451
+ data = [1, 2, 3, 4, 5]
452
+ result = processor.process(data) # noqa: F841
453
+
454
+ # Use context manager
455
+ with transaction_context("main"):
456
+ # Process more data
457
+ for task in repo.list_all():
458
+ processor.process(task.name)
459
+
460
+ # Use advanced search
461
+ results, total = advanced_search(query="test", filters={"status": Status.PENDING}, sort_by="priority", page=1, include_metadata=True)
462
+
463
+ # Create a tree
464
+ root = TreeNode("root")
465
+ child1 = TreeNode("child1")
466
+ child2 = TreeNode("child2")
467
+ root.add_child(child1)
468
+ root.add_child(child2)
469
+ child1.add_child(TreeNode("grandchild1"))
470
+
471
+ print("Done!")
472
+
473
+
474
+ if __name__ == "__main__":
475
+ main()
projects/ui/serena-new/test/resources/repos/python/test_repo/examples/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Examples package for demonstrating test_repo module usage.
3
+ """
projects/ui/serena-new/test/resources/repos/python/test_repo/examples/user_management.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Example demonstrating user management with the test_repo module.
3
+
4
+ This example showcases:
5
+ - Creating and managing users
6
+ - Using various object types and relationships
7
+ - Type annotations and complex Python patterns
8
+ """
9
+
10
+ import logging
11
+ from dataclasses import dataclass
12
+ from typing import Any
13
+
14
+ from test_repo.models import User, create_user_object
15
+ from test_repo.services import UserService
16
+
17
+ # Set up logging
18
+ logging.basicConfig(level=logging.INFO)
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ @dataclass
23
+ class UserStats:
24
+ """Statistics about user activity."""
25
+
26
+ user_id: str
27
+ login_count: int = 0
28
+ last_active_days: int = 0
29
+ engagement_score: float = 0.0
30
+
31
+ def is_active(self) -> bool:
32
+ """Check if the user is considered active."""
33
+ return self.last_active_days < 30
34
+
35
+
36
+ class UserManager:
37
+ """Example class demonstrating complex user management."""
38
+
39
+ def __init__(self, service: UserService):
40
+ self.service = service
41
+ self.active_users: dict[str, User] = {}
42
+ self.user_stats: dict[str, UserStats] = {}
43
+
44
+ def register_user(self, name: str, email: str, roles: list[str] | None = None) -> User:
45
+ """Register a new user."""
46
+ logger.info(f"Registering new user: {name} ({email})")
47
+ user = self.service.create_user(name=name, email=email, roles=roles)
48
+ self.active_users[user.id] = user
49
+ self.user_stats[user.id] = UserStats(user_id=user.id)
50
+ return user
51
+
52
+ def get_user(self, user_id: str) -> User | None:
53
+ """Get a user by ID."""
54
+ if user_id in self.active_users:
55
+ return self.active_users[user_id]
56
+
57
+ # Try to fetch from service
58
+ user = self.service.get_user(user_id)
59
+ if user:
60
+ self.active_users[user.id] = user
61
+ return user
62
+
63
+ def update_user_stats(self, user_id: str, login_count: int, days_since_active: int) -> None:
64
+ """Update statistics for a user."""
65
+ if user_id not in self.user_stats:
66
+ self.user_stats[user_id] = UserStats(user_id=user_id)
67
+
68
+ stats = self.user_stats[user_id]
69
+ stats.login_count = login_count
70
+ stats.last_active_days = days_since_active
71
+
72
+ # Calculate engagement score based on activity
73
+ engagement = (100 - min(days_since_active, 100)) * 0.8
74
+ engagement += min(login_count, 20) * 0.2
75
+ stats.engagement_score = engagement
76
+
77
+ def get_active_users(self) -> list[User]:
78
+ """Get all active users."""
79
+ active_user_ids = [user_id for user_id, stats in self.user_stats.items() if stats.is_active()]
80
+ return [self.active_users[user_id] for user_id in active_user_ids if user_id in self.active_users]
81
+
82
+ def get_user_by_email(self, email: str) -> User | None:
83
+ """Find a user by their email address."""
84
+ for user in self.active_users.values():
85
+ if user.email == email:
86
+ return user
87
+ return None
88
+
89
+
90
+ # Example function demonstrating type annotations
91
+ def process_user_data(users: list[User], include_inactive: bool = False, transform_func: callable | None = None) -> dict[str, Any]:
92
+ """Process user data with optional transformations."""
93
+ result: dict[str, Any] = {"users": [], "total": 0, "admin_count": 0}
94
+
95
+ for user in users:
96
+ if transform_func:
97
+ user_data = transform_func(user.to_dict())
98
+ else:
99
+ user_data = user.to_dict()
100
+
101
+ result["users"].append(user_data)
102
+ result["total"] += 1
103
+
104
+ if "admin" in user.roles:
105
+ result["admin_count"] += 1
106
+
107
+ return result
108
+
109
+
110
+ def main():
111
+ """Main function demonstrating the usage of UserManager."""
112
+ # Initialize service and manager
113
+ service = UserService()
114
+ manager = UserManager(service)
115
+
116
+ # Register some users
117
+ admin = manager.register_user("Admin User", "admin@example.com", ["admin"])
118
+ user1 = manager.register_user("Regular User", "user@example.com", ["user"])
119
+ user2 = manager.register_user("Another User", "another@example.com", ["user"])
120
+
121
+ # Update some stats
122
+ manager.update_user_stats(admin.id, 100, 5)
123
+ manager.update_user_stats(user1.id, 50, 10)
124
+ manager.update_user_stats(user2.id, 10, 45) # Inactive user
125
+
126
+ # Get active users
127
+ active_users = manager.get_active_users()
128
+ logger.info(f"Active users: {len(active_users)}")
129
+
130
+ # Process user data
131
+ user_data = process_user_data(active_users, transform_func=lambda u: {**u, "full_name": u.get("name", "")})
132
+
133
+ logger.info(f"Processed {user_data['total']} users, {user_data['admin_count']} admins")
134
+
135
+ # Example of calling create_user directly
136
+ external_user = create_user_object(id="ext123", name="External User", email="external@example.org", roles=["external"])
137
+ logger.info(f"Created external user: {external_user.name}")
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()
projects/ui/serena-new/test/resources/repos/python/test_repo/ignore_this_dir_with_postfix/ignored_module.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Example demonstrating user management with the test_repo module.
3
+
4
+ This example showcases:
5
+ - Creating and managing users
6
+ - Using various object types and relationships
7
+ - Type annotations and complex Python patterns
8
+ """
9
+
10
+ import logging
11
+ from dataclasses import dataclass
12
+ from typing import Any
13
+
14
+ from test_repo.models import User, create_user_object
15
+ from test_repo.services import UserService
16
+
17
+ # Set up logging
18
+ logging.basicConfig(level=logging.INFO)
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ @dataclass
23
+ class UserStats:
24
+ """Statistics about user activity."""
25
+
26
+ user_id: str
27
+ login_count: int = 0
28
+ last_active_days: int = 0
29
+ engagement_score: float = 0.0
30
+
31
+ def is_active(self) -> bool:
32
+ """Check if the user is considered active."""
33
+ return self.last_active_days < 30
34
+
35
+
36
+ class UserManager:
37
+ """Example class demonstrating complex user management."""
38
+
39
+ def __init__(self, service: UserService):
40
+ self.service = service
41
+ self.active_users: dict[str, User] = {}
42
+ self.user_stats: dict[str, UserStats] = {}
43
+
44
+ def register_user(self, name: str, email: str, roles: list[str] | None = None) -> User:
45
+ """Register a new user."""
46
+ logger.info(f"Registering new user: {name} ({email})")
47
+ user = self.service.create_user(name=name, email=email, roles=roles)
48
+ self.active_users[user.id] = user
49
+ self.user_stats[user.id] = UserStats(user_id=user.id)
50
+ return user
51
+
52
+ def get_user(self, user_id: str) -> User | None:
53
+ """Get a user by ID."""
54
+ if user_id in self.active_users:
55
+ return self.active_users[user_id]
56
+
57
+ # Try to fetch from service
58
+ user = self.service.get_user(user_id)
59
+ if user:
60
+ self.active_users[user.id] = user
61
+ return user
62
+
63
+ def update_user_stats(self, user_id: str, login_count: int, days_since_active: int) -> None:
64
+ """Update statistics for a user."""
65
+ if user_id not in self.user_stats:
66
+ self.user_stats[user_id] = UserStats(user_id=user_id)
67
+
68
+ stats = self.user_stats[user_id]
69
+ stats.login_count = login_count
70
+ stats.last_active_days = days_since_active
71
+
72
+ # Calculate engagement score based on activity
73
+ engagement = (100 - min(days_since_active, 100)) * 0.8
74
+ engagement += min(login_count, 20) * 0.2
75
+ stats.engagement_score = engagement
76
+
77
+ def get_active_users(self) -> list[User]:
78
+ """Get all active users."""
79
+ active_user_ids = [user_id for user_id, stats in self.user_stats.items() if stats.is_active()]
80
+ return [self.active_users[user_id] for user_id in active_user_ids if user_id in self.active_users]
81
+
82
+ def get_user_by_email(self, email: str) -> User | None:
83
+ """Find a user by their email address."""
84
+ for user in self.active_users.values():
85
+ if user.email == email:
86
+ return user
87
+ return None
88
+
89
+
90
+ # Example function demonstrating type annotations
91
+ def process_user_data(users: list[User], include_inactive: bool = False, transform_func: callable | None = None) -> dict[str, Any]:
92
+ """Process user data with optional transformations."""
93
+ result: dict[str, Any] = {"users": [], "total": 0, "admin_count": 0}
94
+
95
+ for user in users:
96
+ if transform_func:
97
+ user_data = transform_func(user.to_dict())
98
+ else:
99
+ user_data = user.to_dict()
100
+
101
+ result["users"].append(user_data)
102
+ result["total"] += 1
103
+
104
+ if "admin" in user.roles:
105
+ result["admin_count"] += 1
106
+
107
+ return result
108
+
109
+
110
+ def main():
111
+ """Main function demonstrating the usage of UserManager."""
112
+ # Initialize service and manager
113
+ service = UserService()
114
+ manager = UserManager(service)
115
+
116
+ # Register some users
117
+ admin = manager.register_user("Admin User", "admin@example.com", ["admin"])
118
+ user1 = manager.register_user("Regular User", "user@example.com", ["user"])
119
+ user2 = manager.register_user("Another User", "another@example.com", ["user"])
120
+
121
+ # Update some stats
122
+ manager.update_user_stats(admin.id, 100, 5)
123
+ manager.update_user_stats(user1.id, 50, 10)
124
+ manager.update_user_stats(user2.id, 10, 45) # Inactive user
125
+
126
+ # Get active users
127
+ active_users = manager.get_active_users()
128
+ logger.info(f"Active users: {len(active_users)}")
129
+
130
+ # Process user data
131
+ user_data = process_user_data(active_users, transform_func=lambda u: {**u, "full_name": u.get("name", "")})
132
+
133
+ logger.info(f"Processed {user_data['total']} users, {user_data['admin_count']} admins")
134
+
135
+ # Example of calling create_user directly
136
+ external_user = create_user_object(id="ext123", name="External User", email="external@example.org", roles=["external"])
137
+ logger.info(f"Created external user: {external_user.name}")
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()
projects/ui/serena-new/test/resources/repos/python/test_repo/scripts/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Scripts package containing entry point scripts for the application.
3
+ """
projects/ui/serena-new/test/resources/repos/python/test_repo/scripts/run_app.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ Main entry point script for the test_repo application.
4
+
5
+ This script demonstrates how a typical application entry point would be structured,
6
+ with command-line arguments, configuration loading, and service initialization.
7
+ """
8
+
9
+ import argparse
10
+ import json
11
+ import logging
12
+ import os
13
+ import sys
14
+ from typing import Any
15
+
16
+ # Add parent directory to path to make imports work
17
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
18
+
19
+ from test_repo.models import Item, User
20
+ from test_repo.services import ItemService, UserService
21
+
22
+ # Configure logging
23
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ def parse_args():
28
+ """Parse command line arguments."""
29
+ parser = argparse.ArgumentParser(description="Test Repo Application")
30
+
31
+ parser.add_argument("--config", type=str, default="config.json", help="Path to configuration file")
32
+
33
+ parser.add_argument("--mode", choices=["user", "item", "both"], default="both", help="Operation mode")
34
+
35
+ parser.add_argument("--verbose", action="store_true", help="Enable verbose logging")
36
+
37
+ return parser.parse_args()
38
+
39
+
40
+ def load_config(config_path: str) -> dict[str, Any]:
41
+ """Load configuration from a JSON file."""
42
+ if not os.path.exists(config_path):
43
+ logger.warning(f"Configuration file not found: {config_path}")
44
+ return {}
45
+
46
+ try:
47
+ with open(config_path, encoding="utf-8") as f:
48
+ return json.load(f)
49
+ except json.JSONDecodeError:
50
+ logger.error(f"Invalid JSON in configuration file: {config_path}")
51
+ return {}
52
+ except Exception as e:
53
+ logger.error(f"Error loading configuration: {e}")
54
+ return {}
55
+
56
+
57
+ def create_sample_users(service: UserService, count: int = 3) -> list[User]:
58
+ """Create sample users for demonstration."""
59
+ users = []
60
+
61
+ # Create admin user
62
+ admin = service.create_user(name="Admin User", email="admin@example.com", roles=["admin"])
63
+ users.append(admin)
64
+
65
+ # Create regular users
66
+ for i in range(count - 1):
67
+ user = service.create_user(name=f"User {i + 1}", email=f"user{i + 1}@example.com", roles=["user"])
68
+ users.append(user)
69
+
70
+ return users
71
+
72
+
73
+ def create_sample_items(service: ItemService, count: int = 5) -> list[Item]:
74
+ """Create sample items for demonstration."""
75
+ categories = ["Electronics", "Books", "Clothing", "Food", "Other"]
76
+ items = []
77
+
78
+ for i in range(count):
79
+ category = categories[i % len(categories)]
80
+ item = service.create_item(name=f"Item {i + 1}", price=10.0 * (i + 1), category=category)
81
+ items.append(item)
82
+
83
+ return items
84
+
85
+
86
+ def run_user_operations(service: UserService, config: dict[str, Any]) -> None:
87
+ """Run operations related to users."""
88
+ logger.info("Running user operations")
89
+
90
+ # Get configuration
91
+ user_count = config.get("user_count", 3)
92
+
93
+ # Create users
94
+ users = create_sample_users(service, user_count)
95
+ logger.info(f"Created {len(users)} users")
96
+
97
+ # Demonstrate some operations
98
+ for user in users:
99
+ logger.info(f"User: {user.name} (ID: {user.id})")
100
+
101
+ # Access a method to demonstrate method calls
102
+ if user.has_role("admin"):
103
+ logger.info(f"{user.name} is an admin")
104
+
105
+ # Lookup a user
106
+ found_user = service.get_user(users[0].id)
107
+ if found_user:
108
+ logger.info(f"Found user: {found_user.name}")
109
+
110
+
111
+ def run_item_operations(service: ItemService, config: dict[str, Any]) -> None:
112
+ """Run operations related to items."""
113
+ logger.info("Running item operations")
114
+
115
+ # Get configuration
116
+ item_count = config.get("item_count", 5)
117
+
118
+ # Create items
119
+ items = create_sample_items(service, item_count)
120
+ logger.info(f"Created {len(items)} items")
121
+
122
+ # Demonstrate some operations
123
+ total_price = 0.0
124
+ for item in items:
125
+ price_display = item.get_display_price()
126
+ logger.info(f"Item: {item.name}, Price: {price_display}")
127
+ total_price += item.price
128
+
129
+ logger.info(f"Total price of all items: ${total_price:.2f}")
130
+
131
+
132
+ def main():
133
+ """Main entry point for the application."""
134
+ # Parse command line arguments
135
+ args = parse_args()
136
+
137
+ # Configure logging level
138
+ if args.verbose:
139
+ logging.getLogger().setLevel(logging.DEBUG)
140
+
141
+ logger.info("Starting Test Repo Application")
142
+
143
+ # Load configuration
144
+ config = load_config(args.config)
145
+ logger.debug(f"Loaded configuration: {config}")
146
+
147
+ # Initialize services
148
+ user_service = UserService()
149
+ item_service = ItemService()
150
+
151
+ # Run operations based on mode
152
+ if args.mode in ("user", "both"):
153
+ run_user_operations(user_service, config)
154
+
155
+ if args.mode in ("item", "both"):
156
+ run_item_operations(item_service, config)
157
+
158
+ logger.info("Application completed successfully")
159
+
160
+
161
+ item_reference = Item(id="1", name="Item 1", price=10.0, category="Electronics")
162
+
163
+ if __name__ == "__main__":
164
+ main()
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/__init__.py ADDED
File without changes
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/complex_types.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TypedDict
2
+
3
+ a: list[int] = [1]
4
+
5
+
6
+ class CustomListInt(list[int]):
7
+ def some_method(self):
8
+ pass
9
+
10
+
11
+ class CustomTypedDict(TypedDict):
12
+ a: int
13
+ b: str
14
+
15
+
16
+ class Outer2:
17
+ class InnerTypedDict(TypedDict):
18
+ a: int
19
+ b: str
20
+
21
+
22
+ class ComplexExtension(Outer2.InnerTypedDict, total=False):
23
+ c: bool
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/models.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Models module that demonstrates various Python class patterns.
3
+ """
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import Any, Generic, TypeVar
7
+
8
+ T = TypeVar("T")
9
+
10
+
11
+ class BaseModel(ABC):
12
+ """
13
+ Abstract base class for all models.
14
+ """
15
+
16
+ def __init__(self, id: str, name: str | None = None):
17
+ self.id = id
18
+ self.name = name or id
19
+
20
+ @abstractmethod
21
+ def to_dict(self) -> dict[str, Any]:
22
+ """Convert model to dictionary representation"""
23
+
24
+ @classmethod
25
+ def from_dict(cls, data: dict[str, Any]) -> "BaseModel":
26
+ """Create a model instance from dictionary data"""
27
+ id = data.get("id", "")
28
+ name = data.get("name")
29
+ return cls(id=id, name=name)
30
+
31
+
32
+ class User(BaseModel):
33
+ """
34
+ User model representing a system user.
35
+ """
36
+
37
+ def __init__(self, id: str, name: str | None = None, email: str = "", roles: list[str] | None = None):
38
+ super().__init__(id, name)
39
+ self.email = email
40
+ self.roles = roles or []
41
+
42
+ def to_dict(self) -> dict[str, Any]:
43
+ return {"id": self.id, "name": self.name, "email": self.email, "roles": self.roles}
44
+
45
+ @classmethod
46
+ def from_dict(cls, data: dict[str, Any]) -> "User":
47
+ instance = super().from_dict(data)
48
+ instance.email = data.get("email", "")
49
+ instance.roles = data.get("roles", [])
50
+ return instance
51
+
52
+ def has_role(self, role: str) -> bool:
53
+ """Check if user has a specific role"""
54
+ return role in self.roles
55
+
56
+
57
+ class Item(BaseModel):
58
+ """
59
+ Item model representing a product or service.
60
+ """
61
+
62
+ def __init__(self, id: str, name: str | None = None, price: float = 0.0, category: str = ""):
63
+ super().__init__(id, name)
64
+ self.price = price
65
+ self.category = category
66
+
67
+ def to_dict(self) -> dict[str, Any]:
68
+ return {"id": self.id, "name": self.name, "price": self.price, "category": self.category}
69
+
70
+ def get_display_price(self) -> str:
71
+ """Format price for display"""
72
+ return f"${self.price:.2f}"
73
+
74
+
75
+ # Generic type example
76
+ class Collection(Generic[T]):
77
+ def __init__(self, items: list[T] | None = None):
78
+ self.items = items or []
79
+
80
+ def add(self, item: T) -> None:
81
+ self.items.append(item)
82
+
83
+ def get_all(self) -> list[T]:
84
+ return self.items
85
+
86
+
87
+ # Factory function
88
+ def create_user_object(id: str, name: str, email: str, roles: list[str] | None = None) -> User:
89
+ """Factory function to create a user"""
90
+ return User(id=id, name=name, email=email, roles=roles)
91
+
92
+
93
+ # Multiple inheritance examples
94
+
95
+
96
+ class Loggable:
97
+ """
98
+ Mixin class that provides logging functionality.
99
+ Example of a common mixin pattern used with multiple inheritance.
100
+ """
101
+
102
+ def __init__(self, **kwargs):
103
+ super().__init__(**kwargs)
104
+ self.log_entries: list[str] = []
105
+
106
+ def log(self, message: str) -> None:
107
+ """Add a log entry"""
108
+ self.log_entries.append(message)
109
+
110
+ def get_logs(self) -> list[str]:
111
+ """Get all log entries"""
112
+ return self.log_entries
113
+
114
+
115
+ class Serializable:
116
+ """
117
+ Mixin class that provides JSON serialization capabilities.
118
+ Another example of a mixin for multiple inheritance.
119
+ """
120
+
121
+ def __init__(self, **kwargs):
122
+ super().__init__(**kwargs)
123
+
124
+ def to_json(self) -> dict[str, Any]:
125
+ """Convert to JSON-serializable dictionary"""
126
+ return self.to_dict() if hasattr(self, "to_dict") else {}
127
+
128
+ @classmethod
129
+ def from_json(cls, data: dict[str, Any]) -> Any:
130
+ """Create instance from JSON data"""
131
+ return cls.from_dict(data) if hasattr(cls, "from_dict") else cls(**data)
132
+
133
+
134
+ class Auditable:
135
+ """
136
+ Mixin for tracking creation and modification timestamps.
137
+ """
138
+
139
+ def __init__(self, **kwargs):
140
+ super().__init__(**kwargs)
141
+ self.created_at: str = kwargs.get("created_at", "")
142
+ self.updated_at: str = kwargs.get("updated_at", "")
143
+
144
+ def update_timestamp(self, timestamp: str) -> None:
145
+ """Update the last modified timestamp"""
146
+ self.updated_at = timestamp
147
+
148
+
149
+ # Diamond inheritance pattern
150
+ class BaseService(ABC):
151
+ """
152
+ Base class for service objects - demonstrates diamond inheritance pattern.
153
+ """
154
+
155
+ def __init__(self, name: str = "base"):
156
+ self.service_name = name
157
+
158
+ @abstractmethod
159
+ def get_service_info(self) -> dict[str, str]:
160
+ """Get service information"""
161
+
162
+
163
+ class DataService(BaseService):
164
+ """
165
+ Data handling service.
166
+ """
167
+
168
+ def __init__(self, **kwargs):
169
+ name = kwargs.pop("name", "data")
170
+ super().__init__(name=name)
171
+ self.data_source = kwargs.get("data_source", "default")
172
+
173
+ def get_service_info(self) -> dict[str, str]:
174
+ return {"service_type": "data", "service_name": self.service_name, "data_source": self.data_source}
175
+
176
+
177
+ class NetworkService(BaseService):
178
+ """
179
+ Network connectivity service.
180
+ """
181
+
182
+ def __init__(self, **kwargs):
183
+ name = kwargs.pop("name", "network")
184
+ super().__init__(name=name)
185
+ self.endpoint = kwargs.get("endpoint", "localhost")
186
+
187
+ def get_service_info(self) -> dict[str, str]:
188
+ return {"service_type": "network", "service_name": self.service_name, "endpoint": self.endpoint}
189
+
190
+
191
+ class DataSyncService(DataService, NetworkService):
192
+ """
193
+ Service that syncs data over network - example of diamond inheritance.
194
+ Inherits from both DataService and NetworkService, which both inherit from BaseService.
195
+ """
196
+
197
+ def __init__(self, **kwargs):
198
+ super().__init__(**kwargs)
199
+ self.sync_interval = kwargs.get("sync_interval", 60)
200
+
201
+ def get_service_info(self) -> dict[str, str]:
202
+ info = super().get_service_info()
203
+ info.update({"service_type": "data_sync", "sync_interval": str(self.sync_interval)})
204
+ return info
205
+
206
+
207
+ # Multiple inheritance with mixins
208
+
209
+
210
+ class LoggableUser(User, Loggable):
211
+ """
212
+ User class with logging capabilities.
213
+ Example of extending a concrete class with a mixin.
214
+ """
215
+
216
+ def __init__(self, id: str, name: str | None = None, email: str = "", roles: list[str] | None = None):
217
+ super().__init__(id=id, name=name, email=email, roles=roles)
218
+
219
+ def add_role(self, role: str) -> None:
220
+ """Add a role to the user and log the action"""
221
+ if role not in self.roles:
222
+ self.roles.append(role)
223
+ self.log(f"Added role '{role}' to user {self.id}")
224
+
225
+
226
+ class TrackedItem(Item, Serializable, Auditable):
227
+ """
228
+ Item with serialization and auditing capabilities.
229
+ Example of a class inheriting from a concrete class and multiple mixins.
230
+ """
231
+
232
+ def __init__(
233
+ self, id: str, name: str | None = None, price: float = 0.0, category: str = "", created_at: str = "", updated_at: str = ""
234
+ ):
235
+ super().__init__(id=id, name=name, price=price, category=category, created_at=created_at, updated_at=updated_at)
236
+ self.stock_level = 0
237
+
238
+ def update_stock(self, quantity: int) -> None:
239
+ """Update stock level and timestamp"""
240
+ self.stock_level = quantity
241
+ self.update_timestamp(f"stock_update_{quantity}")
242
+
243
+ def to_dict(self) -> dict[str, Any]:
244
+ result = super().to_dict()
245
+ result.update({"stock_level": self.stock_level, "created_at": self.created_at, "updated_at": self.updated_at})
246
+ return result
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/name_collisions.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ruff: noqa
2
+ var_will_be_overwritten = 1
3
+
4
+ var_will_be_overwritten = 2
5
+
6
+
7
+ def func_using_overwritten_var():
8
+ print(var_will_be_overwritten)
9
+
10
+
11
+ class ClassWillBeOverwritten:
12
+ def method1(self):
13
+ pass
14
+
15
+
16
+ class ClassWillBeOverwritten:
17
+ def method2(self):
18
+ pass
19
+
20
+
21
+ def func_will_be_overwritten():
22
+ pass
23
+
24
+
25
+ def func_will_be_overwritten():
26
+ pass
27
+
28
+
29
+ def func_calling_overwritten_func():
30
+ func_will_be_overwritten()
31
+
32
+
33
+ def func_calling_overwritten_class():
34
+ ClassWillBeOverwritten()
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/nested.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class OuterClass:
2
+ class NestedClass:
3
+ def find_me(self):
4
+ pass
5
+
6
+ def nested_test(self):
7
+ class WithinMethod:
8
+ pass
9
+
10
+ def func_within_func():
11
+ pass
12
+
13
+ a = self.NestedClass() # noqa: F841
14
+
15
+
16
+ b = OuterClass().NestedClass().find_me()
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/nested_base.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module to test parsing of classes with nested module paths in base classes.
3
+ """
4
+
5
+ from typing import Generic, TypeVar
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ class BaseModule:
11
+ """Base module class for nested module tests."""
12
+
13
+
14
+ class SubModule:
15
+ """Sub-module class for nested paths."""
16
+
17
+ class NestedBase:
18
+ """Nested base class."""
19
+
20
+ def base_method(self):
21
+ """Base method."""
22
+ return "base"
23
+
24
+ class NestedLevel2:
25
+ """Nested level 2."""
26
+
27
+ def nested_level_2_method(self):
28
+ """Nested level 2 method."""
29
+ return "nested_level_2"
30
+
31
+ class GenericBase(Generic[T]):
32
+ """Generic nested base class."""
33
+
34
+ def generic_method(self, value: T) -> T:
35
+ """Generic method."""
36
+ return value
37
+
38
+
39
+ # Classes extending base classes with single-level nesting
40
+ class FirstLevel(SubModule):
41
+ """Class extending a class from a nested module path."""
42
+
43
+ def first_level_method(self):
44
+ """First level method."""
45
+ return "first"
46
+
47
+
48
+ # Classes extending base classes with multi-level nesting
49
+ class TwoLevel(SubModule.NestedBase):
50
+ """Class extending a doubly-nested base class."""
51
+
52
+ def multi_level_method(self):
53
+ """Multi-level method."""
54
+ return "multi"
55
+
56
+ def base_method(self):
57
+ """Override of base method."""
58
+ return "overridden"
59
+
60
+
61
+ class ThreeLevel(SubModule.NestedBase.NestedLevel2):
62
+ """Class extending a triply-nested base class."""
63
+
64
+ def three_level_method(self):
65
+ """Three-level method."""
66
+ return "three"
67
+
68
+
69
+ # Class extending a generic base class with nesting
70
+ class GenericExtension(SubModule.GenericBase[str]):
71
+ """Class extending a generic nested base class."""
72
+
73
+ def generic_extension_method(self, text: str) -> str:
74
+ """Extension method."""
75
+ return f"Extended: {text}"
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/overloaded.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module demonstrating function and method overloading with typing.overload
3
+ """
4
+
5
+ from typing import Any, overload
6
+
7
+
8
+ # Example of function overloading
9
+ @overload
10
+ def process_data(data: str) -> dict[str, str]: ...
11
+
12
+
13
+ @overload
14
+ def process_data(data: int) -> dict[str, int]: ...
15
+
16
+
17
+ @overload
18
+ def process_data(data: list[str | int]) -> dict[str, list[str | int]]: ...
19
+
20
+
21
+ def process_data(data: str | int | list[str | int]) -> dict[str, Any]:
22
+ """
23
+ Process data based on its type.
24
+
25
+ - If string: returns a dict with 'value': <string>
26
+ - If int: returns a dict with 'value': <int>
27
+ - If list: returns a dict with 'value': <list>
28
+ """
29
+ return {"value": data}
30
+
31
+
32
+ # Class with overloaded methods
33
+ class DataProcessor:
34
+ """
35
+ A class demonstrating method overloading.
36
+ """
37
+
38
+ @overload
39
+ def transform(self, input_value: str) -> str: ...
40
+
41
+ @overload
42
+ def transform(self, input_value: int) -> int: ...
43
+
44
+ @overload
45
+ def transform(self, input_value: list[Any]) -> list[Any]: ...
46
+
47
+ def transform(self, input_value: str | int | list[Any]) -> str | int | list[Any]:
48
+ """
49
+ Transform input based on its type.
50
+
51
+ - If string: returns the string in uppercase
52
+ - If int: returns the int multiplied by 2
53
+ - If list: returns the list sorted
54
+ """
55
+ if isinstance(input_value, str):
56
+ return input_value.upper()
57
+ elif isinstance(input_value, int):
58
+ return input_value * 2
59
+ elif isinstance(input_value, list):
60
+ try:
61
+ return sorted(input_value)
62
+ except TypeError:
63
+ return input_value
64
+ return input_value
65
+
66
+ @overload
67
+ def fetch(self, id: int) -> dict[str, Any]: ...
68
+
69
+ @overload
70
+ def fetch(self, id: str, cache: bool = False) -> dict[str, Any] | None: ...
71
+
72
+ def fetch(self, id: int | str, cache: bool = False) -> dict[str, Any] | None:
73
+ """
74
+ Fetch data for a given ID.
75
+
76
+ Args:
77
+ id: The ID to fetch, either numeric or string
78
+ cache: Whether to use cache for string IDs
79
+
80
+ Returns:
81
+ Data dictionary or None if not found
82
+
83
+ """
84
+ # Implementation would actually fetch data
85
+ if isinstance(id, int):
86
+ return {"id": id, "type": "numeric"}
87
+ else:
88
+ return {"id": id, "type": "string", "cached": cache}
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/services.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Services module demonstrating function usage and dependencies.
3
+ """
4
+
5
+ from typing import Any
6
+
7
+ from .models import Item, User
8
+
9
+
10
+ class UserService:
11
+ """Service for user-related operations"""
12
+
13
+ def __init__(self, user_db: dict[str, User] | None = None):
14
+ self.users = user_db or {}
15
+
16
+ def create_user(self, id: str, name: str, email: str) -> User:
17
+ """Create a new user and store it"""
18
+ if id in self.users:
19
+ raise ValueError(f"User with ID {id} already exists")
20
+
21
+ user = User(id=id, name=name, email=email)
22
+ self.users[id] = user
23
+ return user
24
+
25
+ def get_user(self, id: str) -> User | None:
26
+ """Get a user by ID"""
27
+ return self.users.get(id)
28
+
29
+ def list_users(self) -> list[User]:
30
+ """Get a list of all users"""
31
+ return list(self.users.values())
32
+
33
+ def delete_user(self, id: str) -> bool:
34
+ """Delete a user by ID"""
35
+ if id in self.users:
36
+ del self.users[id]
37
+ return True
38
+ return False
39
+
40
+
41
+ class ItemService:
42
+ """Service for item-related operations"""
43
+
44
+ def __init__(self, item_db: dict[str, Item] | None = None):
45
+ self.items = item_db or {}
46
+
47
+ def create_item(self, id: str, name: str, price: float, category: str) -> Item:
48
+ """Create a new item and store it"""
49
+ if id in self.items:
50
+ raise ValueError(f"Item with ID {id} already exists")
51
+
52
+ item = Item(id=id, name=name, price=price, category=category)
53
+ self.items[id] = item
54
+ return item
55
+
56
+ def get_item(self, id: str) -> Item | None:
57
+ """Get an item by ID"""
58
+ return self.items.get(id)
59
+
60
+ def list_items(self, category: str | None = None) -> list[Item]:
61
+ """List all items, optionally filtered by category"""
62
+ if category:
63
+ return [item for item in self.items.values() if item.category == category]
64
+ return list(self.items.values())
65
+
66
+
67
+ # Factory function for services
68
+ def create_service_container() -> dict[str, Any]:
69
+ """Create a container with all services"""
70
+ container = {"user_service": UserService(), "item_service": ItemService()}
71
+ return container
72
+
73
+
74
+ user_var_str = "user_var"
75
+
76
+
77
+ user_service = UserService()
78
+ user_service.create_user("1", "Alice", "alice@example.com")
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/utils.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions and classes demonstrating various Python features.
3
+ """
4
+
5
+ import logging
6
+ from collections.abc import Callable
7
+ from typing import Any, TypeVar
8
+
9
+ # Type variables for generic functions
10
+ T = TypeVar("T")
11
+ U = TypeVar("U")
12
+
13
+
14
+ def setup_logging(level: str = "INFO") -> logging.Logger:
15
+ """Set up and return a configured logger"""
16
+ levels = {
17
+ "DEBUG": logging.DEBUG,
18
+ "INFO": logging.INFO,
19
+ "WARNING": logging.WARNING,
20
+ "ERROR": logging.ERROR,
21
+ "CRITICAL": logging.CRITICAL,
22
+ }
23
+
24
+ logger = logging.getLogger("test_repo")
25
+ logger.setLevel(levels.get(level.upper(), logging.INFO))
26
+
27
+ handler = logging.StreamHandler()
28
+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
29
+ handler.setFormatter(formatter)
30
+ logger.addHandler(handler)
31
+
32
+ return logger
33
+
34
+
35
+ # Decorator example
36
+ def log_execution(func: Callable) -> Callable:
37
+ """Decorator to log function execution"""
38
+
39
+ def wrapper(*args, **kwargs):
40
+ logger = logging.getLogger("test_repo")
41
+ logger.info(f"Executing function: {func.__name__}")
42
+ result = func(*args, **kwargs)
43
+ logger.info(f"Completed function: {func.__name__}")
44
+ return result
45
+
46
+ return wrapper
47
+
48
+
49
+ # Higher-order function
50
+ def map_list(items: list[T], mapper: Callable[[T], U]) -> list[U]:
51
+ """Map a function over a list of items"""
52
+ return [mapper(item) for item in items]
53
+
54
+
55
+ # Class with various Python features
56
+ class ConfigManager:
57
+ """Manages configuration with various access patterns"""
58
+
59
+ _instance = None
60
+
61
+ # Singleton pattern
62
+ def __new__(cls, *args, **kwargs):
63
+ if not cls._instance:
64
+ cls._instance = super().__new__(cls)
65
+ return cls._instance
66
+
67
+ def __init__(self, initial_config: dict[str, Any] | None = None):
68
+ if not hasattr(self, "initialized"):
69
+ self.config = initial_config or {}
70
+ self.initialized = True
71
+
72
+ def __getitem__(self, key: str) -> Any:
73
+ """Allow dictionary-like access"""
74
+ return self.config.get(key)
75
+
76
+ def __setitem__(self, key: str, value: Any) -> None:
77
+ """Allow dictionary-like setting"""
78
+ self.config[key] = value
79
+
80
+ @property
81
+ def debug_mode(self) -> bool:
82
+ """Property example"""
83
+ return self.config.get("debug", False)
84
+
85
+ @debug_mode.setter
86
+ def debug_mode(self, value: bool) -> None:
87
+ self.config["debug"] = value
88
+
89
+
90
+ # Context manager example
91
+ class Timer:
92
+ """Context manager for timing code execution"""
93
+
94
+ def __init__(self, name: str = "Timer"):
95
+ self.name = name
96
+ self.start_time = None
97
+ self.end_time = None
98
+
99
+ def __enter__(self):
100
+ import time
101
+
102
+ self.start_time = time.time()
103
+ return self
104
+
105
+ def __exit__(self, exc_type, exc_val, exc_tb):
106
+ import time
107
+
108
+ self.end_time = time.time()
109
+ print(f"{self.name} took {self.end_time - self.start_time:.6f} seconds")
110
+
111
+
112
+ # Functions with default arguments
113
+ def retry(func: Callable, max_attempts: int = 3, delay: float = 1.0) -> Any:
114
+ """Retry a function with backoff"""
115
+ import time
116
+
117
+ for attempt in range(max_attempts):
118
+ try:
119
+ return func()
120
+ except Exception as e:
121
+ if attempt == max_attempts - 1:
122
+ raise e
123
+ time.sleep(delay * (2**attempt))
projects/ui/serena-new/test/resources/repos/python/test_repo/test_repo/variables.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test module for variable declarations and usage.
3
+
4
+ This module tests various types of variable declarations and usages including:
5
+ - Module-level variables
6
+ - Class-level variables
7
+ - Instance variables
8
+ - Variable reassignments
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+
13
+ # Module-level variables
14
+ module_var = "Initial module value"
15
+
16
+ reassignable_module_var = 10
17
+ reassignable_module_var = 20 # Reassigned
18
+
19
+ # Module-level variable with type annotation
20
+ typed_module_var: int = 42
21
+
22
+
23
+ # Regular class with class and instance variables
24
+ class VariableContainer:
25
+ """Class that contains various variables."""
26
+
27
+ # Class-level variables
28
+ class_var = "Initial class value"
29
+
30
+ reassignable_class_var = True
31
+ reassignable_class_var = False # Reassigned #noqa: PIE794
32
+
33
+ # Class-level variable with type annotation
34
+ typed_class_var: str = "typed value"
35
+
36
+ def __init__(self):
37
+ # Instance variables
38
+ self.instance_var = "Initial instance value"
39
+ self.reassignable_instance_var = 100
40
+
41
+ # Instance variable with type annotation
42
+ self.typed_instance_var: list[str] = ["item1", "item2"]
43
+
44
+ def modify_instance_var(self):
45
+ # Reassign instance variable
46
+ self.instance_var = "Modified instance value"
47
+ self.reassignable_instance_var = 200 # Reassigned
48
+
49
+ def use_module_var(self):
50
+ # Use module-level variables
51
+ result = module_var + " used in method"
52
+ other_result = reassignable_module_var + 5
53
+ return result, other_result
54
+
55
+ def use_class_var(self):
56
+ # Use class-level variables
57
+ result = VariableContainer.class_var + " used in method"
58
+ other_result = VariableContainer.reassignable_class_var
59
+ return result, other_result
60
+
61
+
62
+ # Dataclass with variables
63
+ @dataclass
64
+ class VariableDataclass:
65
+ """Dataclass that contains various fields."""
66
+
67
+ # Field variables with type annotations
68
+ id: int
69
+ name: str
70
+ items: list[str] = field(default_factory=list)
71
+ metadata: dict[str, str] = field(default_factory=dict)
72
+ optional_value: float | None = None
73
+
74
+ # This will be reassigned in various places
75
+ status: str = "pending"
76
+
77
+
78
+ # Function that uses the module variables
79
+ def use_module_variables():
80
+ """Function that uses module-level variables."""
81
+ result = module_var + " used in function"
82
+ other_result = reassignable_module_var * 2
83
+ return result, other_result
84
+
85
+
86
+ # Create instances and use variables
87
+ dataclass_instance = VariableDataclass(id=1, name="Test")
88
+ dataclass_instance.status = "active" # Reassign dataclass field
89
+
90
+ # Use variables at module level
91
+ module_result = module_var + " used at module level"
92
+ other_module_result = reassignable_module_var + 30
93
+
94
+ # Create a second dataclass instance with different status
95
+ second_dataclass = VariableDataclass(id=2, name="Another Test")
96
+ second_dataclass.status = "completed" # Another reassignment of status
projects/ui/serena-new/test/resources/repos/r/test_repo/.Rbuildignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ^.*\.Rproj$
2
+ ^\.Rproj\.user$
3
+ ^\.serena$