Sys.Application.add_load Fires On Each Callback

本文探讨了ASP.NET Ajax中Sys.Application.add_load事件的行为特性,指出该事件不仅在页面首次加载时触发,还在每次回调时激活,这可能不符合开发者期望仅在页面加载时执行特定操作的需求。文章分析了这种行为的设计初衷,并讨论了命名规范可能导致的误解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ASP.NETAjax comes with a nice way to attach to a load event of a page. To doit just call Sys.Application.add_load and pass it a function as anargument. Done. Everything works as expected... WRONG!

It comes out that add_load fires on each callback and not only whenthe page loads for the first time. That is of course a problem if youwant something to happen on page load only.

From what I've been able to learn, this behavior is by design.Although it is never mentioned in a strigh forward way in a description:

"Raised after all scripts have been loaded and after the objects in the application have been created and initialized."

There are some places in the documentation, that suggests that thisis a way it was intended to be. First of all, ASP.NET Ajax tries tomimic that ASP.NET Page life cycle and as such, fires the load eventevery time there is a callback. The other thing that makes me believe,that load's behavior is there by design is this:

"You can use the event arguments to determine whether the page isbeing refreshed as a result of a partial-page update and whatcomponents were created since the previous load event was raised."

So now I know, but I still cannot accept the naming convention.Sys.Application plainly suggests, it's a kind of singleton, and not aper load thingy.

转载于:https://www.cnblogs.com/CodingPerfectWorld/archive/2010/07/29/1788029.html

