diff --git "a/data/editbench/test.jsonl" "b/data/editbench/test.jsonl" --- "a/data/editbench/test.jsonl" +++ "b/data/editbench/test.jsonl" @@ -102,12 +102,12 @@ {"problem_id": 102, "programming_language": "python", "original_code": "import pandas as pd\nimport os\nimport random\nimport torch\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics import precision_score, recall_score\nfrom torch.nn import functional as F\nfrom PIL import Image, ImageDraw, ImageFont\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom colpali_engine.interpretability import (\n get_similarity_maps_from_embeddings,\n plot_all_similarity_maps,\n)\n\n\n# Path to extracted Flickr8k dataset\nFLICKR8K_IMAGES_PATH = \"flickr8k/Images\"\nFLICKR8K_CAPTIONS_PATH = \"flickr8k/captions.txt\"\n\n# Function to load image-text pairs from Flickr8k\n\n\ndef load_flickr8k_data(images_path, captions_path, fraction=0.1):\n # Read captions file\n with open(captions_path, \"r\") as f:\n captions_data = f.readlines()[1:] # Skip header\n\n # Parse captions\n image_text_pairs = {}\n for line in captions_data:\n image_name, caption = line.strip().split(\",\", 1)\n if image_name not in image_text_pairs:\n image_text_pairs[image_name] = []\n image_text_pairs[image_name].append(caption)\n\n # Load only a fraction of the dataset\n selected_images = random.sample(\n list(image_text_pairs.keys()), int(len(image_text_pairs) * fraction)\n )\n image_text_pairs = {k: image_text_pairs[k] for k in selected_images}\n\n # Create pairs of images and captions\n pairs = []\n for image_name, captions in image_text_pairs.items():\n image_path = os.path.join(images_path, image_name)\n if os.path.exists(image_path):\n pairs.append((Image.open(image_path), random.choice(captions)))\n return pairs\n\n\n# Function to create unrelated pairs\n\n\ndef create_unrelated_pairs(image_text_pairs):\n \"\"\"\n Creates unrelated pairs of images and texts by randomly shuffling the texts.\n\n Args:\n image_text_pairs (list): A list of tuples containing images and their corresponding texts.\n\n Returns:\n list: A list of tuples containing images and unrelated texts.\n \"\"\"\n images, texts = zip(*image_text_pairs)\n unrelated_texts = random.sample(texts, len(texts))\n return list(zip(images, unrelated_texts))\n\n\ndef create_visual_pairs(image_text_pairs):\n \"\"\"\n Creates pairs of original and augmented images from image-text pairs.\n\n This function takes a list of image-text pairs and creates new pairs consisting\n of the original images and their augmented versions. The augmentation used\n in this implementation is a horizontal flip.\n\n Args:\n image_text_pairs (list): A list of tuples containing (image, text) pairs,\n where images are PIL Image objects and texts are strings.\n\n Returns:\n list: A list of tuples containing (original_image, augmented_image) pairs,\n where both elements are PIL Image objects.\n \"\"\"\n from torchvision.transforms import ToTensor\n\n images, _ = zip(*image_text_pairs)\n # Example augmentation: horizontal flip\n augmented_images = [ToTensor()(image).flip(-1) for image in images]\n return list(zip(images, augmented_images))\n\n\ndef get_embeddings(images, texts, model_id=\"google/siglip-base-patch16-224\"):\n \"\"\"\n Given lists of images and texts, returns normalized embeddings for both.\n \"\"\"\n # Ensure texts is a list of strings\n if not all(isinstance(t, str) for t in texts):\n raise ValueError(\"All text inputs must be strings.\")\n\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n model = AutoModel.from_pretrained(\n model_id, ignore_mismatched_sizes=True).to(device)\n processor = AutoProcessor.from_pretrained(model_id)\n\n # Preprocess images and texts\n image_inputs = processor(images=images, return_tensors=\"pt\").to(device)\n text_inputs = processor(text=texts, return_tensors=\"pt\", padding=\"max_length\").to(\n device\n )\n\n with torch.no_grad():\n image_embeds = model.get_image_features(**image_inputs)\n text_embeds = model.get_text_features(**text_inputs)\n\n # Normalize embeddings\n image_embeds = image_embeds / image_embeds.norm(dim=-1, keepdim=True)\n text_embeds = text_embeds / text_embeds.norm(dim=-1, keepdim=True)\n\n return image_embeds, text_embeds\n\n\ndef cosine_similarity_analysis(embeddings1, embeddings2, title):\n \"\"\"\n Computes cosine similarity for matching and unrelated pairs and compares distributions.\n \"\"\"\n similarities = cosine_similarity(\n embeddings1.cpu().numpy(), embeddings2.cpu().numpy()\n )\n\n # Matching pairs: Diagonal of the similarity matrix\n matching_similarities = np.diag(similarities)\n\n # Unrelated pairs: Off-diagonal similarities\n unrelated_similarities = similarities[~np.eye(\n similarities.shape[0], dtype=bool)]\n\n print(f\"### {title} ###\")\n print(f\"Mean Matching Similarity: {np.mean(matching_similarities):.4f}\")\n print(f\"Mean Unrelated Similarity: {np.mean(unrelated_similarities):.4f}\")\n print()\n\n # Plot distributions\n plt.figure(figsize=(10, 6))\n sns.histplot(\n matching_similarities, kde=True, label=\"Matching Pairs\", color=\"blue\", bins=30\n )\n sns.histplot(\n unrelated_similarities, kde=True, label=\"Unrelated Pairs\", color=\"red\", bins=30\n )\n plt.title(f\"{title}: Cosine Similarity Distributions\")\n plt.xlabel(\"Cosine Similarity\")\n plt.ylabel(\"Frequency\")\n plt.legend()\n plt.show()\n\n\n# b. Nearest-Neighbor Retrieval\n\n\ndef retrieval_metrics(query_embeds, target_embeds, ground_truth_indices, k=5):\n \"\"\"\n Computes Precision@k and Recall@k for nearest-neighbor retrieval.\n\n This function evaluates the effectiveness of retrieval by calculating Precision@k and Recall@k.\n Precision@k measures the accuracy of the top-k retrieved items, while Recall@k measures the ability\n to find the relevant item within the top-k retrieved items. It assumes there's only one true\n match per query.\n\n Args:\n query_embeds (torch.Tensor): Embeddings of the query data.\n target_embeds (torch.Tensor): Embeddings of the target data (database).\n ground_truth_indices (list): List of indices in the target data representing the true matches for each query.\n k (int): The number of top results to consider.\n\n Returns:\n tuple: A tuple containing mean Precision@k and mean Recall@k.\n \"\"\"\n similarities = cosine_similarity(\n query_embeds.cpu().numpy(), target_embeds.cpu().numpy()\n )\n sorted_indices = np.argsort(-similarities, axis=1)[:, :k] # Top-k indices\n\n # Compute metrics\n precisions = []\n recalls = []\n for i, true_idx in enumerate(ground_truth_indices):\n retrieved_indices = sorted_indices[i]\n true_positives = int(true_idx in retrieved_indices)\n precisions.append(true_positives / k)\n recalls.append(true_positives / 1) # Only one true match per query\n\n mean_precision = np.mean(precisions)\n mean_recall = np.mean(recalls)\n\n return mean_precision, mean_recall\n\n\ndef plot_query_token_importance(\n pil_image, similarity_maps, query_tokens, alpha: float = 0.5\n) -> None:\n \"\"\"\n Plot a separate heatmap for each query token in the similarity_maps.\n\n Args:\n pil_image (PIL.Image.Image): The original image (e.g., loaded via Image.open(...)).\n similarity_maps (torch.Tensor):\n Shape = (num_query_tokens, n_patches_x, n_patches_y).\n query_tokens (List[str]): A list of strings for each token in the query.\n alpha (float): Transparency for the heatmap overlays (0=transparent, 1=opaque).\n \"\"\"\n # Convert PIL to numpy\n image_np = np.array(pil_image)\n H, W = image_np.shape[:2]\n\n num_tokens = similarity_maps.size(0)\n assert num_tokens == len(query_tokens), (\n f\"The number of query tokens in similarity_maps ({num_tokens}) \"\n f\"doesn't match the length of query_tokens list ({len(query_tokens)}).\"\n )\n\n fig, axs = plt.subplots(1, num_tokens, figsize=(5 * num_tokens, 5))\n if num_tokens == 1:\n # If there's only one token, axs won't be an iterable\n axs = [axs]\n\n for idx in range(num_tokens):\n # Each similarity_map for a single query token: shape = (n_patches_x, n_patches_y)\n single_map = similarity_maps[idx] # (n_patches_x, n_patches_y)\n\n # Upsample to full image size\n single_map_4d = single_map.unsqueeze(0).unsqueeze(\n 0\n ) # (1,1,n_patches_x, n_patches_y)\n upsampled = F.interpolate(\n single_map_4d, size=(H, W), mode=\"bilinear\", align_corners=False\n )\n\n # .to(torch.float32) fix if your map is bfloat16\n heatmap = upsampled.squeeze().to(torch.float32).cpu().numpy() # (H, W)\n\n # Optionally normalize heatmap (uncomment if desired)\n # heatmap = (heatmap - heatmap.min()) / (heatmap.max() - heatmap.min() + 1e-8)\n\n # Plot\n axs[idx].imshow(image_np, cmap=None if image_np.ndim == 3 else \"gray\")\n axs[idx].imshow(heatmap, cmap=\"jet\", alpha=alpha)\n axs[idx].set_title(f\"Query: {query_tokens[idx]}\")\n axs[idx].axis(\"off\")\n\n plt.tight_layout()\n plt.show()\n\n\ndef get_maps_and_embeds(\n batch_images, batch_queries, model, processor, image, use_qwen=False\n):\n \"\"\"\n Computes similarity maps and embeddings from a batch of images and queries using the specified model and processor.\n\n Args:\n batch_images (dict): A dictionary of batched image inputs processed by the processor.\n batch_queries (dict): A dictionary of batched query inputs processed by the processor.\n model (nn.Module): The model used for computing embeddings.\n processor (Processor): The processor responsible for image and text preprocessing.\n\n Returns:\n tuple: A tuple containing:\n - original_maps (torch.Tensor): Similarity maps between images and queries\n with shape (num_queries, n_patches_x, n_patches_y).\n - original_image_embeddings (torch.Tensor): Embeddings of the input images.\n - original_query_embeddings (torch.Tensor): Embeddings of the input queries.\n \"\"\"\n with torch.no_grad():\n original_image_embeddings = model.forward(**batch_images)\n original_query_embeddings = model.forward(**batch_queries)\n if use_qwen:\n n_patches = processor.get_n_patches(\n image_size=image.size,\n patch_size=model.patch_size,\n spatial_merge_size=model.spatial_merge_size,\n )\n else:\n n_patches = processor.get_n_patches(\n image_size=image.size, patch_size=model.patch_size\n )\n image_mask = processor.get_image_mask(batch_images)\n\n # Compute original similarity maps\n original_batched_maps = get_similarity_maps_from_embeddings(\n image_embeddings=original_image_embeddings,\n query_embeddings=original_query_embeddings,\n n_patches=n_patches,\n image_mask=image_mask,\n )\n # (query_length, n_patches_x, n_patches_y)\n original_maps = original_batched_maps[0].permute(0, 2, 1).contiguous()\n return original_maps, original_image_embeddings, original_query_embeddings\n\n\ndef visualize_token_map(\n image,\n original_maps,\n token_list,\n token_index=2,\n cmap=\"Greens\",\n figsize=(15, 2),\n show_text=True,\n):\n \"\"\"\n Visualize a token's attention map in three ways: the original image, the raw attention map with numerical values,\n and an overlay of the attention map on the original image.\n Args:\n image (PIL.Image): The input image to visualize.\n original_maps (torch.Tensor or np.ndarray): Attention maps with shape (num_tokens, height, width).\n token_list (list[str]): List of token strings corresponding to each attention map.\n token_index (int, optional): Index of the token/map to visualize. Defaults to 2.\n cmap (str, optional): Matplotlib colormap name for visualizing the attention maps. Defaults to \"Greens\".\n\n The function creates a figure with three subplots:\n 1. The original input image\n 2. The raw attention map with numerical values annotated\n 3. The attention map overlaid on the original image with a colorbar\n\n Returns:\n None. Displays the visualization using matplotlib.\n \"\"\"\n # Convert the image to a NumPy array\n image_np = np.array(image)\n\n # Select the map corresponding to the token\n visual_map = original_maps[token_index]\n\n # Convert visual_map to NumPy array if it's a tensor\n if isinstance(visual_map, torch.Tensor):\n visual_map = visual_map.cpu().to(dtype=torch.float32).numpy()\n elif not isinstance(visual_map, np.ndarray):\n visual_map = np.array(visual_map)\n\n # Convert map to a PIL image\n visual_map_pil = Image.fromarray(visual_map)\n\n # Resize using NEAREST to keep \"big pixels\"\n visual_map_pil = visual_map_pil.resize(\n (image_np.shape[1], image_np.shape[0]), # (width, height)\n resample=Image.NEAREST,\n )\n\n # Convert back to NumPy\n resized_map = np.array(visual_map_pil)\n\n # Create a figure with subplots\n fig, axes = plt.subplots(1, 3, figsize=(15, 2))\n\n # Display the raw image\n axes[0].imshow(image_np)\n axes[0].set_title(\"Raw Image\")\n axes[0].axis(\"off\")\n # Display the raw map with annotations\n im = axes[1].imshow(visual_map, cmap=cmap)\n axes[1].set_title(\"Raw Map\")\n axes[1].axis(\"off\")\n\n if show_text:\n # Annotate the heatmap\n for i in range(visual_map.shape[0]):\n for j in range(visual_map.shape[1]):\n text = axes[1].text(\n j,\n i,\n f\"{visual_map[i, j]:.2f}\",\n ha=\"center\",\n va=\"center\",\n color=\"w\" if visual_map[i, j] > visual_map.max(\n ) / 2 else \"black\",\n )\n\n # Display the overlay plot\n axes[2].imshow(image_np, alpha=1)\n axes[2].imshow(resized_map, cmap=cmap, alpha=0.6)\n axes[2].set_title(\"Overlay: Image + Map\")\n axes[2].axis(\"off\")\n # Add a colorbar for the overlay with matching values to the raw map\n cbar = fig.colorbar(\n plt.cm.ScalarMappable(\n cmap=cmap, norm=plt.Normalize(\n vmin=visual_map.min(), vmax=visual_map.max())\n ),\n ax=axes[2],\n shrink=0.8,\n orientation=\"vertical\",\n )\n cbar.set_label(\"Map Intensity\")\n # Add a title with the token name\n plt.suptitle(f\"Token: {token_list[token_index]}\")\n\n # Adjust layout and show\n plt.tight_layout()\n plt.show()\n\n\ndef create_single_patch_image(\n n_patches_x,\n n_patches_y,\n patch_size,\n main_color,\n special_color,\n special_patch,\n special_patch_width=2,\n):\n \"\"\"\n Creates an image composed of colored patches, with one special patch highlighted.\n\n The image is divided into a grid of n_patches_x by n_patches_y patches, each of size\n patch_size x patch_size pixels. All patches are filled with the main_color, except\n for the special_patch, which is filled with special_color. The special patch can\n also have a width of more than one patch.\n Args:\n n_patches_x (int): Number of patches horizontally.\n n_patches_y (int): Number of patches vertically.\n patch_size (int): The size (in pixels) of each square patch.\n main_color (list): The [R, G, B] color for most patches.\n special_color (list): The [R, G, B] color for the special patch.\n special_patch (tuple): The (row, col) position of the top-left corner of the special patch (0-indexed).\n special_patch_width (int, optional): The width of the special patch in number of patches. Defaults to 2.\n\n Returns:\n PIL Image: The generated image.\n \"\"\"\n\n # Create a 3D NumPy array for the image\n img_height = n_patches_y * patch_size\n img_width = n_patches_x * patch_size\n image_data = np.zeros((img_height, img_width, 3), dtype=np.uint8)\n\n # Fill the entire image with the main color\n image_data[:, :] = main_color\n\n # Assign the special color to the special patch\n special_row, special_col = special_patch\n image_data[\n special_row * patch_size: (special_row + special_patch_width) * patch_size,\n special_col * patch_size: (special_col + special_patch_width) * patch_size,\n ] = special_color\n\n return Image.fromarray(image_data)\n\n\ndef extract_patch_mask(image, patch_size, special_color=[0, 0, 0]):\n \"\"\"\n Extract a binary mask indicating the location of the special patch.\n\n Args:\n image (PIL.Image.Image): The input image.\n patch_size (int): The size of each square patch in pixels.\n special_color (list[int]): The RGB color of the special patch.\n\n Returns:\n np.ndarray: A binary mask of shape (n_patches_y, n_patches_x) indicating\n the special patch location (1 for special patch, 0 otherwise).\n \"\"\"\n # Convert the image to a NumPy array\n image_np = np.array(image)\n\n # Get image dimensions\n img_height, img_width, _ = image_np.shape\n\n # Compute the number of patches\n n_patches_y = img_height // patch_size\n n_patches_x = img_width // patch_size\n\n # Initialize the patch mask\n patch_mask = np.zeros((n_patches_y, n_patches_x), dtype=np.int32)\n\n # Iterate over all patches to locate the special patch\n for row in range(n_patches_y):\n for col in range(n_patches_x):\n # Extract the patch\n patch = image_np[\n row * patch_size: (row + 1) * patch_size,\n col * patch_size: (col + 1) * patch_size,\n ]\n\n # Check if the patch matches the special color\n if np.allclose(patch.mean(axis=(0, 1)), special_color, atol=1e-6):\n patch_mask[row, col] = 1 # Mark this patch as special\n\n return patch_mask\n\n\ndef evaluate_map_quality(similarity_map, patch_mask):\n \"\"\"\n Evaluate the quality of a similarity map with respect to a binary patch mask.\n\n Args:\n similarity_map (torch.Tensor): The similarity map (height, width).\n patch_mask (np.ndarray): The binary mask for the patch (1 for black patch, 0 elsewhere).\n\n Returns:\n dict: Metrics including correlation, peak accuracy, and overlap score.\n \"\"\"\n # Ensure similarity_map is in float32 and on the CPU\n similarity_map = similarity_map.to(dtype=torch.float32).cpu().numpy()\n\n # Flatten the map and mask for easier computation\n sim_map_flat = similarity_map.flatten()\n patch_mask_flat = patch_mask.flatten()\n\n # Ensure the shapes are compatible\n if sim_map_flat.shape != patch_mask_flat.shape:\n raise ValueError(\n f\"Shape mismatch: similarity_map has {sim_map_flat.shape} elements, \"\n f\"but patch_mask has {patch_mask_flat.shape} elements.\"\n )\n\n # (A) Correlation\n correlation = np.corrcoef(\n sim_map_flat, patch_mask_flat.astype(np.float32))[0, 1]\n\n # (B) Peak Signal Location\n max_location = np.unravel_index(\n np.argmax(similarity_map), similarity_map.shape)\n expected_location = np.unravel_index(\n np.argmax(patch_mask), patch_mask.shape)\n peak_accuracy = 1 if max_location == expected_location else 0\n\n # (C) Normalized Map Overlap\n black_patch_score = similarity_map[patch_mask == 1].mean()\n background_score = similarity_map[patch_mask == 0].mean()\n overlap_score = black_patch_score / (\n background_score + 1e-8\n ) # Avoid division by zero\n\n # Return all metrics\n return {\n \"correlation\": correlation,\n \"peak_accuracy\": peak_accuracy,\n \"overlap_score\": overlap_score,\n }\n\n\ndef evaluate_image_maps(similarity_map, real_image):\n \"\"\"\n Evaluates the quality of similarity maps by comparing them to a real image.\n\n Args:\n similarity_map (torch.Tensor): The similarity map to evaluate.\n real_image (PIL.Image.Image): The corresponding real image.\n\n Returns:\n dict: A dictionary containing the calculated metrics: accuracy, score, and rank.\n \"\"\"\n # Convert the real image to a binary array (1 - normalized grayscale)\n image_array = 1 - np.array(real_image.convert(\"L\"),\n dtype=np.float32) / 255.0\n\n # Ensure similarity_map is float32 and on the CPU before using numpy operations\n similarity_map_cpu = similarity_map.to(dtype=torch.float32).cpu().numpy()\n\n # Create a mask for the maximum values in the similarity map\n acc_visual_map = np.where(\n similarity_map_cpu == similarity_map_cpu.max(), similarity_map_cpu, 0\n )\n\n # Check if scaling is necessary\n if image_array.shape != similarity_map_cpu.shape:\n scale_factor = image_array.shape[0] // similarity_map_cpu.shape[0]\n scaled_visual_map = np.kron(\n np.abs(similarity_map_cpu), np.ones((scale_factor, scale_factor))\n )\n rank_map = np.kron(\n np.abs(similarity_map_cpu), np.ones((scale_factor, scale_factor))\n )\n acc_visual_map = np.kron(\n np.abs(acc_visual_map), np.ones((scale_factor, scale_factor))\n )\n else:\n scaled_visual_map = similarity_map_cpu\n rank_map = similarity_map_cpu # Add this to avoid missing variable\n\n # Calculate accuracy and score\n accuracy = np.any(image_array * acc_visual_map)\n score = np.sum(image_array * scaled_visual_map) / (\n np.sum(image_array) + 1e-8\n ) # Avoid division by zero\n\n # Calculate rank\n bin_image = (image_array != 0).astype(int)\n rank_value = np.sum(bin_image * rank_map) / np.sum(\n bin_image\n ) # Avoid division by zero\n sorted_values = sorted(np.abs(similarity_map_cpu.ravel()))[::-1]\n rank = np.where(np.isclose(sorted_values, rank_value))[0][0]\n\n return {\n \"accuracy\": accuracy,\n \"score\": score,\n \"rank\": rank,\n }\n\n\ndef create_single_patch_image_with_text(\n n_patches_x,\n n_patches_y,\n patch_size,\n main_color,\n special_color,\n special_patch,\n text=\"Hello\",\n text_color=(255, 255, 255),\n special_patch_width=2,\n font_size=16,\n # Added font_path parameter with default value\n font_path=\"./fonts/Roboto-Regular.ttf\",\n):\n \"\"\"\n Creates an image composed of colored patches, but places a single word (or text)\n inside the \"special\" patch area.\n \"\"\"\n # Create a 3D NumPy array for the image\n img_height = n_patches_y * patch_size\n img_width = n_patches_x * patch_size\n image_data = np.zeros((img_height, img_width, 3), dtype=np.uint8)\n\n # Fill the entire image with the main color\n image_data[:, :] = main_color\n\n # Assign the special color to the special patch area\n special_row, special_col = special_patch\n image_data[\n special_row * patch_size: (special_row + special_patch_width) * patch_size,\n special_col * patch_size: (special_col + special_patch_width) * patch_size,\n ] = special_color\n\n # Convert to a Pillow Image so we can draw on it\n img = Image.fromarray(image_data)\n draw = ImageDraw.Draw(img)\n\n # Load font with specified size\n try:\n font = ImageFont.truetype(font_path, font_size)\n except IOError:\n print(f\"Error loading font from {font_path}. Using default font.\")\n font = ImageFont.load_default()\n\n # Calculate the center of the special patch in pixel coordinates\n patch_center_x = special_col * patch_size + \\\n (special_patch_width * patch_size) // 2\n patch_center_y = special_row * patch_size + \\\n (special_patch_width * patch_size) // 2\n\n # Calculate text bounding box to center the text\n text_bbox = draw.textbbox((0, 0), text, font=font)\n text_width = text_bbox[2] - text_bbox[0]\n text_height = text_bbox[3] - text_bbox[1]\n\n text_x = patch_center_x - text_width // 2\n text_y = patch_center_y - text_height // 2\n\n # Place text in the center of the special patch\n draw.text((text_x, text_y), text, fill=text_color, font=font)\n\n return img\n\n\ndef visualize_results_grid(results_df):\n columns = [results_df.iloc[:, i] for i in range(len(results_df.columns))]\n columns = [\n (\n pd.to_numeric(col, errors=\"coerce\")\n if not pd.api.types.is_numeric_dtype(col)\n else col\n )\n for col in columns\n ]\n\n # Deduce the grid shape from the number of results rows\n grid_size = int(np.sqrt(len(results_df)))\n # Reshape columns into matrices\n matrices = [col.to_numpy().reshape(grid_size, grid_size)\n for col in columns]\n\n # Visualization setup\n fig, axes = plt.subplots(1, len(results_df.columns), figsize=(12, 2))\n titles = [\n (\n f\"{results_df.columns[i]} (Categorical/Binary)\"\n if i == 0\n else f\"{results_df.columns[i]} (Continuous)\"\n )\n for i in range(len(results_df.columns))\n ]\n # Added colormap for the fourth plot\n cmaps = [\"coolwarm\"] * len(results_df.columns)\n # Plot each matrix\n for i, (matrix, ax, title, cmap) in enumerate(zip(matrices, axes, titles, cmaps)):\n im = ax.imshow(matrix, cmap=cmap, interpolation=\"none\")\n ax.set_title(title)\n ax.set_xticks(range(grid_size))\n ax.set_yticks(range(grid_size))\n fig.colorbar(im, ax=ax)\n\n # Display the plot\n plt.tight_layout()\n plt.show()\n\n\ndef run_expe_word_square(\n word_to_write,\n token,\n n_patches_x,\n n_patches_y,\n patch_size,\n model,\n processor,\n device,\n use_qwen,\n main_color=[255, 255, 255],\n special_color=(0, 0, 0),\n):\n\n all_images_text = [\n create_single_patch_image_with_text(\n n_patches_x=n_patches_x,\n n_patches_y=n_patches_y,\n patch_size=patch_size,\n main_color=main_color,\n special_color=main_color,\n special_patch=(row, col),\n text=word_to_write,\n text_color=(0, 0, 0), # text_color,\n font_size=9,\n )\n for row in range(0, n_patches_y, 2)\n for col in range(0, n_patches_x, 2)\n ]\n\n all_maps = []\n for image in all_images_text:\n batch_images = processor.process_images([image]).to(device)\n batch_queries = processor.process_queries([token]).to(device)\n original_maps, original_image_embeddings, original_query_embeddings = (\n get_maps_and_embeds(\n batch_images, batch_queries, model, processor, image, use_qwen=use_qwen\n )\n )\n original_maps = original_maps.to(dtype=torch.float32).cpu().numpy()\n all_maps.append(original_maps)\n\n input_ids = batch_queries[\"input_ids\"][0] # shape: (num_subtokens,)\n token_list = [processor.tokenizer.decode(\n [token_id]) for token_id in input_ids]\n # print(token_list)\n indexes = [i for i, x in enumerate(\n token_list) if \"<\" not in x and \">\" not in x][2:]\n # print(indexes)\n # print(np.array(token_list)[[indexes]])\n\n results_df = pd.DataFrame(columns=[\"accuracy\", \"score\", \"rank\"])\n for i, (this_map, image) in enumerate(zip(all_maps, all_images_text)):\n visual_map = this_map[indexes[0]]\n metrics = evaluate_image_maps(visual_map, image)\n results_df.loc[i] = metrics.values()\n return results_df\n", "highlighted_code": "\n # Ensure similarity_map is float32 and on the CPU before using numpy operations\n similarity_map_cpu = similarity_map.to(dtype=torch.float32).cpu().numpy()\n", "instruction": "add a check to avoid this operation if it is already a numpy format", "test_code": "import ast\nimport inspect\nimport pytest\n\ndef test_similarity_map_cpu_guarded(implementation):\n \"\"\"\n Ensure that within `evaluate_image_maps`, the line with\n `similarity_map.to(dtype=torch.float32).cpu().numpy()` is preceded by\n an `if` statement that includes 'np' or 'numpy'.\n \"\"\"\n impl_name, module = implementation\n module_code = inspect.getsource(module)\n\n lines = module_code.split('\\n')\n\n # Strip comments and blank lines\n cleaned_lines = []\n for line in lines:\n stripped = line.strip()\n if not stripped or stripped.startswith('#'):\n continue\n # Remove inline comments\n line_no_comment = line.split('#')[0].strip()\n cleaned_lines.append(line_no_comment)\n\n # Flag to track whether we're inside the evaluate_image_maps function\n inside_target_function = False\n function_lines = []\n\n for line in cleaned_lines:\n if line.startswith(\"def evaluate_image_maps(\"):\n inside_target_function = True\n continue\n\n # Stop if we\u2019re out of the function by checking indentation\n if inside_target_function:\n # We know we're out of the target function because the original code is succeeded by a new method\n if line.startswith(\"def \") or line.startswith(\"class \"):\n inside_target_function = False\n break\n \n function_lines.append(line)\n\n if not function_lines:\n pytest.fail(\"Function evaluate_image_maps not found or is empty\")\n\n target_expr = \"similarity_map.to(dtype=torch.float32).cpu().numpy()\"\n\n for idx, line in enumerate(function_lines):\n if target_expr in line:\n if idx == 0:\n pytest.fail(\"Expected 'if' statement before similarity_map conversion, got empty line.\")\n prev_line = function_lines[idx - 1].strip()\n assert prev_line.startswith(\"if\"), \\\n f\"Expected 'if' statement before similarity_map conversion, got: {prev_line}\"\n assert \"np\" in prev_line or \"numpy\" in prev_line, \\\n f\"'if' statement before similarity_map conversion does not mention numpy: {prev_line}\"\n return\n\n pytest.fail(f\"Could not find line with: {target_expr}\")\n", "requirements": "numpy\ntorch\npytest\npytest-mock\npillow\nmatplotlib\nseaborn\npandas\nscikit-learn\ncolpali-engine", "conftest": "import pytest\nimport os\nimport sys\nimport json\nfrom typing import Dict, List, Optional, Any\n\n# Import from local test_utils.py in the same directory\nfrom test_utils import TestUtils, TestResultsManager\n\n# Load all implementations in the current sandbox\nimplementations = TestUtils.load_all_implementations()\ntest_results = TestResultsManager()\n\n@pytest.fixture(scope=\"session\")\ndef sandbox_dir():\n \"\"\"Fixture to provide the sandbox directory path.\"\"\"\n return os.path.dirname(os.path.abspath(__file__))\n\n@pytest.fixture(scope=\"session\")\ndef sandbox_name():\n \"\"\"Fixture to provide the sandbox name.\"\"\"\n return os.path.basename(os.path.dirname(os.path.abspath(__file__)))\n\n@pytest.fixture(scope=\"session\")\ndef all_implementations():\n \"\"\"Fixture to provide all implementations as a dictionary.\"\"\"\n return implementations\n\n@pytest.fixture(params=list(implementations.items()))\ndef implementation(request):\n \"\"\"Fixture to provide each implementation to tests one at a time.\"\"\"\n return request.param\n\n@pytest.fixture(scope=\"session\")\ndef results_manager():\n \"\"\"Fixture to provide access to the test results manager.\"\"\"\n return test_results\n\n# Hook for collecting test results\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n \"\"\"Pytest hook to collect test results.\"\"\"\n # Execute all other hooks to obtain the report object\n outcome = yield\n rep = outcome.get_result()\n \n # We're only interested in the call outcome\n if rep.when == \"call\":\n if hasattr(item, \"callspec\") and \"implementation\" in item.callspec.params:\n # Get implementation name and module\n impl_name, _ = item.callspec.params[\"implementation\"]\n \n # Get test name\n test_name = item.nodeid.split(\"::\")[-1]\n \n # Record result\n if rep.passed:\n test_results.record_result(impl_name, test_name, True)\n elif rep.failed:\n error_msg = str(rep.longrepr) if rep.longrepr else \"Test failed\"\n test_results.record_result(impl_name, test_name, False, error_msg)\n elif rep.skipped:\n skip_reason = rep.longrepr[2] if rep.longrepr else \"Test skipped\"\n test_results.record_skip(impl_name, test_name, skip_reason)\n\n# Hook to save results at the end of testing\n@pytest.hookimpl(trylast=True)\ndef pytest_sessionfinish(session, exitstatus):\n \"\"\"Save test results at the end of the test session.\"\"\"\n test_results.save_results()", "test_utils": "import os\nimport sys\nimport glob\nimport re\nimport importlib.util\nimport traceback\nimport types\nfrom typing import Dict, List, Optional, Any, Tuple\n\nclass TestUtils:\n @staticmethod\n def discover_implementation_files(directory: str = None) -> List[str]:\n \"\"\"Find all implementation files in the current sandbox directory.\"\"\"\n if directory is None:\n directory = os.path.dirname(os.path.abspath(__file__))\n \n patterns = [\n r'modified_code\\d+\\.py',\n r'new_code\\d+\\.py', \n # r'original_code\\.py',\n r'implementation\\d*\\.py'\n ]\n \n pattern = re.compile('|'.join(f'({p})' for p in patterns))\n implementations = []\n \n for file_path in glob.glob(os.path.join(directory, '*.py')):\n if pattern.search(os.path.basename(file_path)):\n implementations.append(file_path)\n \n # Sort files numerically\n def sort_key(path):\n filename = os.path.basename(path)\n match = re.search(r'(\\d+)', filename)\n return int(match.group(1)) if match else 0\n \n return sorted(implementations, key=sort_key)\n \n @staticmethod\n def create_mock_module(file_path: str, module_name: str, error_info: str) -> types.ModuleType:\n \"\"\"Create a mock module that contains error information but can still be tested.\"\"\"\n # Create a new module object\n mock_module = types.ModuleType(module_name)\n \n # Add basic attributes\n mock_module.__file__ = file_path\n mock_module.__name__ = module_name\n mock_module.__display_name__ = module_name\n mock_module.__error__ = error_info\n \n # Add a dummy function that can be detected by test functions\n def dummy_function(*args, **kwargs):\n return f\"Error in module: {error_info}\"\n \n setattr(mock_module, \"implementation_error\", dummy_function)\n \n return mock_module\n\n @staticmethod\n def load_module(file_path: str, module_name: Optional[str] = None) -> Any:\n \"\"\"\n Safely load a module from a file path with proper error handling.\n If the module has errors, return a mock module that can still be tested.\n \"\"\"\n if module_name is None:\n module_name = os.path.basename(file_path).replace('.py', '')\n \n # Create a unique module name to avoid conflicts\n sandbox_id = os.path.basename(os.path.dirname(file_path))\n unique_module_name = f\"{sandbox_id}_{module_name}\"\n \n try:\n # First, try to read the file to check for syntax errors\n with open(file_path, 'r') as f:\n source_code = f.read()\n \n # Check for syntax errors by compiling the code\n try:\n compiled = compile(source_code, file_path, 'exec')\n except SyntaxError as e:\n error_msg = f\"Syntax error: {str(e)}\"\n print(f\"Syntax error in {file_path}: {e}\")\n print(f\" Line {e.lineno}, column {e.offset}: {e.text}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n # Create the module spec\n spec = importlib.util.spec_from_file_location(unique_module_name, file_path)\n if spec is None or spec.loader is None:\n error_msg = f\"Could not create spec for {file_path}\"\n print(f\"Error: {error_msg}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n # Create the module object\n module = importlib.util.module_from_spec(spec)\n sys.modules[unique_module_name] = module\n \n # Special handling for execution errors\n try:\n # Execute the module code in a safe way\n spec.loader.exec_module(module)\n # Store the original name for reference\n module.__display_name__ = module_name\n return module\n except Exception as e:\n error_msg = f\"Runtime error: {str(e)}\"\n traceback_str = traceback.format_exc()\n print(f\"Error executing module {file_path}: {e}\")\n print(traceback_str)\n \n # Create a partial module that contains what we loaded before the error\n mock_module = TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n # Copy any attributes that might have been defined before the error\n for attr_name in dir(module):\n if not attr_name.startswith('__'):\n try:\n setattr(mock_module, attr_name, getattr(module, attr_name))\n except Exception:\n pass # Skip attributes that can't be copied\n \n return mock_module\n \n except FileNotFoundError as e:\n error_msg = f\"File not found: {str(e)}\"\n print(f\"Error: {error_msg}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n except Exception as e:\n error_msg = f\"Unexpected error: {str(e)}\"\n print(f\"Error loading module {file_path}: {e}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n @classmethod\n def load_all_implementations(cls, directory: str = None) -> Dict[str, Any]:\n \"\"\"Load all implementation files in the directory, including those with errors.\"\"\"\n if directory is None:\n directory = os.path.dirname(os.path.abspath(__file__))\n \n implementations = {}\n \n implementation_files = cls.discover_implementation_files(directory)\n if not implementation_files:\n print(\"WARNING: No implementation files found. Check your file naming patterns.\")\n \n for file_path in implementation_files:\n module_name = os.path.basename(file_path).replace('.py', '')\n module = cls.load_module(file_path, module_name)\n \n # Always add the module, even if it has errors\n implementations[module_name] = module\n \n if hasattr(module, '__error__'):\n print(f\"Loaded with errors: {module_name} - {module.__error__}\")\n else:\n print(f\"Successfully loaded: {module_name}\")\n \n return implementations\n\nclass TestResultsManager:\n def __init__(self):\n self.results = {}\n self.sandbox_name = os.path.basename(os.path.dirname(os.path.abspath(__file__)))\n \n def record_result(self, impl_name: str, test_name: str, passed: bool, \n error_msg: Optional[str] = None) -> None:\n \"\"\"Record a test result for an implementation.\"\"\"\n if impl_name not in self.results:\n self.results[impl_name] = {\"passed\": 0, \"failed\": 0, \"skipped\": 0, \"errors\": []}\n \n if passed:\n self.results[impl_name][\"passed\"] += 1\n else:\n self.results[impl_name][\"failed\"] += 1\n if error_msg:\n self.results[impl_name][\"errors\"].append({\n \"test\": test_name,\n \"error\": error_msg\n })\n \n def record_skip(self, impl_name: str, test_name: str, \n reason: Optional[str] = None) -> None:\n \"\"\"Record a skipped test for an implementation.\"\"\"\n if impl_name not in self.results:\n self.results[impl_name] = {\"passed\": 0, \"failed\": 0, \"skipped\": 0, \"errors\": []}\n \n self.results[impl_name][\"skipped\"] += 1\n if reason:\n self.results[impl_name][\"errors\"].append({\n \"test\": test_name,\n \"error\": f\"SKIPPED: {reason}\"\n })\n \n def get_winner(self) -> Tuple[Optional[int], Dict]:\n \"\"\"Determine the winner based on test results.\"\"\"\n winner = None\n max_passed = -1\n \n for impl_name, results in self.results.items():\n if impl_name == \"original_code\":\n continue # Skip original code when determining winner\n \n if results[\"passed\"] > max_passed:\n max_passed = results[\"passed\"]\n winner = impl_name\n # Break ties by looking at failure count\n elif results[\"passed\"] == max_passed and winner is not None:\n if results[\"failed\"] < self.results[winner][\"failed\"]:\n winner = impl_name\n \n # Convert winner to numeric index if possible\n winner_index = -1\n if winner and re.match(r'modified_code\\d+', winner):\n try:\n winner_index = int(re.search(r'(\\d+)', winner).group(1))\n except (AttributeError, ValueError):\n pass\n \n return winner_index, self.results\n \n def save_results(self, filename: str = \"test_results.json\") -> None:\n \"\"\"Save test results to a JSON file.\"\"\"\n import json\n \n winner_index, results = self.get_winner()\n \n # Check if all tests were skipped\n all_skipped = all(\n stats[\"skipped\"] == stats[\"passed\"] + stats[\"failed\"] + stats[\"skipped\"]\n for impl_name, stats in results.items()\n if impl_name != \"original_code\"\n )\n \n output = {\n \"winner\": winner_index,\n \"all_skipped\": all_skipped,\n \"results\": {\n name: {\n \"passed\": stats[\"passed\"],\n \"failed\": stats[\"failed\"],\n \"skipped\": stats[\"skipped\"],\n \"total\": stats[\"passed\"] + stats[\"failed\"] + stats[\"skipped\"]\n }\n for name, stats in results.items()\n if not name.startswith(\"_\") # Skip internal items\n }\n }\n \n with open(filename, \"w\") as f:\n json.dump(output, f, indent=2)\n \n print(f\"Test results saved to {filename}\")\n \n return output", "split": "test"} {"problem_id": 103, "programming_language": "python", "original_code": "from ast import Add\nfrom asyncio import wait\nfrom curses import COLOR_BLUE, COLOR_RED\nfrom re import A\nfrom shutil import move\nfrom glm import degrees\nfrom manim import *\nfrom numpy import size, square\n\nclass Project(Scene):\n def construct(self):\n text = Tex(\"Double Angle\")\n self.play( Write(text))\n\n\n self.wait(5)\n \n transform_text = Tex(\"What is Double Angle?\")\n transform_text.to_corner(UP)\n box = SurroundingRectangle(transform_text)\n box.set_color(WHITE)\n box.set_stroke(width=1.5)\n self.play(\n Transform(text, transform_text)\n )\n self.wait(0.5)\n self.play(Create(box))\n\n\n explanation = Paragraph(\"A double angle is an angle measurement\", \"that has been multiplied by 2 or added to itself.\", line_spacing=0.5, font_size=32)\n explanation.move_to(ORIGIN)\n\n\n self.play(\n Write(explanation)\n )\n\n\n self.wait(3)\n\n\n self.play(\n Transform(explanation, explanation.copy().shift(UP))\n )\n\n\n\n\n trig_cos2 = MathTex(\n r\"\\cos2x = \\cos^2x - \\sin^2x\",\n \n substrings_to_isolate=[\"cos2x\"]\n )\n trig_cos2.set_color_by_tex(\"cos2x\", BLUE)\n trig_cos2.move_to(DOWN)\n transform_formula = Tex(\"Double Angle Formula\")\n transform_formula.to_corner(UP)\n \n \n self.wait(1)\n\n\n self.play(\n Write(trig_cos2)\n )\n\n\n self.wait(2)\n\n self.play(\n FadeOut(trig_cos2, explanation)\n )\n\n self.wait(1)\n\n\n axes = Axes(\n x_range=[-2, 2, 2],\n y_range=[-2, 2, 2],\n x_length=4,\n y_length=4,\n )\n self.add(axes)\n\n # \u5358\u4f4d\u5186\u306e\u4f5c\u6210\n circle = Circle(radius=2, color=BLUE)\n self.add(circle)\n\n # \u539f\u70b9 (Origin)\n dot = Dot(ORIGIN, color=RED)\n self.add(dot)\n\n # \u89d2\u5ea6\u3092\u8868\u3059\u7dda\u5206 (Line representing the angle)\n line = Line(ORIGIN, RIGHT * 2)\n self.add(line)\n\n\n # \u89d2\u5ea6\u306e\u30e9\u30d9\u30eb (Angle label)\n # Create an Arc for the angle\n angle = Arc(\n radius=2,\n start_angle=0, # Start at the positive x-axis\n angle=line.get_angle(), # Use line's angle\n arc_center=ORIGIN,\n color=GREEN\n )\n angle_label = MathTex(r\"\\theta = 0^{\\circ}\").next_to(angle, RIGHT) # Changed Tex to MathTex and added \\\\\n self.add(angle, angle_label)\n\n intersection_dot = Dot(color=YELLOW)\n\n angle_tracker = ValueTracker(0)\n\n def update_line(mobject):\n mobject.become(Line(ORIGIN, RIGHT * 2).rotate(angle_tracker.get_value(), about_point=ORIGIN))\n\n def update_angle(mobject):\n mobject.become(Arc(\n radius=2,\n start_angle=0,\n angle=angle_tracker.get_value(),\n arc_center=ORIGIN,\n color=GREEN\n ))\n\n line.add_updater(update_line)\n angle.add_updater(update_angle)\n\n # Update the angle label\n def update_label(mobject):\n angle_in_degrees = np.degrees(angle_tracker.get_value())\n mobject.become(MathTex(rf\"\\\\theta = {angle_in_degrees:.0f}^{{\\circ}}\")) # Added double brackets\n mobject.next_to(angle, RIGHT)\n\n angle_label.add_updater(update_label)\n\n def update_intersection_dot(mobject):\n angle = angle_tracker.get_value()\n x = 2 * np.cos(angle) # x-coordinate on the circle\n y = 2 * np.sin(angle) # y-coordinate on the circle\n mobject.move_to([x, y, 0])\n\n intersection_dot.add_updater(update_intersection_dot)\n\n self.add(intersection_dot)\n # Animate the angle\n self.play(\n angle_tracker.animate.set_value(PI / 6),\n run_time=2\n )\n self.wait(3)\n\n\n line.clear_updaters()\n intersection_dot.clear_updaters()\n angle.clear_updaters()\n angle_label.clear_updaters()\n\n # Change their color to indicate they are fixed\n fixed_line = line.copy().set_color(ORANGE)\n fixed_dot = intersection_dot.copy().set_color(ORANGE)\n fixed_angle = angle.copy().set_color(ORANGE)\n self.add(fixed_line, fixed_dot, fixed_angle)\n\n # Prepare a new line for the next animation\n new_line = Line(ORIGIN, RIGHT * 2, color=GREEN)\n new_intersection_dot = Dot(color=YELLOW)\n new_angle = Arc(\n radius=0.5,\n start_angle=PI / 6, # Start from 30 degrees\n angle=0,\n arc_center=ORIGIN,\n color=GREEN\n )\n new_label = MathTex(rf\"\\theta = 30^\\circ\").next_to(new_angle, RIGHT).set_color(ORANGE)\n\n # Updaters for the new objects\n new_line.add_updater(lambda m: m.become(\n Line(ORIGIN, RIGHT * 2).rotate(angle_tracker.get_value(), about_point=ORIGIN)\n ))\n\n new_intersection_dot.add_updater(lambda m: m.move_to([\n 2 * np.cos(angle_tracker.get_value()),\n 2 * np.sin(angle_tracker.get_value()),\n 0\n ]))\n\n new_angle.add_updater(lambda m: m.become(\n Arc(\n radius=0.5,\n start_angle=0,\n angle=angle_tracker.get_value(),\n arc_center=ORIGIN,\n color=GREEN\n )\n ))\n\n new_label.add_updater(lambda m: m.become(\n MathTex(rf\"\\theta = {np.degrees(angle_tracker.get_value()):.0f}^\\circ\").next_to(new_angle, LEFT)\n ))\n\n # Add the new objects\n self.add(new_line, new_intersection_dot, new_angle, new_label)\n\n # Animate from 30 degrees to 60 degrees\n self.play(\n angle_tracker.animate.set_value(PI / 3), # 60 degrees\n run_time=2\n )\n self.wait(1)\n\n self.wait(10)\n\n\n self.play(\n FadeOut(circle, dot, line, angle, angle_label, axes, line, angle, intersection_dot, angle_label, new_line, new_angle, new_label, new_intersection_dot, fixed_line, fixed_angle, fixed_dot, angle_tracker)\n )\n\n self.play(\n FadeOut(transform_text, explanation),\n Transform(trig_cos2 , trig_cos2.copy().shift(UP + UP + UP)),\n Transform(text, transform_formula),\n )\n self.wait(2)\n\n cos_xx = MathTex(\n r\"\\cos2x = \\cos(A+B)\"\n )\n cos_xx.move_to(ORIGIN + UP)\n\n\n cos_ab = MathTex (\n r\"\\cos(A+B) =(\\cos A \\cdot \\cos B) - (\\sin A \\cdot \\sin B)\"\n )\n cos_ab.move_to(ORIGIN)\n\n\n let_AB = Tex(\"Let A = B\")\n let_AB.move_to(ORIGIN + DOWN)\n\n\n ab_simple = MathTex(\n r\"\\cos(A+A) = \\cos^2A - \\sin^2A\"\n )\n ab_simple.move_to(ORIGIN + DOWN + DOWN)\n\n\n ab_finalize = MathTex(\n r\"= 1-2\\sin^2x\"\n )\n ab_finalize.move_to(ORIGIN + DOWN + DOWN + DOWN + RIGHT)\n\n\n self.play(\n Write(cos_xx)\n )\n self.wait(0.5)\n self.play(\n Write(cos_ab),\n )\n self.wait(0.5)\n self.play(\n Write(let_AB)\n )\n self.wait(0.5)\n self.play(\n Write(ab_simple)\n )\n self.wait(0.5)\n self.play(\n Write(ab_finalize)\n )\n \n arrow = Arrow(2*UP, 2*DOWN)\n VGroup(arrow).set_x(0).arrange(buff=2)\n arrow.move_to(ORIGIN + RIGHT + RIGHT + RIGHT + RIGHT + RIGHT + RIGHT)\n self.play(Write(arrow))\n \n self.wait(15)\n\n\n self.play(\n FadeOut(text, transform_text, trig_cos2, cos_xx, cos_ab, let_AB, ab_simple, ab_finalize, arrow, box, transform_formula)\n )\n\n\n self.wait(1)\n #moving to the explanation of example\n\n\n #What is proof in Math?\n proof = Tex(\"What is proof?\", font_size = 48)\n self.play(Write(proof))\n self.wait(3)\n\n\n self.play(\n Transform(proof, proof.copy().shift(UP).shift(UP))\n )\n\n\n proof_exp = Paragraph(\"In trigonometry, a proof is a way to show that \", \"two trigonometric expressions are equivalent, regardless of the angle. \",\"This process is called validating or proving trigonometric identities.\", font_size=28)\n self.play(Write(proof_exp))\n\n\n self.wait(8)\n self.play(\n FadeOut(proof, proof_exp)\n )\n \n\n\n #starting with Sin and Cos graph identity\n\n\n\n\n ax = Axes()\n sine = ax.plot(np.sin, color = RED)\n cosine = ax.plot(np.cos, color = BLUE)\n self.play(\n FadeIn(ax, sine, cosine)\n )\n \n red_square = Square(fill_opacity = 1, side_length=0.5, fill_color = RED_C).to_corner(UL)\n blue_square = Square(fill_opacity=1, side_length=0.5, fill_color=BLUE_C).to_corner(UL - DOWN)\n\n\n self.play(DrawBorderThenFill(red_square))\n self.play(DrawBorderThenFill(blue_square))\n text_sin = MathTex(r\"\\sin(x)\")\n text_cos = MathTex(r\"\\cos(x)\")\n text_sin.next_to(Square(fill_opacity=1, side_length=0.5, fill_color=RED_C).to_corner(UL))\n text_cos.next_to(Square(fill_opacity=1, side_length=0.5, fill_color=BLUE_C).to_corner(UL - DOWN))\n # Correct usage of next_to: Multiply RIGHT by a scala\n\n\n self.play(Write(text_sin))\n self.wait(0.5)\n\n\n self.play(Write(text_cos))\n self.wait(0.5)\n\n\n self.wait(8)\n self.play(FadeOut(sine, cosine, text_sin, text_cos, ax, red_square, blue_square))\n self.wait(2)\n\n\n prob_cos = Tex(r\"Prove that $\\cos\\left(x - \\frac{\\pi}{2}\\right)$ is the same as $\\sin x$\")\n self.play(Write(prob_cos))\n self.wait(2)\n\n\n self.play(\n Transform(prob_cos, prob_cos.copy().to_corner(UP))\n )\n self.wait(10)\n\n\n step1 = Tex(r\"1. Make balance equation $\\cos\\left(x - \\frac{\\pi}{2}\\right) = \\sin x$\")\n step2 = Tex(\"2. Identify which side is easier to change form, or simplify.\")\n step3 = Tex(\"3. Formulate and make it equal to the other side.\")\n\n\n steps = VGroup(step1, step2, step3).arrange(DOWN, aligned_edge=LEFT)\n steps.move_to(ORIGIN)\n steps.next_to(prob_cos, DOWN, buff=0.5)\n\n\n self.play(\n Write(steps)\n )\n\n\n self.wait(3)\n\n\n self.play(Circumscribe(step1, Rectangle, time_width=4))\n\n\n self.play(\n FadeOut(step2, step3)\n )\n\n\n step1_exp = MathTex(r\"\\cos\\left(x-\\frac{\\pi}{2}\\right) = \\sin x\")\n step1_exp.move_to(ORIGIN)\n\n\n self.play(\n Write(step1_exp)\n )\n\n\n self.wait(6)\n\n\n self.play(\n FadeOut(step1, step1_exp),\n )\n\n\n self.wait(1)\n\n\n self.play(\n FadeIn(steps),\n )\n \n self.wait(3)\n\n\n self.play(\n Circumscribe(step2, Rectangle, time_width=4)\n )\n\n self.play(\n FadeOut(step1, step3),\n Transform(step2, step2.copy().shift(UP))\n )\n \n self.wait(3)\n\n step2_exp = MathTex(r\"\\cos\\left(x-\\frac{\\pi}{2}\\right)\", color=BLUE)\n step2_exp.move_to(ORIGIN)\n self.play(Write(step2_exp))\n self.wait(2)\n\n step2_exp2 = Tex(\"Left side is easier to change form\", color=BLUE)\n step2_exp2.next_to(step2_exp, DOWN)\n\n self.play(Write(step2_exp2))\n self.wait(2)\n\n step2_exp3 = MathTex(r\"\\cos\\left(x-\\frac{\\pi}{2}\\right) = \\cos(A-B)\", color=WHITE)\n step2_exp3.move_to(ORIGIN)\n\n self.play(\n Transform(step2_exp, step2_exp3),\n FadeOut(step2_exp2)\n )\n self.wait(2)\n\n step2_exp4 = MathTex(r\"\\cos(A-B) = \\cos A \\cos B + \\sin A \\sin B\", color=BLUE)\n step2_exp4.next_to(step2_exp3, DOWN)\n\n self.play(Write(step2_exp4))\n self.wait(2)\n\n step2_exp5 = MathTex(r\"A = x, B = \\frac{\\pi}{2}\", color=BLUE)\n step2_exp5.next_to(step2_exp4, DOWN)\n\n self.play(Write(step2_exp5))\n self.wait(2)\n\n step2_exp6 = MathTex(r\"\\cos x \\cos \\frac{\\pi}{2} + \\sin x \\sin \\frac{\\pi}{2}\", color=WHITE)\n step2_exp6.move_to(ORIGIN)\n\n self.play(\n FadeOut(step2_exp, step2_exp4, step2_exp5),\n Write(step2_exp6)\n )\n self.wait(2)\n\n step2_exp7 = MathTex(r\"\\cos \\frac{\\pi}{2} = 0, \\sin \\frac{\\pi}{2} = 1\", color=BLUE)\n step2_exp7.next_to(step2_exp6, DOWN)\n\n self.play(Write(step2_exp7))\n self.wait(2)\n\nstep2_exp8 = MathTex(r\"\\cos x (0) + \\sin x (1) = \\sin x\", color=WHITE)\n step2_exp8.move_to(ORIGIN)\n\n self.play(\n FadeOut(step2_exp6, step2_exp7),\n Write(step2_exp8)\n )\n self.wait(2)\n\n self.play(FadeOut(step2_exp8, step2))\n\n\n \n\n\n \n\n\n\n\n\n\n \n\n\n\n\n\n\n self.wait(15)\n", "highlighted_code": "step2_exp8 = MathTex(r\"\\cos x (0) + \\sin x (1) = \\sin x\", color=WHITE)\n step2_exp8.move_to(ORIGIN)\n\n self.play(\n FadeOut(step2_exp6, step2_exp7),\n Write(step2_exp8)\n )\n self.wait(2)\n\n self.play(FadeOut(step2_exp8, step2))", "instruction": "Move the proved sinx to center of the screen and fade out rest of equation", "test_code": "import pytest\nimport re\nimport inspect\nfrom typing import List\nimport ast\n\ndef get_source_code(impl_name, module) -> str:\n \"\"\"Get the source code of the implementation module\"\"\"\n try:\n return inspect.getsource(module)\n except Exception:\n return \"\"\n\nimport re\nfrom typing import List\n\ndef test_moves_sinx_equation_to_center(implementation):\n \"\"\"Test if sinx (step2_exp8) is moved to the center of the screen\"\"\"\n impl_name, module = implementation\n code = get_source_code(impl_name, module)\n\n # Look for .move_to(ORIGIN) or .animate.move_to(ORIGIN) applied to sinx object\n moved = re.search(r'step2_exp8(\\.animate)?\\.move_to\\s*\\(\\s*ORIGIN\\s*\\)', code)\n assert moved, f\"{impl_name} does not move sinx (step2_exp8) to center using move_to(ORIGIN)\"\n\ndef test_fades_out_other_equations(implementation):\n \"\"\"Test if other equations (e.g. step2_exp6, step2_exp7) are faded out\"\"\"\n impl_name, module = implementation\n code = get_source_code(impl_name, module)\n\n # Look for FadeOut involving other step2 expressions\n fadeout_other = re.search(r'FadeOut\\s*\\(\\s*step2_exp6\\s*,\\s*step2_exp7\\s*\\)', code) or \\\n re.search(r'FadeOut\\s*\\(\\s*step2_exp\\d+', code)\n assert fadeout_other, f\"{impl_name} does not fade out other equations like step2_exp6, step2_exp7\"\n", "requirements": "pytest\npytest-mock\nmanim\nnumpy\npyglm\npydub", "conftest": "import pytest\nimport os\nimport sys\nimport json\nfrom typing import Dict, List, Optional, Any\n\n# Import from local test_utils.py in the same directory\nfrom test_utils import TestUtils, TestResultsManager\n\n# Load all implementations in the current sandbox\nimplementations = TestUtils.load_all_implementations()\ntest_results = TestResultsManager()\n\n@pytest.fixture(scope=\"session\")\ndef sandbox_dir():\n \"\"\"Fixture to provide the sandbox directory path.\"\"\"\n return os.path.dirname(os.path.abspath(__file__))\n\n@pytest.fixture(scope=\"session\")\ndef sandbox_name():\n \"\"\"Fixture to provide the sandbox name.\"\"\"\n return os.path.basename(os.path.dirname(os.path.abspath(__file__)))\n\n@pytest.fixture(scope=\"session\")\ndef all_implementations():\n \"\"\"Fixture to provide all implementations as a dictionary.\"\"\"\n return implementations\n\n@pytest.fixture(params=list(implementations.items()))\ndef implementation(request):\n \"\"\"Fixture to provide each implementation to tests one at a time.\"\"\"\n return request.param\n\n@pytest.fixture(scope=\"session\")\ndef results_manager():\n \"\"\"Fixture to provide access to the test results manager.\"\"\"\n return test_results\n\n# Hook for collecting test results\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n \"\"\"Pytest hook to collect test results.\"\"\"\n # Execute all other hooks to obtain the report object\n outcome = yield\n rep = outcome.get_result()\n \n # We're only interested in the call outcome\n if rep.when == \"call\":\n if hasattr(item, \"callspec\") and \"implementation\" in item.callspec.params:\n # Get implementation name and module\n impl_name, _ = item.callspec.params[\"implementation\"]\n \n # Get test name\n test_name = item.nodeid.split(\"::\")[-1]\n \n # Record result\n if rep.passed:\n test_results.record_result(impl_name, test_name, True)\n elif rep.failed:\n error_msg = str(rep.longrepr) if rep.longrepr else \"Test failed\"\n test_results.record_result(impl_name, test_name, False, error_msg)\n elif rep.skipped:\n skip_reason = rep.longrepr[2] if rep.longrepr else \"Test skipped\"\n test_results.record_skip(impl_name, test_name, skip_reason)\n\n# Hook to save results at the end of testing\n@pytest.hookimpl(trylast=True)\ndef pytest_sessionfinish(session, exitstatus):\n \"\"\"Save test results at the end of the test session.\"\"\"\n test_results.save_results()", "test_utils": "import os\nimport sys\nimport glob\nimport re\nimport importlib.util\nimport traceback\nimport types\nfrom typing import Dict, List, Optional, Any, Tuple\n\nclass TestUtils:\n @staticmethod\n def discover_implementation_files(directory: str = None) -> List[str]:\n \"\"\"Find all implementation files in the current sandbox directory.\"\"\"\n if directory is None:\n directory = os.path.dirname(os.path.abspath(__file__))\n \n patterns = [\n r'modified_code\\d+\\.py',\n r'new_code\\d+\\.py', \n # r'original_code\\.py',\n r'implementation\\d*\\.py'\n ]\n \n pattern = re.compile('|'.join(f'({p})' for p in patterns))\n implementations = []\n \n for file_path in glob.glob(os.path.join(directory, '*.py')):\n if pattern.search(os.path.basename(file_path)):\n implementations.append(file_path)\n \n # Sort files numerically\n def sort_key(path):\n filename = os.path.basename(path)\n match = re.search(r'(\\d+)', filename)\n return int(match.group(1)) if match else 0\n \n return sorted(implementations, key=sort_key)\n \n @staticmethod\n def create_mock_module(file_path: str, module_name: str, error_info: str) -> types.ModuleType:\n \"\"\"Create a mock module that contains error information but can still be tested.\"\"\"\n # Create a new module object\n mock_module = types.ModuleType(module_name)\n \n # Add basic attributes\n mock_module.__file__ = file_path\n mock_module.__name__ = module_name\n mock_module.__display_name__ = module_name\n mock_module.__error__ = error_info\n \n # Add a dummy function that can be detected by test functions\n def dummy_function(*args, **kwargs):\n return f\"Error in module: {error_info}\"\n \n setattr(mock_module, \"implementation_error\", dummy_function)\n \n return mock_module\n\n @staticmethod\n def load_module(file_path: str, module_name: Optional[str] = None) -> Any:\n \"\"\"\n Safely load a module from a file path with proper error handling.\n If the module has errors, return a mock module that can still be tested.\n \"\"\"\n if module_name is None:\n module_name = os.path.basename(file_path).replace('.py', '')\n \n # Create a unique module name to avoid conflicts\n sandbox_id = os.path.basename(os.path.dirname(file_path))\n unique_module_name = f\"{sandbox_id}_{module_name}\"\n \n try:\n # First, try to read the file to check for syntax errors\n with open(file_path, 'r') as f:\n source_code = f.read()\n \n # Check for syntax errors by compiling the code\n try:\n compiled = compile(source_code, file_path, 'exec')\n except SyntaxError as e:\n error_msg = f\"Syntax error: {str(e)}\"\n print(f\"Syntax error in {file_path}: {e}\")\n print(f\" Line {e.lineno}, column {e.offset}: {e.text}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n # Create the module spec\n spec = importlib.util.spec_from_file_location(unique_module_name, file_path)\n if spec is None or spec.loader is None:\n error_msg = f\"Could not create spec for {file_path}\"\n print(f\"Error: {error_msg}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n # Create the module object\n module = importlib.util.module_from_spec(spec)\n sys.modules[unique_module_name] = module\n \n # Special handling for execution errors\n try:\n # Execute the module code in a safe way\n spec.loader.exec_module(module)\n # Store the original name for reference\n module.__display_name__ = module_name\n return module\n except Exception as e:\n error_msg = f\"Runtime error: {str(e)}\"\n traceback_str = traceback.format_exc()\n print(f\"Error executing module {file_path}: {e}\")\n print(traceback_str)\n \n # Create a partial module that contains what we loaded before the error\n mock_module = TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n # Copy any attributes that might have been defined before the error\n for attr_name in dir(module):\n if not attr_name.startswith('__'):\n try:\n setattr(mock_module, attr_name, getattr(module, attr_name))\n except Exception:\n pass # Skip attributes that can't be copied\n \n return mock_module\n \n except FileNotFoundError as e:\n error_msg = f\"File not found: {str(e)}\"\n print(f\"Error: {error_msg}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n except Exception as e:\n error_msg = f\"Unexpected error: {str(e)}\"\n print(f\"Error loading module {file_path}: {e}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n @classmethod\n def load_all_implementations(cls, directory: str = None) -> Dict[str, Any]:\n \"\"\"Load all implementation files in the directory, including those with errors.\"\"\"\n if directory is None:\n directory = os.path.dirname(os.path.abspath(__file__))\n \n implementations = {}\n \n implementation_files = cls.discover_implementation_files(directory)\n if not implementation_files:\n print(\"WARNING: No implementation files found. Check your file naming patterns.\")\n \n for file_path in implementation_files:\n module_name = os.path.basename(file_path).replace('.py', '')\n module = cls.load_module(file_path, module_name)\n \n # Always add the module, even if it has errors\n implementations[module_name] = module\n \n if hasattr(module, '__error__'):\n print(f\"Loaded with errors: {module_name} - {module.__error__}\")\n else:\n print(f\"Successfully loaded: {module_name}\")\n \n return implementations\n\nclass TestResultsManager:\n def __init__(self):\n self.results = {}\n self.sandbox_name = os.path.basename(os.path.dirname(os.path.abspath(__file__)))\n \n def record_result(self, impl_name: str, test_name: str, passed: bool, \n error_msg: Optional[str] = None) -> None:\n \"\"\"Record a test result for an implementation.\"\"\"\n if impl_name not in self.results:\n self.results[impl_name] = {\"passed\": 0, \"failed\": 0, \"skipped\": 0, \"errors\": []}\n \n if passed:\n self.results[impl_name][\"passed\"] += 1\n else:\n self.results[impl_name][\"failed\"] += 1\n if error_msg:\n self.results[impl_name][\"errors\"].append({\n \"test\": test_name,\n \"error\": error_msg\n })\n \n def record_skip(self, impl_name: str, test_name: str, \n reason: Optional[str] = None) -> None:\n \"\"\"Record a skipped test for an implementation.\"\"\"\n if impl_name not in self.results:\n self.results[impl_name] = {\"passed\": 0, \"failed\": 0, \"skipped\": 0, \"errors\": []}\n \n self.results[impl_name][\"skipped\"] += 1\n if reason:\n self.results[impl_name][\"errors\"].append({\n \"test\": test_name,\n \"error\": f\"SKIPPED: {reason}\"\n })\n \n def get_winner(self) -> Tuple[Optional[int], Dict]:\n \"\"\"Determine the winner based on test results.\"\"\"\n winner = None\n max_passed = -1\n \n for impl_name, results in self.results.items():\n if impl_name == \"original_code\":\n continue # Skip original code when determining winner\n \n if results[\"passed\"] > max_passed:\n max_passed = results[\"passed\"]\n winner = impl_name\n # Break ties by looking at failure count\n elif results[\"passed\"] == max_passed and winner is not None:\n if results[\"failed\"] < self.results[winner][\"failed\"]:\n winner = impl_name\n \n # Convert winner to numeric index if possible\n winner_index = -1\n if winner and re.match(r'modified_code\\d+', winner):\n try:\n winner_index = int(re.search(r'(\\d+)', winner).group(1))\n except (AttributeError, ValueError):\n pass\n \n return winner_index, self.results\n \n def save_results(self, filename: str = \"test_results.json\") -> None:\n \"\"\"Save test results to a JSON file.\"\"\"\n import json\n \n winner_index, results = self.get_winner()\n \n # Check if all tests were skipped\n all_skipped = all(\n stats[\"skipped\"] == stats[\"passed\"] + stats[\"failed\"] + stats[\"skipped\"]\n for impl_name, stats in results.items()\n if impl_name != \"original_code\"\n )\n \n output = {\n \"winner\": winner_index,\n \"all_skipped\": all_skipped,\n \"results\": {\n name: {\n \"passed\": stats[\"passed\"],\n \"failed\": stats[\"failed\"],\n \"skipped\": stats[\"skipped\"],\n \"total\": stats[\"passed\"] + stats[\"failed\"] + stats[\"skipped\"]\n }\n for name, stats in results.items()\n if not name.startswith(\"_\") # Skip internal items\n }\n }\n \n with open(filename, \"w\") as f:\n json.dump(output, f, indent=2)\n \n print(f\"Test results saved to {filename}\")\n \n return output", "split": "test"} {"problem_id": 104, "programming_language": "python", "original_code": "import requests #\u0434\u043b\u044f \u0437\u0430\u043f\u0440\u043e\u0441\u0430 \u043a API\nimport xml.etree.ElementTree #\u0434\u043b\u044f \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 xml-\u043e\u0442\u0432\u0435\u0442\u0430 API\nimport datetime #\u0434\u043b\u044f \u0434\u0430\u0442 \u043f\u043e \u043e\u0441\u0438 \u0438\u043a\u0441\u043e\u0432\nimport pickle #\u0434\u043b\u044f \u0445\u0440\u0430\u043d\u0435\u043d\u0438\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445 \u0432 \u0444\u0430\u0439\u043b\u0435\nimport json\n\n#\u0444\u0430\u043a \u044e \u043d\u0438\u0433\u0435\u0440\n#\u0434\u043e\u043f\u0438\u0448\u0438 \u0447\u0442\u043e\u0431\u044b set_valutes \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u043b\u043e\u0441\u044c!!! \u043e\u043d\u043e \u0444\u0430\u043a\u0438\u043d\u0433 \u043d\u0438\u0433\u0435\u0440 \u0438 \u043d\u0435 \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u0442\u0441\u044f\n\n\n#\u043a\u043b\u0430\u0441\u0441 \u0432\u0430\u043b\u044e\u0442\u0430\nclass valute():\n \"\"\"\u0412\u0430\u043b\u044e\u0442\u0430 \u0438 \u0432\u0441\u0451 \u0441 \u043d\u0435\u0439 \u0441\u0432\u044f\u0437\u0430\u043d\u043d\u043e\u0435, \u0447\u0435\u0440\u0435\u0437 \u0426\u0411 \u0420\u0424 \\n\n \u0422\u0440\u0435\u0431\u0443\u044e\u0442\u0441\u044f \u0431\u0438\u0431\u043b\u0435\u043e\u0442\u0435\u043a\u0438: \\n\n requests \\n\n xml.etree.ElementTree \\n\n datetime \\n\n pickle \\n\n json \\n\n \"\"\"\n def __init__(self, name):\n self.name = name\n def correct_name(self):\n \"\"\"\u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u0438\u043c\u0435\u043d\u0438 \u0432\u0430\u043b\u044e\u0442\u044b \u043d\u0430 \u043d\u0430\u043b\u0438\u0447\u0438\u0435 \u0432 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0435 \u0432\u0430\u043b\u044e\u0442. \u041c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u043e\u0431\u043d\u043e\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043d\u0435 \u0447\u0430\u0449\u0435 \u0440\u0430\u0437\u0430 \u0432 \u0434\u0435\u043d\u044c\"\"\"\n info_opened_file = open(r\"D:\\MoexAPI_bot_aiogram3\\data_files\\Info.json\", \"r\", encoding=\"utf-8\") #\u043e\u0442\u043a\u0440\u044b\u0432\u0430\u0435\u043c \u0444\u0430\u0439\u043b \u0438\u043d\u0444\u044b, encoding \u0447\u0442\u043e\u0431\u044b \u043d\u0435 \u0431\u044b\u043b\u043e\n info = json.load(info_opened_file)\n info_opened_file.close()\n if datetime.datetime.now() - datetime.timedelta(days=1) > datetime.datetime.strptime(info[\"last_day_check\"][\"valute\"], \"%Y-%m-%d %H:%M:%S.%f\"): #\u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u0443\u0441\u043b\u043e\u0432\u0438\u0435 \u0447\u0442\u043e \u0434\u0430\u0442\u0430 \u043f\u0435\u0440\u0435\u0437\u0430\u043f\u0438\u0441\u0438 \u0441\u043f\u0438\u0441\u043a\u0430 \u0432\u0430\u043b\u044e\u0442 \u044d\u0442\u043e \u0445\u043e\u0442\u044f \u0431\u044b 1 \u0434\u0435\u043d\u044c \u043d\u0430\u0437\u0430\u0434\n #\u0435\u0441\u043b\u0438 \u043e\u0442\u043b\u0438\u0447\u0430\u0435\u0442\u0441\u044f \u0431\u043e\u043b\u0435\u0435 \u0447\u0435\u043c \u043d\u0430 1 \u0434\u0435\u043d\u044c, \u0442\u043e \u043f\u0435\u0440\u0435\u043f\u0438\u0441\u044b\u0432\u0430\u0435\u043c \u0441\u043f\u0438\u0441\u043e\u043a (\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e) \u0432\u0430\u043b\u044e\u0442:\n set_valutes = set() #\u0441\u043e\u0437\u0434\u0430\u0451\u043c \u043f\u0443\u0441\u0442\u043e\u0435 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e, \u0432 \u043d\u0435\u0433\u043e \u0431\u0443\u0434\u0435\u043c \u0437\u0430\u043b\u0438\u0432\u0430\u0442\u044c \u0432\u0430\u043b\u044e\u0442\u044b\n s = \"http://www.cbr.ru/scripts/XML_daily.asp\"\n r = requests.get(s)\n root = xml.etree.ElementTree.fromstring(r.content) #\u0437\u0430\u043f\u0440\u043e\u0441 \u0432\u0441\u0451 \u0440\u0430\u0432\u043d\u043e \u0432\u044b\u0434\u0430\u0451\u0442 \u0434\u0430\u043d\u043d\u044b\u0435 \u0441\u0430\u0439\u0442\u0430 \u043a\u0430\u043a \u0441\u0442\u0440\u043e\u043a\u0443, \u0442\u0430\u043a \u0447\u0442\u043e \u0431\u0435\u0437 fromstring \u043d\u0438\u043a\u0430\u043a\n for Valute in root.findall(\"Valute\"):\n CharCode = Valute.find(\"CharCode\")\n set_valutes.add(CharCode.text) #\u0437\u0430\u043b\u0438\u0432\u0430\u0435\u043c \u0432\u0430\u043b\u044e\u0442\u044b \u0432 \u043d\u0430\u0448\u0435 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e\n set_valutes_file_opened = open(r\"D:\\MoexAPI_bot_aiogram3\\data_files\\set_valutes.bin\", \"wb\") #\u043e\u0442\u043a\u0440\u044b\u0432\u0430\u0435\u043c \u0444\u0430\u0439\u043b \u0434\u043b\u044f \u0431\u0438\u043d\u0430\u0440\u043d\u043e\u0439 \u0437\u0430\u043f\u0438\u0441\u0438 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0430 \u0442\u0438\u043a\u0435\u0440\u043e\u0432 \u0432 \u043d\u0435\u0433\u043e\n pickle.dump(set_valutes, set_valutes_file_opened) #\u0437\u0430\u043a\u0438\u0434\u044b\u0432\u0430\u0435\u043c \u0441\u043e\u0437\u0434\u0430\u043d\u043d\u043e\u0435 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0432 \u0444\u0430\u0439\u043b. \u0415\u0441\u043b\u0438 \u0447\u0442\u043e, \u043a\u0430\u0436\u0434\u044b\u0439 \u0440\u0430\u0437 \u0431\u0443\u0434\u0435\u0442 \u043f\u0435\u0440\u0435\u0437\u0430\u043f\u0438\u0441\u044b\u0432\u0430\u0442\u044c\u0441\u044f (\u043f\u0440\u043e\u0432\u0435\u0440\u0435\u043d\u043e)\n set_valutes_file_opened.close() #\u0437\u0430\u043a\u0440\u044b\u0432\u0430\u0435\u043c \u0444\u0430\u0439\u043b\n #\u043f\u043e\u043c\u0435\u043d\u044f\u0435\u043c \u0432\u0440\u0435\u043c\u044f \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0433\u043e \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u044f\n info[\"last_day_check\"][\"valute\"] = str(datetime.datetime.now())\n info_opened_file = open(r\"D:\\MoexAPI_bot_aiogram3\\data_files\\Info.json\", \"w\", encoding=\"utf-8\")\n json.dump(info, info_opened_file, indent = 3, ensure_ascii = False) #\u0437\u0430\u043f\u0438\u0448\u0435\u043c \u043d\u043e\u0432\u044b\u0439 \u0444\u0430\u0439\u043b\n info_opened_file.close()\n #\u0442\u0435\u043f\u0435\u0440\u044c \u043f\u0440\u043e\u0441\u0442\u043e \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u043c \u0435\u0441\u0442\u044c \u043b\u0438 \u0432\u0430\u043b\u044e\u0442\u0430 \u0432 \u0441\u043f\u0438\u0441\u043a\u0435 \u0432\u0430\u043b\u044e\u0442\n set_valutes_file_opened = open(r\"D:\\MoexAPI_bot_aiogram3\\data_files\\set_valutes.bin\", \"rb\") #\u043e\u0442\u043a\u0440\u044b\u0432\u0430\u0435\u043c \u0444\u0430\u0439\u043b \u0441 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e\u043c \u0442\u0438\u043a\u0435\u0440\u043e\u0432 \u0447\u0442\u043e\u0431\u044b \u0435\u0433\u043e \u043e\u0442\u0442\u0443\u0434\u0430 \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c\n set_valutes = pickle.load(set_valutes_file_opened) #\u0438\u0437 \u043e\u0442\u043a\u0440\u044b\u0442\u043e\u0433\u043e \u0444\u0430\u0439\u043b\u0430 \u0432\u044b\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0430 \u0432\u0430\u043b\u044e\u0442 \u0432 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e. \u0415\u0441\u043b\u0438 \u0432\u0434\u0440\u0443\u0433 \u0437\u0430\u043f\u0438\u0448\u0435\u0442\u0441\u044f \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432 (\u0442\u0430\u043a\u043e\u0433\u043e \u0431\u044b\u0442\u044c \u043d\u0435 \u0434\u043e\u043b\u0436\u043d\u043e), \u0442\u043e \u043e\u0442\u043a\u0440\u043e\u0435\u0442\u0441\u044f \u0442\u043e\u043b\u044c\u043a\u043e \u043f\u0435\u0440\u0432\u043e\u0435 \u0438\u0437 \u043d\u0438\u0445\n if self.name in set_valutes: #\u043f\u0440\u043e\u0441\u0442\u043e \u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u0435\u0441\u0442\u044c \u043b\u0438 \u0432\u0430\u043b\u044e\u0442\u0430 \u0432 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0435 \u0442\u0438\u043a\u0435\u0440\u043e\u0432\n return True\n else:\n return False\n def CurrentExchangeRate(self):\n '''\u0422\u0435\u043a\u0443\u0449\u0438\u0439 \u043a\u0443\u0440\u0441 \u043e\u0431\u043c\u0435\u043d\u0430 \u0432\u0430\u043b\u044e\u0442\u044b \u043d\u0430 \u0440\u0443\u0431\u043b\u044c'''\n r = requests.get(\"http://www.cbr.ru/scripts/XML_daily.asp\") #Api \u0426\u0411 \u0420\u0424\n root = xml.etree.ElementTree.fromstring(r.content)\n for Valute in root.findall(\"Valute\"): #\u0438\u0449\u0435\u043c \u043a\u043e\u043d\u0442\u0435\u0439\u043d\u0435\u0440\u044b \u0432\u0430\u043b\u044e\u0442\u044b\n for CharCode in Valute.findall(\"CharCode\"): #\u0438\u0449\u0435\u043c \u043a\u043e\u043d\u0442\u0435\u0439\u043d\u0435\u0440\u044b \u0447\u0430\u0440\u043a\u043e\u0434\u043e\u0432\n if CharCode.text == self.name: #\u043d\u0430\u0445\u043e\u0434\u0438\u043c \u043a\u043e\u043d\u0442\u0435\u0439\u043d\u0435\u0440 \u0441 \u043d\u0443\u0436\u043d\u043e\u0439 \u0432\u0430\u043b\u044e\u0442\u043e\u0439\n return (Valute.find(\"VunitRate\").text)", "highlighted_code": " def correct_name(self):\n \"\"\"\u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u0438\u043c\u0435\u043d\u0438 \u0432\u0430\u043b\u044e\u0442\u044b \u043d\u0430 \u043d\u0430\u043b\u0438\u0447\u0438\u0435 \u0432 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0435 \u0432\u0430\u043b\u044e\u0442. \u041c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u043e\u0431\u043d\u043e\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043d\u0435 \u0447\u0430\u0449\u0435 \u0440\u0430\u0437\u0430 \u0432 \u0434\u0435\u043d\u044c\"\"\"\n info_opened_file = open(r\"D:\\MoexAPI_bot_aiogram3\\data_files\\Info.json\", \"r\", encoding=\"utf-8\") #\u043e\u0442\u043a\u0440\u044b\u0432\u0430\u0435\u043c \u0444\u0430\u0439\u043b \u0438\u043d\u0444\u044b, encoding \u0447\u0442\u043e\u0431\u044b \u043d\u0435 \u0431\u044b\u043b\u043e\n info = json.load(info_opened_file)\n info_opened_file.close()\n if datetime.datetime.now() - datetime.timedelta(days=1) > datetime.datetime.strptime(info[\"last_day_check\"][\"valute\"], \"%Y-%m-%d %H:%M:%S.%f\"): #\u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u0443\u0441\u043b\u043e\u0432\u0438\u0435 \u0447\u0442\u043e \u0434\u0430\u0442\u0430 \u043f\u0435\u0440\u0435\u0437\u0430\u043f\u0438\u0441\u0438 \u0441\u043f\u0438\u0441\u043a\u0430 \u0432\u0430\u043b\u044e\u0442 \u044d\u0442\u043e \u0445\u043e\u0442\u044f \u0431\u044b 1 \u0434\u0435\u043d\u044c \u043d\u0430\u0437\u0430\u0434\n #\u0435\u0441\u043b\u0438 \u043e\u0442\u043b\u0438\u0447\u0430\u0435\u0442\u0441\u044f \u0431\u043e\u043b\u0435\u0435 \u0447\u0435\u043c \u043d\u0430 1 \u0434\u0435\u043d\u044c, \u0442\u043e \u043f\u0435\u0440\u0435\u043f\u0438\u0441\u044b\u0432\u0430\u0435\u043c \u0441\u043f\u0438\u0441\u043e\u043a (\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e) \u0432\u0430\u043b\u044e\u0442:\n set_valutes = set() #\u0441\u043e\u0437\u0434\u0430\u0451\u043c \u043f\u0443\u0441\u0442\u043e\u0435 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e, \u0432 \u043d\u0435\u0433\u043e \u0431\u0443\u0434\u0435\u043c \u0437\u0430\u043b\u0438\u0432\u0430\u0442\u044c \u0432\u0430\u043b\u044e\u0442\u044b\n s = \"http://www.cbr.ru/scripts/XML_daily.asp\"\n r = requests.get(s)\n root = xml.etree.ElementTree.fromstring(r.content) #\u0437\u0430\u043f\u0440\u043e\u0441 \u0432\u0441\u0451 \u0440\u0430\u0432\u043d\u043e \u0432\u044b\u0434\u0430\u0451\u0442 \u0434\u0430\u043d\u043d\u044b\u0435 \u0441\u0430\u0439\u0442\u0430 \u043a\u0430\u043a \u0441\u0442\u0440\u043e\u043a\u0443, \u0442\u0430\u043a \u0447\u0442\u043e \u0431\u0435\u0437 fromstring \u043d\u0438\u043a\u0430\u043a\n for Valute in root.findall(\"Valute\"):\n CharCode = Valute.find(\"CharCode\")\n set_valutes.add(CharCode.text) #\u0437\u0430\u043b\u0438\u0432\u0430\u0435\u043c \u0432\u0430\u043b\u044e\u0442\u044b \u0432 \u043d\u0430\u0448\u0435 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e\n set_valutes_file_opened = open(r\"D:\\MoexAPI_bot_aiogram3\\data_files\\set_valutes.bin\", \"wb\") #\u043e\u0442\u043a\u0440\u044b\u0432\u0430\u0435\u043c \u0444\u0430\u0439\u043b \u0434\u043b\u044f \u0431\u0438\u043d\u0430\u0440\u043d\u043e\u0439 \u0437\u0430\u043f\u0438\u0441\u0438 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0430 \u0442\u0438\u043a\u0435\u0440\u043e\u0432 \u0432 \u043d\u0435\u0433\u043e\n pickle.dump(set_valutes, set_valutes_file_opened) #\u0437\u0430\u043a\u0438\u0434\u044b\u0432\u0430\u0435\u043c \u0441\u043e\u0437\u0434\u0430\u043d\u043d\u043e\u0435 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0432 \u0444\u0430\u0439\u043b. \u0415\u0441\u043b\u0438 \u0447\u0442\u043e, \u043a\u0430\u0436\u0434\u044b\u0439 \u0440\u0430\u0437 \u0431\u0443\u0434\u0435\u0442 \u043f\u0435\u0440\u0435\u0437\u0430\u043f\u0438\u0441\u044b\u0432\u0430\u0442\u044c\u0441\u044f (\u043f\u0440\u043e\u0432\u0435\u0440\u0435\u043d\u043e)\n set_valutes_file_opened.close() #\u0437\u0430\u043a\u0440\u044b\u0432\u0430\u0435\u043c \u0444\u0430\u0439\u043b\n #\u043f\u043e\u043c\u0435\u043d\u044f\u0435\u043c \u0432\u0440\u0435\u043c\u044f \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0433\u043e \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u044f\n info[\"last_day_check\"][\"valute\"] = str(datetime.datetime.now())\n info_opened_file = open(r\"D:\\MoexAPI_bot_aiogram3\\data_files\\Info.json\", \"w\", encoding=\"utf-8\")\n json.dump(info, info_opened_file, indent = 3, ensure_ascii = False) #\u0437\u0430\u043f\u0438\u0448\u0435\u043c \u043d\u043e\u0432\u044b\u0439 \u0444\u0430\u0439\u043b\n info_opened_file.close()\n #\u0442\u0435\u043f\u0435\u0440\u044c \u043f\u0440\u043e\u0441\u0442\u043e \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u043c \u0435\u0441\u0442\u044c \u043b\u0438 \u0432\u0430\u043b\u044e\u0442\u0430 \u0432 \u0441\u043f\u0438\u0441\u043a\u0435 \u0432\u0430\u043b\u044e\u0442\n set_valutes_file_opened = open(r\"D:\\MoexAPI_bot_aiogram3\\data_files\\set_valutes.bin\", \"rb\") #\u043e\u0442\u043a\u0440\u044b\u0432\u0430\u0435\u043c \u0444\u0430\u0439\u043b \u0441 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e\u043c \u0442\u0438\u043a\u0435\u0440\u043e\u0432 \u0447\u0442\u043e\u0431\u044b \u0435\u0433\u043e \u043e\u0442\u0442\u0443\u0434\u0430 \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c\n set_valutes = pickle.load(set_valutes_file_opened) #\u0438\u0437 \u043e\u0442\u043a\u0440\u044b\u0442\u043e\u0433\u043e \u0444\u0430\u0439\u043b\u0430 \u0432\u044b\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0430 \u0432\u0430\u043b\u044e\u0442 \u0432 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e. \u0415\u0441\u043b\u0438 \u0432\u0434\u0440\u0443\u0433 \u0437\u0430\u043f\u0438\u0448\u0435\u0442\u0441\u044f \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432 (\u0442\u0430\u043a\u043e\u0433\u043e \u0431\u044b\u0442\u044c \u043d\u0435 \u0434\u043e\u043b\u0436\u043d\u043e), \u0442\u043e \u043e\u0442\u043a\u0440\u043e\u0435\u0442\u0441\u044f \u0442\u043e\u043b\u044c\u043a\u043e \u043f\u0435\u0440\u0432\u043e\u0435 \u0438\u0437 \u043d\u0438\u0445\n if self.name in set_valutes: #\u043f\u0440\u043e\u0441\u0442\u043e \u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u0435\u0441\u0442\u044c \u043b\u0438 \u0432\u0430\u043b\u044e\u0442\u0430 \u0432 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0435 \u0442\u0438\u043a\u0435\u0440\u043e\u0432\n return True\n else:\n return False", "instruction": "\u043f\u0435\u0440\u0435\u043f\u0438\u0448\u0438 \u043c\u0435\u0442\u043e\u0434 \u0430\u0441\u0438\u043d\u0445\u0440\u043e\u043d\u043d\u043e, \u0438\u043c\u043f\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u0430\u0432 aiofiles \u0438 \u0441\u043e\u0445\u0440\u0430\u043d\u0438\u0432 \u043c\u043e\u0438 \u043a\u043e\u043c\u043c\u0435\u043d\u0442\u0430\u0440\u0438\u0438", "test_code": "import asyncio\nimport inspect\nimport json\nimport pickle\nfrom datetime import datetime, timedelta\nfrom unittest.mock import AsyncMock, MagicMock, patch\nimport pytest\nimport sys\nimport aiofiles\n\nclass AsyncContextManagerMock:\n \"\"\"A mock for async context managers with awaitable methods like read/write\"\"\"\n def __init__(self, read_data=None):\n self.aenter_return = MagicMock()\n self.aenter_return.read = AsyncMock(return_value=read_data)\n self.aenter_return.write = AsyncMock()\n self.aenter_return.close = AsyncMock()\n\n async def __aenter__(self):\n return self.aenter_return\n\n async def __aexit__(self, *args):\n pass\n\n@pytest.fixture\ndef mock_files():\n \"\"\"Setup mock file data for testing\"\"\"\n info_data = {\n \"last_day_check\": {\n \"valute\": (datetime.now() - timedelta(days=2)).strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n }\n }\n info_data_str = json.dumps(info_data)\n set_valutes = {\"USD\", \"EUR\", \"GBP\"}\n set_valutes_bytes = pickle.dumps(set_valutes)\n\n xml_content = \"\"\"\n \n \n 840\n USD\n 1\n \u0414\u043e\u043b\u043b\u0430\u0440 \u0421\u0428\u0410\n 75,1234\n 75,1234\n \n \n 978\n EUR\n 1\n \u0415\u0432\u0440\u043e\n 85,5678\n 85,5678\n \n \n \"\"\"\n\n return {\n \"info_data_str\": info_data_str,\n \"info_data\": info_data,\n \"set_valutes\": set_valutes,\n \"set_valutes_bytes\": set_valutes_bytes,\n \"xml_content\": xml_content.strip()\n }\n\ndef is_any_path_match(path, patterns):\n \"\"\"Check if any pattern is in the path string\"\"\"\n if not isinstance(path, str):\n return False\n path = path.lower().replace('\\\\', '/').replace('//', '/')\n return any(pattern.lower() in path for pattern in patterns)\n\ndef aiofiles_open_side_effect_factory(mock_files):\n \"\"\"Factory to return a patched aiofiles.open function\"\"\"\n def side_effect(*args, **kwargs):\n path = args[0] if args else \"\"\n if is_any_path_match(path, [\"info.json\"]):\n return AsyncContextManagerMock(read_data=mock_files[\"info_data_str\"])\n elif is_any_path_match(path, [\"set_valutes.bin\"]):\n return AsyncContextManagerMock(read_data=mock_files[\"set_valutes_bytes\"])\n else:\n return AsyncContextManagerMock(read_data=\"{}\")\n return side_effect\n\ndef test_correct_imports_and_async_def(implementation):\n \"\"\"Ensure aiofiles is imported and correct_name is async\"\"\"\n impl_name, module = implementation\n source_code = inspect.getsource(module)\n assert \"aiofiles\" in source_code, \"Implementation should import aiofiles\"\n valute_class = getattr(module, \"valute\", None)\n assert valute_class is not None\n assert asyncio.iscoroutinefunction(valute_class.correct_name), \"correct_name should be async\"\n\n@pytest.mark.asyncio\nasync def test_correct_name_logic_async(implementation, mock_files):\n \"\"\"Test correct_name returns correct value and uses aiofiles properly\"\"\"\n impl_name, module = implementation\n sys.modules[module.__name__].aiofiles = aiofiles\n valute_class = getattr(module, \"valute\")\n valute_instance = valute_class(\"USD\")\n invalid_instance = valute_class(\"XYZ\")\n\n with patch(\"aiofiles.open\", side_effect=aiofiles_open_side_effect_factory(mock_files)), \\\n patch(\"pickle.loads\", return_value=mock_files[\"set_valutes\"]), \\\n patch(\"requests.get\") as mock_get:\n mock_response = MagicMock()\n mock_response.content = mock_files[\"xml_content\"]\n mock_get.return_value = mock_response\n\n result_valid = await valute_instance.correct_name()\n result_invalid = await invalid_instance.correct_name()\n\n assert result_valid is True, \"Expected True for valid currency\"\n assert result_invalid is False, \"Expected False for invalid currency\"\n\n@pytest.mark.asyncio\nasync def test_uses_aiofiles_open_exclusively(implementation, mock_files):\n \"\"\"Test that aiofiles.open is used instead of built-in open\"\"\"\n impl_name, module = implementation\n sys.modules[module.__name__].aiofiles = aiofiles\n\n valute_class = getattr(module, \"valute\")\n valute_instance = valute_class(\"USD\")\n\n with patch(\"aiofiles.open\", side_effect=aiofiles_open_side_effect_factory(mock_files)) as mock_aio_open, \\\n patch(\"builtins.open\") as mock_builtin_open, \\\n patch(\"pickle.loads\", return_value=mock_files[\"set_valutes\"]), \\\n patch(\"requests.get\") as mock_get:\n\n mock_response = MagicMock()\n mock_response.content = mock_files[\"xml_content\"]\n mock_get.return_value = mock_response\n\n await valute_instance.correct_name()\n\n # Assert aiofiles.open is used\n assert mock_aio_open.called, \"aiofiles.open should be used for file I/O\"\n # Assert regular open is not used\n assert not mock_builtin_open.called, \"Built-in open() should NOT be used in async method\"", "requirements": "aiofiles\naiohttp\npytest\npytest-asyncio\npytest-mock\nrequests", "conftest": "import pytest\nimport os\nimport sys\nimport json\nfrom typing import Dict, List, Optional, Any\n\n# Import from local test_utils.py in the same directory\nfrom test_utils import TestUtils, TestResultsManager\n\n# Load all implementations in the current sandbox\nimplementations = TestUtils.load_all_implementations()\ntest_results = TestResultsManager()\n\n@pytest.fixture(scope=\"session\")\ndef sandbox_dir():\n \"\"\"Fixture to provide the sandbox directory path.\"\"\"\n return os.path.dirname(os.path.abspath(__file__))\n\n@pytest.fixture(scope=\"session\")\ndef sandbox_name():\n \"\"\"Fixture to provide the sandbox name.\"\"\"\n return os.path.basename(os.path.dirname(os.path.abspath(__file__)))\n\n@pytest.fixture(scope=\"session\")\ndef all_implementations():\n \"\"\"Fixture to provide all implementations as a dictionary.\"\"\"\n return implementations\n\n@pytest.fixture(params=list(implementations.items()))\ndef implementation(request):\n \"\"\"Fixture to provide each implementation to tests one at a time.\"\"\"\n return request.param\n\n@pytest.fixture(scope=\"session\")\ndef results_manager():\n \"\"\"Fixture to provide access to the test results manager.\"\"\"\n return test_results\n\n# Hook for collecting test results\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n \"\"\"Pytest hook to collect test results.\"\"\"\n # Execute all other hooks to obtain the report object\n outcome = yield\n rep = outcome.get_result()\n \n # We're only interested in the call outcome\n if rep.when == \"call\":\n if hasattr(item, \"callspec\") and \"implementation\" in item.callspec.params:\n # Get implementation name and module\n impl_name, _ = item.callspec.params[\"implementation\"]\n \n # Get test name\n test_name = item.nodeid.split(\"::\")[-1]\n \n # Record result\n if rep.passed:\n test_results.record_result(impl_name, test_name, True)\n elif rep.failed:\n error_msg = str(rep.longrepr) if rep.longrepr else \"Test failed\"\n test_results.record_result(impl_name, test_name, False, error_msg)\n elif rep.skipped:\n skip_reason = rep.longrepr[2] if rep.longrepr else \"Test skipped\"\n test_results.record_skip(impl_name, test_name, skip_reason)\n\n# Hook to save results at the end of testing\n@pytest.hookimpl(trylast=True)\ndef pytest_sessionfinish(session, exitstatus):\n \"\"\"Save test results at the end of the test session.\"\"\"\n test_results.save_results()", "test_utils": "import os\nimport sys\nimport glob\nimport re\nimport importlib.util\nimport traceback\nimport types\nfrom typing import Dict, List, Optional, Any, Tuple\n\nclass TestUtils:\n @staticmethod\n def discover_implementation_files(directory: str = None) -> List[str]:\n \"\"\"Find all implementation files in the current sandbox directory.\"\"\"\n if directory is None:\n directory = os.path.dirname(os.path.abspath(__file__))\n \n patterns = [\n r'modified_code\\d+\\.py',\n r'new_code\\d+\\.py', \n # r'original_code\\.py',\n r'implementation\\d*\\.py'\n ]\n \n pattern = re.compile('|'.join(f'({p})' for p in patterns))\n implementations = []\n \n for file_path in glob.glob(os.path.join(directory, '*.py')):\n if pattern.search(os.path.basename(file_path)):\n implementations.append(file_path)\n \n # Sort files numerically\n def sort_key(path):\n filename = os.path.basename(path)\n match = re.search(r'(\\d+)', filename)\n return int(match.group(1)) if match else 0\n \n return sorted(implementations, key=sort_key)\n \n @staticmethod\n def create_mock_module(file_path: str, module_name: str, error_info: str) -> types.ModuleType:\n \"\"\"Create a mock module that contains error information but can still be tested.\"\"\"\n # Create a new module object\n mock_module = types.ModuleType(module_name)\n \n # Add basic attributes\n mock_module.__file__ = file_path\n mock_module.__name__ = module_name\n mock_module.__display_name__ = module_name\n mock_module.__error__ = error_info\n \n # Add a dummy function that can be detected by test functions\n def dummy_function(*args, **kwargs):\n return f\"Error in module: {error_info}\"\n \n setattr(mock_module, \"implementation_error\", dummy_function)\n \n return mock_module\n\n @staticmethod\n def load_module(file_path: str, module_name: Optional[str] = None) -> Any:\n \"\"\"\n Safely load a module from a file path with proper error handling.\n If the module has errors, return a mock module that can still be tested.\n \"\"\"\n if module_name is None:\n module_name = os.path.basename(file_path).replace('.py', '')\n \n # Create a unique module name to avoid conflicts\n sandbox_id = os.path.basename(os.path.dirname(file_path))\n unique_module_name = f\"{sandbox_id}_{module_name}\"\n \n try:\n # First, try to read the file to check for syntax errors\n with open(file_path, 'r') as f:\n source_code = f.read()\n \n # Check for syntax errors by compiling the code\n try:\n compiled = compile(source_code, file_path, 'exec')\n except SyntaxError as e:\n error_msg = f\"Syntax error: {str(e)}\"\n print(f\"Syntax error in {file_path}: {e}\")\n print(f\" Line {e.lineno}, column {e.offset}: {e.text}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n # Create the module spec\n spec = importlib.util.spec_from_file_location(unique_module_name, file_path)\n if spec is None or spec.loader is None:\n error_msg = f\"Could not create spec for {file_path}\"\n print(f\"Error: {error_msg}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n # Create the module object\n module = importlib.util.module_from_spec(spec)\n sys.modules[unique_module_name] = module\n \n # Special handling for execution errors\n try:\n # Execute the module code in a safe way\n spec.loader.exec_module(module)\n # Store the original name for reference\n module.__display_name__ = module_name\n return module\n except Exception as e:\n error_msg = f\"Runtime error: {str(e)}\"\n traceback_str = traceback.format_exc()\n print(f\"Error executing module {file_path}: {e}\")\n print(traceback_str)\n \n # Create a partial module that contains what we loaded before the error\n mock_module = TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n # Copy any attributes that might have been defined before the error\n for attr_name in dir(module):\n if not attr_name.startswith('__'):\n try:\n setattr(mock_module, attr_name, getattr(module, attr_name))\n except Exception:\n pass # Skip attributes that can't be copied\n \n return mock_module\n \n except FileNotFoundError as e:\n error_msg = f\"File not found: {str(e)}\"\n print(f\"Error: {error_msg}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n except Exception as e:\n error_msg = f\"Unexpected error: {str(e)}\"\n print(f\"Error loading module {file_path}: {e}\")\n return TestUtils.create_mock_module(file_path, unique_module_name, error_msg)\n \n @classmethod\n def load_all_implementations(cls, directory: str = None) -> Dict[str, Any]:\n \"\"\"Load all implementation files in the directory, including those with errors.\"\"\"\n if directory is None:\n directory = os.path.dirname(os.path.abspath(__file__))\n \n implementations = {}\n \n implementation_files = cls.discover_implementation_files(directory)\n if not implementation_files:\n print(\"WARNING: No implementation files found. Check your file naming patterns.\")\n \n for file_path in implementation_files:\n module_name = os.path.basename(file_path).replace('.py', '')\n module = cls.load_module(file_path, module_name)\n \n # Always add the module, even if it has errors\n implementations[module_name] = module\n \n if hasattr(module, '__error__'):\n print(f\"Loaded with errors: {module_name} - {module.__error__}\")\n else:\n print(f\"Successfully loaded: {module_name}\")\n \n return implementations\n\nclass TestResultsManager:\n def __init__(self):\n self.results = {}\n self.sandbox_name = os.path.basename(os.path.dirname(os.path.abspath(__file__)))\n \n def record_result(self, impl_name: str, test_name: str, passed: bool, \n error_msg: Optional[str] = None) -> None:\n \"\"\"Record a test result for an implementation.\"\"\"\n if impl_name not in self.results:\n self.results[impl_name] = {\"passed\": 0, \"failed\": 0, \"skipped\": 0, \"errors\": []}\n \n if passed:\n self.results[impl_name][\"passed\"] += 1\n else:\n self.results[impl_name][\"failed\"] += 1\n if error_msg:\n self.results[impl_name][\"errors\"].append({\n \"test\": test_name,\n \"error\": error_msg\n })\n \n def record_skip(self, impl_name: str, test_name: str, \n reason: Optional[str] = None) -> None:\n \"\"\"Record a skipped test for an implementation.\"\"\"\n if impl_name not in self.results:\n self.results[impl_name] = {\"passed\": 0, \"failed\": 0, \"skipped\": 0, \"errors\": []}\n \n self.results[impl_name][\"skipped\"] += 1\n if reason:\n self.results[impl_name][\"errors\"].append({\n \"test\": test_name,\n \"error\": f\"SKIPPED: {reason}\"\n })\n \n def get_winner(self) -> Tuple[Optional[int], Dict]:\n \"\"\"Determine the winner based on test results.\"\"\"\n winner = None\n max_passed = -1\n \n for impl_name, results in self.results.items():\n if impl_name == \"original_code\":\n continue # Skip original code when determining winner\n \n if results[\"passed\"] > max_passed:\n max_passed = results[\"passed\"]\n winner = impl_name\n # Break ties by looking at failure count\n elif results[\"passed\"] == max_passed and winner is not None:\n if results[\"failed\"] < self.results[winner][\"failed\"]:\n winner = impl_name\n \n # Convert winner to numeric index if possible\n winner_index = -1\n if winner and re.match(r'modified_code\\d+', winner):\n try:\n winner_index = int(re.search(r'(\\d+)', winner).group(1))\n except (AttributeError, ValueError):\n pass\n \n return winner_index, self.results\n \n def save_results(self, filename: str = \"test_results.json\") -> None:\n \"\"\"Save test results to a JSON file.\"\"\"\n import json\n \n winner_index, results = self.get_winner()\n \n # Check if all tests were skipped\n all_skipped = all(\n stats[\"skipped\"] == stats[\"passed\"] + stats[\"failed\"] + stats[\"skipped\"]\n for impl_name, stats in results.items()\n if impl_name != \"original_code\"\n )\n \n output = {\n \"winner\": winner_index,\n \"all_skipped\": all_skipped,\n \"results\": {\n name: {\n \"passed\": stats[\"passed\"],\n \"failed\": stats[\"failed\"],\n \"skipped\": stats[\"skipped\"],\n \"total\": stats[\"passed\"] + stats[\"failed\"] + stats[\"skipped\"]\n }\n for name, stats in results.items()\n if not name.startswith(\"_\") # Skip internal items\n }\n }\n \n with open(filename, \"w\") as f:\n json.dump(output, f, indent=2)\n \n print(f\"Test results saved to {filename}\")\n \n return output", "split": "test"} -{"problem_id": 105, "programming_language": "javascript", "original_code": "import { messages } from \"./messages.js\";\n\n$().ready(() => {\n const loading = $('.container-loading');\n const payment = $('.payment-section');\n const info = $('.user-info');\n const main = $('.main');\n\n\n// Retrieve values from localStorage\n const storedData = JSON.parse(localStorage.getItem('userData')) || {};\n const { userInfo, paymentInfo } = storedData;\n\n // Use the retrieved data as needed\n console.log('User Info:', userInfo);\n console.log('Payment Info:', paymentInfo);\n\n $('#generateTaxButton').click(() => {\n main.fadeOut(500);\n setTimeout(() => {\n loading.css('display', 'flex');\n\n let lastTimeout = 0;\n messages.forEach(message => {\n lastTimeout = lastTimeout + message.time;\n })\n console.log(`intervalo: ${lastTimeout}`)\n\n const loadMessages = $('#loading-messages');\n messages.forEach(element => {\n console.log(element.text)\n console.log(element.time)\n const timeout = element.time;\n setTimeout(() => {\n loadMessages.text(element.text);\n }, timeout);\n });\n\n setTimeout(() => {\n console.log('pagamento');\n loading.css('display', 'none');\n payment.css('display', 'block');\n info.css('display', 'block');\n }, lastTimeout + 500);\n }, 200);\n });\n});", "test_code": "/**\n * Test suite for jQuery implementations\n * \n * This suite evaluates implementations against two key criteria:\n * 1. Avoiding deprecated $.parseJSON method\n * 2. Using jQuery methods to manipulate data\n */\n\n// Import utilities from jest-setup.js\nconst {\n discoverImplementationFiles,\n countJQueryUsage,\n usesDeprecatedParseJSON,\n recordTestResult,\n originalJQueryCount\n} = require('../jest-setup');\n\n// =====================================================================\n// Main Test Suite\n// =====================================================================\n\ndescribe('jQuery Implementation Tests', () => {\n // Discover implementations\n const implementations = discoverImplementationFiles();\n \n // Log current implementation files\n console.log(\"Testing implementations:\", implementations.map(impl => impl.name).join(', '));\n \n // Test each implementation\n implementations.forEach(impl => {\n describe(`Implementation: ${impl.name}`, () => {\n \n // =====================================================================\n // Test 1: Deprecated Method Check\n // =====================================================================\n test('should not use deprecated $.parseJSON method', () => {\n // Direct source code analysis for $.parseJSON usage\n const usesDeprecated = usesDeprecatedParseJSON(impl.code);\n \n // Record test result\n recordTestResult(impl.name, 'avoids_deprecated_parseJSON', !usesDeprecated);\n \n // Test assertion - with descriptive error message\n if (usesDeprecated) {\n console.warn(`${impl.name} uses deprecated $.parseJSON method`);\n }\n \n expect(usesDeprecated).toBeFalsy();\n });\n \n // =====================================================================\n // Test 2: jQuery Data Manipulation Check\n // =====================================================================\n test('should use jQuery methods to manipulate data', () => {\n // Count jQuery usage in this implementation\n const jQueryUsageCount = countJQueryUsage(impl.code);\n \n // Implementation should have at least the same count of jQuery usage as original code\n // to demonstrate it's properly using jQuery for data manipulation\n const usesJQueryForData = jQueryUsageCount >= originalJQueryCount;\n \n // Also check for localStorage usage (since we want to ensure data is being used)\n const usesLocalStorage = impl.code.includes('localStorage.getItem') && \n (impl.code.includes('userInfo') || \n impl.code.includes('paymentInfo') ||\n impl.code.includes('userData'));\n \n // Log debugging information\n console.log(`${impl.name} jQuery usage: ${jQueryUsageCount} (original: ${originalJQueryCount}), Uses localStorage: ${usesLocalStorage}`);\n \n // Implementation passes if it uses jQuery at least as much as original and accesses localStorage\n const effectivelyUsesJQuery = usesJQueryForData && usesLocalStorage;\n \n recordTestResult(impl.name, 'uses_jquery_for_data', effectivelyUsesJQuery);\n \n // Test assertion\n expect(effectivelyUsesJQuery).toBeTruthy();\n });\n });\n });\n});", "highlighted_code": "// Retrieve values from localStorage\n const storedData = JSON.parse(localStorage.getItem('userData')) || {};\n const { userInfo, paymentInfo } = storedData;\n\n // Use the retrieved data as needed\n console.log('User Info:', userInfo);\n console.log('Payment Info:', paymentInfo);", "instruction": "with jquerry", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\",\n \"@babel/core\": \"^7.21.4\",\n \"@babel/preset-env\": \"^7.21.4\",\n \"babel-jest\": \"^29.7.0\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"/jest-setup.js\"],\n \"testEnvironment\": \"node\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"collectCoverage\": false,\n \"moduleNameMapper\": {\n \"\\\\./messages\\\\.js\": \"/__mocks__/messages.js\"\n },\n \"transform\": {\n \"^.+\\\\.jsx?$\": \"babel-jest\"\n },\n \"transformIgnorePatterns\": [\n \"/node_modules/\",\n \"tagged_code.js\",\n \"highlighted_code.js\"\n ]\n }\n}", "jest_setup": "/**\n * Jest setup file for jQuery implementations tests\n */\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n// =====================================================================\n// Test Utilities\n// =====================================================================\n\n/**\n * Discovers implementation files to test based on naming patterns\n * @returns {Array} Array of implementation objects with name, path, and code\n */\nfunction discoverImplementationFiles() {\n const patterns = [\n 'modified_code\\\\d+\\\\.js',\n 'new_code\\\\d+\\\\.js',\n 'original_modified_code\\\\d+\\\\.js'\n ];\n \n const regexPattern = new RegExp(patterns.join('|'));\n const files = glob.sync(path.join(__dirname, '*.js'));\n \n return files\n .filter(filePath => regexPattern.test(path.basename(filePath)))\n .map(filePath => ({\n name: path.basename(filePath, '.js'),\n path: filePath,\n code: fs.readFileSync(filePath, 'utf8')\n }));\n}\n\n/**\n * Test result tracking system\n */\nconst testResults = {};\nconst testTracking = {}; // Track which tests have been run for each implementation\n\n/**\n * Records test results for a specific implementation\n * @param {string} implementation - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n */\nfunction recordTestResult(implementation, testName, passed) {\n // Initialize implementation results if needed\n if (!testResults[implementation]) {\n testResults[implementation] = { passed: 0, failed: 0, skipped: 0, total: 0 };\n testTracking[implementation] = new Set();\n }\n \n // Check if this test has already been recorded for this implementation\n const testKey = `${testName}`;\n if (testTracking[implementation].has(testKey)) {\n return; // Skip recording duplicate test results\n }\n \n // Mark this test as recorded\n testTracking[implementation].add(testKey);\n \n // Update test counts\n if (passed) {\n testResults[implementation].passed++;\n } else {\n testResults[implementation].failed++;\n }\n \n testResults[implementation].total = \n testResults[implementation].passed + \n testResults[implementation].failed + \n testResults[implementation].skipped;\n}\n\n/**\n * Determines the winner based on test results\n * @returns {number} The winner index or -1 if no winner\n */\nfunction determineWinner() {\n let winner = null;\n let maxPassed = -1;\n let minFailed = Number.MAX_SAFE_INTEGER;\n \n for (const implName in testResults) {\n // Skip original implementations\n if (implName.startsWith('original_')) {\n continue;\n }\n \n const results = testResults[implName];\n \n if (results.passed > maxPassed || \n (results.passed === maxPassed && results.failed < minFailed)) {\n maxPassed = results.passed;\n minFailed = results.failed;\n winner = implName;\n }\n }\n \n // Convert winner to numeric index\n let winnerIndex = -1;\n if (winner) {\n if (winner.startsWith('modified_code')) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1], 10);\n }\n } else if (winner.startsWith('new_code')) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1], 10);\n }\n }\n }\n \n return winnerIndex;\n}\n\n/**\n * Saves test results to JSON file\n * @returns {Object} The test results object\n */\nfunction saveTestResults() {\n const winnerIndex = determineWinner();\n \n const output = {\n winner: winnerIndex,\n all_skipped: false,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(testResults)) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.total\n };\n }\n \n const outputPath = path.join(__dirname, 'test_results.json');\n fs.writeFileSync(outputPath, JSON.stringify(output, null, 2));\n console.log(`Test results saved to test_results.json`);\n \n return output;\n}\n\n/**\n * Counts jQuery usage patterns in code\n * @param {string} code - Source code to analyze\n * @returns {number} Count of jQuery usage patterns\n */\nfunction countJQueryUsage(code) {\n // Count occurrences of $ usage\n // This includes $(selectors), $.method, $(document).ready, etc.\n const dollarSignCount = (code.match(/\\$/g) || []).length;\n \n // Count occurrences of jQuery usage if it's used instead of $\n const jQueryCount = (code.match(/jQuery/g) || []).length;\n \n return dollarSignCount + jQueryCount;\n}\n\n/**\n * Checks if code uses deprecated $.parseJSON method\n * @param {string} code - Source code to analyze\n * @returns {boolean} Whether code uses deprecated $.parseJSON\n */\nfunction usesDeprecatedParseJSON(code) {\n // Look for the exact pattern $.parseJSON or jQuery.parseJSON with proper boundary checks\n const parseJSONPattern = /(\\$|jQuery)\\.parseJSON\\s*\\(/;\n return parseJSONPattern.test(code);\n}\n\n// Load original code for comparison\nconst originalCodePath = path.join(__dirname, 'original_code.js');\nconst originalCode = fs.readFileSync(originalCodePath, 'utf8');\nconst originalJQueryCount = countJQueryUsage(originalCode);\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = {\n discoverImplementationFiles,\n countJQueryUsage,\n usesDeprecatedParseJSON\n };\n global.__TEST_RESULTS__ = {\n testResults,\n testTracking,\n recordTestResult,\n determineWinner, \n saveTestResults\n };\n global.__JQUERY_DATA__ = {\n originalCode,\n originalJQueryCount\n };\n});\n\n// After all tests run, save the results\nafterAll(() => {\n // Display final results before saving\n console.log(\"\\nFinal Test Results:\");\n for (const [name, stats] of Object.entries(testResults)) {\n console.log(`${name}: ${stats.passed} passes, ${stats.failed} fails (total: ${stats.total})`);\n }\n \n const results = saveTestResults();\n console.log(`Winner: ${results.winner !== undefined ? results.winner : 'None'}`);\n});\n\n// Export for use in tests\nmodule.exports = {\n discoverImplementationFiles,\n countJQueryUsage,\n usesDeprecatedParseJSON,\n recordTestResult,\n determineWinner,\n saveTestResults,\n testResults,\n originalJQueryCount\n};", "babel_config": "module.exports = {\n presets: [\n ['@babel/preset-env', {targets: {node: 'current'}}]\n ]\n};", "other_files": {"hidden.js": "import { messages } from \"./messages.js\";\n\n$(() => {\n const $loading = $('.container-loading');\n const $payment = $('.payment-section');\n const $info = $('.user-info');\n const $main = $('.main');\n const $loadMessages = $('#loading-messages');\n\n // Retrieve and display user data using jQuery\n const storedData = JSON.parse(localStorage.getItem('userData')) || {};\n const { userInfo, paymentInfo } = storedData;\n\n console.log('User Info:', userInfo);\n console.log('Payment Info:', paymentInfo);\n\n if (userInfo) {\n $('.user-name').text(userInfo.name || '');\n $('.user-email').text(userInfo.email || '');\n }\n\n if (paymentInfo) {\n $('.payment-amount').text(`$${paymentInfo.amount || '0.00'}`);\n $('.payment-date').text(paymentInfo.date || '');\n }\n\n $('#generateTaxButton').on('click', () => {\n $main.fadeOut(500, () => {\n $loading.css('display', 'flex');\n\n let lastTimeout = 0;\n messages.forEach(msg => {\n lastTimeout += msg.time;\n });\n\n messages.forEach(msg => {\n setTimeout(() => {\n $loadMessages.text(msg.text);\n }, msg.time);\n });\n\n setTimeout(() => {\n $loading.hide();\n $payment.show();\n $info.show();\n }, lastTimeout + 500);\n });\n });\n});\n", "__mocks__/messages.js": "// Mock for messages.js\nexport const messages = [\n { text: \"Loading data...\", time: 1000 },\n { text: \"Processing information...\", time: 2000 },\n { text: \"Calculating taxes...\", time: 3000 },\n { text: \"Finalizing results...\", time: 1500 }\n];", "__mocks__/jquery.js": "// jQuery mock\nconst elementCache = {};\nconst clickHandlers = {};\n\nconst jquery = function(selector) {\n // Cache elements to ensure the same mock instance is returned for the same selector\n if (!elementCache[selector]) {\n elementCache[selector] = {\n selector,\n ready: function(callback) {\n if (typeof callback === 'function') {\n // Store the callback for later execution\n if (!jquery.readyCallbacks) {\n jquery.readyCallbacks = [];\n }\n jquery.readyCallbacks.push(callback);\n }\n return this;\n },\n text: jest.fn(function(value) {\n if (value !== undefined) {\n this.textValue = value;\n return this;\n }\n return this.textValue || '';\n }),\n css: jest.fn(function(prop, value) {\n if (!this.cssProps) this.cssProps = {};\n this.cssProps[prop] = value;\n return this;\n }),\n fadeOut: jest.fn(function(duration) {\n return this;\n }),\n fadeIn: jest.fn(function(duration) {\n return this;\n }),\n click: function(callback) {\n clickHandlers[selector] = callback;\n return this;\n },\n // Method to trigger the click handler\n triggerClick: function() {\n if (typeof clickHandlers[selector] === 'function') {\n clickHandlers[selector]();\n }\n return this;\n }\n };\n }\n\n return elementCache[selector];\n};\n\n// Helper to execute all ready callbacks\njquery.executeReady = function() {\n if (jquery.readyCallbacks) {\n jquery.readyCallbacks.forEach(callback => {\n try {\n callback();\n } catch (e) {\n console.error('Error in ready callback:', e);\n }\n });\n }\n};\n\n// Extend $ with utility methods\njquery.each = jest.fn((obj, callback) => {\n if (obj && typeof callback === 'function') {\n Object.entries(obj).forEach(([key, value]) => {\n callback(key, value);\n });\n }\n});\n\njquery.parseJSON = jest.fn((data) => {\n // This method is deprecated in jQuery - this should cause a test failure\n try {\n return JSON.parse(data);\n } catch (e) {\n throw new Error('Invalid JSON');\n }\n});\n\n// Reset mock function to clear counters\njquery.resetMocks = function() {\n Object.values(elementCache).forEach(el => {\n if (el.text && el.text.mockClear) el.text.mockClear();\n if (el.css && el.css.mockClear) el.css.mockClear();\n if (el.fadeOut && el.fadeOut.mockClear) el.fadeOut.mockClear();\n if (el.fadeIn && el.fadeIn.mockClear) el.fadeIn.mockClear();\n });\n\n jquery.each.mockClear();\n jquery.parseJSON.mockClear();\n};\n\n// Set global $ variable\nglobal.$ = jquery;\n\n// Export both as default and as named export\nmodule.exports = jquery;", ".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(mkdir:*)\",\n \"Bash(npm install:*)\",\n \"Bash(npm test)\",\n \"Bash(ls:*)\",\n \"Bash(grep:*)\",\n \"Bash(rm:*)\"\n ],\n \"deny\": []\n }\n}"}, "split": "test"} -{"problem_id": 106, "programming_language": "javascript", "original_code": "import React, { useEffect, useState, useCallback } from 'react';\nimport styles from './GameUI.module.css';\nimport { useLocation } from 'react-router-dom';\nimport CharacterStatUI from '../character-stat-ui/CharacterStatUI';\nimport Sprite from '../sprite/Sprite';\nimport GameMap from '../game-map/GameMap';\nimport { characterData } from '../character-data/CharacterData';\nimport MapCharacter from '../map-character/MapCharacter';\n\nconst publicFolder = `${process.env.PUBLIC_URL}`;\n\nconst GameUI = () => {\n const location = useLocation();\n const frontPageState = location.state || {};\n const character = frontPageState.character; \n const map = frontPageState.map;\n // UPDATE UI STATES\n\n // Default UI states\n const [characterUIState, setCharacterUIState] = useState({}); \n const [mapState, setMapState] = useState({});\n const [clickedState, setClickedState] = useState(null);\n const [selectedCharacter, setSelectedCharacter] = useState(\"Alfonse\");\n\n const characterNames = [\"Alfonse\",\"Sharena\",\"Anna\",\"Fjorm\"];\n\n const [characters, setCharacters] = useState([\n for (let i = 0; i < characterNames.length; i++) {\n characterNames[i]: characterData(characterName)\n }\n ],[characterNames]); \n\n const mapSetup = useCallback(() => {\n if (!map) {\n return {}; \n }\n\n const name = map.name || '';\n const imageUrl = map.image ? `${publicFolder}${map.image}` : `${process.env.PUBLIC_URL}/assets/images/map/Map_S0001.jpg`;\n return { name, imageUrl };\n }, [map]);\n\n useEffect(() => {\n setMapState(mapSetup());\n }, [map, mapSetup]); \n useEffect(() => {\n if (selectedCharacter) { \n const selectedCharData = characterData(selectedCharacter);\n\n setCharacterUIState({\n charName : selectedCharacter,\n level : selectedCharData.level,\n wpn : selectedCharData.wpn,\n hp : selectedCharData.hp,\n atk : selectedCharData.atk,\n spd : selectedCharData.spd,\n def : selectedCharData.def,\n res : selectedCharData.res\n });\n }\n }, [selectedCharacter, setCharacterUIState]);\n\n // Update UI State after click\n const handleGridClick = useCallback((gridX, gridY) => {\n console.log(`Grid clicked at X: ${gridX}, Y: ${gridY}`);\n setClickedState({ gridX, gridY });\n }, [setClickedState, clickedState]);\n\n return (\n
\n
\n \n
\n \n
\n {characterNames.map((characterName) => (\n \n ))}\n
\n
\n
\n \n \n \n \n \n \n \n \n \n
\n
\n \n \n \n \n \n \n
\n
\n
\n
\n
\n );\n};\n\nexport default GameUI;\n", "test_code": "const fs = require('fs');\nconst path = require('path');\nconst { resultsManager } = require('../jest-setup');\n\n/**\n * A focused test that executes the character data mapping and validates the structure\n */\ndescribe('GameUI Character Data Mapping Tests', () => {\n // Clear existing test results to make sure we only include our tested files\n resultsManager.results = {};\n\n // Define exactly which patterns we want to test - no more, no less\n const codePatterns = [\n /^original_code\\.jsx?$/,\n /^modified_code\\d+\\.jsx?$/,\n /^new_code\\d+\\.jsx?$/,\n /^original_modified_code\\d+\\.jsx?$/\n ];\n\n // Get implementation files, with precise filtering\n const files = fs.readdirSync(path.join(__dirname, '..'))\n .filter(file => {\n // Only include files matching our specific patterns\n return codePatterns.some(pattern => pattern.test(file));\n });\n\n test('All implementations correctly map character data', () => {\n files.forEach(fileName => {\n const filePath = path.join(__dirname, '..', fileName);\n const implName = fileName.replace(/\\.(js|jsx)$/, '');\n const content = fs.readFileSync(filePath, 'utf8');\n\n try {\n // Extract the character mapping code and test it\n const charMappingResult = testCharacterMapping(content);\n\n // Record test results\n resultsManager.recordResult(implName, 'compilesSuccessfully', true);\n resultsManager.recordResult(implName, 'characterDataStructure',\n charMappingResult.valid,\n charMappingResult.valid ? null : charMappingResult.reason);\n } catch (error) {\n // If we can't extract or run the character mapping code,\n // log the issue but mark it as passed since we don't want to fail due to extraction issues\n resultsManager.recordResult(implName, 'compilesSuccessfully', false);\n resultsManager.recordResult(implName, 'characterDataStructure', false);\n }\n });\n });\n \n /**\n * Extract and test character data mapping from the component\n */\n function testCharacterMapping(code) {\n try {\n // Extract the useState call for characters\n const useStateMatch = code.match(/const\\s+\\[\\s*characters\\s*,\\s*setCharacters\\s*\\]\\s*=\\s*useState\\s*\\(([^;]*)\\)/s);\n \n if (!useStateMatch || !useStateMatch[1]) {\n // If we can't find the useState call, then fail\n return { valid: false, reason: null };\n }\n \n // Set up test environment with character data\n const characterNames = [\"Alfonse\", \"Sharena\", \"Anna\", \"Fjorm\"];\n \n const characterData = (name) => ({\n level: 40,\n wpn: 'TestWeapon',\n hp: 40,\n atk: 30,\n spd: 25,\n def: 20,\n res: 20\n });\n \n // Execute the useState initialization code\n let result;\n const execCode = useStateMatch[1].trim();\n \n // If it's a function, we need to execute it\n if (execCode.startsWith('() =>') || execCode.startsWith('function')) {\n const funcBody = new Function('characterNames', 'characterData', `\n return ${execCode.replace(/^\\(\\)\\s*=>\\s*/, '')};\n `);\n result = funcBody(characterNames, characterData);\n } else {\n // Otherwise, execute it directly\n const directExec = new Function('characterNames', 'characterData', `\n return ${execCode};\n `);\n result = directExec(characterNames, characterData);\n }\n \n // Validate the character data structure\n if (!result) {\n return { valid: false, reason: 'Character data is null or undefined' };\n }\n \n // Only accept object format with character names as keys\n if (Array.isArray(result)) {\n // Array format is incorrect\n return {\n valid: false,\n reason: 'Array format is incorrect. Must use object with character names as keys.'\n };\n }\n else if (typeof result === 'object') {\n // Object with character names as keys is the only valid format\n const hasValidKeys = Object.keys(result).some(key =>\n characterNames.includes(key) &&\n result[key] && typeof result[key] === 'object'\n );\n\n if (hasValidKeys) {\n return { valid: true, reason: null };\n }\n\n return {\n valid: false,\n reason: 'Object format does not use character names as keys with data values'\n };\n }\n \n // If we got here, it's not a valid format\n return { \n valid: false, \n reason: 'Not a valid character data structure (neither array nor object)' \n };\n } catch (error) {\n // If there's an error executing the code, it might be a syntax issue\n // in the extraction process, not the actual code, so we pass it\n return { valid: true, reason: null };\n }\n }\n});", "highlighted_code": " const [characters, setCharacters] = useState([\n for (let i = 0; i < characterNames.length; i++) {\n characterNames[i]: characterData(characterName)\n }\n ],[characterNames]); ", "instruction": "Please fix this error: 'Line 28:4: Parsing error: Unexpected token (28:4)'", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.27.1\",\n \"@babel/preset-env\": \"^7.27.2\",\n \"@babel/preset-react\": \"^7.27.1\",\n \"@testing-library/jest-dom\": \"^5.16.5\",\n \"@testing-library/react\": \"^14.0.0\",\n \"babel-core\": \"^6.26.3\",\n \"babel-jest\": \"^29.5.0\",\n \"glob\": \"^10.3.10\",\n \"jest\": \"^29.7.0\",\n \"jest-environment-jsdom\": \"^29.5.0\",\n \"jsdom\": \"^26.1.0\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-router-dom\": \"^6.13.0\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\n \"./jest-setup.js\"\n ],\n \"testEnvironment\": \"jsdom\",\n \"testMatch\": [\n \"**/tests/**/*.test.js\"\n ],\n \"verbose\": true,\n \"moduleNameMapper\": {\n \"\\\\.(css|less|scss|sass)$\": \"/__mocks__/styleMock.js\"\n },\n \"transform\": {\n \"^.+\\\\.(js|jsx)$\": \"babel-jest\"\n }\n }\n}\n", "jest_setup": "// jest-setup.js - Copy this file to each implementation folder\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\nconst { TextEncoder, TextDecoder } = require('util');\nglobal.TextEncoder = TextEncoder;\nglobal.TextDecoder = TextDecoder;\n\n// Import @testing-library/jest-dom\nrequire('@testing-library/jest-dom');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'original_code\\\\.jsx?',\n 'original_modified_code\\\\d+\\\\.jsx?',\n 'modified_code\\\\d+\\\\.jsx?',\n 'new_code\\\\d+\\\\.jsx?',\n 'implementation\\\\d*\\\\.jsx?'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.{js,jsx}'));\n\n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript or JSX file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n\n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n\n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: [], // Track errors in the module\n __source__: sourceCode // Store source code for testing\n };\n\n // For JSX files, we don't do syntax checking as it would require a full JSX parser\n if (!filePath.endsWith('.jsx')) {\n try {\n // Try to test-compile the code to check for syntax errors (only for .js files)\n new Function(sourceCode);\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n console.error(` Line ${e.lineNumber}, column ${e.columnNumber}`);\n\n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.lineNumber,\n columnNumber: e.columnNumber\n });\n }\n }\n \n try {\n // Try to require the module even if there were syntax errors\n // This may or may not succeed\n delete require.cache[require.resolve(filePath)];\n const loadedModule = require(filePath);\n \n // Copy all properties from the loaded module\n for (const key in loadedModule) {\n if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {\n moduleObj[key] = loadedModule[key];\n }\n }\n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n console.error(e.stack);\n \n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n \n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n \n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n \n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n \n const implementations = {};\n \n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n \n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace('.js', '');\n const module = this.loadModule(filePath, moduleName);\n \n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n \n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n \n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n \n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n \n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n \n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner && /modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n \n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n \n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n \n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n \n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n \n return output;\n }\n}\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n implementations,\n resultsManager\n};", "babel_config": "module.exports = {\n presets: [\n '@babel/preset-env',\n ['@babel/preset-react', { runtime: 'automatic' }],\n ],\n};", "other_files": {"__mocks__/MapCharacter.jsx": "import React from 'react';\n\nconst MapCharacter = ({ character }) => (\n
\n {character}\n
\n);\n\nexport default MapCharacter;", "__mocks__/Sprite.jsx": "import React from 'react';\n\nconst Sprite = ({ spriteName, children }) => (\n
\n {children}\n
\n);\n\nexport default Sprite;", "__mocks__/GameMap.jsx": "import React from 'react';\n\nconst GameMap = (props) => (\n
props.onGridClick && props.onGridClick(1, 1)}>\n Game Map\n
\n);\n\nexport default GameMap;", "__mocks__/CharacterStatUI.jsx": "import React from 'react';\n\nconst CharacterStatUI = (props) => (\n
\n {props.charName}\n {props.level}\n {props.wpn}\n {props.hp}\n {props.atk}\n {props.spd}\n {props.def}\n {props.res}\n
\n);\n\nexport default CharacterStatUI;", "__mocks__/CharacterData.js": "export const characterData = (characterName) => {\n return {\n name: characterName,\n level: 10,\n wpn: 'Weapon',\n hp: 100,\n atk: 50,\n spd: 25,\n def: 30,\n res: 20\n };\n};", "__mocks__/react-router-dom.js": "const React = require('react');\n\nconst useLocation = jest.fn().mockReturnValue({\n state: {\n character: 'Alfonse',\n map: {\n name: 'Test Map',\n image: '/test-map.jpg'\n }\n }\n});\n\nmodule.exports = {\n useLocation,\n MemoryRouter: ({ children }) => React.createElement('div', null, children)\n};", "__mocks__/styleMock.js": "module.exports = {};", ".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(mkdir:*)\",\n \"Bash(npm install:*)\",\n \"Bash(npm test)\",\n \"Bash(npx jest:*)\",\n \"Bash(rm:*)\",\n \"Bash(cat:*)\"\n ],\n \"deny\": []\n }\n}", "__mocks__/character-stat-ui/CharacterStatUI.jsx": "// Mock component for the CharacterStatUI\nconst CharacterStatUI = ({ character }) => {\n return null;\n};\n\nexport default CharacterStatUI;"}, "split": "test"} -{"problem_id": 107, "programming_language": "javascript", "original_code": "import { useState, useEffect, useCallback, useMemo } from 'react';\n\nfunction useDashboardData(user) {\n const [data, setData] = useState({\n customerData: { summary: null, loading: false, customers: [] },\n healthData: [],\n websiteStatus: { checking: false },\n stripeApiKey: \"\",\n dateRange: {\n startDate: (() => {\n const date = new Date();\n date.setFullYear(date.getFullYear() - 1);\n return new Date(date);\n })(),\n endDate: new Date(),\n }\n });\n\n const calculateHealthData = useCallback(() => {\n if (!data.customerData.summary?.customers) return [];\n const months = [];\n const currentDate = new Date(data.dateRange.startDate);\n \n while (currentDate <= data.dateRange.endDate) {\n months.push({\n month: currentDate.toLocaleString(\"default\", { month: \"short\" }),\n year: currentDate.getFullYear(),\n });\n currentDate.setMonth(currentDate.getMonth() + 1);\n }\n\n return months.map(({ month, year }) => {\n const monthYear = `${month} ${year}`;\n const monthCustomers = data.customerData.summary.customers.filter(customer => {\n const customerDate = new Date(customer.created);\n return customerDate.getMonth() === new Date(`${year}-${month}-01`).getMonth() &&\n customerDate.getFullYear() === year;\n });\n\n return {\n monthYear,\n healthy: monthCustomers.filter(c => c.status === \"active\").length,\n warning: monthCustomers.filter(c => c.status === \"churned\").length,\n critical: monthCustomers.filter(c => c.status === \"delinquent\").length,\n };\n });\n }, [data.customerData.summary, data.dateRange]);\n\n const loadSettings = useCallback(async () => {\n if (!user?.id || data.customerData.summary) return;\n if (!user?.id || data.stripeApiKey) return;\n try {\n const response = await fetch(\"/api/db/churnary_user_settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n query: \"SELECT stripe_api_key FROM `user_settings` WHERE `user_id` = ? LIMIT 1\",\n values: [user.id],\n }),\n });\n \n if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);\n const settings = await response.json();\n \n setData(prev => ({ \n ...prev, \n stripeApiKey: settings[0]?.stripe_api_key || \"\" \n }));\n } catch (error) {\n setData(prev => ({ ...prev, error: \"Failed to load user settings\" }));\n }\n }, [user?.id]);\n\n const loadData = useCallback(async () => {\n if (!user?.id) return;\n\n if (!data.stripeApiKey || !user?.id) return;\n\n setData(prev => ({ ...prev, customerData: { ...prev.customerData, loading: true }}));\n\n try {\n setData(prev => ({ \n ...prev, \n customerData: { ...prev.customerData, loading: true },\n error: null \n }));\n\n const response = await fetch(\"/api/stripe-customer-summary\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ userId: user.id }),\n });\n\n if (!response.ok) throw new Error(\"Failed to fetch customer summary\");\n const summary = await response.json();\n if (summary.error) throw new Error(summary.error);\n\n setData(prev => ({\n ...prev,\n customerData: { \n summary, \n loading: false,\n customers: summary.customers \n },\n healthData: calculateHealthData()\n }));\n } catch (error) {\n setData(prev => ({\n ...prev,\n customerData: { ...prev.customerData, loading: false },\n error: error.message\n }));\n }\n }, [user?.id, data.stripeApiKey, calculateHealthData]);\n\n const actions = useMemo(() => ({\n checkWebsites: async () => {\n if (!data.customerData.summary?.customers?.length || !data.customerData.customers) return;\n \n setData(prev => ({ \n ...prev, \n websiteStatus: { checking: true },\n error: null \n }));\n\n try {\n const updatedCustomers = await Promise.all(\n data.customerData.customers.map(async (customer) => {\n const response = await fetch(\"/api/website-churn-detector\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ websiteUrl: customer.website }),\n });\n const health = await response.json();\n return { ...customer, health, status: health.status === \"active\" ? \"active\" : \"churned\" };\n })\n );\n\n const summary = {\n ...data.customerData.summary,\n customers: updatedCustomers,\n active: updatedCustomers.filter(c => c.status === \"active\").length,\n churned: updatedCustomers.filter(c => c.status === \"churned\").length,\n };\n\n setData(prev => ({\n ...prev,\n customerData: { ...prev.customerData, summary },\n healthData: calculateHealthData(),\n websiteStatus: { checking: false }\n }));\n } catch (err) {\n setData(prev => ({\n ...prev,\n websiteStatus: { checking: false },\n error: \"Failed to check websites. Please try again.\"\n }));\n }\n },\n \n setDateRange: (range) => {\n if (range.startDate > range.endDate) {\n setData(prev => ({ ...prev, error: \"Start date cannot be after end date\" }));\n return;\n }\n setData(prev => ({ ...prev, dateRange: range, error: null }));\n },\n\n clearError: () => {\n setData(prev => ({ ...prev, error: null }));\n }\n }), [data.customerData.summary, calculateHealthData]);\n\n useEffect(() => {\n loadSettings();\n }, [loadSettings, user?.id]);\n\n useEffect(() => {\n loadData();\n }, [loadData, user?.id, data.stripeApiKey]);\n\n useEffect(() => {\n loadData();\n }, [loadData]);\n\n return { \n data, \n actions,\n isLoading: data.customerData.loading || data.websiteStatus.checking \n };\n}\n\nexport default useDashboardData;", "test_code": "// Performance tester for useDashboardData implementations\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\nconst { performance } = require('perf_hooks');\nconst vm = require('vm');\nconst babel = require('@babel/core');\nconst React = require('react');\n\n// Mock React hooks for performance testing\nconst mockReactHooks = {\n useState: initialState => {\n let state = initialState;\n const setState = newState => {\n if (typeof newState === 'function') {\n state = newState(state);\n } else {\n state = newState;\n }\n return state;\n };\n return [state, setState];\n },\n useEffect: (effect, deps) => {\n try { effect(); } catch (e) { /* Ignore errors in effects */ }\n },\n useCallback: (callback, deps) => callback,\n useMemo: (factory, deps) => factory()\n};\n\n// Mock fetch for API calls\nglobal.fetch = async (url, options) => {\n if (url === '/api/db/churnary_user_settings') {\n return {\n ok: true,\n json: async () => [{ stripe_api_key: 'mock_stripe_key' }]\n };\n }\n \n if (url === '/api/stripe-customer-summary') {\n // Large dataset will be created dynamically in the test\n return {\n ok: true,\n json: async () => ({ \n customers: [], // Placeholder, will be populated in test\n active: 0,\n churned: 0,\n delinquent: 0\n })\n };\n }\n \n if (url === '/api/website-churn-detector') {\n return {\n ok: true,\n json: async () => ({ status: 'active' })\n };\n }\n \n return { ok: false, json: async () => ({ error: 'Not found' }) };\n};\n\n// Find all implementation files\nfunction findImplementations() {\n // Find all JSX files in the directory - will find original_code, modified_code*, new_code*, etc.\n const jsxFiles = glob.sync(path.join(__dirname, '..', '*.jsx'));\n\n console.log('Finding implementations for performance testing:');\n const implementations = [];\n\n // First, log all available JSX files\n console.log('Available JSX files:');\n jsxFiles.forEach(file => {\n console.log(`- ${path.basename(file)}`);\n });\n console.log('');\n\n // Now process and validate each file\n jsxFiles.forEach(file => {\n const fileName = path.basename(file);\n const content = fs.readFileSync(file, 'utf8');\n\n // Check if the implementation is complete and has necessary exports\n const hasDefaultExport = content.includes('export default');\n const hasReturnStatement = content.includes('return {');\n const isComplete = hasDefaultExport && hasReturnStatement;\n\n if (isComplete) {\n implementations.push({\n name: fileName.replace('.jsx', ''),\n path: file,\n content\n });\n console.log(`\u2713 ${fileName} - Valid implementation`);\n } else {\n console.log(`\u2717 ${fileName} - Invalid or incomplete implementation`);\n\n // Debug what's missing\n if (!hasDefaultExport) console.log(` - Missing 'export default'`);\n if (!hasReturnStatement) console.log(` - Missing 'return {' statement`);\n\n // For incomplete implementations, still add them with a flag\n implementations.push({\n name: fileName.replace('.jsx', ''),\n path: file,\n content,\n incomplete: true\n });\n }\n });\n\n console.log(`\\nTotal: ${jsxFiles.length} JSX files, ${implementations.filter(i => !i.incomplete).length} valid implementations\\n`);\n\n return implementations;\n}\n\n// Transpile and prepare code for execution\nfunction prepareCode(content) {\n // Replace React imports with mocks\n const codeWithMocks = content.replace(\n /import\\s*{\\s*(useState|useEffect|useCallback|useMemo)[^}]*}\\s*from\\s*['\"]react['\"];?/g, \n '// React imports are mocked'\n );\n \n // Transpile JSX\n const { code } = babel.transformSync(codeWithMocks, {\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' } }],\n ['@babel/preset-react', { runtime: 'automatic' }]\n ]\n });\n \n return code;\n}\n\n// Test data with extreme scale - 10 million customers\nconst DATASET_SIZE = 10000000;\n\n// Create test data more efficiently for large datasets\nfunction createTestData(size) {\n // For very large datasets, create only the needed structure\n return {\n user: { id: 'user123' },\n customerData: {\n summary: {\n customers: Array.from({ length: size }, (_, i) => ({\n id: `cust_${i % 10000}`, // Reuse IDs to save memory\n status: ['active', 'churned', 'delinquent'][i % 3],\n created: new Date(2022, i % 12, i % 28 + 1).toISOString(),\n website: `example${i % 1000}.com` // Reuse domains to save memory\n })),\n active: Math.floor(size/3),\n churned: Math.floor(size/3),\n delinquent: size - 2 * Math.floor(size/3)\n }\n }\n };\n}\n\n// Performance timing with warmup and multiple iterations\nasync function runTimedOperation(operation, iterations = 10) {\n // Warmup runs to avoid JIT compilation bias\n for (let i = 0; i < 3; i++) {\n await operation();\n }\n \n // Timed runs\n const times = [];\n const startTime = Date.now();\n const TIMEOUT_MS = 60000; // 1 minute timeout\n\n for (let i = 0; i < iterations; i++) {\n // Check if we've exceeded the total timeout\n if (Date.now() - startTime > TIMEOUT_MS) {\n throw new Error(`Operation timed out after ${TIMEOUT_MS/1000} seconds`);\n }\n\n const start = performance.now();\n await operation();\n const end = performance.now();\n times.push(end - start);\n }\n \n // Calculate statistics\n return {\n avg: times.reduce((sum, time) => sum + time, 0) / times.length,\n min: Math.min(...times),\n max: Math.max(...times)\n };\n}\n\n// Benchmark a single implementation\nasync function benchmarkImplementation(implementation) {\n try {\n console.log(`\\nTesting ${implementation.name}...`);\n const code = prepareCode(implementation.content);\n \n // Create sandbox with mocks\n const context = {\n React,\n useState: mockReactHooks.useState,\n useEffect: mockReactHooks.useEffect,\n useCallback: mockReactHooks.useCallback,\n useMemo: mockReactHooks.useMemo,\n fetch: global.fetch,\n console: console,\n setTimeout: setTimeout,\n clearTimeout: clearTimeout,\n Promise: Promise,\n Date: Date,\n Math: Math,\n Object: Object,\n Array: Array,\n Map: Map,\n Set: Set,\n exports: {},\n module: { exports: {} }\n };\n \n // Execute in sandbox\n vm.createContext(context);\n vm.runInContext(code, context);\n \n // Get the hook function\n const useDashboardData = context.module.exports.default || context.exports.default;\n \n if (!useDashboardData || typeof useDashboardData !== 'function') {\n return {\n name: implementation.name,\n success: false,\n error: 'No useDashboardData function exported'\n };\n }\n \n // Results object\n const results = {\n name: implementation.name,\n success: true,\n metrics: {}\n };\n \n // Test with 10 million customer dataset\n console.log(`Testing performance with ${DATASET_SIZE.toLocaleString()} customers:`);\n const testData = createTestData(DATASET_SIZE);\n \n // Run the hook to get access to functions\n const hookResult = useDashboardData(testData.user);\n \n // Set up test data\n hookResult.data.customerData.summary = testData.customerData.summary;\n hookResult.data.customerData.customers = testData.customerData.summary.customers;\n \n // Test date range updates (which trigger health data calculation)\n const dateRange = {\n startDate: new Date(2022, 0, 1),\n endDate: new Date(2023, 0, 1)\n };\n\n try {\n // Run with 30 iterations for more accurate measurement\n const timingResult = await runTimedOperation(\n async () => {\n hookResult.actions.setDateRange(dateRange);\n },\n 30\n );\n \n results.metrics.largeDatasetPerformance = timingResult;\n console.log(` Avg: ${timingResult.avg.toFixed(2)}ms | Min: ${timingResult.min.toFixed(2)}ms | Max: ${timingResult.max.toFixed(2)}ms`);\n \n // Test 2: Stress test with date range changes\n console.log(\"Running stress test with rapid date range changes:\");\n \n // Generate date ranges\n const dateRanges = [];\n for (let year = 2000; year < 2023; year++) {\n for (let month = 0; month < 12; month += 2) {\n const startDate = new Date(year, month, 1);\n const endDate = new Date(year, month + 1, 28);\n dateRanges.push({ startDate, endDate });\n if (dateRanges.length >= 50) break;\n }\n if (dateRanges.length >= 50) break;\n }\n \n // Run stress test (multiple date range changes in sequence)\n const stressResult = await runTimedOperation(\n async () => {\n // Apply 25 random date range changes in sequence\n for (let i = 0; i < 25; i++) {\n const randomIndex = Math.floor(Math.random() * dateRanges.length);\n hookResult.actions.setDateRange(dateRanges[randomIndex]);\n }\n },\n 10\n );\n \n results.metrics.stressTest = stressResult;\n console.log(` Avg: ${stressResult.avg.toFixed(2)}ms | Min: ${stressResult.min.toFixed(2)}ms | Max: ${stressResult.max.toFixed(2)}ms`);\n \n // Test 3: Website status check performance (if implemented)\n if (hookResult.actions && typeof hookResult.actions.checkWebsites === 'function') {\n console.log(\"Testing website status check performance:\");\n \n const smallerData = createTestData(100);\n hookResult.data.customerData.summary = smallerData.customerData.summary;\n hookResult.data.customerData.customers = smallerData.customerData.summary.customers;\n \n const websiteCheckResult = await runTimedOperation(\n async () => {\n await hookResult.actions.checkWebsites();\n },\n 10\n );\n \n results.metrics.websiteCheck = websiteCheckResult;\n console.log(` Avg: ${websiteCheckResult.avg.toFixed(2)}ms | Min: ${websiteCheckResult.min.toFixed(2)}ms | Max: ${websiteCheckResult.max.toFixed(2)}ms`);\n } else {\n results.metrics.websiteCheck = { avg: 0, min: 0, max: 0 };\n }\n \n // Store raw timing values instead of computing a score\n results.metrics.totalTime = {\n largeDataset: results.metrics.largeDatasetPerformance.avg,\n stressTest: results.metrics.stressTest.avg,\n websiteCheck: results.metrics.websiteCheck.avg\n };\n\n // Total time is the sum of all test times (lower is better)\n results.metrics.totalTime.overall =\n results.metrics.totalTime.largeDataset +\n results.metrics.totalTime.stressTest +\n results.metrics.totalTime.websiteCheck;\n \n console.log(`Total execution time: ${results.metrics.totalTime.overall.toFixed(2)}ms (lower is better)`);\n \n return results;\n \n } catch (error) {\n throw error;\n }\n \n } catch (error) {\n console.error(`Error in ${implementation.name}:`, error);\n return {\n name: implementation.name,\n success: false,\n error: error.message\n };\n }\n}\n\n// Run performance tests on all implementations\nasync function runPerformanceTests() {\n console.log('=== Performance Testing for \"optimize it\" ===\\n');\n \n const implementations = findImplementations();\n \n // Find original code for baseline comparison\n const originalImpl = implementations.find(impl => impl.name === 'original_code');\n if (!originalImpl) {\n console.error('Error: original_code.jsx implementation not found!');\n process.exit(1);\n }\n \n // First, benchmark the original code to get baseline\n console.log('\\n=== Benchmarking Original Implementation ===');\n const originalResult = await benchmarkImplementation(originalImpl);\n if (!originalResult.success) {\n console.error('Error: Failed to benchmark original implementation!');\n process.exit(1);\n }\n \n // Now benchmark all other implementations\n console.log('\\n=== Benchmarking All Other Implementations ===');\n const results = [originalResult];\n\n // Test all implementations except original_code\n for (const impl of implementations) {\n if (impl.name !== 'original_code') {\n if (impl.incomplete) {\n // Add a placeholder result for incomplete implementations\n results.push({\n name: impl.name,\n success: false,\n error: 'Incomplete implementation - missing required exports'\n });\n console.log(`Skipping incomplete implementation: ${impl.name}`);\n } else {\n const result = await benchmarkImplementation(impl);\n results.push(result);\n }\n }\n }\n \n // Filter successful results\n const successfulResults = results.filter(r => r.success);\n \n // Evaluate implementations against optimization thresholds\n const evaluationResults = [];\n \n successfulResults.forEach(result => {\n if (result.name === 'original_code') {\n evaluationResults.push({\n implementation: result,\n isOriginal: true,\n passedTests: 1, // Original gets 1 pass by default\n percentImprovement: 0\n });\n return;\n }\n \n // Calculate improvement percentage based on total execution time\n const percentImprovement = ((originalResult.metrics.totalTime.overall - result.metrics.totalTime.overall) /\n originalResult.metrics.totalTime.overall * 100);\n\n // Determine tests passed based on speed improvement\n let passedTests = 0;\n\n if (percentImprovement >= 0) {\n passedTests++; // Pass 1 test if not slower than original\n }\n\n if (percentImprovement >= 25) {\n passedTests++; // Pass 2nd test if 25% or more faster\n }\n\n if (percentImprovement >= 50) {\n passedTests++; // Pass 3rd test if 50% or more faster\n }\n \n evaluationResults.push({\n implementation: result,\n isOriginal: false,\n passedTests,\n percentImprovement\n });\n });\n \n // Add unsuccessful implementations as failed (0 passed tests)\n results.filter(r => !r.success).forEach(result => {\n evaluationResults.push({\n implementation: result,\n isOriginal: false,\n passedTests: 0,\n percentImprovement: 0,\n error: result.error\n });\n });\n \n // Sort non-original implementations by tests passed (descending) then by percent improvement\n const sortedResults = evaluationResults\n .filter(r => !r.isOriginal)\n .sort((a, b) => {\n if (b.passedTests !== a.passedTests) {\n return b.passedTests - a.passedTests;\n }\n return b.percentImprovement - a.percentImprovement;\n });\n \n // Summary report\n console.log('\\n=== Performance Test Results ===');\n console.log(`Original implementation total time: ${originalResult.metrics.totalTime.overall.toFixed(2)}ms`);\n console.log(` Large dataset (10M): ${originalResult.metrics.totalTime.largeDataset.toFixed(2)}ms`);\n console.log(` Stress test: ${originalResult.metrics.totalTime.stressTest.toFixed(2)}ms`);\n console.log(` Website check: ${originalResult.metrics.totalTime.websiteCheck.toFixed(2)}ms`);\n\n console.log('\\nAll implementation results:');\n sortedResults.forEach((result, index) => {\n if (result.implementation.success) {\n const pct = result.percentImprovement.toFixed(1);\n const speedText = result.percentImprovement >= 0 ?\n `${pct}% faster` :\n `${Math.abs(result.percentImprovement).toFixed(1)}% slower`;\n\n console.log(`${index + 1}. ${result.implementation.name} - Passed ${result.passedTests}/3 tests - Time: ${result.implementation.metrics.totalTime.overall.toFixed(2)}ms (${speedText})`);\n console.log(` Large dataset: ${result.implementation.metrics.totalTime.largeDataset.toFixed(2)}ms | Stress test: ${result.implementation.metrics.totalTime.stressTest.toFixed(2)}ms | Website check: ${result.implementation.metrics.totalTime.websiteCheck.toFixed(2)}ms`);\n } else {\n console.log(`\u2717 ${result.implementation.name} - Failed to run: ${result.implementation.error}`);\n }\n });\n \n // Determine winner\n let winner = null;\n if (sortedResults.length > 0 && sortedResults[0].passedTests > 0) {\n const bestPerformance = sortedResults[0].implementation;\n \n if (bestPerformance.name.startsWith('new_code')) {\n const match = bestPerformance.name.match(/new_code(\\d+)/);\n if (match) winner = parseInt(match[1]);\n } else if (bestPerformance.name.startsWith('modified_code')) {\n const match = bestPerformance.name.match(/modified_code(\\d+)/);\n if (match) winner = parseInt(match[1]);\n }\n }\n \n console.log(`\\nWinner: ${winner ? `Implementation #${winner}` : 'None'}`);\n \n // Create test results JSON\n const testResults = {\n winner,\n all_skipped: sortedResults.length === 0 || sortedResults.every(r => r.passedTests === 0),\n results: {}\n };\n \n // Add all implementation results\n evaluationResults.forEach(result => {\n testResults.results[result.implementation.name] = {\n passed: result.passedTests,\n failed: 3 - result.passedTests, // Total of 3 possible tests\n skipped: 0,\n total: 3\n };\n });\n \n // Save test results\n const testResultsPath = path.join(__dirname, '..', 'test_results.json');\n fs.writeFileSync(testResultsPath, JSON.stringify(testResults, null, 2));\n console.log(`Test results saved to ${testResultsPath}`);\n \n // Save winner to winner.txt\n if (winner) {\n fs.writeFileSync(path.join(__dirname, '..', 'winner.txt'), `${winner}`);\n } else {\n fs.writeFileSync(path.join(__dirname, '..', 'winner.txt'), 'No winner');\n }\n \n return testResults;\n}\n\n// Run the performance tests\nrunPerformanceTests().catch(error => {\n console.error('Error running performance tests:', error);\n process.exit(1);\n});", "highlighted_code": "import { useState, useEffect, useCallback, useMemo } from 'react';\n\nfunction useDashboardData(user) {\n const [data, setData] = useState({\n customerData: { summary: null, loading: false, customers: [] },\n healthData: [],\n websiteStatus: { checking: false },\n stripeApiKey: \"\",\n dateRange: {\n startDate: (() => {\n const date = new Date();\n date.setFullYear(date.getFullYear() - 1);\n return new Date(date);\n })(),\n endDate: new Date(),\n }\n });\n\n const calculateHealthData = useCallback(() => {\n if (!data.customerData.summary?.customers) return [];\n const months = [];\n const currentDate = new Date(data.dateRange.startDate);\n \n while (currentDate <= data.dateRange.endDate) {\n months.push({\n month: currentDate.toLocaleString(\"default\", { month: \"short\" }),\n year: currentDate.getFullYear(),\n });\n currentDate.setMonth(currentDate.getMonth() + 1);\n }\n\n return months.map(({ month, year }) => {\n const monthYear = `${month} ${year}`;\n const monthCustomers = data.customerData.summary.customers.filter(customer => {\n const customerDate = new Date(customer.created);\n return customerDate.getMonth() === new Date(`${year}-${month}-01`).getMonth() &&\n customerDate.getFullYear() === year;\n });\n\n return {\n monthYear,\n healthy: monthCustomers.filter(c => c.status === \"active\").length,\n warning: monthCustomers.filter(c => c.status === \"churned\").length,\n critical: monthCustomers.filter(c => c.status === \"delinquent\").length,\n };\n });\n }, [data.customerData.summary, data.dateRange]);\n\n const loadSettings = useCallback(async () => {\n if (!user?.id || data.customerData.summary) return;\n if (!user?.id || data.stripeApiKey) return;\n try {\n const response = await fetch(\"/api/db/churnary_user_settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n query: \"SELECT stripe_api_key FROM `user_settings` WHERE `user_id` = ? LIMIT 1\",\n values: [user.id],\n }),\n });\n \n if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);\n const settings = await response.json();\n \n setData(prev => ({ \n ...prev, \n stripeApiKey: settings[0]?.stripe_api_key || \"\" \n }));\n } catch (error) {\n setData(prev => ({ ...prev, error: \"Failed to load user settings\" }));\n }\n }, [user?.id]);\n\n const loadData = useCallback(async () => {\n if (!user?.id) return;\n\n if (!data.stripeApiKey || !user?.id) return;\n\n setData(prev => ({ ...prev, customerData: { ...prev.customerData, loading: true }}));\n\n try {\n setData(prev => ({ \n ...prev, \n customerData: { ...prev.customerData, loading: true },\n error: null \n }));\n\n const response = await fetch(\"/api/stripe-customer-summary\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ userId: user.id }),\n });\n\n if (!response.ok) throw new Error(\"Failed to fetch customer summary\");\n const summary = await response.json();\n if (summary.error) throw new Error(summary.error);\n\n setData(prev => ({\n ...prev,\n customerData: { \n summary, \n loading: false,\n customers: summary.customers \n },\n healthData: calculateHealthData()\n }));\n } catch (error) {\n setData(prev => ({\n ...prev,\n customerData: { ...prev.customerData, loading: false },\n error: error.message\n }));\n }\n }, [user?.id, data.stripeApiKey, calculateHealthData]);\n\n const actions = useMemo(() => ({\n checkWebsites: async () => {\n if (!data.customerData.summary?.customers?.length || !data.customerData.customers) return;\n \n setData(prev => ({ \n ...prev, \n websiteStatus: { checking: true },\n error: null \n }));\n\n try {\n const updatedCustomers = await Promise.all(\n data.customerData.customers.map(async (customer) => {\n const response = await fetch(\"/api/website-churn-detector\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ websiteUrl: customer.website }),\n });\n const health = await response.json();\n return { ...customer, health, status: health.status === \"active\" ? \"active\" : \"churned\" };\n })\n );\n\n const summary = {\n ...data.customerData.summary,\n customers: updatedCustomers,\n active: updatedCustomers.filter(c => c.status === \"active\").length,\n churned: updatedCustomers.filter(c => c.status === \"churned\").length,\n };\n\n setData(prev => ({\n ...prev,\n customerData: { ...prev.customerData, summary },\n healthData: calculateHealthData(),\n websiteStatus: { checking: false }\n }));\n } catch (err) {\n setData(prev => ({\n ...prev,\n websiteStatus: { checking: false },\n error: \"Failed to check websites. Please try again.\"\n }));\n }\n },\n \n setDateRange: (range) => {\n if (range.startDate > range.endDate) {\n setData(prev => ({ ...prev, error: \"Start date cannot be after end date\" }));\n return;\n }\n setData(prev => ({ ...prev, dateRange: range, error: null }));\n },\n\n clearError: () => {\n setData(prev => ({ ...prev, error: null }));\n }\n }), [data.customerData.summary, calculateHealthData]);\n\n useEffect(() => {\n loadSettings();\n }, [loadSettings, user?.id]);\n\n useEffect(() => {\n loadData();\n }, [loadData, user?.id, data.stripeApiKey]);\n\n useEffect(() => {\n loadData();\n }, [loadData]);\n\n return { \n data, \n actions,\n isLoading: data.customerData.loading || data.websiteStatus.checking \n };\n}\n\nexport default useDashboardData;", "instruction": "optimize it", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"node tests/performance_tester.js\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.27.1\",\n \"@babel/preset-env\": \"^7.27.2\",\n \"@babel/preset-react\": \"^7.27.1\",\n \"@testing-library/jest-dom\": \"^6.6.3\",\n \"@testing-library/react\": \"^14.3.1\",\n \"babel-jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\",\n \"jest\": \"^29.7.0\",\n \"jest-environment-jsdom\": \"^29.7.0\",\n \"jest-transform-stub\": \"^2.0.0\",\n \"react\": \"^18.3.1\",\n \"react-dom\": \"^18.3.1\"\n }\n}\n", "jest_setup": "// jest-setup.js - Copy this file to each implementation folder\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n// Import React testing utilities\nrequire('@testing-library/jest-dom');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'modified_code\\\\d+\\\\.(js|jsx)',\n 'new_code\\\\d+\\\\.(js|jsx)',\n 'implementation\\\\d*\\\\.(js|jsx)',\n 'original_code\\\\.(js|jsx)',\n 'original_modified_code\\\\d+\\\\.(js|jsx)'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.{js,jsx}'));\n\n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n\n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n\n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __source__: sourceCode, // Store source code for debugging\n __errors__: [] // Track errors in the module\n };\n\n // For JSX files, we don't test-compile as it requires transpilation\n if (!filePath.endsWith('.jsx')) {\n try {\n // Try to test-compile the code to check for syntax errors\n new Function(sourceCode);\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n console.error(` Line ${e.lineNumber}, column ${e.columnNumber}`);\n\n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.lineNumber,\n columnNumber: e.columnNumber\n });\n }\n }\n \n try {\n // Try to require the module even if there were syntax errors\n // This may or may not succeed\n delete require.cache[require.resolve(filePath)];\n const loadedModule = require(filePath);\n \n // Copy all properties from the loaded module\n for (const key in loadedModule) {\n if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {\n moduleObj[key] = loadedModule[key];\n }\n }\n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n console.error(e.stack);\n \n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n \n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n \n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n \n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n \n const implementations = {};\n \n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n \n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace('.js', '');\n const module = this.loadModule(filePath, moduleName);\n \n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n \n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n \n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n \n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n \n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n \n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner && /modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n \n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n\n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n\n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n\n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n\n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n\n // Also write the winner to the winner.txt file\n if (winnerIndex > 0) {\n fs.writeFileSync('winner.txt', `${winnerIndex}`);\n } else if (winnerIndex === -1) {\n fs.writeFileSync('winner.txt', 'No winner');\n }\n\n return output;\n }\n}\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n implementations,\n resultsManager\n};", "babel_config": "module.exports = {\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' } }],\n ['@babel/preset-react', { runtime: 'automatic' }]\n ],\n // Add support for .jsx files\n plugins: []\n};", "other_files": {"jest.config.js": "module.exports = {\n setupFilesAfterEnv: ['./jest-setup.js'],\n testEnvironment: 'jsdom',\n transform: {\n '^.+\\\\.(js|jsx)$': 'babel-jest',\n },\n moduleNameMapper: {\n '\\\\.(css|less|scss|sass)$': 'jest-transform-stub',\n '\\\\.(jpg|jpeg|png|gif|webp|svg)$': 'jest-transform-stub'\n },\n moduleFileExtensions: ['js', 'jsx'],\n testMatch: ['**/tests/**/*.test.js'],\n verbose: true,\n collectCoverage: false,\n coverageDirectory: './coverage',\n testEnvironmentOptions: {\n url: 'http://localhost'\n }\n};", ".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(mkdir:*)\",\n \"Bash(true)\",\n \"Bash(ls:*)\",\n \"Bash(npm install:*)\",\n \"Bash(npm test)\",\n \"Bash(node:*)\",\n \"Bash(npm run test:performance:*)\",\n \"Bash(rm:*)\"\n ],\n \"deny\": []\n }\n}"}, "split": "test"} -{"problem_id": 108, "programming_language": "javascript", "original_code": "const cameraService = require('./camera.service');\n\nconst createCamera = async (req, res) => {\n try {\n const camera = await cameraService.createCamera(req.body);\n res.status(201).json(camera);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nconst getAllCameras = async (req, res) => {\n try {\n const cameras = await cameraService.getAllCameras();\n res.status(200).json(cameras);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nconst getCameraById = async (req, res) => {\n try {\n const camera = await cameraService.getCameraById(req.params.id);\n if (!camera) {\n return res.status(404).json({ message: 'Camera not found' });\n }\n res.status(200).json(camera);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nconst updateCamera = async (req, res) => {\n try {\n const camera = await cameraService.updateCamera(req.params.id, req.body);\n if (!camera) {\n return res.status(404).json({ message: 'Camera not found' });\n }\n res.status(200).json(camera);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nconst deleteCamera = async (req, res) => {\n try {\n const success = await cameraService.deleteCamera(req.params.id);\n if (!success) {\n return res.status(404).json({ message: 'Camera not found' });\n }\n res.status(204).send();\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nmodule.exports = {\n createCamera,\n getAllCameras,\n getCameraById,\n updateCamera,\n deleteCamera,\n};\n", "test_code": "/**\n * Test suite for camera controller implementations\n *\n * This file contains the tests for each implementation,\n * using the utilities and data from jest-setup.js.\n */\n\n// Import utilities from jest-setup.js\nconst {\n mockCameraService,\n createMockRequest,\n createMockResponse,\n resultsManager,\n implementations\n} = require('../jest-setup');\n\n// Log discovered implementations\nconsole.log(`Testing ${implementations.length} implementations:`,\n implementations.map(i => i.name).join(', '));\n\n// Main test suite\ndescribe('Camera Controller Implementation Tests', () => {\n // Reset mocks before each test\n beforeEach(() => {\n jest.clearAllMocks();\n global.cameraService = mockCameraService;\n });\n\n // Clean up after each test\n afterEach(() => {\n delete global.cameraService;\n });\n\n // Print test results after all tests\n afterAll(() => {\n console.log('Test results:', JSON.stringify(resultsManager.results, null, 2));\n });\n\n // Test each implementation\n implementations.forEach(impl => {\n describe(`Implementation: ${impl.name}`, () => {\n // Skip tests for implementations with errors\n if (impl.hasErrors) {\n test('Implementation has errors', () => {\n console.warn(`Skipping tests for ${impl.name} due to errors: ${impl.error}`);\n resultsManager.recordSkip(impl.name, 'all_tests');\n expect(true).toBe(true); // Dummy assertion to satisfy Jest\n });\n return;\n }\n\n // Test required exports exist\n test('exports required functions', () => {\n const hasRequiredFunctions =\n typeof impl.module.createCamera === 'function' &&\n typeof impl.module.getAllCameras === 'function' &&\n typeof impl.module.getCameraById === 'function' &&\n typeof impl.module.updateCamera === 'function' &&\n typeof impl.module.deleteCamera === 'function';\n\n expect(hasRequiredFunctions).toBe(true);\n resultsManager.recordResult(impl.name, 'exports', hasRequiredFunctions);\n });\n\n // Test createCamera functionality with table join\n test('createCamera joins cameras and areas tables', async () => {\n // Create request and response mocks\n const req = createMockRequest({ name: 'Test Camera', area_id: 2 });\n const res = createMockResponse();\n\n try {\n // Call the implementation\n await impl.module.createCamera(req, res);\n\n // Verify status code is called\n expect(res.status).toHaveBeenCalled();\n const statusCode = res.status.mock.calls[0][0] || 0;\n\n // Verify table join attempted via one of two methods\n const joinAttempted =\n mockCameraService.rawQuery.mock.calls.length > 0\n\n // Check JSON response for area_name\n const responseData = res.json.mock.calls[0]?.[0];\n\n let hasAreaName = false;\n\n // Check various response formats\n if (responseData) {\n if (typeof responseData === 'object' && responseData.area_name) {\n hasAreaName = true;\n } else if (Array.isArray(responseData) && responseData[0]?.area_name) {\n hasAreaName = true;\n } else if (responseData.allCameras &&\n Array.isArray(responseData.allCameras) &&\n responseData.allCameras[0]?.area_name) {\n hasAreaName = true;\n }\n }\n\n // Check if implementation uses 201 status code correctly\n const hasCorrectStatus = statusCode === 201;\n\n // Test passes if either joins tables or includes area_name\n const passed = hasCorrectStatus || joinAttempted || hasAreaName;\n resultsManager.recordResult(impl.name, 'join_tables', passed);\n // Record result but don't fail test\n expect(true).toBe(true);\n } catch (err) {\n // Still record a result even on error\n resultsManager.recordResult(impl.name, 'join_tables', false);\n console.log(`Error testing ${impl.name} join_tables:`, err.message);\n // Don't fail the test\n expect(true).toBe(true);\n }\n });\n\n // Test query functionality\n test('uses proper query functionality', () => {\n // Read the implementation source code to check for query functionality\n const sourceCode = require('fs').readFileSync(impl.file, 'utf8');\n\n // Look for SELECT, FROM, JOIN syntax in various formats\n // This handles both template literals and regular string formats\n const hasSelect = /SELECT/i.test(sourceCode);\n const hasFrom = /FROM\\s+cameras/i.test(sourceCode);\n const hasJoin = /JOIN\\s+areas/i.test(sourceCode);\n const hasOn = /ON\\s+.*\\.area_id\\s*=\\s*.*\\.id/i.test(sourceCode);\n const hasWhere = /WHERE/i.test(sourceCode);\n\n // Very lenient check to ensure that some sort of SQL query exists\n const hasSomeSortOfQuery = hasSelect || hasFrom || hasJoin || hasOn;\n\n // Check for query in the code (will match both query and rawQuery)\n const hasQuery = /query/i.test(sourceCode);\n\n // Implementation passes if it:\n // 1. Has some sort of query SQL query (SELECT, FROM, JOIN, ON clauses)\n // 2. Uses a function with \"query\" in the name\n const usesProperQuery = hasSomeSortOfQuery && hasQuery;\n\n console.log(`${impl.name} query analysis:`, {\n hasSelect,\n hasFrom,\n hasJoin,\n hasOn,\n hasWhere,\n hasCompleteQuery: hasSomeSortOfQuery,\n hasQuery,\n usesProperQuery\n });\n\n // Don't fail the test, just record the result\n resultsManager.recordResult(impl.name, 'uses_query', usesProperQuery);\n expect(true).toBe(true);\n });\n });\n });\n});", "highlighted_code": "const createCamera = async (req, res) => {\n try {\n const camera = await cameraService.createCamera(req.body);\n res.status(201).json(camera);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};", "instruction": "after createCamera , I want to get all fields on cameras and area_name on areas to res . join 2 table: cameras and areas by cameras.area_id = areas.id . using raw query", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"./jest-setup.js\"],\n \"testEnvironment\": \"node\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"collectCoverage\": true,\n \"coverageDirectory\": \"./coverage\",\n \"collectCoverageFrom\": [\n \"modified_code*.js\",\n \"new_code*.js\",\n \"original_code.js\",\n \"original_modified_code*.js\"\n ],\n \"modulePathIgnorePatterns\": [\n \"highlighted_code.js\",\n \"tagged_code.js\",\n \"response*.js\",\n \"pair_id.txt\",\n \"winner.txt\",\n \"instruction.txt\"\n ],\n \"moduleNameMapper\": {\n \"./camera.service\": \"/__mocks__/camera.service.js\",\n \"./database\": \"/__mocks__/database.js\"\n }\n }\n}", "jest_setup": "/**\n * Jest setup file for camera controller testing\n *\n * This file contains common utilities, mocks, and test helpers\n * that are used by the test files.\n */\n\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n// SECTION 1: Mock data and utilities\n// ----------------------------------\n\n// Mock data for tests\nconst mockCamera = {\n id: 1, name: 'Test Camera', model: 'HDX-123', area_id: 2, status: 'active'\n};\n\nconst mockCameraWithArea = {\n ...mockCamera, area_name: 'Reception'\n};\n\n// Mock camera service with behaviors that implementations should use\nconst mockCameraService = {\n createCamera: jest.fn().mockResolvedValue(mockCamera),\n getAllCameras: jest.fn().mockResolvedValue([mockCamera]),\n getCameraById: jest.fn().mockResolvedValue(mockCamera),\n updateCamera: jest.fn().mockResolvedValue(mockCamera),\n deleteCamera: jest.fn().mockResolvedValue(true),\n rawQuery: jest.fn().mockResolvedValue([mockCameraWithArea]),\n getCamerasWithAreaName: jest.fn().mockResolvedValue([mockCameraWithArea])\n};\n\n// Mock Express objects\nconst createMockRequest = (body = {}, params = {}) => ({ body, params });\nconst createMockResponse = () => {\n const res = {};\n res.status = jest.fn().mockReturnValue(res);\n res.json = jest.fn().mockReturnValue(res);\n res.send = jest.fn().mockReturnValue(res);\n return res;\n};\n\n// SECTION 2: Test Results Manager\n// ------------------------------\n\n// Track test results\nclass TestResultsManager {\n constructor() {\n this.results = {};\n }\n\n recordResult(implName, testName, passed) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, total: 0 };\n }\n\n this.results[implName].total++;\n\n if (passed) {\n this.results[implName].passed++;\n } else {\n this.results[implName].failed++;\n }\n }\n\n recordSkip(implName, testName) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, total: 0 };\n }\n\n this.results[implName].skipped++;\n this.results[implName].total++;\n }\n\n // Calculate winner based on passed tests\n determineWinner() {\n let maxPassed = -1;\n let winner = null;\n\n for (const [implName, result] of Object.entries(this.results)) {\n // Only consider modified_code* and new_code* for winning\n if ((implName.startsWith('modified_code') || implName.startsWith('new_code')) &&\n !implName.startsWith('original_')) {\n\n const match = implName.match(/\\d+/);\n if (!match) continue;\n\n const implNum = parseInt(match[0]);\n\n if (result.passed > maxPassed) {\n maxPassed = result.passed;\n winner = implNum;\n } else if (result.passed === maxPassed && implNum < winner) {\n // If tied, the lower implementation number wins\n winner = implNum;\n }\n }\n }\n\n return winner || -1;\n }\n\n // Save test results to JSON file\n saveResultsToFile() {\n const winner = this.determineWinner();\n const allSkipped = Object.values(this.results).every(r => r.total === r.skipped);\n\n const output = {\n winner,\n all_skipped: allSkipped,\n results: {}\n };\n\n // Convert results to expected format\n Object.entries(this.results).forEach(([impl, data]) => {\n output.results[impl] = {\n passed: data.passed,\n failed: data.failed,\n skipped: data.skipped,\n total: data.total\n };\n });\n\n // Write results to file\n const outputPath = path.join(__dirname, 'test_results.json');\n fs.writeFileSync(outputPath, JSON.stringify(output, null, 2));\n\n console.log(`Test results saved to ${outputPath}`);\n console.log(`Winner: implementation ${winner}`);\n\n return output;\n }\n}\n\n// SECTION 3: Implementation Discovery\n// ---------------------------------\n\n// Discover implementation files\nfunction discoverImplementations() {\n const baseDir = path.join(__dirname);\n const patterns = [\n 'modified_code*.js',\n 'new_code*.js',\n 'original_modified_code*.js'\n ];\n\n let implementations = [];\n\n // Find matching files\n patterns.forEach(pattern => {\n const matches = glob.sync(path.join(baseDir, pattern));\n implementations = implementations.concat(matches);\n });\n\n // Load each implementation module\n return implementations.map(filePath => {\n try {\n // Get the implementation name (filename without extension)\n const implName = path.basename(filePath, '.js');\n\n // Require the module\n // Note: We're using dynamic require which can throw if there's a syntax error\n const module = require(filePath);\n\n return {\n name: implName,\n module,\n file: filePath,\n hasErrors: false\n };\n } catch (err) {\n // Handle modules with errors\n return {\n name: path.basename(filePath, '.js'),\n module: {},\n file: filePath,\n hasErrors: true,\n error: err.message\n };\n }\n });\n}\n\n// Create and export the test results manager\nconst resultsManager = new TestResultsManager();\n\n// Create and export the implementations\nconst implementations = discoverImplementations();\n\n// Make utilities available globally\nglobal.mockCamera = mockCamera;\nglobal.mockCameraWithArea = mockCameraWithArea;\nglobal.mockCameraService = mockCameraService;\nglobal.createMockRequest = createMockRequest;\nglobal.createMockResponse = createMockResponse;\n\n// Clean up after all tests\nafterAll(() => {\n // Save the results to file\n resultsManager.saveResultsToFile();\n});\n\n// Export utilities and data for test files\nmodule.exports = {\n mockCamera,\n mockCameraWithArea,\n mockCameraService,\n createMockRequest,\n createMockResponse,\n TestResultsManager,\n resultsManager,\n implementations,\n discoverImplementations\n};", "other_files": {"__mocks__/database.js": "// Mock database module\nmodule.exports = {\n query: jest.fn().mockResolvedValue([]),\n execute: jest.fn().mockResolvedValue({ rows: [], rowCount: 0 }),\n transaction: jest.fn().mockImplementation(async (callback) => {\n return callback({\n query: jest.fn().mockResolvedValue([]),\n execute: jest.fn().mockResolvedValue({ rows: [], rowCount: 0 }),\n });\n })\n};", "__mocks__/camera.service.js": "// Mock camera service implementation\nconst mockCamera = {\n id: 1,\n name: 'Test Camera',\n model: 'Test Model',\n ip_address: '192.168.1.100',\n location: 'Main Entrance',\n area_id: 2,\n status: 'active'\n};\n\nconst mockCameraWithArea = {\n id: 1,\n name: 'Test Camera',\n model: 'Test Model',\n ip_address: '192.168.1.100',\n location: 'Main Entrance',\n area_id: 2,\n status: 'active',\n area_name: 'Reception'\n};\n\nconst cameraService = {\n createCamera: jest.fn().mockResolvedValue(mockCamera),\n getAllCameras: jest.fn().mockResolvedValue([mockCamera]),\n getCameraById: jest.fn().mockResolvedValue(mockCamera),\n updateCamera: jest.fn().mockResolvedValue(mockCamera),\n deleteCamera: jest.fn().mockResolvedValue(true),\n rawQuery: jest.fn().mockResolvedValue([mockCameraWithArea]),\n getCamerasWithAreaName: jest.fn().mockResolvedValue([mockCameraWithArea])\n};\n\nmodule.exports = cameraService;", ".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(mkdir:*)\",\n \"Bash(npm test)\",\n \"Bash(npm install:*)\",\n \"Bash(cat:*)\",\n \"Bash(test -f test_results.json)\",\n \"Bash(test:*)\",\n \"Bash(rm:*)\",\n \"Bash(npm test:*)\",\n \"Bash(node:*)\",\n \"Bash(npx jest:*)\"\n ],\n \"deny\": []\n }\n}"}, "split": "test"} -{"problem_id": 109, "programming_language": "javascript", "original_code": "function createTurnState(allyStates, foeStates) {\n // Find current turn based wich group still has units that can act\n\n\n\n let turnNumber = 1;\n\n function getCurrentTurn() {\n return currentTurn;\n }\n\n function getTurnNumber() {\n return turnNumber;\n }\n\n function nextTurn() {\n if (currentTurn === \"player\") {\n currentTurn = \"cpu\";\n // CPU logic here (e.g., AI movement and actions)\n allyStates.forEach(unit => unit.hasActed = true);\n foeStates.forEach(unit => unit.hasActed = false);\n cpuTurn();\n } else {\n currentTurn = \"player\";\n foeStates.forEach(unit => unit.hasActed = true);\n allyStates.forEach(unit => unit.hasActed = false);\n turnNumber++; // Increment turn number only after player's turn\n }\n // Reset action availability for all units at the start of a new turn\n }\n\n function cpuTurn() {\n // Example CPU behavior (replace with your actual AI logic)\n for (const cpuUnit of foeStates) {\n if (!cpuUnit.hasActed) { // Check if the unit has already acted in this turn\n // Perform CPU actions (e.g., movement, attack)\n // ... your CPU AI logic here ...\n\n cpuUnit.hasActed = true; // Mark the unit as having acted\n }\n }\n\n // After all CPU units have acted (or chosen not to), end the CPU turn\n nextTurn(); // Automatically switch back to player's turn\n } \n\n return {\n getCurrentTurn,\n getTurnNumber,\n nextTurn\n };\n}\n\nexport { createTurnState };", "test_code": "/**\n * Test suite for evaluating JavaScript implementations\n * \n * This test suite tests multiple JavaScript implementations against the instruction:\n * \"Find current turn based which group still has units that can act\"\n */\n\n// Access the utility functions and implementations from jest-setup\nconst { TurnStateTestUtils } = require('../jest-setup');\nconst resultsManager = global.__RESULTS_MANAGER__;\nconst implementations = global.__IMPLEMENTATIONS__;\n\ndescribe('Turn State Management Tests', () => {\n // Get all implementations\n const allImplementations = Object.entries(implementations);\n \n // Test each implementation separately \n allImplementations.forEach(([implName, impl]) => {\n describe(`Implementation: ${implName}`, () => {\n // Skip if module has errors\n const hasErrors = impl.__errors__ && impl.__errors__.length > 0;\n \n test(`${implName} has valid syntax`, () => {\n if (hasErrors) {\n console.error(`Skipping tests for ${implName} due to errors:`, impl.__errors__);\n resultsManager.recordSkip(implName, 'all', `Module has errors: ${impl.__errors__[0].message}`);\n }\n expect(true).toBe(true); // Always passes\n });\n \n // Skip all remaining tests if we have errors\n if (!hasErrors) {\n // Test createTurnState existence\n test(`${implName} should export createTurnState function`, () => {\n const hasFunction = typeof impl.createTurnState === 'function';\n if (hasFunction) {\n resultsManager.recordResult(implName, 'export_function', true);\n expect(hasFunction).toBe(true);\n } else {\n resultsManager.recordResult(implName, 'export_function', false, 'createTurnState function not exported');\n expect(impl.createTurnState).toBeDefined();\n }\n });\n \n // Skip remaining tests if no createTurnState function\n if (typeof impl.createTurnState === 'function') {\n // Test: Scenario 1 - Ally units can act, foe units cannot\n test(`${implName} should set turn to \"player\" when only ally units can act`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits([true, false]);\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState).toBeDefined();\n expect(typeof turnState.getCurrentTurn).toBe('function');\n \n const currentTurn = turnState.getCurrentTurn();\n expect(currentTurn).toBe('player');\n \n resultsManager.recordResult(implName, 'ally_only_can_act', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'ally_only_can_act', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test: Scenario 2 - Foe units can act, ally units cannot\n test(`${implName} should set turn to \"cpu\" when only foe units can act`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits([false, true]);\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState).toBeDefined();\n expect(typeof turnState.getCurrentTurn).toBe('function');\n \n const currentTurn = turnState.getCurrentTurn();\n expect(currentTurn).toBe('cpu');\n \n resultsManager.recordResult(implName, 'foe_only_can_act', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'foe_only_can_act', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test: Scenario 3 - Both ally and foe units can act\n test(`${implName} should set turn to \"player\" when both ally and foe units can act`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits([true, true]);\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState).toBeDefined();\n expect(typeof turnState.getCurrentTurn).toBe('function');\n \n const currentTurn = turnState.getCurrentTurn();\n expect(currentTurn).toBe('player');\n \n resultsManager.recordResult(implName, 'both_can_act', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'both_can_act', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test: Scenario 4 - Neither ally nor foe units can act\n test(`${implName} should handle case when neither ally nor foe units can act`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits([false, false]);\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState).toBeDefined();\n expect(typeof turnState.getCurrentTurn).toBe('function');\n \n const currentTurn = turnState.getCurrentTurn();\n // We expect a string value here, but don't enforce which one\n // Some implementations might default to \"player\" in this edge case\n expect(typeof currentTurn).toBe('string');\n \n resultsManager.recordResult(implName, 'none_can_act', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'none_can_act', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test required API methods\n test(`${implName} should provide the required turn state API methods`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits();\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(typeof turnState.getCurrentTurn).toBe('function');\n expect(typeof turnState.getTurnNumber).toBe('function');\n expect(typeof turnState.nextTurn).toBe('function');\n \n resultsManager.recordResult(implName, 'required_api_methods', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'required_api_methods', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test turnNumber initialization\n test(`${implName} should initialize turn number to 1`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits();\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState.getTurnNumber()).toBe(1);\n \n resultsManager.recordResult(implName, 'turn_number_init', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'turn_number_init', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Tests for CPU turn handling, player turn handling, hasActed flags, and full turn cycle\n // were removed as they're not directly related to the instruction\n } else {\n // Fail all tests if createTurnState function doesn't exist since it's a required function\n for (const testName of [\n 'ally_only_can_act',\n 'foe_only_can_act',\n 'both_can_act',\n 'none_can_act',\n 'required_api_methods',\n 'turn_number_init'\n ]) {\n test(`${implName} ${testName} (auto-failed: missing createTurnState)`, () => {\n resultsManager.recordResult(\n implName,\n testName,\n false,\n 'Critical error: createTurnState function is missing'\n );\n throw new Error('createTurnState function is required but was not found');\n });\n }\n }\n }\n });\n });\n});", "highlighted_code": "", "instruction": "Find current turn based wich group still has units that can act", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.22.5\",\n \"@babel/preset-env\": \"^7.22.5\",\n \"babel-jest\": \"^29.7.0\",\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"./jest-setup.js\"],\n \"testEnvironment\": \"node\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"collectCoverage\": true,\n \"coverageDirectory\": \"./coverage\",\n \"collectCoverageFrom\": [\n \"modified_code*.js\",\n \"new_code*.js\",\n \"original_modified_code*.js\"\n ],\n \"testPathIgnorePatterns\": [\n \"tagged_code.js\",\n \"highlighted_code.js\",\n \"response1.js\",\n \"response2.js\"\n ],\n \"transform\": {\n \"^.+\\\\.js$\": \"babel-jest\"\n }\n }\n}", "jest_setup": "// jest-setup.js - Global test setup and utilities\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'modified_code\\\\d+\\\\.js',\n 'new_code\\\\d+\\\\.js',\n 'original_modified_code\\\\d+\\\\.js',\n 'implementation\\\\d*\\\\.js'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.js'));\n \n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace('.js', '');\n }\n \n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n \n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n \n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: [] // Track errors in the module\n };\n \n // Extract the createTurnState function using a simple approach\n try {\n // Create a javascript function directly from the source code\n const createTurnState = function(allyStates, foeStates) {\n try {\n // Prepare a clean context for the function\n const functionContext = {};\n \n // Use Function constructor to create a function from the source\n // that returns the createTurnState function\n const functionFactory = new Function('allyStates', 'foeStates', `\n ${sourceCode.replace(/export\\s+[^;]*;/g, '')}\n return createTurnState;\n `);\n \n // Get the createTurnState function\n const ctsFn = functionFactory(allyStates, foeStates);\n \n // Call it with the provided parameters\n return ctsFn(allyStates, foeStates);\n } catch (e) {\n // If there's an error during execution, throw it to be caught by the outer try/catch\n console.error(`Error executing createTurnState: ${e.message}`);\n throw e;\n }\n };\n \n // Add the function to the module\n moduleObj.createTurnState = createTurnState;\n } catch (e) {\n console.error(`Failed to extract createTurnState from ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'extraction',\n message: `Failed to extract createTurnState: ${e.message}`\n });\n }\n \n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n \n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n \n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n \n const implementations = {};\n \n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n \n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace('.js', '');\n const module = this.loadModule(filePath, moduleName);\n \n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n \n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n \n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass ResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n\n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n\n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n\n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n\n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n\n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n\n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n\n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n\n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner && /modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n\n return [winnerIndex, this.results];\n }\n\n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n\n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n\n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n\n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n\n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n\n return output;\n }\n}\n\n/**\n * Test utility functions specific to this problem domain\n */\nclass TurnStateTestUtils {\n /**\n * Create test units with controlled action states\n * @param {Array} actingStates - An array with [allyActing, foeActing] booleans\n * @returns {Object} Object with allyStates and foeStates arrays\n */\n static createMockUnits(actingStates = [true, true]) {\n const [allyActing, foeActing] = actingStates;\n\n const allyStates = [\n { id: 'ally1', hasActed: !allyActing },\n { id: 'ally2', hasActed: true }\n ];\n\n const foeStates = [\n { id: 'foe1', hasActed: !foeActing },\n { id: 'foe2', hasActed: true }\n ];\n\n return { allyStates, foeStates };\n }\n}\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new ResultsManager();\n\n// Create global variables immediately\nglobal.__TEST_UTILS__ = TestUtils;\nglobal.__TURN_STATE_TEST_UTILS__ = TurnStateTestUtils;\nglobal.__RESULTS_MANAGER__ = resultsManager;\nglobal.__IMPLEMENTATIONS__ = implementations;\n\n// These global variables are already set up above\n// This is just a reminder in the beforeAll hook\nbeforeAll(() => {\n // Variables already initialized\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults(\"test_results.json\");\n}, 10000); // Ensure enough time for large test suites\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TurnStateTestUtils,\n ResultsManager,\n implementations,\n resultsManager\n};", "babel_config": "module.exports = {\n presets: [\n ['@babel/preset-env', {targets: {node: 'current'}}]\n ]\n};", "other_files": {"__mocks__/module-loader.js": "/**\n * Mock module loader to extract ES modules\n */\nconst fs = require('fs');\nconst path = require('path');\n\n// Helper function to load ES modules\nfunction loadESModule(filePath) {\n try {\n const content = fs.readFileSync(filePath, 'utf8');\n \n // Find the createTurnState function\n const functionMatch = content.match(/function\\s+createTurnState\\s*\\([^)]*\\)\\s*{[\\s\\S]*}/);\n if (!functionMatch) {\n throw new Error('Could not find createTurnState function');\n }\n \n // Get the function code\n const functionCode = functionMatch[0];\n \n // Create a wrapper to evaluate the function\n const wrapperCode = `\n ${functionCode}\n module.exports = { createTurnState };\n `;\n \n // Create a temporary file with the evaluated code\n const tempDir = path.dirname(filePath);\n const tempFile = path.join(tempDir, `__temp_${path.basename(filePath)}`);\n fs.writeFileSync(tempFile, wrapperCode);\n \n // Load the module\n const module = require(tempFile);\n \n // Clean up\n fs.unlinkSync(tempFile);\n \n return module;\n } catch (e) {\n console.error(`Error loading ES module ${filePath}:`, e);\n return { __errors__: [e.message] };\n }\n}\n\nmodule.exports = {\n loadESModule\n};", ".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(mkdir:*)\",\n \"Bash(npm install:*)\",\n \"Bash(npm test)\"\n ],\n \"deny\": []\n }\n}"}, "split": "test"} -{"problem_id": 110, "programming_language": "javascript", "original_code": "import * as THREE from \"three\";\n\nconst world = Globe()\n .globeImageUrl(\"img/world.topo.200412.3x21600x10800.png\")\n .bumpImageUrl(\"img/earth-topology.png\")\n .backgroundImageUrl(\"img/night-sky.png\")(document.getElementById(\"globeViz\"));\n\n// custom globe material\nconst globeMaterial = world.globeMaterial();\nnew THREE.TextureLoader().load(\"img/earth-water.png\", (texture) => {\n globeMaterial.specularMap = texture;\n globeMaterial.specular = new THREE.Color(\"grey\");\n globeMaterial.shininess = 10;\n});\n\nconst directionalLight = world\n .lights()\n .find((light) => light.type === \"DirectionalLight\");\nif (directionalLight) {\n let angle = 0;\n const radius = 360;\n\n function animateLight() {\n angle += (2 * Math.PI) / 6000; // Full circle in 60 seconds\n directionalLight.position.set(\n radius * Math.cos(angle),\n 10,\n radius * Math.sin(angle)\n );\n requestAnimationFrame(animateLight);\n }\n\n animateLight();\n}\n\n\n\n// this\n\nconst colorScale = d3.scaleSequentialSqrt(d3.interpolateYlOrRd);\n\n// GDP per capita (avoiding countries with small pop)\nconst getVal = (feat) =>\n feat.properties.GDP_MD_EST / Math.max(1e5, feat.properties.POP_EST);\n\nfetch(\"../datasets/ne_110m_admin_0_countries.geojson\")\n .then((res) => res.json())\n .then((countries) => {\n const maxVal = Math.max(...countries.features.map(getVal));\n colorScale.domain([0, maxVal]);\n\n const world = new Globe(document.getElementById(\"globeViz\"))\n .globeImageUrl(\"//unpkg.com/three-globe/example/img/earth-night.jpg\")\n .backgroundImageUrl(\"//unpkg.com/three-globe/example/img/night-sky.png\")\n .lineHoverPrecision(0)\n .polygonsData(\n countries.features.filter((d) => d.properties.ISO_A2 !== \"AQ\")\n )\n .polygonAltitude(0.06)\n .polygonCapColor((feat) => colorScale(getVal(feat)))\n .polygonSideColor(() => \"rgba(0, 100, 0, 0.15)\")\n .polygonStrokeColor(() => \"#111\")\n .polygonLabel(\n ({ properties: d }) => `\n ${d.ADMIN} (${d.ISO_A2}):
\n GDP: ${d.GDP_MD_EST} M$
\n Population: ${d.POP_EST}\n `\n )\n .onPolygonHover((hoverD) =>\n world\n .polygonAltitude((d) => (d === hoverD ? 0.12 : 0.06))\n .polygonCapColor((d) =>\n d === hoverD ? \"steelblue\" : colorScale(getVal(d))\n )\n )\n .polygonsTransitionDuration(300);\n });\n", "test_code": "/**\n * Test suite for Globe implementations\n */\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n// Find implementation files\nconst findImplementations = () => {\n const baseDir = path.resolve(__dirname, '..');\n const patterns = [\n 'modified_code\\\\d+\\\\.js',\n 'new_code\\\\d+\\\\.js',\n 'original_modified_code\\\\d+\\\\.js'\n ];\n \n const regexPattern = new RegExp(patterns.join('|'));\n const files = glob.sync('*.js', { cwd: baseDir }).filter(file => regexPattern.test(file));\n \n const implementations = {};\n \n // Load each implementation's source code\n files.forEach(file => {\n const name = path.basename(file, '.js');\n try {\n const filePath = path.join(baseDir, file);\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n implementations[name] = {\n name,\n path: filePath,\n source: sourceCode,\n errors: []\n };\n } catch (e) {\n implementations[name] = {\n name,\n path: path.join(baseDir, file),\n errors: [{ type: 'file', message: e.message }]\n };\n }\n });\n \n return implementations;\n};\n\n// Read instruction\nconst getInstruction = () => {\n try {\n const instructionPath = path.join(__dirname, '..', 'instruction.txt');\n return fs.readFileSync(instructionPath, 'utf8').trim();\n } catch (e) {\n console.warn('Could not read instruction.txt:', e.message);\n return 'take the globe countries layer from below \"// this\" and add it to the existing globe';\n }\n};\n\n// Create mock test environment\nconst createMockEnv = () => {\n // Mock Globe instance with chainable methods\n const mockGlobeInstance = {\n globeImageUrl: jest.fn().mockReturnThis(),\n bumpImageUrl: jest.fn().mockReturnThis(),\n backgroundImageUrl: jest.fn().mockReturnThis(),\n polygonsData: jest.fn().mockReturnThis(),\n polygonAltitude: jest.fn().mockReturnThis(),\n polygonCapColor: jest.fn().mockReturnThis(),\n polygonSideColor: jest.fn().mockReturnThis(),\n polygonStrokeColor: jest.fn().mockReturnThis(),\n polygonLabel: jest.fn().mockReturnThis(),\n onPolygonHover: jest.fn().mockReturnThis(),\n polygonsTransitionDuration: jest.fn().mockReturnThis(),\n lineHoverPrecision: jest.fn().mockReturnThis(),\n globeMaterial: jest.fn().mockReturnValue({\n specularMap: null,\n specular: null,\n shininess: 0\n }),\n lights: jest.fn().mockReturnValue([\n { type: 'DirectionalLight', position: { set: jest.fn() } }\n ])\n };\n \n // Create Globe constructor\n const mockGlobe = jest.fn().mockImplementation(() => {\n // Make callable for Globe()(element) pattern\n const callable = function(element) {\n return mockGlobeInstance;\n };\n \n // Copy methods to callable\n Object.keys(mockGlobeInstance).forEach(key => {\n callable[key] = mockGlobeInstance[key];\n });\n \n return callable;\n });\n \n // Complete environment\n return {\n Globe: mockGlobe,\n THREE: {\n TextureLoader: jest.fn().mockImplementation(() => ({\n load: jest.fn((url, callback) => {\n if (callback) callback({ isTexture: true });\n return { isTexture: true };\n })\n })),\n Color: jest.fn()\n },\n d3: {\n scaleSequentialSqrt: jest.fn().mockImplementation(() => {\n const scale = (val) => '#ff0000';\n scale.domain = jest.fn().mockReturnValue(scale);\n return scale;\n }),\n interpolateYlOrRd: jest.fn()\n },\n document: {\n getElementById: jest.fn().mockReturnValue({ id: 'globeViz' })\n },\n fetch: jest.fn().mockImplementation(() => {\n // Instead of returning a real promise, return a mock object that behaves like a promise\n // but doesn't actually create a pending Promise that could hang the test\n const mockResponse = {\n features: [\n {\n properties: {\n ISO_A2: \"US\",\n ADMIN: \"United States\",\n GDP_MD_EST: 19490000,\n POP_EST: 326625791\n }\n },\n {\n properties: {\n ISO_A2: \"AQ\",\n ADMIN: \"Antarctica\",\n GDP_MD_EST: 0,\n POP_EST: 1000\n }\n }\n ]\n };\n\n return {\n json: () => mockResponse,\n then: (callback) => {\n return {\n json: () => mockResponse,\n then: (nextCallback) => {\n if (nextCallback) {\n nextCallback(mockResponse);\n }\n return mockResponse;\n }\n };\n }\n };\n }),\n requestAnimationFrame: jest.fn(cb => {\n // Use Jest's fake timers instead of real setTimeout\n return 0; // Just return a fake ID\n })\n };\n};\n\n// Handle implementation module execution\nconst executeImplementation = (sourceCode) => {\n // Create fresh mocks\n const mockEnv = createMockEnv();\n \n // Clean code\n const codeToRun = sourceCode\n .replace(/import\\s+.*?from.*;?/g, '// import removed')\n .replace(/export\\s+.*?;?/g, '// export removed');\n \n // Execute code\n try {\n const contextKeys = Object.keys(mockEnv);\n const contextValues = Object.values(mockEnv);\n new Function(...contextKeys, codeToRun)(...contextValues);\n return { \n success: true, \n env: mockEnv \n };\n } catch (e) {\n return { \n success: false, \n error: e.message \n };\n }\n};\n\n// Run tests directly and collect results\nconst runTests = (implementations) => {\n const testResults = {};\n \n // Initialize results for each implementation\n Object.keys(implementations).forEach(implName => {\n testResults[implName] = {\n passed: 0,\n failed: 0,\n skipped: 0,\n total: 0\n };\n });\n \n // Test each implementation\n Object.entries(implementations).forEach(([implName, impl]) => {\n console.log(`Testing implementation: ${implName}`);\n \n // Skip implementations with errors\n if (impl.errors && impl.errors.length > 0) {\n console.log(`Implementation ${implName} has errors:`, impl.errors);\n testResults[implName].skipped += 1;\n testResults[implName].total += 1;\n return;\n }\n \n // Execute the implementation to test it\n const result = executeImplementation(impl.source);\n\n // If execution failed, mark as failed\n if (!result.success) {\n console.log(`Implementation ${implName} execution failed:`, result.error);\n\n // For implementations that fail due to variable redeclaration,\n // try to modify the code to remove the redeclaration\n if (result.error.includes(\"already been declared\")) {\n console.log(`Attempting to fix ${implName} for variable redeclaration...`);\n\n // Modify code to remove redeclaration issues\n // Replace 'const world = ' with 'world = ' for second declaration\n const fixedSource = impl.source.replace(/import.*?from.*?;/g, '// imports removed')\n .replace(/const\\s+world\\s*=\\s*Globe\\(\\)/, 'const world = Globe()')\n .replace(/const\\s+world\\s*=\\s*new\\s+Globe/, 'world = new Globe');\n\n const fixedResult = executeImplementation(fixedSource);\n\n if (fixedResult.success) {\n console.log(`Fixed ${implName} successfully!`);\n\n // Execution test passed\n testResults[implName].passed += 1;\n testResults[implName].total += 1;\n\n // Continue with the fixed result\n const env = fixedResult.env;\n\n // Test: Globe constructor\n const globeTest = env.Globe.mock.calls.length > 0;\n if (globeTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n // Only continue if Globe was called\n if (!globeTest) return;\n\n // Get Globe instance\n const globeInstance = env.Globe.mock.results[0].value;\n\n // Test: countries data\n const countriesTest = globeInstance.polygonsData.mock.calls.length > 0;\n if (countriesTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n // Test: fetch for country data\n const fetchTest = env.fetch.mock.calls.length > 0 &&\n env.fetch.mock.calls[0][0].match(/countries|geojson/i);\n if (fetchTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n // Test: styling\n const stylingTest = globeInstance.polygonAltitude.mock.calls.length > 0 &&\n globeInstance.polygonCapColor.mock.calls.length > 0 &&\n globeInstance.polygonSideColor.mock.calls.length > 0 &&\n globeInstance.polygonStrokeColor.mock.calls.length > 0;\n if (stylingTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n // Test: interaction\n const interactionTest = globeInstance.onPolygonHover.mock.calls.length > 0 &&\n globeInstance.polygonLabel.mock.calls.length > 0;\n if (interactionTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n return;\n } else {\n console.log(`Failed to fix ${implName}:`, fixedResult.error);\n }\n }\n\n testResults[implName].failed += 1;\n testResults[implName].total += 1;\n return;\n }\n \n // Execution test passed\n testResults[implName].passed += 1;\n testResults[implName].total += 1;\n \n // Get the environment for more tests\n const env = result.env;\n \n // Test: Globe constructor\n const globeTest = env.Globe.mock.calls.length > 0;\n if (globeTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n \n // Only continue if Globe was called\n if (!globeTest) return;\n \n // Get Globe instance\n const globeInstance = env.Globe.mock.results[0].value;\n \n // Test: countries data\n const countriesTest = globeInstance.polygonsData.mock.calls.length > 0;\n if (countriesTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n \n // Test: fetch for country data\n const fetchTest = env.fetch.mock.calls.length > 0 && \n env.fetch.mock.calls[0][0].match(/countries|geojson/i);\n if (fetchTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n \n // Test: styling\n const stylingTest = globeInstance.polygonAltitude.mock.calls.length > 0 &&\n globeInstance.polygonCapColor.mock.calls.length > 0 &&\n globeInstance.polygonSideColor.mock.calls.length > 0 &&\n globeInstance.polygonStrokeColor.mock.calls.length > 0;\n if (stylingTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n \n // Test: interaction\n const interactionTest = globeInstance.onPolygonHover.mock.calls.length > 0 &&\n globeInstance.polygonLabel.mock.calls.length > 0;\n if (interactionTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n });\n \n return testResults;\n};\n\n// Find winner\nconst determineWinner = (results) => {\n let winner = -1;\n let maxPassed = -1;\n \n Object.entries(results).forEach(([implName, stats]) => {\n if (stats.passed > maxPassed) {\n maxPassed = stats.passed;\n const match = implName.match(/(\\d+)/);\n if (match) {\n winner = parseInt(match[1], 10);\n }\n }\n });\n \n return winner;\n};\n\n// Main test\ndescribe('Globe Implementation Tests', () => {\n // Use Jest's fake timers for more control\n jest.useFakeTimers();\n\n // Get implementations\n const implementations = findImplementations();\n const instruction = getInstruction();\n\n console.log(`Found ${Object.keys(implementations).length} implementations to test`);\n console.log(`Instruction: \"${instruction}\"`);\n\n let testResults = {};\n\n // Run a single test to satisfy Jest\n test('Implementations tested successfully', () => {\n // Direct test execution outside Jest\n testResults = runTests(implementations);\n\n // Determine winner\n const winner = determineWinner(testResults);\n\n // Check if all tests were skipped\n const allSkipped = Object.values(testResults).every(\n stats => stats.total === stats.skipped\n );\n\n // Create final results\n const finalResults = {\n winner,\n all_skipped: allSkipped,\n results: testResults\n };\n\n // Save results\n const resultPath = path.resolve(__dirname, '..', 'test_results.json');\n fs.writeFileSync(resultPath, JSON.stringify(finalResults, null, 2));\n console.log('Test results saved to test_results.json');\n\n // Run any pending timers and promises\n jest.runAllTimers();\n\n // Always pass the test\n expect(true).toBe(true);\n });\n\n // Cleanup after all tests\n afterAll(() => {\n // Clear any remaining timers\n jest.clearAllTimers();\n\n // If you're still seeing hanging tests, try providing additional cleanup\n if (global.gc) {\n global.gc(); // Force garbage collection if available\n }\n });\n});", "highlighted_code": "", "instruction": "take the globe countries layer from below \"// this\" and add it to the existing globe", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest --forceExit\"\n },\n \"devDependencies\": {\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"./jest-setup.js\"],\n \"testEnvironment\": \"node\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"collectCoverage\": false,\n \"transformIgnorePatterns\": [],\n \"moduleNameMapper\": {\n \"^three$\": \"/__mocks__/three.js\",\n \"^d3$\": \"/__mocks__/d3.js\",\n \"\\\\.png$\": \"/__mocks__/fileMock.js\",\n \"\\\\.jpg$\": \"/__mocks__/fileMock.js\"\n }\n }\n}", "jest_setup": "// jest-setup.js\n// This file is intentionally empty as we now handle all testing in test_code.test.js", "other_files": {"__mocks__/globe.js": "// Mock for Globe function\nclass GlobeInstance {\n constructor(domElement) {\n this._domElement = domElement;\n this._properties = {\n globeImageUrl: '',\n bumpImageUrl: '',\n backgroundImageUrl: '',\n polygonsData: [],\n polygonAltitude: 0,\n polygonCapColor: null,\n polygonSideColor: null,\n polygonStrokeColor: null,\n polygonLabel: null,\n polygonsTransitionDuration: 0,\n lineHoverPrecision: 0\n };\n this._globeMaterial = {\n specularMap: null,\n specular: null,\n shininess: 0\n };\n this._lights = [\n { type: 'AmbientLight' },\n { type: 'DirectionalLight', position: { set: jest.fn() } }\n ];\n this._countriesLayerAdded = false;\n }\n\n // Chainable methods\n globeImageUrl(url) {\n this._properties.globeImageUrl = url;\n return this;\n }\n \n bumpImageUrl(url) {\n this._properties.bumpImageUrl = url;\n return this;\n }\n \n backgroundImageUrl(url) {\n this._properties.backgroundImageUrl = url;\n return this;\n }\n \n globeMaterial() {\n return this._globeMaterial;\n }\n \n lights() {\n return this._lights;\n }\n \n polygonsData(data) {\n this._properties.polygonsData = data;\n this._countriesLayerAdded = true;\n return this;\n }\n \n polygonAltitude(altitude) {\n if (typeof altitude === 'function') {\n this._properties.polygonAltitudeFunc = altitude;\n } else {\n this._properties.polygonAltitude = altitude;\n }\n return this;\n }\n \n polygonCapColor(colorFn) {\n this._properties.polygonCapColor = colorFn;\n return this;\n }\n \n polygonSideColor(colorFn) {\n this._properties.polygonSideColor = colorFn;\n return this;\n }\n \n polygonStrokeColor(colorFn) {\n this._properties.polygonStrokeColor = colorFn;\n return this;\n }\n \n polygonLabel(labelFn) {\n this._properties.polygonLabel = labelFn;\n return this;\n }\n \n onPolygonHover(hoverFn) {\n this._properties.onPolygonHover = hoverFn;\n return this;\n }\n \n polygonsTransitionDuration(duration) {\n this._properties.polygonsTransitionDuration = duration;\n return this;\n }\n \n lineHoverPrecision(precision) {\n this._properties.lineHoverPrecision = precision;\n return this;\n }\n \n // Allow checking if countries layer was added\n hasCountriesLayer() {\n return this._countriesLayerAdded;\n }\n}\n\nfunction Globe(domElement) {\n const instance = new GlobeInstance(domElement);\n \n // Make the instance callable to support the syntax:\n // Globe()....(domElement)\n const callable = function(domElement) {\n instance._domElement = domElement;\n return instance;\n };\n \n // Copy all properties and methods from instance to callable\n Object.setPrototypeOf(callable, instance);\n Object.getOwnPropertyNames(GlobeInstance.prototype).forEach(name => {\n if (name !== 'constructor') {\n callable[name] = instance[name].bind(instance);\n }\n });\n \n return callable;\n}\n\nmodule.exports = Globe;", "__mocks__/fetch.js": "// Mock for fetch\nglobal.fetch = jest.fn().mockImplementation((url) => {\n // Sample GeoJSON data\n const mockCountries = {\n features: [\n {\n properties: {\n ISO_A2: \"US\",\n ADMIN: \"United States\",\n GDP_MD_EST: 19490000,\n POP_EST: 326625791\n }\n },\n {\n properties: {\n ISO_A2: \"AQ\",\n ADMIN: \"Antarctica\",\n GDP_MD_EST: 0,\n POP_EST: 1000\n }\n },\n {\n properties: {\n ISO_A2: \"DE\",\n ADMIN: \"Germany\",\n GDP_MD_EST: 3677000,\n POP_EST: 80594017\n }\n }\n ]\n };\n\n return Promise.resolve({\n json: () => Promise.resolve(mockCountries)\n });\n});\n\n// Mock for requestAnimationFrame\nglobal.requestAnimationFrame = jest.fn(callback => setTimeout(callback, 0));", "__mocks__/three.js": "// Mock for Three.js\nclass Color {\n constructor(color) {\n this.color = color;\n }\n}\n\nclass TextureLoader {\n load(url, callback) {\n if (callback) {\n const mockTexture = { isTexture: true };\n setTimeout(() => callback(mockTexture), 0);\n }\n return { isTexture: true };\n }\n}\n\nmodule.exports = {\n Color,\n TextureLoader\n};", "__mocks__/fileMock.js": "// Mock for image files\nmodule.exports = 'mock-file';", "__mocks__/d3.js": "// Mock for d3.js\nfunction scaleSequentialSqrt(interpolator) {\n const scale = {\n domain: function(domain) {\n scale._domain = domain;\n return scale;\n },\n _domain: [0, 1],\n _interpolator: interpolator,\n __type__: 'scaleSequentialSqrt'\n };\n \n // Make the scale callable\n const fn = (value) => {\n // Simple linear mapping from domain to range [0, 1]\n if (scale._domain[0] === scale._domain[1]) return 0.5;\n const normalized = (value - scale._domain[0]) / (scale._domain[1] - scale._domain[0]);\n return Math.max(0, Math.min(1, normalized));\n };\n \n // Copy properties from scale to fn\n Object.setPrototypeOf(fn, scale);\n return fn;\n}\n\nconst interpolateYlOrRd = (t) => `rgba(255, ${Math.floor(255 * (1-t))}, 0, 1)`;\n\nmodule.exports = {\n scaleSequentialSqrt,\n interpolateYlOrRd\n};", "__mocks__/document.js": "// Mock for document\nconst document = {\n getElementById: function(id) {\n return { id: id, type: 'DOM_ELEMENT' };\n }\n};\n\nmodule.exports = document;", ".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(ls:*)\",\n \"Bash(mkdir:*)\",\n \"Bash(npm test)\",\n \"Bash(npm install:*)\"\n ],\n \"deny\": []\n }\n}"}, "split": "test"} -{"problem_id": 111, "programming_language": "javascript", "original_code": "import React from 'react';\nimport styles from './CharacterStatUI.module.css';\nimport Sprite from '../sprite/Sprite';\nimport SingleCharacterStatUI from '../single-character-stat-ui/SingleCharacterStatUI';\nimport MockChild from '../mock-child/MockChild';\n\nconst CharacterStatUI = ({ charName, level, wpn, hp, atk, spd, def, res }) => {\n const characterStats = [\n { characterStatType: 'NAME', characterStatValue: charName },\n { characterStatType: 'LV', characterStatValue: level },\n { characterStatType: 'WPN', characterStatValue: wpn },\n { characterStatType: 'HP', characterStatValue: hp },\n { characterStatType: 'ATK', characterStatValue: atk },\n { characterStatType: 'SPD', characterStatValue: spd },\n { characterStatType: 'DEF', characterStatValue: def },\n { characterStatType: 'RES', characterStatValue: res },\n ];\n\n console.log('Character Stats:', {\n charName,\n level,\n wpn,\n hp,\n atk,\n spd,\n def,\n res\n });\n\n const characterStatsSlice1 = characterStats.slice(0, 4);\n const characterStatsSlice2 = characterStats.slice(4);\n\n return (\n
\n
\n \n
\n
\n {characterStatsSlice1.map((item, index) => (\n \n ))}\n
\n
\n {characterStatsSlice2.map((item, index) => (\n \n ))}\n
\n
\n );\n};\n\nexport default CharacterStatUI;\n\n\n// \n", "test_code": "import React from 'react';\nimport { render, screen } from '@testing-library/react';\nimport '@testing-library/jest-dom';\nimport fs from 'fs';\nimport path from 'path';\n\n// Import the implementations directly from the setup file\nconst { implementations, resultsManager } = require('../jest-setup');\n\n// Testing parameters\nconst testParams = {\n charName: 'Alfonse',\n level: 40,\n wpn: 'Sword',\n hp: 45,\n atk: 35,\n spd: 25,\n def: 30,\n res: 20\n};\n\n// Run basic test to make sure setup works\ntest('Basic test works', () => {\n expect(true).toBe(true);\n});\n\n// Test that implementations were loaded\ntest('Implementations are loaded', () => {\n expect(implementations).toBeDefined();\n expect(Object.keys(implementations).length).toBeGreaterThan(0);\n});\n\n// Test each implementation\nObject.keys(implementations).forEach(implName => {\n describe(`Implementation: ${implName}`, () => {\n const implModule = implementations[implName];\n \n test(`${implName} - Module loads without errors`, () => {\n const hasErrors = implModule.__errors__ && implModule.__errors__.length > 0;\n \n if (hasErrors) {\n const errorMessage = implModule.__errors__.map(e => e.message).join(', ');\n resultsManager.recordResult(implName, 'module_load', false, errorMessage);\n // Just log error but don't fail test - we want to record result\n console.error(`Module ${implName} failed to load: ${errorMessage}`);\n }\n \n resultsManager.recordResult(implName, 'module_load', !hasErrors);\n expect(hasErrors).toBe(false);\n });\n \n // Skip other tests if module has errors\n if (implModule.__errors__ && implModule.__errors__.length > 0) {\n return;\n }\n \n test(`${implName} - Component is defined`, () => {\n const CharacterStatUI = implModule.default;\n const componentDefined = typeof CharacterStatUI === 'function';\n \n resultsManager.recordResult(implName, 'component_defined', componentDefined);\n expect(componentDefined).toBe(true);\n });\n \n test(`${implName} - Component renders without errors`, () => {\n const CharacterStatUI = implModule.default;\n \n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'component_renders', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n \n try {\n render();\n resultsManager.recordResult(implName, 'component_renders', true);\n expect(true).toBe(true);\n } catch (error) {\n resultsManager.recordResult(implName, 'component_renders', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Component renders all character stats`, () => {\n const CharacterStatUI = implModule.default;\n \n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'renders_all_stats', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n \n try {\n render();\n const charStats = screen.getAllByTestId('character-stat');\n \n resultsManager.recordResult(implName, 'renders_all_stats', charStats.length === 8);\n expect(charStats.length).toBe(8);\n } catch (error) {\n resultsManager.recordResult(implName, 'renders_all_stats', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Component renders the Sprite component or MockChild`, () => {\n const CharacterStatUI = implModule.default;\n\n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'renders_sprite', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n\n try {\n render();\n // Check for either direct Sprite or MockChild\n const sprite = screen.queryByTestId('sprite-component');\n const mockChild = screen.queryByTestId('mock-child');\n\n const hasSprite = !!sprite;\n const hasMockChild = !!mockChild && mockChild.getAttribute('data-component-name') === 'CharacterStatPortrait';\n\n // For original code, we only expect MockChild\n if (implName === 'original_code') {\n resultsManager.recordResult(implName, 'renders_sprite', hasMockChild);\n expect(hasMockChild).toBe(true);\n } else {\n // For implementations, we expect direct Sprite\n resultsManager.recordResult(implName, 'renders_sprite', hasSprite);\n expect(hasSprite).toBe(true);\n }\n } catch (error) {\n resultsManager.recordResult(implName, 'renders_sprite', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Sprite has the correct spriteName prop`, () => {\n const CharacterStatUI = implModule.default;\n\n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'sprite_correct_name', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n\n try {\n render();\n\n // For original code, we need to check differently\n if (implName === 'original_code') {\n const mockChild = screen.queryByTestId('mock-child');\n const characterName = mockChild?.getAttribute('data-character-name');\n\n // In the original code, the character name should be Alfonse in the MockChild\n resultsManager.recordResult(implName, 'sprite_correct_name', characterName === 'Alfonse');\n expect(characterName).toBe('Alfonse');\n } else {\n // For implementations, check the Sprite component\n const sprite = screen.queryByTestId('sprite-component');\n const spriteName = sprite?.getAttribute('data-sprite-name');\n\n resultsManager.recordResult(implName, 'sprite_correct_name', spriteName === 'PortraitAlfonse');\n expect(spriteName).toBe('PortraitAlfonse');\n }\n } catch (error) {\n resultsManager.recordResult(implName, 'sprite_correct_name', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Sprite container has overflow hidden`, () => {\n const CharacterStatUI = implModule.default;\n\n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'has_overflow_hidden', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n\n try {\n const { container } = render();\n\n // For original code, we fail this test since it's not implementing the requirement\n if (implName === 'original_code') {\n // Original code doesn't directly use Sprite so it fails this requirement\n resultsManager.recordResult(implName, 'has_overflow_hidden', false, 'Original code does not implement this requirement');\n throw new Error('Original code does not implement this requirement');\n }\n\n const sprite = screen.getByTestId('sprite-component');\n\n // Check if the sprite or its parent has overflow hidden\n let overflowHidden = false;\n let element = sprite;\n\n // Check the sprite itself\n if (element.style.overflow === 'hidden') {\n overflowHidden = true;\n }\n\n // Check parent elements (up to 3 levels)\n for (let i = 0; i < 3; i++) {\n if (element.parentElement) {\n element = element.parentElement;\n if (element.style.overflow === 'hidden') {\n overflowHidden = true;\n break;\n }\n } else {\n break;\n }\n }\n\n resultsManager.recordResult(implName, 'has_overflow_hidden', overflowHidden);\n expect(overflowHidden).toBe(true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_overflow_hidden', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Sprite has proper width/height styling`, () => {\n const CharacterStatUI = implModule.default;\n\n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'has_sizing_styles', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n\n try {\n render();\n\n // For original code, we fail this test since it's not implementing the requirement\n if (implName === 'original_code') {\n // Original code doesn't directly use Sprite so it fails this requirement\n resultsManager.recordResult(implName, 'has_sizing_styles', false, 'Original code does not implement this requirement');\n throw new Error('Original code does not implement this requirement');\n }\n\n const sprite = screen.getByTestId('sprite-component');\n\n // Check if the sprite or its parent has styles to make it fit\n let hasSizingStyles = false;\n\n // Check if the sprite itself has width/height styles\n if (sprite.style.width === '100%' || sprite.style.height === '100%') {\n hasSizingStyles = true;\n }\n\n resultsManager.recordResult(implName, 'has_sizing_styles', hasSizingStyles);\n expect(hasSizingStyles).toBe(true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_sizing_styles', false, error.message);\n throw error;\n }\n });\n });\n});\n\n// After all tests complete, make sure test_results.json is created\nafterAll(() => {\n // Save test results\n try {\n if (resultsManager) {\n resultsManager.saveResults();\n } else {\n // Fallback if resultsManager is not available\n console.error('ResultsManager not available, cannot save test results');\n }\n } catch (error) {\n console.error('Error saving test results:', error);\n }\n});", "highlighted_code": "import React from 'react';\nimport styles from './CharacterStatUI.module.css';\nimport Sprite from '../sprite/Sprite';\nimport SingleCharacterStatUI from '../single-character-stat-ui/SingleCharacterStatUI';\nimport MockChild from '../mock-child/MockChild';\n\nconst CharacterStatUI = ({ charName, level, wpn, hp, atk, spd, def, res }) => {\n const characterStats = [\n { characterStatType: 'NAME', characterStatValue: charName },\n { characterStatType: 'LV', characterStatValue: level },\n { characterStatType: 'WPN', characterStatValue: wpn },\n { characterStatType: 'HP', characterStatValue: hp },\n { characterStatType: 'ATK', characterStatValue: atk },\n { characterStatType: 'SPD', characterStatValue: spd },\n { characterStatType: 'DEF', characterStatValue: def },\n { characterStatType: 'RES', characterStatValue: res },\n ];\n\n console.log('Character Stats:', {\n charName,\n level,\n wpn,\n hp,\n atk,\n spd,\n def,\n res\n });\n\n const characterStatsSlice1 = characterStats.slice(0, 4);\n const characterStatsSlice2 = characterStats.slice(4);\n\n return (\n
\n
\n \n
\n
\n {characterStatsSlice1.map((item, index) => (\n \n ))}\n
\n
\n {characterStatsSlice2.map((item, index) => (\n \n ))}\n
\n
\n );\n};\n\nexport default CharacterStatUI;\n\n\n// \n", "instruction": "The following is the CSS style of the React component: ```css .characterTable { display: grid; grid-template-columns: auto 1fr 1fr; grid-template-rows: 1fr; gap: 0px; width: 100%; max-width: 800px; margin: 0 auto; isolation: isolate; } .characterCell { display: flex; flex-direction: column; gap: 0px; overflow: hidden; } .characterHeader { font-size: 20px; font-weight: bold; margin-bottom: 8px; } .characterLevel { font-size: 16px; font-weight: bold; margin-bottom: 8px; } .statContainer { position: relative; display: inline-block; width: 100%; height: 100%; background-size: cover; background-position: center; z-index: 0; margin-bottom: 0; } .statText { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; text-align: center; font-size: 16px; color: white; font-weight: bold; z-index: 1; } .Sprite[spriteName=\"PortraitAlfonse\"] { /*This selector targets the specific sprite*/ display: flex; align-items: center; padding-left: 8px; box-sizing: border-box; width: 20vw; height: 40px; min-width: 144px; /* 720 * 0.2 */ min-height: 204.8px; /* 1280 * 0.16 */ } ``` Please make the component to fill inside the , fit to width or height and the rest overflow hidden.", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest --config jest.config.js\"\n },\n \"devDependencies\": {\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\",\n \"@testing-library/react\": \"^14.0.0\",\n \"@testing-library/jest-dom\": \"^6.1.4\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"jest-environment-jsdom\": \"^29.7.0\",\n \"@babel/core\": \"^7.22.5\",\n \"@babel/preset-env\": \"^7.22.5\",\n \"@babel/preset-react\": \"^7.22.5\",\n \"babel-jest\": \"^29.7.0\"\n },\n \"jest\": \"./jest.config.js\"\n}", "jest_setup": "// jest-setup.js - Copy this file to each implementation folder\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\nconst { TextEncoder, TextDecoder } = require('util');\n\n// Handle JSX files instead of only JS files\nrequire('@testing-library/jest-dom');\n\nglobal.TextEncoder = TextEncoder;\nglobal.TextDecoder = TextDecoder;\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'modified_code\\\\d+\\\\.(js|jsx)',\n 'new_code\\\\d+\\\\.(js|jsx)',\n 'implementation\\\\d*\\\\.(js|jsx)',\n 'original_code\\\\.(js|jsx)',\n 'original_modified_code\\\\d+\\\\.(js|jsx)'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.{js,jsx}'));\n\n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n // Put original code first\n if (path.basename(a).startsWith('original_code.') && !path.basename(b).startsWith('original_code.')) {\n return -1;\n }\n if (!path.basename(a).startsWith('original_code.') && path.basename(b).startsWith('original_code.')) {\n return 1;\n }\n\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n\n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n\n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __source__: sourceCode, // Store source code for JSX handling\n __errors__: [] // Track errors in the module\n };\n\n try {\n // Skip syntax validation for JSX files - we'll let babel handle that\n if (!filePath.endsWith('.jsx')) {\n // Try to test-compile the code to check for syntax errors\n new Function(sourceCode);\n }\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n console.error(` Line ${e.lineNumber}, column ${e.columnNumber}`);\n\n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.lineNumber,\n columnNumber: e.columnNumber\n });\n }\n\n try {\n // Try to require the module even if there were syntax errors\n // This may or may not succeed\n\n // Clear the require cache to ensure fresh load\n if (require.cache[require.resolve(filePath)]) {\n delete require.cache[require.resolve(filePath)];\n }\n\n const loadedModule = require(filePath);\n\n // Copy all properties from the loaded module\n for (const key in loadedModule) {\n if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {\n moduleObj[key] = loadedModule[key];\n }\n }\n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n console.error(e.stack);\n\n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n\n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n\n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n\n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const implementations = {};\n\n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n\n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n const module = this.loadModule(filePath, moduleName);\n\n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n\n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n\n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = {\n passed: 0,\n failed: 0,\n skipped: 0,\n errors: [],\n // Track tests to ensure we don't count duplicates\n tests: new Set()\n };\n }\n\n // Only count the test once, even if it's recorded multiple times\n if (!this.results[implName].tests.has(testName)) {\n this.results[implName].tests.add(testName);\n\n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n }\n } else {\n // If we've already counted this test but the result changed from pass to fail, update counts\n if (!passed && this.results[implName][testName] === 'passed') {\n this.results[implName].passed -= 1;\n this.results[implName].failed += 1;\n this.results[implName][testName] = 'failed';\n }\n }\n\n // Always record the test state for potential updates\n this.results[implName][testName] = passed ? 'passed' : 'failed';\n\n // Record error if provided\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = {\n passed: 0,\n failed: 0,\n skipped: 0,\n errors: [],\n tests: new Set()\n };\n }\n\n // Only count the test once, even if it's recorded multiple times\n if (!this.results[implName].tests.has(testName)) {\n this.results[implName].tests.add(testName);\n this.results[implName].skipped += 1;\n } else {\n // If test was previously passed or failed, update counts\n if (this.results[implName][testName] === 'passed') {\n this.results[implName].passed -= 1;\n this.results[implName].skipped += 1;\n } else if (this.results[implName][testName] === 'failed') {\n this.results[implName].failed -= 1;\n this.results[implName].skipped += 1;\n }\n }\n\n // Record the test state\n this.results[implName][testName] = 'skipped';\n\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n \n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n \n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n \n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner && /modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n \n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n \n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n \n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n // Use the size of the tests Set to get an accurate count of total tests\n const totalTests = stats.tests ? stats.tests.size : stats.passed + stats.failed + stats.skipped;\n\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: totalTests\n };\n }\n }\n \n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n \n return output;\n }\n}\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n\n // Attach to global object for direct access in tests\n global.TestUtils = TestUtils;\n global.implementations = implementations;\n global.resultsManager = resultsManager;\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n implementations,\n resultsManager\n};", "babel_config": "module.exports = {\n presets: [\n [\n '@babel/preset-env',\n {\n targets: {\n node: 'current',\n },\n },\n ],\n '@babel/preset-react',\n ],\n};", "other_files": {"jest.config.js": "module.exports = {\n setupFilesAfterEnv: ['./jest-setup.js'],\n testEnvironment: 'jsdom',\n testMatch: ['**/tests/**/*.test.js'],\n verbose: true,\n collectCoverage: true,\n coverageDirectory: './coverage',\n collectCoverageFrom: [\n './*.jsx',\n '!jest-setup.js',\n '!babel.config.js',\n '!jest.config.js'\n ],\n moduleNameMapper: {\n '\\\\.module\\\\.css$': '/__mocks__/styleMock.js',\n '\\\\.css$': '/__mocks__/styleMock.js',\n '^../sprite/Sprite$': '/__mocks__/Sprite.js',\n '^../single-character-stat-ui/SingleCharacterStatUI$': '/__mocks__/SingleCharacterStatUI.js',\n '^../mock-child/MockChild$': '/__mocks__/MockChild.js'\n },\n transform: {\n '^.+\\\\.(js|jsx)$': 'babel-jest'\n }\n};", "__mocks__/SingleCharacterStatUI.js": "import React from 'react';\n\nconst SingleCharacterStatUI = ({ characterStatType, characterStatValue, backgroundColor }) => {\n return (\n
\n {characterStatType}: {characterStatValue}\n
\n );\n};\n\nexport default SingleCharacterStatUI;", "__mocks__/MockChild.js": "import React from 'react';\n\nconst MockChild = ({ componentName, characterName, children }) => {\n return (\n
\n {children}\n
\n );\n};\n\nexport default MockChild;", "__mocks__/styleMock.js": "// Mock for CSS modules\nmodule.exports = {};", "__mocks__/Sprite.js": "import React from 'react';\n\nconst Sprite = ({ spriteName, style }) => {\n return (\n
\n {spriteName}\n
\n );\n};\n\nexport default Sprite;", ".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(mkdir:*)\",\n \"Bash(npm install:*)\",\n \"Bash(npm test)\"\n ],\n \"deny\": []\n }\n}"}, "split": "test"} -{"problem_id": 112, "programming_language": "javascript", "original_code": "import React from 'react';\nimport { Meta, Story } from '@storybook/react';\nimport CharacterStatUI from './CharacterStatUI';\n\nexport default {\n title: 'CharacterStatUI',\n component: CharacterStatUI\n};\n\nconst Template = (args) => ;\n\nexport const Default = Template.bind({});\nDefault.args = {};\n", "test_code": "// tests/test_code.test.js\ndescribe('Storybook CharacterStatUI implementation tests', () => {\n // Basic initialization test\n test('Global test variables should be defined', () => {\n expect(global.__TEST_UTILS__).toBeDefined();\n expect(global.__RESULTS_MANAGER__).toBeDefined();\n expect(global.__IMPLEMENTATIONS__).toBeDefined();\n \n // Log implementation information for debugging\n console.log('Implementation count:', Object.keys(global.__IMPLEMENTATIONS__ || {}).length);\n \n // Create a basic test result for each implementation\n const implementations = global.__IMPLEMENTATIONS__ || {};\n Object.keys(implementations).forEach(implName => {\n if (implName !== 'original_code') {\n global.__RESULTS_MANAGER__.recordResult(implName, 'test_setup', true);\n }\n });\n });\n \n // Detailed implementation tests\n describe('Implementation specific tests', () => {\n let implementations;\n let resultsManager;\n \n beforeAll(() => {\n implementations = global.__IMPLEMENTATIONS__ || {};\n resultsManager = global.__RESULTS_MANAGER__;\n });\n \n // Test for Storybook structure according to requirements\n test('Each implementation should have the correct Storybook structure', () => {\n Object.entries(implementations).forEach(([implName, impl]) => {\n\n const testName = 'storybook_structure';\n\n try {\n // Check if implementation has errors\n if (impl.__errors__ && impl.__errors__.length > 0) {\n console.warn(`Implementation ${implName} has errors:`, impl.__errors__);\n resultsManager.recordSkip(implName, testName, 'Implementation has syntax or loading errors');\n return;\n }\n \n // Check for Default export with correct properties\n expect(impl.default).toBeDefined();\n expect(impl.default.title).toBe('CharacterStatUI');\n expect(impl.default.component).toBeDefined();\n \n // Check for Default story\n expect(impl.Default).toBeDefined();\n \n // If Template is defined, check that it's a function \n // (the Template might be created inline in the Template.bind() call)\n if (impl.Template) {\n expect(typeof impl.Template).toBe('function');\n }\n \n // Record success\n resultsManager.recordResult(implName, testName, true);\n } catch (e) {\n // Record failure with error message\n resultsManager.recordResult(implName, testName, false, e.message);\n console.error(`Implementation ${implName} failed structure test:`, e.message);\n }\n });\n });\n \n // Test for required parameters according to instruction.txt\n test('Each implementation should provide required parameters', () => {\n Object.entries(implementations).forEach(([implName, impl]) => {\n\n const testName = 'required_parameters';\n\n try {\n // Skip if implementation has errors\n if (impl.__errors__ && impl.__errors__.length > 0) {\n resultsManager.recordSkip(implName, testName, 'Implementation has syntax or loading errors');\n return;\n }\n \n // Check for parameters in Default.args or default.parameters\n let params = impl.Default.args || {};\n if (Object.keys(params).length === 0 && impl.default.parameters) {\n params = impl.default.parameters;\n }\n \n // Test required parameters from instruction.txt\n expect(Object.keys(params).length).toBeGreaterThan(0);\n expect(params.name).toBe('Alfonse');\n expect(params.level).toBe(40);\n \n // Check if \"Folkvangr\" exists in any parameter value\n const paramValues = Object.values(params);\n const hasFollkvangr = paramValues.includes('Folkvangr');\n expect(hasFollkvangr).toBe(true);\n \n // Stats parameters\n expect(params.wpn).toBe(50);\n expect(params.atk).toBe(50);\n expect(params.spd).toBe(50);\n expect(params.def).toBe(30);\n expect(params.res).toBe(30);\n \n // Record success\n resultsManager.recordResult(implName, testName, true);\n } catch (e) {\n // Record failure with error message\n resultsManager.recordResult(implName, testName, false, e.message);\n console.error(`Implementation ${implName} failed parameters test:`, e.message);\n }\n });\n });\n });\n});", "instruction": "Please make this Storybook test include the parameters: name=\"Alfonse\", level=40, \"Folkvangr\", wpn=50, atk=50, spd=50, def=30, res=30", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"type\": \"commonjs\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"dependencies\": {\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.23.5\",\n \"@babel/preset-env\": \"^7.23.5\",\n \"@babel/preset-react\": \"^7.23.3\",\n \"@storybook/react\": \"^7.6.0\",\n \"@testing-library/jest-dom\": \"^6.1.5\",\n \"@testing-library/react\": \"^14.1.2\",\n \"babel-jest\": \"^29.7.0\",\n \"glob\": \"^10.4.5\",\n \"jest\": \"^29.7.0\",\n \"jest-environment-jsdom\": \"^29.7.0\",\n \"jest-mock\": \"^29.7.0\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\n \"./jest-setup.js\"\n ],\n \"testEnvironment\": \"jsdom\",\n \"testMatch\": [\n \"**/tests/**/*.test.js\"\n ],\n \"verbose\": true,\n \"collectCoverage\": true,\n \"coverageDirectory\": \"./coverage\",\n \"collectCoverageFrom\": [\n \"./*.{js,jsx}\",\n \"!jest-setup.js\"\n ],\n \"transform\": {\n \"^.+\\\\.(js|jsx)$\": \"babel-jest\"\n },\n \"transformIgnorePatterns\": [\n \"/node_modules/(?!(@storybook|storybook-|@babel/runtime)).+\\\\.js$\"\n ],\n \"moduleNameMapper\": {\n \"\\\\./(CharacterStatUI)$\": \"/mocks/CharacterStatUIMock.jsx\",\n \"^@storybook/(.*)$\": \"/node_modules/@storybook/$1\"\n },\n \"moduleDirectories\": [\n \"node_modules\",\n \"\"\n ]\n },\n \"babel\": {\n \"presets\": [\n [\n \"@babel/preset-env\",\n {\n \"targets\": {\n \"node\": \"current\"\n }\n }\n ],\n [\n \"@babel/preset-react\",\n {\n \"runtime\": \"automatic\"\n }\n ]\n ]\n }\n}", "jest_setup": "// jest-setup.js\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\nconst babel = require('@babel/core');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'original_modified_code\\\\d+\\\\.(js|jsx)',\n 'modified_code\\\\d+\\\\.(js|jsx)',\n 'new_code\\\\d+\\\\.(js|jsx)',\n 'implementation\\\\d*\\\\.(js|jsx)',\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.{js,jsx}'));\n\n for (const filePath of files) {\n const basename = path.basename(filePath);\n if (regexPattern.test(basename) && !basename.startsWith('jest-') && basename !== 'test-results.json') {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Transform ES module code to CommonJS for Jest\n * @param {string} sourceCode - The source code to transform\n * @param {string} filePath - The path to the source file (for source maps)\n * @returns {string} Transformed code\n */\n static transformCode(sourceCode, filePath) {\n try {\n const result = babel.transformSync(sourceCode, {\n filename: filePath,\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' }, modules: 'commonjs' }],\n ['@babel/preset-react', { runtime: 'automatic' }]\n ],\n ast: false,\n sourceMaps: false\n });\n \n return result.code;\n } catch (e) {\n console.error(`Babel transform error for ${filePath}: ${e.message}`);\n // Return original code if transform fails, the require will fail with better errors\n return sourceCode;\n }\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n \n // Create module object with default properties\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: [] // Track errors in the module\n };\n \n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n \n // Create a mock for CharacterStatUI\n this.ensureCharacterStatUIMock();\n \n try {\n // Instead of creating temporary files, we'll parse and evaluate the code directly\n try {\n // In-memory evaluation of the module\n // Since we're in a test environment, we can simulate the module structure\n\n // Create a basic module structure with default properties\n moduleObj.default = {\n title: 'CharacterStatUI',\n component: {\n name: 'CharacterStatUI'\n }\n };\n\n // Extract the Default.args from the source code\n const argsMatch = sourceCode.match(/Default\\.args\\s*=\\s*({[^;]*});/);\n if (argsMatch && argsMatch[1]) {\n try {\n // Create a safe evaluation context for the args\n // This is a simple approach - in production we'd use a proper sandbox\n moduleObj.Default = {\n name: 'bound Template',\n args: {}\n };\n\n // Parse the args object\n const argsText = argsMatch[1].replace(/[\\r\\n]/g, '');\n // Extract key-value pairs with a basic regex\n const keyValuePairs = argsText.match(/(\\w+)\\s*:\\s*([^,}]+)/g) || [];\n\n for (const pair of keyValuePairs) {\n const [key, valueStr] = pair.split(':').map(s => s.trim());\n // Parse the value (handling numbers and strings)\n let value;\n if (valueStr.startsWith('\"') || valueStr.startsWith(\"'\")) {\n // It's a string\n value = valueStr.replace(/^[\"']|[\"']$/g, '');\n } else if (!isNaN(Number(valueStr))) {\n // It's a number\n value = Number(valueStr);\n } else {\n // Default to string\n value = valueStr;\n }\n\n moduleObj.Default.args[key] = value;\n }\n } catch (e) {\n console.error(`Error parsing args for ${implName}:`, e.message);\n }\n }\n\n // Check for parameters in the default export\n const paramsMatch = sourceCode.match(/parameters\\s*:\\s*({[^}]*})/);\n if (paramsMatch && paramsMatch[1]) {\n try {\n moduleObj.default.parameters = {};\n\n // Parse the parameters object\n const paramsText = paramsMatch[1].replace(/[\\r\\n]/g, '');\n // Extract key-value pairs\n const keyValuePairs = paramsText.match(/(\\w+)\\s*:\\s*([^,}]+)/g) || [];\n\n for (const pair of keyValuePairs) {\n const [key, valueStr] = pair.split(':').map(s => s.trim());\n // Parse the value\n let value;\n if (valueStr.startsWith('\"') || valueStr.startsWith(\"'\")) {\n value = valueStr.replace(/^[\"']|[\"']$/g, '');\n } else if (!isNaN(Number(valueStr))) {\n value = Number(valueStr);\n } else {\n value = valueStr;\n }\n\n moduleObj.default.parameters[key] = value;\n }\n } catch (e) {\n console.error(`Error parsing parameters for ${implName}:`, e.message);\n }\n }\n\n // Add React for tests that need it\n moduleObj.React = require('react');\n \n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n\n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n \n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.loc ? e.loc.line : undefined,\n columnNumber: e.loc ? e.loc.column : undefined\n });\n }\n \n return moduleObj;\n } catch (e) {\n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n \n return moduleObj;\n }\n }\n\n /**\n * Ensure the CharacterStatUI mock exists\n */\n static ensureCharacterStatUIMock() {\n const mockDir = path.join(__dirname, 'mocks');\n const mockPath = path.join(mockDir, 'CharacterStatUIMock.jsx');\n \n if (!fs.existsSync(mockDir)) {\n fs.mkdirSync(mockDir, { recursive: true });\n }\n \n if (!fs.existsSync(mockPath)) {\n const mockContent = `\n// Mock implementation of CharacterStatUI\nconst React = require('react');\n\nconst CharacterStatUI = (props) => {\n return React.createElement('div', { 'data-testid': 'character-stat-ui' }, 'CharacterStatUI Mock');\n};\n\nmodule.exports = CharacterStatUI;\n `;\n fs.writeFileSync(mockPath, mockContent);\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const implementations = {};\n\n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n return implementations; // Return empty object rather than null\n }\n\n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n const module = this.loadModule(filePath, moduleName);\n\n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n\n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n \n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n \n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n \n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n \n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner) {\n if (/modified_code(\\d+)/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n } else if (/new_code(\\d+)/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n }\n \n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n \n // Check if all tests were skipped\n let allSkipped = true;\n if (Object.keys(results).length > 0) {\n allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.passed === 0 && stats.failed === 0 && stats.skipped > 0;\n });\n }\n \n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n \n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n \n return output;\n }\n}\n\n// Create the mocks directory and CharacterStatUI mock if they don't exist\nTestUtils.ensureCharacterStatUIMock();\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n\n // Debug log\n console.log('Loaded implementation count:', Object.keys(implementations).length);\n console.log('Implementation keys:', Object.keys(implementations));\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n implementations,\n resultsManager\n};", "other_files": {"highlighted_code.jsx": "import React from 'react';\nimport { Meta, Story } from '@storybook/react';\nimport CharacterStatUI from './CharacterStatUI';\n\nexport default {\n title: 'CharacterStatUI',\n component: CharacterStatUI\n};\n\nconst Template = (args) => ;\n\nexport const Default = Template.bind({});\nDefault.args = {};\n", "mocks/CharacterStatUIMock.jsx": "\n// Mock implementation of CharacterStatUI\nconst React = require('react');\n\nconst CharacterStatUI = (props) => {\n return React.createElement('div', { 'data-testid': 'character-stat-ui' }, 'CharacterStatUI Mock');\n};\n\nmodule.exports = CharacterStatUI;\n ", "mocks/CharacterStatUIMock.js": "\n// Mock implementation of CharacterStatUI\nconst React = require('react');\n\nconst CharacterStatUI = (props) => {\n return React.createElement('div', { 'data-testid': 'character-stat-ui' }, 'CharacterStatUI Mock');\n};\n\nmodule.exports = CharacterStatUI;\n ", ".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(mv:*)\",\n \"Bash(npm install:*)\",\n \"Bash(npm test)\"\n ],\n \"deny\": []\n }\n}"}, "split": "test"} -{"problem_id": 113, "programming_language": "javascript", "original_code": "import React, { useRef, useEffect, useState } from 'react'\nimport { useGetQueryListQuery } from '../../api/query';\nimport { MdOutlineArrowDropDown } from 'react-icons/md';\n\n\n\nconst Query = () => {\n const abortController = useRef(null);\n const [isQueryOpen, setIsQueryOpen] = useState(false);\n const [selectedQuery, setSelectedQuery] = useState(null);\n\n const { data: queries, isFetching: queriesFetching, isLoading: queriesLoading } = useGetQueryListQuery({},\n {\n signal: abortController?.current?.signal\n }\n )\n\n // handleQuerySelect\n const handleQuerySelect = (query) => {\n setSelectedQuery(query);\n setIsQueryOpen(false);\n };\n\n useEffect(() => {\n abortController.current = new AbortController();\n return () => {\n abortController.current.abort();\n };\n }, []);\n\n\n\n\n\n return (\n
\n
\n \n Add new\n \n
\n
\n
\n
\n\n
\n setIsQueryOpen(!isQueryOpen)}\n >\n {selectedQuery?.name || \"Select query\"}\n \n \n {isQueryOpen && queries?.data?.length > 0 && (\n
\n {queries?.data.length === 0 ? (\n
\n No queries available\n
\n ) : (\n queries?.data.map((query) => (\n handleQuerySelect(query)}\n >\n {query.name}\n
\n ))\n )}\n
\n )}\n
\n\n
\n
\n \n )\n}\n\nexport default Query", "test_code": "const fs = require('fs');\nconst path = require('path');\nconst React = require('react');\nconst { render, screen, fireEvent, within } = require('@testing-library/react');\nconst { TestUtils, resultsManager } = require('../jest-setup');\n\n// Import the instruction to check implementations against\nconst instruction = fs.readFileSync(path.join(__dirname, '../instruction.txt'), 'utf8').trim();\n\n// Load implementations directly\nconst implementations = TestUtils.loadAllImplementations();\n\n// For this test, we need to create a component loader\n// that dynamically imports a component from a file\nconst loadReactComponent = async (filePath) => {\n try {\n // Use dynamic import with Babel to load JSX files\n const Component = require(filePath).default;\n return { Component, success: true };\n } catch (error) {\n console.error(`Error loading component from ${filePath}:`, error);\n return { success: false, error: error.message };\n }\n};\n\n// Function to read multiple implementation files and test them\nconst testImplementations = (implementations) => {\n describe('React Component Implementation Tests', () => {\n // Generic tests for all implementations\n Object.keys(implementations).forEach((implName) => {\n const impl = implementations[implName];\n \n describe(`Testing ${implName}`, () => {\n let Component;\n \n // Setup - Loading the component before tests\n beforeAll(async () => {\n try {\n const result = await loadReactComponent(impl.__file__);\n if (result.success) {\n Component = result.Component;\n } else {\n console.error(`Failed to load ${implName}:`, result.error);\n }\n } catch (error) {\n console.error(`Error loading ${implName}:`, error);\n }\n });\n\n // Skip all tests if component couldn't be loaded\n beforeEach(() => {\n if (!Component) {\n resultsManager.recordSkip(implName, 'Component loading', 'Component could not be loaded');\n throw new Error(`Component ${implName} could not be loaded`);\n }\n });\n\n // Test: Component should render without crashing\n test('should render without crashing', () => {\n try {\n render();\n resultsManager.recordResult(implName, 'render_without_crashing', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'render_without_crashing', false, error.message);\n throw error;\n }\n });\n\n // Test: Component should have an \"Add new\" button\n test('should have an \"Add new\" button', () => {\n try {\n render();\n const addButton = screen.getByText('Add new');\n expect(addButton).toBeTruthy();\n resultsManager.recordResult(implName, 'has_add_new_button', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_add_new_button', false, error.message);\n throw error;\n }\n });\n\n // Test: Component should have a dropdown button with default text\n test('should have a dropdown button with default text', () => {\n try {\n render();\n // The dropdown might have the text split across elements\n // or combined with other elements, so we use a more flexible approach\n const buttons = screen.getAllByRole('button');\n const dropdownButton = buttons.find(button =>\n button.textContent.includes('Select query')\n );\n expect(dropdownButton).toBeTruthy();\n resultsManager.recordResult(implName, 'has_dropdown_button', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_dropdown_button', false, error.message);\n throw error;\n }\n });\n\n // Test: Dropdown should open when clicked\n test('should open dropdown when clicked', () => {\n try {\n const { container } = render();\n\n // Find the dropdown button by role and text content\n const buttons = screen.getAllByRole('button');\n const dropdownButton = buttons.find(button =>\n button.textContent.includes('Select query')\n );\n\n // Click to open dropdown\n fireEvent.click(dropdownButton);\n\n // Dropdown should now be visible - look for option presence\n const queryText = screen.getByText('Query 1', { exact: false });\n expect(queryText).toBeInTheDocument();\n\n resultsManager.recordResult(implName, 'dropdown_opens', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'dropdown_opens', false, error.message);\n throw error;\n }\n });\n\n // Test: Should select a query when clicked\n test('should select a query when clicked', () => {\n try {\n render();\n\n // Find the dropdown button by role and content\n const buttons = screen.getAllByRole('button');\n const dropdownButton = buttons.find(button =>\n button.textContent.includes('Select query')\n );\n\n // Open dropdown\n fireEvent.click(dropdownButton);\n\n // Find and click on the second option\n const option2Elements = screen.getAllByText(/Query 2/i);\n const option = option2Elements.find(el =>\n // Look for elements that might be query options\n el.className.includes('cursor-pointer') ||\n // If the query option is within a div with onclick property\n el.closest('div[class*=\"cursor-pointer\"]')\n );\n\n if (!option) {\n throw new Error('Could not find clickable Query 2 option');\n }\n\n fireEvent.click(option);\n\n // After selection, the dropdown button should show the selected query\n const updatedButtons = screen.getAllByRole('button');\n const updatedDropdownButton = updatedButtons.find(button =>\n button.textContent.includes('Query 2')\n );\n\n expect(updatedDropdownButton).toBeTruthy();\n\n resultsManager.recordResult(implName, 'selects_query', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'selects_query', false, error.message);\n throw error;\n }\n });\n\n // Test: Should have a \"Query name\" label\n test('should have a \"Query name\" label', () => {\n try {\n const { container } = render();\n // Look for any element containing the text \"Query name\"\n const labelElements = screen.getAllByText(/Query name/i);\n expect(labelElements.length).toBeGreaterThan(0);\n\n // Find the element that's a label\n const label = labelElements.find(el =>\n el.tagName.toLowerCase() === 'label' ||\n el.getAttribute('role') === 'label'\n );\n\n expect(label).toBeTruthy();\n resultsManager.recordResult(implName, 'has_query_name_label', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_query_name_label', false, error.message);\n throw error;\n }\n });\n\n // Specific tests for the instruction: adjust width according to content\n test('should implement label width according to content', () => {\n try {\n const { container } = render();\n const labelElements = screen.getAllByText(/Query name/i);\n\n // Find the element that's a label\n const label = labelElements.find(el =>\n el.tagName.toLowerCase() === 'label' ||\n el.getAttribute('role') === 'label'\n ) || labelElements[0]; // Fallback to first element if no label found\n\n // Check if there's some kind of width setting in the implementations\n // We'll use several strategies to detect this, looking for CSS classes\n // that adjust width based on content\n\n // Common TailwindCSS classes for width fitting\n const hasFittingClass =\n label.className.includes('w-fit') ||\n label.className.includes('w-auto') ||\n label.className.includes('inline-block') ||\n label.className.includes('whitespace-nowrap') ||\n label.className.includes('inline') ||\n label.className.includes('inline-flex') ||\n label.className.includes('w-min') ||\n label.className.includes('w-max') ||\n label.className.includes('max-w-fit') ||\n label.className.includes('min-w-fit') ||\n label.className.includes('flex-none') ||\n label.className.includes('flex-shrink-0') ||\n label.className.includes('shrink-0');\n\n // Skip this check for original_code which we don't expect to have the width adjustment\n if (implName === 'original_code') {\n // Just record as passed but don't check the actual value\n resultsManager.recordResult(implName, 'has_width_fit_class', true);\n } else {\n // For all other implementations, expect the fitting class to be present\n expect(hasFittingClass).toBe(true);\n resultsManager.recordResult(implName, 'has_width_fit_class', true);\n }\n } catch (error) {\n resultsManager.recordResult(implName, 'has_width_fit_class', false, error.message);\n throw error;\n }\n });\n\n // Test: Dropdown should close after selection\n test('should close dropdown after selection', () => {\n try {\n render();\n\n // Find the dropdown button\n const buttons = screen.getAllByRole('button');\n const dropdownButton = buttons.find(button =>\n button.textContent.includes('Select query')\n );\n\n // Open dropdown\n fireEvent.click(dropdownButton);\n\n // Find and click on first option\n const option1Elements = screen.getAllByText(/Query 1/i);\n const option = option1Elements.find(el =>\n el.className.includes('cursor-pointer') ||\n el.closest('div[class*=\"cursor-pointer\"]')\n );\n\n if (!option) {\n throw new Error('Could not find clickable Query 1 option');\n }\n\n // Before clicking, we should be able to find Query 2\n const query2BeforeClick = screen.queryAllByText(/Query 2/i);\n expect(query2BeforeClick.length).toBeGreaterThan(0);\n\n // Click the option\n fireEvent.click(option);\n\n // After clicking, the dropdown should be closed and Query 2 should not be visible\n // Check for elements that don't have a parent button\n const query2AfterClickVisible = screen.queryAllByText(/Query 2/i).filter(el =>\n !el.closest('button')\n );\n\n expect(query2AfterClickVisible.length).toBe(0);\n\n // The dropdown button should now show Query 1\n const updatedButtons = screen.getAllByRole('button');\n const updatedDropdownButton = updatedButtons.find(button =>\n button.textContent.includes('Query 1')\n );\n\n expect(updatedDropdownButton).toBeTruthy();\n\n resultsManager.recordResult(implName, 'closes_dropdown_after_selection', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'closes_dropdown_after_selection', false, error.message);\n throw error;\n }\n });\n });\n });\n });\n};\n\n// Run tests on all implementations\nif (implementations && Object.keys(implementations).length > 0) {\n console.log(`Found ${Object.keys(implementations).length} implementations to test`);\n testImplementations(implementations);\n} else {\n console.error('No implementations found or implementations are empty');\n\n // Add at least one dummy test to avoid Jest error\n test('dummy test to avoid Jest error', () => {\n expect(true).toBe(true);\n });\n}", "highlighted_code": "", "instruction": "adjust width according to content", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"type\": \"commonjs\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"@babel/preset-env\": \"^7.24.0\",\n \"@babel/preset-react\": \"^7.23.3\",\n \"@testing-library/jest-dom\": \"^6.4.2\",\n \"@testing-library/react\": \"^14.2.1\",\n \"babel-jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\",\n \"jest\": \"^29.7.0\",\n \"jest-environment-jsdom\": \"^29.7.0\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"./jest-setup.js\", \"./jest-dom-setup.js\"],\n \"testEnvironment\": \"jsdom\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"transform\": {\n \"^.+\\\\.(js|jsx)$\": \"babel-jest\"\n },\n \"moduleNameMapper\": {\n \"\\\\.(css|less|scss|sass)$\": \"/__mocks__/styleMock.js\",\n \"\\\\.(jpg|jpeg|png|gif|webp|svg)$\": \"/__mocks__/fileMock.js\",\n \"^../../api/(.*)$\": \"/__mocks__/api/$1\"\n },\n \"collectCoverage\": true,\n \"coverageDirectory\": \"./coverage\",\n \"collectCoverageFrom\": [\n \"./*.jsx\",\n \"!jest-setup.js\"\n ]\n }\n}", "jest_setup": "// jest-setup.js - Setup file for Jest tests\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'modified_code\\\\d+\\\\.jsx',\n 'new_code\\\\d+\\\\.jsx',\n 'original_modified_code\\\\d+\\\\.jsx',\n 'implementation\\\\d*\\\\.jsx',\n 'original_code\\\\.jsx'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.jsx'));\n\n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n // Keep original_code always first\n if (path.basename(a) === 'original_code.jsx') return -1;\n if (path.basename(b) === 'original_code.jsx') return 1;\n\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript or JSX file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n\n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n\n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __source__: sourceCode, // Store source code for testing purposes\n __errors__: [] // Track errors in the module\n };\n\n // For JSX files, we can't easily test-compile, so we'll skip that step\n // and rely on Jest/Babel to handle the JSX transformation\n if (!filePath.endsWith('.jsx')) {\n try {\n // Try to test-compile the code to check for syntax errors\n new Function(sourceCode);\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n console.error(` Line ${e.lineNumber}, column ${e.columnNumber}`);\n\n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.lineNumber,\n columnNumber: e.columnNumber\n });\n }\n }\n\n // For JSX/React components, we'll handle them differently in tests\n // and not attempt to require them directly\n if (filePath.endsWith('.jsx')) {\n moduleObj.__component_file__ = true;\n return moduleObj;\n }\n\n try {\n // Try to require the module even if there were syntax errors\n // This may or may not succeed\n delete require.cache[require.resolve(filePath)];\n const loadedModule = require(filePath);\n\n // Copy all properties from the loaded module\n for (const key in loadedModule) {\n if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {\n moduleObj[key] = loadedModule[key];\n }\n }\n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n console.error(e.stack);\n\n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n\n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n\n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n\n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const implementations = {};\n\n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n\n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n const module = this.loadModule(filePath, moduleName);\n\n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n\n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n\n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n\n for (const [implName, results] of Object.entries(this.results)) {\n // Skip original code when determining winner\n if (implName === \"original_code\" || implName === \"original_codex\") {\n continue;\n }\n\n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n\n // If we have a tie, prefer the modified_code implementations over others\n if (winner) {\n // Create a tie-breaker score that prioritizes implementations based on instruction match\n const tiedImplementations = Object.entries(this.results)\n .filter(([name, res]) =>\n name !== \"original_code\" &&\n name !== \"original_codex\" &&\n res.passed === maxPassed)\n .map(([name, _]) => name);\n\n if (tiedImplementations.length > 1) {\n // First, prefer the modified_code implementations\n const modifiedCodeImpls = tiedImplementations.filter(name =>\n name.startsWith('modified_code'));\n\n if (modifiedCodeImpls.length > 0) {\n // If there are multiple modified_code implementations, pick the first one\n winner = modifiedCodeImpls[0];\n }\n }\n }\n\n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner) {\n if (/modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n } else if (/new_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n }\n\n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n \n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n \n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n \n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n \n return output;\n }\n}\n\n// Create results manager\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n // Load implementations inside the beforeAll to ensure it runs in the Jest environment\n const implementations = TestUtils.loadAllImplementations();\n console.log(`Found ${Object.keys(implementations).length} implementations`);\n\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n resultsManager\n};", "jest_dom_setup": "// Import jest-dom utilities\nrequire('@testing-library/jest-dom');", "babel_config": "module.exports = {\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' } }],\n ['@babel/preset-react', { runtime: 'automatic' }]\n ],\n};", "other_files": {"__mocks__/fileMock.js": "module.exports = 'test-file-stub';", "__mocks__/styleMock.js": "module.exports = {};", ".claude/settings.local.json": "{\n \"permissions\": {\n \"allow\": [\n \"Bash(mkdir:*)\",\n \"Bash(npm install:*)\",\n \"Bash(npm test)\",\n \"Bash(npm test:*)\"\n ],\n \"deny\": []\n }\n}", "__mocks__/react-icons/md.js": "// Mock for MdOutlineArrowDropDown component\nconst MdOutlineArrowDropDown = () => {\n return 'MdOutlineArrowDropDown';\n};\n\nmodule.exports = {\n MdOutlineArrowDropDown\n};", "__mocks__/api/query.js": "// Mock for useGetQueryListQuery hook\nconst mockQueries = {\n data: [\n { id: 1, name: 'Query 1' },\n { id: 2, name: 'Query 2' },\n { id: 3, name: 'Query 3' }\n ]\n};\n\nconst useGetQueryListQuery = (params, options) => {\n return {\n data: mockQueries,\n isFetching: false,\n isLoading: false\n };\n};\n\nmodule.exports = {\n useGetQueryListQuery\n};"}, "split": "test"} +{"problem_id": 105, "programming_language": "javascript", "original_code": "import { messages } from \"./messages.js\";\n\n$().ready(() => {\n const loading = $('.container-loading');\n const payment = $('.payment-section');\n const info = $('.user-info');\n const main = $('.main');\n\n\n// Retrieve values from localStorage\n const storedData = JSON.parse(localStorage.getItem('userData')) || {};\n const { userInfo, paymentInfo } = storedData;\n\n // Use the retrieved data as needed\n console.log('User Info:', userInfo);\n console.log('Payment Info:', paymentInfo);\n\n $('#generateTaxButton').click(() => {\n main.fadeOut(500);\n setTimeout(() => {\n loading.css('display', 'flex');\n\n let lastTimeout = 0;\n messages.forEach(message => {\n lastTimeout = lastTimeout + message.time;\n })\n console.log(`intervalo: ${lastTimeout}`)\n\n const loadMessages = $('#loading-messages');\n messages.forEach(element => {\n console.log(element.text)\n console.log(element.time)\n const timeout = element.time;\n setTimeout(() => {\n loadMessages.text(element.text);\n }, timeout);\n });\n\n setTimeout(() => {\n console.log('pagamento');\n loading.css('display', 'none');\n payment.css('display', 'block');\n info.css('display', 'block');\n }, lastTimeout + 500);\n }, 200);\n });\n});", "test_code": "/**\n * Test suite for jQuery implementations\n * \n * This suite evaluates implementations against two key criteria:\n * 1. Avoiding deprecated $.parseJSON method\n * 2. Using jQuery methods to manipulate data\n */\n\n// Import utilities from jest-setup.js\nconst {\n discoverImplementationFiles,\n countJQueryUsage,\n usesDeprecatedParseJSON,\n recordTestResult,\n originalJQueryCount\n} = require('../jest-setup');\n\n// =====================================================================\n// Main Test Suite\n// =====================================================================\n\ndescribe('jQuery Implementation Tests', () => {\n // Discover implementations\n const implementations = discoverImplementationFiles();\n \n // Log current implementation files\n console.log(\"Testing implementations:\", implementations.map(impl => impl.name).join(', '));\n \n // Test each implementation\n implementations.forEach(impl => {\n describe(`Implementation: ${impl.name}`, () => {\n \n // =====================================================================\n // Test 1: Deprecated Method Check\n // =====================================================================\n test('should not use deprecated $.parseJSON method', () => {\n // Direct source code analysis for $.parseJSON usage\n const usesDeprecated = usesDeprecatedParseJSON(impl.code);\n \n // Record test result\n recordTestResult(impl.name, 'avoids_deprecated_parseJSON', !usesDeprecated);\n \n // Test assertion - with descriptive error message\n if (usesDeprecated) {\n console.warn(`${impl.name} uses deprecated $.parseJSON method`);\n }\n \n expect(usesDeprecated).toBeFalsy();\n });\n \n // =====================================================================\n // Test 2: jQuery Data Manipulation Check\n // =====================================================================\n test('should use jQuery methods to manipulate data', () => {\n // Count jQuery usage in this implementation\n const jQueryUsageCount = countJQueryUsage(impl.code);\n \n // Implementation should have at least the same count of jQuery usage as original code\n // to demonstrate it's properly using jQuery for data manipulation\n const usesJQueryForData = jQueryUsageCount >= originalJQueryCount;\n \n // Also check for localStorage usage (since we want to ensure data is being used)\n const usesLocalStorage = impl.code.includes('localStorage.getItem') && \n (impl.code.includes('userInfo') || \n impl.code.includes('paymentInfo') ||\n impl.code.includes('userData'));\n \n // Log debugging information\n console.log(`${impl.name} jQuery usage: ${jQueryUsageCount} (original: ${originalJQueryCount}), Uses localStorage: ${usesLocalStorage}`);\n \n // Implementation passes if it uses jQuery at least as much as original and accesses localStorage\n const effectivelyUsesJQuery = usesJQueryForData && usesLocalStorage;\n \n recordTestResult(impl.name, 'uses_jquery_for_data', effectivelyUsesJQuery);\n \n // Test assertion\n expect(effectivelyUsesJQuery).toBeTruthy();\n });\n });\n });\n});", "highlighted_code": "// Retrieve values from localStorage\n const storedData = JSON.parse(localStorage.getItem('userData')) || {};\n const { userInfo, paymentInfo } = storedData;\n\n // Use the retrieved data as needed\n console.log('User Info:', userInfo);\n console.log('Payment Info:', paymentInfo);", "instruction": "with jquerry", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\",\n \"@babel/core\": \"^7.21.4\",\n \"@babel/preset-env\": \"^7.21.4\",\n \"babel-jest\": \"^29.7.0\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"/jest-setup.js\"],\n \"testEnvironment\": \"node\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"collectCoverage\": false,\n \"moduleNameMapper\": {\n \"\\\\./messages\\\\.js\": \"/__mocks__/messages.js\"\n },\n \"transform\": {\n \"^.+\\\\.jsx?$\": \"babel-jest\"\n },\n \"transformIgnorePatterns\": [\n \"/node_modules/\",\n \"tagged_code.js\",\n \"highlighted_code.js\"\n ]\n }\n}", "jest_setup": "/**\n * Jest setup file for jQuery implementations tests\n */\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n// =====================================================================\n// Test Utilities\n// =====================================================================\n\n/**\n * Discovers implementation files to test based on naming patterns\n * @returns {Array} Array of implementation objects with name, path, and code\n */\nfunction discoverImplementationFiles() {\n const patterns = [\n 'modified_code\\\\d+\\\\.js',\n 'new_code\\\\d+\\\\.js',\n 'original_modified_code\\\\d+\\\\.js'\n ];\n \n const regexPattern = new RegExp(patterns.join('|'));\n const files = glob.sync(path.join(__dirname, '*.js'));\n \n return files\n .filter(filePath => regexPattern.test(path.basename(filePath)))\n .map(filePath => ({\n name: path.basename(filePath, '.js'),\n path: filePath,\n code: fs.readFileSync(filePath, 'utf8')\n }));\n}\n\n/**\n * Test result tracking system\n */\nconst testResults = {};\nconst testTracking = {}; // Track which tests have been run for each implementation\n\n/**\n * Records test results for a specific implementation\n * @param {string} implementation - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n */\nfunction recordTestResult(implementation, testName, passed) {\n // Initialize implementation results if needed\n if (!testResults[implementation]) {\n testResults[implementation] = { passed: 0, failed: 0, skipped: 0, total: 0 };\n testTracking[implementation] = new Set();\n }\n \n // Check if this test has already been recorded for this implementation\n const testKey = `${testName}`;\n if (testTracking[implementation].has(testKey)) {\n return; // Skip recording duplicate test results\n }\n \n // Mark this test as recorded\n testTracking[implementation].add(testKey);\n \n // Update test counts\n if (passed) {\n testResults[implementation].passed++;\n } else {\n testResults[implementation].failed++;\n }\n \n testResults[implementation].total = \n testResults[implementation].passed + \n testResults[implementation].failed + \n testResults[implementation].skipped;\n}\n\n/**\n * Determines the winner based on test results\n * @returns {number} The winner index or -1 if no winner\n */\nfunction determineWinner() {\n let winner = null;\n let maxPassed = -1;\n let minFailed = Number.MAX_SAFE_INTEGER;\n \n for (const implName in testResults) {\n // Skip original implementations\n if (implName.startsWith('original_')) {\n continue;\n }\n \n const results = testResults[implName];\n \n if (results.passed > maxPassed || \n (results.passed === maxPassed && results.failed < minFailed)) {\n maxPassed = results.passed;\n minFailed = results.failed;\n winner = implName;\n }\n }\n \n // Convert winner to numeric index\n let winnerIndex = -1;\n if (winner) {\n if (winner.startsWith('modified_code')) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1], 10);\n }\n } else if (winner.startsWith('new_code')) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1], 10);\n }\n }\n }\n \n return winnerIndex;\n}\n\n/**\n * Saves test results to JSON file\n * @returns {Object} The test results object\n */\nfunction saveTestResults() {\n const winnerIndex = determineWinner();\n \n const output = {\n winner: winnerIndex,\n all_skipped: false,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(testResults)) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.total\n };\n }\n \n const outputPath = path.join(__dirname, 'test_results.json');\n fs.writeFileSync(outputPath, JSON.stringify(output, null, 2));\n console.log(`Test results saved to test_results.json`);\n \n return output;\n}\n\n/**\n * Counts jQuery usage patterns in code\n * @param {string} code - Source code to analyze\n * @returns {number} Count of jQuery usage patterns\n */\nfunction countJQueryUsage(code) {\n // Count occurrences of $ usage\n // This includes $(selectors), $.method, $(document).ready, etc.\n const dollarSignCount = (code.match(/\\$/g) || []).length;\n \n // Count occurrences of jQuery usage if it's used instead of $\n const jQueryCount = (code.match(/jQuery/g) || []).length;\n \n return dollarSignCount + jQueryCount;\n}\n\n/**\n * Checks if code uses deprecated $.parseJSON method\n * @param {string} code - Source code to analyze\n * @returns {boolean} Whether code uses deprecated $.parseJSON\n */\nfunction usesDeprecatedParseJSON(code) {\n // Look for the exact pattern $.parseJSON or jQuery.parseJSON with proper boundary checks\n const parseJSONPattern = /(\\$|jQuery)\\.parseJSON\\s*\\(/;\n return parseJSONPattern.test(code);\n}\n\n// Load original code for comparison\nconst originalCodePath = path.join(__dirname, 'original_code.js');\nconst originalCode = fs.readFileSync(originalCodePath, 'utf8');\nconst originalJQueryCount = countJQueryUsage(originalCode);\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = {\n discoverImplementationFiles,\n countJQueryUsage,\n usesDeprecatedParseJSON\n };\n global.__TEST_RESULTS__ = {\n testResults,\n testTracking,\n recordTestResult,\n determineWinner, \n saveTestResults\n };\n global.__JQUERY_DATA__ = {\n originalCode,\n originalJQueryCount\n };\n});\n\n// After all tests run, save the results\nafterAll(() => {\n // Display final results before saving\n console.log(\"\\nFinal Test Results:\");\n for (const [name, stats] of Object.entries(testResults)) {\n console.log(`${name}: ${stats.passed} passes, ${stats.failed} fails (total: ${stats.total})`);\n }\n \n const results = saveTestResults();\n console.log(`Winner: ${results.winner !== undefined ? results.winner : 'None'}`);\n});\n\n// Export for use in tests\nmodule.exports = {\n discoverImplementationFiles,\n countJQueryUsage,\n usesDeprecatedParseJSON,\n recordTestResult,\n determineWinner,\n saveTestResults,\n testResults,\n originalJQueryCount\n};", "babel_config": "module.exports = {\n presets: [\n ['@babel/preset-env', {targets: {node: 'current'}}]\n ]\n};", "other_files": {"hidden.js": "import { messages } from \"./messages.js\";\n\n$(() => {\n const $loading = $('.container-loading');\n const $payment = $('.payment-section');\n const $info = $('.user-info');\n const $main = $('.main');\n const $loadMessages = $('#loading-messages');\n\n // Retrieve and display user data using jQuery\n const storedData = JSON.parse(localStorage.getItem('userData')) || {};\n const { userInfo, paymentInfo } = storedData;\n\n console.log('User Info:', userInfo);\n console.log('Payment Info:', paymentInfo);\n\n if (userInfo) {\n $('.user-name').text(userInfo.name || '');\n $('.user-email').text(userInfo.email || '');\n }\n\n if (paymentInfo) {\n $('.payment-amount').text(`$${paymentInfo.amount || '0.00'}`);\n $('.payment-date').text(paymentInfo.date || '');\n }\n\n $('#generateTaxButton').on('click', () => {\n $main.fadeOut(500, () => {\n $loading.css('display', 'flex');\n\n let lastTimeout = 0;\n messages.forEach(msg => {\n lastTimeout += msg.time;\n });\n\n messages.forEach(msg => {\n setTimeout(() => {\n $loadMessages.text(msg.text);\n }, msg.time);\n });\n\n setTimeout(() => {\n $loading.hide();\n $payment.show();\n $info.show();\n }, lastTimeout + 500);\n });\n });\n});\n", "__mocks__/messages.js": "// Mock for messages.js\nexport const messages = [\n { text: \"Loading data...\", time: 1000 },\n { text: \"Processing information...\", time: 2000 },\n { text: \"Calculating taxes...\", time: 3000 },\n { text: \"Finalizing results...\", time: 1500 }\n];", "__mocks__/jquery.js": "// jQuery mock\nconst elementCache = {};\nconst clickHandlers = {};\n\nconst jquery = function(selector) {\n // Cache elements to ensure the same mock instance is returned for the same selector\n if (!elementCache[selector]) {\n elementCache[selector] = {\n selector,\n ready: function(callback) {\n if (typeof callback === 'function') {\n // Store the callback for later execution\n if (!jquery.readyCallbacks) {\n jquery.readyCallbacks = [];\n }\n jquery.readyCallbacks.push(callback);\n }\n return this;\n },\n text: jest.fn(function(value) {\n if (value !== undefined) {\n this.textValue = value;\n return this;\n }\n return this.textValue || '';\n }),\n css: jest.fn(function(prop, value) {\n if (!this.cssProps) this.cssProps = {};\n this.cssProps[prop] = value;\n return this;\n }),\n fadeOut: jest.fn(function(duration) {\n return this;\n }),\n fadeIn: jest.fn(function(duration) {\n return this;\n }),\n click: function(callback) {\n clickHandlers[selector] = callback;\n return this;\n },\n // Method to trigger the click handler\n triggerClick: function() {\n if (typeof clickHandlers[selector] === 'function') {\n clickHandlers[selector]();\n }\n return this;\n }\n };\n }\n\n return elementCache[selector];\n};\n\n// Helper to execute all ready callbacks\njquery.executeReady = function() {\n if (jquery.readyCallbacks) {\n jquery.readyCallbacks.forEach(callback => {\n try {\n callback();\n } catch (e) {\n console.error('Error in ready callback:', e);\n }\n });\n }\n};\n\n// Extend $ with utility methods\njquery.each = jest.fn((obj, callback) => {\n if (obj && typeof callback === 'function') {\n Object.entries(obj).forEach(([key, value]) => {\n callback(key, value);\n });\n }\n});\n\njquery.parseJSON = jest.fn((data) => {\n // This method is deprecated in jQuery - this should cause a test failure\n try {\n return JSON.parse(data);\n } catch (e) {\n throw new Error('Invalid JSON');\n }\n});\n\n// Reset mock function to clear counters\njquery.resetMocks = function() {\n Object.values(elementCache).forEach(el => {\n if (el.text && el.text.mockClear) el.text.mockClear();\n if (el.css && el.css.mockClear) el.css.mockClear();\n if (el.fadeOut && el.fadeOut.mockClear) el.fadeOut.mockClear();\n if (el.fadeIn && el.fadeIn.mockClear) el.fadeIn.mockClear();\n });\n\n jquery.each.mockClear();\n jquery.parseJSON.mockClear();\n};\n\n// Set global $ variable\nglobal.$ = jquery;\n\n// Export both as default and as named export\nmodule.exports = jquery;"}, "split": "test"} +{"problem_id": 106, "programming_language": "javascript", "original_code": "import React, { useEffect, useState, useCallback } from 'react';\nimport styles from './GameUI.module.css';\nimport { useLocation } from 'react-router-dom';\nimport CharacterStatUI from '../character-stat-ui/CharacterStatUI';\nimport Sprite from '../sprite/Sprite';\nimport GameMap from '../game-map/GameMap';\nimport { characterData } from '../character-data/CharacterData';\nimport MapCharacter from '../map-character/MapCharacter';\n\nconst publicFolder = `${process.env.PUBLIC_URL}`;\n\nconst GameUI = () => {\n const location = useLocation();\n const frontPageState = location.state || {};\n const character = frontPageState.character; \n const map = frontPageState.map;\n // UPDATE UI STATES\n\n // Default UI states\n const [characterUIState, setCharacterUIState] = useState({}); \n const [mapState, setMapState] = useState({});\n const [clickedState, setClickedState] = useState(null);\n const [selectedCharacter, setSelectedCharacter] = useState(\"Alfonse\");\n\n const characterNames = [\"Alfonse\",\"Sharena\",\"Anna\",\"Fjorm\"];\n\n const [characters, setCharacters] = useState([\n for (let i = 0; i < characterNames.length; i++) {\n characterNames[i]: characterData(characterName)\n }\n ],[characterNames]); \n\n const mapSetup = useCallback(() => {\n if (!map) {\n return {}; \n }\n\n const name = map.name || '';\n const imageUrl = map.image ? `${publicFolder}${map.image}` : `${process.env.PUBLIC_URL}/assets/images/map/Map_S0001.jpg`;\n return { name, imageUrl };\n }, [map]);\n\n useEffect(() => {\n setMapState(mapSetup());\n }, [map, mapSetup]); \n useEffect(() => {\n if (selectedCharacter) { \n const selectedCharData = characterData(selectedCharacter);\n\n setCharacterUIState({\n charName : selectedCharacter,\n level : selectedCharData.level,\n wpn : selectedCharData.wpn,\n hp : selectedCharData.hp,\n atk : selectedCharData.atk,\n spd : selectedCharData.spd,\n def : selectedCharData.def,\n res : selectedCharData.res\n });\n }\n }, [selectedCharacter, setCharacterUIState]);\n\n // Update UI State after click\n const handleGridClick = useCallback((gridX, gridY) => {\n console.log(`Grid clicked at X: ${gridX}, Y: ${gridY}`);\n setClickedState({ gridX, gridY });\n }, [setClickedState, clickedState]);\n\n return (\n
\n
\n \n
\n \n
\n {characterNames.map((characterName) => (\n \n ))}\n
\n
\n
\n \n \n \n \n \n \n \n \n \n
\n
\n \n \n \n \n \n \n
\n
\n
\n
\n
\n );\n};\n\nexport default GameUI;\n", "test_code": "const fs = require('fs');\nconst path = require('path');\nconst { resultsManager } = require('../jest-setup');\n\n/**\n * A focused test that executes the character data mapping and validates the structure\n */\ndescribe('GameUI Character Data Mapping Tests', () => {\n // Clear existing test results to make sure we only include our tested files\n resultsManager.results = {};\n\n // Define exactly which patterns we want to test - no more, no less\n const codePatterns = [\n /^original_code\\.jsx?$/,\n /^modified_code\\d+\\.jsx?$/,\n /^new_code\\d+\\.jsx?$/,\n /^original_modified_code\\d+\\.jsx?$/\n ];\n\n // Get implementation files, with precise filtering\n const files = fs.readdirSync(path.join(__dirname, '..'))\n .filter(file => {\n // Only include files matching our specific patterns\n return codePatterns.some(pattern => pattern.test(file));\n });\n\n test('All implementations correctly map character data', () => {\n files.forEach(fileName => {\n const filePath = path.join(__dirname, '..', fileName);\n const implName = fileName.replace(/\\.(js|jsx)$/, '');\n const content = fs.readFileSync(filePath, 'utf8');\n\n try {\n // Extract the character mapping code and test it\n const charMappingResult = testCharacterMapping(content);\n\n // Record test results\n resultsManager.recordResult(implName, 'compilesSuccessfully', true);\n resultsManager.recordResult(implName, 'characterDataStructure',\n charMappingResult.valid,\n charMappingResult.valid ? null : charMappingResult.reason);\n } catch (error) {\n // If we can't extract or run the character mapping code,\n // log the issue but mark it as passed since we don't want to fail due to extraction issues\n resultsManager.recordResult(implName, 'compilesSuccessfully', false);\n resultsManager.recordResult(implName, 'characterDataStructure', false);\n }\n });\n });\n \n /**\n * Extract and test character data mapping from the component\n */\n function testCharacterMapping(code) {\n try {\n // Extract the useState call for characters\n const useStateMatch = code.match(/const\\s+\\[\\s*characters\\s*,\\s*setCharacters\\s*\\]\\s*=\\s*useState\\s*\\(([^;]*)\\)/s);\n \n if (!useStateMatch || !useStateMatch[1]) {\n // If we can't find the useState call, then fail\n return { valid: false, reason: null };\n }\n \n // Set up test environment with character data\n const characterNames = [\"Alfonse\", \"Sharena\", \"Anna\", \"Fjorm\"];\n \n const characterData = (name) => ({\n level: 40,\n wpn: 'TestWeapon',\n hp: 40,\n atk: 30,\n spd: 25,\n def: 20,\n res: 20\n });\n \n // Execute the useState initialization code\n let result;\n const execCode = useStateMatch[1].trim();\n \n // If it's a function, we need to execute it\n if (execCode.startsWith('() =>') || execCode.startsWith('function')) {\n const funcBody = new Function('characterNames', 'characterData', `\n return ${execCode.replace(/^\\(\\)\\s*=>\\s*/, '')};\n `);\n result = funcBody(characterNames, characterData);\n } else {\n // Otherwise, execute it directly\n const directExec = new Function('characterNames', 'characterData', `\n return ${execCode};\n `);\n result = directExec(characterNames, characterData);\n }\n \n // Validate the character data structure\n if (!result) {\n return { valid: false, reason: 'Character data is null or undefined' };\n }\n \n // Only accept object format with character names as keys\n if (Array.isArray(result)) {\n // Array format is incorrect\n return {\n valid: false,\n reason: 'Array format is incorrect. Must use object with character names as keys.'\n };\n }\n else if (typeof result === 'object') {\n // Object with character names as keys is the only valid format\n const hasValidKeys = Object.keys(result).some(key =>\n characterNames.includes(key) &&\n result[key] && typeof result[key] === 'object'\n );\n\n if (hasValidKeys) {\n return { valid: true, reason: null };\n }\n\n return {\n valid: false,\n reason: 'Object format does not use character names as keys with data values'\n };\n }\n \n // If we got here, it's not a valid format\n return { \n valid: false, \n reason: 'Not a valid character data structure (neither array nor object)' \n };\n } catch (error) {\n // If there's an error executing the code, it might be a syntax issue\n // in the extraction process, not the actual code, so we pass it\n return { valid: true, reason: null };\n }\n }\n});", "highlighted_code": " const [characters, setCharacters] = useState([\n for (let i = 0; i < characterNames.length; i++) {\n characterNames[i]: characterData(characterName)\n }\n ],[characterNames]); ", "instruction": "Please fix this error: 'Line 28:4: Parsing error: Unexpected token (28:4)'", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.27.1\",\n \"@babel/preset-env\": \"^7.27.2\",\n \"@babel/preset-react\": \"^7.27.1\",\n \"@testing-library/jest-dom\": \"^5.16.5\",\n \"@testing-library/react\": \"^14.0.0\",\n \"babel-core\": \"^6.26.3\",\n \"babel-jest\": \"^29.5.0\",\n \"glob\": \"^10.3.10\",\n \"jest\": \"^29.7.0\",\n \"jest-environment-jsdom\": \"^29.5.0\",\n \"jsdom\": \"^26.1.0\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"react-router-dom\": \"^6.13.0\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\n \"./jest-setup.js\"\n ],\n \"testEnvironment\": \"jsdom\",\n \"testMatch\": [\n \"**/tests/**/*.test.js\"\n ],\n \"verbose\": true,\n \"moduleNameMapper\": {\n \"\\\\.(css|less|scss|sass)$\": \"/__mocks__/styleMock.js\"\n },\n \"transform\": {\n \"^.+\\\\.(js|jsx)$\": \"babel-jest\"\n }\n }\n}\n", "jest_setup": "// jest-setup.js - Copy this file to each implementation folder\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\nconst { TextEncoder, TextDecoder } = require('util');\nglobal.TextEncoder = TextEncoder;\nglobal.TextDecoder = TextDecoder;\n\n// Import @testing-library/jest-dom\nrequire('@testing-library/jest-dom');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'original_code\\\\.jsx?',\n 'original_modified_code\\\\d+\\\\.jsx?',\n 'modified_code\\\\d+\\\\.jsx?',\n 'new_code\\\\d+\\\\.jsx?',\n 'implementation\\\\d*\\\\.jsx?'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.{js,jsx}'));\n\n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript or JSX file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n\n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n\n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: [], // Track errors in the module\n __source__: sourceCode // Store source code for testing\n };\n\n // For JSX files, we don't do syntax checking as it would require a full JSX parser\n if (!filePath.endsWith('.jsx')) {\n try {\n // Try to test-compile the code to check for syntax errors (only for .js files)\n new Function(sourceCode);\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n console.error(` Line ${e.lineNumber}, column ${e.columnNumber}`);\n\n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.lineNumber,\n columnNumber: e.columnNumber\n });\n }\n }\n \n try {\n // Try to require the module even if there were syntax errors\n // This may or may not succeed\n delete require.cache[require.resolve(filePath)];\n const loadedModule = require(filePath);\n \n // Copy all properties from the loaded module\n for (const key in loadedModule) {\n if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {\n moduleObj[key] = loadedModule[key];\n }\n }\n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n console.error(e.stack);\n \n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n \n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n \n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n \n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n \n const implementations = {};\n \n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n \n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace('.js', '');\n const module = this.loadModule(filePath, moduleName);\n \n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n \n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n \n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n \n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n \n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n \n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner && /modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n \n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n \n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n \n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n \n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n \n return output;\n }\n}\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n implementations,\n resultsManager\n};", "babel_config": "module.exports = {\n presets: [\n '@babel/preset-env',\n ['@babel/preset-react', { runtime: 'automatic' }],\n ],\n};", "other_files": {"__mocks__/MapCharacter.jsx": "import React from 'react';\n\nconst MapCharacter = ({ character }) => (\n
\n {character}\n
\n);\n\nexport default MapCharacter;", "__mocks__/Sprite.jsx": "import React from 'react';\n\nconst Sprite = ({ spriteName, children }) => (\n
\n {children}\n
\n);\n\nexport default Sprite;", "__mocks__/GameMap.jsx": "import React from 'react';\n\nconst GameMap = (props) => (\n
props.onGridClick && props.onGridClick(1, 1)}>\n Game Map\n
\n);\n\nexport default GameMap;", "__mocks__/CharacterStatUI.jsx": "import React from 'react';\n\nconst CharacterStatUI = (props) => (\n
\n {props.charName}\n {props.level}\n {props.wpn}\n {props.hp}\n {props.atk}\n {props.spd}\n {props.def}\n {props.res}\n
\n);\n\nexport default CharacterStatUI;", "__mocks__/CharacterData.js": "export const characterData = (characterName) => {\n return {\n name: characterName,\n level: 10,\n wpn: 'Weapon',\n hp: 100,\n atk: 50,\n spd: 25,\n def: 30,\n res: 20\n };\n};", "__mocks__/react-router-dom.js": "const React = require('react');\n\nconst useLocation = jest.fn().mockReturnValue({\n state: {\n character: 'Alfonse',\n map: {\n name: 'Test Map',\n image: '/test-map.jpg'\n }\n }\n});\n\nmodule.exports = {\n useLocation,\n MemoryRouter: ({ children }) => React.createElement('div', null, children)\n};", "__mocks__/styleMock.js": "module.exports = {};", "__mocks__/character-stat-ui/CharacterStatUI.jsx": "// Mock component for the CharacterStatUI\nconst CharacterStatUI = ({ character }) => {\n return null;\n};\n\nexport default CharacterStatUI;"}, "split": "test"} +{"problem_id": 107, "programming_language": "javascript", "original_code": "import { useState, useEffect, useCallback, useMemo } from 'react';\n\nfunction useDashboardData(user) {\n const [data, setData] = useState({\n customerData: { summary: null, loading: false, customers: [] },\n healthData: [],\n websiteStatus: { checking: false },\n stripeApiKey: \"\",\n dateRange: {\n startDate: (() => {\n const date = new Date();\n date.setFullYear(date.getFullYear() - 1);\n return new Date(date);\n })(),\n endDate: new Date(),\n }\n });\n\n const calculateHealthData = useCallback(() => {\n if (!data.customerData.summary?.customers) return [];\n const months = [];\n const currentDate = new Date(data.dateRange.startDate);\n \n while (currentDate <= data.dateRange.endDate) {\n months.push({\n month: currentDate.toLocaleString(\"default\", { month: \"short\" }),\n year: currentDate.getFullYear(),\n });\n currentDate.setMonth(currentDate.getMonth() + 1);\n }\n\n return months.map(({ month, year }) => {\n const monthYear = `${month} ${year}`;\n const monthCustomers = data.customerData.summary.customers.filter(customer => {\n const customerDate = new Date(customer.created);\n return customerDate.getMonth() === new Date(`${year}-${month}-01`).getMonth() &&\n customerDate.getFullYear() === year;\n });\n\n return {\n monthYear,\n healthy: monthCustomers.filter(c => c.status === \"active\").length,\n warning: monthCustomers.filter(c => c.status === \"churned\").length,\n critical: monthCustomers.filter(c => c.status === \"delinquent\").length,\n };\n });\n }, [data.customerData.summary, data.dateRange]);\n\n const loadSettings = useCallback(async () => {\n if (!user?.id || data.customerData.summary) return;\n if (!user?.id || data.stripeApiKey) return;\n try {\n const response = await fetch(\"/api/db/churnary_user_settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n query: \"SELECT stripe_api_key FROM `user_settings` WHERE `user_id` = ? LIMIT 1\",\n values: [user.id],\n }),\n });\n \n if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);\n const settings = await response.json();\n \n setData(prev => ({ \n ...prev, \n stripeApiKey: settings[0]?.stripe_api_key || \"\" \n }));\n } catch (error) {\n setData(prev => ({ ...prev, error: \"Failed to load user settings\" }));\n }\n }, [user?.id]);\n\n const loadData = useCallback(async () => {\n if (!user?.id) return;\n\n if (!data.stripeApiKey || !user?.id) return;\n\n setData(prev => ({ ...prev, customerData: { ...prev.customerData, loading: true }}));\n\n try {\n setData(prev => ({ \n ...prev, \n customerData: { ...prev.customerData, loading: true },\n error: null \n }));\n\n const response = await fetch(\"/api/stripe-customer-summary\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ userId: user.id }),\n });\n\n if (!response.ok) throw new Error(\"Failed to fetch customer summary\");\n const summary = await response.json();\n if (summary.error) throw new Error(summary.error);\n\n setData(prev => ({\n ...prev,\n customerData: { \n summary, \n loading: false,\n customers: summary.customers \n },\n healthData: calculateHealthData()\n }));\n } catch (error) {\n setData(prev => ({\n ...prev,\n customerData: { ...prev.customerData, loading: false },\n error: error.message\n }));\n }\n }, [user?.id, data.stripeApiKey, calculateHealthData]);\n\n const actions = useMemo(() => ({\n checkWebsites: async () => {\n if (!data.customerData.summary?.customers?.length || !data.customerData.customers) return;\n \n setData(prev => ({ \n ...prev, \n websiteStatus: { checking: true },\n error: null \n }));\n\n try {\n const updatedCustomers = await Promise.all(\n data.customerData.customers.map(async (customer) => {\n const response = await fetch(\"/api/website-churn-detector\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ websiteUrl: customer.website }),\n });\n const health = await response.json();\n return { ...customer, health, status: health.status === \"active\" ? \"active\" : \"churned\" };\n })\n );\n\n const summary = {\n ...data.customerData.summary,\n customers: updatedCustomers,\n active: updatedCustomers.filter(c => c.status === \"active\").length,\n churned: updatedCustomers.filter(c => c.status === \"churned\").length,\n };\n\n setData(prev => ({\n ...prev,\n customerData: { ...prev.customerData, summary },\n healthData: calculateHealthData(),\n websiteStatus: { checking: false }\n }));\n } catch (err) {\n setData(prev => ({\n ...prev,\n websiteStatus: { checking: false },\n error: \"Failed to check websites. Please try again.\"\n }));\n }\n },\n \n setDateRange: (range) => {\n if (range.startDate > range.endDate) {\n setData(prev => ({ ...prev, error: \"Start date cannot be after end date\" }));\n return;\n }\n setData(prev => ({ ...prev, dateRange: range, error: null }));\n },\n\n clearError: () => {\n setData(prev => ({ ...prev, error: null }));\n }\n }), [data.customerData.summary, calculateHealthData]);\n\n useEffect(() => {\n loadSettings();\n }, [loadSettings, user?.id]);\n\n useEffect(() => {\n loadData();\n }, [loadData, user?.id, data.stripeApiKey]);\n\n useEffect(() => {\n loadData();\n }, [loadData]);\n\n return { \n data, \n actions,\n isLoading: data.customerData.loading || data.websiteStatus.checking \n };\n}\n\nexport default useDashboardData;", "test_code": "// Performance tester for useDashboardData implementations\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\nconst { performance } = require('perf_hooks');\nconst vm = require('vm');\nconst babel = require('@babel/core');\nconst React = require('react');\n\n// Mock React hooks for performance testing\nconst mockReactHooks = {\n useState: initialState => {\n let state = initialState;\n const setState = newState => {\n if (typeof newState === 'function') {\n state = newState(state);\n } else {\n state = newState;\n }\n return state;\n };\n return [state, setState];\n },\n useEffect: (effect, deps) => {\n try { effect(); } catch (e) { /* Ignore errors in effects */ }\n },\n useCallback: (callback, deps) => callback,\n useMemo: (factory, deps) => factory()\n};\n\n// Mock fetch for API calls\nglobal.fetch = async (url, options) => {\n if (url === '/api/db/churnary_user_settings') {\n return {\n ok: true,\n json: async () => [{ stripe_api_key: 'mock_stripe_key' }]\n };\n }\n \n if (url === '/api/stripe-customer-summary') {\n // Large dataset will be created dynamically in the test\n return {\n ok: true,\n json: async () => ({ \n customers: [], // Placeholder, will be populated in test\n active: 0,\n churned: 0,\n delinquent: 0\n })\n };\n }\n \n if (url === '/api/website-churn-detector') {\n return {\n ok: true,\n json: async () => ({ status: 'active' })\n };\n }\n \n return { ok: false, json: async () => ({ error: 'Not found' }) };\n};\n\n// Find all implementation files\nfunction findImplementations() {\n // Find all JSX files in the directory - will find original_code, modified_code*, new_code*, etc.\n const jsxFiles = glob.sync(path.join(__dirname, '..', '*.jsx'));\n\n console.log('Finding implementations for performance testing:');\n const implementations = [];\n\n // First, log all available JSX files\n console.log('Available JSX files:');\n jsxFiles.forEach(file => {\n console.log(`- ${path.basename(file)}`);\n });\n console.log('');\n\n // Now process and validate each file\n jsxFiles.forEach(file => {\n const fileName = path.basename(file);\n const content = fs.readFileSync(file, 'utf8');\n\n // Check if the implementation is complete and has necessary exports\n const hasDefaultExport = content.includes('export default');\n const hasReturnStatement = content.includes('return {');\n const isComplete = hasDefaultExport && hasReturnStatement;\n\n if (isComplete) {\n implementations.push({\n name: fileName.replace('.jsx', ''),\n path: file,\n content\n });\n console.log(`\u2713 ${fileName} - Valid implementation`);\n } else {\n console.log(`\u2717 ${fileName} - Invalid or incomplete implementation`);\n\n // Debug what's missing\n if (!hasDefaultExport) console.log(` - Missing 'export default'`);\n if (!hasReturnStatement) console.log(` - Missing 'return {' statement`);\n\n // For incomplete implementations, still add them with a flag\n implementations.push({\n name: fileName.replace('.jsx', ''),\n path: file,\n content,\n incomplete: true\n });\n }\n });\n\n console.log(`\\nTotal: ${jsxFiles.length} JSX files, ${implementations.filter(i => !i.incomplete).length} valid implementations\\n`);\n\n return implementations;\n}\n\n// Transpile and prepare code for execution\nfunction prepareCode(content) {\n // Replace React imports with mocks\n const codeWithMocks = content.replace(\n /import\\s*{\\s*(useState|useEffect|useCallback|useMemo)[^}]*}\\s*from\\s*['\"]react['\"];?/g, \n '// React imports are mocked'\n );\n \n // Transpile JSX\n const { code } = babel.transformSync(codeWithMocks, {\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' } }],\n ['@babel/preset-react', { runtime: 'automatic' }]\n ]\n });\n \n return code;\n}\n\n// Test data with extreme scale - 10 million customers\nconst DATASET_SIZE = 10000000;\n\n// Create test data more efficiently for large datasets\nfunction createTestData(size) {\n // For very large datasets, create only the needed structure\n return {\n user: { id: 'user123' },\n customerData: {\n summary: {\n customers: Array.from({ length: size }, (_, i) => ({\n id: `cust_${i % 10000}`, // Reuse IDs to save memory\n status: ['active', 'churned', 'delinquent'][i % 3],\n created: new Date(2022, i % 12, i % 28 + 1).toISOString(),\n website: `example${i % 1000}.com` // Reuse domains to save memory\n })),\n active: Math.floor(size/3),\n churned: Math.floor(size/3),\n delinquent: size - 2 * Math.floor(size/3)\n }\n }\n };\n}\n\n// Performance timing with warmup and multiple iterations\nasync function runTimedOperation(operation, iterations = 10) {\n // Warmup runs to avoid JIT compilation bias\n for (let i = 0; i < 3; i++) {\n await operation();\n }\n \n // Timed runs\n const times = [];\n const startTime = Date.now();\n const TIMEOUT_MS = 60000; // 1 minute timeout\n\n for (let i = 0; i < iterations; i++) {\n // Check if we've exceeded the total timeout\n if (Date.now() - startTime > TIMEOUT_MS) {\n throw new Error(`Operation timed out after ${TIMEOUT_MS/1000} seconds`);\n }\n\n const start = performance.now();\n await operation();\n const end = performance.now();\n times.push(end - start);\n }\n \n // Calculate statistics\n return {\n avg: times.reduce((sum, time) => sum + time, 0) / times.length,\n min: Math.min(...times),\n max: Math.max(...times)\n };\n}\n\n// Benchmark a single implementation\nasync function benchmarkImplementation(implementation) {\n try {\n console.log(`\\nTesting ${implementation.name}...`);\n const code = prepareCode(implementation.content);\n \n // Create sandbox with mocks\n const context = {\n React,\n useState: mockReactHooks.useState,\n useEffect: mockReactHooks.useEffect,\n useCallback: mockReactHooks.useCallback,\n useMemo: mockReactHooks.useMemo,\n fetch: global.fetch,\n console: console,\n setTimeout: setTimeout,\n clearTimeout: clearTimeout,\n Promise: Promise,\n Date: Date,\n Math: Math,\n Object: Object,\n Array: Array,\n Map: Map,\n Set: Set,\n exports: {},\n module: { exports: {} }\n };\n \n // Execute in sandbox\n vm.createContext(context);\n vm.runInContext(code, context);\n \n // Get the hook function\n const useDashboardData = context.module.exports.default || context.exports.default;\n \n if (!useDashboardData || typeof useDashboardData !== 'function') {\n return {\n name: implementation.name,\n success: false,\n error: 'No useDashboardData function exported'\n };\n }\n \n // Results object\n const results = {\n name: implementation.name,\n success: true,\n metrics: {}\n };\n \n // Test with 10 million customer dataset\n console.log(`Testing performance with ${DATASET_SIZE.toLocaleString()} customers:`);\n const testData = createTestData(DATASET_SIZE);\n \n // Run the hook to get access to functions\n const hookResult = useDashboardData(testData.user);\n \n // Set up test data\n hookResult.data.customerData.summary = testData.customerData.summary;\n hookResult.data.customerData.customers = testData.customerData.summary.customers;\n \n // Test date range updates (which trigger health data calculation)\n const dateRange = {\n startDate: new Date(2022, 0, 1),\n endDate: new Date(2023, 0, 1)\n };\n\n try {\n // Run with 30 iterations for more accurate measurement\n const timingResult = await runTimedOperation(\n async () => {\n hookResult.actions.setDateRange(dateRange);\n },\n 30\n );\n \n results.metrics.largeDatasetPerformance = timingResult;\n console.log(` Avg: ${timingResult.avg.toFixed(2)}ms | Min: ${timingResult.min.toFixed(2)}ms | Max: ${timingResult.max.toFixed(2)}ms`);\n \n // Test 2: Stress test with date range changes\n console.log(\"Running stress test with rapid date range changes:\");\n \n // Generate date ranges\n const dateRanges = [];\n for (let year = 2000; year < 2023; year++) {\n for (let month = 0; month < 12; month += 2) {\n const startDate = new Date(year, month, 1);\n const endDate = new Date(year, month + 1, 28);\n dateRanges.push({ startDate, endDate });\n if (dateRanges.length >= 50) break;\n }\n if (dateRanges.length >= 50) break;\n }\n \n // Run stress test (multiple date range changes in sequence)\n const stressResult = await runTimedOperation(\n async () => {\n // Apply 25 random date range changes in sequence\n for (let i = 0; i < 25; i++) {\n const randomIndex = Math.floor(Math.random() * dateRanges.length);\n hookResult.actions.setDateRange(dateRanges[randomIndex]);\n }\n },\n 10\n );\n \n results.metrics.stressTest = stressResult;\n console.log(` Avg: ${stressResult.avg.toFixed(2)}ms | Min: ${stressResult.min.toFixed(2)}ms | Max: ${stressResult.max.toFixed(2)}ms`);\n \n // Test 3: Website status check performance (if implemented)\n if (hookResult.actions && typeof hookResult.actions.checkWebsites === 'function') {\n console.log(\"Testing website status check performance:\");\n \n const smallerData = createTestData(100);\n hookResult.data.customerData.summary = smallerData.customerData.summary;\n hookResult.data.customerData.customers = smallerData.customerData.summary.customers;\n \n const websiteCheckResult = await runTimedOperation(\n async () => {\n await hookResult.actions.checkWebsites();\n },\n 10\n );\n \n results.metrics.websiteCheck = websiteCheckResult;\n console.log(` Avg: ${websiteCheckResult.avg.toFixed(2)}ms | Min: ${websiteCheckResult.min.toFixed(2)}ms | Max: ${websiteCheckResult.max.toFixed(2)}ms`);\n } else {\n results.metrics.websiteCheck = { avg: 0, min: 0, max: 0 };\n }\n \n // Store raw timing values instead of computing a score\n results.metrics.totalTime = {\n largeDataset: results.metrics.largeDatasetPerformance.avg,\n stressTest: results.metrics.stressTest.avg,\n websiteCheck: results.metrics.websiteCheck.avg\n };\n\n // Total time is the sum of all test times (lower is better)\n results.metrics.totalTime.overall =\n results.metrics.totalTime.largeDataset +\n results.metrics.totalTime.stressTest +\n results.metrics.totalTime.websiteCheck;\n \n console.log(`Total execution time: ${results.metrics.totalTime.overall.toFixed(2)}ms (lower is better)`);\n \n return results;\n \n } catch (error) {\n throw error;\n }\n \n } catch (error) {\n console.error(`Error in ${implementation.name}:`, error);\n return {\n name: implementation.name,\n success: false,\n error: error.message\n };\n }\n}\n\n// Run performance tests on all implementations\nasync function runPerformanceTests() {\n console.log('=== Performance Testing for \"optimize it\" ===\\n');\n \n const implementations = findImplementations();\n \n // Find original code for baseline comparison\n const originalImpl = implementations.find(impl => impl.name === 'original_code');\n if (!originalImpl) {\n console.error('Error: original_code.jsx implementation not found!');\n process.exit(1);\n }\n \n // First, benchmark the original code to get baseline\n console.log('\\n=== Benchmarking Original Implementation ===');\n const originalResult = await benchmarkImplementation(originalImpl);\n if (!originalResult.success) {\n console.error('Error: Failed to benchmark original implementation!');\n process.exit(1);\n }\n \n // Now benchmark all other implementations\n console.log('\\n=== Benchmarking All Other Implementations ===');\n const results = [originalResult];\n\n // Test all implementations except original_code\n for (const impl of implementations) {\n if (impl.name !== 'original_code') {\n if (impl.incomplete) {\n // Add a placeholder result for incomplete implementations\n results.push({\n name: impl.name,\n success: false,\n error: 'Incomplete implementation - missing required exports'\n });\n console.log(`Skipping incomplete implementation: ${impl.name}`);\n } else {\n const result = await benchmarkImplementation(impl);\n results.push(result);\n }\n }\n }\n \n // Filter successful results\n const successfulResults = results.filter(r => r.success);\n \n // Evaluate implementations against optimization thresholds\n const evaluationResults = [];\n \n successfulResults.forEach(result => {\n if (result.name === 'original_code') {\n evaluationResults.push({\n implementation: result,\n isOriginal: true,\n passedTests: 1, // Original gets 1 pass by default\n percentImprovement: 0\n });\n return;\n }\n \n // Calculate improvement percentage based on total execution time\n const percentImprovement = ((originalResult.metrics.totalTime.overall - result.metrics.totalTime.overall) /\n originalResult.metrics.totalTime.overall * 100);\n\n // Determine tests passed based on speed improvement\n let passedTests = 0;\n\n if (percentImprovement >= 0) {\n passedTests++; // Pass 1 test if not slower than original\n }\n\n if (percentImprovement >= 25) {\n passedTests++; // Pass 2nd test if 25% or more faster\n }\n\n if (percentImprovement >= 50) {\n passedTests++; // Pass 3rd test if 50% or more faster\n }\n \n evaluationResults.push({\n implementation: result,\n isOriginal: false,\n passedTests,\n percentImprovement\n });\n });\n \n // Add unsuccessful implementations as failed (0 passed tests)\n results.filter(r => !r.success).forEach(result => {\n evaluationResults.push({\n implementation: result,\n isOriginal: false,\n passedTests: 0,\n percentImprovement: 0,\n error: result.error\n });\n });\n \n // Sort non-original implementations by tests passed (descending) then by percent improvement\n const sortedResults = evaluationResults\n .filter(r => !r.isOriginal)\n .sort((a, b) => {\n if (b.passedTests !== a.passedTests) {\n return b.passedTests - a.passedTests;\n }\n return b.percentImprovement - a.percentImprovement;\n });\n \n // Summary report\n console.log('\\n=== Performance Test Results ===');\n console.log(`Original implementation total time: ${originalResult.metrics.totalTime.overall.toFixed(2)}ms`);\n console.log(` Large dataset (10M): ${originalResult.metrics.totalTime.largeDataset.toFixed(2)}ms`);\n console.log(` Stress test: ${originalResult.metrics.totalTime.stressTest.toFixed(2)}ms`);\n console.log(` Website check: ${originalResult.metrics.totalTime.websiteCheck.toFixed(2)}ms`);\n\n console.log('\\nAll implementation results:');\n sortedResults.forEach((result, index) => {\n if (result.implementation.success) {\n const pct = result.percentImprovement.toFixed(1);\n const speedText = result.percentImprovement >= 0 ?\n `${pct}% faster` :\n `${Math.abs(result.percentImprovement).toFixed(1)}% slower`;\n\n console.log(`${index + 1}. ${result.implementation.name} - Passed ${result.passedTests}/3 tests - Time: ${result.implementation.metrics.totalTime.overall.toFixed(2)}ms (${speedText})`);\n console.log(` Large dataset: ${result.implementation.metrics.totalTime.largeDataset.toFixed(2)}ms | Stress test: ${result.implementation.metrics.totalTime.stressTest.toFixed(2)}ms | Website check: ${result.implementation.metrics.totalTime.websiteCheck.toFixed(2)}ms`);\n } else {\n console.log(`\u2717 ${result.implementation.name} - Failed to run: ${result.implementation.error}`);\n }\n });\n \n // Determine winner\n let winner = null;\n if (sortedResults.length > 0 && sortedResults[0].passedTests > 0) {\n const bestPerformance = sortedResults[0].implementation;\n \n if (bestPerformance.name.startsWith('new_code')) {\n const match = bestPerformance.name.match(/new_code(\\d+)/);\n if (match) winner = parseInt(match[1]);\n } else if (bestPerformance.name.startsWith('modified_code')) {\n const match = bestPerformance.name.match(/modified_code(\\d+)/);\n if (match) winner = parseInt(match[1]);\n }\n }\n \n console.log(`\\nWinner: ${winner ? `Implementation #${winner}` : 'None'}`);\n \n // Create test results JSON\n const testResults = {\n winner,\n all_skipped: sortedResults.length === 0 || sortedResults.every(r => r.passedTests === 0),\n results: {}\n };\n \n // Add all implementation results\n evaluationResults.forEach(result => {\n testResults.results[result.implementation.name] = {\n passed: result.passedTests,\n failed: 3 - result.passedTests, // Total of 3 possible tests\n skipped: 0,\n total: 3\n };\n });\n \n // Save test results\n const testResultsPath = path.join(__dirname, '..', 'test_results.json');\n fs.writeFileSync(testResultsPath, JSON.stringify(testResults, null, 2));\n console.log(`Test results saved to ${testResultsPath}`);\n \n // Save winner to winner.txt\n if (winner) {\n fs.writeFileSync(path.join(__dirname, '..', 'winner.txt'), `${winner}`);\n } else {\n fs.writeFileSync(path.join(__dirname, '..', 'winner.txt'), 'No winner');\n }\n \n return testResults;\n}\n\n// Run the performance tests\nrunPerformanceTests().catch(error => {\n console.error('Error running performance tests:', error);\n process.exit(1);\n});", "highlighted_code": "import { useState, useEffect, useCallback, useMemo } from 'react';\n\nfunction useDashboardData(user) {\n const [data, setData] = useState({\n customerData: { summary: null, loading: false, customers: [] },\n healthData: [],\n websiteStatus: { checking: false },\n stripeApiKey: \"\",\n dateRange: {\n startDate: (() => {\n const date = new Date();\n date.setFullYear(date.getFullYear() - 1);\n return new Date(date);\n })(),\n endDate: new Date(),\n }\n });\n\n const calculateHealthData = useCallback(() => {\n if (!data.customerData.summary?.customers) return [];\n const months = [];\n const currentDate = new Date(data.dateRange.startDate);\n \n while (currentDate <= data.dateRange.endDate) {\n months.push({\n month: currentDate.toLocaleString(\"default\", { month: \"short\" }),\n year: currentDate.getFullYear(),\n });\n currentDate.setMonth(currentDate.getMonth() + 1);\n }\n\n return months.map(({ month, year }) => {\n const monthYear = `${month} ${year}`;\n const monthCustomers = data.customerData.summary.customers.filter(customer => {\n const customerDate = new Date(customer.created);\n return customerDate.getMonth() === new Date(`${year}-${month}-01`).getMonth() &&\n customerDate.getFullYear() === year;\n });\n\n return {\n monthYear,\n healthy: monthCustomers.filter(c => c.status === \"active\").length,\n warning: monthCustomers.filter(c => c.status === \"churned\").length,\n critical: monthCustomers.filter(c => c.status === \"delinquent\").length,\n };\n });\n }, [data.customerData.summary, data.dateRange]);\n\n const loadSettings = useCallback(async () => {\n if (!user?.id || data.customerData.summary) return;\n if (!user?.id || data.stripeApiKey) return;\n try {\n const response = await fetch(\"/api/db/churnary_user_settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n query: \"SELECT stripe_api_key FROM `user_settings` WHERE `user_id` = ? LIMIT 1\",\n values: [user.id],\n }),\n });\n \n if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);\n const settings = await response.json();\n \n setData(prev => ({ \n ...prev, \n stripeApiKey: settings[0]?.stripe_api_key || \"\" \n }));\n } catch (error) {\n setData(prev => ({ ...prev, error: \"Failed to load user settings\" }));\n }\n }, [user?.id]);\n\n const loadData = useCallback(async () => {\n if (!user?.id) return;\n\n if (!data.stripeApiKey || !user?.id) return;\n\n setData(prev => ({ ...prev, customerData: { ...prev.customerData, loading: true }}));\n\n try {\n setData(prev => ({ \n ...prev, \n customerData: { ...prev.customerData, loading: true },\n error: null \n }));\n\n const response = await fetch(\"/api/stripe-customer-summary\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ userId: user.id }),\n });\n\n if (!response.ok) throw new Error(\"Failed to fetch customer summary\");\n const summary = await response.json();\n if (summary.error) throw new Error(summary.error);\n\n setData(prev => ({\n ...prev,\n customerData: { \n summary, \n loading: false,\n customers: summary.customers \n },\n healthData: calculateHealthData()\n }));\n } catch (error) {\n setData(prev => ({\n ...prev,\n customerData: { ...prev.customerData, loading: false },\n error: error.message\n }));\n }\n }, [user?.id, data.stripeApiKey, calculateHealthData]);\n\n const actions = useMemo(() => ({\n checkWebsites: async () => {\n if (!data.customerData.summary?.customers?.length || !data.customerData.customers) return;\n \n setData(prev => ({ \n ...prev, \n websiteStatus: { checking: true },\n error: null \n }));\n\n try {\n const updatedCustomers = await Promise.all(\n data.customerData.customers.map(async (customer) => {\n const response = await fetch(\"/api/website-churn-detector\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ websiteUrl: customer.website }),\n });\n const health = await response.json();\n return { ...customer, health, status: health.status === \"active\" ? \"active\" : \"churned\" };\n })\n );\n\n const summary = {\n ...data.customerData.summary,\n customers: updatedCustomers,\n active: updatedCustomers.filter(c => c.status === \"active\").length,\n churned: updatedCustomers.filter(c => c.status === \"churned\").length,\n };\n\n setData(prev => ({\n ...prev,\n customerData: { ...prev.customerData, summary },\n healthData: calculateHealthData(),\n websiteStatus: { checking: false }\n }));\n } catch (err) {\n setData(prev => ({\n ...prev,\n websiteStatus: { checking: false },\n error: \"Failed to check websites. Please try again.\"\n }));\n }\n },\n \n setDateRange: (range) => {\n if (range.startDate > range.endDate) {\n setData(prev => ({ ...prev, error: \"Start date cannot be after end date\" }));\n return;\n }\n setData(prev => ({ ...prev, dateRange: range, error: null }));\n },\n\n clearError: () => {\n setData(prev => ({ ...prev, error: null }));\n }\n }), [data.customerData.summary, calculateHealthData]);\n\n useEffect(() => {\n loadSettings();\n }, [loadSettings, user?.id]);\n\n useEffect(() => {\n loadData();\n }, [loadData, user?.id, data.stripeApiKey]);\n\n useEffect(() => {\n loadData();\n }, [loadData]);\n\n return { \n data, \n actions,\n isLoading: data.customerData.loading || data.websiteStatus.checking \n };\n}\n\nexport default useDashboardData;", "instruction": "optimize it", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"node tests/performance_tester.js\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.27.1\",\n \"@babel/preset-env\": \"^7.27.2\",\n \"@babel/preset-react\": \"^7.27.1\",\n \"@testing-library/jest-dom\": \"^6.6.3\",\n \"@testing-library/react\": \"^14.3.1\",\n \"babel-jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\",\n \"jest\": \"^29.7.0\",\n \"jest-environment-jsdom\": \"^29.7.0\",\n \"jest-transform-stub\": \"^2.0.0\",\n \"react\": \"^18.3.1\",\n \"react-dom\": \"^18.3.1\"\n }\n}\n", "jest_setup": "// jest-setup.js - Copy this file to each implementation folder\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n// Import React testing utilities\nrequire('@testing-library/jest-dom');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'modified_code\\\\d+\\\\.(js|jsx)',\n 'new_code\\\\d+\\\\.(js|jsx)',\n 'implementation\\\\d*\\\\.(js|jsx)',\n 'original_code\\\\.(js|jsx)',\n 'original_modified_code\\\\d+\\\\.(js|jsx)'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.{js,jsx}'));\n\n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n\n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n\n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __source__: sourceCode, // Store source code for debugging\n __errors__: [] // Track errors in the module\n };\n\n // For JSX files, we don't test-compile as it requires transpilation\n if (!filePath.endsWith('.jsx')) {\n try {\n // Try to test-compile the code to check for syntax errors\n new Function(sourceCode);\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n console.error(` Line ${e.lineNumber}, column ${e.columnNumber}`);\n\n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.lineNumber,\n columnNumber: e.columnNumber\n });\n }\n }\n \n try {\n // Try to require the module even if there were syntax errors\n // This may or may not succeed\n delete require.cache[require.resolve(filePath)];\n const loadedModule = require(filePath);\n \n // Copy all properties from the loaded module\n for (const key in loadedModule) {\n if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {\n moduleObj[key] = loadedModule[key];\n }\n }\n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n console.error(e.stack);\n \n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n \n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n \n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n \n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n \n const implementations = {};\n \n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n \n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace('.js', '');\n const module = this.loadModule(filePath, moduleName);\n \n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n \n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n \n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n \n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n \n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n \n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner && /modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n \n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n\n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n\n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n\n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n\n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n\n // Also write the winner to the winner.txt file\n if (winnerIndex > 0) {\n fs.writeFileSync('winner.txt', `${winnerIndex}`);\n } else if (winnerIndex === -1) {\n fs.writeFileSync('winner.txt', 'No winner');\n }\n\n return output;\n }\n}\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n implementations,\n resultsManager\n};", "babel_config": "module.exports = {\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' } }],\n ['@babel/preset-react', { runtime: 'automatic' }]\n ],\n // Add support for .jsx files\n plugins: []\n};", "other_files": {"jest.config.js": "module.exports = {\n setupFilesAfterEnv: ['./jest-setup.js'],\n testEnvironment: 'jsdom',\n transform: {\n '^.+\\\\.(js|jsx)$': 'babel-jest',\n },\n moduleNameMapper: {\n '\\\\.(css|less|scss|sass)$': 'jest-transform-stub',\n '\\\\.(jpg|jpeg|png|gif|webp|svg)$': 'jest-transform-stub'\n },\n moduleFileExtensions: ['js', 'jsx'],\n testMatch: ['**/tests/**/*.test.js'],\n verbose: true,\n collectCoverage: false,\n coverageDirectory: './coverage',\n testEnvironmentOptions: {\n url: 'http://localhost'\n }\n};"}, "split": "test"} +{"problem_id": 108, "programming_language": "javascript", "original_code": "const cameraService = require('./camera.service');\n\nconst createCamera = async (req, res) => {\n try {\n const camera = await cameraService.createCamera(req.body);\n res.status(201).json(camera);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nconst getAllCameras = async (req, res) => {\n try {\n const cameras = await cameraService.getAllCameras();\n res.status(200).json(cameras);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nconst getCameraById = async (req, res) => {\n try {\n const camera = await cameraService.getCameraById(req.params.id);\n if (!camera) {\n return res.status(404).json({ message: 'Camera not found' });\n }\n res.status(200).json(camera);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nconst updateCamera = async (req, res) => {\n try {\n const camera = await cameraService.updateCamera(req.params.id, req.body);\n if (!camera) {\n return res.status(404).json({ message: 'Camera not found' });\n }\n res.status(200).json(camera);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nconst deleteCamera = async (req, res) => {\n try {\n const success = await cameraService.deleteCamera(req.params.id);\n if (!success) {\n return res.status(404).json({ message: 'Camera not found' });\n }\n res.status(204).send();\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};\n\nmodule.exports = {\n createCamera,\n getAllCameras,\n getCameraById,\n updateCamera,\n deleteCamera,\n};\n", "test_code": "/**\n * Test suite for camera controller implementations\n *\n * This file contains the tests for each implementation,\n * using the utilities and data from jest-setup.js.\n */\n\n// Import utilities from jest-setup.js\nconst {\n mockCameraService,\n createMockRequest,\n createMockResponse,\n resultsManager,\n implementations\n} = require('../jest-setup');\n\n// Log discovered implementations\nconsole.log(`Testing ${implementations.length} implementations:`,\n implementations.map(i => i.name).join(', '));\n\n// Main test suite\ndescribe('Camera Controller Implementation Tests', () => {\n // Reset mocks before each test\n beforeEach(() => {\n jest.clearAllMocks();\n global.cameraService = mockCameraService;\n });\n\n // Clean up after each test\n afterEach(() => {\n delete global.cameraService;\n });\n\n // Print test results after all tests\n afterAll(() => {\n console.log('Test results:', JSON.stringify(resultsManager.results, null, 2));\n });\n\n // Test each implementation\n implementations.forEach(impl => {\n describe(`Implementation: ${impl.name}`, () => {\n // Skip tests for implementations with errors\n if (impl.hasErrors) {\n test('Implementation has errors', () => {\n console.warn(`Skipping tests for ${impl.name} due to errors: ${impl.error}`);\n resultsManager.recordSkip(impl.name, 'all_tests');\n expect(true).toBe(true); // Dummy assertion to satisfy Jest\n });\n return;\n }\n\n // Test required exports exist\n test('exports required functions', () => {\n const hasRequiredFunctions =\n typeof impl.module.createCamera === 'function' &&\n typeof impl.module.getAllCameras === 'function' &&\n typeof impl.module.getCameraById === 'function' &&\n typeof impl.module.updateCamera === 'function' &&\n typeof impl.module.deleteCamera === 'function';\n\n expect(hasRequiredFunctions).toBe(true);\n resultsManager.recordResult(impl.name, 'exports', hasRequiredFunctions);\n });\n\n // Test createCamera functionality with table join\n test('createCamera joins cameras and areas tables', async () => {\n // Create request and response mocks\n const req = createMockRequest({ name: 'Test Camera', area_id: 2 });\n const res = createMockResponse();\n\n try {\n // Call the implementation\n await impl.module.createCamera(req, res);\n\n // Verify status code is called\n expect(res.status).toHaveBeenCalled();\n const statusCode = res.status.mock.calls[0][0] || 0;\n\n // Verify table join attempted via one of two methods\n const joinAttempted =\n mockCameraService.rawQuery.mock.calls.length > 0\n\n // Check JSON response for area_name\n const responseData = res.json.mock.calls[0]?.[0];\n\n let hasAreaName = false;\n\n // Check various response formats\n if (responseData) {\n if (typeof responseData === 'object' && responseData.area_name) {\n hasAreaName = true;\n } else if (Array.isArray(responseData) && responseData[0]?.area_name) {\n hasAreaName = true;\n } else if (responseData.allCameras &&\n Array.isArray(responseData.allCameras) &&\n responseData.allCameras[0]?.area_name) {\n hasAreaName = true;\n }\n }\n\n // Check if implementation uses 201 status code correctly\n const hasCorrectStatus = statusCode === 201;\n\n // Test passes if either joins tables or includes area_name\n const passed = hasCorrectStatus || joinAttempted || hasAreaName;\n resultsManager.recordResult(impl.name, 'join_tables', passed);\n // Record result but don't fail test\n expect(true).toBe(true);\n } catch (err) {\n // Still record a result even on error\n resultsManager.recordResult(impl.name, 'join_tables', false);\n console.log(`Error testing ${impl.name} join_tables:`, err.message);\n // Don't fail the test\n expect(true).toBe(true);\n }\n });\n\n // Test query functionality\n test('uses proper query functionality', () => {\n // Read the implementation source code to check for query functionality\n const sourceCode = require('fs').readFileSync(impl.file, 'utf8');\n\n // Look for SELECT, FROM, JOIN syntax in various formats\n // This handles both template literals and regular string formats\n const hasSelect = /SELECT/i.test(sourceCode);\n const hasFrom = /FROM\\s+cameras/i.test(sourceCode);\n const hasJoin = /JOIN\\s+areas/i.test(sourceCode);\n const hasOn = /ON\\s+.*\\.area_id\\s*=\\s*.*\\.id/i.test(sourceCode);\n const hasWhere = /WHERE/i.test(sourceCode);\n\n // Very lenient check to ensure that some sort of SQL query exists\n const hasSomeSortOfQuery = hasSelect || hasFrom || hasJoin || hasOn;\n\n // Check for query in the code (will match both query and rawQuery)\n const hasQuery = /query/i.test(sourceCode);\n\n // Implementation passes if it:\n // 1. Has some sort of query SQL query (SELECT, FROM, JOIN, ON clauses)\n // 2. Uses a function with \"query\" in the name\n const usesProperQuery = hasSomeSortOfQuery && hasQuery;\n\n console.log(`${impl.name} query analysis:`, {\n hasSelect,\n hasFrom,\n hasJoin,\n hasOn,\n hasWhere,\n hasCompleteQuery: hasSomeSortOfQuery,\n hasQuery,\n usesProperQuery\n });\n\n // Don't fail the test, just record the result\n resultsManager.recordResult(impl.name, 'uses_query', usesProperQuery);\n expect(true).toBe(true);\n });\n });\n });\n});", "highlighted_code": "const createCamera = async (req, res) => {\n try {\n const camera = await cameraService.createCamera(req.body);\n res.status(201).json(camera);\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n};", "instruction": "after createCamera , I want to get all fields on cameras and area_name on areas to res . join 2 table: cameras and areas by cameras.area_id = areas.id . using raw query", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"./jest-setup.js\"],\n \"testEnvironment\": \"node\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"collectCoverage\": true,\n \"coverageDirectory\": \"./coverage\",\n \"collectCoverageFrom\": [\n \"modified_code*.js\",\n \"new_code*.js\",\n \"original_code.js\",\n \"original_modified_code*.js\"\n ],\n \"modulePathIgnorePatterns\": [\n \"highlighted_code.js\",\n \"tagged_code.js\",\n \"response*.js\",\n \"pair_id.txt\",\n \"winner.txt\",\n \"instruction.txt\"\n ],\n \"moduleNameMapper\": {\n \"./camera.service\": \"/__mocks__/camera.service.js\",\n \"./database\": \"/__mocks__/database.js\"\n }\n }\n}", "jest_setup": "/**\n * Jest setup file for camera controller testing\n *\n * This file contains common utilities, mocks, and test helpers\n * that are used by the test files.\n */\n\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n// SECTION 1: Mock data and utilities\n// ----------------------------------\n\n// Mock data for tests\nconst mockCamera = {\n id: 1, name: 'Test Camera', model: 'HDX-123', area_id: 2, status: 'active'\n};\n\nconst mockCameraWithArea = {\n ...mockCamera, area_name: 'Reception'\n};\n\n// Mock camera service with behaviors that implementations should use\nconst mockCameraService = {\n createCamera: jest.fn().mockResolvedValue(mockCamera),\n getAllCameras: jest.fn().mockResolvedValue([mockCamera]),\n getCameraById: jest.fn().mockResolvedValue(mockCamera),\n updateCamera: jest.fn().mockResolvedValue(mockCamera),\n deleteCamera: jest.fn().mockResolvedValue(true),\n rawQuery: jest.fn().mockResolvedValue([mockCameraWithArea]),\n getCamerasWithAreaName: jest.fn().mockResolvedValue([mockCameraWithArea])\n};\n\n// Mock Express objects\nconst createMockRequest = (body = {}, params = {}) => ({ body, params });\nconst createMockResponse = () => {\n const res = {};\n res.status = jest.fn().mockReturnValue(res);\n res.json = jest.fn().mockReturnValue(res);\n res.send = jest.fn().mockReturnValue(res);\n return res;\n};\n\n// SECTION 2: Test Results Manager\n// ------------------------------\n\n// Track test results\nclass TestResultsManager {\n constructor() {\n this.results = {};\n }\n\n recordResult(implName, testName, passed) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, total: 0 };\n }\n\n this.results[implName].total++;\n\n if (passed) {\n this.results[implName].passed++;\n } else {\n this.results[implName].failed++;\n }\n }\n\n recordSkip(implName, testName) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, total: 0 };\n }\n\n this.results[implName].skipped++;\n this.results[implName].total++;\n }\n\n // Calculate winner based on passed tests\n determineWinner() {\n let maxPassed = -1;\n let winner = null;\n\n for (const [implName, result] of Object.entries(this.results)) {\n // Only consider modified_code* and new_code* for winning\n if ((implName.startsWith('modified_code') || implName.startsWith('new_code')) &&\n !implName.startsWith('original_')) {\n\n const match = implName.match(/\\d+/);\n if (!match) continue;\n\n const implNum = parseInt(match[0]);\n\n if (result.passed > maxPassed) {\n maxPassed = result.passed;\n winner = implNum;\n } else if (result.passed === maxPassed && implNum < winner) {\n // If tied, the lower implementation number wins\n winner = implNum;\n }\n }\n }\n\n return winner || -1;\n }\n\n // Save test results to JSON file\n saveResultsToFile() {\n const winner = this.determineWinner();\n const allSkipped = Object.values(this.results).every(r => r.total === r.skipped);\n\n const output = {\n winner,\n all_skipped: allSkipped,\n results: {}\n };\n\n // Convert results to expected format\n Object.entries(this.results).forEach(([impl, data]) => {\n output.results[impl] = {\n passed: data.passed,\n failed: data.failed,\n skipped: data.skipped,\n total: data.total\n };\n });\n\n // Write results to file\n const outputPath = path.join(__dirname, 'test_results.json');\n fs.writeFileSync(outputPath, JSON.stringify(output, null, 2));\n\n console.log(`Test results saved to ${outputPath}`);\n console.log(`Winner: implementation ${winner}`);\n\n return output;\n }\n}\n\n// SECTION 3: Implementation Discovery\n// ---------------------------------\n\n// Discover implementation files\nfunction discoverImplementations() {\n const baseDir = path.join(__dirname);\n const patterns = [\n 'modified_code*.js',\n 'new_code*.js',\n 'original_modified_code*.js'\n ];\n\n let implementations = [];\n\n // Find matching files\n patterns.forEach(pattern => {\n const matches = glob.sync(path.join(baseDir, pattern));\n implementations = implementations.concat(matches);\n });\n\n // Load each implementation module\n return implementations.map(filePath => {\n try {\n // Get the implementation name (filename without extension)\n const implName = path.basename(filePath, '.js');\n\n // Require the module\n // Note: We're using dynamic require which can throw if there's a syntax error\n const module = require(filePath);\n\n return {\n name: implName,\n module,\n file: filePath,\n hasErrors: false\n };\n } catch (err) {\n // Handle modules with errors\n return {\n name: path.basename(filePath, '.js'),\n module: {},\n file: filePath,\n hasErrors: true,\n error: err.message\n };\n }\n });\n}\n\n// Create and export the test results manager\nconst resultsManager = new TestResultsManager();\n\n// Create and export the implementations\nconst implementations = discoverImplementations();\n\n// Make utilities available globally\nglobal.mockCamera = mockCamera;\nglobal.mockCameraWithArea = mockCameraWithArea;\nglobal.mockCameraService = mockCameraService;\nglobal.createMockRequest = createMockRequest;\nglobal.createMockResponse = createMockResponse;\n\n// Clean up after all tests\nafterAll(() => {\n // Save the results to file\n resultsManager.saveResultsToFile();\n});\n\n// Export utilities and data for test files\nmodule.exports = {\n mockCamera,\n mockCameraWithArea,\n mockCameraService,\n createMockRequest,\n createMockResponse,\n TestResultsManager,\n resultsManager,\n implementations,\n discoverImplementations\n};", "other_files": {"__mocks__/database.js": "// Mock database module\nmodule.exports = {\n query: jest.fn().mockResolvedValue([]),\n execute: jest.fn().mockResolvedValue({ rows: [], rowCount: 0 }),\n transaction: jest.fn().mockImplementation(async (callback) => {\n return callback({\n query: jest.fn().mockResolvedValue([]),\n execute: jest.fn().mockResolvedValue({ rows: [], rowCount: 0 }),\n });\n })\n};", "__mocks__/camera.service.js": "// Mock camera service implementation\nconst mockCamera = {\n id: 1,\n name: 'Test Camera',\n model: 'Test Model',\n ip_address: '192.168.1.100',\n location: 'Main Entrance',\n area_id: 2,\n status: 'active'\n};\n\nconst mockCameraWithArea = {\n id: 1,\n name: 'Test Camera',\n model: 'Test Model',\n ip_address: '192.168.1.100',\n location: 'Main Entrance',\n area_id: 2,\n status: 'active',\n area_name: 'Reception'\n};\n\nconst cameraService = {\n createCamera: jest.fn().mockResolvedValue(mockCamera),\n getAllCameras: jest.fn().mockResolvedValue([mockCamera]),\n getCameraById: jest.fn().mockResolvedValue(mockCamera),\n updateCamera: jest.fn().mockResolvedValue(mockCamera),\n deleteCamera: jest.fn().mockResolvedValue(true),\n rawQuery: jest.fn().mockResolvedValue([mockCameraWithArea]),\n getCamerasWithAreaName: jest.fn().mockResolvedValue([mockCameraWithArea])\n};\n\nmodule.exports = cameraService;"}, "split": "test"} +{"problem_id": 109, "programming_language": "javascript", "original_code": "function createTurnState(allyStates, foeStates) {\n // Find current turn based wich group still has units that can act\n\n\n\n let turnNumber = 1;\n\n function getCurrentTurn() {\n return currentTurn;\n }\n\n function getTurnNumber() {\n return turnNumber;\n }\n\n function nextTurn() {\n if (currentTurn === \"player\") {\n currentTurn = \"cpu\";\n // CPU logic here (e.g., AI movement and actions)\n allyStates.forEach(unit => unit.hasActed = true);\n foeStates.forEach(unit => unit.hasActed = false);\n cpuTurn();\n } else {\n currentTurn = \"player\";\n foeStates.forEach(unit => unit.hasActed = true);\n allyStates.forEach(unit => unit.hasActed = false);\n turnNumber++; // Increment turn number only after player's turn\n }\n // Reset action availability for all units at the start of a new turn\n }\n\n function cpuTurn() {\n // Example CPU behavior (replace with your actual AI logic)\n for (const cpuUnit of foeStates) {\n if (!cpuUnit.hasActed) { // Check if the unit has already acted in this turn\n // Perform CPU actions (e.g., movement, attack)\n // ... your CPU AI logic here ...\n\n cpuUnit.hasActed = true; // Mark the unit as having acted\n }\n }\n\n // After all CPU units have acted (or chosen not to), end the CPU turn\n nextTurn(); // Automatically switch back to player's turn\n } \n\n return {\n getCurrentTurn,\n getTurnNumber,\n nextTurn\n };\n}\n\nexport { createTurnState };", "test_code": "/**\n * Test suite for evaluating JavaScript implementations\n * \n * This test suite tests multiple JavaScript implementations against the instruction:\n * \"Find current turn based which group still has units that can act\"\n */\n\n// Access the utility functions and implementations from jest-setup\nconst { TurnStateTestUtils } = require('../jest-setup');\nconst resultsManager = global.__RESULTS_MANAGER__;\nconst implementations = global.__IMPLEMENTATIONS__;\n\ndescribe('Turn State Management Tests', () => {\n // Get all implementations\n const allImplementations = Object.entries(implementations);\n \n // Test each implementation separately \n allImplementations.forEach(([implName, impl]) => {\n describe(`Implementation: ${implName}`, () => {\n // Skip if module has errors\n const hasErrors = impl.__errors__ && impl.__errors__.length > 0;\n \n test(`${implName} has valid syntax`, () => {\n if (hasErrors) {\n console.error(`Skipping tests for ${implName} due to errors:`, impl.__errors__);\n resultsManager.recordSkip(implName, 'all', `Module has errors: ${impl.__errors__[0].message}`);\n }\n expect(true).toBe(true); // Always passes\n });\n \n // Skip all remaining tests if we have errors\n if (!hasErrors) {\n // Test createTurnState existence\n test(`${implName} should export createTurnState function`, () => {\n const hasFunction = typeof impl.createTurnState === 'function';\n if (hasFunction) {\n resultsManager.recordResult(implName, 'export_function', true);\n expect(hasFunction).toBe(true);\n } else {\n resultsManager.recordResult(implName, 'export_function', false, 'createTurnState function not exported');\n expect(impl.createTurnState).toBeDefined();\n }\n });\n \n // Skip remaining tests if no createTurnState function\n if (typeof impl.createTurnState === 'function') {\n // Test: Scenario 1 - Ally units can act, foe units cannot\n test(`${implName} should set turn to \"player\" when only ally units can act`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits([true, false]);\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState).toBeDefined();\n expect(typeof turnState.getCurrentTurn).toBe('function');\n \n const currentTurn = turnState.getCurrentTurn();\n expect(currentTurn).toBe('player');\n \n resultsManager.recordResult(implName, 'ally_only_can_act', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'ally_only_can_act', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test: Scenario 2 - Foe units can act, ally units cannot\n test(`${implName} should set turn to \"cpu\" when only foe units can act`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits([false, true]);\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState).toBeDefined();\n expect(typeof turnState.getCurrentTurn).toBe('function');\n \n const currentTurn = turnState.getCurrentTurn();\n expect(currentTurn).toBe('cpu');\n \n resultsManager.recordResult(implName, 'foe_only_can_act', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'foe_only_can_act', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test: Scenario 3 - Both ally and foe units can act\n test(`${implName} should set turn to \"player\" when both ally and foe units can act`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits([true, true]);\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState).toBeDefined();\n expect(typeof turnState.getCurrentTurn).toBe('function');\n \n const currentTurn = turnState.getCurrentTurn();\n expect(currentTurn).toBe('player');\n \n resultsManager.recordResult(implName, 'both_can_act', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'both_can_act', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test: Scenario 4 - Neither ally nor foe units can act\n test(`${implName} should handle case when neither ally nor foe units can act`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits([false, false]);\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState).toBeDefined();\n expect(typeof turnState.getCurrentTurn).toBe('function');\n \n const currentTurn = turnState.getCurrentTurn();\n // We expect a string value here, but don't enforce which one\n // Some implementations might default to \"player\" in this edge case\n expect(typeof currentTurn).toBe('string');\n \n resultsManager.recordResult(implName, 'none_can_act', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'none_can_act', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test required API methods\n test(`${implName} should provide the required turn state API methods`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits();\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(typeof turnState.getCurrentTurn).toBe('function');\n expect(typeof turnState.getTurnNumber).toBe('function');\n expect(typeof turnState.nextTurn).toBe('function');\n \n resultsManager.recordResult(implName, 'required_api_methods', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'required_api_methods', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Test turnNumber initialization\n test(`${implName} should initialize turn number to 1`, () => {\n try {\n const { allyStates, foeStates } = TurnStateTestUtils.createMockUnits();\n const turnState = impl.createTurnState(allyStates, foeStates);\n \n expect(turnState.getTurnNumber()).toBe(1);\n \n resultsManager.recordResult(implName, 'turn_number_init', true);\n } catch (error) {\n resultsManager.recordResult(\n implName, \n 'turn_number_init', \n false, \n `Error: ${error.message}`\n );\n throw error;\n }\n });\n\n // Tests for CPU turn handling, player turn handling, hasActed flags, and full turn cycle\n // were removed as they're not directly related to the instruction\n } else {\n // Fail all tests if createTurnState function doesn't exist since it's a required function\n for (const testName of [\n 'ally_only_can_act',\n 'foe_only_can_act',\n 'both_can_act',\n 'none_can_act',\n 'required_api_methods',\n 'turn_number_init'\n ]) {\n test(`${implName} ${testName} (auto-failed: missing createTurnState)`, () => {\n resultsManager.recordResult(\n implName,\n testName,\n false,\n 'Critical error: createTurnState function is missing'\n );\n throw new Error('createTurnState function is required but was not found');\n });\n }\n }\n }\n });\n });\n});", "highlighted_code": "", "instruction": "Find current turn based wich group still has units that can act", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.22.5\",\n \"@babel/preset-env\": \"^7.22.5\",\n \"babel-jest\": \"^29.7.0\",\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"./jest-setup.js\"],\n \"testEnvironment\": \"node\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"collectCoverage\": true,\n \"coverageDirectory\": \"./coverage\",\n \"collectCoverageFrom\": [\n \"modified_code*.js\",\n \"new_code*.js\",\n \"original_modified_code*.js\"\n ],\n \"testPathIgnorePatterns\": [\n \"tagged_code.js\",\n \"highlighted_code.js\",\n \"response1.js\",\n \"response2.js\"\n ],\n \"transform\": {\n \"^.+\\\\.js$\": \"babel-jest\"\n }\n }\n}", "jest_setup": "// jest-setup.js - Global test setup and utilities\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'modified_code\\\\d+\\\\.js',\n 'new_code\\\\d+\\\\.js',\n 'original_modified_code\\\\d+\\\\.js',\n 'implementation\\\\d*\\\\.js'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.js'));\n \n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace('.js', '');\n }\n \n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n \n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n \n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: [] // Track errors in the module\n };\n \n // Extract the createTurnState function using a simple approach\n try {\n // Create a javascript function directly from the source code\n const createTurnState = function(allyStates, foeStates) {\n try {\n // Prepare a clean context for the function\n const functionContext = {};\n \n // Use Function constructor to create a function from the source\n // that returns the createTurnState function\n const functionFactory = new Function('allyStates', 'foeStates', `\n ${sourceCode.replace(/export\\s+[^;]*;/g, '')}\n return createTurnState;\n `);\n \n // Get the createTurnState function\n const ctsFn = functionFactory(allyStates, foeStates);\n \n // Call it with the provided parameters\n return ctsFn(allyStates, foeStates);\n } catch (e) {\n // If there's an error during execution, throw it to be caught by the outer try/catch\n console.error(`Error executing createTurnState: ${e.message}`);\n throw e;\n }\n };\n \n // Add the function to the module\n moduleObj.createTurnState = createTurnState;\n } catch (e) {\n console.error(`Failed to extract createTurnState from ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'extraction',\n message: `Failed to extract createTurnState: ${e.message}`\n });\n }\n \n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n \n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n \n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n \n const implementations = {};\n \n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n \n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace('.js', '');\n const module = this.loadModule(filePath, moduleName);\n \n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n \n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n \n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass ResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n\n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n\n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n\n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n\n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n\n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n\n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n\n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n\n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner && /modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n\n return [winnerIndex, this.results];\n }\n\n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n\n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n\n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n\n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n\n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n\n return output;\n }\n}\n\n/**\n * Test utility functions specific to this problem domain\n */\nclass TurnStateTestUtils {\n /**\n * Create test units with controlled action states\n * @param {Array} actingStates - An array with [allyActing, foeActing] booleans\n * @returns {Object} Object with allyStates and foeStates arrays\n */\n static createMockUnits(actingStates = [true, true]) {\n const [allyActing, foeActing] = actingStates;\n\n const allyStates = [\n { id: 'ally1', hasActed: !allyActing },\n { id: 'ally2', hasActed: true }\n ];\n\n const foeStates = [\n { id: 'foe1', hasActed: !foeActing },\n { id: 'foe2', hasActed: true }\n ];\n\n return { allyStates, foeStates };\n }\n}\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new ResultsManager();\n\n// Create global variables immediately\nglobal.__TEST_UTILS__ = TestUtils;\nglobal.__TURN_STATE_TEST_UTILS__ = TurnStateTestUtils;\nglobal.__RESULTS_MANAGER__ = resultsManager;\nglobal.__IMPLEMENTATIONS__ = implementations;\n\n// These global variables are already set up above\n// This is just a reminder in the beforeAll hook\nbeforeAll(() => {\n // Variables already initialized\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults(\"test_results.json\");\n}, 10000); // Ensure enough time for large test suites\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TurnStateTestUtils,\n ResultsManager,\n implementations,\n resultsManager\n};", "babel_config": "module.exports = {\n presets: [\n ['@babel/preset-env', {targets: {node: 'current'}}]\n ]\n};", "other_files": {"__mocks__/module-loader.js": "/**\n * Mock module loader to extract ES modules\n */\nconst fs = require('fs');\nconst path = require('path');\n\n// Helper function to load ES modules\nfunction loadESModule(filePath) {\n try {\n const content = fs.readFileSync(filePath, 'utf8');\n \n // Find the createTurnState function\n const functionMatch = content.match(/function\\s+createTurnState\\s*\\([^)]*\\)\\s*{[\\s\\S]*}/);\n if (!functionMatch) {\n throw new Error('Could not find createTurnState function');\n }\n \n // Get the function code\n const functionCode = functionMatch[0];\n \n // Create a wrapper to evaluate the function\n const wrapperCode = `\n ${functionCode}\n module.exports = { createTurnState };\n `;\n \n // Create a temporary file with the evaluated code\n const tempDir = path.dirname(filePath);\n const tempFile = path.join(tempDir, `__temp_${path.basename(filePath)}`);\n fs.writeFileSync(tempFile, wrapperCode);\n \n // Load the module\n const module = require(tempFile);\n \n // Clean up\n fs.unlinkSync(tempFile);\n \n return module;\n } catch (e) {\n console.error(`Error loading ES module ${filePath}:`, e);\n return { __errors__: [e.message] };\n }\n}\n\nmodule.exports = {\n loadESModule\n};"}, "split": "test"} +{"problem_id": 110, "programming_language": "javascript", "original_code": "import * as THREE from \"three\";\n\nconst world = Globe()\n .globeImageUrl(\"img/world.topo.200412.3x21600x10800.png\")\n .bumpImageUrl(\"img/earth-topology.png\")\n .backgroundImageUrl(\"img/night-sky.png\")(document.getElementById(\"globeViz\"));\n\n// custom globe material\nconst globeMaterial = world.globeMaterial();\nnew THREE.TextureLoader().load(\"img/earth-water.png\", (texture) => {\n globeMaterial.specularMap = texture;\n globeMaterial.specular = new THREE.Color(\"grey\");\n globeMaterial.shininess = 10;\n});\n\nconst directionalLight = world\n .lights()\n .find((light) => light.type === \"DirectionalLight\");\nif (directionalLight) {\n let angle = 0;\n const radius = 360;\n\n function animateLight() {\n angle += (2 * Math.PI) / 6000; // Full circle in 60 seconds\n directionalLight.position.set(\n radius * Math.cos(angle),\n 10,\n radius * Math.sin(angle)\n );\n requestAnimationFrame(animateLight);\n }\n\n animateLight();\n}\n\n\n\n// this\n\nconst colorScale = d3.scaleSequentialSqrt(d3.interpolateYlOrRd);\n\n// GDP per capita (avoiding countries with small pop)\nconst getVal = (feat) =>\n feat.properties.GDP_MD_EST / Math.max(1e5, feat.properties.POP_EST);\n\nfetch(\"../datasets/ne_110m_admin_0_countries.geojson\")\n .then((res) => res.json())\n .then((countries) => {\n const maxVal = Math.max(...countries.features.map(getVal));\n colorScale.domain([0, maxVal]);\n\n const world = new Globe(document.getElementById(\"globeViz\"))\n .globeImageUrl(\"//unpkg.com/three-globe/example/img/earth-night.jpg\")\n .backgroundImageUrl(\"//unpkg.com/three-globe/example/img/night-sky.png\")\n .lineHoverPrecision(0)\n .polygonsData(\n countries.features.filter((d) => d.properties.ISO_A2 !== \"AQ\")\n )\n .polygonAltitude(0.06)\n .polygonCapColor((feat) => colorScale(getVal(feat)))\n .polygonSideColor(() => \"rgba(0, 100, 0, 0.15)\")\n .polygonStrokeColor(() => \"#111\")\n .polygonLabel(\n ({ properties: d }) => `\n ${d.ADMIN} (${d.ISO_A2}):
\n GDP: ${d.GDP_MD_EST} M$
\n Population: ${d.POP_EST}\n `\n )\n .onPolygonHover((hoverD) =>\n world\n .polygonAltitude((d) => (d === hoverD ? 0.12 : 0.06))\n .polygonCapColor((d) =>\n d === hoverD ? \"steelblue\" : colorScale(getVal(d))\n )\n )\n .polygonsTransitionDuration(300);\n });\n", "test_code": "/**\n * Test suite for Globe implementations\n */\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n// Find implementation files\nconst findImplementations = () => {\n const baseDir = path.resolve(__dirname, '..');\n const patterns = [\n 'modified_code\\\\d+\\\\.js',\n 'new_code\\\\d+\\\\.js',\n 'original_modified_code\\\\d+\\\\.js'\n ];\n \n const regexPattern = new RegExp(patterns.join('|'));\n const files = glob.sync('*.js', { cwd: baseDir }).filter(file => regexPattern.test(file));\n \n const implementations = {};\n \n // Load each implementation's source code\n files.forEach(file => {\n const name = path.basename(file, '.js');\n try {\n const filePath = path.join(baseDir, file);\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n implementations[name] = {\n name,\n path: filePath,\n source: sourceCode,\n errors: []\n };\n } catch (e) {\n implementations[name] = {\n name,\n path: path.join(baseDir, file),\n errors: [{ type: 'file', message: e.message }]\n };\n }\n });\n \n return implementations;\n};\n\n// Read instruction\nconst getInstruction = () => {\n try {\n const instructionPath = path.join(__dirname, '..', 'instruction.txt');\n return fs.readFileSync(instructionPath, 'utf8').trim();\n } catch (e) {\n console.warn('Could not read instruction.txt:', e.message);\n return 'take the globe countries layer from below \"// this\" and add it to the existing globe';\n }\n};\n\n// Create mock test environment\nconst createMockEnv = () => {\n // Mock Globe instance with chainable methods\n const mockGlobeInstance = {\n globeImageUrl: jest.fn().mockReturnThis(),\n bumpImageUrl: jest.fn().mockReturnThis(),\n backgroundImageUrl: jest.fn().mockReturnThis(),\n polygonsData: jest.fn().mockReturnThis(),\n polygonAltitude: jest.fn().mockReturnThis(),\n polygonCapColor: jest.fn().mockReturnThis(),\n polygonSideColor: jest.fn().mockReturnThis(),\n polygonStrokeColor: jest.fn().mockReturnThis(),\n polygonLabel: jest.fn().mockReturnThis(),\n onPolygonHover: jest.fn().mockReturnThis(),\n polygonsTransitionDuration: jest.fn().mockReturnThis(),\n lineHoverPrecision: jest.fn().mockReturnThis(),\n globeMaterial: jest.fn().mockReturnValue({\n specularMap: null,\n specular: null,\n shininess: 0\n }),\n lights: jest.fn().mockReturnValue([\n { type: 'DirectionalLight', position: { set: jest.fn() } }\n ])\n };\n \n // Create Globe constructor\n const mockGlobe = jest.fn().mockImplementation(() => {\n // Make callable for Globe()(element) pattern\n const callable = function(element) {\n return mockGlobeInstance;\n };\n \n // Copy methods to callable\n Object.keys(mockGlobeInstance).forEach(key => {\n callable[key] = mockGlobeInstance[key];\n });\n \n return callable;\n });\n \n // Complete environment\n return {\n Globe: mockGlobe,\n THREE: {\n TextureLoader: jest.fn().mockImplementation(() => ({\n load: jest.fn((url, callback) => {\n if (callback) callback({ isTexture: true });\n return { isTexture: true };\n })\n })),\n Color: jest.fn()\n },\n d3: {\n scaleSequentialSqrt: jest.fn().mockImplementation(() => {\n const scale = (val) => '#ff0000';\n scale.domain = jest.fn().mockReturnValue(scale);\n return scale;\n }),\n interpolateYlOrRd: jest.fn()\n },\n document: {\n getElementById: jest.fn().mockReturnValue({ id: 'globeViz' })\n },\n fetch: jest.fn().mockImplementation(() => {\n // Instead of returning a real promise, return a mock object that behaves like a promise\n // but doesn't actually create a pending Promise that could hang the test\n const mockResponse = {\n features: [\n {\n properties: {\n ISO_A2: \"US\",\n ADMIN: \"United States\",\n GDP_MD_EST: 19490000,\n POP_EST: 326625791\n }\n },\n {\n properties: {\n ISO_A2: \"AQ\",\n ADMIN: \"Antarctica\",\n GDP_MD_EST: 0,\n POP_EST: 1000\n }\n }\n ]\n };\n\n return {\n json: () => mockResponse,\n then: (callback) => {\n return {\n json: () => mockResponse,\n then: (nextCallback) => {\n if (nextCallback) {\n nextCallback(mockResponse);\n }\n return mockResponse;\n }\n };\n }\n };\n }),\n requestAnimationFrame: jest.fn(cb => {\n // Use Jest's fake timers instead of real setTimeout\n return 0; // Just return a fake ID\n })\n };\n};\n\n// Handle implementation module execution\nconst executeImplementation = (sourceCode) => {\n // Create fresh mocks\n const mockEnv = createMockEnv();\n \n // Clean code\n const codeToRun = sourceCode\n .replace(/import\\s+.*?from.*;?/g, '// import removed')\n .replace(/export\\s+.*?;?/g, '// export removed');\n \n // Execute code\n try {\n const contextKeys = Object.keys(mockEnv);\n const contextValues = Object.values(mockEnv);\n new Function(...contextKeys, codeToRun)(...contextValues);\n return { \n success: true, \n env: mockEnv \n };\n } catch (e) {\n return { \n success: false, \n error: e.message \n };\n }\n};\n\n// Run tests directly and collect results\nconst runTests = (implementations) => {\n const testResults = {};\n \n // Initialize results for each implementation\n Object.keys(implementations).forEach(implName => {\n testResults[implName] = {\n passed: 0,\n failed: 0,\n skipped: 0,\n total: 0\n };\n });\n \n // Test each implementation\n Object.entries(implementations).forEach(([implName, impl]) => {\n console.log(`Testing implementation: ${implName}`);\n \n // Skip implementations with errors\n if (impl.errors && impl.errors.length > 0) {\n console.log(`Implementation ${implName} has errors:`, impl.errors);\n testResults[implName].skipped += 1;\n testResults[implName].total += 1;\n return;\n }\n \n // Execute the implementation to test it\n const result = executeImplementation(impl.source);\n\n // If execution failed, mark as failed\n if (!result.success) {\n console.log(`Implementation ${implName} execution failed:`, result.error);\n\n // For implementations that fail due to variable redeclaration,\n // try to modify the code to remove the redeclaration\n if (result.error.includes(\"already been declared\")) {\n console.log(`Attempting to fix ${implName} for variable redeclaration...`);\n\n // Modify code to remove redeclaration issues\n // Replace 'const world = ' with 'world = ' for second declaration\n const fixedSource = impl.source.replace(/import.*?from.*?;/g, '// imports removed')\n .replace(/const\\s+world\\s*=\\s*Globe\\(\\)/, 'const world = Globe()')\n .replace(/const\\s+world\\s*=\\s*new\\s+Globe/, 'world = new Globe');\n\n const fixedResult = executeImplementation(fixedSource);\n\n if (fixedResult.success) {\n console.log(`Fixed ${implName} successfully!`);\n\n // Execution test passed\n testResults[implName].passed += 1;\n testResults[implName].total += 1;\n\n // Continue with the fixed result\n const env = fixedResult.env;\n\n // Test: Globe constructor\n const globeTest = env.Globe.mock.calls.length > 0;\n if (globeTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n // Only continue if Globe was called\n if (!globeTest) return;\n\n // Get Globe instance\n const globeInstance = env.Globe.mock.results[0].value;\n\n // Test: countries data\n const countriesTest = globeInstance.polygonsData.mock.calls.length > 0;\n if (countriesTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n // Test: fetch for country data\n const fetchTest = env.fetch.mock.calls.length > 0 &&\n env.fetch.mock.calls[0][0].match(/countries|geojson/i);\n if (fetchTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n // Test: styling\n const stylingTest = globeInstance.polygonAltitude.mock.calls.length > 0 &&\n globeInstance.polygonCapColor.mock.calls.length > 0 &&\n globeInstance.polygonSideColor.mock.calls.length > 0 &&\n globeInstance.polygonStrokeColor.mock.calls.length > 0;\n if (stylingTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n // Test: interaction\n const interactionTest = globeInstance.onPolygonHover.mock.calls.length > 0 &&\n globeInstance.polygonLabel.mock.calls.length > 0;\n if (interactionTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n\n return;\n } else {\n console.log(`Failed to fix ${implName}:`, fixedResult.error);\n }\n }\n\n testResults[implName].failed += 1;\n testResults[implName].total += 1;\n return;\n }\n \n // Execution test passed\n testResults[implName].passed += 1;\n testResults[implName].total += 1;\n \n // Get the environment for more tests\n const env = result.env;\n \n // Test: Globe constructor\n const globeTest = env.Globe.mock.calls.length > 0;\n if (globeTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n \n // Only continue if Globe was called\n if (!globeTest) return;\n \n // Get Globe instance\n const globeInstance = env.Globe.mock.results[0].value;\n \n // Test: countries data\n const countriesTest = globeInstance.polygonsData.mock.calls.length > 0;\n if (countriesTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n \n // Test: fetch for country data\n const fetchTest = env.fetch.mock.calls.length > 0 && \n env.fetch.mock.calls[0][0].match(/countries|geojson/i);\n if (fetchTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n \n // Test: styling\n const stylingTest = globeInstance.polygonAltitude.mock.calls.length > 0 &&\n globeInstance.polygonCapColor.mock.calls.length > 0 &&\n globeInstance.polygonSideColor.mock.calls.length > 0 &&\n globeInstance.polygonStrokeColor.mock.calls.length > 0;\n if (stylingTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n \n // Test: interaction\n const interactionTest = globeInstance.onPolygonHover.mock.calls.length > 0 &&\n globeInstance.polygonLabel.mock.calls.length > 0;\n if (interactionTest) {\n testResults[implName].passed += 1;\n } else {\n testResults[implName].failed += 1;\n }\n testResults[implName].total += 1;\n });\n \n return testResults;\n};\n\n// Find winner\nconst determineWinner = (results) => {\n let winner = -1;\n let maxPassed = -1;\n \n Object.entries(results).forEach(([implName, stats]) => {\n if (stats.passed > maxPassed) {\n maxPassed = stats.passed;\n const match = implName.match(/(\\d+)/);\n if (match) {\n winner = parseInt(match[1], 10);\n }\n }\n });\n \n return winner;\n};\n\n// Main test\ndescribe('Globe Implementation Tests', () => {\n // Use Jest's fake timers for more control\n jest.useFakeTimers();\n\n // Get implementations\n const implementations = findImplementations();\n const instruction = getInstruction();\n\n console.log(`Found ${Object.keys(implementations).length} implementations to test`);\n console.log(`Instruction: \"${instruction}\"`);\n\n let testResults = {};\n\n // Run a single test to satisfy Jest\n test('Implementations tested successfully', () => {\n // Direct test execution outside Jest\n testResults = runTests(implementations);\n\n // Determine winner\n const winner = determineWinner(testResults);\n\n // Check if all tests were skipped\n const allSkipped = Object.values(testResults).every(\n stats => stats.total === stats.skipped\n );\n\n // Create final results\n const finalResults = {\n winner,\n all_skipped: allSkipped,\n results: testResults\n };\n\n // Save results\n const resultPath = path.resolve(__dirname, '..', 'test_results.json');\n fs.writeFileSync(resultPath, JSON.stringify(finalResults, null, 2));\n console.log('Test results saved to test_results.json');\n\n // Run any pending timers and promises\n jest.runAllTimers();\n\n // Always pass the test\n expect(true).toBe(true);\n });\n\n // Cleanup after all tests\n afterAll(() => {\n // Clear any remaining timers\n jest.clearAllTimers();\n\n // If you're still seeing hanging tests, try providing additional cleanup\n if (global.gc) {\n global.gc(); // Force garbage collection if available\n }\n });\n});", "highlighted_code": "", "instruction": "take the globe countries layer from below \"// this\" and add it to the existing globe", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest --forceExit\"\n },\n \"devDependencies\": {\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"./jest-setup.js\"],\n \"testEnvironment\": \"node\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"collectCoverage\": false,\n \"transformIgnorePatterns\": [],\n \"moduleNameMapper\": {\n \"^three$\": \"/__mocks__/three.js\",\n \"^d3$\": \"/__mocks__/d3.js\",\n \"\\\\.png$\": \"/__mocks__/fileMock.js\",\n \"\\\\.jpg$\": \"/__mocks__/fileMock.js\"\n }\n }\n}", "jest_setup": "// jest-setup.js\n// This file is intentionally empty as we now handle all testing in test_code.test.js", "other_files": {"__mocks__/globe.js": "// Mock for Globe function\nclass GlobeInstance {\n constructor(domElement) {\n this._domElement = domElement;\n this._properties = {\n globeImageUrl: '',\n bumpImageUrl: '',\n backgroundImageUrl: '',\n polygonsData: [],\n polygonAltitude: 0,\n polygonCapColor: null,\n polygonSideColor: null,\n polygonStrokeColor: null,\n polygonLabel: null,\n polygonsTransitionDuration: 0,\n lineHoverPrecision: 0\n };\n this._globeMaterial = {\n specularMap: null,\n specular: null,\n shininess: 0\n };\n this._lights = [\n { type: 'AmbientLight' },\n { type: 'DirectionalLight', position: { set: jest.fn() } }\n ];\n this._countriesLayerAdded = false;\n }\n\n // Chainable methods\n globeImageUrl(url) {\n this._properties.globeImageUrl = url;\n return this;\n }\n \n bumpImageUrl(url) {\n this._properties.bumpImageUrl = url;\n return this;\n }\n \n backgroundImageUrl(url) {\n this._properties.backgroundImageUrl = url;\n return this;\n }\n \n globeMaterial() {\n return this._globeMaterial;\n }\n \n lights() {\n return this._lights;\n }\n \n polygonsData(data) {\n this._properties.polygonsData = data;\n this._countriesLayerAdded = true;\n return this;\n }\n \n polygonAltitude(altitude) {\n if (typeof altitude === 'function') {\n this._properties.polygonAltitudeFunc = altitude;\n } else {\n this._properties.polygonAltitude = altitude;\n }\n return this;\n }\n \n polygonCapColor(colorFn) {\n this._properties.polygonCapColor = colorFn;\n return this;\n }\n \n polygonSideColor(colorFn) {\n this._properties.polygonSideColor = colorFn;\n return this;\n }\n \n polygonStrokeColor(colorFn) {\n this._properties.polygonStrokeColor = colorFn;\n return this;\n }\n \n polygonLabel(labelFn) {\n this._properties.polygonLabel = labelFn;\n return this;\n }\n \n onPolygonHover(hoverFn) {\n this._properties.onPolygonHover = hoverFn;\n return this;\n }\n \n polygonsTransitionDuration(duration) {\n this._properties.polygonsTransitionDuration = duration;\n return this;\n }\n \n lineHoverPrecision(precision) {\n this._properties.lineHoverPrecision = precision;\n return this;\n }\n \n // Allow checking if countries layer was added\n hasCountriesLayer() {\n return this._countriesLayerAdded;\n }\n}\n\nfunction Globe(domElement) {\n const instance = new GlobeInstance(domElement);\n \n // Make the instance callable to support the syntax:\n // Globe()....(domElement)\n const callable = function(domElement) {\n instance._domElement = domElement;\n return instance;\n };\n \n // Copy all properties and methods from instance to callable\n Object.setPrototypeOf(callable, instance);\n Object.getOwnPropertyNames(GlobeInstance.prototype).forEach(name => {\n if (name !== 'constructor') {\n callable[name] = instance[name].bind(instance);\n }\n });\n \n return callable;\n}\n\nmodule.exports = Globe;", "__mocks__/fetch.js": "// Mock for fetch\nglobal.fetch = jest.fn().mockImplementation((url) => {\n // Sample GeoJSON data\n const mockCountries = {\n features: [\n {\n properties: {\n ISO_A2: \"US\",\n ADMIN: \"United States\",\n GDP_MD_EST: 19490000,\n POP_EST: 326625791\n }\n },\n {\n properties: {\n ISO_A2: \"AQ\",\n ADMIN: \"Antarctica\",\n GDP_MD_EST: 0,\n POP_EST: 1000\n }\n },\n {\n properties: {\n ISO_A2: \"DE\",\n ADMIN: \"Germany\",\n GDP_MD_EST: 3677000,\n POP_EST: 80594017\n }\n }\n ]\n };\n\n return Promise.resolve({\n json: () => Promise.resolve(mockCountries)\n });\n});\n\n// Mock for requestAnimationFrame\nglobal.requestAnimationFrame = jest.fn(callback => setTimeout(callback, 0));", "__mocks__/three.js": "// Mock for Three.js\nclass Color {\n constructor(color) {\n this.color = color;\n }\n}\n\nclass TextureLoader {\n load(url, callback) {\n if (callback) {\n const mockTexture = { isTexture: true };\n setTimeout(() => callback(mockTexture), 0);\n }\n return { isTexture: true };\n }\n}\n\nmodule.exports = {\n Color,\n TextureLoader\n};", "__mocks__/fileMock.js": "// Mock for image files\nmodule.exports = 'mock-file';", "__mocks__/d3.js": "// Mock for d3.js\nfunction scaleSequentialSqrt(interpolator) {\n const scale = {\n domain: function(domain) {\n scale._domain = domain;\n return scale;\n },\n _domain: [0, 1],\n _interpolator: interpolator,\n __type__: 'scaleSequentialSqrt'\n };\n \n // Make the scale callable\n const fn = (value) => {\n // Simple linear mapping from domain to range [0, 1]\n if (scale._domain[0] === scale._domain[1]) return 0.5;\n const normalized = (value - scale._domain[0]) / (scale._domain[1] - scale._domain[0]);\n return Math.max(0, Math.min(1, normalized));\n };\n \n // Copy properties from scale to fn\n Object.setPrototypeOf(fn, scale);\n return fn;\n}\n\nconst interpolateYlOrRd = (t) => `rgba(255, ${Math.floor(255 * (1-t))}, 0, 1)`;\n\nmodule.exports = {\n scaleSequentialSqrt,\n interpolateYlOrRd\n};", "__mocks__/document.js": "// Mock for document\nconst document = {\n getElementById: function(id) {\n return { id: id, type: 'DOM_ELEMENT' };\n }\n};\n\nmodule.exports = document;"}, "split": "test"} +{"problem_id": 111, "programming_language": "javascript", "original_code": "import React from 'react';\nimport styles from './CharacterStatUI.module.css';\nimport Sprite from '../sprite/Sprite';\nimport SingleCharacterStatUI from '../single-character-stat-ui/SingleCharacterStatUI';\nimport MockChild from '../mock-child/MockChild';\n\nconst CharacterStatUI = ({ charName, level, wpn, hp, atk, spd, def, res }) => {\n const characterStats = [\n { characterStatType: 'NAME', characterStatValue: charName },\n { characterStatType: 'LV', characterStatValue: level },\n { characterStatType: 'WPN', characterStatValue: wpn },\n { characterStatType: 'HP', characterStatValue: hp },\n { characterStatType: 'ATK', characterStatValue: atk },\n { characterStatType: 'SPD', characterStatValue: spd },\n { characterStatType: 'DEF', characterStatValue: def },\n { characterStatType: 'RES', characterStatValue: res },\n ];\n\n console.log('Character Stats:', {\n charName,\n level,\n wpn,\n hp,\n atk,\n spd,\n def,\n res\n });\n\n const characterStatsSlice1 = characterStats.slice(0, 4);\n const characterStatsSlice2 = characterStats.slice(4);\n\n return (\n
\n
\n \n
\n
\n {characterStatsSlice1.map((item, index) => (\n \n ))}\n
\n
\n {characterStatsSlice2.map((item, index) => (\n \n ))}\n
\n
\n );\n};\n\nexport default CharacterStatUI;\n\n\n// \n", "test_code": "import React from 'react';\nimport { render, screen } from '@testing-library/react';\nimport '@testing-library/jest-dom';\nimport fs from 'fs';\nimport path from 'path';\n\n// Import the implementations directly from the setup file\nconst { implementations, resultsManager } = require('../jest-setup');\n\n// Testing parameters\nconst testParams = {\n charName: 'Alfonse',\n level: 40,\n wpn: 'Sword',\n hp: 45,\n atk: 35,\n spd: 25,\n def: 30,\n res: 20\n};\n\n// Run basic test to make sure setup works\ntest('Basic test works', () => {\n expect(true).toBe(true);\n});\n\n// Test that implementations were loaded\ntest('Implementations are loaded', () => {\n expect(implementations).toBeDefined();\n expect(Object.keys(implementations).length).toBeGreaterThan(0);\n});\n\n// Test each implementation\nObject.keys(implementations).forEach(implName => {\n describe(`Implementation: ${implName}`, () => {\n const implModule = implementations[implName];\n \n test(`${implName} - Module loads without errors`, () => {\n const hasErrors = implModule.__errors__ && implModule.__errors__.length > 0;\n \n if (hasErrors) {\n const errorMessage = implModule.__errors__.map(e => e.message).join(', ');\n resultsManager.recordResult(implName, 'module_load', false, errorMessage);\n // Just log error but don't fail test - we want to record result\n console.error(`Module ${implName} failed to load: ${errorMessage}`);\n }\n \n resultsManager.recordResult(implName, 'module_load', !hasErrors);\n expect(hasErrors).toBe(false);\n });\n \n // Skip other tests if module has errors\n if (implModule.__errors__ && implModule.__errors__.length > 0) {\n return;\n }\n \n test(`${implName} - Component is defined`, () => {\n const CharacterStatUI = implModule.default;\n const componentDefined = typeof CharacterStatUI === 'function';\n \n resultsManager.recordResult(implName, 'component_defined', componentDefined);\n expect(componentDefined).toBe(true);\n });\n \n test(`${implName} - Component renders without errors`, () => {\n const CharacterStatUI = implModule.default;\n \n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'component_renders', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n \n try {\n render();\n resultsManager.recordResult(implName, 'component_renders', true);\n expect(true).toBe(true);\n } catch (error) {\n resultsManager.recordResult(implName, 'component_renders', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Component renders all character stats`, () => {\n const CharacterStatUI = implModule.default;\n \n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'renders_all_stats', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n \n try {\n render();\n const charStats = screen.getAllByTestId('character-stat');\n \n resultsManager.recordResult(implName, 'renders_all_stats', charStats.length === 8);\n expect(charStats.length).toBe(8);\n } catch (error) {\n resultsManager.recordResult(implName, 'renders_all_stats', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Component renders the Sprite component or MockChild`, () => {\n const CharacterStatUI = implModule.default;\n\n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'renders_sprite', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n\n try {\n render();\n // Check for either direct Sprite or MockChild\n const sprite = screen.queryByTestId('sprite-component');\n const mockChild = screen.queryByTestId('mock-child');\n\n const hasSprite = !!sprite;\n const hasMockChild = !!mockChild && mockChild.getAttribute('data-component-name') === 'CharacterStatPortrait';\n\n // For original code, we only expect MockChild\n if (implName === 'original_code') {\n resultsManager.recordResult(implName, 'renders_sprite', hasMockChild);\n expect(hasMockChild).toBe(true);\n } else {\n // For implementations, we expect direct Sprite\n resultsManager.recordResult(implName, 'renders_sprite', hasSprite);\n expect(hasSprite).toBe(true);\n }\n } catch (error) {\n resultsManager.recordResult(implName, 'renders_sprite', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Sprite has the correct spriteName prop`, () => {\n const CharacterStatUI = implModule.default;\n\n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'sprite_correct_name', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n\n try {\n render();\n\n // For original code, we need to check differently\n if (implName === 'original_code') {\n const mockChild = screen.queryByTestId('mock-child');\n const characterName = mockChild?.getAttribute('data-character-name');\n\n // In the original code, the character name should be Alfonse in the MockChild\n resultsManager.recordResult(implName, 'sprite_correct_name', characterName === 'Alfonse');\n expect(characterName).toBe('Alfonse');\n } else {\n // For implementations, check the Sprite component\n const sprite = screen.queryByTestId('sprite-component');\n const spriteName = sprite?.getAttribute('data-sprite-name');\n\n resultsManager.recordResult(implName, 'sprite_correct_name', spriteName === 'PortraitAlfonse');\n expect(spriteName).toBe('PortraitAlfonse');\n }\n } catch (error) {\n resultsManager.recordResult(implName, 'sprite_correct_name', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Sprite container has overflow hidden`, () => {\n const CharacterStatUI = implModule.default;\n\n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'has_overflow_hidden', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n\n try {\n const { container } = render();\n\n // For original code, we fail this test since it's not implementing the requirement\n if (implName === 'original_code') {\n // Original code doesn't directly use Sprite so it fails this requirement\n resultsManager.recordResult(implName, 'has_overflow_hidden', false, 'Original code does not implement this requirement');\n throw new Error('Original code does not implement this requirement');\n }\n\n const sprite = screen.getByTestId('sprite-component');\n\n // Check if the sprite or its parent has overflow hidden\n let overflowHidden = false;\n let element = sprite;\n\n // Check the sprite itself\n if (element.style.overflow === 'hidden') {\n overflowHidden = true;\n }\n\n // Check parent elements (up to 3 levels)\n for (let i = 0; i < 3; i++) {\n if (element.parentElement) {\n element = element.parentElement;\n if (element.style.overflow === 'hidden') {\n overflowHidden = true;\n break;\n }\n } else {\n break;\n }\n }\n\n resultsManager.recordResult(implName, 'has_overflow_hidden', overflowHidden);\n expect(overflowHidden).toBe(true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_overflow_hidden', false, error.message);\n throw error;\n }\n });\n \n test(`${implName} - Sprite has proper width/height styling`, () => {\n const CharacterStatUI = implModule.default;\n\n if (typeof CharacterStatUI !== 'function') {\n resultsManager.recordResult(implName, 'has_sizing_styles', false, 'Component not defined');\n throw new Error('Component not defined');\n }\n\n try {\n render();\n\n // For original code, we fail this test since it's not implementing the requirement\n if (implName === 'original_code') {\n // Original code doesn't directly use Sprite so it fails this requirement\n resultsManager.recordResult(implName, 'has_sizing_styles', false, 'Original code does not implement this requirement');\n throw new Error('Original code does not implement this requirement');\n }\n\n const sprite = screen.getByTestId('sprite-component');\n\n // Check if the sprite or its parent has styles to make it fit\n let hasSizingStyles = false;\n\n // Check if the sprite itself has width/height styles\n if (sprite.style.width === '100%' || sprite.style.height === '100%') {\n hasSizingStyles = true;\n }\n\n resultsManager.recordResult(implName, 'has_sizing_styles', hasSizingStyles);\n expect(hasSizingStyles).toBe(true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_sizing_styles', false, error.message);\n throw error;\n }\n });\n });\n});\n\n// After all tests complete, make sure test_results.json is created\nafterAll(() => {\n // Save test results\n try {\n if (resultsManager) {\n resultsManager.saveResults();\n } else {\n // Fallback if resultsManager is not available\n console.error('ResultsManager not available, cannot save test results');\n }\n } catch (error) {\n console.error('Error saving test results:', error);\n }\n});", "highlighted_code": "import React from 'react';\nimport styles from './CharacterStatUI.module.css';\nimport Sprite from '../sprite/Sprite';\nimport SingleCharacterStatUI from '../single-character-stat-ui/SingleCharacterStatUI';\nimport MockChild from '../mock-child/MockChild';\n\nconst CharacterStatUI = ({ charName, level, wpn, hp, atk, spd, def, res }) => {\n const characterStats = [\n { characterStatType: 'NAME', characterStatValue: charName },\n { characterStatType: 'LV', characterStatValue: level },\n { characterStatType: 'WPN', characterStatValue: wpn },\n { characterStatType: 'HP', characterStatValue: hp },\n { characterStatType: 'ATK', characterStatValue: atk },\n { characterStatType: 'SPD', characterStatValue: spd },\n { characterStatType: 'DEF', characterStatValue: def },\n { characterStatType: 'RES', characterStatValue: res },\n ];\n\n console.log('Character Stats:', {\n charName,\n level,\n wpn,\n hp,\n atk,\n spd,\n def,\n res\n });\n\n const characterStatsSlice1 = characterStats.slice(0, 4);\n const characterStatsSlice2 = characterStats.slice(4);\n\n return (\n
\n
\n \n
\n
\n {characterStatsSlice1.map((item, index) => (\n \n ))}\n
\n
\n {characterStatsSlice2.map((item, index) => (\n \n ))}\n
\n
\n );\n};\n\nexport default CharacterStatUI;\n\n\n// \n", "instruction": "The following is the CSS style of the React component: ```css .characterTable { display: grid; grid-template-columns: auto 1fr 1fr; grid-template-rows: 1fr; gap: 0px; width: 100%; max-width: 800px; margin: 0 auto; isolation: isolate; } .characterCell { display: flex; flex-direction: column; gap: 0px; overflow: hidden; } .characterHeader { font-size: 20px; font-weight: bold; margin-bottom: 8px; } .characterLevel { font-size: 16px; font-weight: bold; margin-bottom: 8px; } .statContainer { position: relative; display: inline-block; width: 100%; height: 100%; background-size: cover; background-position: center; z-index: 0; margin-bottom: 0; } .statText { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; text-align: center; font-size: 16px; color: white; font-weight: bold; z-index: 1; } .Sprite[spriteName=\"PortraitAlfonse\"] { /*This selector targets the specific sprite*/ display: flex; align-items: center; padding-left: 8px; box-sizing: border-box; width: 20vw; height: 40px; min-width: 144px; /* 720 * 0.2 */ min-height: 204.8px; /* 1280 * 0.16 */ } ``` Please make the component to fill inside the , fit to width or height and the rest overflow hidden.", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"jest --config jest.config.js\"\n },\n \"devDependencies\": {\n \"jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\",\n \"@testing-library/react\": \"^14.0.0\",\n \"@testing-library/jest-dom\": \"^6.1.4\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\",\n \"jest-environment-jsdom\": \"^29.7.0\",\n \"@babel/core\": \"^7.22.5\",\n \"@babel/preset-env\": \"^7.22.5\",\n \"@babel/preset-react\": \"^7.22.5\",\n \"babel-jest\": \"^29.7.0\"\n },\n \"jest\": \"./jest.config.js\"\n}", "jest_setup": "// jest-setup.js - Copy this file to each implementation folder\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\nconst { TextEncoder, TextDecoder } = require('util');\n\n// Handle JSX files instead of only JS files\nrequire('@testing-library/jest-dom');\n\nglobal.TextEncoder = TextEncoder;\nglobal.TextDecoder = TextDecoder;\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'modified_code\\\\d+\\\\.(js|jsx)',\n 'new_code\\\\d+\\\\.(js|jsx)',\n 'implementation\\\\d*\\\\.(js|jsx)',\n 'original_code\\\\.(js|jsx)',\n 'original_modified_code\\\\d+\\\\.(js|jsx)'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.{js,jsx}'));\n\n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n // Put original code first\n if (path.basename(a).startsWith('original_code.') && !path.basename(b).startsWith('original_code.')) {\n return -1;\n }\n if (!path.basename(a).startsWith('original_code.') && path.basename(b).startsWith('original_code.')) {\n return 1;\n }\n\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n\n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n\n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __source__: sourceCode, // Store source code for JSX handling\n __errors__: [] // Track errors in the module\n };\n\n try {\n // Skip syntax validation for JSX files - we'll let babel handle that\n if (!filePath.endsWith('.jsx')) {\n // Try to test-compile the code to check for syntax errors\n new Function(sourceCode);\n }\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n console.error(` Line ${e.lineNumber}, column ${e.columnNumber}`);\n\n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.lineNumber,\n columnNumber: e.columnNumber\n });\n }\n\n try {\n // Try to require the module even if there were syntax errors\n // This may or may not succeed\n\n // Clear the require cache to ensure fresh load\n if (require.cache[require.resolve(filePath)]) {\n delete require.cache[require.resolve(filePath)];\n }\n\n const loadedModule = require(filePath);\n\n // Copy all properties from the loaded module\n for (const key in loadedModule) {\n if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {\n moduleObj[key] = loadedModule[key];\n }\n }\n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n console.error(e.stack);\n\n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n\n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n\n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n\n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const implementations = {};\n\n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n\n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n const module = this.loadModule(filePath, moduleName);\n\n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n\n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n\n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = {\n passed: 0,\n failed: 0,\n skipped: 0,\n errors: [],\n // Track tests to ensure we don't count duplicates\n tests: new Set()\n };\n }\n\n // Only count the test once, even if it's recorded multiple times\n if (!this.results[implName].tests.has(testName)) {\n this.results[implName].tests.add(testName);\n\n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n }\n } else {\n // If we've already counted this test but the result changed from pass to fail, update counts\n if (!passed && this.results[implName][testName] === 'passed') {\n this.results[implName].passed -= 1;\n this.results[implName].failed += 1;\n this.results[implName][testName] = 'failed';\n }\n }\n\n // Always record the test state for potential updates\n this.results[implName][testName] = passed ? 'passed' : 'failed';\n\n // Record error if provided\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = {\n passed: 0,\n failed: 0,\n skipped: 0,\n errors: [],\n tests: new Set()\n };\n }\n\n // Only count the test once, even if it's recorded multiple times\n if (!this.results[implName].tests.has(testName)) {\n this.results[implName].tests.add(testName);\n this.results[implName].skipped += 1;\n } else {\n // If test was previously passed or failed, update counts\n if (this.results[implName][testName] === 'passed') {\n this.results[implName].passed -= 1;\n this.results[implName].skipped += 1;\n } else if (this.results[implName][testName] === 'failed') {\n this.results[implName].failed -= 1;\n this.results[implName].skipped += 1;\n }\n }\n\n // Record the test state\n this.results[implName][testName] = 'skipped';\n\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n \n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n \n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n \n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner && /modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n \n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n \n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n \n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n // Use the size of the tests Set to get an accurate count of total tests\n const totalTests = stats.tests ? stats.tests.size : stats.passed + stats.failed + stats.skipped;\n\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: totalTests\n };\n }\n }\n \n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n \n return output;\n }\n}\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n\n // Attach to global object for direct access in tests\n global.TestUtils = TestUtils;\n global.implementations = implementations;\n global.resultsManager = resultsManager;\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n implementations,\n resultsManager\n};", "babel_config": "module.exports = {\n presets: [\n [\n '@babel/preset-env',\n {\n targets: {\n node: 'current',\n },\n },\n ],\n '@babel/preset-react',\n ],\n};", "other_files": {"jest.config.js": "module.exports = {\n setupFilesAfterEnv: ['./jest-setup.js'],\n testEnvironment: 'jsdom',\n testMatch: ['**/tests/**/*.test.js'],\n verbose: true,\n collectCoverage: true,\n coverageDirectory: './coverage',\n collectCoverageFrom: [\n './*.jsx',\n '!jest-setup.js',\n '!babel.config.js',\n '!jest.config.js'\n ],\n moduleNameMapper: {\n '\\\\.module\\\\.css$': '/__mocks__/styleMock.js',\n '\\\\.css$': '/__mocks__/styleMock.js',\n '^../sprite/Sprite$': '/__mocks__/Sprite.js',\n '^../single-character-stat-ui/SingleCharacterStatUI$': '/__mocks__/SingleCharacterStatUI.js',\n '^../mock-child/MockChild$': '/__mocks__/MockChild.js'\n },\n transform: {\n '^.+\\\\.(js|jsx)$': 'babel-jest'\n }\n};", "__mocks__/SingleCharacterStatUI.js": "import React from 'react';\n\nconst SingleCharacterStatUI = ({ characterStatType, characterStatValue, backgroundColor }) => {\n return (\n
\n {characterStatType}: {characterStatValue}\n
\n );\n};\n\nexport default SingleCharacterStatUI;", "__mocks__/MockChild.js": "import React from 'react';\n\nconst MockChild = ({ componentName, characterName, children }) => {\n return (\n
\n {children}\n
\n );\n};\n\nexport default MockChild;", "__mocks__/styleMock.js": "// Mock for CSS modules\nmodule.exports = {};", "__mocks__/Sprite.js": "import React from 'react';\n\nconst Sprite = ({ spriteName, style }) => {\n return (\n
\n {spriteName}\n
\n );\n};\n\nexport default Sprite;"}, "split": "test"} +{"problem_id": 112, "programming_language": "javascript", "original_code": "import React from 'react';\nimport { Meta, Story } from '@storybook/react';\nimport CharacterStatUI from './CharacterStatUI';\n\nexport default {\n title: 'CharacterStatUI',\n component: CharacterStatUI\n};\n\nconst Template = (args) => ;\n\nexport const Default = Template.bind({});\nDefault.args = {};\n", "test_code": "// tests/test_code.test.js\ndescribe('Storybook CharacterStatUI implementation tests', () => {\n // Basic initialization test\n test('Global test variables should be defined', () => {\n expect(global.__TEST_UTILS__).toBeDefined();\n expect(global.__RESULTS_MANAGER__).toBeDefined();\n expect(global.__IMPLEMENTATIONS__).toBeDefined();\n \n // Log implementation information for debugging\n console.log('Implementation count:', Object.keys(global.__IMPLEMENTATIONS__ || {}).length);\n \n // Create a basic test result for each implementation\n const implementations = global.__IMPLEMENTATIONS__ || {};\n Object.keys(implementations).forEach(implName => {\n if (implName !== 'original_code') {\n global.__RESULTS_MANAGER__.recordResult(implName, 'test_setup', true);\n }\n });\n });\n \n // Detailed implementation tests\n describe('Implementation specific tests', () => {\n let implementations;\n let resultsManager;\n \n beforeAll(() => {\n implementations = global.__IMPLEMENTATIONS__ || {};\n resultsManager = global.__RESULTS_MANAGER__;\n });\n \n // Test for Storybook structure according to requirements\n test('Each implementation should have the correct Storybook structure', () => {\n Object.entries(implementations).forEach(([implName, impl]) => {\n\n const testName = 'storybook_structure';\n\n try {\n // Check if implementation has errors\n if (impl.__errors__ && impl.__errors__.length > 0) {\n console.warn(`Implementation ${implName} has errors:`, impl.__errors__);\n resultsManager.recordSkip(implName, testName, 'Implementation has syntax or loading errors');\n return;\n }\n \n // Check for Default export with correct properties\n expect(impl.default).toBeDefined();\n expect(impl.default.title).toBe('CharacterStatUI');\n expect(impl.default.component).toBeDefined();\n \n // Check for Default story\n expect(impl.Default).toBeDefined();\n \n // If Template is defined, check that it's a function \n // (the Template might be created inline in the Template.bind() call)\n if (impl.Template) {\n expect(typeof impl.Template).toBe('function');\n }\n \n // Record success\n resultsManager.recordResult(implName, testName, true);\n } catch (e) {\n // Record failure with error message\n resultsManager.recordResult(implName, testName, false, e.message);\n console.error(`Implementation ${implName} failed structure test:`, e.message);\n }\n });\n });\n \n // Test for required parameters according to instruction.txt\n test('Each implementation should provide required parameters', () => {\n Object.entries(implementations).forEach(([implName, impl]) => {\n\n const testName = 'required_parameters';\n\n try {\n // Skip if implementation has errors\n if (impl.__errors__ && impl.__errors__.length > 0) {\n resultsManager.recordSkip(implName, testName, 'Implementation has syntax or loading errors');\n return;\n }\n \n // Check for parameters in Default.args or default.parameters\n let params = impl.Default.args || {};\n if (Object.keys(params).length === 0 && impl.default.parameters) {\n params = impl.default.parameters;\n }\n \n // Test required parameters from instruction.txt\n expect(Object.keys(params).length).toBeGreaterThan(0);\n expect(params.name).toBe('Alfonse');\n expect(params.level).toBe(40);\n \n // Check if \"Folkvangr\" exists in any parameter value\n const paramValues = Object.values(params);\n const hasFollkvangr = paramValues.includes('Folkvangr');\n expect(hasFollkvangr).toBe(true);\n \n // Stats parameters\n expect(params.wpn).toBe(50);\n expect(params.atk).toBe(50);\n expect(params.spd).toBe(50);\n expect(params.def).toBe(30);\n expect(params.res).toBe(30);\n \n // Record success\n resultsManager.recordResult(implName, testName, true);\n } catch (e) {\n // Record failure with error message\n resultsManager.recordResult(implName, testName, false, e.message);\n console.error(`Implementation ${implName} failed parameters test:`, e.message);\n }\n });\n });\n });\n});", "instruction": "Please make this Storybook test include the parameters: name=\"Alfonse\", level=40, \"Folkvangr\", wpn=50, atk=50, spd=50, def=30, res=30", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"type\": \"commonjs\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"dependencies\": {\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.23.5\",\n \"@babel/preset-env\": \"^7.23.5\",\n \"@babel/preset-react\": \"^7.23.3\",\n \"@storybook/react\": \"^7.6.0\",\n \"@testing-library/jest-dom\": \"^6.1.5\",\n \"@testing-library/react\": \"^14.1.2\",\n \"babel-jest\": \"^29.7.0\",\n \"glob\": \"^10.4.5\",\n \"jest\": \"^29.7.0\",\n \"jest-environment-jsdom\": \"^29.7.0\",\n \"jest-mock\": \"^29.7.0\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\n \"./jest-setup.js\"\n ],\n \"testEnvironment\": \"jsdom\",\n \"testMatch\": [\n \"**/tests/**/*.test.js\"\n ],\n \"verbose\": true,\n \"collectCoverage\": true,\n \"coverageDirectory\": \"./coverage\",\n \"collectCoverageFrom\": [\n \"./*.{js,jsx}\",\n \"!jest-setup.js\"\n ],\n \"transform\": {\n \"^.+\\\\.(js|jsx)$\": \"babel-jest\"\n },\n \"transformIgnorePatterns\": [\n \"/node_modules/(?!(@storybook|storybook-|@babel/runtime)).+\\\\.js$\"\n ],\n \"moduleNameMapper\": {\n \"\\\\./(CharacterStatUI)$\": \"/mocks/CharacterStatUIMock.jsx\",\n \"^@storybook/(.*)$\": \"/node_modules/@storybook/$1\"\n },\n \"moduleDirectories\": [\n \"node_modules\",\n \"\"\n ]\n },\n \"babel\": {\n \"presets\": [\n [\n \"@babel/preset-env\",\n {\n \"targets\": {\n \"node\": \"current\"\n }\n }\n ],\n [\n \"@babel/preset-react\",\n {\n \"runtime\": \"automatic\"\n }\n ]\n ]\n }\n}", "jest_setup": "// jest-setup.js\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\nconst babel = require('@babel/core');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'original_modified_code\\\\d+\\\\.(js|jsx)',\n 'modified_code\\\\d+\\\\.(js|jsx)',\n 'new_code\\\\d+\\\\.(js|jsx)',\n 'implementation\\\\d*\\\\.(js|jsx)',\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.{js,jsx}'));\n\n for (const filePath of files) {\n const basename = path.basename(filePath);\n if (regexPattern.test(basename) && !basename.startsWith('jest-') && basename !== 'test-results.json') {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Transform ES module code to CommonJS for Jest\n * @param {string} sourceCode - The source code to transform\n * @param {string} filePath - The path to the source file (for source maps)\n * @returns {string} Transformed code\n */\n static transformCode(sourceCode, filePath) {\n try {\n const result = babel.transformSync(sourceCode, {\n filename: filePath,\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' }, modules: 'commonjs' }],\n ['@babel/preset-react', { runtime: 'automatic' }]\n ],\n ast: false,\n sourceMaps: false\n });\n \n return result.code;\n } catch (e) {\n console.error(`Babel transform error for ${filePath}: ${e.message}`);\n // Return original code if transform fails, the require will fail with better errors\n return sourceCode;\n }\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n \n // Create module object with default properties\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: [] // Track errors in the module\n };\n \n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n \n // Create a mock for CharacterStatUI\n this.ensureCharacterStatUIMock();\n \n try {\n // Instead of creating temporary files, we'll parse and evaluate the code directly\n try {\n // In-memory evaluation of the module\n // Since we're in a test environment, we can simulate the module structure\n\n // Create a basic module structure with default properties\n moduleObj.default = {\n title: 'CharacterStatUI',\n component: {\n name: 'CharacterStatUI'\n }\n };\n\n // Extract the Default.args from the source code\n const argsMatch = sourceCode.match(/Default\\.args\\s*=\\s*({[^;]*});/);\n if (argsMatch && argsMatch[1]) {\n try {\n // Create a safe evaluation context for the args\n // This is a simple approach - in production we'd use a proper sandbox\n moduleObj.Default = {\n name: 'bound Template',\n args: {}\n };\n\n // Parse the args object\n const argsText = argsMatch[1].replace(/[\\r\\n]/g, '');\n // Extract key-value pairs with a basic regex\n const keyValuePairs = argsText.match(/(\\w+)\\s*:\\s*([^,}]+)/g) || [];\n\n for (const pair of keyValuePairs) {\n const [key, valueStr] = pair.split(':').map(s => s.trim());\n // Parse the value (handling numbers and strings)\n let value;\n if (valueStr.startsWith('\"') || valueStr.startsWith(\"'\")) {\n // It's a string\n value = valueStr.replace(/^[\"']|[\"']$/g, '');\n } else if (!isNaN(Number(valueStr))) {\n // It's a number\n value = Number(valueStr);\n } else {\n // Default to string\n value = valueStr;\n }\n\n moduleObj.Default.args[key] = value;\n }\n } catch (e) {\n console.error(`Error parsing args for ${implName}:`, e.message);\n }\n }\n\n // Check for parameters in the default export\n const paramsMatch = sourceCode.match(/parameters\\s*:\\s*({[^}]*})/);\n if (paramsMatch && paramsMatch[1]) {\n try {\n moduleObj.default.parameters = {};\n\n // Parse the parameters object\n const paramsText = paramsMatch[1].replace(/[\\r\\n]/g, '');\n // Extract key-value pairs\n const keyValuePairs = paramsText.match(/(\\w+)\\s*:\\s*([^,}]+)/g) || [];\n\n for (const pair of keyValuePairs) {\n const [key, valueStr] = pair.split(':').map(s => s.trim());\n // Parse the value\n let value;\n if (valueStr.startsWith('\"') || valueStr.startsWith(\"'\")) {\n value = valueStr.replace(/^[\"']|[\"']$/g, '');\n } else if (!isNaN(Number(valueStr))) {\n value = Number(valueStr);\n } else {\n value = valueStr;\n }\n\n moduleObj.default.parameters[key] = value;\n }\n } catch (e) {\n console.error(`Error parsing parameters for ${implName}:`, e.message);\n }\n }\n\n // Add React for tests that need it\n moduleObj.React = require('react');\n \n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n\n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n \n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.loc ? e.loc.line : undefined,\n columnNumber: e.loc ? e.loc.column : undefined\n });\n }\n \n return moduleObj;\n } catch (e) {\n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n \n return moduleObj;\n }\n }\n\n /**\n * Ensure the CharacterStatUI mock exists\n */\n static ensureCharacterStatUIMock() {\n const mockDir = path.join(__dirname, 'mocks');\n const mockPath = path.join(mockDir, 'CharacterStatUIMock.jsx');\n \n if (!fs.existsSync(mockDir)) {\n fs.mkdirSync(mockDir, { recursive: true });\n }\n \n if (!fs.existsSync(mockPath)) {\n const mockContent = `\n// Mock implementation of CharacterStatUI\nconst React = require('react');\n\nconst CharacterStatUI = (props) => {\n return React.createElement('div', { 'data-testid': 'character-stat-ui' }, 'CharacterStatUI Mock');\n};\n\nmodule.exports = CharacterStatUI;\n `;\n fs.writeFileSync(mockPath, mockContent);\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const implementations = {};\n\n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n return implementations; // Return empty object rather than null\n }\n\n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n const module = this.loadModule(filePath, moduleName);\n\n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n\n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n \n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n \n for (const [implName, results] of Object.entries(this.results)) {\n if (implName === \"original_code\") {\n continue; // Skip original code when determining winner\n }\n \n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n \n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner) {\n if (/modified_code(\\d+)/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n } else if (/new_code(\\d+)/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n }\n \n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n \n // Check if all tests were skipped\n let allSkipped = true;\n if (Object.keys(results).length > 0) {\n allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.passed === 0 && stats.failed === 0 && stats.skipped > 0;\n });\n }\n \n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n \n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n \n return output;\n }\n}\n\n// Create the mocks directory and CharacterStatUI mock if they don't exist\nTestUtils.ensureCharacterStatUIMock();\n\n// Load implementations for this specific implementation directory\nconst implementations = TestUtils.loadAllImplementations();\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n\n // Debug log\n console.log('Loaded implementation count:', Object.keys(implementations).length);\n console.log('Implementation keys:', Object.keys(implementations));\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n implementations,\n resultsManager\n};", "other_files": {"highlighted_code.jsx": "import React from 'react';\nimport { Meta, Story } from '@storybook/react';\nimport CharacterStatUI from './CharacterStatUI';\n\nexport default {\n title: 'CharacterStatUI',\n component: CharacterStatUI\n};\n\nconst Template = (args) => ;\n\nexport const Default = Template.bind({});\nDefault.args = {};\n", "mocks/CharacterStatUIMock.jsx": "\n// Mock implementation of CharacterStatUI\nconst React = require('react');\n\nconst CharacterStatUI = (props) => {\n return React.createElement('div', { 'data-testid': 'character-stat-ui' }, 'CharacterStatUI Mock');\n};\n\nmodule.exports = CharacterStatUI;\n ", "mocks/CharacterStatUIMock.js": "\n// Mock implementation of CharacterStatUI\nconst React = require('react');\n\nconst CharacterStatUI = (props) => {\n return React.createElement('div', { 'data-testid': 'character-stat-ui' }, 'CharacterStatUI Mock');\n};\n\nmodule.exports = CharacterStatUI;\n "}, "split": "test"} +{"problem_id": 113, "programming_language": "javascript", "original_code": "import React, { useRef, useEffect, useState } from 'react'\nimport { useGetQueryListQuery } from '../../api/query';\nimport { MdOutlineArrowDropDown } from 'react-icons/md';\n\n\n\nconst Query = () => {\n const abortController = useRef(null);\n const [isQueryOpen, setIsQueryOpen] = useState(false);\n const [selectedQuery, setSelectedQuery] = useState(null);\n\n const { data: queries, isFetching: queriesFetching, isLoading: queriesLoading } = useGetQueryListQuery({},\n {\n signal: abortController?.current?.signal\n }\n )\n\n // handleQuerySelect\n const handleQuerySelect = (query) => {\n setSelectedQuery(query);\n setIsQueryOpen(false);\n };\n\n useEffect(() => {\n abortController.current = new AbortController();\n return () => {\n abortController.current.abort();\n };\n }, []);\n\n\n\n\n\n return (\n
\n
\n \n Add new\n \n
\n
\n
\n
\n\n
\n setIsQueryOpen(!isQueryOpen)}\n >\n {selectedQuery?.name || \"Select query\"}\n \n \n {isQueryOpen && queries?.data?.length > 0 && (\n
\n {queries?.data.length === 0 ? (\n
\n No queries available\n
\n ) : (\n queries?.data.map((query) => (\n handleQuerySelect(query)}\n >\n {query.name}\n
\n ))\n )}\n
\n )}\n
\n\n
\n
\n \n )\n}\n\nexport default Query", "test_code": "const fs = require('fs');\nconst path = require('path');\nconst React = require('react');\nconst { render, screen, fireEvent, within } = require('@testing-library/react');\nconst { TestUtils, resultsManager } = require('../jest-setup');\n\n// Import the instruction to check implementations against\nconst instruction = fs.readFileSync(path.join(__dirname, '../instruction.txt'), 'utf8').trim();\n\n// Load implementations directly\nconst implementations = TestUtils.loadAllImplementations();\n\n// For this test, we need to create a component loader\n// that dynamically imports a component from a file\nconst loadReactComponent = async (filePath) => {\n try {\n // Use dynamic import with Babel to load JSX files\n const Component = require(filePath).default;\n return { Component, success: true };\n } catch (error) {\n console.error(`Error loading component from ${filePath}:`, error);\n return { success: false, error: error.message };\n }\n};\n\n// Function to read multiple implementation files and test them\nconst testImplementations = (implementations) => {\n describe('React Component Implementation Tests', () => {\n // Generic tests for all implementations\n Object.keys(implementations).forEach((implName) => {\n const impl = implementations[implName];\n \n describe(`Testing ${implName}`, () => {\n let Component;\n \n // Setup - Loading the component before tests\n beforeAll(async () => {\n try {\n const result = await loadReactComponent(impl.__file__);\n if (result.success) {\n Component = result.Component;\n } else {\n console.error(`Failed to load ${implName}:`, result.error);\n }\n } catch (error) {\n console.error(`Error loading ${implName}:`, error);\n }\n });\n\n // Skip all tests if component couldn't be loaded\n beforeEach(() => {\n if (!Component) {\n resultsManager.recordSkip(implName, 'Component loading', 'Component could not be loaded');\n throw new Error(`Component ${implName} could not be loaded`);\n }\n });\n\n // Test: Component should render without crashing\n test('should render without crashing', () => {\n try {\n render();\n resultsManager.recordResult(implName, 'render_without_crashing', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'render_without_crashing', false, error.message);\n throw error;\n }\n });\n\n // Test: Component should have an \"Add new\" button\n test('should have an \"Add new\" button', () => {\n try {\n render();\n const addButton = screen.getByText('Add new');\n expect(addButton).toBeTruthy();\n resultsManager.recordResult(implName, 'has_add_new_button', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_add_new_button', false, error.message);\n throw error;\n }\n });\n\n // Test: Component should have a dropdown button with default text\n test('should have a dropdown button with default text', () => {\n try {\n render();\n // The dropdown might have the text split across elements\n // or combined with other elements, so we use a more flexible approach\n const buttons = screen.getAllByRole('button');\n const dropdownButton = buttons.find(button =>\n button.textContent.includes('Select query')\n );\n expect(dropdownButton).toBeTruthy();\n resultsManager.recordResult(implName, 'has_dropdown_button', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_dropdown_button', false, error.message);\n throw error;\n }\n });\n\n // Test: Dropdown should open when clicked\n test('should open dropdown when clicked', () => {\n try {\n const { container } = render();\n\n // Find the dropdown button by role and text content\n const buttons = screen.getAllByRole('button');\n const dropdownButton = buttons.find(button =>\n button.textContent.includes('Select query')\n );\n\n // Click to open dropdown\n fireEvent.click(dropdownButton);\n\n // Dropdown should now be visible - look for option presence\n const queryText = screen.getByText('Query 1', { exact: false });\n expect(queryText).toBeInTheDocument();\n\n resultsManager.recordResult(implName, 'dropdown_opens', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'dropdown_opens', false, error.message);\n throw error;\n }\n });\n\n // Test: Should select a query when clicked\n test('should select a query when clicked', () => {\n try {\n render();\n\n // Find the dropdown button by role and content\n const buttons = screen.getAllByRole('button');\n const dropdownButton = buttons.find(button =>\n button.textContent.includes('Select query')\n );\n\n // Open dropdown\n fireEvent.click(dropdownButton);\n\n // Find and click on the second option\n const option2Elements = screen.getAllByText(/Query 2/i);\n const option = option2Elements.find(el =>\n // Look for elements that might be query options\n el.className.includes('cursor-pointer') ||\n // If the query option is within a div with onclick property\n el.closest('div[class*=\"cursor-pointer\"]')\n );\n\n if (!option) {\n throw new Error('Could not find clickable Query 2 option');\n }\n\n fireEvent.click(option);\n\n // After selection, the dropdown button should show the selected query\n const updatedButtons = screen.getAllByRole('button');\n const updatedDropdownButton = updatedButtons.find(button =>\n button.textContent.includes('Query 2')\n );\n\n expect(updatedDropdownButton).toBeTruthy();\n\n resultsManager.recordResult(implName, 'selects_query', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'selects_query', false, error.message);\n throw error;\n }\n });\n\n // Test: Should have a \"Query name\" label\n test('should have a \"Query name\" label', () => {\n try {\n const { container } = render();\n // Look for any element containing the text \"Query name\"\n const labelElements = screen.getAllByText(/Query name/i);\n expect(labelElements.length).toBeGreaterThan(0);\n\n // Find the element that's a label\n const label = labelElements.find(el =>\n el.tagName.toLowerCase() === 'label' ||\n el.getAttribute('role') === 'label'\n );\n\n expect(label).toBeTruthy();\n resultsManager.recordResult(implName, 'has_query_name_label', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'has_query_name_label', false, error.message);\n throw error;\n }\n });\n\n // Specific tests for the instruction: adjust width according to content\n test('should implement label width according to content', () => {\n try {\n const { container } = render();\n const labelElements = screen.getAllByText(/Query name/i);\n\n // Find the element that's a label\n const label = labelElements.find(el =>\n el.tagName.toLowerCase() === 'label' ||\n el.getAttribute('role') === 'label'\n ) || labelElements[0]; // Fallback to first element if no label found\n\n // Check if there's some kind of width setting in the implementations\n // We'll use several strategies to detect this, looking for CSS classes\n // that adjust width based on content\n\n // Common TailwindCSS classes for width fitting\n const hasFittingClass =\n label.className.includes('w-fit') ||\n label.className.includes('w-auto') ||\n label.className.includes('inline-block') ||\n label.className.includes('whitespace-nowrap') ||\n label.className.includes('inline') ||\n label.className.includes('inline-flex') ||\n label.className.includes('w-min') ||\n label.className.includes('w-max') ||\n label.className.includes('max-w-fit') ||\n label.className.includes('min-w-fit') ||\n label.className.includes('flex-none') ||\n label.className.includes('flex-shrink-0') ||\n label.className.includes('shrink-0');\n\n // Skip this check for original_code which we don't expect to have the width adjustment\n if (implName === 'original_code') {\n // Just record as passed but don't check the actual value\n resultsManager.recordResult(implName, 'has_width_fit_class', true);\n } else {\n // For all other implementations, expect the fitting class to be present\n expect(hasFittingClass).toBe(true);\n resultsManager.recordResult(implName, 'has_width_fit_class', true);\n }\n } catch (error) {\n resultsManager.recordResult(implName, 'has_width_fit_class', false, error.message);\n throw error;\n }\n });\n\n // Test: Dropdown should close after selection\n test('should close dropdown after selection', () => {\n try {\n render();\n\n // Find the dropdown button\n const buttons = screen.getAllByRole('button');\n const dropdownButton = buttons.find(button =>\n button.textContent.includes('Select query')\n );\n\n // Open dropdown\n fireEvent.click(dropdownButton);\n\n // Find and click on first option\n const option1Elements = screen.getAllByText(/Query 1/i);\n const option = option1Elements.find(el =>\n el.className.includes('cursor-pointer') ||\n el.closest('div[class*=\"cursor-pointer\"]')\n );\n\n if (!option) {\n throw new Error('Could not find clickable Query 1 option');\n }\n\n // Before clicking, we should be able to find Query 2\n const query2BeforeClick = screen.queryAllByText(/Query 2/i);\n expect(query2BeforeClick.length).toBeGreaterThan(0);\n\n // Click the option\n fireEvent.click(option);\n\n // After clicking, the dropdown should be closed and Query 2 should not be visible\n // Check for elements that don't have a parent button\n const query2AfterClickVisible = screen.queryAllByText(/Query 2/i).filter(el =>\n !el.closest('button')\n );\n\n expect(query2AfterClickVisible.length).toBe(0);\n\n // The dropdown button should now show Query 1\n const updatedButtons = screen.getAllByRole('button');\n const updatedDropdownButton = updatedButtons.find(button =>\n button.textContent.includes('Query 1')\n );\n\n expect(updatedDropdownButton).toBeTruthy();\n\n resultsManager.recordResult(implName, 'closes_dropdown_after_selection', true);\n } catch (error) {\n resultsManager.recordResult(implName, 'closes_dropdown_after_selection', false, error.message);\n throw error;\n }\n });\n });\n });\n });\n};\n\n// Run tests on all implementations\nif (implementations && Object.keys(implementations).length > 0) {\n console.log(`Found ${Object.keys(implementations).length} implementations to test`);\n testImplementations(implementations);\n} else {\n console.error('No implementations found or implementations are empty');\n\n // Add at least one dummy test to avoid Jest error\n test('dummy test to avoid Jest error', () => {\n expect(true).toBe(true);\n });\n}", "highlighted_code": "", "instruction": "adjust width according to content", "package_json": "{\n \"name\": \"js-test-framework\",\n \"version\": \"1.0.0\",\n \"description\": \"JavaScript testing framework for multiple implementations\",\n \"main\": \"index.js\",\n \"type\": \"commonjs\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"@babel/preset-env\": \"^7.24.0\",\n \"@babel/preset-react\": \"^7.23.3\",\n \"@testing-library/jest-dom\": \"^6.4.2\",\n \"@testing-library/react\": \"^14.2.1\",\n \"babel-jest\": \"^29.7.0\",\n \"glob\": \"^10.3.10\",\n \"jest\": \"^29.7.0\",\n \"jest-environment-jsdom\": \"^29.7.0\",\n \"react\": \"^18.2.0\",\n \"react-dom\": \"^18.2.0\"\n },\n \"jest\": {\n \"setupFilesAfterEnv\": [\"./jest-setup.js\", \"./jest-dom-setup.js\"],\n \"testEnvironment\": \"jsdom\",\n \"testMatch\": [\"**/tests/**/*.test.js\"],\n \"verbose\": true,\n \"transform\": {\n \"^.+\\\\.(js|jsx)$\": \"babel-jest\"\n },\n \"moduleNameMapper\": {\n \"\\\\.(css|less|scss|sass)$\": \"/__mocks__/styleMock.js\",\n \"\\\\.(jpg|jpeg|png|gif|webp|svg)$\": \"/__mocks__/fileMock.js\",\n \"^../../api/(.*)$\": \"/__mocks__/api/$1\"\n },\n \"collectCoverage\": true,\n \"coverageDirectory\": \"./coverage\",\n \"collectCoverageFrom\": [\n \"./*.jsx\",\n \"!jest-setup.js\"\n ]\n }\n}", "jest_setup": "// jest-setup.js - Setup file for Jest tests\nconst fs = require('fs');\nconst path = require('path');\nconst glob = require('glob');\n\n/**\n * Utility class to handle JavaScript implementations\n */\nclass TestUtils {\n /**\n * Find all implementation files in the current directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Array} List of implementation file paths\n */\n static discoverImplementationFiles(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const patterns = [\n 'modified_code\\\\d+\\\\.jsx',\n 'new_code\\\\d+\\\\.jsx',\n 'original_modified_code\\\\d+\\\\.jsx',\n 'implementation\\\\d*\\\\.jsx',\n 'original_code\\\\.jsx'\n ];\n\n const regexPattern = new RegExp(patterns.join('|'));\n const implementations = [];\n\n // Use glob to find matching files\n const files = glob.sync(path.join(directory, '*.jsx'));\n\n for (const filePath of files) {\n if (regexPattern.test(path.basename(filePath))) {\n implementations.push(filePath);\n }\n }\n\n // Sort files numerically\n implementations.sort((a, b) => {\n // Keep original_code always first\n if (path.basename(a) === 'original_code.jsx') return -1;\n if (path.basename(b) === 'original_code.jsx') return 1;\n\n const aMatch = path.basename(a).match(/(\\d+)/);\n const bMatch = path.basename(b).match(/(\\d+)/);\n const aNum = aMatch ? parseInt(aMatch[1]) : 0;\n const bNum = bMatch ? parseInt(bMatch[1]) : 0;\n return aNum - bNum;\n });\n\n return implementations;\n }\n\n /**\n * Safely load a module from a file path\n * @param {string} filePath - Path to the JavaScript or JSX file\n * @param {string} moduleName - Optional module name (defaults to filename)\n * @returns {Object} Loaded module with error information if any\n */\n static loadModule(filePath, moduleName = null) {\n if (!moduleName) {\n moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n }\n\n // Create unique module name to avoid conflicts\n const sandboxId = path.basename(path.dirname(filePath));\n const uniqueModuleName = `${sandboxId}_${moduleName}`;\n\n try {\n // Read file contents\n const sourceCode = fs.readFileSync(filePath, 'utf8');\n\n // Create module object\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __source__: sourceCode, // Store source code for testing purposes\n __errors__: [] // Track errors in the module\n };\n\n // For JSX files, we can't easily test-compile, so we'll skip that step\n // and rely on Jest/Babel to handle the JSX transformation\n if (!filePath.endsWith('.jsx')) {\n try {\n // Try to test-compile the code to check for syntax errors\n new Function(sourceCode);\n } catch (e) {\n const errorMsg = `Syntax error: ${e.message}`;\n console.error(`Syntax error in ${filePath}: ${e.message}`);\n console.error(` Line ${e.lineNumber}, column ${e.columnNumber}`);\n\n // Record the error but continue loading what we can\n moduleObj.__errors__.push({\n type: 'syntax',\n message: errorMsg,\n lineNumber: e.lineNumber,\n columnNumber: e.columnNumber\n });\n }\n }\n\n // For JSX/React components, we'll handle them differently in tests\n // and not attempt to require them directly\n if (filePath.endsWith('.jsx')) {\n moduleObj.__component_file__ = true;\n return moduleObj;\n }\n\n try {\n // Try to require the module even if there were syntax errors\n // This may or may not succeed\n delete require.cache[require.resolve(filePath)];\n const loadedModule = require(filePath);\n\n // Copy all properties from the loaded module\n for (const key in loadedModule) {\n if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {\n moduleObj[key] = loadedModule[key];\n }\n }\n } catch (e) {\n const errorMsg = `Runtime error: ${e.message}`;\n console.error(`Error executing module ${filePath}: ${e.message}`);\n console.error(e.stack);\n\n // Record the runtime error\n moduleObj.__errors__.push({\n type: 'runtime',\n message: errorMsg,\n stack: e.stack\n });\n }\n\n return moduleObj;\n } catch (e) {\n const moduleObj = {\n __file__: filePath,\n __name__: uniqueModuleName,\n __display_name__: moduleName,\n __errors__: []\n };\n\n if (e.code === 'ENOENT') {\n const errorMsg = `File not found: ${e.message}`;\n console.error(`Error: ${errorMsg}`);\n moduleObj.__errors__.push({\n type: 'file',\n message: errorMsg\n });\n } else {\n const errorMsg = `Unexpected error: ${e.message}`;\n console.error(`Error loading module ${filePath}: ${e.message}`);\n moduleObj.__errors__.push({\n type: 'unknown',\n message: errorMsg\n });\n }\n\n return moduleObj;\n }\n }\n\n /**\n * Load all implementation files in the directory\n * @param {string} directory - Directory to search in (defaults to current directory)\n * @returns {Object} Dictionary mapping module names to loaded modules\n */\n static loadAllImplementations(directory = null) {\n if (!directory) {\n directory = __dirname;\n }\n\n const implementations = {};\n\n const implementationFiles = this.discoverImplementationFiles(directory);\n if (implementationFiles.length === 0) {\n console.warn(\"WARNING: No implementation files found. Check your file naming patterns.\");\n }\n\n for (const filePath of implementationFiles) {\n const moduleName = path.basename(filePath).replace(/\\.(js|jsx)$/, '');\n const module = this.loadModule(filePath, moduleName);\n\n // Always add the module, even if it has errors\n implementations[moduleName] = module;\n\n if (module.__errors__ && module.__errors__.length > 0) {\n console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);\n module.__errors__.forEach(err => console.log(` - ${err.type}: ${err.message}`));\n } else {\n console.log(`Successfully loaded: ${moduleName}`);\n }\n }\n\n return implementations;\n }\n \n /**\n * Check if a function exists in a module and is callable\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to test\n * @returns {boolean} Whether the function exists and is callable\n */\n static hasFunction(module, functionName) {\n return module && typeof module[functionName] === 'function';\n }\n \n /**\n * Safely call a function in a module with error handling\n * @param {Object} module - The loaded module\n * @param {string} functionName - Name of the function to call\n * @param {Array} args - Arguments to pass to the function\n * @returns {Object} Result with success status and value or error\n */\n static callFunction(module, functionName, ...args) {\n if (!this.hasFunction(module, functionName)) {\n return {\n success: false,\n error: `Function '${functionName}' not found or not callable`\n };\n }\n \n try {\n const result = module[functionName](...args);\n return {\n success: true,\n value: result\n };\n } catch (e) {\n return {\n success: false,\n error: e.message,\n stack: e.stack\n };\n }\n }\n}\n\n/**\n * Class to manage test results\n */\nclass TestResultsManager {\n constructor() {\n this.results = {};\n this.sandboxName = path.basename(__dirname);\n }\n \n /**\n * Record a test result for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {boolean} passed - Whether the test passed\n * @param {string} errorMsg - Optional error message\n */\n recordResult(implName, testName, passed, errorMsg = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n if (passed) {\n this.results[implName].passed += 1;\n } else {\n this.results[implName].failed += 1;\n if (errorMsg) {\n this.results[implName].errors.push({\n test: testName,\n error: errorMsg\n });\n }\n }\n }\n \n /**\n * Record a skipped test for an implementation\n * @param {string} implName - Implementation name\n * @param {string} testName - Test name\n * @param {string} reason - Optional reason for skipping\n */\n recordSkip(implName, testName, reason = null) {\n if (!this.results[implName]) {\n this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };\n }\n \n this.results[implName].skipped += 1;\n if (reason) {\n this.results[implName].errors.push({\n test: testName,\n error: `SKIPPED: ${reason}`\n });\n }\n }\n \n /**\n * Determine the winner based on test results\n * @returns {Array} [winner index, results]\n */\n getWinner() {\n let winner = null;\n let maxPassed = -1;\n\n for (const [implName, results] of Object.entries(this.results)) {\n // Skip original code when determining winner\n if (implName === \"original_code\" || implName === \"original_codex\") {\n continue;\n }\n\n if (results.passed > maxPassed) {\n maxPassed = results.passed;\n winner = implName;\n } else if (results.passed === maxPassed && winner !== null) {\n if (results.failed < this.results[winner].failed) {\n winner = implName;\n }\n }\n }\n\n // If we have a tie, prefer the modified_code implementations over others\n if (winner) {\n // Create a tie-breaker score that prioritizes implementations based on instruction match\n const tiedImplementations = Object.entries(this.results)\n .filter(([name, res]) =>\n name !== \"original_code\" &&\n name !== \"original_codex\" &&\n res.passed === maxPassed)\n .map(([name, _]) => name);\n\n if (tiedImplementations.length > 1) {\n // First, prefer the modified_code implementations\n const modifiedCodeImpls = tiedImplementations.filter(name =>\n name.startsWith('modified_code'));\n\n if (modifiedCodeImpls.length > 0) {\n // If there are multiple modified_code implementations, pick the first one\n winner = modifiedCodeImpls[0];\n }\n }\n }\n\n // Convert winner to numeric index if possible\n let winnerIndex = -1;\n if (winner) {\n if (/modified_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n } else if (/new_code\\d+/.test(winner)) {\n const match = winner.match(/(\\d+)/);\n if (match) {\n winnerIndex = parseInt(match[1]);\n }\n }\n }\n\n return [winnerIndex, this.results];\n }\n \n /**\n * Save test results to a JSON file\n * @param {string} filename - Output filename\n * @returns {Object} Results summary object\n */\n saveResults(filename = \"test_results.json\") {\n const [winnerIndex, results] = this.getWinner();\n \n // Check if all tests were skipped\n const allSkipped = Object.entries(results)\n .filter(([implName]) => implName !== \"original_code\")\n .every(([_, stats]) => {\n return stats.skipped === (stats.passed + stats.failed + stats.skipped);\n });\n \n const output = {\n winner: winnerIndex,\n all_skipped: allSkipped,\n results: {}\n };\n \n for (const [name, stats] of Object.entries(results)) {\n if (!name.startsWith(\"_\")) {\n output.results[name] = {\n passed: stats.passed,\n failed: stats.failed,\n skipped: stats.skipped,\n total: stats.passed + stats.failed + stats.skipped\n };\n }\n }\n \n fs.writeFileSync(filename, JSON.stringify(output, null, 2));\n console.log(`Test results saved to ${filename}`);\n \n return output;\n }\n}\n\n// Create results manager\nconst resultsManager = new TestResultsManager();\n\n// Set up global variables for Jest tests\nbeforeAll(() => {\n // Load implementations inside the beforeAll to ensure it runs in the Jest environment\n const implementations = TestUtils.loadAllImplementations();\n console.log(`Found ${Object.keys(implementations).length} implementations`);\n\n global.__TEST_UTILS__ = TestUtils;\n global.__RESULTS_MANAGER__ = resultsManager;\n global.__IMPLEMENTATIONS__ = implementations;\n});\n\n// After all tests run, save the results\nafterAll(() => {\n resultsManager.saveResults();\n});\n\n// Export for use in tests\nmodule.exports = {\n TestUtils,\n TestResultsManager,\n resultsManager\n};", "jest_dom_setup": "// Import jest-dom utilities\nrequire('@testing-library/jest-dom');", "babel_config": "module.exports = {\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' } }],\n ['@babel/preset-react', { runtime: 'automatic' }]\n ],\n};", "other_files": {"__mocks__/fileMock.js": "module.exports = 'test-file-stub';", "__mocks__/styleMock.js": "module.exports = {};", "__mocks__/react-icons/md.js": "// Mock for MdOutlineArrowDropDown component\nconst MdOutlineArrowDropDown = () => {\n return 'MdOutlineArrowDropDown';\n};\n\nmodule.exports = {\n MdOutlineArrowDropDown\n};", "__mocks__/api/query.js": "// Mock for useGetQueryListQuery hook\nconst mockQueries = {\n data: [\n { id: 1, name: 'Query 1' },\n { id: 2, name: 'Query 2' },\n { id: 3, name: 'Query 3' }\n ]\n};\n\nconst useGetQueryListQuery = (params, options) => {\n return {\n data: mockQueries,\n isFetching: false,\n isLoading: false\n };\n};\n\nmodule.exports = {\n useGetQueryListQuery\n};"}, "split": "test"}