import numpy as np import matplotlib.pyplot as plt import heapq import time import math from tqdm import tqdm class ThreatMap: def __init__(self, width, height, resolution=100): self.width = width self.height = height self.resolution = resolution # meters per grid cell self.terrain = np.zeros((width, height)) self.radars = [] self.fires = [] self.threat_map = np.zeros((width, height, 3)) # [terrain, radar, fire] self.combined_threat = np.zeros((width, height)) self.weights = np.array([0.2, 0.2, 0.3]) # Initial weights [wg, wR, wAA] def generate_terrain(self, terrain_type='mountain'): if terrain_type == 'mountain': # Generate mountain-like terrain x = np.linspace(0, 10, self.width) y = np.linspace(0, 10, self.height) X, Y = np.meshgrid(x, y) Z = 500 * np.sin(0.5*X) * np.cos(0.5*Y) + 300 self.terrain = Z.T elif terrain_type == 'valley': # Generate valley terrain for i in range(self.width): for j in range(self.height): self.terrain[i, j] = 100 + 50 * np.sin(i/20) + 50 * np.cos(j/20) # Normalize terrain self.terrain = (self.terrain - np.min(self.terrain)) / (np.max(self.terrain) - np.min(self.terrain)) * 1000 def add_radar(self, x, y, direction, max_range, fov=120): self.radars.append({ 'pos': (x, y), 'direction': direction, # in degrees 'max_range': max_range, # in meters 'fov': fov # field of view in degrees }) def add_fire(self, x, y, min_range, max_range): self.fires.append({ 'pos': (x, y), 'min_range': min_range, 'max_range': max_range }) def calculate_terrain_threat(self, x, y, z): h_max = np.max(self.terrain[x, y]) h_min = np.min(self.terrain[x, y]) return (h_max - h_min) / (z - h_max + 1e-5) def calculate_radar_threat(self, x, y, z): threat = 0 for radar in self.radars: rx, ry = radar['pos'] dx = (x - rx) * self.resolution dy = (y - ry) * self.resolution distance = np.sqrt(dx**2 + dy**2) # Check if within max range if distance > radar['max_range']: continue # Check if within field of view angle = math.degrees(math.atan2(dy, dx)) angle_diff = abs((angle - radar['direction'] + 180) % 360 - 180) if angle_diff > radar['fov'] / 2: continue # Calculate radar threat with exponential decay if distance < radar['max_range']: threat += np.exp(-10 * distance / radar['max_range']) return threat def calculate_fire_threat(self, x, y): threat = 0 for fire in self.fires: fx, fy = fire['pos'] dx = (x - fx) * self.resolution dy = (y - fy) * self.resolution distance = np.sqrt(dx**2 + dy**2) if distance < fire['min_range'] or distance > fire['max_range']: continue threat += np.exp(-10 * (distance - fire['min_range']) / (fire['max_range'] - fire['min_range'])) return threat def calculate_threats(self, z=500): for i in range(self.width): for j in range(self.height): # Terrain threat self.threat_map[i, j, 0] = self.calculate_terrain_threat(i, j, z) # Radar threat self.threat_map[i, j, 1] = self.calculate_radar_threat(i, j, z) # Fire threat self.threat_map[i, j, 2] = self.calculate_fire_threat(i, j) def variable_weighting(self, T): """Apply variable weighting based on threat levels""" S = np.array([ 1 + np.exp(T[0]), 1 + 1/(T[1] + 1), 1 + 1/(T[2] + 1) ]) W_prime = self.weights * S / np.sum(self.weights * S) return np.sum(W_prime * T) def combine_threats(self): for i in range(self.width): for j in range(self.height): T = self.threat_map[i, j] self.combined_threat[i, j] = self.variable_weighting(T) def plot_threat_map(self): plt.figure(figsize=(12, 10)) plt.imshow(self.combined_threat.T, origin='lower', cmap='hot') # Plot radars for radar in self.radars: x, y = radar['pos'] plt.scatter(x, y, s=100, c='blue', marker='^', label='Radar') # Plot fires for fire in self.fires: x, y = fire['pos'] plt.scatter(x, y, s=100, c='red', marker='o', label='Fire') plt.colorbar(label='Threat Level') plt.title('Combined Threat Map') plt.xlabel('X (grid cells)') plt.ylabel('Y (grid cells)') plt.legend() plt.show() class ImprovedARAStar: def __init__(self, threat_map, max_turn_angle=45): self.threat_map = threat_map self.width = threat_map.width self.height = threat_map.height self.resolution = threat_map.resolution self.max_turn_angle = max_turn_angle # in degrees self.k = 0.2 # Threat penalty coefficient self.epsilon = 2.0 # Initial epsilon def heuristic(self, a, b): # Euclidean distance return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) * self.resolution def get_neighbors(self, node, parent): neighbors = [] # 8-connected grid for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: if dx == 0 and dy == 0: continue x, y = node[0] + dx, node[1] + dy # Check bounds if x < 0 or x >= self.width or y < 0 or y >= self.height: continue # Check turn angle constraint if parent exists if parent: px, py = parent # Vector from parent to current node vec1 = (node[0] - px, node[1] - py) # Vector from current node to neighbor vec2 = (x - node[0], y - node[1]) # Calculate angle between vectors dot = vec1[0]*vec2[0] + vec1[1]*vec2[1] mag1 = math.sqrt(vec1[0]**2 + vec1[1]**2) mag2 = math.sqrt(vec2[0]**2 + vec2[1]**2) if mag1 > 0 and mag2 > 0: cos_angle = dot / (mag1 * mag2) angle = math.degrees(math.acos(max(min(cos_angle, 1), -1))) if angle > self.max_turn_angle: continue neighbors.append((x, y)) return neighbors def path_cost(self, a, b): # Euclidean distance dx = (a[0]-b[0]) * self.resolution dy = (a[1]-b[1]) * self.resolution return math.sqrt(dx**2 + dy**2) def plan(self, start, goal, max_time=60): OPEN = [] CLOSED = {} INCONS = {} # Initialize start node g_score = {start: 0} h_score = self.heuristic(start, goal) T_score = self.threat_map.combined_threat[start[0], start[1]] epsilon_s = self.epsilon * (1 + self.k * T_score) f_score = {start: g_score[start] + epsilon_s * h_score} heapq.heappush(OPEN, (f_score[start], start)) parent = {start: None} start_time = time.time() path_found = False while OPEN and time.time() - start_time < max_time: _, current = heapq.heappop(OPEN) if current == goal: path_found = True break CLOSED[current] = g_score[current] neighbors = self.get_neighbors(current, parent.get(current)) for neighbor in neighbors: # Calculate tentative g_score tentative_g = g_score[current] + self.path_cost(current, neighbor) # Get threat value for neighbor T_neighbor = self.threat_map.combined_threat[neighbor[0], neighbor[1]] epsilon_s = self.epsilon * (1 + self.k * T_neighbor) if neighbor in CLOSED and tentative_g >= CLOSED.get(neighbor, float('inf')): continue if tentative_g < g_score.get(neighbor, float('inf')): parent[neighbor] = current g_score[neighbor] = tentative_g h_val = self.heuristic(neighbor, goal) f_score[neighbor] = tentative_g + epsilon_s * h_val if neighbor in CLOSED: INCONS[neighbor] = g_score[neighbor] else: heapq.heappush(OPEN, (f_score[neighbor], neighbor)) # Reconstruct path path = [] if path_found: current = goal while current is not None: path.append(current) current = parent.get(current) path.reverse() # Calculate path metrics path_length = 0 threat_value = 0 if len(path) > 1: for i in range(1, len(path)): path_length += self.path_cost(path[i-1], path[i]) threat_value += self.threat_map.combined_threat[path[i][0], path[i][1]] threat_value /= len(path) return path, path_length, threat_value, time.time() - start_time def plot_path(self, path, title="Path Planning Result"): plt.figure(figsize=(12, 10)) plt.imshow(self.threat_map.combined_threat.T, origin='lower', cmap='hot') # Plot radars for radar in self.threat_map.radars: x, y = radar['pos'] plt.scatter(x, y, s=100, c='blue', marker='^', label='Radar') # Plot fires for fire in self.threat_map.fires: x, y = fire['pos'] plt.scatter(x, y, s=100, c='red', marker='o', label='Fire') # Plot path if path: path_x = [p[0] for p in path] path_y = [p[1] for p in path] plt.plot(path_x, path_y, 'g-', linewidth=2, label='Planned Path') plt.scatter(path_x[0], path_y[0], s=150, c='green', marker='o', label='Start') plt.scatter(path_x[-1], path_y[-1], s=150, c='purple', marker='*', label='Goal') plt.colorbar(label='Threat Level') plt.title(title) plt.xlabel('X (grid cells)') plt.ylabel('Y (grid cells)') plt.legend() plt.show() # Simulation and Experiment def run_simulation(): # Create threat map width, height = 100, 100 threat_map = ThreatMap(width, height, resolution=100) threat_map.generate_terrain('mountain') # Add threats (radars and fires) threat_map.add_radar(20, 80, 45, 5000) threat_map.add_radar(60, 40, 180, 4000) threat_map.add_radar(80, 70, 270, 6000) threat_map.add_fire(30, 30, 1000, 3000) threat_map.add_fire(50, 60, 1500, 4000) threat_map.add_fire(70, 20, 2000, 3500) # Calculate threats threat_map.calculate_threats(z=500) threat_map.combine_threats() # Plot threat map threat_map.plot_threat_map() # Create planner planner = ImprovedARAStar(threat_map) # Define scenarios scenarios = { 'Easy': {'start': (10, 90), 'goal': (90, 10), 'max_time': 60}, 'Medium': {'start': (5, 5), 'goal': (95, 95), 'max_time': 120}, 'Hard': {'start': (10, 50), 'goal': (90, 50), 'max_time': 300} } results = [] # Run simulations for name, params in scenarios.items(): print(f"\nRunning {name} scenario...") start, goal = params['start'], params['goal'] # Plan path path, length, threat, time_used = planner.plan(start, goal, params['max_time']) if path: print(f"Path found! Length: {length:.2f}m, Avg Threat: {threat:.4f}, Time: {time_used:.2f}s") planner.plot_path(path, title=f"{name} Scenario Path Planning") else: print("No path found!") results.append({ 'scenario': name, 'success': bool(path), 'path_length': length, 'avg_threat': threat, 'time': time_used }) # Print results print("\nSimulation Results:") print("{:<10} {:<10} {:<15} {:<15} {:<10}".format( "Scenario", "Success", "Path Length(m)", "Avg Threat", "Time(s)")) for res in results: print("{:<10} {:<10} {:<15.2f} {:<15.4f} {:<10.2f}".format( res['scenario'], str(res['success']), res['path_length'], res['avg_threat'], res['time'])) # Additional experiments (ablation study) print("\nRunning ablation study...") # Remove fire threats print("\nWithout fire threats:") threat_map_no_fire = ThreatMap(width, height, resolution=100) threat_map_no_fire.terrain = threat_map.terrain.copy() threat_map_no_fire.radars = threat_map.radars.copy() threat_map_no_fire.calculate_threats(z=500) threat_map_no_fire.combine_threats() planner_no_fire = ImprovedARAStar(threat_map_no_fire) path, length, threat, time_used = planner_no_fire.plan(scenarios['Medium']['start'], scenarios['Medium']['goal'], 120) planner_no_fire.plot_path(path, "Path Planning Without Fire Threats") # Remove radar threats print("\nWithout radar threats:") threat_map_no_radar = ThreatMap(width, height, resolution=100) threat_map_no_radar.terrain = threat_map.terrain.copy() threat_map_no_radar.fires = threat_map.fires.copy() threat_map_no_radar.calculate_threats(z=500) threat_map_no_radar.combine_threats() planner_no_radar = ImprovedARAStar(threat_map_no_radar) path, length, threat, time_used = planner_no_radar.plan(scenarios['Medium']['start'], scenarios['Medium']['goal'], 120) planner_no_radar.plot_path(path, "Path Planning Without Radar Threats") # Remove terrain threats print("\nWithout terrain threats:") threat_map_no_terrain = ThreatMap(width, height, resolution=100) threat_map_no_terrain.radars = threat_map.radars.copy() threat_map_no_terrain.fires = threat_map.fires.copy() threat_map_no_terrain.calculate_threats(z=500) threat_map_no_terrain.combine_threats() planner_no_terrain = ImprovedARAStar(threat_map_no_terrain) path, length, threat, time_used = planner_no_terrain.plan(scenarios['Medium']['start'], scenarios['Medium']['goal'], 120) planner_no_terrain.plot_path(path, "Path Planning Without Terrain Threats") if __name__ == "__main__": run_simulation() 生成的航迹为直线,且寻优时间总为0
06-12
RuntimeError Traceback (most recent call last) Cell In[19], line 2 1 # Train the model on the COCO8 example dataset for 100 epochs ----> 2 results = model.train(data="C:\\Users\\asus\\Downloads\\coco8.yaml", epochs=100, imgsz=640) File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\engine\model.py:799, in Model.train(self, trainer, **kwargs) 796 self.model = self.trainer.model 798 self.trainer.hub_session = self.session # attach optional HUB session --> 799 self.trainer.train() 800 # Update model and cfg after training 801 if RANK in {-1, 0}: File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\engine\trainer.py:227, in BaseTrainer.train(self) 224 ddp_cleanup(self, str(file)) 226 else: --> 227 self._do_train(world_size) File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\engine\trainer.py:348, in BaseTrainer._do_train(self, world_size) 346 if world_size > 1: 347 self._setup_ddp(world_size) --> 348 self._setup_train(world_size) 350 nb = len(self.train_loader) # number of batches 351 nw = max(round(self.args.warmup_epochs * nb), 100) if self.args.warmup_epochs > 0 else -1 # warmup iterations File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\engine\trainer.py:285, in BaseTrainer._setup_train(self, world_size) 283 if self.amp and RANK in {-1, 0}: # Single-GPU and DDP 284 callbacks_backup = callbacks.default_callbacks.copy() # backup callbacks as check_amp() resets them --> 285 self.amp = torch.tensor(check_amp(self.model), device=self.device) 286 callbacks.default_callbacks = callbacks_backup # restore callbacks 287 if RANK > -1 and world_size > 1: # DDP File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\utils\checks.py:782, in check_amp(model) 779 try: 780 from ultralytics import YOLO --> 782 assert amp_allclose(YOLO("yolo11n.pt"), im) 783 LOGGER.info(f"{prefix}checks passed ✅") 784 except ConnectionError: File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\utils\checks.py:770, in check_amp.<locals>.amp_allclose(m, im) 768 batch = [im] * 8 769 imgsz = max(256, int(model.stride.max() * 4)) # max stride P5-32 and P6-64 --> 770 a = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # FP32 inference 771 with autocast(enabled=True): 772 b = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # AMP inference File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\engine\model.py:185, in Model.__call__(self, source, stream, **kwargs) 156 def __call__( 157 self, 158 source: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor] = None, 159 stream: bool = False, 160 **kwargs: Any, 161 ) -> list: 162 """ 163 Alias for the predict method, enabling the model instance to be callable for predictions. 164 (...) 183 ... print(f"Detected {len(r)} objects in image") 184 """ --> 185 return self.predict(source, stream, **kwargs) File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\engine\model.py:555, in Model.predict(self, source, stream, predictor, **kwargs) 553 if prompts and hasattr(self.predictor, "set_prompts"): # for SAM-type models 554 self.predictor.set_prompts(prompts) --> 555 return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream) File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\engine\predictor.py:227, in BasePredictor.__call__(self, source, model, stream, *args, **kwargs) 225 return self.stream_inference(source, model, *args, **kwargs) 226 else: --> 227 return list(self.stream_inference(source, model, *args, **kwargs)) File D:\anaconda\envs\pytorch_env\lib\site-packages\torch\autograd\grad_mode.py:43, in _DecoratorContextManager._wrap_generator.<locals>.generator_context(*args, **kwargs) 40 try: 41 # Issuing `None` to a generator fires it up 42 with self.clone(): ---> 43 response = gen.send(None) 45 while True: 46 try: 47 # Forward the response to our caller and get its next request File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\engine\predictor.py:326, in BasePredictor.stream_inference(self, source, model, *args, **kwargs) 324 # Preprocess 325 with profilers[0]: --> 326 im = self.preprocess(im0s) 328 # Inference 329 with profilers[1]: File D:\anaconda\envs\pytorch_env\lib\site-packages\ultralytics\engine\predictor.py:167, in BasePredictor.preprocess(self, im) 165 im = im.transpose((0, 3, 1, 2)) # BHWC to BCHW, (n, 3, h, w) 166 im = np.ascontiguousarray(im) # contiguous --> 167 im = torch.from_numpy(im) 169 im = im.to(self.device) 170 im = im.half() if self.model.fp16 else im.float() # uint8 to fp16/32 RuntimeError: Numpy is not available
07-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值