code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
FROM python:3.12-slim
WORKDIR /app/OpenManus
RUN apt-get update && apt-get install -y --no-install-recommends git curl \
&& rm -rf /var/lib/apt/lists/* \
&& (command -v uv >/dev/null 2>&1 || pip install --no-cache-dir uv)
COPY . .
RUN uv pip install --system -r requirements.txt
CMD ["bash"]
|
2301_77160584/OpenManus
|
Dockerfile
|
Dockerfile
|
mit
| 305
|
# Python version check: 3.11-3.13
import sys
if sys.version_info < (3, 11) or sys.version_info > (3, 13):
print(
"Warning: Unsupported Python version {ver}, please use 3.11-3.13".format(
ver=".".join(map(str, sys.version_info))
)
)
|
2301_77160584/OpenManus
|
app/__init__.py
|
Python
|
mit
| 270
|
from app.agent.base import BaseAgent
from app.agent.planning import PlanningAgent
from app.agent.react import ReActAgent
from app.agent.swe import SWEAgent
from app.agent.toolcall import ToolCallAgent
__all__ = [
"BaseAgent",
"PlanningAgent",
"ReActAgent",
"SWEAgent",
"ToolCallAgent",
]
|
2301_77160584/OpenManus
|
app/agent/__init__.py
|
Python
|
mit
| 310
|
from abc import ABC, abstractmethod
from contextlib import asynccontextmanager
from typing import List, Optional
from pydantic import BaseModel, Field, model_validator
from app.llm import LLM
from app.logger import logger
from app.schema import ROLE_TYPE, AgentState, Memory, Message
class BaseAgent(BaseModel, ABC):
"""Abstract base class for managing agent state and execution.
Provides foundational functionality for state transitions, memory management,
and a step-based execution loop. Subclasses must implement the `step` method.
"""
# Core attributes
name: str = Field(..., description="Unique name of the agent")
description: Optional[str] = Field(None, description="Optional agent description")
# Prompts
system_prompt: Optional[str] = Field(
None, description="System-level instruction prompt"
)
next_step_prompt: Optional[str] = Field(
None, description="Prompt for determining next action"
)
# Dependencies
llm: LLM = Field(default_factory=LLM, description="Language model instance")
memory: Memory = Field(default_factory=Memory, description="Agent's memory store")
state: AgentState = Field(
default=AgentState.IDLE, description="Current agent state"
)
# Execution control
max_steps: int = Field(default=10, description="Maximum steps before termination")
current_step: int = Field(default=0, description="Current step in execution")
duplicate_threshold: int = 2
class Config:
arbitrary_types_allowed = True
extra = "allow" # Allow extra fields for flexibility in subclasses
@model_validator(mode="after")
def initialize_agent(self) -> "BaseAgent":
"""Initialize agent with default settings if not provided."""
if self.llm is None or not isinstance(self.llm, LLM):
self.llm = LLM(config_name=self.name.lower())
if not isinstance(self.memory, Memory):
self.memory = Memory()
return self
@asynccontextmanager
async def state_context(self, new_state: AgentState):
"""Context manager for safe agent state transitions.
Args:
new_state: The state to transition to during the context.
Yields:
None: Allows execution within the new state.
Raises:
ValueError: If the new_state is invalid.
"""
if not isinstance(new_state, AgentState):
raise ValueError(f"Invalid state: {new_state}")
previous_state = self.state
self.state = new_state
try:
yield
except Exception as e:
self.state = AgentState.ERROR # Transition to ERROR on failure
raise e
finally:
self.state = previous_state # Revert to previous state
def update_memory(
self,
role: ROLE_TYPE, # type: ignore
content: str,
base64_image: Optional[str] = None,
**kwargs,
) -> None:
"""Add a message to the agent's memory.
Args:
role: The role of the message sender (user, system, assistant, tool).
content: The message content.
base64_image: Optional base64 encoded image.
**kwargs: Additional arguments (e.g., tool_call_id for tool messages).
Raises:
ValueError: If the role is unsupported.
"""
message_map = {
"user": Message.user_message,
"system": Message.system_message,
"assistant": Message.assistant_message,
"tool": lambda content, **kw: Message.tool_message(content, **kw),
}
if role not in message_map:
raise ValueError(f"Unsupported message role: {role}")
# Create message with appropriate parameters based on role
kwargs = {"base64_image": base64_image, **(kwargs if role == "tool" else {})}
self.memory.add_message(message_map[role](content, **kwargs))
async def run(self, request: Optional[str] = None) -> str:
"""Execute the agent's main loop asynchronously.
Args:
request: Optional initial user request to process.
Returns:
A string summarizing the execution results.
Raises:
RuntimeError: If the agent is not in IDLE state at start.
"""
if self.state != AgentState.IDLE:
raise RuntimeError(f"Cannot run agent from state: {self.state}")
if request:
self.update_memory("user", request)
results: List[str] = []
async with self.state_context(AgentState.RUNNING):
while (
self.current_step < self.max_steps and self.state != AgentState.FINISHED
):
self.current_step += 1
logger.info(f"Executing step {self.current_step}/{self.max_steps}")
step_result = await self.step()
# Check for stuck state
if self.is_stuck():
self.handle_stuck_state()
results.append(f"Step {self.current_step}: {step_result}")
if self.current_step >= self.max_steps:
self.current_step = 0
self.state = AgentState.IDLE
results.append(f"Terminated: Reached max steps ({self.max_steps})")
return "\n".join(results) if results else "No steps executed"
@abstractmethod
async def step(self) -> str:
"""Execute a single step in the agent's workflow.
Must be implemented by subclasses to define specific behavior.
"""
def handle_stuck_state(self):
"""Handle stuck state by adding a prompt to change strategy"""
stuck_prompt = "\
Observed duplicate responses. Consider new strategies and avoid repeating ineffective paths already attempted."
self.next_step_prompt = f"{stuck_prompt}\n{self.next_step_prompt}"
logger.warning(f"Agent detected stuck state. Added prompt: {stuck_prompt}")
def is_stuck(self) -> bool:
"""Check if the agent is stuck in a loop by detecting duplicate content"""
if len(self.memory.messages) < 2:
return False
last_message = self.memory.messages[-1]
if not last_message.content:
return False
# Count identical content occurrences
duplicate_count = sum(
1
for msg in reversed(self.memory.messages[:-1])
if msg.role == "assistant" and msg.content == last_message.content
)
return duplicate_count >= self.duplicate_threshold
@property
def messages(self) -> List[Message]:
"""Retrieve a list of messages from the agent's memory."""
return self.memory.messages
@messages.setter
def messages(self, value: List[Message]):
"""Set the list of messages in the agent's memory."""
self.memory.messages = value
|
2301_77160584/OpenManus
|
app/agent/base.py
|
Python
|
mit
| 6,942
|
import json
from typing import Any, Optional
from pydantic import Field
from app.agent.toolcall import ToolCallAgent
from app.logger import logger
from app.prompt.manus import NEXT_STEP_PROMPT, SYSTEM_PROMPT
from app.tool import Terminate, ToolCollection
from app.tool.browser_use_tool import BrowserUseTool
from app.tool.file_saver import FileSaver
from app.tool.python_execute import PythonExecute
class Manus(ToolCallAgent):
"""
A versatile general-purpose agent that uses planning to solve various tasks.
This agent extends PlanningAgent with a comprehensive set of tools and capabilities,
including Python execution, web browsing, file operations, and information retrieval
to handle a wide range of user requests.
"""
name: str = "Manus"
description: str = (
"A versatile agent that can solve various tasks using multiple tools"
)
system_prompt: str = SYSTEM_PROMPT
next_step_prompt: str = NEXT_STEP_PROMPT
max_observe: int = 2000
max_steps: int = 20
# Add general-purpose tools to the tool collection
available_tools: ToolCollection = Field(
default_factory=lambda: ToolCollection(
PythonExecute(), BrowserUseTool(), FileSaver(), Terminate()
)
)
async def _handle_special_tool(self, name: str, result: Any, **kwargs):
if not self._is_special_tool(name):
return
else:
await self.available_tools.get_tool(BrowserUseTool().name).cleanup()
await super()._handle_special_tool(name, result, **kwargs)
async def get_browser_state(self) -> Optional[dict]:
"""Get the current browser state for context in next steps."""
browser_tool = self.available_tools.get_tool(BrowserUseTool().name)
if not browser_tool:
return None
try:
# Get browser state directly from the tool with no context parameter
result = await browser_tool.get_current_state()
if result.error:
logger.debug(f"Browser state error: {result.error}")
return None
# Store screenshot if available
if hasattr(result, "base64_image") and result.base64_image:
self._current_base64_image = result.base64_image
# Parse the state info
return json.loads(result.output)
except Exception as e:
logger.debug(f"Failed to get browser state: {str(e)}")
return None
async def think(self) -> bool:
# Add your custom pre-processing here
browser_state = await self.get_browser_state()
# Modify the next_step_prompt temporarily
original_prompt = self.next_step_prompt
if browser_state and not browser_state.get("error"):
self.next_step_prompt += f"\nCurrent browser state:\nURL: {browser_state.get('url', 'N/A')}\nTitle: {browser_state.get('title', 'N/A')}\n"
# Call parent implementation
result = await super().think()
# Restore original prompt
self.next_step_prompt = original_prompt
return result
|
2301_77160584/OpenManus
|
app/agent/manus.py
|
Python
|
mit
| 3,125
|
import time
from typing import Dict, List, Optional
from pydantic import Field, model_validator
from app.agent.toolcall import ToolCallAgent
from app.logger import logger
from app.prompt.planning import NEXT_STEP_PROMPT, PLANNING_SYSTEM_PROMPT
from app.schema import TOOL_CHOICE_TYPE, Message, ToolCall, ToolChoice
from app.tool import PlanningTool, Terminate, ToolCollection
class PlanningAgent(ToolCallAgent):
"""
An agent that creates and manages plans to solve tasks.
This agent uses a planning tool to create and manage structured plans,
and tracks progress through individual steps until task completion.
"""
name: str = "planning"
description: str = "An agent that creates and manages plans to solve tasks"
system_prompt: str = PLANNING_SYSTEM_PROMPT
next_step_prompt: str = NEXT_STEP_PROMPT
available_tools: ToolCollection = Field(
default_factory=lambda: ToolCollection(PlanningTool(), Terminate())
)
tool_choices: TOOL_CHOICE_TYPE = ToolChoice.AUTO # type: ignore
special_tool_names: List[str] = Field(default_factory=lambda: [Terminate().name])
tool_calls: List[ToolCall] = Field(default_factory=list)
active_plan_id: Optional[str] = Field(default=None)
# Add a dictionary to track the step status for each tool call
step_execution_tracker: Dict[str, Dict] = Field(default_factory=dict)
current_step_index: Optional[int] = None
max_steps: int = 20
@model_validator(mode="after")
def initialize_plan_and_verify_tools(self) -> "PlanningAgent":
"""Initialize the agent with a default plan ID and validate required tools."""
self.active_plan_id = f"plan_{int(time.time())}"
if "planning" not in self.available_tools.tool_map:
self.available_tools.add_tool(PlanningTool())
return self
async def think(self) -> bool:
"""Decide the next action based on plan status."""
prompt = (
f"CURRENT PLAN STATUS:\n{await self.get_plan()}\n\n{self.next_step_prompt}"
if self.active_plan_id
else self.next_step_prompt
)
self.messages.append(Message.user_message(prompt))
# Get the current step index before thinking
self.current_step_index = await self._get_current_step_index()
result = await super().think()
# After thinking, if we decided to execute a tool and it's not a planning tool or special tool,
# associate it with the current step for tracking
if result and self.tool_calls:
latest_tool_call = self.tool_calls[0] # Get the most recent tool call
if (
latest_tool_call.function.name != "planning"
and latest_tool_call.function.name not in self.special_tool_names
and self.current_step_index is not None
):
self.step_execution_tracker[latest_tool_call.id] = {
"step_index": self.current_step_index,
"tool_name": latest_tool_call.function.name,
"status": "pending", # Will be updated after execution
}
return result
async def act(self) -> str:
"""Execute a step and track its completion status."""
result = await super().act()
# After executing the tool, update the plan status
if self.tool_calls:
latest_tool_call = self.tool_calls[0]
# Update the execution status to completed
if latest_tool_call.id in self.step_execution_tracker:
self.step_execution_tracker[latest_tool_call.id]["status"] = "completed"
self.step_execution_tracker[latest_tool_call.id]["result"] = result
# Update the plan status if this was a non-planning, non-special tool
if (
latest_tool_call.function.name != "planning"
and latest_tool_call.function.name not in self.special_tool_names
):
await self.update_plan_status(latest_tool_call.id)
return result
async def get_plan(self) -> str:
"""Retrieve the current plan status."""
if not self.active_plan_id:
return "No active plan. Please create a plan first."
result = await self.available_tools.execute(
name="planning",
tool_input={"command": "get", "plan_id": self.active_plan_id},
)
return result.output if hasattr(result, "output") else str(result)
async def run(self, request: Optional[str] = None) -> str:
"""Run the agent with an optional initial request."""
if request:
await self.create_initial_plan(request)
return await super().run()
async def update_plan_status(self, tool_call_id: str) -> None:
"""
Update the current plan progress based on completed tool execution.
Only marks a step as completed if the associated tool has been successfully executed.
"""
if not self.active_plan_id:
return
if tool_call_id not in self.step_execution_tracker:
logger.warning(f"No step tracking found for tool call {tool_call_id}")
return
tracker = self.step_execution_tracker[tool_call_id]
if tracker["status"] != "completed":
logger.warning(f"Tool call {tool_call_id} has not completed successfully")
return
step_index = tracker["step_index"]
try:
# Mark the step as completed
await self.available_tools.execute(
name="planning",
tool_input={
"command": "mark_step",
"plan_id": self.active_plan_id,
"step_index": step_index,
"step_status": "completed",
},
)
logger.info(
f"Marked step {step_index} as completed in plan {self.active_plan_id}"
)
except Exception as e:
logger.warning(f"Failed to update plan status: {e}")
async def _get_current_step_index(self) -> Optional[int]:
"""
Parse the current plan to identify the first non-completed step's index.
Returns None if no active step is found.
"""
if not self.active_plan_id:
return None
plan = await self.get_plan()
try:
plan_lines = plan.splitlines()
steps_index = -1
# Find the index of the "Steps:" line
for i, line in enumerate(plan_lines):
if line.strip() == "Steps:":
steps_index = i
break
if steps_index == -1:
return None
# Find the first non-completed step
for i, line in enumerate(plan_lines[steps_index + 1 :], start=0):
if "[ ]" in line or "[→]" in line: # not_started or in_progress
# Mark current step as in_progress
await self.available_tools.execute(
name="planning",
tool_input={
"command": "mark_step",
"plan_id": self.active_plan_id,
"step_index": i,
"step_status": "in_progress",
},
)
return i
return None # No active step found
except Exception as e:
logger.warning(f"Error finding current step index: {e}")
return None
async def create_initial_plan(self, request: str) -> None:
"""Create an initial plan based on the request."""
logger.info(f"Creating initial plan with ID: {self.active_plan_id}")
messages = [
Message.user_message(
f"Analyze the request and create a plan with ID {self.active_plan_id}: {request}"
)
]
self.memory.add_messages(messages)
response = await self.llm.ask_tool(
messages=messages,
system_msgs=[Message.system_message(self.system_prompt)],
tools=self.available_tools.to_params(),
tool_choice=ToolChoice.AUTO,
)
assistant_msg = Message.from_tool_calls(
content=response.content, tool_calls=response.tool_calls
)
self.memory.add_message(assistant_msg)
plan_created = False
for tool_call in response.tool_calls:
if tool_call.function.name == "planning":
result = await self.execute_tool(tool_call)
logger.info(
f"Executed tool {tool_call.function.name} with result: {result}"
)
# Add tool response to memory
tool_msg = Message.tool_message(
content=result,
tool_call_id=tool_call.id,
name=tool_call.function.name,
)
self.memory.add_message(tool_msg)
plan_created = True
break
if not plan_created:
logger.warning("No plan created from initial request")
tool_msg = Message.assistant_message(
"Error: Parameter `plan_id` is required for command: create"
)
self.memory.add_message(tool_msg)
async def main():
# Configure and run the agent
agent = PlanningAgent(available_tools=ToolCollection(PlanningTool(), Terminate()))
result = await agent.run("Help me plan a trip to the moon")
print(result)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
|
2301_77160584/OpenManus
|
app/agent/planning.py
|
Python
|
mit
| 9,764
|
from abc import ABC, abstractmethod
from typing import Optional
from pydantic import Field
from app.agent.base import BaseAgent
from app.llm import LLM
from app.schema import AgentState, Memory
class ReActAgent(BaseAgent, ABC):
name: str
description: Optional[str] = None
system_prompt: Optional[str] = None
next_step_prompt: Optional[str] = None
llm: Optional[LLM] = Field(default_factory=LLM)
memory: Memory = Field(default_factory=Memory)
state: AgentState = AgentState.IDLE
max_steps: int = 10
current_step: int = 0
@abstractmethod
async def think(self) -> bool:
"""Process current state and decide next action"""
@abstractmethod
async def act(self) -> str:
"""Execute decided actions"""
async def step(self) -> str:
"""Execute a single step: think and act."""
should_act = await self.think()
if not should_act:
return "Thinking complete - no action needed"
return await self.act()
|
2301_77160584/OpenManus
|
app/agent/react.py
|
Python
|
mit
| 1,012
|
from typing import List
from pydantic import Field
from app.agent.toolcall import ToolCallAgent
from app.prompt.swe import NEXT_STEP_TEMPLATE, SYSTEM_PROMPT
from app.tool import Bash, StrReplaceEditor, Terminate, ToolCollection
class SWEAgent(ToolCallAgent):
"""An agent that implements the SWEAgent paradigm for executing code and natural conversations."""
name: str = "swe"
description: str = "an autonomous AI programmer that interacts directly with the computer to solve tasks."
system_prompt: str = SYSTEM_PROMPT
next_step_prompt: str = NEXT_STEP_TEMPLATE
available_tools: ToolCollection = ToolCollection(
Bash(), StrReplaceEditor(), Terminate()
)
special_tool_names: List[str] = Field(default_factory=lambda: [Terminate().name])
max_steps: int = 30
bash: Bash = Field(default_factory=Bash)
working_dir: str = "."
async def think(self) -> bool:
"""Process current state and decide next action"""
# Update working directory
self.working_dir = await self.bash.execute("pwd")
self.next_step_prompt = self.next_step_prompt.format(
current_dir=self.working_dir
)
return await super().think()
|
2301_77160584/OpenManus
|
app/agent/swe.py
|
Python
|
mit
| 1,219
|
import json
from typing import Any, List, Optional, Union
from pydantic import Field
from app.agent.react import ReActAgent
from app.exceptions import TokenLimitExceeded
from app.logger import logger
from app.prompt.toolcall import NEXT_STEP_PROMPT, SYSTEM_PROMPT
from app.schema import TOOL_CHOICE_TYPE, AgentState, Message, ToolCall, ToolChoice
from app.tool import CreateChatCompletion, Terminate, ToolCollection
TOOL_CALL_REQUIRED = "Tool calls required but none provided"
class ToolCallAgent(ReActAgent):
"""Base agent class for handling tool/function calls with enhanced abstraction"""
name: str = "toolcall"
description: str = "an agent that can execute tool calls."
system_prompt: str = SYSTEM_PROMPT
next_step_prompt: str = NEXT_STEP_PROMPT
available_tools: ToolCollection = ToolCollection(
CreateChatCompletion(), Terminate()
)
tool_choices: TOOL_CHOICE_TYPE = ToolChoice.AUTO # type: ignore
special_tool_names: List[str] = Field(default_factory=lambda: [Terminate().name])
tool_calls: List[ToolCall] = Field(default_factory=list)
_current_base64_image: Optional[str] = None
max_steps: int = 30
max_observe: Optional[Union[int, bool]] = None
async def think(self) -> bool:
"""Process current state and decide next actions using tools"""
if self.next_step_prompt:
user_msg = Message.user_message(self.next_step_prompt)
self.messages += [user_msg]
try:
# Get response with tool options
response = await self.llm.ask_tool(
messages=self.messages,
system_msgs=(
[Message.system_message(self.system_prompt)]
if self.system_prompt
else None
),
tools=self.available_tools.to_params(),
tool_choice=self.tool_choices,
)
except ValueError:
raise
except Exception as e:
# Check if this is a RetryError containing TokenLimitExceeded
if hasattr(e, "__cause__") and isinstance(e.__cause__, TokenLimitExceeded):
token_limit_error = e.__cause__
logger.error(
f"🚨 Token limit error (from RetryError): {token_limit_error}"
)
self.memory.add_message(
Message.assistant_message(
f"Maximum token limit reached, cannot continue execution: {str(token_limit_error)}"
)
)
self.state = AgentState.FINISHED
return False
raise
self.tool_calls = response.tool_calls
# Log response info
logger.info(f"✨ {self.name}'s thoughts: {response.content}")
logger.info(
f"🛠️ {self.name} selected {len(response.tool_calls) if response.tool_calls else 0} tools to use"
)
if response.tool_calls:
logger.info(
f"🧰 Tools being prepared: {[call.function.name for call in response.tool_calls]}"
)
logger.info(
f"🔧 Tool arguments: {response.tool_calls[0].function.arguments}"
)
try:
# Handle different tool_choices modes
if self.tool_choices == ToolChoice.NONE:
if response.tool_calls:
logger.warning(
f"🤔 Hmm, {self.name} tried to use tools when they weren't available!"
)
if response.content:
self.memory.add_message(Message.assistant_message(response.content))
return True
return False
# Create and add assistant message
assistant_msg = (
Message.from_tool_calls(
content=response.content, tool_calls=self.tool_calls
)
if self.tool_calls
else Message.assistant_message(response.content)
)
self.memory.add_message(assistant_msg)
if self.tool_choices == ToolChoice.REQUIRED and not self.tool_calls:
return True # Will be handled in act()
# For 'auto' mode, continue with content if no commands but content exists
if self.tool_choices == ToolChoice.AUTO and not self.tool_calls:
return bool(response.content)
return bool(self.tool_calls)
except Exception as e:
logger.error(f"🚨 Oops! The {self.name}'s thinking process hit a snag: {e}")
self.memory.add_message(
Message.assistant_message(
f"Error encountered while processing: {str(e)}"
)
)
return False
async def act(self) -> str:
"""Execute tool calls and handle their results"""
if not self.tool_calls:
if self.tool_choices == ToolChoice.REQUIRED:
raise ValueError(TOOL_CALL_REQUIRED)
# Return last message content if no tool calls
return self.messages[-1].content or "No content or commands to execute"
results = []
for command in self.tool_calls:
# Reset base64_image for each tool call
self._current_base64_image = None
result = await self.execute_tool(command)
if self.max_observe:
result = result[: self.max_observe]
logger.info(
f"🎯 Tool '{command.function.name}' completed its mission! Result: {result}"
)
# Add tool response to memory
tool_msg = Message.tool_message(
content=result,
tool_call_id=command.id,
name=command.function.name,
base64_image=self._current_base64_image,
)
self.memory.add_message(tool_msg)
results.append(result)
return "\n\n".join(results)
async def execute_tool(self, command: ToolCall) -> str:
"""Execute a single tool call with robust error handling"""
if not command or not command.function or not command.function.name:
return "Error: Invalid command format"
name = command.function.name
if name not in self.available_tools.tool_map:
return f"Error: Unknown tool '{name}'"
try:
# Parse arguments
args = json.loads(command.function.arguments or "{}")
# Execute the tool
logger.info(f"🔧 Activating tool: '{name}'...")
result = await self.available_tools.execute(name=name, tool_input=args)
# Handle special tools
await self._handle_special_tool(name=name, result=result)
# Check if result is a ToolResult with base64_image
if hasattr(result, "base64_image") and result.base64_image:
# Store the base64_image for later use in tool_message
self._current_base64_image = result.base64_image
# Format result for display
observation = (
f"Observed output of cmd `{name}` executed:\n{str(result)}"
if result
else f"Cmd `{name}` completed with no output"
)
return observation
# Format result for display (standard case)
observation = (
f"Observed output of cmd `{name}` executed:\n{str(result)}"
if result
else f"Cmd `{name}` completed with no output"
)
return observation
except json.JSONDecodeError:
error_msg = f"Error parsing arguments for {name}: Invalid JSON format"
logger.error(
f"📝 Oops! The arguments for '{name}' don't make sense - invalid JSON, arguments:{command.function.arguments}"
)
return f"Error: {error_msg}"
except Exception as e:
error_msg = f"⚠️ Tool '{name}' encountered a problem: {str(e)}"
logger.error(error_msg)
return f"Error: {error_msg}"
async def _handle_special_tool(self, name: str, result: Any, **kwargs):
"""Handle special tool execution and state changes"""
if not self._is_special_tool(name):
return
if self._should_finish_execution(name=name, result=result, **kwargs):
# Set agent state to finished
logger.info(f"🏁 Special tool '{name}' has completed the task!")
self.state = AgentState.FINISHED
@staticmethod
def _should_finish_execution(**kwargs) -> bool:
"""Determine if tool execution should finish the agent"""
return True
def _is_special_tool(self, name: str) -> bool:
"""Check if tool name is in special tools list"""
return name.lower() in [n.lower() for n in self.special_tool_names]
|
2301_77160584/OpenManus
|
app/agent/toolcall.py
|
Python
|
mit
| 9,036
|
import threading
import tomllib
from pathlib import Path
from typing import Dict, List, Optional
from pydantic import BaseModel, Field
def get_project_root() -> Path:
"""Get the project root directory"""
return Path(__file__).resolve().parent.parent
PROJECT_ROOT = get_project_root()
WORKSPACE_ROOT = PROJECT_ROOT / "workspace"
class LLMSettings(BaseModel):
model: str = Field(..., description="Model name")
base_url: str = Field(..., description="API base URL")
api_key: str = Field(..., description="API key")
max_tokens: int = Field(4096, description="Maximum number of tokens per request")
max_input_tokens: Optional[int] = Field(
None,
description="Maximum input tokens to use across all requests (None for unlimited)",
)
temperature: float = Field(1.0, description="Sampling temperature")
api_type: str = Field(..., description="AzureOpenai or Openai")
api_version: str = Field(..., description="Azure Openai version if AzureOpenai")
class ProxySettings(BaseModel):
server: str = Field(None, description="Proxy server address")
username: Optional[str] = Field(None, description="Proxy username")
password: Optional[str] = Field(None, description="Proxy password")
class SearchSettings(BaseModel):
engine: str = Field(default="Google", description="Search engine the llm to use")
class BrowserSettings(BaseModel):
headless: bool = Field(False, description="Whether to run browser in headless mode")
disable_security: bool = Field(
True, description="Disable browser security features"
)
extra_chromium_args: List[str] = Field(
default_factory=list, description="Extra arguments to pass to the browser"
)
chrome_instance_path: Optional[str] = Field(
None, description="Path to a Chrome instance to use"
)
wss_url: Optional[str] = Field(
None, description="Connect to a browser instance via WebSocket"
)
cdp_url: Optional[str] = Field(
None, description="Connect to a browser instance via CDP"
)
proxy: Optional[ProxySettings] = Field(
None, description="Proxy settings for the browser"
)
max_content_length: int = Field(
2000, description="Maximum length for content retrieval operations"
)
class AppConfig(BaseModel):
llm: Dict[str, LLMSettings]
browser_config: Optional[BrowserSettings] = Field(
None, description="Browser configuration"
)
search_config: Optional[SearchSettings] = Field(
None, description="Search configuration"
)
class Config:
arbitrary_types_allowed = True
class Config:
_instance = None
_lock = threading.Lock()
_initialized = False
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
if not self._initialized:
with self._lock:
if not self._initialized:
self._config = None
self._load_initial_config()
self._initialized = True
@staticmethod
def _get_config_path() -> Path:
root = PROJECT_ROOT
config_path = root / "config" / "config.toml"
if config_path.exists():
return config_path
example_path = root / "config" / "config.example.toml"
if example_path.exists():
return example_path
raise FileNotFoundError("No configuration file found in config directory")
def _load_config(self) -> dict:
config_path = self._get_config_path()
with config_path.open("rb") as f:
return tomllib.load(f)
def _load_initial_config(self):
raw_config = self._load_config()
base_llm = raw_config.get("llm", {})
llm_overrides = {
k: v for k, v in raw_config.get("llm", {}).items() if isinstance(v, dict)
}
default_settings = {
"model": base_llm.get("model"),
"base_url": base_llm.get("base_url"),
"api_key": base_llm.get("api_key"),
"max_tokens": base_llm.get("max_tokens", 4096),
"max_input_tokens": base_llm.get("max_input_tokens"),
"temperature": base_llm.get("temperature", 1.0),
"api_type": base_llm.get("api_type", ""),
"api_version": base_llm.get("api_version", ""),
}
# handle browser config.
browser_config = raw_config.get("browser", {})
browser_settings = None
if browser_config:
# handle proxy settings.
proxy_config = browser_config.get("proxy", {})
proxy_settings = None
if proxy_config and proxy_config.get("server"):
proxy_settings = ProxySettings(
**{
k: v
for k, v in proxy_config.items()
if k in ["server", "username", "password"] and v
}
)
# filter valid browser config parameters.
valid_browser_params = {
k: v
for k, v in browser_config.items()
if k in BrowserSettings.__annotations__ and v is not None
}
# if there is proxy settings, add it to the parameters.
if proxy_settings:
valid_browser_params["proxy"] = proxy_settings
# only create BrowserSettings when there are valid parameters.
if valid_browser_params:
browser_settings = BrowserSettings(**valid_browser_params)
search_config = raw_config.get("search", {})
search_settings = None
if search_config:
search_settings = SearchSettings(**search_config)
config_dict = {
"llm": {
"default": default_settings,
**{
name: {**default_settings, **override_config}
for name, override_config in llm_overrides.items()
},
},
"browser_config": browser_settings,
"search_config": search_settings,
}
self._config = AppConfig(**config_dict)
@property
def llm(self) -> Dict[str, LLMSettings]:
return self._config.llm
@property
def browser_config(self) -> Optional[BrowserSettings]:
return self._config.browser_config
@property
def search_config(self) -> Optional[SearchSettings]:
return self._config.search_config
config = Config()
|
2301_77160584/OpenManus
|
app/config.py
|
Python
|
mit
| 6,672
|
class ToolError(Exception):
"""Raised when a tool encounters an error."""
def __init__(self, message):
self.message = message
class OpenManusError(Exception):
"""Base exception for all OpenManus errors"""
class TokenLimitExceeded(OpenManusError):
"""Exception raised when the token limit is exceeded"""
|
2301_77160584/OpenManus
|
app/exceptions.py
|
Python
|
mit
| 332
|
from abc import ABC, abstractmethod
from enum import Enum
from typing import Dict, List, Optional, Union
from pydantic import BaseModel
from app.agent.base import BaseAgent
class FlowType(str, Enum):
PLANNING = "planning"
class BaseFlow(BaseModel, ABC):
"""Base class for execution flows supporting multiple agents"""
agents: Dict[str, BaseAgent]
tools: Optional[List] = None
primary_agent_key: Optional[str] = None
class Config:
arbitrary_types_allowed = True
def __init__(
self, agents: Union[BaseAgent, List[BaseAgent], Dict[str, BaseAgent]], **data
):
# Handle different ways of providing agents
if isinstance(agents, BaseAgent):
agents_dict = {"default": agents}
elif isinstance(agents, list):
agents_dict = {f"agent_{i}": agent for i, agent in enumerate(agents)}
else:
agents_dict = agents
# If primary agent not specified, use first agent
primary_key = data.get("primary_agent_key")
if not primary_key and agents_dict:
primary_key = next(iter(agents_dict))
data["primary_agent_key"] = primary_key
# Set the agents dictionary
data["agents"] = agents_dict
# Initialize using BaseModel's init
super().__init__(**data)
@property
def primary_agent(self) -> Optional[BaseAgent]:
"""Get the primary agent for the flow"""
return self.agents.get(self.primary_agent_key)
def get_agent(self, key: str) -> Optional[BaseAgent]:
"""Get a specific agent by key"""
return self.agents.get(key)
def add_agent(self, key: str, agent: BaseAgent) -> None:
"""Add a new agent to the flow"""
self.agents[key] = agent
@abstractmethod
async def execute(self, input_text: str) -> str:
"""Execute the flow with given input"""
class PlanStepStatus(str, Enum):
"""Enum class defining possible statuses of a plan step"""
NOT_STARTED = "not_started"
IN_PROGRESS = "in_progress"
COMPLETED = "completed"
BLOCKED = "blocked"
@classmethod
def get_all_statuses(cls) -> list[str]:
"""Return a list of all possible step status values"""
return [status.value for status in cls]
@classmethod
def get_active_statuses(cls) -> list[str]:
"""Return a list of values representing active statuses (not started or in progress)"""
return [cls.NOT_STARTED.value, cls.IN_PROGRESS.value]
@classmethod
def get_status_marks(cls) -> Dict[str, str]:
"""Return a mapping of statuses to their marker symbols"""
return {
cls.COMPLETED.value: "[✓]",
cls.IN_PROGRESS.value: "[→]",
cls.BLOCKED.value: "[!]",
cls.NOT_STARTED.value: "[ ]",
}
|
2301_77160584/OpenManus
|
app/flow/base.py
|
Python
|
mit
| 2,835
|
from typing import Dict, List, Union
from app.agent.base import BaseAgent
from app.flow.base import BaseFlow, FlowType
from app.flow.planning import PlanningFlow
class FlowFactory:
"""Factory for creating different types of flows with support for multiple agents"""
@staticmethod
def create_flow(
flow_type: FlowType,
agents: Union[BaseAgent, List[BaseAgent], Dict[str, BaseAgent]],
**kwargs,
) -> BaseFlow:
flows = {
FlowType.PLANNING: PlanningFlow,
}
flow_class = flows.get(flow_type)
if not flow_class:
raise ValueError(f"Unknown flow type: {flow_type}")
return flow_class(agents, **kwargs)
|
2301_77160584/OpenManus
|
app/flow/flow_factory.py
|
Python
|
mit
| 704
|
import json
import time
from typing import Dict, List, Optional, Union
from pydantic import Field
from app.agent.base import BaseAgent
from app.flow.base import BaseFlow, PlanStepStatus
from app.llm import LLM
from app.logger import logger
from app.schema import AgentState, Message, ToolChoice
from app.tool import PlanningTool
class PlanningFlow(BaseFlow):
"""A flow that manages planning and execution of tasks using agents."""
llm: LLM = Field(default_factory=lambda: LLM())
planning_tool: PlanningTool = Field(default_factory=PlanningTool)
executor_keys: List[str] = Field(default_factory=list)
active_plan_id: str = Field(default_factory=lambda: f"plan_{int(time.time())}")
current_step_index: Optional[int] = None
def __init__(
self, agents: Union[BaseAgent, List[BaseAgent], Dict[str, BaseAgent]], **data
):
# Set executor keys before super().__init__
if "executors" in data:
data["executor_keys"] = data.pop("executors")
# Set plan ID if provided
if "plan_id" in data:
data["active_plan_id"] = data.pop("plan_id")
# Initialize the planning tool if not provided
if "planning_tool" not in data:
planning_tool = PlanningTool()
data["planning_tool"] = planning_tool
# Call parent's init with the processed data
super().__init__(agents, **data)
# Set executor_keys to all agent keys if not specified
if not self.executor_keys:
self.executor_keys = list(self.agents.keys())
def get_executor(self, step_type: Optional[str] = None) -> BaseAgent:
"""
Get an appropriate executor agent for the current step.
Can be extended to select agents based on step type/requirements.
"""
# If step type is provided and matches an agent key, use that agent
if step_type and step_type in self.agents:
return self.agents[step_type]
# Otherwise use the first available executor or fall back to primary agent
for key in self.executor_keys:
if key in self.agents:
return self.agents[key]
# Fallback to primary agent
return self.primary_agent
async def execute(self, input_text: str) -> str:
"""Execute the planning flow with agents."""
try:
if not self.primary_agent:
raise ValueError("No primary agent available")
# Create initial plan if input provided
if input_text:
await self._create_initial_plan(input_text)
# Verify plan was created successfully
if self.active_plan_id not in self.planning_tool.plans:
logger.error(
f"Plan creation failed. Plan ID {self.active_plan_id} not found in planning tool."
)
return f"Failed to create plan for: {input_text}"
result = ""
while True:
# Get current step to execute
self.current_step_index, step_info = await self._get_current_step_info()
# Exit if no more steps or plan completed
if self.current_step_index is None:
result += await self._finalize_plan()
break
# Execute current step with appropriate agent
step_type = step_info.get("type") if step_info else None
executor = self.get_executor(step_type)
step_result = await self._execute_step(executor, step_info)
result += step_result + "\n"
# Check if agent wants to terminate
if hasattr(executor, "state") and executor.state == AgentState.FINISHED:
break
return result
except Exception as e:
logger.error(f"Error in PlanningFlow: {str(e)}")
return f"Execution failed: {str(e)}"
async def _create_initial_plan(self, request: str) -> None:
"""Create an initial plan based on the request using the flow's LLM and PlanningTool."""
logger.info(f"Creating initial plan with ID: {self.active_plan_id}")
# Create a system message for plan creation
system_message = Message.system_message(
"You are a planning assistant. Create a concise, actionable plan with clear steps. "
"Focus on key milestones rather than detailed sub-steps. "
"Optimize for clarity and efficiency."
)
# Create a user message with the request
user_message = Message.user_message(
f"Create a reasonable plan with clear steps to accomplish the task: {request}"
)
# Call LLM with PlanningTool
response = await self.llm.ask_tool(
messages=[user_message],
system_msgs=[system_message],
tools=[self.planning_tool.to_param()],
tool_choice=ToolChoice.AUTO,
)
# Process tool calls if present
if response.tool_calls:
for tool_call in response.tool_calls:
if tool_call.function.name == "planning":
# Parse the arguments
args = tool_call.function.arguments
if isinstance(args, str):
try:
args = json.loads(args)
except json.JSONDecodeError:
logger.error(f"Failed to parse tool arguments: {args}")
continue
# Ensure plan_id is set correctly and execute the tool
args["plan_id"] = self.active_plan_id
# Execute the tool via ToolCollection instead of directly
result = await self.planning_tool.execute(**args)
logger.info(f"Plan creation result: {str(result)}")
return
# If execution reached here, create a default plan
logger.warning("Creating default plan")
# Create default plan using the ToolCollection
await self.planning_tool.execute(
**{
"command": "create",
"plan_id": self.active_plan_id,
"title": f"Plan for: {request[:50]}{'...' if len(request) > 50 else ''}",
"steps": ["Analyze request", "Execute task", "Verify results"],
}
)
async def _get_current_step_info(self) -> tuple[Optional[int], Optional[dict]]:
"""
Parse the current plan to identify the first non-completed step's index and info.
Returns (None, None) if no active step is found.
"""
if (
not self.active_plan_id
or self.active_plan_id not in self.planning_tool.plans
):
logger.error(f"Plan with ID {self.active_plan_id} not found")
return None, None
try:
# Direct access to plan data from planning tool storage
plan_data = self.planning_tool.plans[self.active_plan_id]
steps = plan_data.get("steps", [])
step_statuses = plan_data.get("step_statuses", [])
# Find first non-completed step
for i, step in enumerate(steps):
if i >= len(step_statuses):
status = PlanStepStatus.NOT_STARTED.value
else:
status = step_statuses[i]
if status in PlanStepStatus.get_active_statuses():
# Extract step type/category if available
step_info = {"text": step}
# Try to extract step type from the text (e.g., [SEARCH] or [CODE])
import re
type_match = re.search(r"\[([A-Z_]+)\]", step)
if type_match:
step_info["type"] = type_match.group(1).lower()
# Mark current step as in_progress
try:
await self.planning_tool.execute(
command="mark_step",
plan_id=self.active_plan_id,
step_index=i,
step_status=PlanStepStatus.IN_PROGRESS.value,
)
except Exception as e:
logger.warning(f"Error marking step as in_progress: {e}")
# Update step status directly if needed
if i < len(step_statuses):
step_statuses[i] = PlanStepStatus.IN_PROGRESS.value
else:
while len(step_statuses) < i:
step_statuses.append(PlanStepStatus.NOT_STARTED.value)
step_statuses.append(PlanStepStatus.IN_PROGRESS.value)
plan_data["step_statuses"] = step_statuses
return i, step_info
return None, None # No active step found
except Exception as e:
logger.warning(f"Error finding current step index: {e}")
return None, None
async def _execute_step(self, executor: BaseAgent, step_info: dict) -> str:
"""Execute the current step with the specified agent using agent.run()."""
# Prepare context for the agent with current plan status
plan_status = await self._get_plan_text()
step_text = step_info.get("text", f"Step {self.current_step_index}")
# Create a prompt for the agent to execute the current step
step_prompt = f"""
CURRENT PLAN STATUS:
{plan_status}
YOUR CURRENT TASK:
You are now working on step {self.current_step_index}: "{step_text}"
Please execute this step using the appropriate tools. When you're done, provide a summary of what you accomplished.
"""
# Use agent.run() to execute the step
try:
step_result = await executor.run(step_prompt)
# Mark the step as completed after successful execution
await self._mark_step_completed()
return step_result
except Exception as e:
logger.error(f"Error executing step {self.current_step_index}: {e}")
return f"Error executing step {self.current_step_index}: {str(e)}"
async def _mark_step_completed(self) -> None:
"""Mark the current step as completed."""
if self.current_step_index is None:
return
try:
# Mark the step as completed
await self.planning_tool.execute(
command="mark_step",
plan_id=self.active_plan_id,
step_index=self.current_step_index,
step_status=PlanStepStatus.COMPLETED.value,
)
logger.info(
f"Marked step {self.current_step_index} as completed in plan {self.active_plan_id}"
)
except Exception as e:
logger.warning(f"Failed to update plan status: {e}")
# Update step status directly in planning tool storage
if self.active_plan_id in self.planning_tool.plans:
plan_data = self.planning_tool.plans[self.active_plan_id]
step_statuses = plan_data.get("step_statuses", [])
# Ensure the step_statuses list is long enough
while len(step_statuses) <= self.current_step_index:
step_statuses.append(PlanStepStatus.NOT_STARTED.value)
# Update the status
step_statuses[self.current_step_index] = PlanStepStatus.COMPLETED.value
plan_data["step_statuses"] = step_statuses
async def _get_plan_text(self) -> str:
"""Get the current plan as formatted text."""
try:
result = await self.planning_tool.execute(
command="get", plan_id=self.active_plan_id
)
return result.output if hasattr(result, "output") else str(result)
except Exception as e:
logger.error(f"Error getting plan: {e}")
return self._generate_plan_text_from_storage()
def _generate_plan_text_from_storage(self) -> str:
"""Generate plan text directly from storage if the planning tool fails."""
try:
if self.active_plan_id not in self.planning_tool.plans:
return f"Error: Plan with ID {self.active_plan_id} not found"
plan_data = self.planning_tool.plans[self.active_plan_id]
title = plan_data.get("title", "Untitled Plan")
steps = plan_data.get("steps", [])
step_statuses = plan_data.get("step_statuses", [])
step_notes = plan_data.get("step_notes", [])
# Ensure step_statuses and step_notes match the number of steps
while len(step_statuses) < len(steps):
step_statuses.append(PlanStepStatus.NOT_STARTED.value)
while len(step_notes) < len(steps):
step_notes.append("")
# Count steps by status
status_counts = {status: 0 for status in PlanStepStatus.get_all_statuses()}
for status in step_statuses:
if status in status_counts:
status_counts[status] += 1
completed = status_counts[PlanStepStatus.COMPLETED.value]
total = len(steps)
progress = (completed / total) * 100 if total > 0 else 0
plan_text = f"Plan: {title} (ID: {self.active_plan_id})\n"
plan_text += "=" * len(plan_text) + "\n\n"
plan_text += (
f"Progress: {completed}/{total} steps completed ({progress:.1f}%)\n"
)
plan_text += f"Status: {status_counts[PlanStepStatus.COMPLETED.value]} completed, {status_counts[PlanStepStatus.IN_PROGRESS.value]} in progress, "
plan_text += f"{status_counts[PlanStepStatus.BLOCKED.value]} blocked, {status_counts[PlanStepStatus.NOT_STARTED.value]} not started\n\n"
plan_text += "Steps:\n"
status_marks = PlanStepStatus.get_status_marks()
for i, (step, status, notes) in enumerate(
zip(steps, step_statuses, step_notes)
):
# Use status marks to indicate step status
status_mark = status_marks.get(
status, status_marks[PlanStepStatus.NOT_STARTED.value]
)
plan_text += f"{i}. {status_mark} {step}\n"
if notes:
plan_text += f" Notes: {notes}\n"
return plan_text
except Exception as e:
logger.error(f"Error generating plan text from storage: {e}")
return f"Error: Unable to retrieve plan with ID {self.active_plan_id}"
async def _finalize_plan(self) -> str:
"""Finalize the plan and provide a summary using the flow's LLM directly."""
plan_text = await self._get_plan_text()
# Create a summary using the flow's LLM directly
try:
system_message = Message.system_message(
"You are a planning assistant. Your task is to summarize the completed plan."
)
user_message = Message.user_message(
f"The plan has been completed. Here is the final plan status:\n\n{plan_text}\n\nPlease provide a summary of what was accomplished and any final thoughts."
)
response = await self.llm.ask(
messages=[user_message], system_msgs=[system_message]
)
return f"Plan completed:\n\n{response}"
except Exception as e:
logger.error(f"Error finalizing plan with LLM: {e}")
# Fallback to using an agent for the summary
try:
agent = self.primary_agent
summary_prompt = f"""
The plan has been completed. Here is the final plan status:
{plan_text}
Please provide a summary of what was accomplished and any final thoughts.
"""
summary = await agent.run(summary_prompt)
return f"Plan completed:\n\n{summary}"
except Exception as e2:
logger.error(f"Error finalizing plan with agent: {e2}")
return "Plan completed. Error generating summary."
|
2301_77160584/OpenManus
|
app/flow/planning.py
|
Python
|
mit
| 16,501
|
import math
from typing import Dict, List, Optional, Union
import tiktoken
from openai import (
APIError,
AsyncAzureOpenAI,
AsyncOpenAI,
AuthenticationError,
OpenAIError,
RateLimitError,
)
from tenacity import (
retry,
retry_if_exception_type,
stop_after_attempt,
wait_random_exponential,
)
from app.config import LLMSettings, config
from app.exceptions import TokenLimitExceeded
from app.logger import logger # Assuming a logger is set up in your app
from app.schema import (
ROLE_VALUES,
TOOL_CHOICE_TYPE,
TOOL_CHOICE_VALUES,
Message,
ToolChoice,
)
REASONING_MODELS = ["o1", "o3-mini"]
class TokenCounter:
# Token constants
BASE_MESSAGE_TOKENS = 4
FORMAT_TOKENS = 2
LOW_DETAIL_IMAGE_TOKENS = 85
HIGH_DETAIL_TILE_TOKENS = 170
# Image processing constants
MAX_SIZE = 2048
HIGH_DETAIL_TARGET_SHORT_SIDE = 768
TILE_SIZE = 512
def __init__(self, tokenizer):
self.tokenizer = tokenizer
def count_text(self, text: str) -> int:
"""Calculate tokens for a text string"""
return 0 if not text else len(self.tokenizer.encode(text))
def count_image(self, image_item: dict) -> int:
"""
Calculate tokens for an image based on detail level and dimensions
For "low" detail: fixed 85 tokens
For "high" detail:
1. Scale to fit in 2048x2048 square
2. Scale shortest side to 768px
3. Count 512px tiles (170 tokens each)
4. Add 85 tokens
"""
detail = image_item.get("detail", "medium")
# For low detail, always return fixed token count
if detail == "low":
return self.LOW_DETAIL_IMAGE_TOKENS
# For medium detail (default in OpenAI), use high detail calculation
# OpenAI doesn't specify a separate calculation for medium
# For high detail, calculate based on dimensions if available
if detail == "high" or detail == "medium":
# If dimensions are provided in the image_item
if "dimensions" in image_item:
width, height = image_item["dimensions"]
return self._calculate_high_detail_tokens(width, height)
# Default values when dimensions aren't available or detail level is unknown
if detail == "high":
# Default to a 1024x1024 image calculation for high detail
return self._calculate_high_detail_tokens(1024, 1024) # 765 tokens
elif detail == "medium":
# Default to a medium-sized image for medium detail
return 1024 # This matches the original default
else:
# For unknown detail levels, use medium as default
return 1024
def _calculate_high_detail_tokens(self, width: int, height: int) -> int:
"""Calculate tokens for high detail images based on dimensions"""
# Step 1: Scale to fit in MAX_SIZE x MAX_SIZE square
if width > self.MAX_SIZE or height > self.MAX_SIZE:
scale = self.MAX_SIZE / max(width, height)
width = int(width * scale)
height = int(height * scale)
# Step 2: Scale so shortest side is HIGH_DETAIL_TARGET_SHORT_SIDE
scale = self.HIGH_DETAIL_TARGET_SHORT_SIDE / min(width, height)
scaled_width = int(width * scale)
scaled_height = int(height * scale)
# Step 3: Count number of 512px tiles
tiles_x = math.ceil(scaled_width / self.TILE_SIZE)
tiles_y = math.ceil(scaled_height / self.TILE_SIZE)
total_tiles = tiles_x * tiles_y
# Step 4: Calculate final token count
return (
total_tiles * self.HIGH_DETAIL_TILE_TOKENS
) + self.LOW_DETAIL_IMAGE_TOKENS
def count_content(self, content: Union[str, List[Union[str, dict]]]) -> int:
"""Calculate tokens for message content"""
if not content:
return 0
if isinstance(content, str):
return self.count_text(content)
token_count = 0
for item in content:
if isinstance(item, str):
token_count += self.count_text(item)
elif isinstance(item, dict):
if "text" in item:
token_count += self.count_text(item["text"])
elif "image_url" in item:
token_count += self.count_image(item)
return token_count
def count_tool_calls(self, tool_calls: List[dict]) -> int:
"""Calculate tokens for tool calls"""
token_count = 0
for tool_call in tool_calls:
if "function" in tool_call:
function = tool_call["function"]
token_count += self.count_text(function.get("name", ""))
token_count += self.count_text(function.get("arguments", ""))
return token_count
def count_message_tokens(self, messages: List[dict]) -> int:
"""Calculate the total number of tokens in a message list"""
total_tokens = self.FORMAT_TOKENS # Base format tokens
for message in messages:
tokens = self.BASE_MESSAGE_TOKENS # Base tokens per message
# Add role tokens
tokens += self.count_text(message.get("role", ""))
# Add content tokens
if "content" in message:
tokens += self.count_content(message["content"])
# Add tool calls tokens
if "tool_calls" in message:
tokens += self.count_tool_calls(message["tool_calls"])
# Add name and tool_call_id tokens
tokens += self.count_text(message.get("name", ""))
tokens += self.count_text(message.get("tool_call_id", ""))
total_tokens += tokens
return total_tokens
class LLM:
_instances: Dict[str, "LLM"] = {}
def __new__(
cls, config_name: str = "default", llm_config: Optional[LLMSettings] = None
):
if config_name not in cls._instances:
instance = super().__new__(cls)
instance.__init__(config_name, llm_config)
cls._instances[config_name] = instance
return cls._instances[config_name]
def __init__(
self, config_name: str = "default", llm_config: Optional[LLMSettings] = None
):
if not hasattr(self, "client"): # Only initialize if not already initialized
llm_config = llm_config or config.llm
llm_config = llm_config.get(config_name, llm_config["default"])
self.model = llm_config.model
self.max_tokens = llm_config.max_tokens
self.temperature = llm_config.temperature
self.api_type = llm_config.api_type
self.api_key = llm_config.api_key
self.api_version = llm_config.api_version
self.base_url = llm_config.base_url
# Add token counting related attributes
self.total_input_tokens = 0
self.max_input_tokens = (
llm_config.max_input_tokens
if hasattr(llm_config, "max_input_tokens")
else None
)
# Initialize tokenizer
try:
self.tokenizer = tiktoken.encoding_for_model(self.model)
except KeyError:
# If the model is not in tiktoken's presets, use cl100k_base as default
self.tokenizer = tiktoken.get_encoding("cl100k_base")
if self.api_type == "azure":
self.client = AsyncAzureOpenAI(
base_url=self.base_url,
api_key=self.api_key,
api_version=self.api_version,
)
else:
self.client = AsyncOpenAI(api_key=self.api_key, base_url=self.base_url)
self.token_counter = TokenCounter(self.tokenizer)
def count_tokens(self, text: str) -> int:
"""Calculate the number of tokens in a text"""
if not text:
return 0
return len(self.tokenizer.encode(text))
def count_message_tokens(self, messages: List[dict]) -> int:
return self.token_counter.count_message_tokens(messages)
def update_token_count(self, input_tokens: int) -> None:
"""Update token counts"""
# Only track tokens if max_input_tokens is set
self.total_input_tokens += input_tokens
logger.info(
f"Token usage: Input={input_tokens}, Cumulative Input={self.total_input_tokens}"
)
def check_token_limit(self, input_tokens: int) -> bool:
"""Check if token limits are exceeded"""
if self.max_input_tokens is not None:
return (self.total_input_tokens + input_tokens) <= self.max_input_tokens
# If max_input_tokens is not set, always return True
return True
def get_limit_error_message(self, input_tokens: int) -> str:
"""Generate error message for token limit exceeded"""
if (
self.max_input_tokens is not None
and (self.total_input_tokens + input_tokens) > self.max_input_tokens
):
return f"Request may exceed input token limit (Current: {self.total_input_tokens}, Needed: {input_tokens}, Max: {self.max_input_tokens})"
return "Token limit exceeded"
@staticmethod
def format_messages(messages: List[Union[dict, Message]]) -> List[dict]:
"""
Format messages for LLM by converting them to OpenAI message format.
Args:
messages: List of messages that can be either dict or Message objects
Returns:
List[dict]: List of formatted messages in OpenAI format
Raises:
ValueError: If messages are invalid or missing required fields
TypeError: If unsupported message types are provided
Examples:
>>> msgs = [
... Message.system_message("You are a helpful assistant"),
... {"role": "user", "content": "Hello"},
... Message.user_message("How are you?")
... ]
>>> formatted = LLM.format_messages(msgs)
"""
formatted_messages = []
for message in messages:
# Convert Message objects to dictionaries
if isinstance(message, Message):
message = message.to_dict()
if not isinstance(message, dict):
raise TypeError(f"Unsupported message type: {type(message)}")
# Validate required fields
if "role" not in message:
raise ValueError("Message dict must contain 'role' field")
# Process base64 images if present
if message.get("base64_image"):
# Initialize or convert content to appropriate format
if not message.get("content"):
message["content"] = []
elif isinstance(message["content"], str):
message["content"] = [{"type": "text", "text": message["content"]}]
elif isinstance(message["content"], list):
# Convert string items to proper text objects
message["content"] = [
(
{"type": "text", "text": item}
if isinstance(item, str)
else item
)
for item in message["content"]
]
# Add the image to content
message["content"].append(
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{message['base64_image']}"
},
}
)
# Remove the base64_image field
del message["base64_image"]
# Only include messages with content or tool_calls
if "content" in message or "tool_calls" in message:
formatted_messages.append(message)
# Validate all roles
invalid_roles = [
msg for msg in formatted_messages if msg["role"] not in ROLE_VALUES
]
if invalid_roles:
raise ValueError(f"Invalid role: {invalid_roles[0]['role']}")
return formatted_messages
@retry(
wait=wait_random_exponential(min=1, max=60),
stop=stop_after_attempt(6),
retry=retry_if_exception_type(
(OpenAIError, Exception, ValueError)
), # Don't retry TokenLimitExceeded
)
async def ask(
self,
messages: List[Union[dict, Message]],
system_msgs: Optional[List[Union[dict, Message]]] = None,
stream: bool = True,
temperature: Optional[float] = None,
) -> str:
"""
Send a prompt to the LLM and get the response.
Args:
messages: List of conversation messages
system_msgs: Optional system messages to prepend
stream (bool): Whether to stream the response
temperature (float): Sampling temperature for the response
Returns:
str: The generated response
Raises:
TokenLimitExceeded: If token limits are exceeded
ValueError: If messages are invalid or response is empty
OpenAIError: If API call fails after retries
Exception: For unexpected errors
"""
try:
# Format system and user messages
if system_msgs:
system_msgs = self.format_messages(system_msgs)
messages = system_msgs + self.format_messages(messages)
else:
messages = self.format_messages(messages)
# Calculate input token count
input_tokens = self.count_message_tokens(messages)
# Check if token limits are exceeded
if not self.check_token_limit(input_tokens):
error_message = self.get_limit_error_message(input_tokens)
# Raise a special exception that won't be retried
raise TokenLimitExceeded(error_message)
params = {
"model": self.model,
"messages": messages,
}
if self.model in REASONING_MODELS:
params["max_completion_tokens"] = self.max_tokens
else:
params["max_tokens"] = self.max_tokens
params["temperature"] = (
temperature if temperature is not None else self.temperature
)
if not stream:
# Non-streaming request
params["stream"] = False
response = await self.client.chat.completions.create(**params)
if not response.choices or not response.choices[0].message.content:
raise ValueError("Empty or invalid response from LLM")
# Update token counts
self.update_token_count(response.usage.prompt_tokens)
return response.choices[0].message.content
# Streaming request, For streaming, update estimated token count before making the request
self.update_token_count(input_tokens)
params["stream"] = True
response = await self.client.chat.completions.create(**params)
collected_messages = []
async for chunk in response:
chunk_message = chunk.choices[0].delta.content or ""
collected_messages.append(chunk_message)
print(chunk_message, end="", flush=True)
print() # Newline after streaming
full_response = "".join(collected_messages).strip()
if not full_response:
raise ValueError("Empty response from streaming LLM")
return full_response
except TokenLimitExceeded:
# Re-raise token limit errors without logging
raise
except ValueError as ve:
logger.error(f"Validation error: {ve}")
raise
except OpenAIError as oe:
logger.error(f"OpenAI API error: {oe}")
if isinstance(oe, AuthenticationError):
logger.error("Authentication failed. Check API key.")
elif isinstance(oe, RateLimitError):
logger.error("Rate limit exceeded. Consider increasing retry attempts.")
elif isinstance(oe, APIError):
logger.error(f"API error: {oe}")
raise
except Exception as e:
logger.error(f"Unexpected error in ask: {e}")
raise
@retry(
wait=wait_random_exponential(min=1, max=60),
stop=stop_after_attempt(6),
retry=retry_if_exception_type(
(OpenAIError, Exception, ValueError)
), # Don't retry TokenLimitExceeded
)
async def ask_with_images(
self,
messages: List[Union[dict, Message]],
images: List[Union[str, dict]],
system_msgs: Optional[List[Union[dict, Message]]] = None,
stream: bool = False,
temperature: Optional[float] = None,
) -> str:
"""
Send a prompt with images to the LLM and get the response.
Args:
messages: List of conversation messages
images: List of image URLs or image data dictionaries
system_msgs: Optional system messages to prepend
stream (bool): Whether to stream the response
temperature (float): Sampling temperature for the response
Returns:
str: The generated response
Raises:
TokenLimitExceeded: If token limits are exceeded
ValueError: If messages are invalid or response is empty
OpenAIError: If API call fails after retries
Exception: For unexpected errors
"""
try:
# Format messages
formatted_messages = self.format_messages(messages)
# Ensure the last message is from the user to attach images
if not formatted_messages or formatted_messages[-1]["role"] != "user":
raise ValueError(
"The last message must be from the user to attach images"
)
# Process the last user message to include images
last_message = formatted_messages[-1]
# Convert content to multimodal format if needed
content = last_message["content"]
multimodal_content = (
[{"type": "text", "text": content}]
if isinstance(content, str)
else content
if isinstance(content, list)
else []
)
# Add images to content
for image in images:
if isinstance(image, str):
multimodal_content.append(
{"type": "image_url", "image_url": {"url": image}}
)
elif isinstance(image, dict) and "url" in image:
multimodal_content.append({"type": "image_url", "image_url": image})
elif isinstance(image, dict) and "image_url" in image:
multimodal_content.append(image)
else:
raise ValueError(f"Unsupported image format: {image}")
# Update the message with multimodal content
last_message["content"] = multimodal_content
# Add system messages if provided
if system_msgs:
all_messages = self.format_messages(system_msgs) + formatted_messages
else:
all_messages = formatted_messages
# Calculate tokens and check limits
input_tokens = self.count_message_tokens(all_messages)
if not self.check_token_limit(input_tokens):
raise TokenLimitExceeded(self.get_limit_error_message(input_tokens))
# Set up API parameters
params = {
"model": self.model,
"messages": all_messages,
"stream": stream,
}
# Add model-specific parameters
if self.model in REASONING_MODELS:
params["max_completion_tokens"] = self.max_tokens
else:
params["max_tokens"] = self.max_tokens
params["temperature"] = (
temperature if temperature is not None else self.temperature
)
# Handle non-streaming request
if not stream:
response = await self.client.chat.completions.create(**params)
if not response.choices or not response.choices[0].message.content:
raise ValueError("Empty or invalid response from LLM")
self.update_token_count(response.usage.prompt_tokens)
return response.choices[0].message.content
# Handle streaming request
self.update_token_count(input_tokens)
response = await self.client.chat.completions.create(**params)
collected_messages = []
async for chunk in response:
chunk_message = chunk.choices[0].delta.content or ""
collected_messages.append(chunk_message)
print(chunk_message, end="", flush=True)
print() # Newline after streaming
full_response = "".join(collected_messages).strip()
if not full_response:
raise ValueError("Empty response from streaming LLM")
return full_response
except TokenLimitExceeded:
raise
except ValueError as ve:
logger.error(f"Validation error in ask_with_images: {ve}")
raise
except OpenAIError as oe:
logger.error(f"OpenAI API error: {oe}")
if isinstance(oe, AuthenticationError):
logger.error("Authentication failed. Check API key.")
elif isinstance(oe, RateLimitError):
logger.error("Rate limit exceeded. Consider increasing retry attempts.")
elif isinstance(oe, APIError):
logger.error(f"API error: {oe}")
raise
except Exception as e:
logger.error(f"Unexpected error in ask_with_images: {e}")
raise
@retry(
wait=wait_random_exponential(min=1, max=60),
stop=stop_after_attempt(6),
retry=retry_if_exception_type(
(OpenAIError, Exception, ValueError)
), # Don't retry TokenLimitExceeded
)
async def ask_tool(
self,
messages: List[Union[dict, Message]],
system_msgs: Optional[List[Union[dict, Message]]] = None,
timeout: int = 300,
tools: Optional[List[dict]] = None,
tool_choice: TOOL_CHOICE_TYPE = ToolChoice.AUTO, # type: ignore
temperature: Optional[float] = None,
**kwargs,
):
"""
Ask LLM using functions/tools and return the response.
Args:
messages: List of conversation messages
system_msgs: Optional system messages to prepend
timeout: Request timeout in seconds
tools: List of tools to use
tool_choice: Tool choice strategy
temperature: Sampling temperature for the response
**kwargs: Additional completion arguments
Returns:
ChatCompletionMessage: The model's response
Raises:
TokenLimitExceeded: If token limits are exceeded
ValueError: If tools, tool_choice, or messages are invalid
OpenAIError: If API call fails after retries
Exception: For unexpected errors
"""
try:
# Validate tool_choice
if tool_choice not in TOOL_CHOICE_VALUES:
raise ValueError(f"Invalid tool_choice: {tool_choice}")
# Format messages
if system_msgs:
system_msgs = self.format_messages(system_msgs)
messages = system_msgs + self.format_messages(messages)
else:
messages = self.format_messages(messages)
# Calculate input token count
input_tokens = self.count_message_tokens(messages)
# If there are tools, calculate token count for tool descriptions
tools_tokens = 0
if tools:
for tool in tools:
tools_tokens += self.count_tokens(str(tool))
input_tokens += tools_tokens
# Check if token limits are exceeded
if not self.check_token_limit(input_tokens):
error_message = self.get_limit_error_message(input_tokens)
# Raise a special exception that won't be retried
raise TokenLimitExceeded(error_message)
# Validate tools if provided
if tools:
for tool in tools:
if not isinstance(tool, dict) or "type" not in tool:
raise ValueError("Each tool must be a dict with 'type' field")
# Set up the completion request
params = {
"model": self.model,
"messages": messages,
"tools": tools,
"tool_choice": tool_choice,
"timeout": timeout,
**kwargs,
}
if self.model in REASONING_MODELS:
params["max_completion_tokens"] = self.max_tokens
else:
params["max_tokens"] = self.max_tokens
params["temperature"] = (
temperature if temperature is not None else self.temperature
)
response = await self.client.chat.completions.create(**params)
# Check if response is valid
if not response.choices or not response.choices[0].message:
print(response)
raise ValueError("Invalid or empty response from LLM")
# Update token counts
self.update_token_count(response.usage.prompt_tokens)
return response.choices[0].message
except TokenLimitExceeded:
# Re-raise token limit errors without logging
raise
except ValueError as ve:
logger.error(f"Validation error in ask_tool: {ve}")
raise
except OpenAIError as oe:
logger.error(f"OpenAI API error: {oe}")
if isinstance(oe, AuthenticationError):
logger.error("Authentication failed. Check API key.")
elif isinstance(oe, RateLimitError):
logger.error("Rate limit exceeded. Consider increasing retry attempts.")
elif isinstance(oe, APIError):
logger.error(f"API error: {oe}")
raise
except Exception as e:
logger.error(f"Unexpected error in ask_tool: {e}")
raise
|
2301_77160584/OpenManus
|
app/llm.py
|
Python
|
mit
| 27,125
|
import sys
from datetime import datetime
from loguru import logger as _logger
from app.config import PROJECT_ROOT
_print_level = "INFO"
def define_log_level(print_level="INFO", logfile_level="DEBUG", name: str = None):
"""Adjust the log level to above level"""
global _print_level
_print_level = print_level
current_date = datetime.now()
formatted_date = current_date.strftime("%Y%m%d%H%M%S")
log_name = (
f"{name}_{formatted_date}" if name else formatted_date
) # name a log with prefix name
_logger.remove()
_logger.add(sys.stderr, level=print_level)
_logger.add(PROJECT_ROOT / f"logs/{log_name}.log", level=logfile_level)
return _logger
logger = define_log_level()
if __name__ == "__main__":
logger.info("Starting application")
logger.debug("Debug message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")
try:
raise ValueError("Test error")
except Exception as e:
logger.exception(f"An error occurred: {e}")
|
2301_77160584/OpenManus
|
app/logger.py
|
Python
|
mit
| 1,074
|
SYSTEM_PROMPT = "You are OpenManus, an all-capable AI assistant, aimed at solving any task presented by the user. You have various tools at your disposal that you can call upon to efficiently complete complex requests. Whether it's programming, information retrieval, file processing, or web browsing, you can handle it all."
NEXT_STEP_PROMPT = """You can interact with the computer using PythonExecute, save important content and information files through FileSaver, open browsers with BrowserUseTool, and retrieve information using GoogleSearch.
PythonExecute: Execute Python code to interact with the computer system, data processing, automation tasks, etc.
FileSaver: Save files locally, such as txt, py, html, etc.
BrowserUseTool: Open, browse, and use web browsers. If you open a local HTML file, you must provide the absolute path to the file.
Terminate: End the current interaction when the task is complete or when you need additional information from the user. Use this tool to signal that you've finished addressing the user's request or need clarification before proceeding further.
Based on user needs, proactively select the most appropriate tool or combination of tools. For complex tasks, you can break down the problem and use different tools step by step to solve it. After using each tool, clearly explain the execution results and suggest the next steps.
Always maintain a helpful, informative tone throughout the interaction. If you encounter any limitations or need more details, clearly communicate this to the user before terminating.
"""
|
2301_77160584/OpenManus
|
app/prompt/manus.py
|
Python
|
mit
| 1,570
|
PLANNING_SYSTEM_PROMPT = """
You are an expert Planning Agent tasked with solving problems efficiently through structured plans.
Your job is:
1. Analyze requests to understand the task scope
2. Create a clear, actionable plan that makes meaningful progress with the `planning` tool
3. Execute steps using available tools as needed
4. Track progress and adapt plans when necessary
5. Use `finish` to conclude immediately when the task is complete
Available tools will vary by task but may include:
- `planning`: Create, update, and track plans (commands: create, update, mark_step, etc.)
- `finish`: End the task when complete
Break tasks into logical steps with clear outcomes. Avoid excessive detail or sub-steps.
Think about dependencies and verification methods.
Know when to conclude - don't continue thinking once objectives are met.
"""
NEXT_STEP_PROMPT = """
Based on the current state, what's your next action?
Choose the most efficient path forward:
1. Is the plan sufficient, or does it need refinement?
2. Can you execute the next step immediately?
3. Is the task complete? If so, use `finish` right away.
Be concise in your reasoning, then select the appropriate tool or action.
"""
|
2301_77160584/OpenManus
|
app/prompt/planning.py
|
Python
|
mit
| 1,199
|
SYSTEM_PROMPT = """SETTING: You are an autonomous programmer, and you're working directly in the command line with a special interface.
The special interface consists of a file editor that shows you {{WINDOW}} lines of a file at a time.
In addition to typical bash commands, you can also use specific commands to help you navigate and edit files.
To call a command, you need to invoke it with a function call/tool call.
Please note that THE EDIT COMMAND REQUIRES PROPER INDENTATION.
If you'd like to add the line ' print(x)' you must fully write that out, with all those spaces before the code! Indentation is important and code that is not indented correctly will fail and require fixing before it can be run.
RESPONSE FORMAT:
Your shell prompt is formatted as follows:
(Open file: <path>)
(Current directory: <cwd>)
bash-$
First, you should _always_ include a general thought about what you're going to do next.
Then, for every response, you must include exactly _ONE_ tool call/function call.
Remember, you should always include a _SINGLE_ tool call/function call and then wait for a response from the shell before continuing with more discussion and commands. Everything you include in the DISCUSSION section will be saved for future reference.
If you'd like to issue two commands at once, PLEASE DO NOT DO THAT! Please instead first submit just the first tool call, and then after receiving a response you'll be able to issue the second tool call.
Note that the environment does NOT support interactive session commands (e.g. python, vim), so please do not invoke them.
"""
NEXT_STEP_TEMPLATE = """{{observation}}
(Open file: {{open_file}})
(Current directory: {{working_dir}})
bash-$
"""
|
2301_77160584/OpenManus
|
app/prompt/swe.py
|
Python
|
mit
| 1,707
|
SYSTEM_PROMPT = "You are an agent that can execute tool calls"
NEXT_STEP_PROMPT = (
"If you want to stop interaction, use `terminate` tool/function call."
)
|
2301_77160584/OpenManus
|
app/prompt/toolcall.py
|
Python
|
mit
| 162
|
from enum import Enum
from typing import Any, List, Literal, Optional, Union
from pydantic import BaseModel, Field
class Role(str, Enum):
"""Message role options"""
SYSTEM = "system"
USER = "user"
ASSISTANT = "assistant"
TOOL = "tool"
ROLE_VALUES = tuple(role.value for role in Role)
ROLE_TYPE = Literal[ROLE_VALUES] # type: ignore
class ToolChoice(str, Enum):
"""Tool choice options"""
NONE = "none"
AUTO = "auto"
REQUIRED = "required"
TOOL_CHOICE_VALUES = tuple(choice.value for choice in ToolChoice)
TOOL_CHOICE_TYPE = Literal[TOOL_CHOICE_VALUES] # type: ignore
class AgentState(str, Enum):
"""Agent execution states"""
IDLE = "IDLE"
RUNNING = "RUNNING"
FINISHED = "FINISHED"
ERROR = "ERROR"
class Function(BaseModel):
name: str
arguments: str
class ToolCall(BaseModel):
"""Represents a tool/function call in a message"""
id: str
type: str = "function"
function: Function
class Message(BaseModel):
"""Represents a chat message in the conversation"""
role: ROLE_TYPE = Field(...) # type: ignore
content: Optional[str] = Field(default=None)
tool_calls: Optional[List[ToolCall]] = Field(default=None)
name: Optional[str] = Field(default=None)
tool_call_id: Optional[str] = Field(default=None)
base64_image: Optional[str] = Field(default=None)
def __add__(self, other) -> List["Message"]:
"""支持 Message + list 或 Message + Message 的操作"""
if isinstance(other, list):
return [self] + other
elif isinstance(other, Message):
return [self, other]
else:
raise TypeError(
f"unsupported operand type(s) for +: '{type(self).__name__}' and '{type(other).__name__}'"
)
def __radd__(self, other) -> List["Message"]:
"""支持 list + Message 的操作"""
if isinstance(other, list):
return other + [self]
else:
raise TypeError(
f"unsupported operand type(s) for +: '{type(other).__name__}' and '{type(self).__name__}'"
)
def to_dict(self) -> dict:
"""Convert message to dictionary format"""
message = {"role": self.role}
if self.content is not None:
message["content"] = self.content
if self.tool_calls is not None:
message["tool_calls"] = [tool_call.dict() for tool_call in self.tool_calls]
if self.name is not None:
message["name"] = self.name
if self.tool_call_id is not None:
message["tool_call_id"] = self.tool_call_id
if self.base64_image is not None:
message["base64_image"] = self.base64_image
return message
@classmethod
def user_message(
cls, content: str, base64_image: Optional[str] = None
) -> "Message":
"""Create a user message"""
return cls(role=Role.USER, content=content, base64_image=base64_image)
@classmethod
def system_message(cls, content: str) -> "Message":
"""Create a system message"""
return cls(role=Role.SYSTEM, content=content)
@classmethod
def assistant_message(
cls, content: Optional[str] = None, base64_image: Optional[str] = None
) -> "Message":
"""Create an assistant message"""
return cls(role=Role.ASSISTANT, content=content, base64_image=base64_image)
@classmethod
def tool_message(
cls, content: str, name, tool_call_id: str, base64_image: Optional[str] = None
) -> "Message":
"""Create a tool message"""
return cls(
role=Role.TOOL,
content=content,
name=name,
tool_call_id=tool_call_id,
base64_image=base64_image,
)
@classmethod
def from_tool_calls(
cls,
tool_calls: List[Any],
content: Union[str, List[str]] = "",
base64_image: Optional[str] = None,
**kwargs,
):
"""Create ToolCallsMessage from raw tool calls.
Args:
tool_calls: Raw tool calls from LLM
content: Optional message content
base64_image: Optional base64 encoded image
"""
formatted_calls = [
{"id": call.id, "function": call.function.model_dump(), "type": "function"}
for call in tool_calls
]
return cls(
role=Role.ASSISTANT,
content=content,
tool_calls=formatted_calls,
base64_image=base64_image,
**kwargs,
)
class Memory(BaseModel):
messages: List[Message] = Field(default_factory=list)
max_messages: int = Field(default=100)
def add_message(self, message: Message) -> None:
"""Add a message to memory"""
self.messages.append(message)
# Optional: Implement message limit
if len(self.messages) > self.max_messages:
self.messages = self.messages[-self.max_messages :]
def add_messages(self, messages: List[Message]) -> None:
"""Add multiple messages to memory"""
self.messages.extend(messages)
def clear(self) -> None:
"""Clear all messages"""
self.messages.clear()
def get_recent_messages(self, n: int) -> List[Message]:
"""Get n most recent messages"""
return self.messages[-n:]
def to_dict_list(self) -> List[dict]:
"""Convert messages to list of dicts"""
return [msg.to_dict() for msg in self.messages]
|
2301_77160584/OpenManus
|
app/schema.py
|
Python
|
mit
| 5,530
|
from app.tool.base import BaseTool
from app.tool.bash import Bash
from app.tool.create_chat_completion import CreateChatCompletion
from app.tool.planning import PlanningTool
from app.tool.str_replace_editor import StrReplaceEditor
from app.tool.terminate import Terminate
from app.tool.tool_collection import ToolCollection
__all__ = [
"BaseTool",
"Bash",
"Terminate",
"StrReplaceEditor",
"ToolCollection",
"CreateChatCompletion",
"PlanningTool",
]
|
2301_77160584/OpenManus
|
app/tool/__init__.py
|
Python
|
mit
| 479
|
from abc import ABC, abstractmethod
from typing import Any, Dict, Optional
from pydantic import BaseModel, Field
class BaseTool(ABC, BaseModel):
name: str
description: str
parameters: Optional[dict] = None
class Config:
arbitrary_types_allowed = True
async def __call__(self, **kwargs) -> Any:
"""Execute the tool with given parameters."""
return await self.execute(**kwargs)
@abstractmethod
async def execute(self, **kwargs) -> Any:
"""Execute the tool with given parameters."""
def to_param(self) -> Dict:
"""Convert tool to function call format."""
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.parameters,
},
}
class ToolResult(BaseModel):
"""Represents the result of a tool execution."""
output: Any = Field(default=None)
error: Optional[str] = Field(default=None)
base64_image: Optional[str] = Field(default=None)
system: Optional[str] = Field(default=None)
class Config:
arbitrary_types_allowed = True
def __bool__(self):
return any(getattr(self, field) for field in self.__fields__)
def __add__(self, other: "ToolResult"):
def combine_fields(
field: Optional[str], other_field: Optional[str], concatenate: bool = True
):
if field and other_field:
if concatenate:
return field + other_field
raise ValueError("Cannot combine tool results")
return field or other_field
return ToolResult(
output=combine_fields(self.output, other.output),
error=combine_fields(self.error, other.error),
base64_image=combine_fields(self.base64_image, other.base64_image, False),
system=combine_fields(self.system, other.system),
)
def __str__(self):
return f"Error: {self.error}" if self.error else self.output
def replace(self, **kwargs):
"""Returns a new ToolResult with the given fields replaced."""
# return self.copy(update=kwargs)
return type(self)(**{**self.dict(), **kwargs})
class CLIResult(ToolResult):
"""A ToolResult that can be rendered as a CLI output."""
class ToolFailure(ToolResult):
"""A ToolResult that represents a failure."""
|
2301_77160584/OpenManus
|
app/tool/base.py
|
Python
|
mit
| 2,457
|
import asyncio
import os
from typing import Optional
from app.exceptions import ToolError
from app.tool.base import BaseTool, CLIResult, ToolResult
_BASH_DESCRIPTION = """Execute a bash command in the terminal.
* Long running commands: For commands that may run indefinitely, it should be run in the background and the output should be redirected to a file, e.g. command = `python3 app.py > server.log 2>&1 &`.
* Interactive: If a bash command returns exit code `-1`, this means the process is not yet finished. The assistant must then send a second call to terminal with an empty `command` (which will retrieve any additional logs), or it can send additional text (set `command` to the text) to STDIN of the running process, or it can send command=`ctrl+c` to interrupt the process.
* Timeout: If a command execution result says "Command timed out. Sending SIGINT to the process", the assistant should retry running the command in the background.
"""
class _BashSession:
"""A session of a bash shell."""
_started: bool
_process: asyncio.subprocess.Process
command: str = "/bin/bash"
_output_delay: float = 0.2 # seconds
_timeout: float = 120.0 # seconds
_sentinel: str = "<<exit>>"
def __init__(self):
self._started = False
self._timed_out = False
async def start(self):
if self._started:
return
self._process = await asyncio.create_subprocess_shell(
self.command,
preexec_fn=os.setsid,
shell=True,
bufsize=0,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
self._started = True
def stop(self):
"""Terminate the bash shell."""
if not self._started:
raise ToolError("Session has not started.")
if self._process.returncode is not None:
return
self._process.terminate()
async def run(self, command: str):
"""Execute a command in the bash shell."""
if not self._started:
raise ToolError("Session has not started.")
if self._process.returncode is not None:
return ToolResult(
system="tool must be restarted",
error=f"bash has exited with returncode {self._process.returncode}",
)
if self._timed_out:
raise ToolError(
f"timed out: bash has not returned in {self._timeout} seconds and must be restarted",
)
# we know these are not None because we created the process with PIPEs
assert self._process.stdin
assert self._process.stdout
assert self._process.stderr
# send command to the process
self._process.stdin.write(
command.encode() + f"; echo '{self._sentinel}'\n".encode()
)
await self._process.stdin.drain()
# read output from the process, until the sentinel is found
try:
async with asyncio.timeout(self._timeout):
while True:
await asyncio.sleep(self._output_delay)
# if we read directly from stdout/stderr, it will wait forever for
# EOF. use the StreamReader buffer directly instead.
output = (
self._process.stdout._buffer.decode()
) # pyright: ignore[reportAttributeAccessIssue]
if self._sentinel in output:
# strip the sentinel and break
output = output[: output.index(self._sentinel)]
break
except asyncio.TimeoutError:
self._timed_out = True
raise ToolError(
f"timed out: bash has not returned in {self._timeout} seconds and must be restarted",
) from None
if output.endswith("\n"):
output = output[:-1]
error = (
self._process.stderr._buffer.decode()
) # pyright: ignore[reportAttributeAccessIssue]
if error.endswith("\n"):
error = error[:-1]
# clear the buffers so that the next output can be read correctly
self._process.stdout._buffer.clear() # pyright: ignore[reportAttributeAccessIssue]
self._process.stderr._buffer.clear() # pyright: ignore[reportAttributeAccessIssue]
return CLIResult(output=output, error=error)
class Bash(BaseTool):
"""A tool for executing bash commands"""
name: str = "bash"
description: str = _BASH_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The bash command to execute. Can be empty to view additional logs when previous exit code is `-1`. Can be `ctrl+c` to interrupt the currently running process.",
},
},
"required": ["command"],
}
_session: Optional[_BashSession] = None
async def execute(
self, command: str | None = None, restart: bool = False, **kwargs
) -> CLIResult:
if restart:
if self._session:
self._session.stop()
self._session = _BashSession()
await self._session.start()
return ToolResult(system="tool has been restarted.")
if self._session is None:
self._session = _BashSession()
await self._session.start()
if command is not None:
return await self._session.run(command)
raise ToolError("no command provided.")
if __name__ == "__main__":
bash = Bash()
rst = asyncio.run(bash.execute("ls -l"))
print(rst)
|
2301_77160584/OpenManus
|
app/tool/bash.py
|
Python
|
mit
| 5,768
|
import asyncio
import json
from typing import Generic, Optional, TypeVar
from browser_use import Browser as BrowserUseBrowser
from browser_use import BrowserConfig
from browser_use.browser.context import BrowserContext, BrowserContextConfig
from browser_use.dom.service import DomService
from pydantic import Field, field_validator
from pydantic_core.core_schema import ValidationInfo
from app.config import config
from app.llm import LLM
from app.tool.base import BaseTool, ToolResult
from app.tool.web_search import WebSearch
_BROWSER_DESCRIPTION = """
Interact with a web browser to perform various actions such as navigation, element interaction, content extraction, and tab management. This tool provides a comprehensive set of browser automation capabilities:
Navigation:
- 'go_to_url': Go to a specific URL in the current tab
- 'go_back': Go back
- 'refresh': Refresh the current page
- 'web_search': Search the query in the current tab, the query should be a search query like humans search in web, concrete and not vague or super long. More the single most important items.
Element Interaction:
- 'click_element': Click an element by index
- 'input_text': Input text into a form element
- 'scroll_down'/'scroll_up': Scroll the page (with optional pixel amount)
- 'scroll_to_text': If you dont find something which you want to interact with, scroll to it
- 'send_keys': Send strings of special keys like Escape,Backspace, Insert, PageDown, Delete, Enter, Shortcuts such as `Control+o`, `Control+Shift+T` are supported as well. This gets used in keyboard.press.
- 'get_dropdown_options': Get all options from a dropdown
- 'select_dropdown_option': Select dropdown option for interactive element index by the text of the option you want to select
Content Extraction:
- 'extract_content': Extract page content to retrieve specific information from the page, e.g. all company names, a specifc description, all information about, links with companies in structured format or simply links
Tab Management:
- 'switch_tab': Switch to a specific tab
- 'open_tab': Open a new tab with a URL
- 'close_tab': Close the current tab
Utility:
- 'wait': Wait for a specified number of seconds
"""
Context = TypeVar("Context")
class BrowserUseTool(BaseTool, Generic[Context]):
name: str = "browser_use"
description: str = _BROWSER_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"go_to_url",
"click_element",
"input_text",
"scroll_down",
"scroll_up",
"scroll_to_text",
"send_keys",
"get_dropdown_options",
"select_dropdown_option",
"go_back",
"web_search",
"wait",
"extract_content",
"switch_tab",
"open_tab",
"close_tab",
],
"description": "The browser action to perform",
},
"url": {
"type": "string",
"description": "URL for 'go_to_url' or 'open_tab' actions",
},
"index": {
"type": "integer",
"description": "Element index for 'click_element', 'input_text', 'get_dropdown_options', or 'select_dropdown_option' actions",
},
"text": {
"type": "string",
"description": "Text for 'input_text', 'scroll_to_text', or 'select_dropdown_option' actions",
},
"scroll_amount": {
"type": "integer",
"description": "Pixels to scroll (positive for down, negative for up) for 'scroll_down' or 'scroll_up' actions",
},
"tab_id": {
"type": "integer",
"description": "Tab ID for 'switch_tab' action",
},
"query": {
"type": "string",
"description": "Search query for 'web_search' action",
},
"goal": {
"type": "string",
"description": "Extraction goal for 'extract_content' action",
},
"keys": {
"type": "string",
"description": "Keys to send for 'send_keys' action",
},
"seconds": {
"type": "integer",
"description": "Seconds to wait for 'wait' action",
},
},
"required": ["action"],
"dependencies": {
"go_to_url": ["url"],
"click_element": ["index"],
"input_text": ["index", "text"],
"switch_tab": ["tab_id"],
"open_tab": ["url"],
"scroll_down": ["scroll_amount"],
"scroll_up": ["scroll_amount"],
"scroll_to_text": ["text"],
"send_keys": ["keys"],
"get_dropdown_options": ["index"],
"select_dropdown_option": ["index", "text"],
"go_back": [],
"web_search": ["query"],
"wait": ["seconds"],
"extract_content": ["goal"],
},
}
lock: asyncio.Lock = Field(default_factory=asyncio.Lock)
browser: Optional[BrowserUseBrowser] = Field(default=None, exclude=True)
context: Optional[BrowserContext] = Field(default=None, exclude=True)
dom_service: Optional[DomService] = Field(default=None, exclude=True)
web_search_tool: WebSearch = Field(default_factory=WebSearch, exclude=True)
# Context for generic functionality
tool_context: Optional[Context] = Field(default=None, exclude=True)
llm: Optional[LLM] = Field(default_factory=LLM)
@field_validator("parameters", mode="before")
def validate_parameters(cls, v: dict, info: ValidationInfo) -> dict:
if not v:
raise ValueError("Parameters cannot be empty")
return v
async def _ensure_browser_initialized(self) -> BrowserContext:
"""Ensure browser and context are initialized."""
if self.browser is None:
browser_config_kwargs = {"headless": False, "disable_security": True}
if config.browser_config:
from browser_use.browser.browser import ProxySettings
# handle proxy settings.
if config.browser_config.proxy and config.browser_config.proxy.server:
browser_config_kwargs["proxy"] = ProxySettings(
server=config.browser_config.proxy.server,
username=config.browser_config.proxy.username,
password=config.browser_config.proxy.password,
)
browser_attrs = [
"headless",
"disable_security",
"extra_chromium_args",
"chrome_instance_path",
"wss_url",
"cdp_url",
]
for attr in browser_attrs:
value = getattr(config.browser_config, attr, None)
if value is not None:
if not isinstance(value, list) or value:
browser_config_kwargs[attr] = value
self.browser = BrowserUseBrowser(BrowserConfig(**browser_config_kwargs))
if self.context is None:
context_config = BrowserContextConfig()
# if there is context config in the config, use it.
if (
config.browser_config
and hasattr(config.browser_config, "new_context_config")
and config.browser_config.new_context_config
):
context_config = config.browser_config.new_context_config
self.context = await self.browser.new_context(context_config)
self.dom_service = DomService(await self.context.get_current_page())
return self.context
async def execute(
self,
action: str,
url: Optional[str] = None,
index: Optional[int] = None,
text: Optional[str] = None,
scroll_amount: Optional[int] = None,
tab_id: Optional[int] = None,
query: Optional[str] = None,
goal: Optional[str] = None,
keys: Optional[str] = None,
seconds: Optional[int] = None,
**kwargs,
) -> ToolResult:
"""
Execute a specified browser action.
Args:
action: The browser action to perform
url: URL for navigation or new tab
index: Element index for click or input actions
text: Text for input action or search query
scroll_amount: Pixels to scroll for scroll action
tab_id: Tab ID for switch_tab action
query: Search query for Google search
goal: Extraction goal for content extraction
keys: Keys to send for keyboard actions
seconds: Seconds to wait
**kwargs: Additional arguments
Returns:
ToolResult with the action's output or error
"""
async with self.lock:
try:
context = await self._ensure_browser_initialized()
# Get max content length from config
max_content_length = getattr(
config.browser_config, "max_content_length", 2000
)
# Navigation actions
if action == "go_to_url":
if not url:
return ToolResult(
error="URL is required for 'go_to_url' action"
)
page = await context.get_current_page()
await page.goto(url)
await page.wait_for_load_state()
return ToolResult(output=f"Navigated to {url}")
elif action == "go_back":
await context.go_back()
return ToolResult(output="Navigated back")
elif action == "refresh":
await context.refresh_page()
return ToolResult(output="Refreshed current page")
elif action == "web_search":
if not query:
return ToolResult(
error="Query is required for 'web_search' action"
)
search_results = await self.web_search_tool.execute(query)
if search_results:
# Navigate to the first search result
first_result = search_results[0]
if isinstance(first_result, dict) and "url" in first_result:
url_to_navigate = first_result["url"]
elif isinstance(first_result, str):
url_to_navigate = first_result
else:
return ToolResult(
error=f"Invalid search result format: {first_result}"
)
page = await context.get_current_page()
await page.goto(url_to_navigate)
await page.wait_for_load_state()
return ToolResult(
output=f"Searched for '{query}' and navigated to first result: {url_to_navigate}\nAll results:"
+ "\n".join([str(r) for r in search_results])
)
else:
return ToolResult(
error=f"No search results found for '{query}'"
)
# Element interaction actions
elif action == "click_element":
if index is None:
return ToolResult(
error="Index is required for 'click_element' action"
)
element = await context.get_dom_element_by_index(index)
if not element:
return ToolResult(error=f"Element with index {index} not found")
download_path = await context._click_element_node(element)
output = f"Clicked element at index {index}"
if download_path:
output += f" - Downloaded file to {download_path}"
return ToolResult(output=output)
elif action == "input_text":
if index is None or not text:
return ToolResult(
error="Index and text are required for 'input_text' action"
)
element = await context.get_dom_element_by_index(index)
if not element:
return ToolResult(error=f"Element with index {index} not found")
await context._input_text_element_node(element, text)
return ToolResult(
output=f"Input '{text}' into element at index {index}"
)
elif action == "scroll_down" or action == "scroll_up":
direction = 1 if action == "scroll_down" else -1
amount = (
scroll_amount
if scroll_amount is not None
else context.config.browser_window_size["height"]
)
await context.execute_javascript(
f"window.scrollBy(0, {direction * amount});"
)
return ToolResult(
output=f"Scrolled {'down' if direction > 0 else 'up'} by {amount} pixels"
)
elif action == "scroll_to_text":
if not text:
return ToolResult(
error="Text is required for 'scroll_to_text' action"
)
page = await context.get_current_page()
try:
locator = page.get_by_text(text, exact=False)
await locator.scroll_into_view_if_needed()
return ToolResult(output=f"Scrolled to text: '{text}'")
except Exception as e:
return ToolResult(error=f"Failed to scroll to text: {str(e)}")
elif action == "send_keys":
if not keys:
return ToolResult(
error="Keys are required for 'send_keys' action"
)
page = await context.get_current_page()
await page.keyboard.press(keys)
return ToolResult(output=f"Sent keys: {keys}")
elif action == "get_dropdown_options":
if index is None:
return ToolResult(
error="Index is required for 'get_dropdown_options' action"
)
element = await context.get_dom_element_by_index(index)
if not element:
return ToolResult(error=f"Element with index {index} not found")
page = await context.get_current_page()
options = await page.evaluate(
"""
(xpath) => {
const select = document.evaluate(xpath, document, null,
XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (!select) return null;
return Array.from(select.options).map(opt => ({
text: opt.text,
value: opt.value,
index: opt.index
}));
}
""",
element.xpath,
)
return ToolResult(output=f"Dropdown options: {options}")
elif action == "select_dropdown_option":
if index is None or not text:
return ToolResult(
error="Index and text are required for 'select_dropdown_option' action"
)
element = await context.get_dom_element_by_index(index)
if not element:
return ToolResult(error=f"Element with index {index} not found")
page = await context.get_current_page()
await page.select_option(element.xpath, label=text)
return ToolResult(
output=f"Selected option '{text}' from dropdown at index {index}"
)
# Content extraction actions
elif action == "extract_content":
if not goal:
return ToolResult(
error="Goal is required for 'extract_content' action"
)
page = await context.get_current_page()
try:
# Get page content and convert to markdown for better processing
html_content = await page.content()
# Import markdownify here to avoid global import
try:
import markdownify
content = markdownify.markdownify(html_content)
except ImportError:
# Fallback if markdownify is not available
content = html_content
# Create prompt for LLM
prompt_text = """
Your task is to extract the content of the page. You will be given a page and a goal, and you should extract all relevant information around this goal from the page.
Examples of extraction goals:
- Extract all company names
- Extract specific descriptions
- Extract all information about a topic
- Extract links with companies in structured format
- Extract all links
If the goal is vague, summarize the page. Respond in JSON format.
Extraction goal: {goal}
Page content:
{page}
"""
# Format the prompt with the goal and content
max_content_length = min(50000, len(content))
formatted_prompt = prompt_text.format(
goal=goal, page=content[:max_content_length]
)
# Create a proper message list for the LLM
from app.schema import Message
messages = [Message.user_message(formatted_prompt)]
# Use LLM to extract content based on the goal
response = await self.llm.ask(messages)
msg = f"Extracted from page:\n{response}\n"
return ToolResult(output=msg)
except Exception as e:
# Provide a more helpful error message
error_msg = f"Failed to extract content: {str(e)}"
try:
# Try to return a portion of the page content as fallback
return ToolResult(
output=f"{error_msg}\nHere's a portion of the page content:\n{content[:2000]}..."
)
except:
# If all else fails, just return the error
return ToolResult(error=error_msg)
# Tab management actions
elif action == "switch_tab":
if tab_id is None:
return ToolResult(
error="Tab ID is required for 'switch_tab' action"
)
await context.switch_to_tab(tab_id)
page = await context.get_current_page()
await page.wait_for_load_state()
return ToolResult(output=f"Switched to tab {tab_id}")
elif action == "open_tab":
if not url:
return ToolResult(error="URL is required for 'open_tab' action")
await context.create_new_tab(url)
return ToolResult(output=f"Opened new tab with {url}")
elif action == "close_tab":
await context.close_current_tab()
return ToolResult(output="Closed current tab")
# Utility actions
elif action == "wait":
seconds_to_wait = seconds if seconds is not None else 3
await asyncio.sleep(seconds_to_wait)
return ToolResult(output=f"Waited for {seconds_to_wait} seconds")
else:
return ToolResult(error=f"Unknown action: {action}")
except Exception as e:
return ToolResult(error=f"Browser action '{action}' failed: {str(e)}")
async def get_current_state(
self, context: Optional[BrowserContext] = None
) -> ToolResult:
"""
Get the current browser state as a ToolResult.
If context is not provided, uses self.context.
"""
try:
# Use provided context or fall back to self.context
ctx = context or self.context
if not ctx:
return ToolResult(error="Browser context not initialized")
state = await ctx.get_state()
# Create a viewport_info dictionary if it doesn't exist
viewport_height = 0
if hasattr(state, "viewport_info") and state.viewport_info:
viewport_height = state.viewport_info.height
elif hasattr(ctx, "config") and hasattr(ctx.config, "browser_window_size"):
viewport_height = ctx.config.browser_window_size.get("height", 0)
# Take a screenshot for the state
screenshot = await ctx.take_screenshot(full_page=True)
# Build the state info with all required fields
state_info = {
"url": state.url,
"title": state.title,
"tabs": [tab.model_dump() for tab in state.tabs],
"help": "[0], [1], [2], etc., represent clickable indices corresponding to the elements listed. Clicking on these indices will navigate to or interact with the respective content behind them.",
"interactive_elements": (
state.element_tree.clickable_elements_to_string()
if state.element_tree
else ""
),
"scroll_info": {
"pixels_above": getattr(state, "pixels_above", 0),
"pixels_below": getattr(state, "pixels_below", 0),
"total_height": getattr(state, "pixels_above", 0)
+ getattr(state, "pixels_below", 0)
+ viewport_height,
},
"viewport_height": viewport_height,
}
return ToolResult(
output=json.dumps(state_info, indent=4, ensure_ascii=False),
base64_image=screenshot,
)
except Exception as e:
return ToolResult(error=f"Failed to get browser state: {str(e)}")
async def cleanup(self):
"""Clean up browser resources."""
async with self.lock:
if self.context is not None:
await self.context.close()
self.context = None
self.dom_service = None
if self.browser is not None:
await self.browser.close()
self.browser = None
def __del__(self):
"""Ensure cleanup when object is destroyed."""
if self.browser is not None or self.context is not None:
try:
asyncio.run(self.cleanup())
except RuntimeError:
loop = asyncio.new_event_loop()
loop.run_until_complete(self.cleanup())
loop.close()
@classmethod
def create_with_context(cls, context: Context) -> "BrowserUseTool[Context]":
"""Factory method to create a BrowserUseTool with a specific context."""
tool = cls()
tool.tool_context = context
return tool
|
2301_77160584/OpenManus
|
app/tool/browser_use_tool.py
|
Python
|
mit
| 24,924
|
from typing import Any, List, Optional, Type, Union, get_args, get_origin
from pydantic import BaseModel, Field
from app.tool import BaseTool
class CreateChatCompletion(BaseTool):
name: str = "create_chat_completion"
description: str = (
"Creates a structured completion with specified output formatting."
)
# Type mapping for JSON schema
type_mapping: dict = {
str: "string",
int: "integer",
float: "number",
bool: "boolean",
dict: "object",
list: "array",
}
response_type: Optional[Type] = None
required: List[str] = Field(default_factory=lambda: ["response"])
def __init__(self, response_type: Optional[Type] = str):
"""Initialize with a specific response type."""
super().__init__()
self.response_type = response_type
self.parameters = self._build_parameters()
def _build_parameters(self) -> dict:
"""Build parameters schema based on response type."""
if self.response_type == str:
return {
"type": "object",
"properties": {
"response": {
"type": "string",
"description": "The response text that should be delivered to the user.",
},
},
"required": self.required,
}
if isinstance(self.response_type, type) and issubclass(
self.response_type, BaseModel
):
schema = self.response_type.model_json_schema()
return {
"type": "object",
"properties": schema["properties"],
"required": schema.get("required", self.required),
}
return self._create_type_schema(self.response_type)
def _create_type_schema(self, type_hint: Type) -> dict:
"""Create a JSON schema for the given type."""
origin = get_origin(type_hint)
args = get_args(type_hint)
# Handle primitive types
if origin is None:
return {
"type": "object",
"properties": {
"response": {
"type": self.type_mapping.get(type_hint, "string"),
"description": f"Response of type {type_hint.__name__}",
}
},
"required": self.required,
}
# Handle List type
if origin is list:
item_type = args[0] if args else Any
return {
"type": "object",
"properties": {
"response": {
"type": "array",
"items": self._get_type_info(item_type),
}
},
"required": self.required,
}
# Handle Dict type
if origin is dict:
value_type = args[1] if len(args) > 1 else Any
return {
"type": "object",
"properties": {
"response": {
"type": "object",
"additionalProperties": self._get_type_info(value_type),
}
},
"required": self.required,
}
# Handle Union type
if origin is Union:
return self._create_union_schema(args)
return self._build_parameters()
def _get_type_info(self, type_hint: Type) -> dict:
"""Get type information for a single type."""
if isinstance(type_hint, type) and issubclass(type_hint, BaseModel):
return type_hint.model_json_schema()
return {
"type": self.type_mapping.get(type_hint, "string"),
"description": f"Value of type {getattr(type_hint, '__name__', 'any')}",
}
def _create_union_schema(self, types: tuple) -> dict:
"""Create schema for Union types."""
return {
"type": "object",
"properties": {
"response": {"anyOf": [self._get_type_info(t) for t in types]}
},
"required": self.required,
}
async def execute(self, required: list | None = None, **kwargs) -> Any:
"""Execute the chat completion with type conversion.
Args:
required: List of required field names or None
**kwargs: Response data
Returns:
Converted response based on response_type
"""
required = required or self.required
# Handle case when required is a list
if isinstance(required, list) and len(required) > 0:
if len(required) == 1:
required_field = required[0]
result = kwargs.get(required_field, "")
else:
# Return multiple fields as a dictionary
return {field: kwargs.get(field, "") for field in required}
else:
required_field = "response"
result = kwargs.get(required_field, "")
# Type conversion logic
if self.response_type == str:
return result
if isinstance(self.response_type, type) and issubclass(
self.response_type, BaseModel
):
return self.response_type(**kwargs)
if get_origin(self.response_type) in (list, dict):
return result # Assuming result is already in correct format
try:
return self.response_type(result)
except (ValueError, TypeError):
return result
|
2301_77160584/OpenManus
|
app/tool/create_chat_completion.py
|
Python
|
mit
| 5,621
|
import os
import aiofiles
from app.config import WORKSPACE_ROOT
from app.tool.base import BaseTool
class FileSaver(BaseTool):
name: str = "file_saver"
description: str = """Save content to a local file at a specified path.
Use this tool when you need to save text, code, or generated content to a file on the local filesystem.
The tool accepts content and a file path, and saves the content to that location.
"""
parameters: dict = {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "(required) The content to save to the file.",
},
"file_path": {
"type": "string",
"description": "(required) The path where the file should be saved, including filename and extension.",
},
"mode": {
"type": "string",
"description": "(optional) The file opening mode. Default is 'w' for write. Use 'a' for append.",
"enum": ["w", "a"],
"default": "w",
},
},
"required": ["content", "file_path"],
}
async def execute(self, content: str, file_path: str, mode: str = "w") -> str:
"""
Save content to a file at the specified path.
Args:
content (str): The content to save to the file.
file_path (str): The path where the file should be saved.
mode (str, optional): The file opening mode. Default is 'w' for write. Use 'a' for append.
Returns:
str: A message indicating the result of the operation.
"""
try:
# Place the generated file in the workspace directory
if os.path.isabs(file_path):
file_name = os.path.basename(file_path)
full_path = os.path.join(WORKSPACE_ROOT, file_name)
else:
full_path = os.path.join(WORKSPACE_ROOT, file_path)
# Ensure the directory exists
directory = os.path.dirname(full_path)
if directory and not os.path.exists(directory):
os.makedirs(directory)
# Write directly to the file
async with aiofiles.open(full_path, mode, encoding="utf-8") as file:
await file.write(content)
return f"Content successfully saved to {full_path}"
except Exception as e:
return f"Error saving file: {str(e)}"
|
2301_77160584/OpenManus
|
app/tool/file_saver.py
|
Python
|
mit
| 2,493
|
# tool/planning.py
from typing import Dict, List, Literal, Optional
from app.exceptions import ToolError
from app.tool.base import BaseTool, ToolResult
_PLANNING_TOOL_DESCRIPTION = """
A planning tool that allows the agent to create and manage plans for solving complex tasks.
The tool provides functionality for creating plans, updating plan steps, and tracking progress.
"""
class PlanningTool(BaseTool):
"""
A planning tool that allows the agent to create and manage plans for solving complex tasks.
The tool provides functionality for creating plans, updating plan steps, and tracking progress.
"""
name: str = "planning"
description: str = _PLANNING_TOOL_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"command": {
"description": "The command to execute. Available commands: create, update, list, get, set_active, mark_step, delete.",
"enum": [
"create",
"update",
"list",
"get",
"set_active",
"mark_step",
"delete",
],
"type": "string",
},
"plan_id": {
"description": "Unique identifier for the plan. Required for create, update, set_active, and delete commands. Optional for get and mark_step (uses active plan if not specified).",
"type": "string",
},
"title": {
"description": "Title for the plan. Required for create command, optional for update command.",
"type": "string",
},
"steps": {
"description": "List of plan steps. Required for create command, optional for update command.",
"type": "array",
"items": {"type": "string"},
},
"step_index": {
"description": "Index of the step to update (0-based). Required for mark_step command.",
"type": "integer",
},
"step_status": {
"description": "Status to set for a step. Used with mark_step command.",
"enum": ["not_started", "in_progress", "completed", "blocked"],
"type": "string",
},
"step_notes": {
"description": "Additional notes for a step. Optional for mark_step command.",
"type": "string",
},
},
"required": ["command"],
"additionalProperties": False,
}
plans: dict = {} # Dictionary to store plans by plan_id
_current_plan_id: Optional[str] = None # Track the current active plan
async def execute(
self,
*,
command: Literal[
"create", "update", "list", "get", "set_active", "mark_step", "delete"
],
plan_id: Optional[str] = None,
title: Optional[str] = None,
steps: Optional[List[str]] = None,
step_index: Optional[int] = None,
step_status: Optional[
Literal["not_started", "in_progress", "completed", "blocked"]
] = None,
step_notes: Optional[str] = None,
**kwargs,
):
"""
Execute the planning tool with the given command and parameters.
Parameters:
- command: The operation to perform
- plan_id: Unique identifier for the plan
- title: Title for the plan (used with create command)
- steps: List of steps for the plan (used with create command)
- step_index: Index of the step to update (used with mark_step command)
- step_status: Status to set for a step (used with mark_step command)
- step_notes: Additional notes for a step (used with mark_step command)
"""
if command == "create":
return self._create_plan(plan_id, title, steps)
elif command == "update":
return self._update_plan(plan_id, title, steps)
elif command == "list":
return self._list_plans()
elif command == "get":
return self._get_plan(plan_id)
elif command == "set_active":
return self._set_active_plan(plan_id)
elif command == "mark_step":
return self._mark_step(plan_id, step_index, step_status, step_notes)
elif command == "delete":
return self._delete_plan(plan_id)
else:
raise ToolError(
f"Unrecognized command: {command}. Allowed commands are: create, update, list, get, set_active, mark_step, delete"
)
def _create_plan(
self, plan_id: Optional[str], title: Optional[str], steps: Optional[List[str]]
) -> ToolResult:
"""Create a new plan with the given ID, title, and steps."""
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: create")
if plan_id in self.plans:
raise ToolError(
f"A plan with ID '{plan_id}' already exists. Use 'update' to modify existing plans."
)
if not title:
raise ToolError("Parameter `title` is required for command: create")
if (
not steps
or not isinstance(steps, list)
or not all(isinstance(step, str) for step in steps)
):
raise ToolError(
"Parameter `steps` must be a non-empty list of strings for command: create"
)
# Create a new plan with initialized step statuses
plan = {
"plan_id": plan_id,
"title": title,
"steps": steps,
"step_statuses": ["not_started"] * len(steps),
"step_notes": [""] * len(steps),
}
self.plans[plan_id] = plan
self._current_plan_id = plan_id # Set as active plan
return ToolResult(
output=f"Plan created successfully with ID: {plan_id}\n\n{self._format_plan(plan)}"
)
def _update_plan(
self, plan_id: Optional[str], title: Optional[str], steps: Optional[List[str]]
) -> ToolResult:
"""Update an existing plan with new title or steps."""
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: update")
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
plan = self.plans[plan_id]
if title:
plan["title"] = title
if steps:
if not isinstance(steps, list) or not all(
isinstance(step, str) for step in steps
):
raise ToolError(
"Parameter `steps` must be a list of strings for command: update"
)
# Preserve existing step statuses for unchanged steps
old_steps = plan["steps"]
old_statuses = plan["step_statuses"]
old_notes = plan["step_notes"]
# Create new step statuses and notes
new_statuses = []
new_notes = []
for i, step in enumerate(steps):
# If the step exists at the same position in old steps, preserve status and notes
if i < len(old_steps) and step == old_steps[i]:
new_statuses.append(old_statuses[i])
new_notes.append(old_notes[i])
else:
new_statuses.append("not_started")
new_notes.append("")
plan["steps"] = steps
plan["step_statuses"] = new_statuses
plan["step_notes"] = new_notes
return ToolResult(
output=f"Plan updated successfully: {plan_id}\n\n{self._format_plan(plan)}"
)
def _list_plans(self) -> ToolResult:
"""List all available plans."""
if not self.plans:
return ToolResult(
output="No plans available. Create a plan with the 'create' command."
)
output = "Available plans:\n"
for plan_id, plan in self.plans.items():
current_marker = " (active)" if plan_id == self._current_plan_id else ""
completed = sum(
1 for status in plan["step_statuses"] if status == "completed"
)
total = len(plan["steps"])
progress = f"{completed}/{total} steps completed"
output += f"• {plan_id}{current_marker}: {plan['title']} - {progress}\n"
return ToolResult(output=output)
def _get_plan(self, plan_id: Optional[str]) -> ToolResult:
"""Get details of a specific plan."""
if not plan_id:
# If no plan_id is provided, use the current active plan
if not self._current_plan_id:
raise ToolError(
"No active plan. Please specify a plan_id or set an active plan."
)
plan_id = self._current_plan_id
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
plan = self.plans[plan_id]
return ToolResult(output=self._format_plan(plan))
def _set_active_plan(self, plan_id: Optional[str]) -> ToolResult:
"""Set a plan as the active plan."""
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: set_active")
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
self._current_plan_id = plan_id
return ToolResult(
output=f"Plan '{plan_id}' is now the active plan.\n\n{self._format_plan(self.plans[plan_id])}"
)
def _mark_step(
self,
plan_id: Optional[str],
step_index: Optional[int],
step_status: Optional[str],
step_notes: Optional[str],
) -> ToolResult:
"""Mark a step with a specific status and optional notes."""
if not plan_id:
# If no plan_id is provided, use the current active plan
if not self._current_plan_id:
raise ToolError(
"No active plan. Please specify a plan_id or set an active plan."
)
plan_id = self._current_plan_id
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
if step_index is None:
raise ToolError("Parameter `step_index` is required for command: mark_step")
plan = self.plans[plan_id]
if step_index < 0 or step_index >= len(plan["steps"]):
raise ToolError(
f"Invalid step_index: {step_index}. Valid indices range from 0 to {len(plan['steps'])-1}."
)
if step_status and step_status not in [
"not_started",
"in_progress",
"completed",
"blocked",
]:
raise ToolError(
f"Invalid step_status: {step_status}. Valid statuses are: not_started, in_progress, completed, blocked"
)
if step_status:
plan["step_statuses"][step_index] = step_status
if step_notes:
plan["step_notes"][step_index] = step_notes
return ToolResult(
output=f"Step {step_index} updated in plan '{plan_id}'.\n\n{self._format_plan(plan)}"
)
def _delete_plan(self, plan_id: Optional[str]) -> ToolResult:
"""Delete a plan."""
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: delete")
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
del self.plans[plan_id]
# If the deleted plan was the active plan, clear the active plan
if self._current_plan_id == plan_id:
self._current_plan_id = None
return ToolResult(output=f"Plan '{plan_id}' has been deleted.")
def _format_plan(self, plan: Dict) -> str:
"""Format a plan for display."""
output = f"Plan: {plan['title']} (ID: {plan['plan_id']})\n"
output += "=" * len(output) + "\n\n"
# Calculate progress statistics
total_steps = len(plan["steps"])
completed = sum(1 for status in plan["step_statuses"] if status == "completed")
in_progress = sum(
1 for status in plan["step_statuses"] if status == "in_progress"
)
blocked = sum(1 for status in plan["step_statuses"] if status == "blocked")
not_started = sum(
1 for status in plan["step_statuses"] if status == "not_started"
)
output += f"Progress: {completed}/{total_steps} steps completed "
if total_steps > 0:
percentage = (completed / total_steps) * 100
output += f"({percentage:.1f}%)\n"
else:
output += "(0%)\n"
output += f"Status: {completed} completed, {in_progress} in progress, {blocked} blocked, {not_started} not started\n\n"
output += "Steps:\n"
# Add each step with its status and notes
for i, (step, status, notes) in enumerate(
zip(plan["steps"], plan["step_statuses"], plan["step_notes"])
):
status_symbol = {
"not_started": "[ ]",
"in_progress": "[→]",
"completed": "[✓]",
"blocked": "[!]",
}.get(status, "[ ]")
output += f"{i}. {status_symbol} {step}\n"
if notes:
output += f" Notes: {notes}\n"
return output
|
2301_77160584/OpenManus
|
app/tool/planning.py
|
Python
|
mit
| 13,623
|
import multiprocessing
import sys
from io import StringIO
from typing import Dict
from app.tool.base import BaseTool
class PythonExecute(BaseTool):
"""A tool for executing Python code with timeout and safety restrictions."""
name: str = "python_execute"
description: str = "Executes Python code string. Note: Only print outputs are visible, function return values are not captured. Use print statements to see results."
parameters: dict = {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "The Python code to execute.",
},
},
"required": ["code"],
}
def _run_code(self, code: str, result_dict: dict, safe_globals: dict) -> None:
original_stdout = sys.stdout
try:
output_buffer = StringIO()
sys.stdout = output_buffer
exec(code, safe_globals, safe_globals)
result_dict["observation"] = output_buffer.getvalue()
result_dict["success"] = True
except Exception as e:
result_dict["observation"] = str(e)
result_dict["success"] = False
finally:
sys.stdout = original_stdout
async def execute(
self,
code: str,
timeout: int = 5,
) -> Dict:
"""
Executes the provided Python code with a timeout.
Args:
code (str): The Python code to execute.
timeout (int): Execution timeout in seconds.
Returns:
Dict: Contains 'output' with execution output or error message and 'success' status.
"""
with multiprocessing.Manager() as manager:
result = manager.dict({"observation": "", "success": False})
if isinstance(__builtins__, dict):
safe_globals = {"__builtins__": __builtins__}
else:
safe_globals = {"__builtins__": __builtins__.__dict__.copy()}
proc = multiprocessing.Process(
target=self._run_code, args=(code, result, safe_globals)
)
proc.start()
proc.join(timeout)
# timeout process
if proc.is_alive():
proc.terminate()
proc.join(1)
return {
"observation": f"Execution timeout after {timeout} seconds",
"success": False,
}
return dict(result)
|
2301_77160584/OpenManus
|
app/tool/python_execute.py
|
Python
|
mit
| 2,497
|
"""Utility to run shell commands asynchronously with a timeout."""
import asyncio
TRUNCATED_MESSAGE: str = "<response clipped><NOTE>To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.</NOTE>"
MAX_RESPONSE_LEN: int = 16000
def maybe_truncate(content: str, truncate_after: int | None = MAX_RESPONSE_LEN):
"""Truncate content and append a notice if content exceeds the specified length."""
return (
content
if not truncate_after or len(content) <= truncate_after
else content[:truncate_after] + TRUNCATED_MESSAGE
)
async def run(
cmd: str,
timeout: float | None = 120.0, # seconds
truncate_after: int | None = MAX_RESPONSE_LEN,
):
"""Run a shell command asynchronously with a timeout."""
process = await asyncio.create_subprocess_shell(
cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
return (
process.returncode or 0,
maybe_truncate(stdout.decode(), truncate_after=truncate_after),
maybe_truncate(stderr.decode(), truncate_after=truncate_after),
)
except asyncio.TimeoutError as exc:
try:
process.kill()
except ProcessLookupError:
pass
raise TimeoutError(
f"Command '{cmd}' timed out after {timeout} seconds"
) from exc
|
2301_77160584/OpenManus
|
app/tool/run.py
|
Python
|
mit
| 1,596
|
from app.tool.search.baidu_search import BaiduSearchEngine
from app.tool.search.base import WebSearchEngine
from app.tool.search.duckduckgo_search import DuckDuckGoSearchEngine
from app.tool.search.google_search import GoogleSearchEngine
__all__ = [
"WebSearchEngine",
"BaiduSearchEngine",
"DuckDuckGoSearchEngine",
"GoogleSearchEngine",
]
|
2301_77160584/OpenManus
|
app/tool/search/__init__.py
|
Python
|
mit
| 358
|
from baidusearch.baidusearch import search
from app.tool.search.base import WebSearchEngine
class BaiduSearchEngine(WebSearchEngine):
def perform_search(self, query, num_results=10, *args, **kwargs):
"""Baidu search engine."""
return search(query, num_results=num_results)
|
2301_77160584/OpenManus
|
app/tool/search/baidu_search.py
|
Python
|
mit
| 296
|
class WebSearchEngine(object):
def perform_search(
self, query: str, num_results: int = 10, *args, **kwargs
) -> list[dict]:
"""
Perform a web search and return a list of URLs.
Args:
query (str): The search query to submit to the search engine.
num_results (int, optional): The number of search results to return. Default is 10.
args: Additional arguments.
kwargs: Additional keyword arguments.
Returns:
List: A list of dict matching the search query.
"""
raise NotImplementedError
|
2301_77160584/OpenManus
|
app/tool/search/base.py
|
Python
|
mit
| 608
|
from duckduckgo_search import DDGS
from app.tool.search.base import WebSearchEngine
class DuckDuckGoSearchEngine(WebSearchEngine):
async def perform_search(self, query, num_results=10, *args, **kwargs):
"""DuckDuckGo search engine."""
return DDGS.text(query, num_results=num_results)
|
2301_77160584/OpenManus
|
app/tool/search/duckduckgo_search.py
|
Python
|
mit
| 307
|
from googlesearch import search
from app.tool.search.base import WebSearchEngine
class GoogleSearchEngine(WebSearchEngine):
def perform_search(self, query, num_results=10, *args, **kwargs):
"""Google search engine."""
return search(query, num_results=num_results)
|
2301_77160584/OpenManus
|
app/tool/search/google_search.py
|
Python
|
mit
| 287
|
from collections import defaultdict
from pathlib import Path
from typing import Literal, get_args
from app.exceptions import ToolError
from app.tool import BaseTool
from app.tool.base import CLIResult, ToolResult
from app.tool.run import run
Command = Literal[
"view",
"create",
"str_replace",
"insert",
"undo_edit",
]
SNIPPET_LINES: int = 4
MAX_RESPONSE_LEN: int = 16000
TRUNCATED_MESSAGE: str = "<response clipped><NOTE>To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.</NOTE>"
_STR_REPLACE_EDITOR_DESCRIPTION = """Custom editing tool for viewing, creating and editing files
* State is persistent across command calls and discussions with the user
* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep
* The `create` command cannot be used if the specified `path` already exists as a file
* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`
* The `undo_edit` command will revert the last edit made to the file at `path`
Notes for using the `str_replace` command:
* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!
* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique
* The `new_str` parameter should contain the edited lines that should replace the `old_str`
"""
def maybe_truncate(content: str, truncate_after: int | None = MAX_RESPONSE_LEN):
"""Truncate content and append a notice if content exceeds the specified length."""
return (
content
if not truncate_after or len(content) <= truncate_after
else content[:truncate_after] + TRUNCATED_MESSAGE
)
class StrReplaceEditor(BaseTool):
"""A tool for executing bash commands"""
name: str = "str_replace_editor"
description: str = _STR_REPLACE_EDITOR_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"command": {
"description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.",
"enum": ["view", "create", "str_replace", "insert", "undo_edit"],
"type": "string",
},
"path": {
"description": "Absolute path to file or directory.",
"type": "string",
},
"file_text": {
"description": "Required parameter of `create` command, with the content of the file to be created.",
"type": "string",
},
"old_str": {
"description": "Required parameter of `str_replace` command containing the string in `path` to replace.",
"type": "string",
},
"new_str": {
"description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.",
"type": "string",
},
"insert_line": {
"description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.",
"type": "integer",
},
"view_range": {
"description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
"items": {"type": "integer"},
"type": "array",
},
},
"required": ["command", "path"],
}
_file_history: list = defaultdict(list)
async def execute(
self,
*,
command: Command,
path: str,
file_text: str | None = None,
view_range: list[int] | None = None,
old_str: str | None = None,
new_str: str | None = None,
insert_line: int | None = None,
**kwargs,
) -> str:
_path = Path(path)
self.validate_path(command, _path)
if command == "view":
result = await self.view(_path, view_range)
elif command == "create":
if file_text is None:
raise ToolError("Parameter `file_text` is required for command: create")
self.write_file(_path, file_text)
self._file_history[_path].append(file_text)
result = ToolResult(output=f"File created successfully at: {_path}")
elif command == "str_replace":
if old_str is None:
raise ToolError(
"Parameter `old_str` is required for command: str_replace"
)
result = self.str_replace(_path, old_str, new_str)
elif command == "insert":
if insert_line is None:
raise ToolError(
"Parameter `insert_line` is required for command: insert"
)
if new_str is None:
raise ToolError("Parameter `new_str` is required for command: insert")
result = self.insert(_path, insert_line, new_str)
elif command == "undo_edit":
result = self.undo_edit(_path)
else:
raise ToolError(
f'Unrecognized command {command}. The allowed commands for the {self.name} tool are: {", ".join(get_args(Command))}'
)
return str(result)
def validate_path(self, command: str, path: Path):
"""
Check that the path/command combination is valid.
"""
# Check if its an absolute path
if not path.is_absolute():
suggested_path = Path("") / path
raise ToolError(
f"The path {path} is not an absolute path, it should start with `/`. Maybe you meant {suggested_path}?"
)
# Check if path exists
if not path.exists() and command != "create":
raise ToolError(
f"The path {path} does not exist. Please provide a valid path."
)
if path.exists() and command == "create":
raise ToolError(
f"File already exists at: {path}. Cannot overwrite files using command `create`."
)
# Check if the path points to a directory
if path.is_dir():
if command != "view":
raise ToolError(
f"The path {path} is a directory and only the `view` command can be used on directories"
)
async def view(self, path: Path, view_range: list[int] | None = None):
"""Implement the view command"""
if path.is_dir():
if view_range:
raise ToolError(
"The `view_range` parameter is not allowed when `path` points to a directory."
)
_, stdout, stderr = await run(
rf"find {path} -maxdepth 2 -not -path '*/\.*'"
)
if not stderr:
stdout = f"Here's the files and directories up to 2 levels deep in {path}, excluding hidden items:\n{stdout}\n"
return CLIResult(output=stdout, error=stderr)
file_content = self.read_file(path)
init_line = 1
if view_range:
if len(view_range) != 2 or not all(isinstance(i, int) for i in view_range):
raise ToolError(
"Invalid `view_range`. It should be a list of two integers."
)
file_lines = file_content.split("\n")
n_lines_file = len(file_lines)
init_line, final_line = view_range
if init_line < 1 or init_line > n_lines_file:
raise ToolError(
f"Invalid `view_range`: {view_range}. Its first element `{init_line}` should be within the range of lines of the file: {[1, n_lines_file]}"
)
if final_line > n_lines_file:
raise ToolError(
f"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be smaller than the number of lines in the file: `{n_lines_file}`"
)
if final_line != -1 and final_line < init_line:
raise ToolError(
f"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be larger or equal than its first `{init_line}`"
)
if final_line == -1:
file_content = "\n".join(file_lines[init_line - 1 :])
else:
file_content = "\n".join(file_lines[init_line - 1 : final_line])
return CLIResult(
output=self._make_output(file_content, str(path), init_line=init_line)
)
def str_replace(self, path: Path, old_str: str, new_str: str | None):
"""Implement the str_replace command, which replaces old_str with new_str in the file content"""
# Read the file content
file_content = self.read_file(path).expandtabs()
old_str = old_str.expandtabs()
new_str = new_str.expandtabs() if new_str is not None else ""
# Check if old_str is unique in the file
occurrences = file_content.count(old_str)
if occurrences == 0:
raise ToolError(
f"No replacement was performed, old_str `{old_str}` did not appear verbatim in {path}."
)
elif occurrences > 1:
file_content_lines = file_content.split("\n")
lines = [
idx + 1
for idx, line in enumerate(file_content_lines)
if old_str in line
]
raise ToolError(
f"No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines {lines}. Please ensure it is unique"
)
# Replace old_str with new_str
new_file_content = file_content.replace(old_str, new_str)
# Write the new content to the file
self.write_file(path, new_file_content)
# Save the content to history
self._file_history[path].append(file_content)
# Create a snippet of the edited section
replacement_line = file_content.split(old_str)[0].count("\n")
start_line = max(0, replacement_line - SNIPPET_LINES)
end_line = replacement_line + SNIPPET_LINES + new_str.count("\n")
snippet = "\n".join(new_file_content.split("\n")[start_line : end_line + 1])
# Prepare the success message
success_msg = f"The file {path} has been edited. "
success_msg += self._make_output(
snippet, f"a snippet of {path}", start_line + 1
)
success_msg += "Review the changes and make sure they are as expected. Edit the file again if necessary."
return CLIResult(output=success_msg)
def insert(self, path: Path, insert_line: int, new_str: str):
"""Implement the insert command, which inserts new_str at the specified line in the file content."""
file_text = self.read_file(path).expandtabs()
new_str = new_str.expandtabs()
file_text_lines = file_text.split("\n")
n_lines_file = len(file_text_lines)
if insert_line < 0 or insert_line > n_lines_file:
raise ToolError(
f"Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: {[0, n_lines_file]}"
)
new_str_lines = new_str.split("\n")
new_file_text_lines = (
file_text_lines[:insert_line]
+ new_str_lines
+ file_text_lines[insert_line:]
)
snippet_lines = (
file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line]
+ new_str_lines
+ file_text_lines[insert_line : insert_line + SNIPPET_LINES]
)
new_file_text = "\n".join(new_file_text_lines)
snippet = "\n".join(snippet_lines)
self.write_file(path, new_file_text)
self._file_history[path].append(file_text)
success_msg = f"The file {path} has been edited. "
success_msg += self._make_output(
snippet,
"a snippet of the edited file",
max(1, insert_line - SNIPPET_LINES + 1),
)
success_msg += "Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). Edit the file again if necessary."
return CLIResult(output=success_msg)
def undo_edit(self, path: Path):
"""Implement the undo_edit command."""
if not self._file_history[path]:
raise ToolError(f"No edit history found for {path}.")
old_text = self._file_history[path].pop()
self.write_file(path, old_text)
return CLIResult(
output=f"Last edit to {path} undone successfully. {self._make_output(old_text, str(path))}"
)
def read_file(self, path: Path):
"""Read the content of a file from a given path; raise a ToolError if an error occurs."""
try:
return path.read_text()
except Exception as e:
raise ToolError(f"Ran into {e} while trying to read {path}") from None
def write_file(self, path: Path, file: str):
"""Write the content of a file to a given path; raise a ToolError if an error occurs."""
try:
path.write_text(file)
except Exception as e:
raise ToolError(f"Ran into {e} while trying to write to {path}") from None
def _make_output(
self,
file_content: str,
file_descriptor: str,
init_line: int = 1,
expand_tabs: bool = True,
):
"""Generate output for the CLI based on the content of a file."""
file_content = maybe_truncate(file_content)
if expand_tabs:
file_content = file_content.expandtabs()
file_content = "\n".join(
[
f"{i + init_line:6}\t{line}"
for i, line in enumerate(file_content.split("\n"))
]
)
return (
f"Here's the result of running `cat -n` on {file_descriptor}:\n"
+ file_content
+ "\n"
)
|
2301_77160584/OpenManus
|
app/tool/str_replace_editor.py
|
Python
|
mit
| 14,729
|
import asyncio
import os
import shlex
from typing import Optional
from app.tool.base import BaseTool, CLIResult
class Terminal(BaseTool):
name: str = "execute_command"
description: str = """Request to execute a CLI command on the system.
Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task.
You must tailor your command to the user's system and provide a clear explanation of what the command does.
Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run.
Commands will be executed in the current working directory.
Note: You MUST append a `sleep 0.05` to the end of the command for commands that will complete in under 50ms, as this will circumvent a known issue with the terminal tool where it will sometimes not return the output when the command completes too quickly.
"""
parameters: dict = {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "(required) The CLI command to execute. This should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.",
}
},
"required": ["command"],
}
process: Optional[asyncio.subprocess.Process] = None
current_path: str = os.getcwd()
lock: asyncio.Lock = asyncio.Lock()
async def execute(self, command: str) -> CLIResult:
"""
Execute a terminal command asynchronously with persistent context.
Args:
command (str): The terminal command to execute.
Returns:
str: The output, and error of the command execution.
"""
# Split the command by & to handle multiple commands
commands = [cmd.strip() for cmd in command.split("&") if cmd.strip()]
final_output = CLIResult(output="", error="")
for cmd in commands:
sanitized_command = self._sanitize_command(cmd)
# Handle 'cd' command internally
if sanitized_command.lstrip().startswith("cd "):
result = await self._handle_cd_command(sanitized_command)
else:
async with self.lock:
try:
self.process = await asyncio.create_subprocess_shell(
sanitized_command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=self.current_path,
)
stdout, stderr = await self.process.communicate()
result = CLIResult(
output=stdout.decode().strip(),
error=stderr.decode().strip(),
)
except Exception as e:
result = CLIResult(output="", error=str(e))
finally:
self.process = None
# Combine outputs
if result.output:
final_output.output += (
(result.output + "\n") if final_output.output else result.output
)
if result.error:
final_output.error += (
(result.error + "\n") if final_output.error else result.error
)
# Remove trailing newlines
final_output.output = final_output.output.rstrip()
final_output.error = final_output.error.rstrip()
return final_output
async def execute_in_env(self, env_name: str, command: str) -> CLIResult:
"""
Execute a terminal command asynchronously within a specified Conda environment.
Args:
env_name (str): The name of the Conda environment.
command (str): The terminal command to execute within the environment.
Returns:
str: The output, and error of the command execution.
"""
sanitized_command = self._sanitize_command(command)
# Construct the command to run within the Conda environment
# Using 'conda run -n env_name command' to execute without activating
conda_command = f"conda run -n {shlex.quote(env_name)} {sanitized_command}"
return await self.execute(conda_command)
async def _handle_cd_command(self, command: str) -> CLIResult:
"""
Handle 'cd' commands to change the current path.
Args:
command (str): The 'cd' command to process.
Returns:
TerminalOutput: The result of the 'cd' command.
"""
try:
parts = shlex.split(command)
if len(parts) < 2:
new_path = os.path.expanduser("~")
else:
new_path = os.path.expanduser(parts[1])
# Handle relative paths
if not os.path.isabs(new_path):
new_path = os.path.join(self.current_path, new_path)
new_path = os.path.abspath(new_path)
if os.path.isdir(new_path):
self.current_path = new_path
return CLIResult(
output=f"Changed directory to {self.current_path}", error=""
)
else:
return CLIResult(output="", error=f"No such directory: {new_path}")
except Exception as e:
return CLIResult(output="", error=str(e))
@staticmethod
def _sanitize_command(command: str) -> str:
"""
Sanitize the command for safe execution.
Args:
command (str): The command to sanitize.
Returns:
str: The sanitized command.
"""
# Example sanitization: restrict certain dangerous commands
dangerous_commands = ["rm", "sudo", "shutdown", "reboot"]
try:
parts = shlex.split(command)
if any(cmd in dangerous_commands for cmd in parts):
raise ValueError("Use of dangerous commands is restricted.")
except Exception:
# If shlex.split fails, try basic string comparison
if any(cmd in command for cmd in dangerous_commands):
raise ValueError("Use of dangerous commands is restricted.")
# Additional sanitization logic can be added here
return command
async def close(self):
"""Close the persistent shell process if it exists."""
async with self.lock:
if self.process:
self.process.terminate()
try:
await asyncio.wait_for(self.process.wait(), timeout=5)
except asyncio.TimeoutError:
self.process.kill()
await self.process.wait()
finally:
self.process = None
async def __aenter__(self):
"""Enter the asynchronous context manager."""
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Exit the asynchronous context manager and close the process."""
await self.close()
|
2301_77160584/OpenManus
|
app/tool/terminal.py
|
Python
|
mit
| 7,195
|
from app.tool.base import BaseTool
_TERMINATE_DESCRIPTION = """Terminate the interaction when the request is met OR if the assistant cannot proceed further with the task.
When you have finished all the tasks, call this tool to end the work."""
class Terminate(BaseTool):
name: str = "terminate"
description: str = _TERMINATE_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"status": {
"type": "string",
"description": "The finish status of the interaction.",
"enum": ["success", "failure"],
}
},
"required": ["status"],
}
async def execute(self, status: str) -> str:
"""Finish the current execution"""
return f"The interaction has been completed with status: {status}"
|
2301_77160584/OpenManus
|
app/tool/terminate.py
|
Python
|
mit
| 833
|
"""Collection classes for managing multiple tools."""
from typing import Any, Dict, List
from app.exceptions import ToolError
from app.tool.base import BaseTool, ToolFailure, ToolResult
class ToolCollection:
"""A collection of defined tools."""
def __init__(self, *tools: BaseTool):
self.tools = tools
self.tool_map = {tool.name: tool for tool in tools}
def __iter__(self):
return iter(self.tools)
def to_params(self) -> List[Dict[str, Any]]:
return [tool.to_param() for tool in self.tools]
async def execute(
self, *, name: str, tool_input: Dict[str, Any] = None
) -> ToolResult:
tool = self.tool_map.get(name)
if not tool:
return ToolFailure(error=f"Tool {name} is invalid")
try:
result = await tool(**tool_input)
return result
except ToolError as e:
return ToolFailure(error=e.message)
async def execute_all(self) -> List[ToolResult]:
"""Execute all tools in the collection sequentially."""
results = []
for tool in self.tools:
try:
result = await tool()
results.append(result)
except ToolError as e:
results.append(ToolFailure(error=e.message))
return results
def get_tool(self, name: str) -> BaseTool:
return self.tool_map.get(name)
def add_tool(self, tool: BaseTool):
self.tools += (tool,)
self.tool_map[tool.name] = tool
return self
def add_tools(self, *tools: BaseTool):
for tool in tools:
self.add_tool(tool)
return self
|
2301_77160584/OpenManus
|
app/tool/tool_collection.py
|
Python
|
mit
| 1,665
|
import asyncio
from typing import List
from tenacity import retry, stop_after_attempt, wait_exponential
from app.config import config
from app.tool.base import BaseTool
from app.tool.search import (
BaiduSearchEngine,
DuckDuckGoSearchEngine,
GoogleSearchEngine,
WebSearchEngine,
)
class WebSearch(BaseTool):
name: str = "web_search"
description: str = """Perform a web search and return a list of relevant links.
This function attempts to use the primary search engine API to get up-to-date results.
If an error occurs, it falls back to an alternative search engine."""
parameters: dict = {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "(required) The search query to submit to the search engine.",
},
"num_results": {
"type": "integer",
"description": "(optional) The number of search results to return. Default is 10.",
"default": 10,
},
},
"required": ["query"],
}
_search_engine: dict[str, WebSearchEngine] = {
"google": GoogleSearchEngine(),
"baidu": BaiduSearchEngine(),
"duckduckgo": DuckDuckGoSearchEngine(),
}
async def execute(self, query: str, num_results: int = 10) -> List[str]:
"""
Execute a Web search and return a list of URLs.
Args:
query (str): The search query to submit to the search engine.
num_results (int, optional): The number of search results to return. Default is 10.
Returns:
List[str]: A list of URLs matching the search query.
"""
engine_order = self._get_engine_order()
for engine_name in engine_order:
engine = self._search_engine[engine_name]
try:
links = await self._perform_search_with_engine(
engine, query, num_results
)
if links:
return links
except Exception as e:
print(f"Search engine '{engine_name}' failed with error: {e}")
return []
def _get_engine_order(self) -> List[str]:
"""
Determines the order in which to try search engines.
Preferred engine is first (based on configuration), followed by the remaining engines.
Returns:
List[str]: Ordered list of search engine names.
"""
preferred = "google"
if config.search_config and config.search_config.engine:
preferred = config.search_config.engine.lower()
engine_order = []
if preferred in self._search_engine:
engine_order.append(preferred)
for key in self._search_engine:
if key not in engine_order:
engine_order.append(key)
return engine_order
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=1, max=10),
)
async def _perform_search_with_engine(
self,
engine: WebSearchEngine,
query: str,
num_results: int,
) -> List[str]:
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None, lambda: list(engine.perform_search(query, num_results=num_results))
)
|
2301_77160584/OpenManus
|
app/tool/web_search.py
|
Python
|
mit
| 3,367
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Japan Travel Handbook - April 15-23, 2024</title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; margin: 0; padding: 20px; }
.container { max-width: 1000px; margin: 0 auto; }
h1, h2, h3 { color: #333; }
.day-item { background: #f9f9f9; padding: 15px; margin: 10px 0; border-radius: 5px; }
.important-note { background: #ffe6e6; padding: 10px; border-radius: 5px; }
.phrase-table { width: 100%; border-collapse: collapse; }
.phrase-table td, .phrase-table th { border: 1px solid #ddd; padding: 8px; }
.proposal-spot { background: #e6ffe6; padding: 15px; margin: 10px 0; border-radius: 5px; }
.flight-info { background: #e6f3ff; padding: 15px; margin: 10px 0; border-radius: 5px; }
.checklist { background: #fff3e6; padding: 15px; margin: 10px 0; border-radius: 5px; }
.hotels { background: #e6e6ff; padding: 15px; margin: 10px 0; border-radius: 5px; }
.proposal-plan { background: #ffe6ff; padding: 15px; margin: 10px 0; border-radius: 5px; }
.checkbox-list li { list-style-type: none; margin-bottom: 8px; }
.checkbox-list li:before { content: "☐ "; }
.warning { color: #ff4444; }
</style>
</head>
<body>
<div class="container">
[Previous content remains the same...]
<div class="proposal-plan">
<h2>🌸 Proposal Planning Guide 🌸</h2>
<h3>Ring Security & Transport</h3>
<ul>
<li><strong>Carrying the Ring:</strong>
<ul>
<li>Always keep the ring in your carry-on luggage, never in checked bags</li>
<li>Use a discrete, non-branded box or case</li>
<li>Consider travel insurance that covers jewelry</li>
<li>Keep receipt/appraisal documentation separate from the ring</li>
</ul>
</li>
<li><strong>Airport Security Tips:</strong>
<ul>
<li>No need to declare the ring unless value exceeds ¥1,000,000 (~$6,700)</li>
<li>If asked, simply state it's "personal jewelry"</li>
<li>Consider requesting private screening to maintain surprise</li>
<li>Keep ring in original box until through security, then transfer to more discrete case</li>
</ul>
</li>
</ul>
<h3>Proposal Location Details - Maruyama Park</h3>
<ul>
<li><strong>Best Timing:</strong>
<ul>
<li>Date: April 19 (Day 5)</li>
<li>Time: 5:30 PM (30 minutes before sunset)</li>
<li>Park closes at 8:00 PM in April</li>
</ul>
</li>
<li><strong>Specific Spot Recommendations:</strong>
<ul>
<li>Primary Location: Near the famous weeping cherry tree
<br>- Less crowded in early evening
<br>- Beautiful illumination starts at dusk
<br>- Iconic Kyoto backdrop
</li>
<li>Backup Location: Gion Shirakawa area
<br>- Atmospheric stone-paved street
<br>- Traditional buildings and cherry trees
<br>- Beautiful in light rain
</li>
</ul>
</li>
</ul>
<h3>Proposal Day Planning</h3>
<ul>
<li><strong>Morning Preparation:</strong>
<ul>
<li>Confirm weather forecast</li>
<li>Transfer ring to secure pocket/bag</li>
<li>Have backup indoor location details ready</li>
</ul>
</li>
<li><strong>Suggested Timeline:</strong>
<ul>
<li>4:00 PM: Start heading to Maruyama Park area</li>
<li>4:30 PM: Light refreshments at nearby tea house</li>
<li>5:15 PM: Begin walk through park</li>
<li>5:30 PM: Arrive at proposal spot</li>
<li>6:00 PM: Sunset and illumination begins</li>
<li>7:00 PM: Celebratory dinner reservation</li>
</ul>
</li>
</ul>
<h3>Celebration Dinner Options</h3>
<ul>
<li><strong>Traditional Japanese:</strong> Kikunoi Roan
<br>- Intimate 2-star Michelin restaurant
<br>- Advance reservation required (3 months)
<br>- Price: ¥15,000-20,000 per person
</li>
<li><strong>Modern Fusion:</strong> The Sodoh
<br>- Beautiful garden views
<br>- Western-style seating available
<br>- Price: ¥12,000-15,000 per person
</li>
</ul>
<div class="warning">
<h3>Important Notes:</h3>
<ul>
<li>Keep proposal plans in separate notes from shared itinerary</li>
<li>Have a backup plan in case of rain (indoor locations listed above)</li>
<li>Consider hiring a local photographer to capture the moment</li>
<li>Save restaurant staff contact info in case of timing changes</li>
</ul>
</div>
</div>
</div>
</body>
</html>
|
2301_77160584/OpenManus
|
examples/japan-travel-plan/japan_travel_handbook.html
|
HTML
|
mit
| 5,951
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Japan Travel Guide (Mobile)</title>
<style>
* { box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
margin: 0;
padding: 10px;
line-height: 1.6;
font-size: 16px;
}
.container {
max-width: 100%;
margin: 0 auto;
}
h1 { font-size: 1.5em; margin: 10px 0; }
h2 { font-size: 1.3em; margin: 8px 0; }
h3 { font-size: 1.1em; margin: 6px 0; }
/* Mobile-friendly cards */
.card {
background: #fff;
border-radius: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
margin: 10px 0;
padding: 15px;
}
/* Collapsible sections */
.collapsible {
background: #f8f9fa;
border: none;
border-radius: 8px;
width: 100%;
padding: 15px;
text-align: left;
font-size: 1.1em;
font-weight: bold;
cursor: pointer;
margin: 5px 0;
}
.content {
display: none;
padding: 10px;
}
.active {
background: #e9ecef;
}
/* Mobile-friendly tables */
.table-wrapper {
overflow-x: auto;
margin: 10px 0;
}
table {
width: 100%;
border-collapse: collapse;
min-width: 300px;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th {
background: #f8f9fa;
}
/* Touch-friendly lists */
ul, ol {
padding-left: 20px;
margin: 10px 0;
}
li {
margin: 8px 0;
padding: 5px 0;
}
/* Emergency info styling */
.emergency {
background: #ffe6e6;
border-left: 4px solid #ff4444;
padding: 10px;
margin: 10px 0;
}
/* Quick access buttons */
.quick-access {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin: 10px 0;
}
.quick-btn {
background: #007bff;
color: white;
border: none;
border-radius: 20px;
padding: 10px 20px;
font-size: 0.9em;
cursor: pointer;
flex: 1 1 auto;
text-align: center;
min-width: 120px;
}
/* Dark mode support */
@media (prefers-color-scheme: dark) {
body {
background: #1a1a1a;
color: #fff;
}
.card {
background: #2d2d2d;
}
.collapsible {
background: #333;
color: #fff;
}
.active {
background: #404040;
}
th {
background: #333;
}
td, th {
border-color: #404040;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Japan Travel Guide</h1>
<p><strong>April 15-23, 2024</strong></p>
<div class="quick-access">
<button class="quick-btn" onclick="showSection('emergency')">Emergency</button>
<button class="quick-btn" onclick="showSection('phrases')">Phrases</button>
<button class="quick-btn" onclick="showSection('transport')">Transport</button>
<button class="quick-btn" onclick="showSection('proposal')">Proposal</button>
</div>
<div class="emergency card" id="emergency">
<h2>Emergency Contacts</h2>
<ul>
<li>🚑 Emergency: 119</li>
<li>👮 Police: 110</li>
<li>🏢 US Embassy: +81-3-3224-5000</li>
<li>ℹ️ Tourist Info: 03-3201-3331</li>
</ul>
</div>
<button class="collapsible">📅 Daily Itinerary</button>
<div class="content">
<div class="table-wrapper">
<table>
<tr><th>Date</th><th>Location</th><th>Activities</th></tr>
<tr><td>Apr 15</td><td>Tokyo</td><td>Arrival, Shinjuku</td></tr>
<tr><td>Apr 16</td><td>Tokyo</td><td>Meiji, Harajuku, Senso-ji</td></tr>
<tr><td>Apr 17</td><td>Tokyo</td><td>Tea Ceremony, Budokan</td></tr>
<tr><td>Apr 18</td><td>Kyoto</td><td>Travel, Kinkaku-ji</td></tr>
<tr><td>Apr 19</td><td>Kyoto</td><td>Fushimi Inari, Proposal</td></tr>
<tr><td>Apr 20</td><td>Nara</td><td>Deer Park, Temples</td></tr>
<tr><td>Apr 21</td><td>Tokyo</td><td>Return, Bay Cruise</td></tr>
</table>
</div>
</div>
<button class="collapsible">🗣️ Essential Phrases</button>
<div class="content">
<div class="table-wrapper">
<table>
<tr><th>English</th><th>Japanese</th></tr>
<tr><td>Thank you</td><td>ありがとう</td></tr>
<tr><td>Excuse me</td><td>すみません</td></tr>
<tr><td>Please</td><td>お願いします</td></tr>
<tr><td>Where is...</td><td>...はどこですか</td></tr>
<tr><td>Help!</td><td>助けて!</td></tr>
</table>
</div>
</div>
<button class="collapsible">🚅 Transportation</button>
<div class="content">
<div class="card">
<h3>Key Routes</h3>
<ul>
<li>Tokyo-Kyoto: 2h15m</li>
<li>Kyoto-Nara: 45m</li>
<li>Last trains: ~midnight</li>
</ul>
<p><strong>JR Pass:</strong> Activate April 15</p>
</div>
</div>
<button class="collapsible">💍 Proposal Plan</button>
<div class="content">
<div class="card">
<h3>April 19 Timeline</h3>
<ul>
<li>4:00 PM: Head to Maruyama Park</li>
<li>5:30 PM: Arrive at spot</li>
<li>7:00 PM: Dinner at Kikunoi Roan</li>
</ul>
<p><strong>Backup:</strong> Gion Shirakawa area</p>
</div>
</div>
<button class="collapsible">💰 Budget Tracker</button>
<div class="content">
<div class="table-wrapper">
<table>
<tr><th>Item</th><th>Budget</th></tr>
<tr><td>Hotels</td><td>$1500-2000</td></tr>
<tr><td>Transport</td><td>$600-800</td></tr>
<tr><td>Food</td><td>$800-1000</td></tr>
<tr><td>Activities</td><td>$600-800</td></tr>
<tr><td>Shopping</td><td>$500-400</td></tr>
</table>
</div>
</div>
</div>
<script>
// Add click handlers for collapsible sections
var coll = document.getElementsByClassName("collapsible");
for (var i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
// Function to show specific section
function showSection(id) {
document.getElementById(id).scrollIntoView({
behavior: 'smooth'
});
}
</script>
</body>
</html>
|
2301_77160584/OpenManus
|
examples/japan-travel-plan/japan_travel_handbook_mobile.html
|
HTML
|
mit
| 8,218
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Japan Travel Handbook (Print Version) - April 15-23, 2024</title>
<style>
@media print {
body {
font-family: Arial, sans-serif;
font-size: 11pt;
line-height: 1.4;
margin: 0.5in;
}
h1 { font-size: 16pt; }
h2 { font-size: 14pt; }
h3 { font-size: 12pt; }
.section {
margin: 10px 0;
padding: 5px;
border: 1px solid #ccc;
page-break-inside: avoid;
}
.no-break {
page-break-inside: avoid;
}
table {
border-collapse: collapse;
width: 100%;
margin: 10px 0;
}
td, th {
border: 1px solid #000;
padding: 4px;
font-size: 10pt;
}
ul, ol {
margin: 5px 0;
padding-left: 20px;
}
li {
margin: 3px 0;
}
.page-break {
page-break-before: always;
}
}
/* Screen styles */
body {
font-family: Arial, sans-serif;
line-height: 1.4;
margin: 20px;
max-width: 800px;
margin: 0 auto;
}
.section {
margin: 15px 0;
padding: 15px;
border: 1px solid #ccc;
border-radius: 5px;
}
table {
border-collapse: collapse;
width: 100%;
margin: 10px 0;
}
td, th {
border: 1px solid #000;
padding: 8px;
}
@media screen {
.page-break {
margin: 30px 0;
border-top: 2px dashed #ccc;
}
}
</style>
</head>
<body>
<h1>Japan Travel Handbook (Print Version)</h1>
<p><strong>Trip Dates:</strong> April 15-23, 2024</p>
<div class="section">
<h2>Emergency Contacts & Important Information</h2>
<ul>
<li>Emergency in Japan: 119 (Ambulance/Fire) / 110 (Police)</li>
<li>US Embassy Tokyo: +81-3-3224-5000</li>
<li>Tourist Information Hotline: 03-3201-3331</li>
<li>Your Travel Insurance: [Write number here]</li>
</ul>
</div>
<div class="section">
<h2>Daily Itinerary Summary</h2>
<table>
<tr><th>Date</th><th>Location</th><th>Key Activities</th></tr>
<tr><td>Apr 15</td><td>Tokyo</td><td>Arrival, Shinjuku area exploration</td></tr>
<tr><td>Apr 16</td><td>Tokyo</td><td>Meiji Shrine, Harajuku, Senso-ji, Skytree</td></tr>
<tr><td>Apr 17</td><td>Tokyo</td><td>Tea Ceremony, Budokan, Yanaka Ginza</td></tr>
<tr><td>Apr 18</td><td>Kyoto</td><td>Travel to Kyoto, Kinkaku-ji, Gion</td></tr>
<tr><td>Apr 19</td><td>Kyoto</td><td>Fushimi Inari, Arashiyama, Evening Proposal</td></tr>
<tr><td>Apr 20</td><td>Nara/Kyoto</td><td>Nara Park day trip, deer feeding</td></tr>
<tr><td>Apr 21</td><td>Tokyo</td><td>Return to Tokyo, bay cruise</td></tr>
</table>
</div>
<div class="page-break"></div>
<div class="section">
<h2>Essential Japanese Phrases</h2>
<table>
<tr><th>English</th><th>Japanese</th><th>When to Use</th></tr>
<tr><td>Arigatou gozaimasu</td><td>ありがとうございます</td><td>Thank you (formal)</td></tr>
<tr><td>Sumimasen</td><td>すみません</td><td>Excuse me/Sorry</td></tr>
<tr><td>Onegaishimasu</td><td>お願いします</td><td>Please</td></tr>
<tr><td>Toire wa doko desu ka?</td><td>トイレはどこですか?</td><td>Where is the bathroom?</td></tr>
<tr><td>Eigo ga hanasemasu ka?</td><td>英語が話せますか?</td><td>Do you speak English?</td></tr>
</table>
</div>
<div class="section">
<h2>Transportation Notes</h2>
<ul>
<li>JR Pass: Activate on April 15</li>
<li>Tokyo-Kyoto Shinkansen: ~2h15m</li>
<li>Kyoto-Nara Local Train: ~45m</li>
<li>Last trains: Usually around midnight</li>
<li>Keep ¥3000 for unexpected taxi rides</li>
</ul>
</div>
<div class="page-break"></div>
<div class="section no-break">
<h2>Proposal Day Timeline (April 19)</h2>
<table>
<tr><th>Time</th><th>Activity</th><th>Notes</th></tr>
<tr><td>4:00 PM</td><td>Head to Maruyama Park</td><td>Check weather first</td></tr>
<tr><td>4:30 PM</td><td>Tea house visit</td><td>Light refreshments</td></tr>
<tr><td>5:15 PM</td><td>Park walk begins</td><td>Head to weeping cherry tree</td></tr>
<tr><td>5:30 PM</td><td>Arrive at spot</td><td>Find quiet area</td></tr>
<tr><td>7:00 PM</td><td>Dinner reservation</td><td>Kikunoi Roan</td></tr>
</table>
<p><strong>Backup Location:</strong> Gion Shirakawa area (in case of rain)</p>
</div>
<div class="section">
<h2>Quick Reference Budget</h2>
<table>
<tr><th>Item</th><th>Budget (USD)</th><th>Notes</th></tr>
<tr><td>Hotels</td><td>1500-2000</td><td>Pre-booked</td></tr>
<tr><td>Transport</td><td>600-800</td><td>Including JR Pass</td></tr>
<tr><td>Food</td><td>800-1000</td><td>~$60/person/day</td></tr>
<tr><td>Activities</td><td>600-800</td><td>Including tea ceremony</td></tr>
<tr><td>Shopping</td><td>500-400</td><td>Souvenirs/gifts</td></tr>
</table>
</div>
</body>
</html>
|
2301_77160584/OpenManus
|
examples/japan-travel-plan/japan_travel_handbook_print.html
|
HTML
|
mit
| 5,863
|
import asyncio
from app.agent.manus import Manus
from app.logger import logger
async def main():
agent = Manus()
try:
prompt = input("Enter your prompt: ")
if not prompt.strip():
logger.warning("Empty prompt provided.")
return
logger.warning("Processing your request...")
await agent.run(prompt)
logger.info("Request processing completed.")
except KeyboardInterrupt:
logger.warning("Operation interrupted.")
if __name__ == "__main__":
asyncio.run(main())
|
2301_77160584/OpenManus
|
main.py
|
Python
|
mit
| 549
|
import asyncio
import time
from app.agent.manus import Manus
from app.flow.base import FlowType
from app.flow.flow_factory import FlowFactory
from app.logger import logger
async def run_flow():
agents = {
"manus": Manus(),
}
try:
prompt = input("Enter your prompt: ")
if prompt.strip().isspace() or not prompt:
logger.warning("Empty prompt provided.")
return
flow = FlowFactory.create_flow(
flow_type=FlowType.PLANNING,
agents=agents,
)
logger.warning("Processing your request...")
try:
start_time = time.time()
result = await asyncio.wait_for(
flow.execute(prompt),
timeout=3600, # 60 minute timeout for the entire execution
)
elapsed_time = time.time() - start_time
logger.info(f"Request processed in {elapsed_time:.2f} seconds")
logger.info(result)
except asyncio.TimeoutError:
logger.error("Request processing timed out after 1 hour")
logger.info(
"Operation terminated due to timeout. Please try a simpler request."
)
except KeyboardInterrupt:
logger.info("Operation cancelled by user.")
except Exception as e:
logger.error(f"Error: {str(e)}")
if __name__ == "__main__":
asyncio.run(run_flow())
|
2301_77160584/OpenManus
|
run_flow.py
|
Python
|
mit
| 1,419
|
from setuptools import find_packages, setup
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="openmanus",
version="0.1.0",
author="mannaandpoem and OpenManus Team",
author_email="mannaandpoem@gmail.com",
description="A versatile agent that can solve various tasks using multiple tools",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/mannaandpoem/OpenManus",
packages=find_packages(),
install_requires=[
"pydantic~=2.10.4",
"openai>=1.58.1,<1.67.0",
"tenacity~=9.0.0",
"pyyaml~=6.0.2",
"loguru~=0.7.3",
"numpy",
"datasets~=3.2.0",
"html2text~=2024.2.26",
"gymnasium~=1.0.0",
"pillow~=10.4.0",
"browsergym~=0.13.3",
"uvicorn~=0.34.0",
"unidiff~=0.7.5",
"browser-use~=0.1.40",
"googlesearch-python~=1.3.0",
"aiofiles~=24.1.0",
"pydantic_core>=2.27.2,<2.28.0",
"colorama~=0.4.6",
],
classifiers=[
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.12",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.12",
entry_points={
"console_scripts": [
"openmanus=main:main",
],
},
)
|
2301_77160584/OpenManus
|
setup.py
|
Python
|
mit
| 1,430
|
/* 基础样式重置 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
color: #333;
line-height: 1.6;
background-color: #f5f7fa;
}
.container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
padding: 0 15px;
}
a {
text-decoration: none;
color: inherit;
}
ul {
list-style: none;
}
/* 头部导航 */
header {
background-color: #fff;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
position: sticky;
top: 0;
z-index: 100;
}
header .container {
display: flex;
justify-content: space-between;
align-items: center;
height: 70px;
}
.logo {
display: flex;
align-items: center;
}
.logo img {
height: 40px;
margin-right: 10px;
}
.logo span {
font-size: 20px;
font-weight: bold;
color: #0066cc;
}
nav ul {
display: flex;
}
nav ul li {
margin-left: 25px;
}
nav ul li a {
font-size: 16px;
color: #555;
padding: 5px 0;
position: relative;
transition: color 0.3s;
}
nav ul li a:hover,
nav ul li a.active {
color: #0066cc;
}
nav ul li a.active:after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 100%;
height: 2px;
background-color: #0066cc;
}
/* 英雄区域 */
.hero {
background: linear-gradient(135deg, #0066cc, #004080);
color: white;
padding: 50px 0;
text-align: center;
}
.hero h1 {
font-size: 36px;
margin-bottom: 15px;
}
.hero p {
font-size: 18px;
margin-bottom: 20px;
opacity: 0.9;
}
.location {
display: inline-flex;
align-items: center;
background-color: rgba(255, 255, 255, 0.2);
padding: 8px 15px;
border-radius: 20px;
}
.location i {
margin-right: 5px;
}
/* 主要内容区 */
.main-content {
padding: 40px 0;
}
.services-section {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
padding: 30px;
margin-bottom: 30px;
}
.services-section h2,
.monitoring-map h2,
.monitoring-dashboard h2 {
font-size: 24px;
color: #333;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 1px solid #eee;
}
.transport-tools,
.info-query {
margin-bottom: 30px;
}
.transport-tools h3,
.info-query h3 {
font-size: 18px;
color: #555;
margin-bottom: 15px;
}
.transport-grid,
.query-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
}
.query-grid {
grid-template-columns: repeat(3, 1fr);
}
.transport-item,
.query-item {
background-color: #f9f9f9;
border-radius: 8px;
padding: 20px;
text-align: center;
transition: all 0.3s;
cursor: pointer;
}
.transport-item:hover,
.query-item:hover {
background-color: #e6f0ff;
transform: translateY(-5px);
box-shadow: 0 5px 15px rgba(0, 102, 204, 0.1);
}
.transport-item .icon,
.query-item .icon {
font-size: 36px;
color: #0066cc;
margin-bottom: 10px;
}
.transport-item .text,
.query-item .text {
font-size: 16px;
font-weight: 500;
}
.query-item .desc {
font-size: 12px;
color: #888;
margin-top: 5px;
}
/* 监测地图 */
.monitoring-map {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
padding: 30px;
margin-bottom: 30px;
}
.map-container {
position: relative;
border: 1px solid #eee;
border-radius: 8px;
overflow: hidden;
}
.map-controls {
position: absolute;
top: 10px;
right: 10px;
z-index: 10;
display: flex;
flex-direction: column;
}
.map-controls button {
background-color: white;
border: 1px solid #ddd;
width: 30px;
height: 30px;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 5px;
cursor: pointer;
transition: all 0.2s;
}
.map-controls button:hover {
background-color: #f0f0f0;
}
.map-image img {
width: 100%;
display: block;
}
.map-legend {
position: absolute;
bottom: 20px;
right: 20px;
background-color: rgba(255, 255, 255, 0.9);
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.legend-item {
display: flex;
align-items: center;
margin-bottom: 5px;
}
.legend-item .color {
width: 15px;
height: 15px;
border-radius: 3px;
margin-right: 8px;
}
.legend-item .text {
font-size: 12px;
}
/* 监测仪表板 */
.monitoring-dashboard {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
padding: 30px;
}
.dashboard-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 20px;
}
.dashboard-card {
border: 1px solid #eee;
border-radius: 8px;
overflow: hidden;
}
.card-header {
background-color: #f5f7fa;
padding: 15px;
display: flex;
justify-content: space-between;
align-items: center;
}
.card-header h3 {
font-size: 16px;
margin: 0;
}
.status {
font-size: 12px;
padding: 3px 8px;
border-radius: 10px;
background-color: #eee;
}
.status.active {
background-color: #e6f7e6;
color: #00aa00;
}
.card-body {
padding: 20px;
}
.metric {
text-align: center;
margin-bottom: 20px;
}
.metric-value {
font-size: 36px;
font-weight: bold;
color: #0066cc;
}
.metric-label {
font-size: 14px;
color: #666;
}
.alerts {
margin-top: 15px;
}
.alert-item {
display: flex;
align-items: center;
padding: 8px 12px;
border-radius: 5px;
margin-bottom: 8px;
font-size: 14px;
}
.alert-item i {
margin-right: 8px;
}
.alert-item.info {
background-color: #e6f0ff;
color: #0066cc;
}
.alert-item.warning {
background-color: #fff8e6;
color: #ffaa00;
}
.alert-item.danger {
background-color: #ffe6e6;
color: #ff0000;
}
.chart-container {
height: 200px;
display: flex;
align-items: center;
justify-content: center;
}
.chart-placeholder {
color: #999;
text-align: center;
border: 1px dashed #ddd;
padding: 20px;
width: 100%;
border-radius: 5px;
}
.card-footer {
padding: 15px;
text-align: center;
border-top: 1px solid #eee;
}
.btn-primary {
background-color: #0066cc;
color: white;
border: none;
padding: 8px 15px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.btn-primary:hover {
background-color: #0055aa;
}
/* 页脚 */
footer {
background-color: #2c3e50;
color: #fff;
padding: 50px 0 20px;
}
.footer-content {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
gap: 30px;
margin-bottom: 30px;
}
.footer-logo {
display: flex;
flex-direction: column;
align-items: flex-start;
}
.footer-logo img {
height: 40px;
margin-bottom: 10px;
}
.footer-logo span {
font-size: 18px;
font-weight: bold;
}
.footer-links {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
.link-group h4 {
font-size: 16px;
margin-bottom: 15px;
color: #fff;
}
.link-group ul li {
margin-bottom: 8px;
}
.link-group ul li a {
color: rgba(255, 255, 255, 0.7);
transition: color 0.3s;
}
.link-group ul li a:hover {
color: #fff;
}
.footer-contact h4 {
font-size: 16px;
margin-bottom: 15px;
}
.footer-contact p {
margin-bottom: 10px;
display: flex;
align-items: center;
color: rgba(255, 255, 255, 0.7);
}
.footer-contact p i {
margin-right: 8px;
}
.social-links {
display: flex;
margin-top: 15px;
}
.social-links a {
width: 36px;
height: 36px;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.1);
display: flex;
align-items: center;
justify-content: center;
margin-right: 10px;
transition: background-color 0.3s;
}
.social-links a:hover {
background-color: rgba(255, 255, 255, 0.2);
}
.copyright {
text-align: center;
padding-top: 20px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.5);
font-size: 14px;
}
/* 响应式设计 */
@media (max-width: 992px) {
.transport-grid,
.query-grid {
grid-template-columns: repeat(2, 1fr);
}
.dashboard-grid {
grid-template-columns: 1fr;
}
.footer-content {
grid-template-columns: 1fr;
}
.footer-links {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 768px) {
header .container {
flex-direction: column;
height: auto;
padding: 15px;
}
nav ul {
flex-wrap: wrap;
justify-content: center;
margin-top: 15px;
}
nav ul li {
margin: 5px 10px;
}
.hero h1 {
font-size: 28px;
}
.hero p {
font-size: 16px;
}
}
@media (max-width: 576px) {
.transport-grid,
.query-grid {
grid-template-columns: 1fr;
}
.footer-links {
grid-template-columns: 1fr;
}
}
|
2301_77385112/zhi_yu_an_xing
|
css/style.css
|
CSS
|
unknown
| 9,099
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>智驭安行 - 智慧交通安全监测系统</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
<header>
<div class="container">
<div class="logo">
<img src="img/logo.png" alt="智驭安行">
<span>智驭安行</span>
</div>
<nav>
<ul>
<li><a href="index.html" class="active">首页</a></li>
<li><a href="travel-service.html">出行服务</a></li>
<li><a href="vehicle-info.html">车辆信息</a></li>
<li><a href="tech-support.html">学习与技术支持</a></li>
<li><a href="customer-service.html">客户服务</a></li>
<li><a href="data.html">数据</a></li>
</ul>
</nav>
</div>
</header>
<div class="hero">
<div class="container">
<h1>智能交通安全监测系统</h1>
<p>实时监测公共交通工具上司机和乘客的异常行为,提升城市交通安全</p>
<div class="location">
<i class="fas fa-map-marker-alt"></i>
<span>北京市</span>
</div>
</div>
</div>
<div class="main-content">
<div class="container">
<div class="services-section">
<h2>出行服务</h2>
<div class="transport-tools">
<h3>交通工具</h3>
<div class="transport-grid">
<div class="transport-item" data-type="bus">
<div class="icon">
<i class="fas fa-bus"></i>
</div>
<div class="text">公交车</div>
</div>
<div class="transport-item" data-type="subway">
<div class="icon">
<i class="fas fa-subway"></i>
</div>
<div class="text">地铁</div>
</div>
<div class="transport-item" data-type="train">
<div class="icon">
<i class="fas fa-train"></i>
</div>
<div class="text">高铁</div>
</div>
<div class="transport-item" data-type="railway">
<div class="icon">
<i class="fas fa-train"></i>
</div>
<div class="text">火车</div>
</div>
</div>
</div>
<div class="info-query">
<h3>信息查询</h3>
<div class="query-grid">
<div class="query-item" data-type="realtime">
<div class="icon">
<i class="fas fa-clock"></i>
</div>
<div class="text">实时公交</div>
<div class="desc">点击查看</div>
</div>
<div class="query-item" data-type="route">
<div class="icon">
<i class="fas fa-search"></i>
</div>
<div class="text">查询公交</div>
<div class="desc">点击查看</div>
</div>
<div class="query-item" data-type="subway">
<div class="icon">
<i class="fas fa-map"></i>
</div>
<div class="text">地铁线路</div>
<div class="desc">点击查看</div>
</div>
</div>
</div>
</div>
<div class="monitoring-map">
<h2>北京市轨道交通线网图</h2>
<div class="map-container">
<div class="map-controls">
<button class="zoom-in"><i class="fas fa-plus"></i></button>
<button class="zoom-out"><i class="fas fa-minus"></i></button>
<button class="reset"><i class="fas fa-redo"></i></button>
</div>
<div class="map-image">
<img src="img/beijing-subway-map.jpg" alt="北京市轨道交通线网图">
</div>
<div class="map-legend">
<div class="legend-title">图例</div>
<div class="legend-items">
<div class="legend-item">
<div class="color" style="background-color: #E40077;"></div>
<div class="text">1号线</div>
</div>
<div class="legend-item">
<div class="color" style="background-color: #0070BD;"></div>
<div class="text">2号线</div>
</div>
<div class="legend-item">
<div class="color" style="background-color: #F9E701;"></div>
<div class="text">4号线</div>
</div>
</div>
</div>
</div>
</div>
<div class="monitoring-dashboard">
<h2>异常行为监测概览</h2>
<div class="dashboard-grid">
<div class="dashboard-card">
<div class="card-header">
<h3>今日监测统计</h3>
<div class="card-actions">
<button class="refresh-btn"><i class="fas fa-sync-alt"></i></button>
</div>
</div>
<div class="card-content">
<div class="metrics">
<div class="metric">
<div class="metric-value">1,245</div>
<div class="metric-label">监测车辆</div>
</div>
<div class="metric">
<div class="metric-value">87</div>
<div class="metric-label">异常行为</div>
</div>
<div class="metric">
<div class="metric-value">42</div>
<div class="metric-label">司机异常</div>
</div>
<div class="metric">
<div class="metric-value">45</div>
<div class="metric-label">乘客异常</div>
</div>
</div>
</div>
</div>
<div class="dashboard-card">
<div class="card-header">
<h3>实时告警</h3>
<div class="card-actions">
<button class="view-all-btn">查看全部</button>
</div>
</div>
<div class="card-content">
<div class="alerts">
<div class="alert">
<div class="alert-icon warning">
<i class="fas fa-exclamation-triangle"></i>
</div>
<div class="alert-content">
<div class="alert-title">检测到1号公交车司机疲劳驾驶行为</div>
<div class="alert-time">10分钟前</div>
</div>
</div>
<div class="alert">
<div class="alert-icon danger">
<i class="fas fa-exclamation-circle"></i>
</div>
<div class="alert-content">
<div class="alert-title">5号地铁车厢内检测到可疑物品</div>
<div class="alert-time">25分钟前</div>
</div>
</div>
<div class="alert">
<div class="alert-icon warning">
<i class="fas fa-exclamation-triangle"></i>
</div>
<div class="alert-content">
<div class="alert-title">3号公交车乘客区域检测到异常行为</div>
<div class="alert-time">40分钟前</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer>
<div class="container">
<div class="footer-content">
<div class="footer-logo">
<img src="img/logo.png" alt="智驭安行">
<span>智驭安行</span>
</div>
<div class="footer-links">
<div class="link-group">
<h3>关于我们</h3>
<ul>
<li><a href="#">公司简介</a></li>
<li><a href="#">联系方式</a></li>
<li><a href="#">加入我们</a></li>
</ul>
</div>
<div class="link-group">
<h3>服务支持</h3>
<ul>
<li><a href="#">帮助中心</a></li>
<li><a href="#">常见问题</a></li>
<li><a href="#">技术支持</a></li>
</ul>
</div>
<div class="link-group">
<h3>法律信息</h3>
<ul>
<li><a href="#">隐私政策</a></li>
<li><a href="#">使用条款</a></li>
<li><a href="#">版权声明</a></li>
</ul>
</div>
</div>
<div class="footer-contact">
<h3>联系我们</h3>
<p><i class="fas fa-phone"></i> 400-123-4567</p>
<p><i class="fas fa-envelope"></i> contact@zhiyuanxing.com</p>
<div class="social-links">
<a href="#"><i class="fab fa-weixin"></i></a>
<a href="#"><i class="fab fa-weibo"></i></a>
<a href="#"><i class="fab fa-qq"></i></a>
</div>
</div>
</div>
<div class="footer-bottom">
<p>© 2023 智驭安行 版权所有</p>
</div>
</div>
</footer>
<script src="js/main.js"></script>
</body>
</html>
|
2301_77385112/zhi_yu_an_xing
|
index.html
|
HTML
|
unknown
| 12,429
|
// 智驭安行 - 智慧交通系统主要JavaScript文件
document.addEventListener('DOMContentLoaded', function() {
// 初始化导航栏激活状态
initNavigation();
// 初始化交通工具点击事件
initTransportItems();
// 初始化查询项点击事件
initQueryItems();
// 初始化地图控制
initMapControls();
// 初始化仪表盘数据
initDashboardData();
// 初始化异常行为监测模拟
initAnomalyDetection();
});
// 导航栏激活状态
function initNavigation() {
const navLinks = document.querySelectorAll('nav ul li a');
const currentPath = window.location.pathname;
navLinks.forEach(link => {
if (link.getAttribute('href') === currentPath ||
(currentPath === '/' && link.getAttribute('href') === 'index.html')) {
link.classList.add('active');
}
link.addEventListener('click', function(e) {
navLinks.forEach(l => l.classList.remove('active'));
this.classList.add('active');
});
});
}
// 交通工具项点击事件
function initTransportItems() {
const transportItems = document.querySelectorAll('.transport-item');
transportItems.forEach(item => {
item.addEventListener('click', function() {
const transportType = this.getAttribute('data-type');
// 模拟跳转到相应的交通工具监测页面
if (transportType) {
window.location.href = `transport-monitor.html?type=${transportType}`;
} else {
console.log('未设置交通工具类型');
}
});
});
}
// 查询项点击事件
function initQueryItems() {
const queryItems = document.querySelectorAll('.query-item');
queryItems.forEach(item => {
item.addEventListener('click', function() {
const queryType = this.getAttribute('data-type');
// 模拟跳转到相应的查询页面
if (queryType) {
window.location.href = `query.html?type=${queryType}`;
} else {
console.log('未设置查询类型');
}
});
});
}
// 地图控制功能
function initMapControls() {
const zoomInBtn = document.querySelector('.map-controls .zoom-in');
const zoomOutBtn = document.querySelector('.map-controls .zoom-out');
const resetBtn = document.querySelector('.map-controls .reset');
if (zoomInBtn && zoomOutBtn && resetBtn) {
let scale = 1;
const mapImage = document.querySelector('.map-image img');
zoomInBtn.addEventListener('click', function() {
scale += 0.1;
updateMapScale(mapImage, scale);
});
zoomOutBtn.addEventListener('click', function() {
scale = Math.max(0.5, scale - 0.1);
updateMapScale(mapImage, scale);
});
resetBtn.addEventListener('click', function() {
scale = 1;
updateMapScale(mapImage, scale);
// 重置位置
mapImage.style.transform = `scale(${scale})`;
mapImage.style.transformOrigin = 'center center';
});
// 实现地图拖动功能
let isDragging = false;
let startX, startY, initialX = 0, initialY = 0;
mapImage.addEventListener('mousedown', function(e) {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
initialX = parseInt(mapImage.style.left || 0);
initialY = parseInt(mapImage.style.top || 0);
mapImage.style.cursor = 'grabbing';
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
const dx = e.clientX - startX;
const dy = e.clientY - startY;
mapImage.style.left = `${initialX + dx}px`;
mapImage.style.top = `${initialY + dy}px`;
});
document.addEventListener('mouseup', function() {
isDragging = false;
mapImage.style.cursor = 'grab';
});
}
}
// 更新地图缩放
function updateMapScale(mapImage, scale) {
if (mapImage) {
mapImage.style.transform = `scale(${scale})`;
}
}
// 初始化仪表盘数据
function initDashboardData() {
// 模拟获取实时数据
updateMetrics();
// 定期更新数据
setInterval(updateMetrics, 5000);
// 初始化图表
initCharts();
}
// 更新指标数据
function updateMetrics() {
const metricValues = document.querySelectorAll('.metric-value');
metricValues.forEach(metric => {
// 模拟数据变化
const currentValue = parseInt(metric.textContent);
const variation = Math.floor(Math.random() * 5) - 2; // -2 到 2 的随机变化
const newValue = Math.max(0, currentValue + variation);
// 应用数字变化动画
animateNumberChange(metric, currentValue, newValue);
});
// 更新告警信息
updateAlerts();
}
// 数字变化动画
function animateNumberChange(element, start, end) {
const duration = 1000; // 动画持续时间(毫秒)
const startTime = performance.now();
function updateNumber(currentTime) {
const elapsedTime = currentTime - startTime;
const progress = Math.min(elapsedTime / duration, 1);
const currentValue = Math.floor(start + (end - start) * progress);
element.textContent = currentValue;
if (progress < 1) {
requestAnimationFrame(updateNumber);
}
}
requestAnimationFrame(updateNumber);
}
// 更新告警信息
function updateAlerts() {
const alertsContainer = document.querySelector('.alerts');
if (alertsContainer) {
// 随机决定是否添加新告警
if (Math.random() > 0.7) {
const alertTypes = ['info', 'warning', 'danger'];
const alertMessages = [
'检测到1号公交车司机疲劳驾驶行为',
'5号地铁车厢内检测到可疑物品',
'3号公交车乘客区域检测到异常行为',
'2号地铁站台人流密度过高',
'4号公交车司机长时间分心驾驶'
];
const alertType = alertTypes[Math.floor(Math.random() * alertTypes.length)];
const alertMessage = alertMessages[Math.floor(Math.random() * alertMessages.length)];
const alertItem = document.createElement('div');
alertItem.className = `alert-item ${alertType}`;
alertItem.innerHTML = `<i class="fas fa-exclamation-circle"></i>${alertMessage}`;
// 添加新告警到顶部
alertsContainer.prepend(alertItem);
// 限制告警数量,保持最新的5条
const alerts = alertsContainer.querySelectorAll('.alert-item');
if (alerts.length > 5) {
alertsContainer.removeChild(alerts[alerts.length - 1]);
}
// 添加点击处理告警的功能
alertItem.addEventListener('click', function() {
this.style.opacity = '0.5';
this.style.textDecoration = 'line-through';
// 2秒后移除告警
setTimeout(() => {
this.remove();
}, 2000);
});
}
}
}
// 初始化图表
function initCharts() {
// 这里可以集成图表库如Chart.js或ECharts
// 以下是一个简单的模拟实现
const chartContainers = document.querySelectorAll('.chart-container');
chartContainers.forEach(container => {
const placeholder = container.querySelector('.chart-placeholder');
if (placeholder) {
placeholder.textContent = '图表加载中...';
// 模拟图表加载
setTimeout(() => {
placeholder.textContent = '图表已加载(这里实际项目中应集成图表库)';
}, 1500);
}
});
}
// 异常行为监测模拟
function initAnomalyDetection() {
// 模拟异常行为检测系统
console.log('异常行为监测系统已初始化');
// 定期检查异常行为
setInterval(checkForAnomalies, 8000);
}
// 检查异常行为
function checkForAnomalies() {
// 模拟异常行为检测
const anomalyTypes = [
'司机疲劳驾驶',
'司机分心驾驶',
'乘客异常行为',
'车内可疑物品',
'车辆超载'
];
// 随机决定是否触发异常行为告警
if (Math.random() > 0.7) {
const anomalyType = anomalyTypes[Math.floor(Math.random() * anomalyTypes.length)];
const vehicleId = Math.floor(Math.random() * 10) + 1;
const severity = Math.random() > 0.5 ? '高' : '中';
// 创建告警通知
createAnomalyNotification(anomalyType, vehicleId, severity);
}
}
// 创建异常行为告警通知
function createAnomalyNotification(type, vehicleId, severity) {
// 检查通知容器是否存在,如果不存在则创建
let notificationContainer = document.querySelector('.notification-container');
if (!notificationContainer) {
notificationContainer = document.createElement('div');
notificationContainer.className = 'notification-container';
notificationContainer.style.position = 'fixed';
notificationContainer.style.top = '20px';
notificationContainer.style.right = '20px';
notificationContainer.style.zIndex = '1000';
document.body.appendChild(notificationContainer);
}
// 创建通知元素
const notification = document.createElement('div');
notification.className = `notification ${severity === '高' ? 'high' : 'medium'}`;
notification.style.backgroundColor = severity === '高' ? '#ff4d4d' : '#ffcc00';
notification.style.color = severity === '高' ? 'white' : 'black';
notification.style.padding = '15px';
notification.style.borderRadius = '5px';
notification.style.marginBottom = '10px';
notification.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.2)';
notification.style.display = 'flex';
notification.style.justifyContent = 'space-between';
notification.style.alignItems = 'center';
notification.style.transition = 'all 0.3s ease';
notification.style.cursor = 'pointer';
// 通知内容
notification.innerHTML = `
<div>
<strong>异常行为告警</strong>
<p>车辆ID: ${vehicleId} - 检测到${type}</p>
<p>严重程度: ${severity}</p>
</div>
<div class="close-btn" style="font-size: 20px; cursor: pointer;">×</div>
`;
// 添加到通知容器
notificationContainer.appendChild(notification);
// 添加关闭按钮事件
const closeBtn = notification.querySelector('.close-btn');
closeBtn.addEventListener('click', function(e) {
e.stopPropagation();
notification.style.opacity = '0';
notification.style.transform = 'translateX(100%)';
setTimeout(() => {
notification.remove();
}, 300);
});
// 点击通知跳转到详情页面
notification.addEventListener('click', function() {
window.location.href = `anomaly-details.html?id=${vehicleId}&type=${encodeURIComponent(type)}`;
});
// 5秒后自动消失
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transform = 'translateX(100%)';
setTimeout(() => {
notification.remove();
}, 300);
}, 5000);
}
// 模拟实时数据更新
function simulateRealTimeData() {
// 这里可以添加WebSocket连接或轮询API的代码
console.log('实时数据模拟已启动');
// 模拟数据更新
setInterval(() => {
// 更新在线车辆数
updateOnlineVehicles();
// 更新监控状态
updateMonitoringStatus();
}, 3000);
}
// 更新在线车辆数
function updateOnlineVehicles() {
const onlineVehiclesElement = document.querySelector('.online-vehicles');
if (onlineVehiclesElement) {
const currentValue = parseInt(onlineVehiclesElement.textContent);
const variation = Math.floor(Math.random() * 3) - 1; // -1 到 1 的随机变化
const newValue = Math.max(0, currentValue + variation);
onlineVehiclesElement.textContent = newValue;
}
}
// 更新监控状态
function updateMonitoringStatus() {
const statusElements = document.querySelectorAll('.status');
statusElements.forEach(status => {
// 随机决定是否改变状态
if (Math.random() > 0.9) {
if (status.classList.contains('active')) {
status.classList.remove('active');
status.textContent = '离线';
status.style.backgroundColor = '#eee';
status.style.color = '#666';
} else {
status.classList.add('active');
status.textContent = '在线';
status.style.backgroundColor = '#e6f7e6';
status.style.color = '#00aa00';
}
}
});
}
// 启动实时数据模拟
simulateRealTimeData();
|
2301_77385112/zhi_yu_an_xing
|
js/main.js
|
JavaScript
|
unknown
| 13,652
|
// 交通工具监测页面专用脚本
document.addEventListener('DOMContentLoaded', function() {
// 获取URL参数
const urlParams = new URLSearchParams(window.location.search);
const transportType = urlParams.get('type');
// 根据交通工具类型加载相应的监测界面
loadTransportMonitor(transportType);
// 初始化视频监控模拟
initVideoMonitoring();
// 初始化异常行为检测
initAnomalyDetection();
// 初始化实时数据更新
initRealTimeData();
});
// 加载交通工具监测界面
function loadTransportMonitor(type) {
const monitorTitle = document.querySelector('.monitor-title');
const monitorDescription = document.querySelector('.monitor-description');
if (monitorTitle && monitorDescription) {
// 根据类型设置标题和描述
switch(type) {
case 'bus':
monitorTitle.textContent = '公交车异常行为监测';
monitorDescription.textContent = '实时监测公交车内司机和乘客行为,检测疲劳驾驶、分心驾驶、乘客异常行为等安全隐患。';
break;
case 'subway':
monitorTitle.textContent = '地铁异常行为监测';
monitorDescription.textContent = '实时监测地铁车厢内乘客行为,检测可疑物品、异常行为等安全隐患。';
break;
case 'highspeed':
monitorTitle.textContent = '高铁异常行为监测';
monitorDescription.textContent = '实时监测高铁车厢内乘客行为,保障旅客安全。';
break;
case 'train':
monitorTitle.textContent = '火车异常行为监测';
monitorDescription.textContent = '实时监测火车车厢内乘客行为,保障旅客安全。';
break;
default:
monitorTitle.textContent = '交通工具异常行为监测';
monitorDescription.textContent = '实时监测交通工具内司机和乘客行为,保障出行安全。';
}
}
// 加载相应的监控摄像头列表
loadCameraList(type);
}
// 加载监控摄像头列表
function loadCameraList(type) {
const cameraListContainer = document.querySelector('.camera-list');
if (cameraListContainer) {
// 清空现有列表
cameraListContainer.innerHTML = '';
// 根据类型生成不同数量的摄像头
let cameraCount = 0;
switch(type) {
case 'bus':
cameraCount = 6;
break;
case 'subway':
cameraCount = 8;
break;
case 'highspeed':
cameraCount = 10;
break;
case 'train':
cameraCount = 12;
break;
default:
cameraCount = 6;
}
// 生成摄像头列表
for (let i = 1; i <= cameraCount; i++) {
const cameraItem = document.createElement('div');
cameraItem.className = 'camera-item';
cameraItem.setAttribute('data-id', i);
let cameraName = '';
if (type === 'bus') {
cameraName = i <= 2 ? `${i}号公交车司机摄像头` : `${i-2}号公交车乘客区域摄像头`;
} else if (type === 'subway') {
cameraName = `${i}号地铁车厢摄像头`;
} else if (type === 'highspeed') {
cameraName = `${i}号高铁车厢摄像头`;
} else if (type === 'train') {
cameraName = `${i}号火车车厢摄像头`;
} else {
cameraName = `${i}号摄像头`;
}
cameraItem.innerHTML = `
<div class="camera-info">
<span class="camera-name">${cameraName}</span>
<span class="camera-status ${Math.random() > 0.2 ? 'online' : 'offline'}">
${Math.random() > 0.2 ? '在线' : '离线'}
</span>
</div>
<div class="camera-actions">
<button class="btn-view">查看</button>
<button class="btn-history">历史</button>
</div>
`;
cameraListContainer.appendChild(cameraItem);
}
// 添加摄像头点击事件
addCameraEvents();
}
}
// 添加摄像头事件
function addCameraEvents() {
const cameraItems = document.querySelectorAll('.camera-item');
cameraItems.forEach(item => {
const viewBtn = item.querySelector('.btn-view');
const historyBtn = item.querySelector('.btn-history');
const cameraId = item.getAttribute('data-id');
if (viewBtn) {
viewBtn.addEventListener('click', function() {
// 显示实时监控视频
showLiveVideo(cameraId);
});
}
if (historyBtn) {
historyBtn.addEventListener('click', function() {
// 显示历史监控记录
showHistoryRecords(cameraId);
});
}
});
}
// 显示实时监控视频
function showLiveVideo(cameraId) {
const videoContainer = document.querySelector('.video-container');
const videoTitle = document.querySelector('.video-title');
if (videoContainer && videoTitle) {
// 更新视频标题
videoTitle.textContent = `摄像头 #${cameraId} 实时监控`;
// 清空现有视频
videoContainer.innerHTML = '';
// 创建视频元素(这里使用模拟视频)
const videoElement = document.createElement('div');
videoElement.className = 'video-simulation';
videoElement.innerHTML = `
<div class="video-overlay">
<div class="video-info">
<span class="camera-id">摄像头 #${cameraId}</span>
<span class="timestamp">${new Date().toLocaleString()}</span>
</div>
<div class="detection-box" style="display: none;"></div>
</div>
<div class="video-placeholder">视频加载中...</div>
`;
videoContainer.appendChild(videoElement);
// 模拟视频加载
setTimeout(() => {
const placeholder = videoElement.querySelector('.video-placeholder');
if (placeholder) {
placeholder.textContent = '实时视频监控中(模拟)';
// 随机触发异常行为检测
simulateAnomalyDetection(videoElement);
}
}, 1500);
}
}
// 显示历史监控记录
function showHistoryRecords(cameraId) {
const videoContainer = document.querySelector('.video-container');
const videoTitle = document.querySelector('.video-title');
if (videoContainer && videoTitle) {
// 更新视频标题
videoTitle.textContent = `摄像头 #${cameraId} 历史记录`;
// 清空现有视频
videoContainer.innerHTML = '';
// 创建历史记录列表
const historyList = document.createElement('div');
historyList.className = 'history-list';
// 生成一些模拟的历史记录
const today = new Date();
for (let i = 0; i < 5; i++) {
const recordDate = new Date(today);
recordDate.setHours(today.getHours() - i * 2);
const historyItem = document.createElement('div');
historyItem.className = 'history-item';
const hasAnomaly = Math.random() > 0.6;
historyItem.innerHTML = `
<div class="history-time">${recordDate.toLocaleString()}</div>
<div class="history-info">
<span class="history-status ${hasAnomaly ? 'anomaly' : 'normal'}">
${hasAnomaly ? '检测到异常' : '正常'}
</span>
${hasAnomaly ? '<span class="history-detail">点击查看详情</span>' : ''}
</div>
`;
if (hasAnomaly) {
historyItem.addEventListener('click', function() {
// 显示异常行为详情
showAnomalyDetails(cameraId, recordDate);
});
}
historyList.appendChild(historyItem);
}
videoContainer.appendChild(historyList);
}
}
// 显示异常行为详情
function showAnomalyDetails(cameraId, timestamp) {
const videoContainer = document.querySelector('.video-container');
const videoTitle = document.querySelector('.video-title');
if (videoContainer && videoTitle) {
// 更新视频标题
videoTitle.textContent = `异常行为详情 - 摄像头 #${cameraId} - ${timestamp.toLocaleString()}`;
// 清空现有内容
videoContainer.innerHTML = '';
// 创建异常详情
const anomalyDetails = document.createElement('div');
anomalyDetails.className = 'anomaly-details';
// 随机选择异常类型
const anomalyTypes = [
'司机疲劳驾驶',
'司机分心驾驶',
'乘客异常行为',
'车内可疑物品',
'车辆超载'
];
const anomalyType = anomalyTypes[Math.floor(Math.random() * anomalyTypes.length)];
// 生成详情内容
anomalyDetails.innerHTML = `
<div class="anomaly-video">
<div class="video-simulation">
<div class="video-overlay">
<div class="video-info">
<span class="camera-id">摄像头 #${cameraId}</span>
<span class="timestamp">${timestamp.toLocaleString()}</span>
</div>
<div class="detection-box" style="display: block; top: 40%; left: 30%; width: 40%; height: 30%;">
<span>${anomalyType}</span>
</div>
</div>
<div class="video-placeholder">异常行为视频回放(模拟)</div>
</div>
</div>
<div class="anomaly-info">
<h3>异常行为分析</h3>
<div class="info-item">
<span class="label">异常类型:</span>
<span class="value">${anomalyType}</span>
</div>
<div class="info-item">
<span class="label">检测时间:</span>
<span class="value">${timestamp.toLocaleString()}</span>
</div>
<div class="info-item">
<span class="label">置信度:</span>
<span class="value">${Math.floor(Math.random() * 20) + 80}%</span>
</div>
<div class="info-item">
<span class="label">处理状态:</span>
<span class="value status-pending">待处理</span>
</div>
<div class="actions">
<button class="btn-process">标记为已处理</button>
<button class="btn-export">导出报告</button>
</div>
</div>
`;
videoContainer.appendChild(anomalyDetails);
// 添加按钮事件
const processBtn = anomalyDetails.querySelector('.btn-process');
const exportBtn = anomalyDetails.querySelector('.btn-export');
if (processBtn) {
processBtn.addEventListener('click', function() {
const statusElement = anomalyDetails.querySelector('.status-pending');
if (statusElement) {
statusElement.textContent = '已处理';
statusElement.className = 'value status-processed';
}
this.disabled = true;
});
}
if (exportBtn) {
exportBtn.addEventListener('click', function() {
alert('报告已导出(模拟)');
});
}
}
}
// 模拟异常行为检测
function simulateAnomalyDetection(videoElement) {
if (!videoElement) return;
const detectionBox = videoElement.querySelector('.detection-box');
if (detectionBox) {
// 随机决定是否触发异常检测
setInterval(() => {
if (Math.random() > 0.7) {
// 显示检测框
detectionBox.style.display = 'block';
// 随机位置和大小
const top = Math.floor(Math.random() * 60) + 20;
const left = Math.floor(Math.random() * 60) + 20;
const width = Math.floor(Math.random() * 30) + 20;
const height = Math.floor(Math.random() * 30) + 20;
detectionBox.style.top = `${top}%`;
detectionBox.style.left = `${left}%`;
detectionBox.style.width = `${width}%`;
detectionBox.style.height = `${height}%`;
// 随机选择异常类型
const anomalyTypes = [
'司机疲劳驾驶',
'司机分心驾驶',
'乘客异常行为',
'可疑物品',
'异常行为'
];
const anomalyType = anomalyTypes[Math.floor(Math.random() * anomalyTypes.length)];
detectionBox.innerHTML = `<span>${anomalyType}</span>`;
// 触发告警
triggerAlarm(anomalyType);
// 3秒后隐藏
setTimeout(() => {
detectionBox.style.display = 'none';
}, 3000);
}
}, 10000); // 每10秒检测一次
}
}
// 触发告警
function triggerAlarm(anomalyType) {
const alertsContainer = document.querySelector('.alerts-container');
if (alertsContainer) {
// 创建新告警
const alertItem = document.createElement('div');
alertItem.className = 'alert-item new';
// 当前时间
const now = new Date();
const timeString = now.toLocaleTimeString();
// 告警内容
alertItem.innerHTML = `
<div class="alert-time">${timeString}</div>
<div class="alert-content">
<div class="alert-type">检测到${anomalyType}</div>
<div class="alert-actions">
<button class="btn-view-alert">查看</button>
<button class="btn-ignore">忽略</button>
</div>
</div>
`;
// 添加到告警容器
alertsContainer.prepend(alertItem);
// 添加告警事件
const viewBtn = alertItem.querySelector('.btn-view-alert');
const ignoreBtn = alertItem.querySelector('.btn-ignore');
if (viewBtn) {
viewBtn.addEventListener('click', function() {
// 查看告警详情
alert(`查看${anomalyType}告警详情(模拟)`);
alertItem.classList.remove('new');
});
}
if (ignoreBtn) {
ignoreBtn.addEventListener('click', function() {
// 忽略告警
alertItem.remove();
});
}
// 5秒后移除新告警样式
setTimeout(() => {
alertItem.classList.remove('new');
}, 5000);
// 限制告警数量,最多显示10条
const alertItems = alertsContainer.querySelectorAll('.alert-item');
if (alertItems.length > 10) {
alertItems[alertItems.length - 1].remove();
}
}
}
// 初始化异常行为检测
function initAnomalyDetection() {
console.log('异常行为检测系统已初始化');
}
// 初始化实时数据更新
function initRealTimeData() {
// 更新实时统计数据
updateStatistics();
// 定期更新数据
setInterval(updateStatistics, 5000);
}
// 更新统计数据
function updateStatistics() {
const statItems = document.querySelectorAll('.stat-item .value');
statItems.forEach(item => {
// 获取当前值
const currentValue = parseInt(item.textContent);
// 随机变化值
const variation = Math.floor(Math.random() * 5) - 2; // -2 到 2 的随机变化
const newValue = Math.max(0, currentValue + variation);
// 更新值
item.textContent = newValue;
// 如果值增加,添加增加动画
if (variation > 0) {
item.classList.add('increased');
setTimeout(() => {
item.classList.remove('increased');
}, 1000);
}
// 如果值减少,添加减少动画
if (variation < 0) {
item.classList.add('decreased');
setTimeout(() => {
item.classList.remove('decreased');
}, 1000);
}
});
}
// 初始化图表
function initCharts() {
// 这里可以使用图表库如Chart.js来创建图表
// 由于是模拟,这里只添加一个占位符
console.log('图表初始化(模拟)');
}
// 导出报告
function exportReport(data) {
// 模拟导出报告功能
console.log('导出报告', data);
return true;
}
// 处理异常事件
function processAnomaly(anomalyId, action) {
// 模拟处理异常事件
console.log(`处理异常事件 #${anomalyId},操作: ${action}`);
return true;
}
// 添加标记
function addMarker(type, position, description) {
// 模拟在地图上添加标记
console.log(`添加标记: 类型=${type}, 位置=${position}, 描述=${description}`);
return true;
}
// 初始化实时位置追踪
function initLocationTracking() {
// 模拟实时位置追踪
console.log('实时位置追踪已初始化');
// 模拟位置更新
setInterval(() => {
// 随机生成新位置
const newLat = 39.9 + (Math.random() - 0.5) * 0.1;
const newLng = 116.4 + (Math.random() - 0.5) * 0.1;
// 更新位置显示
updateVehicleLocation(newLat, newLng);
}, 3000);
}
// 更新车辆位置
function updateVehicleLocation(lat, lng) {
const locationElement = document.querySelector('.vehicle-location');
if (locationElement) {
locationElement.textContent = `位置: ${lat.toFixed(6)}, ${lng.toFixed(6)}`;
}
}
// 初始化设备状态监控
function initDeviceMonitoring() {
// 模拟设备状态监控
console.log('设备状态监控已初始化');
// 定期更新设备状态
setInterval(() => {
updateDeviceStatus();
}, 8000);
}
// 更新设备状态
function updateDeviceStatus() {
const deviceItems = document.querySelectorAll('.device-item');
deviceItems.forEach(item => {
// 随机决定设备状态
const statusTypes = ['正常', '警告', '错误', '离线'];
const statusWeights = [0.7, 0.15, 0.1, 0.05]; // 权重,使正常状态出现概率更高
// 根据权重随机选择状态
let random = Math.random();
let statusIndex = 0;
let cumulativeWeight = 0;
for (let i = 0; i < statusWeights.length; i++) {
cumulativeWeight += statusWeights[i];
if (random < cumulativeWeight) {
statusIndex = i;
break;
}
}
const status = statusTypes[statusIndex];
const statusElement = item.querySelector('.device-status');
if (statusElement) {
// 移除所有状态类
statusElement.classList.remove('status-normal', 'status-warning', 'status-error', 'status-offline');
// 添加新状态类
statusElement.textContent = status;
switch (status) {
case '正常':
statusElement.classList.add('status-normal');
break;
case '警告':
statusElement.classList.add('status-warning');
break;
case '错误':
statusElement.classList.add('status-error');
break;
case '离线':
statusElement.classList.add('status-offline');
break;
}
}
});
}
// 初始化事件日志
function initEventLog() {
// 模拟事件日志
console.log('事件日志已初始化');
// 定期添加新事件
setInterval(() => {
addEventLog();
}, 15000);
}
// 添加事件日志
function addEventLog() {
const logContainer = document.querySelector('.event-log');
if (logContainer) {
// 事件类型
const eventTypes = [
'系统启动',
'摄像头连接',
'摄像头断开',
'检测到异常',
'告警触发',
'告警处理',
'系统更新',
'用户登录',
'用户操作'
];
// 随机选择事件类型
const eventType = eventTypes[Math.floor(Math.random() * eventTypes.length)];
// 创建事件日志项
const logItem = document.createElement('div');
logItem.className = 'log-item';
// 当前时间
const now = new Date();
const timeString = now.toLocaleTimeString();
// 日志内容
logItem.innerHTML = `
<div class="log-time">${timeString}</div>
<div class="log-content">${eventType}</div>
`;
// 添加到日志容器
logContainer.prepend(logItem);
// 限制日志数量,最多显示50条
const logItems = logContainer.querySelectorAll('.log-item');
if (logItems.length > 50) {
logItems[logItems.length - 1].remove();
}
}
}
|
2301_77385112/zhi_yu_an_xing
|
js/transport-monitor.js
|
JavaScript
|
unknown
| 22,700
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>交通工具监测 - 智驭安行</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
/* 监测页面特定样式 */
.monitor-container {
display: grid;
grid-template-columns: 1fr 300px;
gap: 20px;
margin-bottom: 30px;
}
.video-section {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
padding: 20px;
}
.video-title {
font-size: 18px;
font-weight: 600;
margin-bottom: 15px;
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}
.video-container {
position: relative;
width: 100%;
height: 400px;
background-color: #f0f0f0;
border-radius: 8px;
overflow: hidden;
}
.video-simulation {
position: relative;
width: 100%;
height: 100%;
background-color: #222;
}
.video-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10;
}
.video-info {
position: absolute;
top: 10px;
left: 10px;
background-color: rgba(0, 0, 0, 0.5);
color: white;
padding: 5px 10px;
border-radius: 4px;
font-size: 12px;
display: flex;
gap: 10px;
}
.detection-box {
position: absolute;
border: 2px solid #ff0000;
background-color: rgba(255, 0, 0, 0.2);
display: none;
}
.detection-box span {
position: absolute;
top: -25px;
left: 0;
background-color: #ff0000;
color: white;
padding: 2px 8px;
font-size: 12px;
white-space: nowrap;
}
.video-placeholder {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 16px;
text-align: center;
}
.camera-controls {
display: flex;
justify-content: space-between;
margin-top: 15px;
}
.camera-selector {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.camera-btn {
background-color: #f0f0f0;
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px 10px;
cursor: pointer;
transition: all 0.2s;
}
.camera-btn:hover,
.camera-btn.active {
background-color: #0066cc;
color: white;
border-color: #0066cc;
}
.view-controls {
display: flex;
gap: 10px;
}
.view-btn {
background-color: #f0f0f0;
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px 10px;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
gap: 5px;
}
.view-btn:hover {
background-color: #e6f0ff;
}
.alerts-section {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
padding: 20px;
height: 100%;
display: flex;
flex-direction: column;
}
.alerts-title {
font-size: 18px;
font-weight: 600;
margin-bottom: 15px;
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}
.alerts-container {
flex: 1;
overflow-y: auto;
max-height: 400px;
}
.alert-item {
padding: 10px;
border-radius: 5px;
margin-bottom: 10px;
background-color: #f9f9f9;
border-left: 3px solid #ddd;
transition: all 0.3s;
}
.alert-item.new {
background-color: #fff8e6;
border-left-color: #ffcc00;
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(255, 204, 0, 0.4); }
70% { box-shadow: 0 0 0 10px rgba(255, 204, 0, 0); }
100% { box-shadow: 0 0 0 0 rgba(255, 204, 0, 0); }
}
.alert-time {
font-size: 12px;
color: #888;
margin-bottom: 5px;
}
.alert-content {
display: flex;
justify-content: space-between;
align-items: center;
}
.alert-type {
font-weight: 500;
}
.alert-actions {
display: flex;
gap: 5px;
}
.alert-actions button {
background-color: #f0f0f0;
border: 1px solid #ddd;
border-radius: 4px;
padding: 3px 8px;
font-size: 12px;
cursor: pointer;
transition: all 0.2s;
}
.btn-view-alert:hover {
background-color: #e6f0ff;
border-color: #0066cc;
color: #0066cc;
}
.btn-ignore:hover {
background-color: #ffe6e6;
border-color: #cc0000;
color: #cc0000;
}
.stats-section {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
padding: 20px;
margin-bottom: 30px;
}
.stats-title {
font-size: 18px;
font-weight: 600;
margin-bottom: 15px;
color: #333;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 15px;
}
.stat-item {
background-color: #f9f9f9;
border-radius: 8px;
padding: 15px;
text-align: center;
}
.stat-item .label {
font-size: 14px;
color: #666;
margin-bottom: 5px;
}
.stat-item .value {
font-size: 24px;
font-weight: 600;
color: #333;
transition: all 0.3s;
}
.stat-item .value.increased {
color: #00aa00;
animation: fadeIn 1s;
}
.stat-item .value.decreased {
color: #cc0000;
animation: fadeIn 1s;
}
@keyframes fadeIn {
from { opacity: 0.5; }
to { opacity: 1; }
}
.anomaly-details {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.anomaly-info {
background-color: #f9f9f9;
border-radius: 8px;
padding: 15px;
}
.anomaly-info h3 {
font-size: 16px;
margin-bottom: 15px;
padding-bottom: 5px;
border-bottom: 1px solid #eee;
}
.info-item {
display: flex;
margin-bottom: 10px;
}
.info-item .label {
width: 100px;
font-weight: 500;
}
.status-pending {
color: #ff9900;
}
.status-processed {
color: #00aa00;
}
.actions {
margin-top: 20px;
display: flex;
gap: 10px;
}
.actions button {
padding: 8px 15px;
border-radius: 4px;
border: none;
cursor: pointer;
transition: all 0.2s;
}
.btn-process {
background-color: #0066cc;
color: white;
}
.btn-process:hover {
background-color: #0055aa;
}
.btn-export {
background-color: #f0f0f0;
color: #333;
}
.btn-export:hover {
background-color: #e0e0e0;
}
</style>
</head>
<body>
<header>
<div class="container">
<div class="logo">
<img src="img/logo.png" alt="智驭安行">
<span>智驭安行</span>
</div>
<nav>
<ul>
<li><a href="index.html">首页</a></li>
<li><a href="#" class="active">出行服务</a></li>
<li><a href="#">车辆信息</a></li>
<li><a href="#">学习与技术支持</a></li>
<li><a href="#">客户服务</a></li>
<li><a href="#">数据</a></li>
</ul>
</nav>
</div>
</header>
<div class="hero">
<div class="container">
<h1>交通工具异常行为监测</h1>
<p>实时监测公共交通工具上司机和乘客的异常行为</p>
<div class="location">
<i class="fas fa-map-marker-alt"></i>
<span>北京市</span>
</div>
</div>
</div>
<div class="main-content">
<div class="container">
<div class="stats-section">
<h2 class="stats-title">监测统计</h2>
<div class="stats-grid">
<div class="stat-item">
<div class="label">今日监测车辆</div>
<div class="value">128</div>
</div>
<div class="stat-item">
<div class="label">今日异常行为</div>
<div class="value">23</div>
</div>
<div class="stat-item">
<div class="label">司机异常行为</div>
<div class="value">12</div>
</div>
<div class="stat-item">
<div class="label">乘客异常行为</div>
<div class="value">11</div>
</div>
</div>
</div>
<div class="monitor-container">
<div class="video-section">
<h2 class="video-title">实时监控</h2>
<div class="video-container">
<div class="video-simulation">
<div class="video-overlay">
<div class="video-info">
<span class="camera-id">摄像头 #1</span>
<span class="timestamp">2023-06-15 14:30:45</span>
</div>
<div class="detection-box">
<span>司机疲劳驾驶</span>
</div>
</div>
<div class="video-placeholder">实时视频监控中(模拟)</div>
</div>
</div>
<div class="camera-controls">
<div class="camera-selector">
<button class="camera-btn active" data-camera="1">摄像头 1</button>
<button class="camera-btn" data-camera="2">摄像头 2</button>
<button class="camera-btn" data-camera="3">摄像头 3</button>
<button class="camera-btn" data-camera="4">摄像头 4</button>
</div>
<div class="view-controls">
<button class="view-btn" data-view="live">
<i class="fas fa-video"></i>
实时
</button>
<button class="view-btn" data-view="history">
<i class="fas fa-history"></i>
历史
</button>
</div>
</div>
</div>
<div class="alerts-section">
<h2 class="alerts-title">实时告警</h2>
<div class="alerts-container">
<div class="alert-item new">
<div class="alert-time">14:25:30</div>
<div class="alert-content">
<div class="alert-type">检测到司机疲劳驾驶</div>
<div class="alert-actions">
<button class="btn-view-alert">查看</button>
<button class="btn-ignore">忽略</button>
</div>
</div>
</div>
<div class="alert-item">
<div class="alert-time">14:10:15</div>
<div class="alert-content">
<div class="alert-type">检测到乘客异常行为</div>
<div class="alert-actions">
<button class="btn-view-alert">查看</button>
<button class="btn-ignore">忽略</button>
</div>
</div>
</div>
<div class="alert-item">
<div class="alert-time">13:55:42</div>
<div class="alert-content">
<div class="alert-type">检测到车内可疑物品</div>
<div class="alert-actions">
<button class="btn-view-alert">查看</button>
<button class="btn-ignore">忽略</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="services-section">
<h2>异常行为分析</h2>
<div id="anomaly-analysis">
<!-- 异常行为分析内容将通过JavaScript动态加载 -->
<div class="chart-container">
<div class="chart-placeholder">加载异常行为分析图表...</div>
</div>
</div>
</div>
</div>
</div>
<footer>
<div class="container">
<div class="footer-content">
<div class="footer-logo">
<img src="img/logo.png" alt="智驭安行">
<span>智驭安行</span>
</div>
<div class="footer-links">
<div class="link-group">
<h3>关于我们</h3>
<ul>
<li><a href="#">公司简介</a></li>
<li><a href="#">联系方式</a></li>
<li><a href="#">加入我们</a></li>
</ul>
</div>
<div class="link-group">
<h3>服务支持</h3>
<ul>
<li><a href="#">帮助中心</a></li>
<li><a href="#">常见问题</a></li>
<li><a href="#">技术支持</a></li>
</ul>
</div>
<div class="link-group">
<h3>法律信息</h3>
<ul>
<li><a href="#">隐私政策</a></li>
<li><a href="#">使用条款</a></li>
<li><a href="#">版权声明</a></li>
</ul>
</div>
</div>
<div class="footer-contact">
<h3>联系我们</h3>
<p><i class="fas fa-phone"></i> 400-123-4567</p>
<p><i class="fas fa-envelope"></i> contact@zhiyuanxing.com</p>
<div class="social-links">
<a href="#"><i class="fab fa-weixin"></i></a>
<a href="#"><i class="fab fa-weibo"></i></a>
<a href="#"><i class="fab fa-qq"></i></a>
</div>
</div>
</div>
<div class="footer-bottom">
<p>© 2023 智驭安行 版权所有</p>
</div>
</div>
</footer>
<script src="js/main.js"></script>
<script src="js/transport-monitor.js"></script>
<script>
// 更新时间戳
function updateTimestamp() {
const timestampElement = document.querySelector('.timestamp');
if (timestampElement) {
const now = new Date();
timestampElement.textContent = now.toLocaleString();
}
setTimeout(updateTimestamp, 1000);
}
updateTimestamp();
// 摄像头切换
const cameraBtns = document.querySelectorAll('.camera-btn');
cameraBtns.forEach(btn => {
btn.addEventListener('click', function() {
const cameraId = this.getAttribute('data-camera');
// 更新按钮状态
cameraBtns.forEach(b => b.classList.remove('active'));
this.classList.add('active');
// 更新摄像头ID显示
const cameraIdElement = document.querySelector('.camera-id');
if (cameraIdElement) {
cameraIdElement.textContent = `摄像头 #${cameraId}`;
}
// 模拟加载新摄像头视频
const videoPlaceholder = document.querySelector('.video-placeholder');
if (videoPlaceholder) {
videoPlaceholder.textContent = '加载摄像头视频中...';
setTimeout(() => {
videoPlaceholder.textContent = `摄像头 #${cameraId} 实时视频监控中(模拟)`;
}, 500);
}
});
});
// 视图切换
const viewBtns = document.querySelectorAll('.view-btn');
viewBtns.forEach(btn => {
btn.addEventListener('click', function() {
const viewType = this.getAttribute('data-view');
const cameraId = document.querySelector('.camera-btn.active').getAttribute('data-camera');
// 更新按钮状态
viewBtns.forEach(b => b.classList.remove('active'));
this.classList.add('active');
// 根据视图类型更新显示
if (viewType === 'live') {
// 显示实时视图
const videoPlaceholder = document.querySelector('.video-placeholder');
if (videoPlaceholder) {
videoPlaceholder.textContent = `摄像头 #${cameraId} 实时视频监控中(模拟)`;
}
} else if (viewType === 'history') {
// 显示历史记录
const videoContainer = document.querySelector('.video-container');
if (videoContainer) {
videoContainer.innerHTML = `
<div class="anomaly-details">
<div class="anomaly-video">
<div class="video-simulation">
<div class="video-overlay">
<div class="video-info">
<span class="camera-id">摄像头 #${cameraId}</span>
<span class="timestamp">2023-06-15 13:45:22</span>
</div>
<div class="detection-box" style="display: block; top: 40%; left: 30%; width: 40%; height: 30%;">
<span>司机疲劳驾驶</span>
</div>
</div>
<div class="video-placeholder">异常行为视频回放(模拟)</div>
</div>
</div>
<div class="anomaly-info">
<h3>异常行为分析</h3>
<div class="info-item">
<span class="label">异常类型:</span>
<span class="value">司机疲劳驾驶</span>
</div>
<div class="info-item">
<span class="label">检测时间:</span>
<span class="value">2023-06-15 13:45:22</span>
</div>
<div class="info-item">
<span class="label">置信度:</span>
<span class="value">92%</span>
</div>
<div class="info-item">
<span class="label">处理状态:</span>
<span class="value status-pending">待处理</span>
</div>
<div class="actions">
<button class="btn-process">标记为已处理</button>
<button class="btn-export">导出报告</button>
</div>
</div>
</div>
`;
// 添加按钮事件
const processBtn = document.querySelector('.btn-process');
const exportBtn = document.querySelector('.btn-export');
if (processBtn) {
processBtn.addEventListener('click', function() {
const statusElement = document.querySelector('.status-pending');
if (statusElement) {
statusElement.textContent = '已处理';
statusElement.className = 'value status-processed';
}
this.disabled = true;
});
}
if (exportBtn) {
exportBtn.addEventListener('click', function() {
alert('报告已导出(模拟)');
});
}
}
}
});
});
// 告警按钮事件
const viewAlertBtns = document.querySelectorAll('.btn-view-alert');
const ignoreAlertBtns = document.querySelectorAll('.btn-ignore');
viewAlertBtns.forEach(btn => {
btn.addEventListener('click', function() {
const alertItem = this.closest('.alert-item');
const alertType = alertItem.querySelector('.alert-type').textContent;
// 切换到历史视图并显示相关告警
const historyBtn = document.querySelector('.view-btn[data-view="history"]');
if (historyBtn) {
historyBtn.click();
}
// 移除新告警样式
alertItem.classList.remove('new');
});
});
ignoreAlertBtns.forEach(btn => {
btn.addEventListener('click', function() {
const alertItem = this.closest('.alert-item');
alertItem.remove();
});
});
</script>
</body>
</html>
|
2301_77385112/zhi_yu_an_xing
|
transport-monitor.html
|
HTML
|
unknown
| 25,762
|
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# 第二章 数据类型,运算符,内置函数"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 填空题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"-10\n"
]
}
],
"source": [
"a=-68//7#//为整除,有向下取整特点\r\n",
"print(a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"|: {50, 70, 40, 60}\n",
"&: {40, 60}\n",
"-: {50}\n"
]
}
],
"source": [
"b = {40, 50, 60}\n",
"c = {40, 60, 70}\n",
"#并集\n",
"print(\"|:\",b|c)\n",
"#交集\n",
"print(\"&:\",b&c)\n",
"#差集=b并c-b交c\n",
"print(\"-:\",b-c)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
}
],
"source": [
"print(chr(ord('0')+3))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 判断题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n"
]
}
],
"source": [
"print(3>5 and math.sin(0))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n"
]
}
],
"source": [
"print(4<5==5)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 编程题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入包含若干自然数的列表:平均值为: 2.0\n"
]
}
],
"source": [
"data = eval(input('请输入包含若干自然数的列表:'))\n",
"avg = sum(data) / len(data)\n",
"avg = round(avg, 3)\n",
"print('平均值为:', avg)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入包含若干自然数的列表:降序排列后的列表: [3, 2, 1]\n"
]
}
],
"source": [
"data = eval(input('请输入包含若干自然数的列表:'))\n",
"print('降序排列后的列表:', sorted(data, reverse=True))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入包含若干自然数的列表:每个元素的位数: [1, 1, 1]\n"
]
}
],
"source": [
"data = eval(input('请输入包含若干自然数的列表:'))\n",
"data = map(str, data)\n",
"length = list(map(len, data))\n",
"print('每个元素的位数:', length)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入包含若干自然数的列表:绝对值最大的数字: 3\n"
]
}
],
"source": [
"data = eval(input('请输入包含若干自然数的列表:'))\n",
"print('绝对值最大的数字:', max(data, key=abs))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入包含若干自然数的列表:乘积: 6\n"
]
}
],
"source": [
"from operator import mul\n",
"from functools import reduce\n",
"\n",
"data = eval(input('请输入包含若干自然数的列表:'))\n",
"print('乘积:', reduce(mul, data))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入第一个向量:"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入第二个向量:内积: 11\n"
]
}
],
"source": [
"from operator import mul\n",
"from functools import reduce\n",
"\n",
"vec1 = eval(input('请输入第一个向量:'))\n",
"vec2 = eval(input('请输入第二个向量:'))\n",
"print('内积:', sum(map(mul, vec1, vec2)))"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 第三章练习"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# 第三章 列表、元组、字典、集合与字符串"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 列表"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[]\n",
"[1, 2, 3, 4, 5, 6]\n",
"[1.1, 1.2, 1.3, 1.4, 1.5, 1.6]\n",
"['apple', 'banana', 'cherry']\n",
"[True, False, True]\n",
"[[1, 2], [3, 4]]\n",
"[1, 'apple', 3.14, True]\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n",
"[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n",
"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n",
"[1, 2, 3, 4, 5, 6]\n",
"['hello', 'world']\n",
"[(1, 2), (3, 4), (4, 5)]\n",
"[{'name': 'Lao'}, {'name': 'WZT'}]\n",
"[1, 2]\n",
"[1, 2, 3, 4, 5]\n",
"[1, 2, 3, 4]\n",
"[1, 2, 4, 5, 6]\n",
"[1, 2, 3, 4, 5]\n"
]
}
],
"source": [
"list_1 = []#空列表\n",
"print(list_1)\n",
"list_2 = [1,2,3,4,5,6]#包含整数的列表\n",
"print(list_2)\n",
"list_3 = [1.1,1.2,1.3,1.4,1.5,1.6]#包含浮点数的列表\n",
"print(list_3)\n",
"list_4 = [\"apple\",\"banana\",\"cherry\"]#包含字符串的列表\n",
"print(list_4)\n",
"list_5 = [True,False,True]#包含布尔值的列表\n",
"print(list_5)\n",
"list_6 = [[1,2],[3,4]]#嵌套列表\n",
"print(list_6)\n",
"list_7 = [1,\"apple\",3.14,True]\n",
"print(list_7)\n",
"list_8 = list(range(10))\n",
"print(list_8)\n",
"list_9 = [x*2 for x in range(10)]\n",
"print(list_9)\n",
"list_10 = list_9[:]#复制列表\n",
"print(list_10)\n",
"list_11 = [0]*10\n",
"print(list_11)\n",
"list_12 = list_1+list_2\n",
"print(list_12)\n",
"list_13 = \"hello world\".split()\n",
"print(list_13)\n",
"list_14 = [(1,2),(3,4),(4,5)]\n",
"print(list_14)\n",
"list_15 = [{\"name\":\"Lao\"},{\"name\":\"WZT\"}]\n",
"print(list_15)\n",
"#利用append()\n",
"list_16 = []\n",
"list_16.append(1)\n",
"list_16.append(2)\n",
"print(list_16)\n",
"#利用extend方法扩张列表扩张列表\n",
"list_17 = [1,2]\n",
"list_17.extend([3,4,5])\n",
"print(list_17)\n",
"#利用insert方法输入元素\n",
"list_18 = [1,3,4]\n",
"list_18.insert(1,2)\n",
"print(list_18)\n",
"\n",
"#利用remove方法上删除元素\n",
"list_19 = [1,2,3,4,5,6]\n",
"list_19.remove(3)\n",
"print(list_19)\n",
"\n",
"#利用pop方法烫除元素弹出元素\n",
"list_20 = [1,2,3,4,5,6]\n",
"list_20.pop()\n",
"print(list_20)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 元组"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"()\n",
"(1, 2, 3, 4, 5, 6)\n",
"(1.1, 1.2, 1.3, 1.5)\n",
"('apple', 'banana', 'cherry')\n",
"(True, False, True)\n",
"((1, 2), (3, 4))\n",
"(1, 'apple', 3.14, True)\n",
"(1,)\n",
"(1, 2, 3, 4)\n",
"([1, 2], [2, 3], [4, 5])\n",
"({'name': 'Lao'}, {'name': 'WZT'})\n",
"({1, 2}, {3, 4})\n",
"(1, 2, 3)\n",
"('h', 'e', 'l', 'l', 'o')\n",
"(<function func at 0x7f500a21c940>, 'hello')\n",
"((1, 2), (3, 4))\n",
"(None, 1, None, 2, 3, 'apple')\n",
"(1, 2, 3, 2, 3, 4)\n",
"(1, 1, 1, 1, 1)\n",
"(2, 3, 4)\n"
]
}
],
"source": [
"tuple_1 = ()\n",
"print(tuple_1)\n",
"tuple_2 = (1,2,3,4,5,6)\n",
"print(tuple_2)\n",
"tuple_3 = (1.1,1.2,1.3,1.5)\n",
"print(tuple_3)\n",
"\n",
"tuple_4 = (\"apple\",\"banana\",\"cherry\")\n",
"print(tuple_4)\n",
"\n",
"tuple_5 = (True,False,True)\n",
"print(tuple_5)\n",
"\n",
"tuple_6 = ((1,2),(3,4))\n",
"print(tuple_6)\n",
"\n",
"tuple_7 = (1,\"apple\",3.14,True)\n",
"print(tuple_7)\n",
"\n",
"tuple_8 = (1,)\n",
"print(tuple_8)\n",
"\n",
"tuple_9 = tuple([1,2,3,4])\n",
"print(tuple_9)\n",
"\n",
"tuple_10 = ([1,2],[2,3],[4,5])\n",
"print(tuple_10)\n",
"\n",
"tuple_11 = ({\"name\":\"Lao\"},{\"name\":\"WZT\"})\n",
"print(tuple_11)\n",
"\n",
"tuple_12 = ({1,2},{3,4})\n",
"print(tuple_12)\n",
"\n",
"a,b,c = 1,2,3\n",
"tuple_13 = (a,b,c)\n",
"print(tuple_13)\n",
"\n",
"tuple_14 = tuple(\"hello\")\n",
"print(tuple_14)\n",
"\n",
"def func():\n",
" return \"hello\"\n",
"tuple_15 = (func,func())\n",
"print(tuple_15)\n",
"\n",
"tuple_16 = ((1,2),(3,4))\n",
"print(tuple_16)\n",
"\n",
"tuple_17 = (None,1,None,2,3,\"apple\")\n",
"print(tuple_17)\n",
"\n",
"tuple_18 = (1,2,3) + (2,3,4)\n",
"print(tuple_18)\n",
"\n",
"tuple_19 = (1,)*5\n",
"print(tuple_19)\n",
"\n",
"tuple_20 = (1,2,3,4,5,6,7,8)[1:4]\n",
"print(tuple_20)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 字典"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{}\n",
"{1: 'one', 2: 'two', 3: 'three'}\n",
"{'name': 'Alice', 'age': 25, 'city': 'New York'}\n",
"{1: 'one', 'name': 'Alice', 3.14: 'pi'}\n",
"{'person': {'name': 'Alice', 'age': 25}, 'city': 'New York'}\n",
"{'fruits': ['apple', 'banana', 'cherry'], 'numbers': [1, 2, 3]}\n",
"{'coordinates': (10, 20), 'dimensions': (200, 400)}\n",
"{'name': 'Alice', 'age': 25, 'city': 'New York'}\n",
"{'name': 'Alice', 'age': 25, 'city': 'New York'}\n",
"{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n",
"{'name': 'Alice', 'age': 25, 'city': 'New York'}\n",
"{'is_student': True, 'is_employed': False}\n",
"{'name': None, 'age': 25, 'city': 'New York'}\n",
"{'name': 'Alice', 'age': 25, 'city': 'New York'}\n",
"{'even_numbers': {8, 2, 4, 6}, 'odd_numbers': {1, 3, 5, 7}}\n",
"{'name': 'Alice', 'age': 26}\n",
"{'name': 'Alice'}\n",
"{'name': 'Alice'}\n",
"{'name': 'Alice', 'age': 25}\n",
"{'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}\n"
]
}
],
"source": [
"dict_1 = {}\n",
"print(dict_1)\n",
"\n",
"dict_2 = {1: \"one\", 2: \"two\", 3: \"three\"}\n",
"print(dict_2)\n",
"\n",
"\n",
"dict_3 = {\"name\": \"Alice\", \"age\": 25, \"city\": \"New York\"}\n",
"print(dict_3)\n",
"\n",
"\n",
"dict_4 = {1: \"one\", \"name\": \"Alice\", 3.14: \"pi\"}\n",
"print(dict_4)\n",
"\n",
"dict_5 = {\"person\": {\"name\": \"Alice\", \"age\": 25}, \"city\": \"New York\"}\n",
"print(dict_5)\n",
"\n",
"dict_6 = {\"fruits\": [\"apple\", \"banana\", \"cherry\"], \"numbers\": [1, 2, 3]}\n",
"print(dict_6)\n",
"\n",
"dict_7 = {\"coordinates\": (10, 20), \"dimensions\": (200, 400)}\n",
"print(dict_7)\n",
"\n",
"dict_8 = dict(name=\"Alice\", age=25, city=\"New York\")\n",
"print(dict_8)\n",
"\n",
"dict_9 = dict([(\"name\", \"Alice\"), (\"age\", 25), (\"city\", \"New York\")])\n",
"print(dict_9)\n",
"\n",
"dict_10 = {x: x**2 for x in range(5)}\n",
"print(dict_10)\n",
"\n",
"keys = [\"name\", \"age\", \"city\"]\n",
"values = [\"Alice\", 25, \"New York\"]\n",
"dict_11 = dict(zip(keys, values))\n",
"print(dict_11)\n",
"\n",
"dict_12 = {\"is_student\": True, \"is_employed\": False}\n",
"print(dict_12)\n",
"\n",
"dict_13 = {\"name\": None, \"age\": 25, \"city\": \"New York\"}\n",
"print(dict_13)\n",
"\n",
"\n",
"keys = [\"name\", \"age\", \"city\"]\n",
"values = [\"Alice\", 25, \"New York\"]\n",
"dict_14 = {k: v for k, v in zip(keys, values)}\n",
"print(dict_14)\n",
"\n",
"dict_15 = {\"even_numbers\": {2, 4, 6, 8}, \"odd_numbers\": {1, 3, 5, 7}}\n",
"print(dict_15)\n",
"\n",
"\n",
"dict_16 = {\"name\": \"Alice\", \"age\": 25}\n",
"dict_16[\"age\"] = 26\n",
"print(dict_16)\n",
"\n",
"\n",
"dict_17 = {\"name\": \"Alice\", \"age\": 25}\n",
"del dict_17[\"age\"]\n",
"print(dict_17)\n",
"\n",
"dict_18 = {\"name\": \"Alice\", \"age\": 25}\n",
"age = dict_18.pop(\"age\")\n",
"print(dict_18)\n",
"\n",
"\n",
"dict_19 = {\"name\": \"Alice\"}\n",
"dict_19.setdefault(\"age\", 25)\n",
"print(dict_19)\n",
"\n",
"\n",
"dict20 = {\"name\": \"Alice\", \"age\": 25}\n",
"dict21 = {\"city\": \"New York\", \"country\": \"USA\"}\n",
"merged_dict = {**dict20, **dict21}\n",
"print(merged_dict)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 集合"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"set()\n",
"{1, 2, 3, 4, 5}\n",
"{1.1, 2.2, 3.3, 4.4, 5.5}\n",
"{'apple', 'banana', 'cherry'}\n",
"{False, True}\n",
"{'apple', 3.14, 1}\n",
"{1, 2, 3, 4, 5}\n",
"{1, 2, 3, 4, 5}\n",
"{'o', 'l', 'h', 'e'}\n",
"{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}\n",
"{1, 2, 3, 4}\n",
"{1, 2, 4}\n",
"{1, 2, 3, 4}\n",
"1\n",
"set()\n",
"{1, 2, 3, 4, 5}\n",
"{3}\n",
"{1, 2}\n",
"{1, 2, 4, 5}\n",
"True\n"
]
}
],
"source": [
"empty_set = set()\n",
"print(empty_set)\n",
"\n",
"int_set = {1, 2, 3, 4, 5}\n",
"print(int_set)\n",
"\n",
"float_set = {1.1, 2.2, 3.3, 4.4, 5.5}\n",
"print(float_set)\n",
"\n",
"str_set = {\"apple\", \"banana\", \"cherry\"}\n",
"print(str_set)\n",
"\n",
"bool_set = {True, False}\n",
"print(bool_set)\n",
"\n",
"mixed_set = {1, \"apple\", 3.14, True}\n",
"print(mixed_set)\n",
"\n",
"list_to_set = set([1, 2, 3, 4, 5])\n",
"print(list_to_set)\n",
"\n",
"tuple_to_set = set((1, 2, 3, 4, 5))\n",
"print(tuple_to_set)\n",
"\n",
"\n",
"string_to_set = set(\"hello\")\n",
"print(string_to_set)\n",
"\n",
"comprehension_set = {x * 2 for x in range(10)}\n",
"print(comprehension_set)\n",
"\n",
"add_element_set = {1, 2, 3}\n",
"add_element_set.add(4)\n",
"print(add_element_set)\n",
"\n",
"remove_element_set = {1, 2, 3, 4}\n",
"remove_element_set.remove(3)\n",
"print(remove_element_set)\n",
"\n",
"discard_element_set = {1, 2, 3, 4}\n",
"discard_element_set.discard(5)\n",
"print(discard_element_set)\n",
"\n",
"\n",
"pop_element_set = {1, 2, 3, 4, 5}\n",
"popped_element = pop_element_set.pop()\n",
"print(popped_element)\n",
"\n",
"clear_set = {1, 2, 3}\n",
"clear_set.clear()\n",
"print(clear_set)\n",
"\n",
"set_a = {1, 2, 3}\n",
"set_b = {3, 4, 5}\n",
"union_set = set_a | set_b\n",
"print(union_set)\n",
"\n",
"\n",
"set_a = {1, 2, 3}\n",
"set_b = {3, 4, 5}\n",
"intersection_set = set_a & set_b\n",
"print(intersection_set)\n",
"\n",
"set_a = {1, 2, 3}\n",
"set_b = {3, 4, 5}\n",
"difference_set = set_a - set_b\n",
"print(difference_set)\n",
"\n",
"\n",
"set_a = {1, 2, 3}\n",
"set_b = {3, 4, 5}\n",
"symmetric_difference_set = set_a ^ set_b\n",
"print(symmetric_difference_set)\n",
"\n",
"subset_a = {1, 2}\n",
"superset_b = {1, 2, 3, 4}\n",
"is_subset = subset_a.issubset(superset_b)\n",
"print(is_subset)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 字符串"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"hello, world\n",
"This is a\n",
"multi-line string\n",
"He said, \"Hello!\"\n",
"It's a sunny day\n",
"第一步 line\n",
"Second line\n",
"C:\\Users\\Name\n",
"Hello, Alice\n",
"Hello, Charlie\n",
"hahaha\n",
"Hello, world\n",
"今天天气不\n",
"7\n",
"Hello, Python\n",
"['apple', 'banana', 'cherry']\n",
"apple,banana,cherry\n",
"HELLO\n",
"hello\n",
"hello\n"
]
}
],
"source": [
"empty_str = \"\"\n",
"print(empty_str)\n",
"\n",
"simple_str = \"hello, world\"\n",
"print(simple_str)\n",
"\n",
"multi_line_str = \"\"\"This is a\n",
"multi-line string\"\"\"\n",
"print(multi_line_str)\n",
"\n",
"quote_str = 'He said, \"Hello!\"'\n",
"print(quote_str)\n",
"\n",
"single_quote_str = \"It's a sunny day\"\n",
"print(single_quote_str)\n",
"\n",
"escaped_str = \"第一步 line\\nSecond line\"\n",
"print(escaped_str)\n",
"\n",
"raw_str = r\"C:\\Users\\Name\"\n",
"print(raw_str)\n",
"\n",
"formatted_str = \"Hello, %s\" % \"Alice\"\n",
"print(formatted_str)\n",
"\n",
"name = \"Charlie\"\n",
"f_str = f\"Hello, {name}\"\n",
"print(f_str)\n",
"\n",
"repeated_str = \"ha\" * 3\n",
"print(repeated_str)\n",
"\n",
"concatenated_str = \"Hello, \" + \"world\"\n",
"print(concatenated_str)\n",
"\n",
"sliced_str = \"今天天气不错\"[0:5]\n",
"print(sliced_str)\n",
"\n",
"find_str = \"Hello, world\".find(\"world\")\n",
"print(find_str)\n",
"\n",
"replace_str = \"Hello, world\".replace(\"world\", \"Python\")\n",
"print(replace_str)\n",
"\n",
"split_str = \"apple,banana,cherry\".split(\",\")\n",
"print(split_str)\n",
"\n",
"joined_str = \",\".join([\"apple\", \"banana\", \"cherry\"])\n",
"print(joined_str)\n",
"\n",
"upper_str = \"hello\".upper()\n",
"print(upper_str)\n",
"\n",
"lower_str = \"HELLO\".lower()\n",
"print(lower_str)\n",
"\n",
"strip_str = \" hello \".strip()\n",
"print(strip_str)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 课后习题"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"### 填空题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"df1 = [1,2,3,4]\n",
"print(df1.sort())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[3, 4]\n"
]
}
],
"source": [
"#列表索引index从0开始\n",
"data = [1,2,3,4]\n",
"print(data[2:100])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
}
],
"source": [
"x=3\n",
"y=4\n",
"x,y=y,x\n",
"print(y)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"97\n"
]
}
],
"source": [
"data = {'a':97,'A':65}\n",
"print(data.get('a',None))"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"### 编程题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入一个字符串:Counter({'a': 2, 's': 1, 'v': 1, 'u': 1, 'c': 1, 'b': 1, 'w': 1, 'e': 1})\n"
]
}
],
"source": [
"from collections import Counter\n",
"\n",
"text = input('请输入一个字符串:')\n",
"frequencies = Counter(text)\n",
"print(frequencies)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入一个字符串:[('v', 0), ('u', 1), ('w', 2), ('g', 3), ('d', 4), ('f', 5), ('q', 6)]\n"
]
}
],
"source": [
"text = input('请输入一个字符串:')\n",
"positions = [(ch, index) for index, ch in enumerate(text)\n",
" if text.index(ch)==text.rindex(ch)]\n",
"print(positions)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入一个字符串:[('d', 0), ('w', 1), ('e', 2), ('f', 3), ('q', 4), ('b', 5), ('i', 6)]\n"
]
}
],
"source": [
"text = input('请输入一个字符串:')\n",
"positions = [(ch, index) for index, ch in enumerate(text)\n",
" if index==text.rindex(ch)]\n",
"print(positions)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入包含若干集合的列表:{1, 123}\n"
]
}
],
"source": [
"from operator import __or__\n",
"from functools import reduce\n",
"\n",
"sets = eval(input('请输入包含若干集合的列表:'))\n",
"union = reduce(__or__, sets, set())\n",
"print(union)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入一个字符串:\u0013\u0002\u0006\f",
"\u0012\n"
]
}
],
"source": [
"text = input('请输入一个字符串:')\n",
"result = [chr(abs(ord(ch)-ord(text[index+1])))\n",
" for index, ch in enumerate(text[:-1])]\n",
"result.append(chr(abs(ord(text[-1])-ord(text[0]))))\n",
"print(''.join(result))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入一个字符串:No\n"
]
}
],
"source": [
"text = input('请输入一个字符串:')\n",
"if text==text[::-1]:\n",
" print('Yes')\n",
"else:\n",
" print('No')"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"### 操作题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0:97\n",
"1:98\n",
"2:105\n",
"3:106\n",
"4:98\n",
"5:110\n",
"6:97\n",
"7:90\n",
"8:109\n",
"9:90\n"
]
}
],
"source": [
"from string import digits\n",
"from random import choice\n",
"from collections import Counter\n",
"\n",
"z = ''.join(choice(digits) for i in range(1000))\n",
"result = Counter(z)\n",
"for digit, fre in sorted(result.items()):\n",
" print(digit, fre, sep=':')"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# 第4章 程序控制结构、函数定义与使用"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 课堂练习"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入月利润(元): 应发放奖金总数为: 1.1 元\n"
]
}
],
"source": [
"'''\n",
"question 1\n",
"企业发放的奖金根据利淘提成。利淘(I)低于或等于10万元吋,奖金可提10%;\n",
"利润高于10万元,低于或等于20万元吋, 10万的部分按10%提成,高于10万元的部分,可提成7.5%; \n",
"20万到40万元(含) 之同肘,高于20万元的部分,可提成5%; \n",
"40万元到60万元(含)之间时高于40万元的部分,可提成3%; \n",
"60万元到100万元()之同吋,高于60万元的部分,可提成1.5%, \n",
"高于100万元肘,超辻100万元的部分按l%提成,\n",
"当键盘输入月利洞(I),求应发放奖金总数?\n",
"'''\n",
"def calculate_bonus(profit):\n",
" if profit <= 100000:\n",
" bonus = profit * 0.10\n",
" elif profit <= 200000:\n",
" bonus = 100000 * 0.10 + (profit - 100000) * 0.075\n",
" elif profit <= 400000:\n",
" bonus = 100000 * 0.10 + 100000 * 0.075 + (profit - 200000) * 0.05\n",
" elif profit <= 600000:\n",
" bonus = 100000 * 0.10 + 100000 * 0.075 + 200000 * 0.05 + (profit - 400000) * 0.03\n",
" elif profit <= 1000000:\n",
" bonus = 100000 * 0.10 + 100000 * 0.075 + 200000 * 0.05 + 200000 * 0.03 + (profit - 600000) * 0.015\n",
" else:\n",
" bonus = 100000 * 0.10 + 100000 * 0.075 + 200000 * 0.05 + 200000 * 0.03 + 400000 * 0.015 + (profit - 1000000) * 0.01\n",
" return bonus\n",
"\n",
"# 输入利润1\n",
"profit = float(input(\"请输入月利润(元): \"))\n",
"bonus = calculate_bonus(profit)\n",
"print(f\"应发放奖金总数为: {bonus} 元\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入系数 a: "
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入系数 b: "
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入系数 c: 方程有一个实根: -1.0\n"
]
}
],
"source": [
"'''\n",
"question 2\n",
"求解一元额次方程组:a*x^2 + b*x + c=0,\n",
"其中a,b,c分别为系数从键盘输入,使用分支嵌套\n",
"'''\n",
"def solve_quadratic(a, b, c):\n",
" discriminant = b**2 - 4*a*c\n",
" if discriminant > 0:\n",
" root1 = (-b + math.sqrt(discriminant)) / (2*a)\n",
" root2 = (-b - math.sqrt(discriminant)) / (2*a)\n",
" return root1, root2\n",
" elif discriminant == 0:\n",
" root = -b / (2*a)\n",
" return root,\n",
" else:\n",
" return None\n",
"\n",
"# 输入系数\n",
"a = float(input(\"请输入系数 a: \"))\n",
"b = float(input(\"请输入系数 b: \"))\n",
"c = float(input(\"请输入系数 c: \"))\n",
"\n",
"roots = solve_quadratic(a, b, c)\n",
"if roots:\n",
" if len(roots) == 2:\n",
" print(f\"方程有两个实根: {roots[0]} 和 {roots[1]}\")\n",
" else:\n",
" print(f\"方程有一个实根: {roots[0]}\")\n",
"else:\n",
" print(\"方程无实根\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入 x: 函数值为: 3528105/351217 (约分后: 3528105/351217)\n"
]
}
],
"source": [
"\n",
"'''\n",
"question 3\n",
"编写计算分段函数的程序\n",
"第一段x>5时, y = sin(x)+sqrt(x^2+1)\n",
"第二段0<x<=5时, y = e^x + log_{5}(x)+x^(1/5)\n",
"第三段x<=0时, y = cos(x)-x^3+3x\n",
"'''\n",
"import math\n",
"from fractions import Fraction\n",
"def piecewise_function(x):\n",
" if x > 5:\n",
" y = math.sin(x) + math.sqrt(x**2 + 1)\n",
" elif 0 < x <= 5:\n",
" y = math.exp(x) + math.log(x, 5) + x**(1/5)\n",
" else:\n",
" y = math.cos(x) - x**3 + 3*x\n",
" return y\n",
"\n",
"# 输入 x\n",
"x = float(input(\"请输入 x: \"))\n",
"result = piecewise_function(x)\n",
"\n",
"# Convert result to fraction if possible\n",
"try:\n",
" result_fraction = Fraction(result).limit_denominator()\n",
" print(f\"函数值为: {result_fraction} (约分后: {result_fraction.numerator}/{result_fraction.denominator})\")\n",
"except:\n",
" print(f\"函数值为: {result}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 填空题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"print(3 and 5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n"
]
}
],
"source": [
"df2 = not{}\n",
"print(df2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"28.274333882308138\n"
]
}
],
"source": [
"from math import pi as PI\n",
"\n",
"def CircleArea(r):\n",
" if isinstance(r, (int,float)) and r>0:\n",
" return PI*r*r\n",
" else:\n",
" print('半径必须为大于0的整数或实数')\n",
"\n",
"a = CircleArea(3)\n",
"print(a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.0\n"
]
}
],
"source": [
"def mean(*para):\n",
" return sum(para)/len(para)\n",
"\n",
"b =mean(1,2,3)\n",
"print(b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [],
"source": [
"def rate(origin, userInput): \n",
" right = sum(map(lambda oc, uc: oc==uc, origin, userInput))\n",
" return right"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 编程题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 2, 7, 11]\n"
]
}
],
"source": [
"\n",
"def factoring(n):\n",
" '''对大数进行因数分解'''\n",
" if not isinstance(n, int):\n",
" print('You must give me an integer')\n",
" return\n",
" # 小于n的所有素数\n",
" primes = [p for p in range(2, n) if 0 not in\n",
" [p% d for d in range(2, int(p**0.5)+1)]]\n",
" # 开始分解,把所有因数都添加到result列表中\n",
" result = []\n",
" for p in primes:\n",
" while n!=1:\n",
" if n%p == 0:\n",
" n = n//p\n",
" result.append(p)\n",
" else:\n",
" break\n",
" else:\n",
" return result\n",
" # 考虑参数本身就是素数的情况\n",
" if not result:\n",
" return [n]\n",
"\n",
"print(factoring(308))\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"615\n"
]
}
],
"source": [
"\n",
"def compute(n, a):\n",
" return sum(map(lambda i: int(str(a)*i), range(1, n+1)))\n",
"\n",
"print(compute(3, 5))\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n"
]
}
],
"source": [
"from itertools import cycle\n",
"\n",
"def demo(lst, k):\n",
" #切片,以免影响原来的数据\n",
" t_lst = lst[:]\n",
" \n",
" #游戏一直进行到只剩下最后一个人\n",
" while len(t_lst) > 1:\n",
" #创建cycle对象\n",
" c = cycle(t_lst)\n",
" #从1到k报数\n",
" for i in range(k):\n",
" t = next(c)\n",
" #一个人出局,圈子缩小\n",
" index = t_lst.index(t)\n",
" t_lst = t_lst[index+1:] + t_lst[:index]\n",
" \n",
" #游戏结束\n",
" return t_lst[0]\n",
"\n",
"lst = list(range(1,11))\n",
"print(demo(lst, 3))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n"
]
}
],
"source": [
"def isPalindrome(text):\n",
" '''循环,首尾检查'''\n",
" length = len(text)\n",
" for i in range(length//2+1):\n",
" if text[i] != text[-1-i]:\n",
" return False\n",
" return True\n",
"\n",
"print(isPalindrome('deed'))\n",
"print(isPalindrome('need'))"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"1. ## 操作题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a\n",
"b\n",
"c\n",
"d\n",
"a\n",
"b\n",
"c\n",
"d\n",
"a\n",
"b\n",
"c\n",
"d\n",
"a\n",
"b\n",
"c\n",
"d\n",
"a\n",
"b\n",
"c\n",
"d\n"
]
}
],
"source": [
"def myCycle(iterable):\n",
" while True:\n",
" for item in iterable:\n",
" yield item\n",
"\n",
"c = myCycle('abcd')\n",
"for i in range(20):\n",
" print(next(c))"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# 第五章 文件操作"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 超市营业额1.xlsx数据分析"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'张三': 8260, '李四': 8240, '王五': 5020, '赵六': 6800, '周七': 4810, '钱八': 4260}\n",
"{'9:00~14:00': 17250, '14:00~21:00': 20140}\n",
"{'化妆品': 13140, '食品': 10310, '日用品': 6460, '蔬菜水果': 7480}\n"
]
}
],
"source": [
"# 超市营业额1.xlsx数据分析\n",
"from openpyxl import load_workbook\n",
"\n",
"# 3个字典分别存储按员工、按时段、按柜台的销售总额\n",
"persons = dict()\n",
"periods = dict()\n",
"goods = dict()\n",
"ws = load_workbook('超市营业额1.xlsx').worksheets[0]\n",
"for index, row in enumerate(ws.rows):\n",
" # 跳过第一行的表头\n",
" if index==0:\n",
" continue\n",
" # 获取每行的相关信息\n",
" _, name, _, time, num, good = map(lambda cell: cell.value, row)\n",
" # 根据每行的值更新三个字典\n",
" persons[name] = persons.get(name, 0)+num\n",
" periods[time] = periods.get(time, 0)+num\n",
" goods[good] = goods.get(good, 0)+num\n",
"\n",
"print(persons)\n",
"print(periods)\n",
"print(goods)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 每个人的爱好.xlsx数据分析"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [],
"source": [
"from openpyxl import load_workbook\n",
"\n",
"wb = load_workbook('每个人的爱好.xlsx')\n",
"ws = wb.worksheets[0]\n",
"for index, row in enumerate(ws.rows):\n",
" if index == 0:\n",
" titles = tuple(map(lambda cell: cell.value, row))[1:]\n",
" lastCol = len(titles)+2\n",
" ws.cell(row=index+1, column=lastCol, value='所有爱好')\n",
" else:\n",
" values = tuple(map(lambda cell: cell.value, row))[1:]\n",
" result = ','.join((titles[i] for i, v in enumerate(values)\n",
" if v=='是'))\n",
" ws.cell(row=index+1, column=lastCol, value=result)\n",
"\n",
"wb.save('每个人的爱好汇总.xlsx')"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# 第六章 NumPy数组运算与矩阵运算"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 填空题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"第2题: 7\n",
"第3题: 12\n",
"第4题: 12.0\n",
"第5题: 0\n",
"第6题: False\n",
"第7题: (4, 4)\n",
"第8题: 16\n",
"第9题: (3,)\n",
"第10题: (3, 4)\n",
"第11题: 30\n",
"第12题: 25\n",
"第13题: 32\n",
"第14题: 1\n",
"第15题: 55\n",
"第16题: 72\n",
"第17题: 3\n",
"第18题: 15.0\n",
"第19题: 15\n",
"第20题: 6\n",
"第21题: 2\n",
"第22题: [[2.5 3.5 4.5]]\n",
"第23题: [[55]]\n"
]
}
],
"source": [
"# 第六章课后习题,填空题\n",
"# pip install numpy\n",
"import numpy as np\n",
"x2 = np.arange(8)\n",
"# 第2题:输出x2最后一个元素\n",
"print(\"第2题:\", x2[-1])\n",
"\n",
"x3 = np.zeros((3, 4))\n",
"# 第3题:输出x3的元素个数\n",
"print(\"第3题:\", x3.size)\n",
"\n",
"x4 = np.ones((3, 4)).sum()\n",
"# 第4题:输出x4的和\n",
"print(\"第4题:\", x4)\n",
"\n",
"x5 = len(np.random.rand(0, 50, 5))\n",
"# 第5题:输出x5的长度\n",
"print(\"第5题:\", x5)\n",
"\n",
"x6 = all(np.random.rand(20000) > 1)\n",
"# 第6题:判断是否所有随机数都大于1\n",
"print(\"第6题:\", x6)\n",
"\n",
"x7 = np.diag((1, 2, 3, 4)).shape\n",
"# 第7题:输出对角矩阵的形状\n",
"print(\"第7题:\", x7)\n",
"\n",
"x8 = np.diag((1, 2, 3, 4)).size\n",
"# 第8题:输出对角矩阵的元素个数\n",
"print(\"第8题:\", x8)\n",
"\n",
"x9 = np.random.randn(3).shape\n",
"# 第9题:输出随机数组的形状\n",
"print(\"第9题:\", x9)\n",
"\n",
"x10 = np.random.rand(3, 4).shape\n",
"# 第10题:输出随机二维数组的形状\n",
"print(\"第10题:\", x10)\n",
"\n",
"x11 = np.array((1, 2, 3, 4, 5))\n",
"# 第11题:输出x11乘以2的和\n",
"print(\"第11题:\", (x11 * 2).sum())\n",
"\n",
"# 第12题:输出x11平方的最大值\n",
"print(\"第12题:\", (x11 ** 2).max())\n",
"# 第13题:输出2的x11次方的最大值\n",
"print(\"第13题:\", (2 ** x11).max())\n",
"# 第14题:输出x11整除5的和\n",
"print(\"第14题:\", (x11 // 5).sum())\n",
"# 第15题:输出x11平方的和\n",
"print(\"第15题:\", sum(x11 * x11))\n",
"\n",
"x16 = np.array([1, 2, 3])\n",
"y16 = np.array([[3],[4], [5]])\n",
"# 第16题:输出x16和y16的点积\n",
"print(\"第16题:\", (x16 * y16).sum())\n",
"\n",
"x17 = np.array([3, 5, 1, 9, 6, 3])\n",
"# 第17题:输出x17中最大值的索引\n",
"print(\"第17题:\", np.argmax(x17))\n",
"\n",
"x18 = np.random.randint(0, 100, (3, 5))\n",
"# 第18题:输出x18的正弦值绝对值取整后的和\n",
"print(\"第18题:\", np.ceil(abs(np.sin(x18))).sum())\n",
"\n",
"x19 = np.array([3, 5, 1, 9, 6, 3])\n",
"# 第19题:输出x19中大于5的元素的和\n",
"print(\"第19题:\", x19[x19 > 5].sum())\n",
"# 第20题:输出x19中大于5且为偶数的第一个元素\n",
"print(\"第20题:\", x19[(x19 % 2 == 0) & (x19 > 5)][0])\n",
"# 第21题:输出x19中大于5的元素个数\n",
"print(\"第21题:\", np.where(x19 > 5, 1, 0).sum())\n",
"\n",
"x22 = np.matrix([[1, 2, 3], [4, 5, 6]])\n",
"# 第22题:输出x22按列的均值\n",
"print(\"第22题:\", x22.mean(axis=0))\n",
"\n",
"x23 = np.matrix([1, 2, 3, 4, 5])\n",
"# 第23题:输出x23与其转置的乘积\n",
"print(\"第23题:\", x23 * x23.T)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"第24题(np.partition): [9 6 5]\n",
"第24题(自编写函数): [9, 6, 5]\n"
]
}
],
"source": [
"\n",
"'''\n",
"24 题:找出一个一维数组中n个最大数据,使用np.partition函数和自编写函数两种方法\n",
"\n",
"25 题:找出一个二维数组中唯一的行,使用np.unique函数和自编写函数两种方法\n",
"\n",
"'''\n",
"# 第24题:找出一个一维数组中n个最大数据\n",
"# 使用np.partition函数\n",
"def top_n_with_partition(arr, n):\n",
" partitioned = np.partition(arr, -n)\n",
" return np.sort(partitioned[-n:])[::-1]\n",
"\n",
"# 自编写函数\n",
"def top_n_custom(arr, n):\n",
" return sorted(arr, reverse=True)[:n]\n",
"\n",
"# 示例数组和n值\n",
"arr24 = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])\n",
"n24 = 3\n",
"\n",
"# 输出结果\n",
"print(\"第24题(np.partition):\", top_n_with_partition(arr24, n24))\n",
"print(\"第24题(自编写函数):\", top_n_custom(arr24, n24))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"第25题(np.unique): [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n",
"第25题(自编写函数): [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n"
]
}
],
"source": [
"# 第25题:找出一个二维数组中唯一的行\n",
"# 使用np.unique函数\n",
"def unique_rows_with_np(arr):\n",
" return np.unique(arr, axis=0)\n",
"\n",
"# 自编写函数\n",
"def unique_rows_custom(arr):\n",
" unique_rows = []\n",
" for row in arr:\n",
" if not any(np.array_equal(row, unique_row) for unique_row in unique_rows):\n",
" unique_rows.append(row)\n",
" return np.array(unique_rows)\n",
"\n",
"# 示例二维数组\n",
"arr25 = np.array([[1, 2, 3], [4, 5, 6], [1, 2, 3], [7, 8, 9]])\n",
"\n",
"# 输出结果\n",
"print(\"第25题(np.unique):\", unique_rows_with_np(arr25))\n",
"print(\"第25题(自编写函数):\", unique_rows_custom(arr25))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"15.0\n"
]
}
],
"source": [
"df3 = np.empty((3,5)).sum()\n",
"print(df3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# 第7章 Pandas数据分析实战"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"## 操作题"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 日期 交易额 weekday\n",
"24 2023-03-25 8498.0 Saturday\n",
"20 2023-03-21 8661.0 Tuesday\n",
"9 2023-03-10 8789.0 Friday\n"
]
}
],
"source": [
"import pandas as pd\n",
"\n",
"df = pd.read_excel('超市营业额2.xlsx')\n",
"df = df.loc[:, ['日期', '交易额']].groupby('日期',\n",
" as_index=False).sum()\n",
"df = df.nsmallest(3, '交易额')\n",
"df['weekday'] = pd.to_datetime(df['日期']).dt.day_name()\n",
"print(df)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [],
"source": [
"import pandas as pd\n",
"\n",
"df = pd.read_excel('超市营业额2.xlsx')\n",
"df['工号'] = df['工号'].map(lambda s: str(s)[-1]+str(s))\n",
"df.to_excel('超市营业额2_修改工号.xlsx', index=False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [],
"source": [
"import pandas as pd\n",
"\n",
"df = pd.read_excel('超市营业额2.xlsx')\n",
"with pd.ExcelWriter('各员工数据.xlsx') as writer:\n",
" names = set(df['姓名'].values)\n",
" for name in names:\n",
" dff = df[df.姓名 == name]\n",
" dff.to_excel(writer, sheet_name=name, index=False)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAkoAAAGvCAYAAACkQvo1AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAA9hAAAPYQGoP6dpAADAWklEQVR4nOzdd3hTZRvH8W/SpHszWgoFyt6gggwB2RtEEWXIUIYDVESGOBBxoKDIVIYg6AsCLkRQ9pS9R9l7lJZC98w67x+nCYQOOtJS4P5cVy/a5OTkpEDz6/Pcz/1oFEVREEIIIYQQ6Wjv9wUIIYQQQhRWEpSEEEIIITIhQUkIIYQQIhMSlIQQQgghMiFBSQghhBAiExKUhBBCCCEyIUFJCCGEECITuvt9AfeTxWIhLCwMLy8vNBrN/b4cIYQQQmSDoijEx8cTFBSEVpu/Yz6PdFAKCwsjODj4fl+GEEIIIXLhypUrlCpVKl+f45EOSl5eXoD6jfb29r7PVyOEEEKI7IiLiyM4ONj2Pp6fHumgZJ1u8/b2lqAkhBBCPGAKomxGirmFEEIIITIhQUkIIYQQIhMSlIQQQgghMvFI1ygJIYR4tJnNZoxG4/2+DHEXvV6Pk5PT/b4MQIKSEEKIR5CiKISHhxMTE3O/L0VkwtfXl8DAwPve51CCkhBCiEeONSQVL14cd3f3+/5mLG5TFIWkpCRu3LgBQIkSJe7r9UhQEkII8Ugxm822kFSkSJH7fTkiA25ubgDcuHGD4sWL39dpOCnmFkII8Uix1iS5u7vf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k6mUaNGAERGRjJ8+HCsra3R6XQEBwfj4uLC1atXqVWrVpH2XQhRMsmMkhCixLAkULq7jYODA7t27WLXrl306dMnW7vp06eza9cu3n333ULvqxDi0SAzSkKIEkOn03HhwgVKly6d6+M3btxg6NCh2e5LTk6mXr16gJajNHLkSAAMBoNp1kmvl78ZhRC5k0BJCFFi6HQ6/Pz88kzmvpuDgwNhYWEAjBgxwnR/WloaS5cu5eDBg+zbt68ouiuEeARIoCSEKDGUUha3SUtLIyMjI8fjBoOBlJQUkpKSWL58uSmPqXXr1oXeXyFEySeBkhCixChIoPTNN98wb948KleubLr0ppQiJSUFd3d3YmJiOH/+PH5+fsydO5dly5YVZdeFECWUXJgXQpQYRqMx3zYGgwGAsWPHsnXrVoKCgti4cSMbNmygWbNmHD58mCpVquDl5UX58uWLustCiBJOZpSEECWGwWDIN5l74MCBpn+PHDkSBwcHPD09UUoRExPDkCFDuHjxIs8995xFq+iEEI83CZSEECWGwWDIN5k7Ky9p+fLlREREsHnzZkBLBP/555+ZOHEiISEhzJkzB4B9+/Yxd+5c/Pz8HsRbEEKUMDplyUV/IYQogVJTU7Gzs8t238mTJzl8+LCpptLFixf58ssvefPNNyVYEkLkIIGSEEIIIYQZkswthBBCCGGGBEpCCCGEEGZIoCSEEEIIYYYESkIIIYQQZkigJIQQQghhhgRKQgghhBBmSKAkhBBCCGGGBEpCCCGEEGb8P2We6fSgdFFSAAAAAElFTkSuQmCC",
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib.font_manager as fm\n",
"\n",
"df = pd.read_excel('超市营业额2.xlsx',\n",
" usecols=['日期', '柜台', '交易额'])\n",
"df = df.groupby(by=['日期','柜台'], as_index=False).sum()\n",
"df = df.pivot(index='日期', columns='柜台', values='交易额')\n",
"df.plot()\n",
"myfont = fm.FontProperties(fname=r'SimHei.ttf') \n",
"plt.xlabel('日期', fontproperties=myfont)\n",
"plt.legend(prop=myfont)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAZ0AAAGFCAYAAAAmWi5UAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAA9hAAAPYQGoP6dpAABZCklEQVR4nO3dd3xT9f7H8VdWm6TpXlCgZRRBKDJEcIAKFUSWKJfrFX5exgUccO914cJ99TrvFVFQHCgO3FfgilcRRJwgyN6jtEBLoXskbeb5/VEJlNXSpjlJ+nk+Hn1gktOTT2qbd853ahRFURBCCCH8QKt2AUIIIZoPCR0hhBB+I6EjhBDCbyR0hBBC+I2EjhBCCL+R0BFCCOE3EjpCCCH8RkJHCCGE30joCCGE8BsJHSGEEH4joSOEEMJvJHSEEEL4jYSOEEIIv5HQEUII4Td6tQsQQohjPB4PDodD7TLESQwGAzqdzifnktARQgQEh8PB/v378Xg8apciTiMmJoYWLVqg0WgadR4JHSGE6hRF4fDhw+h0Otq0aYNWKy3/gUJRFGw2G0ePHgWgZcuWjTqfhI4QQnUulwubzUZKSgpms1ntcsRJTCYTAEePHiUpKalRTW3ycUIIoTq32w1AWFiYypWIMzn2YcDpdDbqPBI6QoiA0dj+AtF0fPX/RkJHCCF8wOPxeK/YGsrlclFZWemjigKT9OkIIQJW2/uW+vX5sp8e1uDv/eqrr5gxYwbr1q3DZDJx44030q1bNx544IEzfs8TTzxBQUEBL774IgCbN28mMzOT/Px8wsPDT/s9VqsVi8VCdHT0KY/ZbDZeffVVJk2a1ODX0dTkSkcIIXzgpZde4tprr/V2uoeHh9fqo8rOzsblcpGVlcWHH34IgNForHXMtm3bGDBgwBkDByAiIgKtVktpaekpX2PHjsVoNDbR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s3jTB9/T/rdlvQrQmrO9WW8VvO6fjVq1czadIkTKaalSLy8vIwGo289tprVFVVkZeXR48ePYCaVQIcDgf33nsvf/3rX71zXSoqKli2bBmPPPIIAKWlpVxzzTXeK53q6mpyc3PPONnTYrHU66ooLCyMuXPncuWVVwLQokULvv76a9q2beu97Y85UhI6omnkb4VVz8CO/yKDAxqvWO+fOTpNpbDSzqP/3c4bP+7n9qvO4/qerdBqg+fK7UwuvfRSNm/eTHh4zQoOb7/9Nh06dKB///7k5ubyxBNPMH78eC6++OJa3zdx4kTvf0+bNo3MzEyuv/56AG688UamTJlCSkoKMTExtGjRAji+vtvJC3nq9XpKSkq8t1etWsXq1au59957ax2n1WqZOHEiERE1zbRFRUVcffXVGAwG7+36bLvdWBI6wrcK98KKR2HHF0jY+M5hTaLaJfjEoZIq7v5kE/NW7eOuwZ0YktFC7ZIapaioiAkTJmA0GnG73SxevJjZs2czduxYoqKiOHr0KP/5z39o2bIllZWVZGZmMm/ePD7++GPmzp2Lx+PBbrfzww8/8PDDDwM14TJjxgxMJhO9evVi9uzZAHz55ZeMGDGiVjCsXr0agG+++YaRI0eyZcsWbrjhBm677TYURam1EKjH4+Gtt94665WOPxaokdARvmErhu+ehnXzweNUu5qQEwhzdHxpz9FKbnnvN7q3ieGeqztxYWtL3d8UgBISEvjiiy8AuO+++5g8eTLTp09n+vTpvPXWW8yfP5+VK1cyf/58JkyY4N2wbfjw4fz2229kZGQwYsQI70ZsX3/9NYmJiVRUVNCvXz/+8pe/eJ9r0KBBlJSUEBUVxf79++nevTsXXHABUHOF1a1bNx577DFeffVVRo0adUqt9VkJ+9j6cE1JQkc0jssBv86D75+Dahkc0FR22wNnjo4vbTpYyrg31jC8SzxTegb3MOvly5fzwQcfALBp0yaeeuopli1bRnFxMS+99BLvv/8+n3/+OXFxcZjNZgYPHsy4ceO48soradOmDWlpaXz//feMHj2am2++mW7dutG9e3fv+cPDw73NeIsWLWLQoEHeEBs9ejS33347q1atOuPq0u3atWP69One2y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CCH8RkJHCCGE30joCCGE8Jv/B/bqk6x8K1X0AAAAAElFTkSuQmCC",
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib import font_manager\n",
"import matplotlib.font_manager as fm\n",
"import os\n",
"\n",
"# 设置图形中使用中文字体\n",
"myfont = fm.FontProperties(fname=r'SimHei.ttf') \n",
"df = pd.read_excel('超市营业额2.xlsx',\n",
" usecols=['柜台','交易额'])\n",
"df = df.groupby(by='柜台', as_index=False).sum()\n",
"df.plot(x='柜台', y='交易额', kind='pie',autopct='%1.1f%%', labels=df.柜台.values,textprops={'fontproperties': myfont})\n",
"\n",
"explode = (0.05, 0, 0, 0, 0) # 突出显示第一块 (搜索引擎)\n",
"plt.ylabel('交易额',fontproperties=myfont)\n",
"plt.legend(prop=myfont)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAZ0AAAGFCAYAAAAmWi5UAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAA9hAAAPYQGoP6dpAABeBUlEQVR4nO3dd3hUZdrH8e/MZJJJDwkpJEAIEIpSFUFQFIkiiCKK7CqsiygiK+7rWhCXoujq2hsKiiiKqFhQbFioAiIIKBBCLwmEhPTepp73jyyDIYGEZGbOlPtzXXPJtHN+AzH3nOfc53k0iqIoCCGEEC6gVTuAEEII3yFFRwghhMtI0RFCCOEyUnSEEEK4jBQdIYQQLiNFRwghhMtI0RFCCOEyUnSEEEK4jBQdIYQQLiNFRwghhMtI0RFCCOEyUnSEEEK4jBQdIYQQLiNFRwghhMv4qR1ACCFOsd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35ElswT4sIggPf+4shMTBnXAoK+/yubZTlL3XNzTlTHZPWH3eb1+06ZN3HnnnQQGBgKQnZ2NwWAgMjKS6upqsrOz6dSpE1A7S4DJZGL69On885//tH/O8vJy/P397UtTl5SUEBISYj/SqampISsr66wXe7Zt25alS5cyePDgc2a94IILmD9/PkOGDAEgLi6OLVu20KFDB/v9TZs22fOeSRoJhFvbd7KMeesO8/3uk8ilNaKkyswzP+xn0aZ0/i8lmb/2a9fijjd3MGjQIFJTU+0F4/3336dTp04MHjyYrKwsnnrqKSZMmMCll15a530TJ060/3nq1KmkpKRw8803A3Dbbbdx9913Ex8fT0REBHFxccDp+d3OnMjTz8+P4uJi+/3169ezZcsWpk+fXud1Wq2WiRMnEhwcDEBhYSHXXnster3efr8py263lBQd4VCHcst57scDrNmfixxDizPllhmZuTyNtzcc5cFrujCqd7xHTVZ5psLCQu644w4MBgNWq5Wvv/6auXPnMm7cOMLCwsjLy+PLL7+kTZs2VFRUkJKSwoIFC/jss8+YP38+NpsNo9HIxo0beeyxx4Da4jJt2jQCAwO56KKLmDt3LgDff/89N9xwQ53CsGXLFgBWrVrFqFGj2L17N3/961+599577UuFn2Kz2XjvvffqHOn89NNPdY50XDHw5flfNYRbKK0yM+ebPYx4bSOr90nBEed2rLCK+z/ZyYjXNrJmX67acZrt1BLRy5Yto2vXrkyaNIn77ruPzMxMHn74Ybp160ZWVhb33nsve/fuZcGCBUDt2jkDBgzg7rvv5qeffmLNmjX4+/uzbt069u7dy88//0x5eTl33XWXfV/XXHMNxcXFmEwmDhw4gMFgoFevXkDtEdbbb7/N8OHDeeutt3jsscfqFfOmzIR9an44Z5IjHdEiVpvCx1uP88qqgy5dVVN4h/055dy1eDvDukZyb79QteO0yOrVq1m6dCkAu3bt4plnnmHlypUUFRXx+uuv89FHH7F8+XIiIyMJCgpi2LBhjB8/niFDhtCuXTsSExPZsGEDY8aM4Z577qFnz5707t3bvv2AgAD7MN5XX33FNddcY191dMyYMfzrX/9i/fr1Z51dOik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te4blkuWohvNSgQYNITU21F4z333+fTp06MXjwYLKysnjqqaeYMGECl156aZ33TZw40f7nqVOnkpKSws033wzAbbfdxt133018fDwRERHExcUBtUULQKutO3ji5+dHcXGx/f769evZsmUL06dPr/M6rVbLxIkTCQ4OBqCwsJBrr70WvV5vv6/T6Vr8dyLUJ0VHCC9VWFjIHXfcgcFgwGq18vXXXzN37lzGjRtHWFgYeXl5fPnll7Rp04aKigpSUlJYsGABn332GfPnz8dms2E0Gtm4cSOPPfYYUFtcpk2bRmBgIBdddBFz584F4Pvvv+eGG26oUxi2bNkCwKpVqxg1ahS7d+/mr3/9K/feey+KotSZ3dpms/Hee+/VOdL56aef6hzpyKCMl1CEEF5v+vTpyt13322/v2jRIuXyyy9XzGazsmDBAsVoNNqfq6ysVB555BHlgw8+UIqLi5W8vDylb9++Sl5enqIoilJWVqb06tVL2blzp/09NTU1SnFxsWK1WpXDhw8rwcHBitFoVBITE5WQkBBlwYIFSnx8vLJ8+fIG83Xt2lVZt26d/X5sbKySnp5e5/7Bgwcd85chVCVHOkL4gNWrV7N06VIAdu3axTPPPMPKlSspKiri9ddf56OPPmL58uVERkYSFBTEsGHDGD9+PEOGDKFdu3YkJiayYcMGxowZwz333EPPnj3p3bu3ffsBAQH2YbyvvvqKa665Bn9/f6C2GeFf//oX69ev55JLLmkwX1JSEvfdd5/9/pnDa61bt5Z1f7yEFB0hvNiECRMYN24cfn5+XHfddbzwwgt8+umn9O7dm3nz5hEbG8tDDz3EkiVLmD17Nq+99hoAKSkpLFq0iOjoaABMJpO9AMycOZOEhAT746eKC4DZbGbevHn2YTeASZMmsXHjRnJzc+vlq6ysxGQysWLFijrng84cXgOwWCz19ic8jxQdIbxYZWWl/Zf0559/TufOnSkqKmLw4MG88sorPPzww3zwwQe89dZbBAcH89prrzFjxgyCg4PRarVYrVYqKirQaDSsXr0arVZrP9lvsViorKwkPz+fiIgIAObOnUtERAQjR460ZzAYDCxcuJCxY8eyfv16evToYX9u2bJlPPLIIxgMB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IYTLSNERQgjhMlJ0hBBCuIwUHSGEEC7z/1Wg17tIcWMbAAAAAElFTkSuQmCC",
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib.font_manager as fm\n",
"\n",
"# 设置图形中使用中文字体\n",
"\n",
"df = pd.read_excel('超市营业额2.xlsx',\n",
" usecols=['姓名','柜台','交易额'])\n",
"df = df[df.姓名=='张三']\n",
"df = df.groupby(by='柜台', as_index=False).sum()\n",
"df.plot(x='柜台', y='交易额', kind='pie', autopct='%1.1f%%',labels=df.柜台.values,textprops={'fontproperties': myfont})\n",
"plt.legend(prop=myfont)\n",
"plt.ylabel('交易额',fontproperties=myfont)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# AI使用"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [],
"source": [
"import os # 导入 os 模块\n",
"import re\n",
"from openai import OpenAI\n",
"import requests\n",
"import json\n",
"import time\n",
"from rich.console import Console"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [],
"source": [
"# 从环境变量中读取 API 密钥\n",
"api_key = os.getenv(\"OPENAI_API_KEY\")\n",
"base_url = \"https://api-nejdk8n346qb53b8.aistudio-app.com/v1\" # 您的 base_url\n",
"\n",
"if not api_key:\n",
" print(\"错误:OPENAI_API_KEY 环境变量未设置。\")\n",
" print(\"请设置 OPENAI_API_KEY 环境变量后重试。\")\n",
" exit()\n",
"\n",
"# 从命令行获取用户输入的问题\n",
"user_question = input(\"请输入您的问题: \")\n",
"\n",
"client = OpenAI(\n",
" api_key=api_key, # 使用从环境变量读取的密钥\n",
" base_url=base_url\n",
")\n",
"\n",
"print(\"\\nAI 正在思考,请稍候...\\n\")\n",
"\n",
"try:\n",
" completion = client.chat.completions.create(\n",
" model=\"deepseek-r1:70b\",\n",
" temperature=0.6,\n",
" messages=[\n",
" {\"role\": \"user\", \"content\": user_question} # 使用从命令行获取的问题\n",
" ],\n",
" stream=True\n",
" )\n",
" full_response = \"\"\n",
" for chunk in completion:\n",
" content = None\n",
" if hasattr(chunk.choices[0].delta, \"reasoning_content\") and chunk.choices[0].delta.reasoning_content:\n",
" content = chunk.choices[0].delta.reasoning_content\n",
" elif hasattr(chunk.choices[0].delta, \"content\") and chunk.choices[0].delta.content:\n",
" content = chunk.choices[0].delta.content\n",
"\n",
" if content:\n",
" print(content, end=\"\", flush=True) \n",
" full_response += content\n",
" print() # 在流式输出结束后换行\n",
"\n",
"except Exception as e:\n",
" print(f\"\\n发生错误: {e}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"scrolled": true
},
"outputs": [],
"source": [
" "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "py35-paddle1.2.0"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
|
2301_76574743/python-data-deep
|
python数据挖掘.ipynb
|
Jupyter Notebook
|
unknown
| 187,522
|
{
"cells": [
{
"cell_type": "markdown",
"id": "f45aeb52",
"metadata": {},
"source": [
"##### 第二章 -数据类型、运算符和内置函数\n",
"\n",
"##### 编程题:工资统计\n",
"###### 某公司有一份员工工资表,工资数据如下(单位:元):\n",
"salaries = [5500, 7200, 6600, 8000, 5200, 9100, 6100, 7000, 8300, 5900]\n",
"\n",
"###### 要求:\n",
"###### 1. 计算所有员工的平均工资(使用内置函数)。\n",
"###### 2. 找出工资高于平均工资的员工数量(使用运算符和内置函数)。\n",
"###### 3. 将所有工资按从高到低排序(使用内置函数)。\n",
"###### 4. 输出排序后的工资列表。\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "1bf916b5",
"metadata": {
"ExecuteTime": {
"end_time": "2025-05-30T02:19:21.508126Z",
"start_time": "2025-05-30T02:19:21.493095Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"平均工资: 6890.0 元\n",
"工资高于平均工资的员工数量: 5 人\n",
"排序后的工资列表: [9100, 8300, 8000, 7200, 7000, 6600, 6100, 5900, 5500, 5200]\n"
]
}
],
"source": [
"salaries = [5500, 7200, 6600, 8000, 5200, 9100, 6100, 7000, 8300, 5900]\n",
"\n",
"# 1. 计算所有员工的平均工资\n",
"average_salary = sum(salaries) / len(salaries)\n",
"print(\"平均工资:\", average_salary, \"元\")\n",
"\n",
"# 2. 找出工资高于平均工资的员工数量\n",
"above_average_count = len([salary for salary in salaries if salary > average_salary])\n",
"print(\"工资高于平均工资的员工数量:\", above_average_count, \"人\")\n",
"\n",
"# 3. 将所有工资按从高到低排序\n",
"salaries.sort(reverse=True)\n",
"\n",
"# 4. 输出排序后的工资列表\n",
"print(\"排序后的工资列表:\", salaries)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "8850f39c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"成绩在90分及以上的学生人数: 2\n",
"分数最低的学生姓名: 王五\n",
"所有学生姓名: 张三, 李四, 王五, 赵六, 钱七\n"
]
}
],
"source": [
"# 编程题:学生成绩处理\n",
"# 某班有一组学生姓名和对应的成绩如下:\n",
"students = [\"张三\", \"李四\", \"王五\", \"赵六\", \"钱七\"]\n",
"scores = [85, 92, 78, 90, 88]\n",
"\n",
"# 要求:\n",
"# 1. 统计成绩在90分及以上的学生人数(使用运算符和内置函数)。\n",
"# 2. 找出分数最低的学生姓名(结合数据类型和内置函数)。\n",
"# 3. 将所有学生姓名用英文逗号连接成一个字符串(使用字符串方法和内置函数)。\n",
"# 4. 输出上述结果。\n",
"\n",
"# 1. 统计成绩在90分及以上的学生人数\n",
"high_score_count = len([score for score in scores if score >= 90])\n",
"print(\"成绩在90分及以上的学生人数:\", high_score_count)\n",
"\n",
"# 2. 找出分数最低的学生姓名\n",
"min_score = min(scores)\n",
"min_index = scores.index(min_score)\n",
"min_student = students[min_index]\n",
"print(\"分数最低的学生姓名:\", min_student)\n",
"\n",
"# 3. 将所有学生姓名用英文逗号连接成一个字符串\n",
"students_str = \", \".join(students)\n",
"print(\"所有学生姓名:\", students_str)"
]
},
{
"cell_type": "markdown",
"id": "699bec6a",
"metadata": {},
"source": [
"##### 第三章 -列表、元组、字典、集合与字符串"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "35741c83",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"按类别分组的图书信息: {'计算机': ['Python编程', '数据结构'], '数学': ['高等数学', '线性代数'], '历史': ['世界历史', '中国通史']}\n",
"每个类别下的图书数量: {'计算机': 2, '数学': 2, '历史': 2}\n",
"所有作者姓名(去重后按字母顺序): ['孙健', '张伟', '李明', '王芳', '赵强', '钱丽']\n",
"所有馆藏编号: A001; A002; B001; B002; C001; C002\n"
]
}
],
"source": [
"# 编程题:图书信息管理\n",
"# 某图书馆有如下图书信息(书名、作者、类别、馆藏编号):\n",
"books = [\n",
" (\"Python编程\", \"张伟\", \"计算机\", \"A001\"),\n",
" (\"数据结构\", \"李明\", \"计算机\", \"A002\"),\n",
" (\"高等数学\", \"王芳\", \"数学\", \"B001\"),\n",
" (\"线性代数\", \"赵强\", \"数学\", \"B002\"),\n",
" (\"世界历史\", \"钱丽\", \"历史\", \"C001\"),\n",
" (\"中国通史\", \"孙健\", \"历史\", \"C002\")\n",
"]\n",
"\n",
"# 要求:\n",
"# 1. 将所有图书信息按类别分组,存储为字典,键为类别,值为该类别下所有书的书名列表。\n",
"# 2. 统计每个类别下的图书数量,结果以字典形式输出。\n",
"# 3. 提取所有作者姓名,去重后按字母顺序输出(使用集合和字符串方法)。\n",
"# 4. 输出所有馆藏编号组成的字符串,每个编号之间用英文分号分隔。\n",
"\n",
"# 请在下方编写代码实现上述功能。\n",
"\n",
"# 1. 将所有图书信息按类别分组,存储为字典\n",
"books_by_category = {}\n",
"for book in books:\n",
" title, author, category, id = book\n",
" if category not in books_by_category:\n",
" books_by_category[category] = []\n",
" books_by_category[category].append(title)\n",
"print(\"按类别分组的图书信息:\", books_by_category)\n",
"\n",
"# 2. 统计每个类别下的图书数量\n",
"category_counts = {category: len(titles) for category, titles in books_by_category.items()}\n",
"print(\"每个类别下的图书数量:\", category_counts)\n",
"\n",
"# 3. 提取所有作者姓名,去重后按字母顺序输出\n",
"authors = {book[1] for book in books}\n",
"sorted_authors = sorted(authors)\n",
"print(\"所有作者姓名(去重后按字母顺序):\", sorted_authors)\n",
"\n",
"# 4. 输出所有馆藏编号组成的字符串\n",
"ids = [book[3] for book in books]\n",
"ids_str = \"; \".join(ids)\n",
"print(\"所有馆藏编号:\", ids_str)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "8c802eb3",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"每个兴趣小组的报名人数: {'篮球': 2, '音乐': 3, '美术': 3, '足球': 3}\n",
"报名人数最多的兴趣小组: ['音乐', '美术', '足球']\n",
"所有报名学生姓名: 孙八, 张三, 李四, 王五, 赵六, 钱七\n",
"所有兴趣小组名称: ['篮球', '美术', '足球', '音乐']\n"
]
}
],
"source": [
"'''\n",
"#### 编程题:班级兴趣小组统计\n",
"\n",
"某班同学的兴趣小组报名信息如下,每个元组包含学生姓名和其报名的兴趣小组(可能有多个):\n",
"\n",
"students_groups = [\n",
" (\"张三\", [\"篮球\", \"音乐\"]),\n",
" (\"李四\", [\"美术\", \"音乐\", \"足球\"]),\n",
" (\"王五\", [\"足球\"]),\n",
" (\"赵六\", [\"篮球\", \"美术\"]),\n",
" (\"钱七\", [\"音乐\", \"足球\"]),\n",
" (\"孙八\", [\"美术\"])\n",
"]\n",
"\n",
"要求:\n",
"1. 统计每个兴趣小组的报名人数(用字典实现,键为兴趣小组,值为人数)。\n",
"2. 找出报名人数最多的兴趣小组名称(如有并列,全部输出)。\n",
"3. 输出所有报名过兴趣小组的学生姓名(去重后,按字母顺序,用英文逗号连接成字符串)。\n",
"4. 输出所有兴趣小组名称(去重后,按字母顺序组成列表)。\n",
"'''\n",
"# 1. 统计每个兴趣小组的报名人数\n",
"students_groups = [\n",
" (\"张三\", [\"篮球\", \"音乐\"]),\n",
" (\"李四\", [\"美术\", \"音乐\", \"足球\"]),\n",
" (\"王五\", [\"足球\"]),\n",
" (\"赵六\", [\"篮球\", \"美术\"]),\n",
" (\"钱七\", [\"音乐\", \"足球\"]),\n",
" (\"孙八\", [\"美术\"])\n",
"]\n",
"\n",
"group_counts = {}\n",
"for name, groups in students_groups:\n",
" for group in groups:\n",
" group_counts[group] = group_counts.get(group, 0) + 1\n",
"print(\"每个兴趣小组的报名人数:\", group_counts)\n",
"\n",
"# 2. 找出报名人数最多的兴趣小组名称\n",
"max_count = max(group_counts.values())\n",
"most_popular = [group for group, count in group_counts.items() if count == max_count]\n",
"print(\"报名人数最多的兴趣小组:\", most_popular)\n",
"\n",
"# 3. 输出所有报名过兴趣小组的学生姓名(去重后,按字母顺序,用英文逗号连接成字符串)\n",
"student_names = sorted({name for name, _ in students_groups})\n",
"students_str = \", \".join(student_names)\n",
"print(\"所有报名学生姓名:\", students_str)\n",
"\n",
"# 4. 输出所有兴趣小组名称(去重后,按字母顺序组成列表)\n",
"all_groups = sorted({group for _, groups in students_groups for group in groups})\n",
"print(\"所有兴趣小组名称:\", all_groups)"
]
},
{
"cell_type": "markdown",
"id": "1757bf39",
"metadata": {},
"source": [
"##### 第四章 -程序控制结构、函数定义与使用"
]
},
{
"cell_type": "markdown",
"id": "6499e358",
"metadata": {},
"source": [
"#### 编程题:快递费用计算器\n",
"\n",
"某快递公司按照以下规则收取快递费用:\n",
"\n",
"- 首重1公斤以内(含1公斤)收费8元;\n",
"- 超过1公斤的部分,每增加1公斤(不足1公斤按1公斤计)加收5元;\n",
"- 偏远地区(如输入的地区为“西藏”或“新疆”)总费用加收10元。\n",
"\n",
"请编写一个函数 `calculate_fee(weight, region)`,根据用户输入的包裹重量(单位:公斤,浮点数)和地区(字符串),返回应收快递费用。主程序循环接收用户输入,直到输入“exit”为止,输出每次计算的费用。"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "f8ee8233",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"快递费用:428元\n",
"快递费用:428元\n",
"程序结束。\n"
]
}
],
"source": [
"def calculate_fee(weight, region):\n",
" # 首重8元,超重每公斤5元,偏远地区加收10元\n",
" base_fee = 8\n",
" if weight <= 1:\n",
" fee = base_fee\n",
" else:\n",
" # 向上取整\n",
" import math\n",
" extra = math.ceil(weight - 1)\n",
" fee = base_fee + extra * 5\n",
" if region in [\"西藏\", \"新疆\"]:\n",
" fee += 10\n",
" return fee\n",
"\n",
"while True:\n",
" user_input = input(\"请输入包裹重量(公斤)和地区(用空格分隔,或输入exit退出):\")\n",
" if user_input.strip().lower() == \"exit\":\n",
" print(\"程序结束。\")\n",
" break\n",
" try:\n",
" weight_str, region = user_input.strip().split()\n",
" weight = float(weight_str)\n",
" fee = calculate_fee(weight, region)\n",
" print(f\"快递费用:{fee}元\")\n",
" except Exception as e:\n",
" print(\"输入格式有误,请重新输入。\")"
]
},
{
"cell_type": "markdown",
"id": "d340a549",
"metadata": {},
"source": [
"#### 编程题:判断素数并统计区间素数个数\n",
"\n",
"请编写如下功能:\n",
"1. 定义一个函数 `is_prime(n)`,判断参数 n 是否为素数,返回布尔值。\n",
"2. 定义一个函数 `count_primes(start, end)`,统计区间 [start, end] 内素数的个数。\n",
"3. 主程序循环接收用户输入的两个正整数(start, end),输出区间内素数的数量,输入\"exit\"退出。"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "8c17a100",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2到80之间共有22个素数。\n",
"程序结束。\n"
]
}
],
"source": [
"def is_prime(n):\n",
" if n < 2:\n",
" return False\n",
" for i in range(2, int(n ** 0.5) + 1):\n",
" if n % i == 0:\n",
" return False\n",
" return True\n",
"\n",
"def count_primes(start, end):\n",
" count = 0\n",
" for num in range(start, end + 1):\n",
" if is_prime(num):\n",
" count += 1\n",
" return count\n",
"\n",
"while True:\n",
" user_input = input(\"请输入两个正整数start和end(用空格分隔,或输入exit退出):\")\n",
" if user_input.strip().lower() == \"exit\":\n",
" print(\"程序结束。\")\n",
" break\n",
" try:\n",
" start_str, end_str = user_input.strip().split()\n",
" start, end = int(start_str), int(end_str)\n",
" if start > end or start < 1:\n",
" print(\"输入区间不合法,请重新输入。\")\n",
" continue\n",
" prime_count = count_primes(start, end)\n",
" print(f\"{start}到{end}之间共有{prime_count}个素数。\")\n",
" except Exception:\n",
" print(\"输入格式有误,请重新输入。\")"
]
},
{
"cell_type": "markdown",
"id": "6e81aac8",
"metadata": {},
"source": [
"##### 第五章 -文件操作"
]
},
{
"cell_type": "markdown",
"id": "d284efbd",
"metadata": {},
"source": [
"#### 编程题1:学生成绩文件读写\n",
"\n",
"请编写程序,完成以下功能:\n",
"\n",
"1. 用户输入若干学生姓名和成绩(格式如“张三 85”,输入“end”结束),将数据写入名为`students.txt`的文本文件,每行一个学生信息。\n",
"2. 读取`students.txt`文件,统计成绩大于等于90分的学生人数,并输出所有学生的平均成绩。"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "4e3d4ff6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"成绩大于等于90分的学生人数:1\n",
"所有学生的平均成绩:71.67\n"
]
}
],
"source": [
"# 1. 输入学生信息并写入文件\n",
"with open(\"../期末题目-by-student/students.txt\", \"w\", encoding=\"utf-8\") as f:\n",
" while True:\n",
" entry = input(\"请输入学生姓名和成绩(如“张三 85”,输入end结束):\")\n",
" if entry.strip().lower() == \"end\":\n",
" break\n",
" f.write(entry.strip() + \"\\n\")\n",
"\n",
"# 2. 读取文件并统计\n",
"scores = []\n",
"high_score_count = 0\n",
"with open(\"../期末题目-by-student/students.txt\", \"r\", encoding=\"utf-8\") as f:\n",
" for line in f:\n",
" parts = line.strip().split()\n",
" if len(parts) == 2:\n",
" name, score_str = parts\n",
" try:\n",
" score = float(score_str)\n",
" scores.append(score)\n",
" if score >= 90:\n",
" high_score_count += 1\n",
" except ValueError:\n",
" continue\n",
"if scores:\n",
" avg_score = sum(scores) / len(scores)\n",
" print(f\"成绩大于等于90分的学生人数:{high_score_count}\")\n",
" print(f\"所有学生的平均成绩:{avg_score:.2f}\")\n",
"else:\n",
" print(\"没有有效成绩数据。\")"
]
},
{
"cell_type": "markdown",
"id": "ef11b667",
"metadata": {},
"source": [
"#### 编程题2:文本文件字符/词语统计\n",
"\n",
"请编写程序,完成以下功能:\n",
"\n",
"1. 用户输入一段中英文混合文本,将其写入名为`text.txt`的文件。\n",
"2. 读取`text.txt`文件,统计并输出其中出现次数最多的“词语”及其出现次数(中文按单字统计,英文按单词统计,忽略大小写和标点)。"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "a93e3575",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"出现次数最多的是:'喜',出现了2次。\n"
]
}
],
"source": [
"import re\n",
"from collections import Counter\n",
"\n",
"# 1. 输入中英文混合文本并写入文件\n",
"text = input(\"请输入一段中英文混合文本:\\n\")\n",
"with open(\"../期末题目-by-student/text.txt\", \"w\", encoding=\"utf-8\") as f:\n",
" f.write(text)\n",
"\n",
"# 2. 读取文件并统计“词语”出现次数\n",
"with open(\"../期末题目-by-student/text.txt\", \"r\", encoding=\"utf-8\") as f:\n",
" content = f.read().lower()\n",
" # 英文单词\n",
" en_words = re.findall(r\"[a-zA-Z]+\", content)\n",
" # 中文单字\n",
" zh_chars = re.findall(r\"[\\u4e00-\\u9fff]\", content)\n",
" # 合并统计\n",
" tokens = en_words + zh_chars\n",
" counter = Counter(tokens)\n",
" if counter:\n",
" most_common, count = counter.most_common(1)[0]\n",
" print(f\"出现次数最多的是:'{most_common}',出现了{count}次。\")\n",
" else:\n",
" print(\"没有检测到词语或字符。\")"
]
},
{
"cell_type": "markdown",
"id": "ecda7878",
"metadata": {},
"source": [
"##### 第六章 -NumPy数组运算与矩阵运算"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "acf3553b",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "6f496b59",
"metadata": {},
"source": [
"#### 编程题1:城市温度数据分析\n",
"\n",
"某地气象站记录了一周内每天的最高气温(单位:℃),数据如下:\n",
"\n",
"`[23.5, 25.1, 22.8, 24.6, 26.0, 27.3, 25.8]`\n",
"\n",
"请完成以下任务:\n",
"\n",
"1. 使用NumPy计算该周的平均气温、最高气温和最低气温。\n",
"2. 计算每天与平均气温的差值,输出差值数组。\n",
"3. 判断哪几天的气温高于平均气温,并输出对应的天数(下标从0开始)。"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "cf33c83b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"平均气温:25.01℃,最高气温:27.3℃,最低气温:22.8℃\n",
"每天与平均气温的差值: [-1.51428571 0.08571429 -2.21428571 -0.41428571 0.98571429 2.28571429\n",
" 0.78571429]\n",
"高于平均气温的天数下标: [1 4 5 6]\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"temps = np.array([23.5, 25.1, 22.8, 24.6, 26.0, 27.3, 25.8])\n",
"\n",
"# 1. 平均、最高、最低气温\n",
"avg_temp = np.mean(temps)\n",
"max_temp = np.max(temps)\n",
"min_temp = np.min(temps)\n",
"print(f\"平均气温:{avg_temp:.2f}℃,最高气温:{max_temp}℃,最低气温:{min_temp}℃\")\n",
"\n",
"# 2. 每天与平均气温的差值\n",
"diffs = temps - avg_temp\n",
"print(\"每天与平均气温的差值:\", diffs)\n",
"\n",
"# 3. 高于平均气温的天数下标\n",
"above_avg_days = np.where(temps > avg_temp)[0]\n",
"print(\"高于平均气温的天数下标:\", above_avg_days)"
]
},
{
"cell_type": "markdown",
"id": "9ca2dbe7",
"metadata": {},
"source": [
"#### 编程题2:商品销量矩阵分析\n",
"\n",
"某超市统计了3种商品在4个季度的销量(单位:件),数据如下(行表示商品,列表示季度):\n",
"\n",
"```\n",
"[[120, 135, 150, 160],\n",
" [80, 95, 100, 110],\n",
" [200, 210, 220, 230]]\n",
"```\n",
"\n",
"请完成以下任务:\n",
"\n",
"1. 使用NumPy计算每种商品的年总销量。\n",
"2. 计算每个季度的总销量。\n",
"3. 计算所有商品全年总销量。\n",
"4. 计算每种商品各季度销量占全年销量的百分比(保留两位小数)。"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "a3951bc7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"每种商品年总销量: [565 385 860]\n",
"每个季度总销量: [400 440 470 500]\n",
"所有商品全年总销量: 1810\n",
"各商品各季度销量占全年百分比:\n",
" [[ 6.63 7.46 8.29 8.84]\n",
" [ 4.42 5.25 5.52 6.08]\n",
" [11.05 11.6 12.15 12.71]]\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"sales = np.array([\n",
" [120, 135, 150, 160],\n",
" [80, 95, 100, 110],\n",
" [200, 210, 220, 230]\n",
"])\n",
"\n",
"# 1. 每种商品年总销量\n",
"product_totals = np.sum(sales, axis=1)\n",
"print(\"每种商品年总销量:\", product_totals)\n",
"\n",
"# 2. 每个季度总销量\n",
"quarter_totals = np.sum(sales, axis=0)\n",
"print(\"每个季度总销量:\", quarter_totals)\n",
"\n",
"# 3. 所有商品全年总销量\n",
"total_sales = np.sum(sales)\n",
"print(\"所有商品全年总销量:\", total_sales)\n",
"\n",
"# 4. 每种商品各季度销量占全年销量百分比\n",
"percent = sales / total_sales * 100\n",
"percent_rounded = np.round(percent, 2)\n",
"print(\"各商品各季度销量占全年百分比:\\n\", percent_rounded)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.0"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
2301_76574743/python-data-deep
|
期末.ipynb
|
Jupyter Notebook
|
unknown
| 23,432
|
# -*- coding: utf-8 -*-
"""
波士顿房价预测 - 线性回归模型
结合数据探索、模型评估和可视化分析
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
from sklearn.metrics import explained_variance_score, median_absolute_error
from sklearn.preprocessing import StandardScaler
# 设置中文字体和图形样式
plt.rcParams['font.sans-serif'] = ['SimHei'] # 支持中文显示
plt.rcParams['axes.unicode_minus'] = False # 正确显示负号
column_names = [
'CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE',
'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV'
]
def load_boston_data():
"""
从本地CSV文件加载波士顿房价数据集
返回: 特征数据框和目标序列
"""
# 确保data目录存在(由main函数创建)
file_path = './data/boston_housing.csv'
if not os.path.exists(file_path):
raise FileNotFoundError(f"数据文件 {file_path} 不存在,请检查目录结构")
df = pd.read_csv(file_path, names=column_names)
if 'MEDV' not in df.columns:
raise ValueError("数据集必须包含'MEDV'列")
# 数据清洗:移除极端异常值(处理明显不合理的房价)
Q1 = df['MEDV'].quantile(0.01)
Q3 = df['MEDV'].quantile(0.99)
df = df[(df['MEDV'] >= Q1) & (df['MEDV'] <= Q3)]
feature_names = df.columns.tolist()
feature_names.remove('MEDV')
return df, feature_names
def explore_data(df):
"""
数据探索分析
"""
print("=" * 50)
print("数据探索分析")
print("=" * 50)
print(f"数据集维度: {df.shape}")
print(f"\n前5行数据:")
print(df.head())
print(f"\n数据基本信息:")
print(df.info())
print(f"\n描述性统计:")
print(df.describe())
# 检查缺失值
missing_values = df.isnull().sum()
if missing_values.any():
print(f"\n缺失值情况:\n{missing_values[missing_values > 0]}")
else:
print("\n无缺失值")
# 特征相关性分析
print(f"\n目标变量MEDV与各特征的相关性:")
correlations = df.corr()['MEDV'].sort_values(ascending=False)
print(correlations)
def visualize_data(df):
"""
数据可视化分析
"""
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
# 房价分布直方图
axes[0, 0].hist(df['MEDV'], bins=30, alpha=0.7, color='skyblue', edgecolor='black')
axes[0, 0].set_xlabel('房屋价格(千美元)')
axes[0, 0].set_ylabel('频数')
axes[0, 0].set_title('房价分布直方图')
axes[0, 0].grid(True, alpha=0.3)
# 关键特征与房价的关系散点图(选择两个重要特征)
axes[1, 0].scatter(df['RM'], df['MEDV'], alpha=0.6, color='green')
axes[1, 0].set_xlabel('房间数量 (RM)')
axes[1, 0].set_ylabel('价格')
axes[1, 0].set_title('房间数量 vs 房价')
axes[1, 0].grid(True, alpha=0.3)
axes[1, 1].scatter(df['LSTAT'], df['MEDV'], alpha=0.6, color='red')
axes[1, 1].set_xlabel('低收入人口比例 (LSTAT)')
axes[1, 1].set_ylabel('价格')
axes[1, 1].set_title('低收入人口比例 vs 房价')
axes[1, 1].grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
def build_and_evaluate_model(X, y):
"""
构建线性回归模型并进行评估
返回: 训练好的模型和评估结果
"""
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 数据标准化,提升线性回归性能
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 构建并训练线性回归模型
model = LinearRegression()
model.fit(X_train_scaled, y_train)
# 预测
y_pred = model.predict(X_test_scaled)
# 计算评估指标
metrics = {
'MSE': mean_squared_error(y_test, y_pred),
'RMSE': np.sqrt(mean_squared_error(y_test, y_pred)),
'MAE': mean_absolute_error(y_test, y_pred),
'R2': r2_score(y_test, y_pred),
'解释方差': explained_variance_score(y_test, y_pred),
'中值绝对误差': median_absolute_error(y_test, y_pred)
}
# 交叉验证评估
cv_scores = cross_val_score(model, X_train_scaled, y_train, cv=5, scoring='r2')
metrics['交叉验证R2均值'] = cv_scores.mean()
metrics['交叉验证R2标准差'] = cv_scores.std()
return model, metrics, y_test, y_pred, X_train, X_test, scaler
def print_model_results(model, metrics, feature_names):
"""
打印模型结果和评估指标
"""
print("=" * 50)
print("模型评估结果")
print("=" * 50)
print(f"截距项: {model.intercept_:.4f}")
print("\n特征系数:")
for name, coef in zip(feature_names, model.coef_):
print(f" {name}: {coef:>8.4f}")
print("\n评估指标:")
for metric, value in metrics.items():
if metric == 'R2':
print(f" {metric}: {value:.4f}")
else:
print(f" {metric}: {value:.4f}")
def visualize_results(y_test, y_pred):
"""
可视化模型预测结果
"""
fig, axes = plt.subplots(1, 2, figsize=(15, 6))
# 真实值 vs 预测值散点图
axes[0].scatter(y_test, y_pred, alpha=0.7, color='blue')
axes[0].plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--', lw=2)
axes[0].set_xlabel('真实价格')
axes[0].set_ylabel('预测价格')
axes[0].set_title('真实值 vs 预测值')
axes[0].grid(True, alpha=0.3)
# 添加R²到图中
r2 = r2_score(y_test, y_pred)
axes[0].text(0.05, 0.95, f'R² = {r2:.4f}', transform=axes[0].transAxes,
bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.8))
# 预测值与真实值对比折线图(前50个样本)
indices = range(min(50, len(y_test)))
axes[1].plot(indices, y_test.values[:50], 'o-', label='真实值', linewidth=2, markersize=6)
axes[1].plot(indices, y_pred[:50], 's-', label='预测值', linewidth=2, markersize=4)
axes[1].set_xlabel('样本索引')
axes[1].set_ylabel('价格')
axes[1].set_title('预测值与真实值对比(前50个样本)')
axes[1].legend()
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
def main():
print("波士顿房价预测分析")
print("=" * 50)
# 1. 加载数据
df, feature_names = load_boston_data()
X = df.drop('MEDV', axis=1)
y = df['MEDV']
# 2. 数据探索
explore_data(df)
# 3. 数据可视化
visualize_data(df)
# 4. 构建和评估模型
model, metrics, y_test, y_pred, X_train, X_test, scaler = build_and_evaluate_model(X, y)
# 5. 打印结果
print_model_results(model, metrics, feature_names)
# 6. 结果可视化
visualize_results(y_test, y_pred)
print("\n分析完成!")
if __name__ == "__main__":
# 创建目录
os.makedirs('./data', exist_ok=True)
main()
|
2301_77705369/ml-model
|
boston.py
|
Python
|
unknown
| 7,595
|
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit
|
2301_76667160/vue-devui
|
.husky/commit-msg
|
Shell
|
mit
| 76
|
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
pnpx @ls-lint/ls-lint && pnpx lint-staged
|
2301_76667160/vue-devui
|
.husky/pre-commit
|
Shell
|
mit
| 84
|
const types = ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'release', 'chore', 'revert'];
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-empty': [2, 'never'],
'type-enum': [2, 'always', types],
'scope-case': [0, 'always'],
'subject-empty': [2, 'never'],
'subject-case': [0, 'never'],
'header-max-length': [2, 'always', 88],
},
};
|
2301_76667160/vue-devui
|
commitlint.config.js
|
JavaScript
|
mit
| 419
|
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
|
2301_77204479/AnotherRedisDesktopManager
|
config/dev.env.js
|
JavaScript
|
mit
| 156
|
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 9988, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
// when not web conditon, such as index.html as main, relative path
assetsPublicPath: './',
/**
* Source Maps
*/
productionSourceMap: false,
// https://webpack.js.org/configuration/devtool/#production
// devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
|
2301_77204479/AnotherRedisDesktopManager
|
config/index.js
|
JavaScript
|
mit
| 2,051
|
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
|
2301_77204479/AnotherRedisDesktopManager
|
config/prod.env.js
|
JavaScript
|
mit
| 61
|
/* Element Chalk Variables */
// Special comment for theme configurator
// type|skipAutoTranslation|Category|Order
// skipAutoTranslation 1
/* Transition
-------------------------- */
$--all-transition: all .3s cubic-bezier(.645,.045,.355,1) !default;
$--fade-transition: opacity 300ms cubic-bezier(0.23, 1, 0.32, 1) !default;
$--fade-linear-transition: opacity 200ms linear !default;
$--md-fade-transition: transform 300ms cubic-bezier(0.23, 1, 0.32, 1), opacity 300ms cubic-bezier(0.23, 1, 0.32, 1) !default;
$--border-transition-base: border-color .2s cubic-bezier(.645,.045,.355,1) !default;
$--color-transition-base: color .2s cubic-bezier(.645,.045,.355,1) !default;
/* Color
-------------------------- */
/// color|1|Brand Color|0
$--color-primary: #52a6fd !default;
/// color|1|Background Color|4
$--color-white: #263238 !default;
/// color|1|Background Color|4
$--color-black: #000000 !default;
$--color-primary-light-1: mix($--color-white, $--color-primary, 10%) !default; /* 53a8ff */
$--color-primary-light-2: mix($--color-white, $--color-primary, 20%) !default; /* 66b1ff */
$--color-primary-light-3: mix($--color-white, $--color-primary, 30%) !default; /* 79bbff */
$--color-primary-light-4: mix($--color-white, $--color-primary, 40%) !default; /* 8cc5ff */
$--color-primary-light-5: mix($--color-white, $--color-primary, 50%) !default; /* a0cfff */
$--color-primary-light-6: mix($--color-white, $--color-primary, 60%) !default; /* b3d8ff */
$--color-primary-light-7: mix($--color-white, $--color-primary, 70%) !default; /* c6e2ff */
$--color-primary-light-8: mix($--color-white, $--color-primary, 80%) !default; /* d9ecff */
$--color-primary-light-9: mix($--color-white, $--color-primary, 90%) !default; /* ecf5ff */
/// color|1|Functional Color|1
$--color-success: #67C23A !default;
/// color|1|Functional Color|1
$--color-warning: #E6A23C !default;
/// color|1|Functional Color|1
$--color-danger: #F56C6C !default;
/// color|1|Functional Color|1
$--color-info: #a3a6ad !default;
$--color-success-light: mix($--color-white, $--color-success, 80%) !default;
$--color-warning-light: mix($--color-white, $--color-warning, 80%) !default;
$--color-danger-light: mix($--color-white, $--color-danger, 80%) !default;
$--color-info-light: mix($--color-white, $--color-info, 80%) !default;
$--color-success-lighter: mix($--color-white, $--color-success, 90%) !default;
$--color-warning-lighter: mix($--color-white, $--color-warning, 90%) !default;
$--color-danger-lighter: mix($--color-white, $--color-danger, 90%) !default;
$--color-info-lighter: mix($--color-white, $--color-info, 90%) !default;
/// color|1|Font Color|2
$--color-text-primary: #F3F3F4 !default;
/// color|1|Font Color|2
$--color-text-regular: #F3F3F4 !default;
/// color|1|Font Color|2
$--color-text-secondary: #F3F3F4 !default;
/// color|1|Font Color|2
$--color-text-placeholder: #507fa9 !default;
/// color|1|Border Color|3
$--border-color-base: #7f8ea5 !default;
/// color|1|Border Color|3
$--border-color-light: #7f8ea5 !default;
/// color|1|Border Color|3
$--border-color-lighter: #7f8ea5 !default;
/// color|1|Border Color|3
$--border-color-extra-light: #7f8ea5 !default;
// Background
/// color|1|Background Color|4
$--background-color-base: #3b4b54 !default;
/*custom styles*/
body {
background: $--color-white;
}
/*custom styles end*/
/* Link
-------------------------- */
$--link-color: $--color-primary-light-2 !default;
$--link-hover-color: $--color-primary !default;
/* Border
-------------------------- */
$--border-width-base: 1px !default;
$--border-style-base: solid !default;
$--border-color-hover: $--color-text-placeholder !default;
$--border-base: $--border-width-base $--border-style-base $--border-color-base !default;
/// borderRadius|1|Radius|0
$--border-radius-base: 4px !default;
/// borderRadius|1|Radius|0
$--border-radius-small: 2px !default;
/// borderRadius|1|Radius|0
$--border-radius-circle: 100% !default;
/// borderRadius|1|Radius|0
$--border-radius-zero: 0 !default;
// Box-shadow
/// boxShadow|1|Shadow|1
$--box-shadow-base: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04) !default;
// boxShadow|1|Shadow|1
$--box-shadow-dark: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .12) !default;
/// boxShadow|1|Shadow|1
$--box-shadow-light: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !default;
/* Fill
-------------------------- */
$--fill-base: $--color-white !default;
/* Typography
-------------------------- */
$--font-path: 'fonts' !default;
$--font-display: 'auto' !default;
/// fontSize|1|Font Size|0
$--font-size-extra-large: 20px !default;
/// fontSize|1|Font Size|0
$--font-size-large: 18px !default;
/// fontSize|1|Font Size|0
$--font-size-medium: 16px !default;
/// fontSize|1|Font Size|0
$--font-size-base: 14px !default;
/// fontSize|1|Font Size|0
$--font-size-small: 13px !default;
/// fontSize|1|Font Size|0
$--font-size-extra-small: 12px !default;
/// fontWeight|1|Font Weight|1
$--font-weight-primary: 500 !default;
/// fontWeight|1|Font Weight|1
$--font-weight-secondary: 100 !default;
/// fontLineHeight|1|Line Height|2
$--font-line-height-primary: 24px !default;
/// fontLineHeight|1|Line Height|2
$--font-line-height-secondary: 16px !default;
$--font-color-disabled-base: #bbb !default;
/* Size
-------------------------- */
$--size-base: 14px !default;
/* z-index
-------------------------- */
$--index-normal: 1 !default;
$--index-top: 1000 !default;
$--index-popper: 2000 !default;
/* Disable base
-------------------------- */
$--disabled-fill-base: $--background-color-base !default;
$--disabled-color-base: $--color-text-placeholder !default;
$--disabled-border-base: $--border-color-light !default;
/* Icon
-------------------------- */
$--icon-color: #666 !default;
$--icon-color-base: $--color-info !default;
/* Checkbox
-------------------------- */
/// fontSize||Font|1
$--checkbox-font-size: 14px !default;
/// fontWeight||Font|1
$--checkbox-font-weight: $--font-weight-primary !default;
/// color||Color|0
$--checkbox-font-color: $--color-text-regular !default;
$--checkbox-input-height: 14px !default;
$--checkbox-input-width: 14px !default;
/// borderRadius||Border|2
$--checkbox-border-radius: $--border-radius-small !default;
/// color||Color|0
$--checkbox-background-color: $--color-white !default;
$--checkbox-input-border: $--border-base !default;
/// color||Color|0
$--checkbox-disabled-border-color: $--border-color-base !default;
$--checkbox-disabled-input-fill: #edf2fc !default;
$--checkbox-disabled-icon-color: $--color-text-placeholder !default;
$--checkbox-disabled-checked-input-fill: $--border-color-extra-light !default;
$--checkbox-disabled-checked-input-border-color: $--border-color-base !default;
$--checkbox-disabled-checked-icon-color: $--color-text-placeholder !default;
/// color||Color|0
$--checkbox-checked-font-color: $--color-primary !default;
$--checkbox-checked-input-border-color: $--color-primary !default;
/// color||Color|0
$--checkbox-checked-background-color: $--color-primary !default;
$--checkbox-checked-icon-color: $--fill-base !default;
$--checkbox-input-border-color-hover: $--color-primary !default;
/// height||Other|4
$--checkbox-bordered-height: 40px !default;
/// padding||Spacing|3
$--checkbox-bordered-padding: 9px 20px 9px 10px !default;
/// padding||Spacing|3
$--checkbox-bordered-medium-padding: 7px 20px 7px 10px !default;
/// padding||Spacing|3
$--checkbox-bordered-small-padding: 5px 15px 5px 10px !default;
/// padding||Spacing|3
$--checkbox-bordered-mini-padding: 3px 15px 3px 10px !default;
$--checkbox-bordered-medium-input-height: 14px !default;
$--checkbox-bordered-medium-input-width: 14px !default;
/// height||Other|4
$--checkbox-bordered-medium-height: 36px !default;
$--checkbox-bordered-small-input-height: 12px !default;
$--checkbox-bordered-small-input-width: 12px !default;
/// height||Other|4
$--checkbox-bordered-small-height: 32px !default;
$--checkbox-bordered-mini-input-height: 12px !default;
$--checkbox-bordered-mini-input-width: 12px !default;
/// height||Other|4
$--checkbox-bordered-mini-height: 28px !default;
/// color||Color|0
$--checkbox-button-checked-background-color: $--color-primary !default;
/// color||Color|0
$--checkbox-button-checked-font-color: $--color-white !default;
/// color||Color|0
$--checkbox-button-checked-border-color: $--color-primary !default;
/* Radio
-------------------------- */
/// fontSize||Font|1
$--radio-font-size: $--font-size-base !default;
/// fontWeight||Font|1
$--radio-font-weight: $--font-weight-primary !default;
/// color||Color|0
$--radio-font-color: $--color-text-regular !default;
$--radio-input-height: 14px !default;
$--radio-input-width: 14px !default;
/// borderRadius||Border|2
$--radio-input-border-radius: $--border-radius-circle !default;
/// color||Color|0
$--radio-input-background-color: $--color-white !default;
$--radio-input-border: $--border-base !default;
/// color||Color|0
$--radio-input-border-color: $--border-color-base !default;
/// color||Color|0
$--radio-icon-color: $--color-white !default;
$--radio-disabled-input-border-color: $--disabled-border-base !default;
$--radio-disabled-input-fill: $--disabled-fill-base !default;
$--radio-disabled-icon-color: $--disabled-fill-base !default;
$--radio-disabled-checked-input-border-color: $--disabled-border-base !default;
$--radio-disabled-checked-input-fill: $--disabled-fill-base !default;
$--radio-disabled-checked-icon-color: $--color-text-placeholder !default;
/// color||Color|0
$--radio-checked-font-color: $--color-primary !default;
/// color||Color|0
$--radio-checked-input-border-color: $--color-primary !default;
/// color||Color|0
$--radio-checked-input-background-color: $--color-white !default;
/// color||Color|0
$--radio-checked-icon-color: $--color-primary !default;
$--radio-input-border-color-hover: $--color-primary !default;
$--radio-bordered-height: 40px !default;
$--radio-bordered-padding: 12px 20px 0 10px !default;
$--radio-bordered-medium-padding: 10px 20px 0 10px !default;
$--radio-bordered-small-padding: 8px 15px 0 10px !default;
$--radio-bordered-mini-padding: 6px 15px 0 10px !default;
$--radio-bordered-medium-input-height: 14px !default;
$--radio-bordered-medium-input-width: 14px !default;
$--radio-bordered-medium-height: 36px !default;
$--radio-bordered-small-input-height: 12px !default;
$--radio-bordered-small-input-width: 12px !default;
$--radio-bordered-small-height: 32px !default;
$--radio-bordered-mini-input-height: 12px !default;
$--radio-bordered-mini-input-width: 12px !default;
$--radio-bordered-mini-height: 28px !default;
/// fontSize||Font|1
$--radio-button-font-size: $--font-size-base !default;
/// color||Color|0
$--radio-button-checked-background-color: $--color-primary !default;
/// color||Color|0
$--radio-button-checked-font-color: $--color-white !default;
/// color||Color|0
$--radio-button-checked-border-color: $--color-primary !default;
$--radio-button-disabled-checked-fill: $--border-color-extra-light !default;
/* Select
-------------------------- */
$--select-border-color-hover: $--border-color-hover !default;
$--select-disabled-border: $--disabled-border-base !default;
/// fontSize||Font|1
$--select-font-size: $--font-size-base !default;
$--select-close-hover-color: $--color-text-secondary !default;
$--select-input-color: $--color-text-placeholder !default;
$--select-multiple-input-color: #666 !default;
/// color||Color|0
$--select-input-focus-border-color: $--color-primary !default;
/// fontSize||Font|1
$--select-input-font-size: 14px !default;
$--select-option-color: $--color-text-regular !default;
$--select-option-disabled-color: $--color-text-placeholder !default;
$--select-option-disabled-background: $--color-white !default;
/// height||Other|4
$--select-option-height: 34px !default;
$--select-option-hover-background: $--background-color-base !default;
/// color||Color|0
$--select-option-selected-font-color: $--color-primary !default;
$--select-option-selected-hover: $--background-color-base !default;
$--select-group-color: $--color-info !default;
$--select-group-height: 30px !default;
$--select-group-font-size: 12px !default;
$--select-dropdown-background: $--color-white !default;
$--select-dropdown-shadow: $--box-shadow-light !default;
$--select-dropdown-empty-color: #999 !default;
/// height||Other|4
$--select-dropdown-max-height: 274px !default;
$--select-dropdown-padding: 6px 0 !default;
$--select-dropdown-empty-padding: 10px 0 !default;
$--select-dropdown-border: solid 1px $--border-color-light !default;
/* Alert
-------------------------- */
$--alert-padding: 8px 16px !default;
/// borderRadius||Border|2
$--alert-border-radius: $--border-radius-base !default;
/// fontSize||Font|1
$--alert-title-font-size: 13px !default;
/// fontSize||Font|1
$--alert-description-font-size: 12px !default;
/// fontSize||Font|1
$--alert-close-font-size: 12px !default;
/// fontSize||Font|1
$--alert-close-customed-font-size: 13px !default;
$--alert-success-color: $--color-success-lighter !default;
$--alert-info-color: $--color-info-lighter !default;
$--alert-warning-color: $--color-warning-lighter !default;
$--alert-danger-color: $--color-danger-lighter !default;
/// height||Other|4
$--alert-icon-size: 16px !default;
/// height||Other|4
$--alert-icon-large-size: 28px !default;
/* MessageBox
-------------------------- */
/// color||Color|0
$--messagebox-title-color: $--color-text-primary !default;
$--msgbox-width: 420px !default;
$--msgbox-border-radius: 4px !default;
/// fontSize||Font|1
$--messagebox-font-size: $--font-size-large !default;
/// fontSize||Font|1
$--messagebox-content-font-size: $--font-size-base !default;
/// color||Color|0
$--messagebox-content-color: $--color-text-regular !default;
/// fontSize||Font|1
$--messagebox-error-font-size: 12px !default;
$--msgbox-padding-primary: 15px !default;
/// color||Color|0
$--messagebox-success-color: $--color-success !default;
/// color||Color|0
$--messagebox-info-color: $--color-info !default;
/// color||Color|0
$--messagebox-warning-color: $--color-warning !default;
/// color||Color|0
$--messagebox-danger-color: $--color-danger !default;
/*fix dark mode message box icon top error*/
.el-message-box__status {
top: 48.5%;
}
/* Message
-------------------------- */
$--message-shadow: $--box-shadow-base !default;
$--message-min-width: 380px !default;
$--message-background-color: #edf2fc !default;
$--message-padding: 15px 15px 15px 20px !default;
/// color||Color|0
$--message-close-icon-color: $--color-text-placeholder !default;
/// height||Other|4
$--message-close-size: 16px !default;
/// color||Color|0
$--message-close-hover-color: $--color-text-secondary !default;
/// color||Color|0
$--message-success-font-color: $--color-success !default;
/// color||Color|0
$--message-info-font-color: $--color-info !default;
/// color||Color|0
$--message-warning-font-color: $--color-warning !default;
/// color||Color|0
$--message-danger-font-color: $--color-danger !default;
/* Notification
-------------------------- */
$--notification-width: 330px !default;
/// padding||Spacing|3
$--notification-padding: 14px 26px 14px 13px !default;
$--notification-radius: 8px !default;
$--notification-shadow: $--box-shadow-light !default;
/// color||Color|0
$--notification-border-color: $--border-color-lighter !default;
$--notification-icon-size: 24px !default;
$--notification-close-font-size: $--message-close-size !default;
$--notification-group-margin-left: 13px !default;
$--notification-group-margin-right: 8px !default;
/// fontSize||Font|1
$--notification-content-font-size: $--font-size-base !default;
/// color||Color|0
$--notification-content-color: $--color-text-regular !default;
/// fontSize||Font|1
$--notification-title-font-size: 16px !default;
/// color||Color|0
$--notification-title-color: $--color-text-primary !default;
/// color||Color|0
$--notification-close-color: $--color-text-secondary !default;
/// color||Color|0
$--notification-close-hover-color: $--color-text-regular !default;
/// color||Color|0
$--notification-success-icon-color: $--color-success !default;
/// color||Color|0
$--notification-info-icon-color: $--color-info !default;
/// color||Color|0
$--notification-warning-icon-color: $--color-warning !default;
/// color||Color|0
$--notification-danger-icon-color: $--color-danger !default;
/* Input
-------------------------- */
$--input-font-size: $--font-size-base !default;
/// color||Color|0
$--input-font-color: $--color-text-regular !default;
/// height||Other|4
$--input-width: 140px !default;
/// height||Other|4
$--input-height: 40px !default;
$--input-border: $--border-base !default;
$--input-border-color: $--border-color-base !default;
/// borderRadius||Border|2
$--input-border-radius: $--border-radius-base !default;
$--input-border-color-hover: $--border-color-hover !default;
/// color||Color|0
$--input-background-color: $--color-white !default;
$--input-fill-disabled: $--disabled-fill-base !default;
$--input-color-disabled: $--font-color-disabled-base !default;
/// color||Color|0
$--input-icon-color: $--color-text-placeholder !default;
/// color||Color|0
$--input-placeholder-color: $--color-text-placeholder !default;
$--input-max-width: 314px !default;
$--input-hover-border: $--border-color-hover !default;
$--input-clear-hover-color: $--color-text-secondary !default;
$--input-focus-border: $--color-primary !default;
$--input-focus-fill: $--color-white !default;
$--input-disabled-fill: $--disabled-fill-base !default;
$--input-disabled-border: $--disabled-border-base !default;
$--input-disabled-color: $--disabled-color-base !default;
$--input-disabled-placeholder-color: $--color-text-placeholder !default;
/// fontSize||Font|1
$--input-medium-font-size: 14px !default;
/// height||Other|4
$--input-medium-height: 36px !default;
/// fontSize||Font|1
$--input-small-font-size: 13px !default;
/// height||Other|4
$--input-small-height: 32px !default;
/// fontSize||Font|1
$--input-mini-font-size: 12px !default;
/// height||Other|4
$--input-mini-height: 28px !default;
/* Cascader
-------------------------- */
/// color||Color|0
$--cascader-menu-font-color: $--color-text-regular !default;
/// color||Color|0
$--cascader-menu-selected-font-color: $--color-primary !default;
$--cascader-menu-fill: $--fill-base !default;
$--cascader-menu-font-size: $--font-size-base !default;
$--cascader-menu-radius: $--border-radius-base !default;
$--cascader-menu-border: solid 1px $--border-color-light !default;
$--cascader-menu-shadow: $--box-shadow-light !default;
$--cascader-node-background-hover: $--background-color-base !default;
$--cascader-node-color-disabled:$--color-text-placeholder !default;
$--cascader-color-empty:$--color-text-placeholder !default;
$--cascader-tag-background: #f0f2f5;
/* Group
-------------------------- */
$--group-option-flex: 0 0 (1/5) * 100% !default;
$--group-option-offset-bottom: 12px !default;
$--group-option-fill-hover: rgba($--color-black, 0.06) !default;
$--group-title-color: $--color-black !default;
$--group-title-font-size: $--font-size-base !default;
$--group-title-width: 66px !default;
/* Tab
-------------------------- */
$--tab-font-size: $--font-size-base !default;
$--tab-border-line: 1px solid #e4e4e4 !default;
$--tab-header-color-active: $--color-text-secondary !default;
$--tab-header-color-hover: $--color-text-regular !default;
$--tab-header-color: $--color-text-regular !default;
$--tab-header-fill-active: rgba($--color-black, 0.06) !default;
$--tab-header-fill-hover: rgba($--color-black, 0.06) !default;
$--tab-vertical-header-width: 90px !default;
$--tab-vertical-header-count-color: $--color-white !default;
$--tab-vertical-header-count-fill: $--color-text-secondary !default;
/* Button
-------------------------- */
/// fontSize||Font|1
$--button-font-size: $--font-size-base !default;
/// fontWeight||Font|1
$--button-font-weight: $--font-weight-primary !default;
/// borderRadius||Border|2
$--button-border-radius: $--border-radius-base !default;
/// padding||Spacing|3
$--button-padding-vertical: 12px !default;
/// padding||Spacing|3
$--button-padding-horizontal: 20px !default;
/// fontSize||Font|1
$--button-medium-font-size: $--font-size-base !default;
/// borderRadius||Border|2
$--button-medium-border-radius: $--border-radius-base !default;
/// padding||Spacing|3
$--button-medium-padding-vertical: 10px !default;
/// padding||Spacing|3
$--button-medium-padding-horizontal: 20px !default;
/// fontSize||Font|1
$--button-small-font-size: 12px !default;
$--button-small-border-radius: #{$--border-radius-base - 1} !default;
/// padding||Spacing|3
$--button-small-padding-vertical: 9px !default;
/// padding||Spacing|3
$--button-small-padding-horizontal: 15px !default;
/// fontSize||Font|1
$--button-mini-font-size: 12px !default;
$--button-mini-border-radius: #{$--border-radius-base - 1} !default;
/// padding||Spacing|3
$--button-mini-padding-vertical: 7px !default;
/// padding||Spacing|3
$--button-mini-padding-horizontal: 15px !default;
/// color||Color|0
$--button-default-font-color: $--color-text-regular !default;
/// color||Color|0
$--button-default-background-color: $--color-white !default;
/// color||Color|0
$--button-default-border-color: $--border-color-base !default;
/// color||Color|0
$--button-disabled-font-color: $--color-text-placeholder !default;
/// color||Color|0
$--button-disabled-background-color: $--color-white !default;
/// color||Color|0
$--button-disabled-border-color: $--border-color-lighter !default;
/// color||Color|0
$--button-primary-border-color: $--color-primary !default;
/// color||Color|0
$--button-primary-font-color: $--color-white !default;
/// color||Color|0
$--button-primary-background-color: $--color-primary !default;
/// color||Color|0
$--button-success-border-color: $--color-success !default;
/// color||Color|0
$--button-success-font-color: $--color-white !default;
/// color||Color|0
$--button-success-background-color: $--color-success !default;
/// color||Color|0
$--button-warning-border-color: $--color-warning !default;
/// color||Color|0
$--button-warning-font-color: $--color-white !default;
/// color||Color|0
$--button-warning-background-color: $--color-warning !default;
/// color||Color|0
$--button-danger-border-color: $--color-danger !default;
/// color||Color|0
$--button-danger-font-color: $--color-white !default;
/// color||Color|0
$--button-danger-background-color: $--color-danger !default;
/// color||Color|0
$--button-info-border-color: $--color-info !default;
/// color||Color|0
$--button-info-font-color: $--color-white !default;
/// color||Color|0
$--button-info-background-color: $--color-info !default;
$--button-hover-tint-percent: 20% !default;
$--button-active-shade-percent: 10% !default;
/* cascader
-------------------------- */
$--cascader-height: 200px !default;
/* Switch
-------------------------- */
/// color||Color|0
$--switch-on-color: $--color-primary !default;
/// color||Color|0
$--switch-off-color: $--border-color-base !default;
/// fontSize||Font|1
$--switch-font-size: $--font-size-base !default;
$--switch-core-border-radius: 10px !default;
// height||Other|4 TODO: width 代码写死的40px 所以下面这三个属性都没意义
$--switch-width: 40px !default;
// height||Other|4
$--switch-height: 20px !default;
// height||Other|4
$--switch-button-size: 16px !default;
/* Dialog
-------------------------- */
$--dialog-background-color: $--color-white !default;
$--dialog-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3) !default;
/// fontSize||Font|1
$--dialog-title-font-size: $--font-size-large !default;
/// fontSize||Font|1
$--dialog-content-font-size: 14px !default;
/// fontLineHeight||LineHeight|2
$--dialog-font-line-height: $--font-line-height-primary !default;
/// padding||Spacing|3
$--dialog-padding-primary: 20px !default;
/* Table
-------------------------- */
/// color||Color|0
$--table-border-color: $--border-color-lighter !default;
$--table-border: 1px solid $--table-border-color !default;
/// color||Color|0
$--table-font-color: $--color-text-regular !default;
/// color||Color|0
$--table-header-font-color: $--color-text-secondary !default;
/// color||Color|0
$--table-row-hover-background-color: $--background-color-base !default;
$--table-current-row-background-color: $--color-primary-light-9 !default;
/// color||Color|0
$--table-header-background-color: $--color-white !default;
$--table-fixed-box-shadow: 0 0 10px rgba(0, 0, 0, .12) !default;
.el-table__row--striped {
td {
background: $--background-color-base !important;
}
}
/* Pagination
-------------------------- */
/// fontSize||Font|1
$--pagination-font-size: 13px !default;
/// color||Color|0
$--pagination-background-color: $--color-white !default;
/// color||Color|0
$--pagination-font-color: $--color-text-primary !default;
$--pagination-border-radius: 3px !default;
/// color||Color|0
$--pagination-button-color: $--color-text-primary !default;
/// height||Other|4
$--pagination-button-width: 35.5px !default;
/// height||Other|4
$--pagination-button-height: 28px !default;
/// color||Color|0
$--pagination-button-disabled-color: $--color-text-placeholder !default;
/// color||Color|0
$--pagination-button-disabled-background-color: $--color-white !default;
/// color||Color|0
$--pagination-hover-color: $--color-primary !default;
/* Popup
-------------------------- */
/// color||Color|0
$--popup-modal-background-color: $--color-black !default;
/// opacity||Other|1
$--popup-modal-opacity: 0.5 !default;
/* Popover
-------------------------- */
/// color||Color|0
$--popover-background-color: $--color-white !default;
/// fontSize||Font|1
$--popover-font-size: $--font-size-base !default;
/// color||Color|0
$--popover-border-color: $--border-color-lighter !default;
$--popover-arrow-size: 6px !default;
/// padding||Spacing|3
$--popover-padding: 12px !default;
$--popover-padding-large: 18px 20px !default;
/// fontSize||Font|1
$--popover-title-font-size: 16px !default;
/// color||Color|0
$--popover-title-font-color: $--color-text-primary !default;
/* Tooltip
-------------------------- */
/// color|1|Color|0
$--tooltip-fill: $--color-text-primary !default;
/// color|1|Color|0
$--tooltip-color: $--color-white !default;
/// fontSize||Font|1
$--tooltip-font-size: 12px !default;
/// color||Color|0
$--tooltip-border-color: $--color-text-primary !default;
$--tooltip-arrow-size: 6px !default;
/// padding||Spacing|3
$--tooltip-padding: 10px !default;
/* Tag
-------------------------- */
/// color||Color|0
$--tag-info-color: $--color-info !default;
/// color||Color|0
$--tag-primary-color: $--color-primary !default;
/// color||Color|0
$--tag-success-color: $--color-success !default;
/// color||Color|0
$--tag-warning-color: $--color-warning !default;
/// color||Color|0
$--tag-danger-color: $--color-danger !default;
/// fontSize||Font|1
$--tag-font-size: 12px !default;
$--tag-border-radius: 4px !default;
$--tag-padding: 0 10px !default;
/* Tree
-------------------------- */
/// color||Color|0
$--tree-node-hover-background-color: $--background-color-base !default;
/// color||Color|0
$--tree-font-color: $--color-text-regular !default;
/// color||Color|0
$--tree-expand-icon-color: $--color-text-placeholder !default;
/* Dropdown
-------------------------- */
$--dropdown-menu-box-shadow: $--box-shadow-light !default;
$--dropdown-menuItem-hover-fill: $--color-primary-light-9 !default;
$--dropdown-menuItem-hover-color: $--link-color !default;
/* Badge
-------------------------- */
/// color||Color|0
$--badge-background-color: $--color-danger !default;
$--badge-radius: 10px !default;
/// fontSize||Font|1
$--badge-font-size: 12px !default;
/// padding||Spacing|3
$--badge-padding: 6px !default;
/// height||Other|4
$--badge-size: 18px !default;
/* Card
--------------------------*/
/// color||Color|0
$--card-border-color: $--border-color-lighter !default;
$--card-border-radius: 4px !default;
/// padding||Spacing|3
$--card-padding: 20px !default;
/* Slider
--------------------------*/
/// color||Color|0
$--slider-main-background-color: $--color-primary !default;
/// color||Color|0
$--slider-runway-background-color: $--border-color-light !default;
$--slider-button-hover-color: mix($--color-primary, black, 97%) !default;
$--slider-stop-background-color: $--color-white !default;
$--slider-disable-color: $--color-text-placeholder !default;
$--slider-margin: 16px 0 !default;
$--slider-border-radius: 3px !default;
/// height|1|Other|4
$--slider-height: 6px !default;
/// height||Other|4
$--slider-button-size: 16px !default;
$--slider-button-wrapper-size: 36px !default;
$--slider-button-wrapper-offset: -15px !default;
/* Steps
--------------------------*/
$--steps-border-color: $--disabled-border-base !default;
$--steps-border-radius: 4px !default;
$--steps-padding: 20px !default;
/* Menu
--------------------------*/
/// fontSize||Font|1
$--menu-item-font-size: $--font-size-base !default;
/// color||Color|0
$--menu-item-font-color: $--color-text-primary !default;
/// color||Color|0
$--menu-background-color: $--color-white !default;
$--menu-item-hover-fill: $--color-primary-light-9 !default;
/* Rate
--------------------------*/
$--rate-height: 20px !default;
/// fontSize||Font|1
$--rate-font-size: $--font-size-base !default;
/// height||Other|3
$--rate-icon-size: 18px !default;
/// margin||Spacing|2
$--rate-icon-margin: 6px !default;
$--rate-icon-color: $--color-text-placeholder !default;
/* DatePicker
--------------------------*/
$--datepicker-font-color: $--color-text-regular !default;
/// color|1|Color|0
$--datepicker-off-font-color: $--color-text-placeholder !default;
/// color||Color|0
$--datepicker-header-font-color: $--color-text-regular !default;
$--datepicker-icon-color: $--color-text-primary !default;
$--datepicker-border-color: $--disabled-border-base !default;
$--datepicker-inner-border-color: #e4e4e4 !default;
/// color||Color|0
$--datepicker-inrange-background-color: $--border-color-extra-light !default;
/// color||Color|0
$--datepicker-inrange-hover-background-color: $--border-color-extra-light !default;
/// color||Color|0
$--datepicker-active-color: $--color-primary !default;
/// color||Color|0
$--datepicker-hover-font-color: $--color-primary !default;
$--datepicker-cell-hover-color: #fff !default;
/* Loading
--------------------------*/
/// height||Other|4
$--loading-spinner-size: 42px !default;
/// height||Other|4
$--loading-fullscreen-spinner-size: 50px !default;
/* Scrollbar
--------------------------*/
$--scrollbar-background-color: rgba($--color-text-secondary, .3) !default;
$--scrollbar-hover-background-color: rgba($--color-text-secondary, .5) !default;
/* Carousel
--------------------------*/
/// fontSize||Font|1
$--carousel-arrow-font-size: 12px !default;
$--carousel-arrow-size: 36px !default;
$--carousel-arrow-background: rgba(31, 45, 61, 0.11) !default;
$--carousel-arrow-hover-background: rgba(31, 45, 61, 0.23) !default;
/// width||Other|4
$--carousel-indicator-width: 30px !default;
/// height||Other|4
$--carousel-indicator-height: 2px !default;
$--carousel-indicator-padding-horizontal: 4px !default;
$--carousel-indicator-padding-vertical: 12px !default;
$--carousel-indicator-out-color: $--border-color-hover !default;
/* Collapse
--------------------------*/
/// color||Color|0
$--collapse-border-color: $--border-color-lighter !default;
/// height||Other|4
$--collapse-header-height: 48px !default;
/// color||Color|0
$--collapse-header-background-color: $--color-white !default;
/// color||Color|0
$--collapse-header-font-color: $--color-text-primary !default;
/// fontSize||Font|1
$--collapse-header-font-size: 13px !default;
/// color||Color|0
$--collapse-content-background-color: $--color-white !default;
/// fontSize||Font|1
$--collapse-content-font-size: 13px !default;
/// color||Color|0
$--collapse-content-font-color: $--color-text-primary !default;
/* Transfer
--------------------------*/
$--transfer-border-color: $--border-color-lighter !default;
$--transfer-border-radius: $--border-radius-base !default;
/// height||Other|4
$--transfer-panel-width: 200px !default;
/// height||Other|4
$--transfer-panel-header-height: 40px !default;
/// color||Color|0
$--transfer-panel-header-background-color: $--background-color-base !default;
/// height||Other|4
$--transfer-panel-footer-height: 40px !default;
/// height||Other|4
$--transfer-panel-body-height: 246px !default;
/// height||Other|4
$--transfer-item-height: 30px !default;
/// height||Other|4
$--transfer-filter-height: 32px !default;
/* Header
--------------------------*/
$--header-padding: 0 20px !default;
/* Footer
--------------------------*/
$--footer-padding: 0 20px !default;
/* Main
--------------------------*/
$--main-padding: 20px !default;
/* Timeline
--------------------------*/
$--timeline-node-size-normal: 12px !default;
$--timeline-node-size-large: 14px !default;
$--timeline-node-color: $--border-color-light !default;
/* Backtop
--------------------------*/
/// color||Color|0
$--backtop-background-color: $--color-white !default;
/// color||Color|0
$--backtop-font-color: $--color-primary !default;
/// color||Color|0
$--backtop-hover-background-color: $--border-color-extra-light !default;
/* Link
--------------------------*/
/// fontSize||Font|1
$--link-font-size: $--font-size-base !default;
/// fontWeight||Font|1
$--link-font-weight: $--font-weight-primary !default;
/// color||Color|0
$--link-default-font-color: $--color-text-regular !default;
/// color||Color|0
$--link-default-active-color: $--color-primary !default;
/// color||Color|0
$--link-disabled-font-color: $--color-text-placeholder !default;
/// color||Color|0
$--link-primary-font-color: $--color-primary !default;
/// color||Color|0
$--link-success-font-color: $--color-success !default;
/// color||Color|0
$--link-warning-font-color: $--color-warning !default;
/// color||Color|0
$--link-danger-font-color: $--color-danger !default;
/// color||Color|0
$--link-info-font-color: $--color-info !default;
/* Calendar
--------------------------*/
/// border||Other|4
$--calendar-border: $--table-border !default;
/// color||Other|4
$--calendar-selected-background-color: #F2F8FE !default;
$--calendar-cell-width: 85px !default;
/* Form
-------------------------- */
/// fontSize||Font|1
$--form-label-font-size: $--font-size-base !default;
/* Avatar
--------------------------*/
/// color||Color|0
$--avatar-font-color: #fff !default;
/// color||Color|0
$--avatar-background-color: #C0C4CC !default;
/// fontSize||Font Size|1
$--avatar-text-font-size: 14px !default;
/// fontSize||Font Size|1
$--avatar-icon-font-size: 18px !default;
/// borderRadius||Border|2
$--avatar-border-radius: $--border-radius-base !default;
/// size|1|Avatar Size|3
$--avatar-large-size: 40px !default;
/// size|1|Avatar Size|3
$--avatar-medium-size: 36px !default;
/// size|1|Avatar Size|3
$--avatar-small-size: 28px !default;
/* Break-point
--------------------------*/
$--sm: 768px !default;
$--md: 992px !default;
$--lg: 1200px !default;
$--xl: 1920px !default;
$--breakpoints: (
'xs' : (max-width: $--sm - 1),
'sm' : (min-width: $--sm),
'md' : (min-width: $--md),
'lg' : (min-width: $--lg),
'xl' : (min-width: $--xl)
);
$--breakpoints-spec: (
'xs-only' : (max-width: $--sm - 1),
'sm-and-up' : (min-width: $--sm),
'sm-only': "(min-width: #{$--sm}) and (max-width: #{$--md - 1})",
'sm-and-down': (max-width: $--md - 1),
'md-and-up' : (min-width: $--md),
'md-only': "(min-width: #{$--md}) and (max-width: #{$--lg - 1})",
'md-and-down': (max-width: $--lg - 1),
'lg-and-up' : (min-width: $--lg),
'lg-only': "(min-width: #{$--lg}) and (max-width: #{$--xl - 1})",
'lg-and-down': (max-width: $--xl - 1),
'xl-only' : (min-width: $--xl),
);
|
2301_77204479/AnotherRedisDesktopManager
|
element-variables.scss
|
SCSS
|
mit
| 35,660
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" type="text/css" id="theme-link">
<title>Another Redis Desktop Manager</title>
</head>
<body>
<!-- this script must be placed here after body -->
<script type="text/javascript">
const ipcRenderer = require('electron').ipcRenderer;
function globalChangeTheme(theme) {
theme && (localStorage.theme = theme);
!theme && (theme = localStorage.theme);
const themeName = (theme == 'dark' ? 'dark' : 'chalk');
const themeHref = 'static/theme/' + themeName + '/index.css';
document.getElementById('theme-link').href = themeHref;
themeName == 'dark' ? document.body.classList.add('dark-mode') :
document.body.classList.remove('dark-mode');
// change native theme
ipcRenderer.invoke('changeTheme', themeName);
}
// theme init start
globalChangeTheme();
</script>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
|
2301_77204479/AnotherRedisDesktopManager
|
index.html
|
HTML
|
mit
| 1,154
|
// Modules to control application life and create native browser window
const {
app, BrowserWindow, Menu, ipcMain, dialog, nativeTheme,
} = require('electron');
const url = require('url');
const path = require('path');
const fontManager = require('./font-manager');
const winState = require('./win-state');
// disable GPU for some white screen issues
// app.disableHardwareAcceleration();
// app.commandLine.appendSwitch('disable-gpu');
global.APP_ENV = (process.env.ARDM_ENV === 'development') ? 'development' : 'production';
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
// handle uncaught exception
process.on('uncaughtException', (err, origin) => {
if (!err) {
return;
}
dialog.showMessageBoxSync(mainWindow, {
type: 'error',
title: 'Whoops! Uncaught Exception',
message: err.stack,
detail: '\nDon\'t worry, I will fix it! 😎😎\n\n'
+ 'Submit issue to: \nhttps://github.com/qishibo/AnotherRedisDesktopManager/',
});
process.exit();
});
// auto update
if (APP_ENV === 'production') {
require('./update')();
}
function createWindow() {
// get last win stage
const lastWinStage = winState.getLastState();
// Create the browser window.
mainWindow = new BrowserWindow({
x: lastWinStage.x,
y: lastWinStage.y,
width: lastWinStage.width,
height: lastWinStage.height,
icon: `${__dirname}/icons/icon.png`,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: true,
// add this to keep 'remote' module avaiable. Tips: it will be removed in electron 14
enableRemoteModule: true,
contextIsolation: false,
},
});
if (lastWinStage.maximized) {
mainWindow.maximize();
}
winState.watchClose(mainWindow);
// and load the index.html of the app.
if (APP_ENV === 'production') {
// mainWindow.loadFile('index.html');
mainWindow.loadURL(url.format({
protocol: 'file',
slashes: true,
pathname: path.join(__dirname, 'index.html'),
query: { version: app.getVersion() },
}));
} else {
mainWindow.loadURL(`http://localhost:9988/?version=${app.getVersion()}`);
}
// Open the DevTools.
// mainWindow.webContents.openDevTools();
mainWindow.on('close', () => {
mainWindow.webContents.send('closingWindow');
});
// Emitted when the window is closed.
mainWindow.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
// const contents = mainWindow.webContents;
// // contents.openFindWindow();
// contents.findInPage('133');
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', () => {
app.quit();
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
// if (process.platform !== 'darwin') {
// app.quit();
// }
});
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
// hide window
ipcMain.on('hideWindow', () => {
mainWindow && mainWindow.hide();
});
// minimize window
ipcMain.on('minimizeWindow', () => {
mainWindow && mainWindow.minimize();
});
// toggle maximize
ipcMain.on('toggleMaximize', () => {
if (mainWindow) {
// restore failed on MacOS, use unmaximize instead
mainWindow.isMaximized() ? mainWindow.unmaximize() : mainWindow.maximize();
}
});
ipcMain.handle('getMainArgs', (event, arg) => ({
argv: process.argv,
version: app.getVersion(),
}));
ipcMain.handle('changeTheme', (event, theme) => {
nativeTheme.themeSource = (theme === 'dark' ? 'dark' : 'light');
return nativeTheme.shouldUseDarkColors;
});
ipcMain.handle('getTempPath', (event, arg) => app.getPath('temp'));
// for mac copy paset shortcut
if (process.platform === 'darwin') {
const template = [
// { role: 'appMenu' },
{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideothers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' },
],
},
{ role: 'editMenu' },
// { role: 'viewMenu' },
{
label: 'View',
submenu: [
...(
(APP_ENV === 'production') ? [] : [{ role: 'toggledevtools' }]
),
{ role: 'togglefullscreen' },
],
},
// { role: 'windowMenu' },
{
role: 'window',
submenu: [
{ role: 'minimize' },
{ role: 'zoom' },
{ type: 'separator' },
{ role: 'front' },
{ type: 'separator' },
// { role: 'window' }
],
},
{
role: 'help',
submenu: [
{
label: 'Learn More',
click: async () => {
const { shell } = require('electron');
await shell.openExternal('https://github.com/qishibo/AnotherRedisDesktopManager');
},
},
],
},
];
menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
}
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
|
2301_77204479/AnotherRedisDesktopManager
|
pack/electron/electron-main.js
|
JavaScript
|
mit
| 5,780
|
const { ipcMain } = require('electron');
ipcMain.on('get-all-fonts', (event, arg) => {
try {
require('font-list').getFonts().then((fonts) => {
if (!fonts || !fonts.length) {
fonts = [];
}
fonts = fonts.map(font => font.replace('"', '').replace('"', ''));
event.sender.send('send-all-fonts', fonts);
});
} catch (e) {
event.sender.send('send-all-fonts', ['Default Initial']);
}
});
|
2301_77204479/AnotherRedisDesktopManager
|
pack/electron/font-manager.js
|
JavaScript
|
mit
| 434
|
const { session, ipcMain, net } = require('electron');
const { autoUpdater } = require('electron-updater');
// disable auto download
autoUpdater.autoDownload = false;
let mainEvent;
const update = () => {
bindMainListener();
ipcMain.on('update-check', (event, arg) => {
mainEvent = event;
autoUpdater.checkForUpdates()
.then(() => {})
.catch((err) => {
// mainEvent.sender.send('update-error', err);
});
});
ipcMain.on('continue-update', (event, arg) => {
autoUpdater.downloadUpdate()
.then(() => {})
.catch((err) => {
// mainEvent.sender.send('update-error', err);
});
});
};
function bindMainListener() {
autoUpdater.on('checking-for-update', () => {});
autoUpdater.on('update-available', (info) => {
mainEvent.sender.send('update-available', info);
});
autoUpdater.on('update-not-available', (info) => {
mainEvent.sender.send('update-not-available', info);
});
autoUpdater.on('error', (err) => {
mainEvent.sender.send('update-error', err);
});
autoUpdater.on('download-progress', (progressObj) => {
mainEvent.sender.send('download-progress', progressObj);
});
autoUpdater.on('update-downloaded', (info) => {
mainEvent.sender.send('update-downloaded', info);
});
}
module.exports = update;
|
2301_77204479/AnotherRedisDesktopManager
|
pack/electron/update.js
|
JavaScript
|
mit
| 1,320
|
const { app, screen } = require('electron');
const path = require('path');
const fs = require('fs');
const winState = {
// {x, y, width, height, maximized}
getLastState() {
let data = '{}';
try {
data = fs.readFileSync(this.getStateFile());
} catch (err) {}
const lastWinStage = this.parseJson(data);
const lastX = lastWinStage.x;
const lastY = lastWinStage.y;
const primary = screen.getPrimaryDisplay();
// recovery position only when app in primary screen
// if in external screens, reset position for uncaught display issues
if (
lastX < 0 || lastY < 0
|| lastX > primary.workAreaSize.width || lastY > primary.workAreaSize.height
) {
lastWinStage.x = null;
lastWinStage.y = null;
}
// adjust extremely small window
(lastWinStage.width < 250) && (lastWinStage.width = 1100);
(lastWinStage.height < 250) && (lastWinStage.height = 728);
return lastWinStage;
// // there is some uncaught display issues when display in external screens
// // such as windows disappears even x < width
// let screenCanDisplay = false;
// const displays = screen.getAllDisplays()
// for (const display of displays) {
// const bounds = display.workArea;
// // check if there is a screen can display this position
// if (bounds.x * lastX > 0 && bounds.y * lastY > 0) {
// if (bounds.width > Math.abs(lastX) && bounds.height > Math.abs(lastY)) {
// screenCanDisplay = true;
// break;
// }
// }
// }
// let state = {...lastWinStage, x: null, y: null};
// // recovery to last position
// if (screenCanDisplay) {
// state.x = lastX;
// state.y = lastY;
// }
// return state;
},
watchClose(win) {
win.on('close', () => {
const winState = this.getWinState(win);
if (!winState) {
return;
}
this.saveStateToStorage(winState);
});
},
getWinState(win) {
try {
const winBounds = win.getBounds();
const state = {
x: winBounds.x,
y: winBounds.y,
width: winBounds.width,
height: winBounds.height,
maximized: win.isMaximized(),
};
return state;
} catch (err) {
return false;
}
},
saveStateToStorage(winState) {
fs.writeFile(this.getStateFile(), JSON.stringify(winState), (err) => {});
},
getStateFile() {
const userPath = app.getPath('userData');
const fileName = 'ardm-win-state.json';
return path.join(userPath, fileName);
},
parseJson(str) {
let json = false;
try {
json = JSON.parse(str);
} catch (err) {}
return json;
},
};
module.exports = winState;
|
2301_77204479/AnotherRedisDesktopManager
|
pack/electron/win-state.js
|
JavaScript
|
mit
| 2,740
|
const { notarize } = require('@electron/notarize');
exports.default = async function notarizing(context) {
const { electronPlatformName, appOutDir } = context;
if (electronPlatformName !== 'darwin') {
return;
}
const appName = context.packager.appInfo.productFilename;
return await notarize({
appBundleId: 'me.qii404.another-redis-desktop-manager',
appPath: `${appOutDir}/${appName}.app`,
appleId: process.env.APPLEID,
appleIdPassword: process.env.APPLEID_PASSWORD,
teamId: '68JN8DV835',
});
};
|
2301_77204479/AnotherRedisDesktopManager
|
pack/scripts/notarize.js
|
JavaScript
|
mit
| 534
|
<template>
<el-container class="wrap-container" spellcheck="false">
<!-- left aside draggable container -->
<div class="aside-drag-container" :style="{width: sideWidth + 'px'}">
<!-- connections -->
<el-aside class="aside-connection">
<Aside></Aside>
</el-aside>
<!-- drag area -->
<div id="drag-resize-container">
<div id="drag-resize-pointer"></div>
</div>
</div>
<!-- right main container -->
<el-container class='right-main-container'>
<!-- tab container -->
<el-main class='main-tabs-container'>
<Tabs></Tabs>
</el-main>
</el-container>
<UpdateCheck></UpdateCheck>
</el-container>
</template>
<script>
import Aside from '@/Aside';
import Tabs from '@/components/Tabs';
import UpdateCheck from '@/components/UpdateCheck';
import addon from './addon';
export default {
name: 'App',
data() {
return {
sideWidth: 265,
};
},
created() {
this.$bus.$on('reloadSettings', () => {
addon.reloadSettings();
});
// restore side bar width
this.restoreSideBarWidth();
},
components: { Aside, Tabs, UpdateCheck },
methods: {
bindSideBarDrag() {
const that = this;
const dragPointer = document.getElementById('drag-resize-pointer');
function mousemove(e) {
const mouseX = e.x;
const dragSideWidth = mouseX - 17;
if ((dragSideWidth > 200) && (dragSideWidth < 1500)) {
that.sideWidth = dragSideWidth;
}
}
function mouseup(e) {
document.documentElement.removeEventListener('mousemove', mousemove);
document.documentElement.removeEventListener('mouseup', mouseup);
// store side bar with
localStorage.sideWidth = that.sideWidth;
}
dragPointer.addEventListener('mousedown', (e) => {
e.preventDefault();
document.documentElement.addEventListener('mousemove', mousemove);
document.documentElement.addEventListener('mouseup', mouseup);
});
},
restoreSideBarWidth() {
const { sideWidth } = localStorage;
sideWidth && (this.sideWidth = sideWidth);
},
},
mounted() {
setTimeout(() => {
this.$bus.$emit('update-check');
}, 2000);
this.bindSideBarDrag();
// addon init setup
addon.setup();
},
};
</script>
<style type="text/css">
html {
height: 100%;
}
body {
height: 100%;
padding: 8px;
margin: 0;
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
/*fix body scroll-y caused by tooltip in table*/
overflow: hidden;
}
button, input, textarea, .vjs__tree {
font-family: inherit !important;
}
a {
color: #8e8d8d;
}
/*fix el-select bottom scroll bar*/
.el-scrollbar__wrap {
overflow-x: hidden;
}
/*scrollbar style start*/
::-webkit-scrollbar {
width: 9px;
}
/*track*/
::-webkit-scrollbar-track {
background: #eaeaea;
border-radius: 4px;
}
.dark-mode ::-webkit-scrollbar-track {
background: #425057;
}
/*track hover*/
::-webkit-scrollbar-track:hover {
background: #e0e0dd;
}
.dark-mode ::-webkit-scrollbar-track:hover {
background: #495961;
}
/*thumb*/
::-webkit-scrollbar-thumb {
border-radius: 8px;
background: #c1c1c1;
}
.dark-mode ::-webkit-scrollbar-thumb {
background: #5a6f7a;
}
/*thumb hover*/
::-webkit-scrollbar-thumb:hover {
background: #7f7f7f;
}
.dark-mode ::-webkit-scrollbar-thumb:hover {
background: #6a838f;
}
/*scrollbar style end*/
/*list index*/
li .list-index {
color: #828282;
/*font-size: 80%;*/
user-select: none;
margin-right: 10px;
min-width: 28px;
}
.dark-mode li .list-index {
color: #adacac;
}
.wrap-container {
height: 100%;
}
.aside-drag-container {
position: relative;
user-select: none;
/*max-width: 50%;*/
}
.aside-connection {
height: 100%;
width: 100% !important;
border-right: 1px solid #e4e0e0;
overflow: hidden;
}
/*fix right container imdraggable*/
.right-main-container {
width: 10%;
}
.right-main-container .main-tabs-container {
overflow-y: hidden;
padding-top: 0px;
padding-right: 4px;
}
.el-message-box .el-message-box__message {
word-break: break-all;
overflow-y: auto;
max-height: 80vh;
}
#drag-resize-container {
position: absolute;
/*height: 100%;*/
width: 10px;
right: -12px;
top: 0px;
}
#drag-resize-pointer {
position: fixed;
height: 100%;
width: 10px;
cursor: col-resize;
}
#drag-resize-pointer::after {
content: "";
display: inline-block;
width: 2px;
height: 20px;
border-left: 1px solid #adabab;
border-right: 1px solid #adabab;
position: absolute;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
.dark-mode #drag-resize-pointer::after {
border-left: 1px solid #b9b8b8;
border-right: 1px solid #b9b8b8;
}
@keyframes rotate {
to{ transform: rotate(360deg); }
}
/*vxe-table dark-mode color*/
html .dark-mode {
--vxe-ui-table-header-background-color: #273239 !important;
--vxe-ui-layout-background-color: #273239 !important;
--vxe-ui-table-row-striped-background-color: #3b4b54 !important;
--vxe-ui-table-row-hover-background-color: #3b4b54 !important;
--vxe-ui-table-row-hover-striped-background-color: #50646f !important;
/*border color*/
--vxe-ui-table-border-color: #7f8ea5 !important;
/*font color*/
--vxe-ui-font-color: #f3f3f4 !important;
--vxe-ui-table-header-font-color: #f3f3f4 !important;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/App.vue
|
Vue
|
mit
| 5,387
|
<template>
<div class="aside-outer-container">
<div>
<!-- new connection button -->
<div class="aside-top-container">
<el-button class='aside-setting-btn' type="primary" icon="el-icon-time" @click="$refs.commandLogDialog.show()" :title='$t("message.command_log")+" Ctrl+g"' plain></el-button>
<el-button class='aside-setting-btn' type="primary" icon="el-icon-setting" @click="$refs.settingDialog.show()" :title='$t("message.settings")+" Ctrl+,"' plain></el-button>
<div class="aside-new-connection-container">
<el-button class="aside-new-connection-btn" type="info" @click="addNewConnection" icon="el-icon-circle-plus" :title='$t("message.new_connection")+" Ctrl+n"'>{{ $t('message.new_connection') }}</el-button>
</div>
</div>
<!-- new connection dialog -->
<NewConnectionDialog
@editConnectionFinished="editConnectionFinished"
ref="newConnectionDialog">
</NewConnectionDialog>
<!-- user settings -->
<Setting ref="settingDialog"></Setting>
<!-- redis command logs -->
<CommandLog ref='commandLogDialog'></CommandLog>
<!-- hot key tips dialog -->
<HotKeys ref='hotKeysDialog'></HotKeys>
<!-- custom shell formatter -->
<CustomFormatter></CustomFormatter>
</div>
<!-- connection list -->
<Connections ref="connections"></Connections>
</div>
</template>
<script type="text/javascript">
import Setting from '@/components/Setting';
import Connections from '@/components/Connections';
import NewConnectionDialog from '@/components/NewConnectionDialog';
import CommandLog from '@/components/CommandLog';
import HotKeys from '@/components/HotKeys';
import CustomFormatter from '@/components/CustomFormatter';
export default {
data() {
return {};
},
components: {
Connections, NewConnectionDialog, Setting, CommandLog, HotKeys, CustomFormatter,
},
methods: {
editConnectionFinished() {
this.$refs.connections.initConnections();
},
addNewConnection() {
this.$refs.newConnectionDialog.show();
},
initShortcut() {
// new connection
this.$shortcut.bind('ctrl+n, ⌘+n', () => {
this.$refs.newConnectionDialog.show();
return false;
});
// settings
this.$shortcut.bind('ctrl+,', () => {
this.$refs.settingDialog.show();
return false;
});
this.$shortcut.bind('⌘+,', () => {
this.$refs.settingDialog.show();
return false;
});
// logs
this.$shortcut.bind('ctrl+g, ⌘+g', () => {
this.$refs.commandLogDialog.show();
return false;
});
},
},
mounted() {
this.initShortcut();
},
};
</script>
<style type="text/css">
.aside-top-container {
margin-right: 8px;
}
.aside-top-container .aside-new-connection-container {
margin-right: 109px;
}
.aside-new-connection-container .aside-new-connection-btn {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
.aside-top-container .aside-setting-btn {
float: right;
width: 44px;
margin-right: 5px;
}
.dark-mode .aside-top-container .el-button--info {
color: #52a6fd;
background: inherit;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/Aside.vue
|
Vue
|
mit
| 3,253
|
import getopts from 'getopts';
import { ipcRenderer } from 'electron';
import bus from './bus';
import storage from './storage';
export default {
setup() {
// reload settings when init
this.reloadSettings();
// init args start from cli
this.bindCliArgs();
// bing href click
this.openHrefInBrowser();
},
reloadSettings() {
this.initFont();
this.initZoom();
},
initFont() {
const fontFamily = storage.getFontFamily();
document.body.style.fontFamily = fontFamily;
// tell monaco editor
bus.$emit('fontInited', fontFamily);
},
initZoom() {
let zoomFactor = storage.getSetting('zoomFactor');
zoomFactor = zoomFactor || 1.0;
const { webFrame } = require('electron');
webFrame.setZoomFactor(zoomFactor);
},
openHrefInBrowser() {
const { shell } = require('electron');
document.addEventListener('click', (event) => {
const ele = event.target;
if (ele && (ele.nodeName.toLowerCase() === 'a') && ele.href.startsWith('http')) {
event.preventDefault();
shell.openExternal(ele.href);
}
});
},
bindCliArgs() {
ipcRenderer.invoke('getMainArgs').then((result) => {
if (!result.argv) {
return;
}
const mainArgs = getopts(result.argv);
if (!mainArgs.host) {
return;
}
// common args
const connection = {
host: mainArgs.host,
port: mainArgs.port ? mainArgs.port : 6379,
auth: mainArgs.auth,
username: mainArgs.username,
name: mainArgs.name,
separator: mainArgs.separator,
connectionReadOnly: mainArgs.readonly,
};
// cluster args
if (mainArgs.cluster) {
connection.cluster = true;
}
// ssh args
if (mainArgs['ssh-host'] && mainArgs['ssh-username']) {
const sshOptions = {
host: mainArgs['ssh-host'],
port: mainArgs['ssh-port'] ? mainArgs['ssh-port'] : 22,
username: mainArgs['ssh-username'],
password: mainArgs['ssh-password'],
privatekey: mainArgs['ssh-private-key'],
passphrase: mainArgs['ssh-passphrase'],
timeout: mainArgs['ssh-timeout'],
};
connection.sshOptions = sshOptions;
}
// sentinel args
if (mainArgs['sentinel-master-name']) {
const sentinelOptions = {
masterName: mainArgs['sentinel-master-name'],
nodePassword: mainArgs['sentinel-node-password'],
};
connection.sentinelOptions = sentinelOptions;
}
// ssl args
if (mainArgs.ssl) {
const sslOptions = {
key: mainArgs['ssl-key'],
ca: mainArgs['ssl-ca'],
cert: mainArgs['ssl-cert'],
};
connection.sslOptions = sslOptions;
}
// add to storage
storage.addConnection(connection);
bus.$emit('refreshConnections');
// open connection after added
setTimeout(() => {
bus.$emit('openConnection', connection.name);
// tmp connection, delete it after opened
if (!mainArgs.save) {
storage.deleteConnection(connection);
}
}, 300);
});
},
};
|
2301_77204479/AnotherRedisDesktopManager
|
src/addon.js
|
JavaScript
|
mit
| 3,200
|
import Vue from 'vue';
const eventHub = new Vue();
export default {
$on(...event) {
eventHub.$on(...event);
},
$off(...event) {
eventHub.$off(...event);
},
$once(...event) {
eventHub.$once(...event);
},
$emit(...event) {
eventHub.$emit(...event);
},
};
|
2301_77204479/AnotherRedisDesktopManager
|
src/bus.js
|
JavaScript
|
mit
| 287
|
const adminCMD = {
ACL: ['ACL CAT [categoryname]', 'ACL DELUSER username [username ...]', 'ACL DRYRUN username command [arg [arg ...]]', 'ACL GENPASS [bits]', 'ACL GETUSER username', 'ACL LIST', 'ACL LOAD', 'ACL LOG [count|RESET]', 'ACL SAVE', 'ACL SETUSER username [rule [rule ...]]', 'ACL USERS', 'ACL WHOAMI'],
BGREWRITEAOF: 'BGREWRITEAOF',
BGSAVE: 'BGSAVE',
CLIENT: ['CLIENT LIST [TYPE normal|master|replica|pubsub]', 'CLIENT GETNAME', 'CLIENT REPLY ON|OFF|SKIP', 'CLIENT ID'],
CLUSTER: ['CLUSTER COUNT-FAILURE-REPORTS node-id', 'CLUSTER COUNTKEYSINSLOT slot', 'CLUSTER GETKEYSINSLOT slot count', 'CLUSTER INFO', 'CLUSTER KEYSLOT key', 'CLUSTER NODES', 'CLUSTER SLAVES node-id', 'CLUSTER REPLICAS node-id', 'CLUSTER SLOTS'],
CONFIG: ['CONFIG GET parameter', 'CONFIG SET parameter value', 'CONFIG RESETSTAT'],
DEBUG: ['DEBUG OBJECT key', 'DEBUG SEGFAULT'],
FAILOVER: 'FAILOVER [TO host port [FORCE]] [ABORT] [TIMEOUT milliseconds]',
LATENCY: ['LATENCY DOCTOR', 'LATENCY GRAPH event', 'LATENCY HISTOGRAM [command [command ...]]', 'LATENCY HISTORY event', 'LATENCY LATEST', 'LATENCY RESET [event [event ...]]'],
MODULE: ['MODULE LIST', 'MODULE LOAD path [arg [arg ...]]', 'MODULE UNLOAD name'],
MONITOR: 'MONITOR',
PFDEBUG: 'PFDEBUG',
PFSELFTEST: 'PFSELFTEST',
PSYNC: 'PSYNC replicationid offset',
REPLCONF: 'REPLCONF',
REPLICAOF: 'REPLICAOF host port',
SAVE: 'SAVE',
SHUTDOWN: 'SHUTDOWN [NOSAVE|SAVE] [NOW] [FORCE] [ABORT]',
SLAVEOF: 'SLAVEOF host port',
SLOWLOG: 'SLOWLOG subcommand [argument]',
SYNC: 'SYNC',
};
const readCMD = {
AUTH: 'AUTH password',
BITCOUNT: 'BITCOUNT key [start] [end]',
BITOP: 'BITOP operation destkey key [key ...]',
BITPOS: 'BITPOS key bit [start] [end]',
COMMAND: ['COMMAND COUNT', 'COMMAND GETKEYS', 'COMMAND INFO command-name [command-name ...]'],
DBSIZE: 'DBSIZE',
DISCARD: 'DISCARD',
DUMP: 'DUMP key',
ECHO: 'ECHO message',
EXEC: 'EXEC',
EXISTS: 'EXISTS key',
GET: 'GET key',
GETBIT: 'GETBIT key offset',
GETRANGE: 'GETRANGE key start end',
HEXISTS: 'HEXISTS key field',
HGET: 'HGET key field',
HGETALL: 'HGETALL key',
HKEYS: 'HKEYS key',
HLEN: 'HLEN key',
HMGET: 'HMGET key field [field ...]',
HSCAN: 'HSCAN key cursor [MATCH pattern] [COUNT count]',
HVALS: 'HVALS key',
INFO: 'INFO [section]',
KEYS: 'KEYS pattern',
LASTSAVE: 'LASTSAVE',
LINDEX: 'LINDEX key index',
LLEN: 'LLEN key',
LRANGE: 'LRANGE key start stop',
MGET: 'MGET key [key ...]',
MULTI: 'MULTI',
OBJECT: ['OBJECT ENCODING key', 'OBJECT FREQ key', 'OBJECT IDLETIME key', 'OBJECT REFCOUNT key'],
PING: 'PING [message]',
PUBSUB: ['PUBSUB CHANNELS [pattern]', 'PUBSUB NUMSUB [channel-1 ...]', 'PUBSUB NUMPAT'],
PSUBSCRIBE: 'PSUBSCRIBE pattern [pattern ...]',
PTTL: 'PTTL key',
PUNSUBSCRIBE: 'PUNSUBSCRIBE [pattern ...]',
RANDOMKEY: 'RANDOMKEY',
ROLE: 'ROLE',
SCAN: 'SCAN cursor [MATCH pattern] [COUNT count]',
SCARD: 'SCARD key',
SDIFF: 'SDIFF key [key ...]',
SELECT: 'SELECT index',
SINTER: 'SINTER key [key ...]',
SISMEMBER: 'SISMEMBER key member',
SMEMBERS: 'SMEMBERS key',
SRANDMEMBER: 'SRANDMEMBER key [count]',
SSCAN: 'SSCAN key cursor [MATCH pattern] [COUNT count]',
STRLEN: 'STRLEN key',
SUBSCRIBE: 'SUBSCRIBE channel [channel ...]',
SUNION: 'SUNION key [key ...]',
TIME: 'TIME',
TTL: 'TTL key',
TYPE: 'TYPE key',
UNSUBSCRIBE: 'UNSUBSCRIBE [channel ...]',
UNWATCH: 'UNWATCH',
WATCH: 'WATCH key [key ...]',
ZCARD: 'ZCARD key',
ZCOUNT: 'ZCOUNT key min max',
ZLEXCOUNT: 'ZLEXCOUNT key min max',
ZRANGE: 'ZRANGE key start stop [WITHSCORES]',
ZRANGEBYLEX: 'ZRANGEBYLEX key min max [LIMIT offset count]',
ZRANGEBYSCORE: 'ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]',
ZRANK: 'ZRANK key member',
ZREVRANGE: 'ZREVRANGE key start stop [WITHSCORES]',
ZREVRANGEBYLEX: 'ZREVRANGEBYLEX key max min [LIMIT offset count]',
ZREVRANGEBYSCORE: 'ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]',
ZREVRANK: 'ZREVRANK key member',
ZSCAN: 'ZSCAN key cursor [MATCH pattern] [COUNT count]',
ZSCORE: 'ZSCORE key member',
GEOHASH: 'GEOHASH key member [member ...]',
GEOPOS: 'GEOPOS key member [member ...]',
GEODIST: 'GEODIST key member1 member2 [unit]',
HSTRLEN: 'HSTRLEN key field',
MEMORY: ['MEMORY DOCTOR', 'MEMORY HELP', 'MEMORY MALLOC-STATS', 'MEMORY STATS', 'MEMORY USAGE key [SAMPLES count]'],
XINFO: 'XINFO [CONSUMERS key groupname] [GROUPS key] [STREAM key] [HELP]',
XRANGE: 'XRANGE key start end [COUNT count]',
XREVRANGE: 'XREVRANGE key end start [COUNT count]',
XLEN: 'XLEN key',
XREAD: 'XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...]',
XREADGROUP: 'XREADGROUP GROUP group consumer [COUNT count] [BLOCK milliseconds] [NOACK] STREAMS key [key ...] ID [ID ...]',
XPENDING: 'XPENDING key group [start end count] [consumer]',
};
const writeCMD = {
APPEND: 'APPEND key value',
BLMOVE: 'BLMOVE source destination LEFT|RIGHT LEFT|RIGHT timeout',
BLPOP: 'BLPOP key [key ...] timeout',
BRPOP: 'BRPOP key [key ...] timeout',
BRPOPLPUSH: 'BRPOPLPUSH source destination timeout',
BZPOPMAX: 'BZPOPMAX key [key ...] timeout',
BZPOPMIN: 'BZPOPMIN key [key ...] timeout',
COPY: 'COPY source destination [DB destination-db] [REPLACE]',
DECR: 'DECR key',
DECRBY: 'DECRBY key decrement',
DEL: 'DEL key [key ...]',
EVAL: 'EVAL script numkeys key [key ...] arg [arg ...]',
EVALSHA: 'EVALSHA sha1 numkeys key [key ...] arg [arg ...]',
EXPIRE: 'EXPIRE key seconds',
EXPIREAT: 'EXPIREAT key timestamp',
FLUSHALL: 'FLUSHALL',
FLUSHDB: 'FLUSHDB',
GEOADD: 'GEOADD key [NX|XX] [CH] longitude latitude member [longitude latitude member ...]',
GETDEL: 'GETDEL key',
GETSET: 'GETSET key value',
HDEL: 'HDEL key field [field ...]',
HINCRBY: 'HINCRBY key field increment',
HINCRBYFLOAT: 'HINCRBYFLOAT key field increment',
HMSET: 'HMSET key field value [field value ...]',
HSET: 'HSET key field value',
HSETNX: 'HSETNX key field value',
INCR: 'INCR key',
INCRBY: 'INCRBY key increment',
INCRBYFLOAT: 'INCRBYFLOAT key increment',
LINSERT: 'LINSERT key BEFORE|AFTER pivot value',
LMOVE: 'LMOVE source destination LEFT|RIGHT LEFT|RIGHT',
LPOP: 'LPOP key',
LPUSH: 'LPUSH key value [value ...]',
LPUSHX: 'LPUSHX key value',
LREM: 'LREM key count value',
LSET: 'LSET key index value',
LTRIM: 'LTRIM key start stop',
MIGRATE: 'MIGRATE host port key destination-db timeout',
MOVE: 'MOVE key db',
MSET: 'MSET key value [key value ...]',
MSETNX: 'MSETNX key value [key value ...]',
PERSIST: 'PERSIST key',
PEXPIRE: 'PEXPIRE key milliseconds',
PEXPIREAT: 'PEXPIREAT key milliseconds-timestamp',
PSETEX: 'PSETEX key milliseconds value',
PUBLISH: 'PUBLISH channel message',
RENAME: 'RENAME key newkey',
RENAMENX: 'RENAMENX key newkey',
RESTORE: 'RESTORE key ttl serialized-value',
RPOP: 'RPOP key',
RPOPLPUSH: 'RPOPLPUSH source destination',
RPUSH: 'RPUSH key value [value ...]',
RPUSHX: 'RPUSHX key value',
SADD: 'SADD key member [member ...]',
SCRIPT: ['SCRIPT EXISTS script [script ...]', 'SCRIPT FLUSH', 'SCRIPT KILL', 'SCRIPT LOAD script'],
SDIFFSTORE: 'SDIFFSTORE destination key [key ...]',
SET: 'SET key value',
SETBIT: 'SETBIT key offset value',
SETEX: 'SETEX key seconds value',
SETNX: 'SETNX key value',
SETRANGE: 'SETRANGE key offset value',
SINTERSTORE: 'SINTERSTORE destination key [key ...]',
SMOVE: 'SMOVE source destination member',
SORT: 'SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]',
SPOP: 'SPOP key',
SREM: 'SREM key member [member ...]',
SUNIONSTORE: 'SUNIONSTORE destination key [key ...]',
SWAPDB: 'SWAPDB index1 index2',
UNLINK: 'UNLINK key [key ...]',
XADD: 'XADD key ID field string [field string ...]',
XDEL: 'XDEL key ID [ID ...]',
XGROUP: ['XGROUP CREATE key groupname id|$ [MKSTREAM]', 'XGROUP CREATECONSUMER key groupname consumername', 'XGROUP DELCONSUMER key groupname consumername', 'XGROUP DESTROY key groupname', 'XGROUP SETID key groupname id|$'],
XTRIM: 'XTRIM key MAXLEN [~] count',
ZADD: 'ZADD key score member [score] [member]',
ZDIFFSTORE: 'ZDIFFSTORE destination numkeys key [key ...]',
ZINCRBY: 'ZINCRBY key increment member',
ZINTERSTORE: 'ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]',
ZPOPMAX: 'ZPOPMAX key [count]',
ZPOPMIN: 'ZPOPMIN key [count]',
ZRANGESTORE: 'ZRANGESTORE dst src min max [BYSCORE|BYLEX] [REV] [LIMIT offset count]',
ZREM: 'ZREM key member [member ...]',
ZREMRANGEBYLEX: 'ZREMRANGEBYLEX key min max',
ZREMRANGEBYRANK: 'ZREMRANGEBYRANK key start stop',
ZREMRANGEBYSCORE: 'ZREMRANGEBYSCORE key min max',
ZUNIONSTORE: 'ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]',
};
module.exports = {
allCMD: { ...adminCMD, ...readCMD, ...writeCMD },
writeCMD,
};
|
2301_77204479/AnotherRedisDesktopManager
|
src/commands.js
|
JavaScript
|
mit
| 8,979
|
<template>
<div class="cli-content-container">
<!-- monaco editor div -->
<div class="monaco-editor-con" ref="editor"></div>
</div>
</template>
<script type="text/javascript">
// import * as monaco from 'monaco-editor';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
export default {
props: {
content: { type: String, default: () => {} },
},
created() {
// listen font family change and reset options
// to avoid cursor offset
this.$bus.$on('fontInited', this.changeFont);
},
watch: {
// refresh
content(newVal) {
this.monacoEditor.setValue(newVal);
},
},
methods: {
changeFont(fontFamily) {
this.monacoEditor && this.monacoEditor.updateOptions({
fontFamily,
});
},
scrollToBottom() {
this.monacoEditor.revealLine(this.monacoEditor.getModel().getLineCount());
},
},
mounted() {
this.monacoEditor = monaco.editor.create(
this.$refs.editor,
{
value: this.content,
theme: 'vs-dark',
language: 'plaintext',
links: false,
readOnly: true,
cursorStyle: 'underline-thin',
lineNumbers: 'off',
contextmenu: false,
// set fontsize and family to avoid cursor offset
fontSize: 14,
fontFamily: this.$storage.getFontFamily(),
showFoldingControls: 'always',
// auto layout, performance cost
automaticLayout: true,
wordWrap: 'on',
// wordWrapColumn: 120,
// long text indent when wrapped
wrappingIndent: 'none',
// cursor line highlight
renderLineHighlight: 'none',
// highlight word when cursor in
occurrencesHighlight: false,
// disable scroll one page at last line
scrollBeyondLastLine: false,
// hide scroll sign of current line
hideCursorInOverviewRuler: true,
minimap: {
enabled: false,
},
// vertical line
guides: {
indentation: false,
highlightActiveIndentation: false,
},
scrollbar: {
useShadows: false,
verticalScrollbarSize: '9px',
horizontalScrollbarSize: '9px',
},
},
);
// hide tooltip in readonly mode
const messageContribution = this.monacoEditor.getContribution('editor.contrib.messageController');
this.monacoEditor.onDidAttemptReadOnlyEdit(() => {
messageContribution.dispose();
});
},
destroyed() {
this.monacoEditor.dispose();
this.$bus.$off('fontInited', this.changeFont);
},
};
</script>
<style type="text/css">
.cli-content-container .monaco-editor-con {
min-height: 150px;
height: calc(100vh - 160px);
clear: both;
overflow: hidden;
background: #263238;
border: 1px solid #e4e7ed;
border-bottom: 0px;
border-radius: 4px 4px 0 0;
}
.dark-mode .cli-content-container .monaco-editor-con {
background: #324148;
border-color: #7f8ea5;
}
/* font color*/
.cli-content-container .monaco-editor-con .mtk1 {
color: #d3d5d9;
}
.dark-mode .cli-content-container .monaco-editor-con .mtk1 {
color: #e8e8e8;
}
/*hide cursor*/
.cli-content-container .monaco-editor .cursors-layer > .cursor {
display: none !important;
}
/*change default scrollbar style*/
.cli-content-container .monaco-editor .scrollbar {
background: #eaeaea;
border-radius: 4px;
}
.dark-mode .cli-content-container .monaco-editor .scrollbar {
background: #425057;
}
.cli-content-container .monaco-editor .scrollbar:hover {
background: #e0e0dd;
}
.dark-mode .cli-content-container .monaco-editor .scrollbar:hover {
background: #495961;
}
.cli-content-container .monaco-editor-con .monaco-editor .slider {
border-radius: 4px;
background: #c1c1c1;
}
.dark-mode .cli-content-container .monaco-editor-con .monaco-editor .slider {
background: #5a6f7a;
}
.cli-content-container .monaco-editor-con .monaco-editor .slider:hover {
background: #7f7f7f;
}
.dark-mode .cli-content-container .monaco-editor-con .monaco-editor .slider:hover {
background: #6a838f;
}
/*remove background color*/
.cli-content-container .monaco-editor .margin {
background-color: inherit;
}
.cli-content-container .monaco-editor-con .monaco-editor,
.cli-content-container .monaco-editor-con .monaco-editor-background,
.cli-content-container .monaco-editor-con .monaco-editor .inputarea.ime-input {
background-color: inherit;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/CliContent.vue
|
Vue
|
mit
| 4,555
|
<template>
<div>
<el-form @submit.native.prevent>
<el-form-item>
<!-- content textarea -->
<!-- <el-input
ref="cliContent"
type="textarea"
:value="contentStr"
rows='22'
:disabled="true"
:readonly="true"
id='cli-content'>
</el-input> -->
<CliContent ref="editor" :content="contentStr"></CliContent>
<!-- input params -->
<el-autocomplete
class="input-suggestion"
autocomplete="off"
v-model="params"
:debounce='10'
:disabled='subscribeMode || monitorMode'
:fetch-suggestions="inputSuggestion"
:placeholder="$t('message.enter_to_exec')"
:select-when-unmatched="true"
:trigger-on-focus="false"
popper-class="cli-console-suggestion"
ref="cliParams"
@select='$refs.cliParams.focus()'
@keyup.enter.native="consoleExec"
@keyup.up.native="searchUp"
@keyup.down.native="searchDown">
</el-autocomplete>
</el-form-item>
</el-form>
<el-button v-if='subscribeMode' @click='stopSubscribe' type='danger' class='stop-subscribe'>Stop Subscribe</el-button>
<el-button v-else-if='monitorMode' @click='stopMonitor' type='danger' class='stop-subscribe'>Stop Monitor</el-button>
</div>
</template>
<script type="text/javascript">
import { allCMD } from '@/commands';
import splitargs from '@qii404/redis-splitargs';
import { ipcRenderer } from 'electron';
import CliContent from '@/components/CliContent';
export default {
data() {
return {
params: '',
content: [],
historyIndex: 0,
inputSuggestionItems: [],
multiQueue: null,
subscribeMode: false,
monitorMode: false,
maxHistory: 2000,
};
},
props: ['client', 'hotKeyScope'],
components: { CliContent },
computed: {
paramsTrim() {
return this.params.replace(/^\s+|\s+$/g, '');
},
paramsArr() {
try {
// buf array
const paramsArr = splitargs(this.paramsTrim, true);
// command to string
paramsArr[0] = paramsArr[0].toString().toLowerCase();
return paramsArr;
} catch (e) {
return [this.paramsTrim];
}
},
contentStr() {
if (this.content.length > this.maxHistory) {
// this.content = this.content.slice(-this.maxHistory);
this.content.splice(0, this.content.length - this.maxHistory);
}
return `${this.content.join('\n')}\n`;
},
},
created() {
this.$bus.$on('changeDb', (client, dbIndex) => {
if (!this.anoClient || client.options.connectionName != this.anoClient.options.connectionName) {
return;
}
if (this.anoClient.condition.select == dbIndex) {
return;
}
this.anoClient.select(dbIndex);
});
},
methods: {
initShow() {
if (!this.client) {
return;
}
// copy to another client
this.anoClient = this.client.duplicate();
// bind subscribe messages
this.bindSubscribeMessage();
this.anoClient.on('ready', () => {
!this.anoClient.cliInited && this.initCliContent();
this.anoClient.cliInited = true;
});
this.$nextTick(() => {
this.$refs.cliParams.focus();
});
},
initCliContent() {
this.content.push(`\n> ${this.anoClient.options.connectionName} connected!`);
this.scrollToBottom();
},
tabClick() {
this.$nextTick(() => {
this.$refs.cliParams.focus();
});
},
inputSuggestion(input, cb) {
// tmp store cb
this.cb = cb;
if (!this.paramsTrim) {
cb([]);
return;
}
let items = this.inputSuggestionItems.filter(item => item.toLowerCase().indexOf(input.toLowerCase()) !== -1);
// add cmd tips
items = this.addCMDTips(items);
const suggestions = [...new Set(items)].map(item => ({ value: item }));
cb(suggestions);
},
addCMDTips(items = []) {
const { paramsArr } = this;
const paramsLen = paramsArr.length;
const cmd = paramsArr[0].toUpperCase();
if (!cmd) {
return items;
}
for (const key in allCMD) {
if (key.startsWith(cmd)) {
const tip = allCMD[key];
// single tip
if (typeof tip === 'string') {
items.unshift(tip);
}
// with sub commands, such as CONFIG SET/GET...
else {
items = tip.concat(items);
}
}
}
return items;
},
bindSubscribeMessage() {
// bind subscribe message
this.anoClient.on('message', (channel, message) => {
this.scrollToBottom(`\n${channel}\n${message}`);
});
// bind psubscribe message
this.anoClient.on('pmessage', (pattern, channel, message) => {
this.scrollToBottom(`\n${pattern}\n${channel}\n${message}`);
});
},
stopSubscribe() {
this.subscribeMode = false;
const subSet = this.anoClient.condition.subscriber.set;
if (!subSet) {
return;
}
Object.keys(subSet.subscribe).length && this.anoClient.unsubscribe();
Object.keys(subSet.psubscribe).length && this.anoClient.punsubscribe();
},
stopMonitor() {
this.monitorMode = false;
this.monitorInstance && this.monitorInstance.disconnect();
},
consoleExec() {
const params = this.paramsTrim;
const { paramsArr } = this;
this.params = '';
this.content.push(`> ${params}`);
// append to history command
this.appendToHistory(params);
if (paramsArr[0] == 'exit' || paramsArr[0] == 'quit') {
return this.$bus.$emit('removePreTab');
}
if (paramsArr[0] == 'clear') {
return this.content = [];
}
// mock help command
if (paramsArr[0] == 'help') {
return this.scrollToBottom('Input your command and select from tips');
}
// multi-exec mode
if (paramsArr[0] == 'multi') {
this.multiQueue = [];
return this.scrollToBottom('OK');
}
// multi-discard-mode
if (paramsArr[0] == 'discard') {
// discard when not multi condition
if (!Array.isArray(this.multiQueue)) {
return this.scrollToBottom('(error) ERR DISCARD without MULTI');
}
this.multiQueue = null;
return this.scrollToBottom('OK');
}
// multi dequeue
if (paramsArr[0] == 'exec') {
// exec when not multi condition
if (!Array.isArray(this.multiQueue)) {
return this.scrollToBottom('(error) ERR EXEC without MULTI');
}
this.anoClient.multi(this.multiQueue).execBuffer((err, reply) => {
if (err) {
this.content.push(`${err}`);
} else {
this.content.push(this.resolveResult(reply).trim());
}
this.scrollToBottom();
});
return this.multiQueue = null;
}
// multi enqueue
if (Array.isArray(this.multiQueue)) {
this.multiQueue.push(['callBuffer', paramsArr[0], ...paramsArr.slice(1)]);
return this.scrollToBottom('QUEUED');
}
// subscribe command
if (/subscribe/.test(paramsArr[0])) {
this.subscribeMode = true;
}
// monitor command
if (paramsArr[0] == 'monitor') {
this.anoClient.monitor().then((monitor) => {
this.monitorMode = true;
this.scrollToBottom('OK');
this.monitorInstance = monitor;
this.monitorInstance.on('monitor', (time, args, source, database) => {
this.scrollToBottom(`${time} [${database} ${source}] ${args.join(' ')}`);
});
});
return;
}
// normal command
const promise = this.anoClient.callBuffer(paramsArr[0], paramsArr.slice(1));
// normal command promise
promise.then((reply) => {
this.content.push(this.resolveResult(reply).trim());
this.execFinished(paramsArr);
this.scrollToBottom();
}).catch((err) => {
this.multiQueue = null;
this.scrollToBottom(err.message);
});
},
execFinished(params) {
const operate = params[0].toLowerCase();
if (operate === 'select' && !isNaN(params[1])) {
this.$bus.$emit('changeDb', this.anoClient, params[1]);
}
// operate may add new key, refresh left key list
if (['hmset', 'hset', 'lpush', 'rpush', 'set', 'sadd', 'zadd', 'xadd', 'json.set'].includes(operate)) {
this.$bus.$emit('refreshKeyList', this.client, Buffer.from(params[1]), 'add');
}
if (['del'].includes(operate)) {
this.$bus.$emit('refreshKeyList', this.client, Buffer.from(params[1]), 'del');
}
},
scrollToBottom(append = '') {
append && (this.content.push(`${append}`));
this.$nextTick(() => {
if (this.$refs.editor) {
return this.$refs.editor.scrollToBottom();
}
if (!this.$refs.cliContent) {
return;
}
const textarea = this.$refs.cliContent.$el.firstChild;
textarea.scrollTop = textarea.scrollHeight;
});
},
appendToHistory(params) {
if (!params || !params.length) {
return;
}
const items = this.inputSuggestionItems;
if (items[items.length - 1] !== params) {
items.push(params);
}
this.historyIndex = items.length;
},
resolveResult(result) {
let append = '';
// list or dict
if (typeof result === 'object' && result !== null && !Buffer.isBuffer(result)) {
const isArray = Array.isArray(result);
for (const i in result) {
// list or dict
if (typeof result[i] === 'object' && result[i] !== null && !Buffer.isBuffer(result[i])) {
// fix ioredis pipline result such as [[null, "v1"], [null, "v2"]]
// null is the result, and v1 is the value
if (result[i][0] === null) {
append += this.resolveResult(result[i][1]);
} else {
append += this.resolveResult(result[i]);
}
}
// string buffer null
else {
append += `${(isArray ? '' : (`${this.$util.bufToString(i)}\n`))
+ this.$util.bufToString(result[i])}\n`;
}
}
}
// string buffer null
else {
append = `${this.$util.bufToString(result)}\n`;
}
return append;
},
searchUp() {
if (this.suggesttionShowing()) {
return;
}
(--this.historyIndex < 0) && (this.historyIndex = 0);
if (!this.inputSuggestionItems[this.historyIndex]) {
this.params = '';
return;
}
this.params = this.inputSuggestionItems[this.historyIndex];
},
searchDown() {
if (this.suggesttionShowing()) {
return;
}
if (++this.historyIndex > this.inputSuggestionItems.length) {
this.historyIndex = this.inputSuggestionItems.length;
}
if (!this.inputSuggestionItems[this.historyIndex]) {
this.params = '';
return;
}
this.params = this.inputSuggestionItems[this.historyIndex];
},
suggesttionShowing() {
const ele = document.querySelector('.cli-console-suggestion');
if (ele && ele.style.display != 'none') {
return true;
}
return false;
},
initShortcut() {
// this.$shortcut.bind('ctrl+c', this.hotKeyScope, () => {
// this.params = '';
// this.scrollToBottom('> ^C');
// // close the tips
// (typeof this.cb == 'function') && this.cb([]);
// });
this.$shortcut.bind('ctrl+l, ⌘+l', this.hotKeyScope, () => {
this.content = [];
});
},
initHistoryTips() {
const key = `cliTips_${this.client.options.connectionName}`;
const tips = localStorage.getItem(key);
this.inputSuggestionItems = tips ? JSON.parse(tips) : [];
ipcRenderer.on('closingWindow', (event, arg) => {
this.storeCommandTips();
});
},
storeCommandTips() {
const key = this.$storage.getStorageKeyByName('cli_tip', this.client.options.connectionName);
localStorage.setItem(key, JSON.stringify(this.inputSuggestionItems.slice(-200)));
},
},
mounted() {
this.initShow();
this.initShortcut();
this.initHistoryTips();
},
beforeDestroy() {
this.anoClient && this.anoClient.quit && this.anoClient.quit();
this.$shortcut.deleteScope(this.hotKeyScope);
this.storeCommandTips();
},
};
</script>
<style type="text/css">
.cli-dailog .el-dialog__body {
padding: 0 20px;
}
.input-suggestion {
width: 100%;
line-height: 34px !important;
}
.input-suggestion input {
color: #babdc1;
background: #263238;
border-top: 0px;
border-radius: 0 0 4px 4px;
}
.dark-mode .input-suggestion input {
color: #f7f7f7;
background: #324148;
}
.input-suggestion input::-webkit-input-placeholder {
color: #8a8b8e;
}
#cli-content {
color: #babdc1;
background: #263238;
border-bottom: 0px;
border-radius: 4px 4px 0 0;
cursor: text;
height: calc(100vh - 160px);
}
.dark-mode #cli-content {
color: #f7f7f7;
background: #324148;
}
.stop-subscribe {
position: fixed;
right: 30px;
bottom: 104px;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/CliTab.vue
|
Vue
|
mit
| 13,435
|
<template>
<el-dialog @open='openDialog' :title="$t('message.command_log')" :visible.sync="visible" custom-class='command-log-dialog' width="90%" append-to-body>
<ul ref='commandLogUl' class="command-log-ul">
<li v-for="record of logsShow">
<span class="command-time">{{ record.time }} -</span>
<span class="command-con-name">[{{ record.connectionName }}]: </span>
<span class="command-name">{{ record.name }} </span>
<span class="command-args">{{ record.args }} </span>
<span class="command-cost">[{{ record.cost }}ms]</span>
</li>
</ul>
<!-- filter -->
<el-input v-model='filter' size='mini' style='max-width: 200px;' :placeholder="$t('message.key_to_search')"></el-input>
<!-- show only write commands -->
<el-checkbox v-model='showOnlyWrite'>Only Write</el-checkbox>
<div slot="footer" class="dialog-footer">
<el-button @click="logs=[]">{{ $t('el.colorpicker.clear') }}</el-button>
<el-button @click="visible=false">{{ $t('el.messagebox.cancel') }}</el-button>
</div>
</el-dialog>
</template>
<script type="text/javascript">
import { writeCMD } from '@/commands.js';
export default {
data() {
return {
visible: false,
logs: [],
maxLength: 2000,
filter: '',
showOnlyWrite: false,
};
},
created() {
this.$bus.$on('commandLog', (record) => {
// hide ping
if (record.command.name === 'ping') {
return;
}
this.logs.push({
name: record.command.name,
args: (record.command.name === 'auth') ? '***' : record.command.args.map(item => (item.length > 100 ? (`${item.slice(0, 100)}...`) : item.toString())).join(' '),
cost: record.cost.toFixed(2),
time: record.time.toTimeString().substr(0, 8),
connectionName: record.connectionName,
});
this.logs.length > this.maxLength && (this.logs = this.logs.slice(-this.maxLength));
this.visible && this.scrollToBottom();
});
},
computed: {
logsShow() {
let { logs } = this;
if (this.showOnlyWrite) {
logs = logs.filter(item => writeCMD[item.name.toUpperCase()]);
}
if (this.filter) {
logs = logs.filter(item => item.name.includes(this.filter) || item.args.includes(this.filter));
}
return logs;
},
},
methods: {
show() {
this.visible = true;
},
openDialog() {
this.scrollToBottom();
},
scrollToBottom() {
this.$nextTick(() => {
const dom = this.$refs.commandLogUl;
dom && (dom.scrollTop = dom.scrollHeight);
});
},
},
};
</script>
<style type="text/css">
.command-log-dialog.el-dialog {
margin-top: 10vh !important;
}
.command-log-ul {
padding: 10px;
overflow: auto;
min-height: 150px;
height: calc(90vh - 307px);
border: 1px solid grey;
border-radius: 5px;
list-style-type: none;
}
.command-log-ul li {
color: #333;
}
.dark-mode .command-log-ul li {
color: #f7f7f7;
}
.command-log-ul .command-time {
/*color: #f7f7f7;*/
}
.command-log-ul .command-con-name {
color: #7a7a7a;
}
.dark-mode .command-log-ul .command-con-name {
color: #b4b3b3;
}
.command-log-ul .command-name {
font-weight: bold;
}
.command-log-ul .command-args {
color: #7a7a7a;
font-size: 95%;
}
.dark-mode .command-log-ul .command-args {
color: #b4b3b3;
}
.command-log-ul .command-cost {
color: #e59090;
font-size: 90%;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/CommandLog.vue
|
Vue
|
mit
| 3,515
|
<template>
<div class="connection-menu-title">
<div class="connection-opt-icons">
<!-- right menu operate icons -->
<i :title="$t('message.redis_status')"
class="connection-right-icon fa fa-home"
:style="{ color: client ? '#7cad7c' : ''}"
@click.stop.prevent="openStatus">
</i>
<i :title="$t('message.redis_console')"
class="connection-right-icon fa fa-terminal font-weight-bold"
@click.stop.prevent="openCli">
</i>
<i :title="$t('message.refresh_connection')"
class='connection-right-icon el-icon-refresh font-weight-bold'
@click.stop.prevent="refreshConnection">
</i>
<!-- more operate menu -->
<el-dropdown
class='connection-menu-more'
placement='bottom-start'
:show-timeout=100
:hide-timeout=300>
<i class="connection-right-icon el-icon-menu" @click.stop></i>
<el-dropdown-menu class='connection-menu-more-ul' slot="dropdown">
<el-dropdown-item @click.native='closeConnection'>
<span><i class='more-operate-ico fa fa-power-off'></i> {{ $t('message.close_connection') }}</span>
</el-dropdown-item>
<el-dropdown-item @click.native='showEditConnection'>
<span><i class='more-operate-ico el-icon-edit-outline'></i> {{ $t('message.edit_connection') }}</span>
</el-dropdown-item>
<el-dropdown-item @click.native='deleteConnection'>
<span><i class='more-operate-ico el-icon-delete'></i> {{ $t('message.del_connection') }}</span>
</el-dropdown-item>
<el-dropdown-item @click.native='duplicateConnection'>
<span><i class='more-operate-ico fa fa-clone'></i> {{ $t('message.duplicate_connection') }}</span>
</el-dropdown-item>
<!-- menu color picker -->
<el-tooltip placement="right" effect="light">
<el-color-picker
slot='content'
v-model="menuColor"
@change='changeColor'
:predefine="['#f56c6c', '#F5C800', '#409EFF', '#85ce61', '#c6e2ff']">
</el-color-picker>
<el-dropdown-item divided>
<span><i class='more-operate-ico fa fa-bookmark-o'></i> {{ $t('message.mark_color') }}</span>
</el-dropdown-item>
</el-tooltip>
<el-dropdown-item @click.native='memoryAnalisys'>
<span><i class='more-operate-ico fa fa-table'></i> {{ $t('message.memory_analysis') }}</span>
</el-dropdown-item>
<el-dropdown-item @click.native='slowLog'>
<span><i class='more-operate-ico fa fa-hourglass-start'></i> {{ $t('message.slow_log') }}</span>
</el-dropdown-item>
<el-dropdown-item @click.native='importKeys' divided>
<span><i class='more-operate-ico el-icon-download'></i> {{ $t('message.import') }}Key</span>
</el-dropdown-item>
<el-dropdown-item @click.native='flushDB'>
<span><i class='more-operate-ico fa fa-exclamation-triangle'></i> {{ $t('message.flushdb') }}</span>
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
<div :title="connectionTitle()" class="connection-name">{{config.connectionName}}
<!-- <i v-if="client" style="position: absolute; left: 2px; bottom: 5px; width: 8px; height: 8px; border-radius: 4px; background-color: green;"></i> -->
</div>
<!-- edit connection dialog -->
<NewConnectionDialog
editMode='true'
:config='config'
@editConnectionFinished='editConnectionFinished'
ref='editConnectionDialog'>
</NewConnectionDialog>
</div>
</template>
<script type="text/javascript">
import storage from '@/storage.js';
import { remote } from 'electron';
import NewConnectionDialog from '@/components/NewConnectionDialog';
export default {
data() {
return {
menuColor: '#409EFF',
};
},
props: ['config', 'client'],
components: { NewConnectionDialog },
created() {
this.$bus.$on('duplicateConnection', (newConfig) => {
// not self
if (this.config.name !== newConfig.name) {
return;
}
this.showEditConnection();
});
},
methods: {
connectionTitle() {
const { config } = this;
const sep = '-----------';
const lines = [
config.connectionName,
sep,
`${this.$t('message.host')}: ${config.host}`,
`${this.$t('message.port')}: ${config.port}`,
];
config.username && lines.push(`${this.$t('message.username')}: ${config.username}`);
config.separator && lines.push(`${this.$t('message.separator')}: "${config.separator}"`);
if (config.connectionReadOnly) {
lines.push(`${sep}\nREADONLY`);
}
if (config.sshOptions) {
lines.push(`${sep}\nSSH:`);
lines.push(` ${this.$t('message.host')}: ${config.sshOptions.host}`);
lines.push(` ${this.$t('message.port')}: ${config.sshOptions.port}`);
lines.push(` ${this.$t('message.username')}: ${config.sshOptions.username}`);
}
if (config.cluster) {
lines.push(`${sep}\nCLUSTER`);
}
if (config.sentinelOptions) {
lines.push(`${sep}\nSENTINEL:`);
lines.push(` ${this.$t('message.master_group_name')}: ${config.sentinelOptions.masterName}`);
}
return lines.join('\n');
},
refreshConnection() {
this.$emit('refreshConnection');
},
showEditConnection() {
// connection is cloesd, do not display confirm
if (!this.client) {
return this.$refs.editConnectionDialog.show();
}
this.$confirm(
this.$t('message.close_to_edit_connection'),
{ type: 'warning' },
).then(() => {
this.$bus.$emit('closeConnection', this.config.connectionName);
this.$refs.editConnectionDialog.show();
}).catch(() => {});
},
closeConnection() {
this.$confirm(
this.$t('message.close_to_connection'),
{ type: 'warning' },
).then(() => {
this.$bus.$emit('closeConnection', this.config.connectionName);
}).catch(() => {});
},
editConnectionFinished(newConfig) {
this.$bus.$emit('refreshConnections');
},
duplicateConnection() {
// empty key\order , just as a new connection
const newConfig = {
...this.config,
key: undefined,
order: undefined,
connectionName: undefined,
};
storage.addConnection(newConfig);
this.$bus.$emit('refreshConnections');
// 100ms after connection list is ready
setTimeout(() => {
this.$bus.$emit('duplicateConnection', newConfig);
}, 100);
},
deleteConnection() {
this.$confirm(
this.$t('message.confirm_to_delete_connection'),
{ type: 'warning' },
).then(() => {
storage.deleteConnection(this.config);
this.$bus.$emit('refreshConnections');
this.$message.success({
message: this.$t('message.delete_success'),
duration: 1000,
});
}).catch(() => {});
},
openStatus() {
if (!this.client) {
// open Connections.vue menu
this.$parent.$parent.$parent.$refs.connectionMenu.open(this.config.connectionName);
// open connection
this.$parent.$parent.$parent.openConnection();
} else {
this.$bus.$emit('openStatus', this.client, this.config.connectionName);
}
},
openCli() {
// open cli before connection opened
if (!this.client) {
// open Connections.vue menu
this.$parent.$parent.$parent.$refs.connectionMenu.open(this.config.connectionName);
// open connection
this.$parent.$parent.$parent.openConnection(() => {
this.$bus.$emit('openCli', this.client, this.config.connectionName);
});
} else {
this.$bus.$emit('openCli', this.client, this.config.connectionName);
}
},
memoryAnalisys() {
if (!this.client) {
return;
}
this.$bus.$emit('memoryAnalysis', this.client, this.config.connectionName);
},
slowLog() {
if (!this.client) {
return;
}
this.$bus.$emit('slowLog', this.client, this.config.connectionName);
},
importKeys() {
remote.dialog.showOpenDialog(remote.getCurrentWindow(), {
properties: ['openFile'],
}).then((reply) => {
if (reply.canceled) {
return;
}
const succ = [];
const fail = [];
let count = 0;
const rl = require('readline').createInterface({
input: require('fs').createReadStream(reply.filePaths[0]),
});
rl.on('line', (line) => {
let [key, content, ttl] = line.split(',');
if (!key || !content) {
return;
}
count++;
// show notify in first time
if (count === 1) {
this.$notify.success({
message: this.$createElement('p', { ref: 'importKeysNotify' }, ''),
duration: 0,
});
}
key = Buffer.from(key, 'hex');
content = Buffer.from(content, 'hex');
ttl = ttl > 0 ? ttl : 0;
// fix #1213, REPLACE can be used in Redis>=3.0
this.client.callBuffer('RESTORE', key, ttl, content, 'REPLACE').then((reply) => {
// reply == 'OK'
succ.push(key);
this.$set(this.$refs.importKeysNotify,
'innerHTML',
`Succ: ${succ.length}, Fail: ${fail.length}`);
}).catch((e) => {
fail.push(key);
this.$set(this.$refs.importKeysNotify,
'innerHTML',
`Succ: ${succ.length}, Fail: ${fail.length}`);
});
});
rl.on('close', () => {
if (count === 0) {
return this.$message.error('File parse failed.');
}
(count > 10000) && this.$message.success({
message: this.$t('message.import_success'),
duration: 800,
});
// refresh keu list
this.$bus.$emit('refreshKeyList', this.client);
});
});
},
flushDB() {
if (!this.client) {
return;
}
const preDB = this.client.condition ? this.client.condition.select : 0;
const inputTxt = 'y';
const placeholder = this.$t('message.flushdb_prompt', { txt: inputTxt });
this.$prompt(this.$t('message.confirm_flush_db', { db: preDB }), {
inputValidator: value => ((value == inputTxt) ? true : placeholder),
inputPlaceholder: placeholder,
})
.then((value) => {
this.client.flushdb().then((reply) => {
if (reply == 'OK') {
this.$message.success({
message: this.$t('message.delete_success'),
duration: 1000,
});
this.refreshConnection();
}
}).catch((e) => { this.$message.error(e.message); });
})
.catch((e) => {});
},
changeColor(color) {
this.$emit('changeColor', color);
},
},
};
</script>
<style type="text/css">
.connection-menu-title {
margin-left: -20px;
}
.connection-menu .connection-name {
margin-right: 115px;
padding-right: 6px;
word-break: keep-all;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-weight: bold;
font-size: 1.04em;
}
.connection-menu .connection-opt-icons {
/*width: 30px;*/
/*float: right;
margin-right: 28px;*/
position: absolute;
right: 25px;
top: -2px;
}
.connection-menu .connection-right-icon {
display: inline-block;
font-size: 1.16em;
/*font-weight: bold;*/
padding: 3px;
margin-right: -4px;
transition: background 0.2s;
}
.connection-menu .connection-right-icon:hover {
/*color: #85878a;*/
background: #dcdee0;
border-radius: 3px;
}
.dark-mode .connection-menu .connection-right-icon:hover {
background: #58707b;
}
/*fix more operation btn icon vertical-center*/
.connection-menu-more {
vertical-align: baseline;
}
/*more operation ul>ico*/
.connection-menu-more-ul .more-operate-ico {
width: 13px;
text-align: center;
}
.font-weight-bold {
font-weight: bold;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/ConnectionMenu.vue
|
Vue
|
mit
| 12,309
|
<template>
<el-menu
ref="connectionMenu"
:collapse-transition='false'
:id="connectionAnchor"
@open="openConnection()"
class="connection-menu"
active-text-color="#ffd04b">
<el-submenu :index="config.connectionName">
<!-- connection menu -->
<ConnectionMenu
slot="title"
:config="config"
:client='client'
@changeColor='setColor'
@refreshConnection='openConnection(false, true)'>
</ConnectionMenu>
<!-- db search operate -->
<OperateItem
ref='operateItem'
:config="config"
:client='client'>
</OperateItem>
<!-- key list -->
<KeyList
ref='keyList'
:config="config"
:globalSettings='globalSettings'
:client='client'>
</KeyList>
</el-submenu>
</el-menu>
</template>
<script type="text/javascript">
import redisClient from '@/redisClient.js';
import KeyList from '@/components/KeyList';
import OperateItem from '@/components/OperateItem';
import ConnectionMenu from '@/components/ConnectionMenu';
export default {
data() {
return {
client: null,
pingTimer: null,
pingInterval: 10000, // ms
lastSelectedDb: 0,
};
},
props: ['config', 'globalSettings', 'index'],
components: { ConnectionMenu, OperateItem, KeyList },
created() {
this.$bus.$on('closeConnection', (connectionName = false) => {
this.closeConnection(connectionName);
});
// open connection
this.$bus.$on('openConnection', (connectionName) => {
if (connectionName && (connectionName == this.config.connectionName)) {
this.openConnection();
this.$refs.connectionMenu.open(this.config.connectionName);
}
});
},
computed: {
connectionAnchor() {
return `connection-anchor-${this.config.connectionName}`;
},
},
methods: {
initShow() {
this.$refs.operateItem.initShow();
this.$refs.keyList.initShow();
},
initLastSelectedDb() {
const db = parseInt(localStorage.getItem(`lastSelectedDb_${this.config.connectionName}`));
if (db > 0 && this.lastSelectedDb != db) {
this.lastSelectedDb = db;
this.$refs.operateItem && this.$refs.operateItem.setDb(db);
}
},
openConnection(callback = false, forceOpen = false) {
// scroll to connection
this.scrollToConnection();
// recovery last selected db
this.initLastSelectedDb();
// opened, do nothing
if (this.client) {
return forceOpen ? this.afterOpenConnection(this.client, callback) : false;
}
// set searching status first
this.$refs.operateItem.searchIcon = 'el-icon-loading';
// create a new client
const clientPromise = this.getRedisClient(this.config);
clientPromise.then((realClient) => {
this.afterOpenConnection(realClient, callback);
}).catch((e) => {});
},
afterOpenConnection(client, callback = false) {
// new connection, not ready
if (client.status != 'ready') {
client.on('ready', () => {
if (client.readyInited) {
return;
}
client.readyInited = true;
// open status tab
this.$bus.$emit('openStatus', client, this.config.connectionName);
this.startPingInterval();
this.initShow();
callback && callback();
});
}
// connection is ready
else {
this.initShow();
callback && callback();
}
},
closeConnection(connectionName) {
// if connectionName is not passed, close all connections
if (connectionName && (connectionName != this.config.connectionName)) {
return;
}
this.$refs.connectionMenu
&& this.$refs.connectionMenu.close(this.config.connectionName);
this.$bus.$emit('removeAllTab', connectionName);
// clear ping interval
clearInterval(this.pingTimer);
// reset operateItem items
this.$refs.operateItem && this.$refs.operateItem.resetStatus();
// reset keyList items
this.$refs.keyList && this.$refs.keyList.resetKeyList(true);
this.client && this.client.quit && this.client.quit();
this.client = null;
},
startPingInterval() {
this.pingTimer = setInterval(() => {
this.client && this.client.ping().then((reply) => {}).catch((e) => {
// this.$message.error('Ping Error: ' + e.message);
});
}, this.pingInterval);
},
getRedisClient(config) {
// prevent changing back to raw config, such as config.db
const configCopy = JSON.parse(JSON.stringify(config));
// select db
configCopy.db = this.lastSelectedDb;
// ssh client
if (configCopy.sshOptions) {
var clientPromise = redisClient.createSSHConnection(
configCopy.sshOptions, configCopy.host, configCopy.port, configCopy.auth, configCopy,
);
}
// normal client
else {
var clientPromise = redisClient.createConnection(
configCopy.host, configCopy.port, configCopy.auth, configCopy,
);
}
clientPromise.then((client) => {
this.client = client;
client.on('error', (error) => {
this.$message.error({
message: `Client On Error: ${error} Config right?`,
duration: 3000,
customClass: 'redis-on-error-message',
});
this.$bus.$emit('closeConnection');
});
}).catch((error) => {
this.$message.error(error.message);
this.$bus.$emit('closeConnection');
});
return clientPromise;
},
setColor(color, save = true) {
const ulDom = this.$refs.connectionMenu.$el;
const className = 'menu-with-custom-color';
// save to setting
save && this.$storage.editConnectionItem(this.config, { color });
if (!color) {
ulDom.classList.remove(className);
} else {
ulDom.classList.add(className);
this.$el.style.setProperty('--menu-color', color);
}
},
scrollToConnection() {
this.$nextTick(() => {
// 300ms after menu expand animination
setTimeout(() => {
let scrollTop = 0;
const menus = document.querySelectorAll('.connections-wrap .connections-list>ul');
// calc height sum of all above menus
for (const menu of menus) {
if (menu.id === this.connectionAnchor) {
break;
}
scrollTop += (menu.clientHeight + 8);
}
// if connections filter input exists, scroll more
// 32 = height('.filter-input')+margin
const offset = document.querySelector('.connections-wrap .filter-input') ? 32 : 0;
document.querySelector('.connections-wrap').scrollTo({
top: scrollTop + offset,
behavior: 'smooth',
});
}, 320);
});
},
},
mounted() {
this.setColor(this.config.color, false);
},
beforeDestroy() {
this.closeConnection(this.config.connectionName);
},
};
</script>
<style type="text/css">
/*menu ul*/
.connection-menu {
margin-bottom: 8px;
padding-right: 6px;
border-right: 0;
}
.connection-menu.menu-with-custom-color li.el-submenu {
border-left: 5px solid var(--menu-color);
border-radius: 4px 0 0 4px;
padding-left: 3px;
}
/*this error shows first*/
.redis-on-error-message {
z-index:9999 !important;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/ConnectionWrapper.vue
|
Vue
|
mit
| 7,530
|
<template>
<div class="connections-wrap">
<!-- search connections input -->
<div v-if="connections.length>=filterEnableNum" class="filter-input">
<el-input
v-model="filterMode"
suffix-icon="el-icon-search"
:placeholder="$t('message.search_connection')"
clearable
size="mini">
</el-input>
</div>
<!-- connections list -->
<div class="connections-list">
<ConnectionWrapper
v-for="item, index of filteredConnections"
:key="item.key ? item.key : item.connectionName"
:index="index"
:globalSettings="globalSettings"
:config='item'>
</ConnectionWrapper>
</div>
<ScrollToTop parentNum='1' :posRight='false'></ScrollToTop>
</div>
</template>
<script type="text/javascript">
import storage from '@/storage.js';
import ConnectionWrapper from '@/components/ConnectionWrapper';
import ScrollToTop from '@/components/ScrollToTop';
import Sortable from 'sortablejs';
export default {
data() {
return {
connections: [],
globalSettings: this.$storage.getSetting(),
filterEnableNum: 4,
filterMode: '',
};
},
components: { ConnectionWrapper, ScrollToTop },
created() {
this.$bus.$on('refreshConnections', () => {
this.initConnections();
});
this.$bus.$on('reloadSettings', (settings) => {
this.globalSettings = settings;
});
},
computed: {
filteredConnections() {
if (!this.filterMode) {
return this.connections;
}
return this.connections.filter(item => {
return item.name.toLowerCase().includes(this.filterMode.toLowerCase());
});
},
},
methods: {
initConnections() {
const connections = storage.getConnections(true);
const slovedConnections = [];
// this.connections = [];
for (const item of connections) {
item.connectionName = storage.getConnectionName(item);
// fix history bug, prevent db into config
delete item.db;
slovedConnections.push(item);
}
this.connections = slovedConnections;
},
sortOrder() {
const dragWrapper = document.querySelector('.connections-list');
Sortable.create(dragWrapper, {
handle: '.el-submenu__title',
animation: 400,
direction: 'vertical',
onEnd: (e) => {
const { newIndex } = e;
const { oldIndex } = e;
// change in connections
const currentRow = this.connections.splice(oldIndex, 1)[0];
this.connections.splice(newIndex, 0, currentRow);
// store
this.$storage.reOrderAndStore(this.connections);
},
});
},
},
mounted() {
this.initConnections();
this.sortOrder();
},
};
</script>
<style type="text/css">
.connections-wrap {
height: calc(100vh - 59px);
overflow-y: auto;
margin-top: 11px;
}
.connections-wrap .filter-input {
padding-right: 13px;
margin-bottom: 4px;
}
/* set drag area min height, target to the end will be correct */
.connections-wrap .connections-list {
min-height: calc(100vh - 110px);
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/Connections.vue
|
Vue
|
mit
| 3,165
|
<template>
<el-dialog :title="$t('message.custom_formatter')" :visible.sync="visible" append-to-body width='60%'>
<!-- new formatter btn -->
<el-button size="mini" @click="addDialog=true">+ {{ $t('message.new') }}</el-button>
<!-- formatter list -->
<el-table :data='formatters'>
<el-table-column
label="Name"
prop="name"
width="120">
</el-table-column>
<el-table-column
label="Formatter">
<template slot-scope="scope">
{{ formatterPreview(scope.row) }}
</template>
</el-table-column>
<el-table-column
label="Operation"
width="90">
<template slot-scope="scope">
<el-button icon="el-icon-delete" type="text" @click="removeFormatter(scope.$index)"></el-button>
<el-button icon="el-icon-edit-outline" type="text" @click="showEditDialog(scope.row)"></el-button>
</template>
</el-table-column>
</el-table>
<!-- new formatter dialog -->
<el-dialog :close-on-click-modal='false' :title="!editMode ? $t('message.new') : $t('message.edit')"
:visible.sync="addDialog" append-to-body
@closed='reset'>
<el-form label-position="top" size="mini">
<el-form-item label="Name" required>
<el-input v-model='formatter.name'></el-input>
</el-form-item>
<el-form-item label="Command" required>
<span slot="label">
Command
<el-popover
placement="top-start"
title="Command"
trigger="hover">
<i slot="reference" class="el-icon-question"></i>
<p>Executable file, such as <el-tag>/bin/bash</el-tag>, <el-tag>/bin/node</el-tag>, <el-tag>xxx.sh</el-tag>, <el-tag>xxx.php</el-tag>, make sure it is executable</p>
</el-popover>
</span>
<FileInput
:file.sync='formatter.command'
placeholder='/bin/bash'>
</FileInput>
</el-form-item>
<el-form-item label="Params">
<span slot="label">
Params
<el-popover
placement="top-start"
title="Params"
trigger="hover">
<i slot="reference" class="el-icon-question"></i>
<p>
Command params, such as "--key
<el-tag>{KEY}</el-tag> --value <el-tag>{VALUE}</el-tag>"<hr>
<b>Template variables to be replaced:</b>
<table>
<tr>
<td>[String]</td>
<td><el-tag>{VALUE}</el-tag></td>
</tr>
<tr>
<td>[Hash]</td>
<td><el-tag>{FIELD}</el-tag> <el-tag>{VALUE}</el-tag></td>
</tr>
<tr>
<td>[List]</td>
<td><el-tag>{VALUE}</el-tag></td>
</tr>
<tr>
<td>[Set]</td>
<td><el-tag>{VALUE}</el-tag></td>
</tr>
<tr>
<td>[Zset]</td>
<td><el-tag>{SCORE}</el-tag> <el-tag>{MEMBER}</el-tag></td>
</tr>
</table>
<hr>
If your value is unvisible, you can pass <el-tag>{HEX}</el-tag> instead of <el-tag>{VALUE}</el-tag><br>
then hex such as <i>68656c6c6f20776f726c64</i> will be passed
<hr>
If your value is too long(>8000), it will be writen to a file,<br> you can use <el-tag>{HEX_FILE}</el-tag> to get the path and read in your script,<br>
the content in this file is same with <el-tag>{HEX}</el-tag>
</p>
</el-popover>
</span>
<el-input v-model='formatter.params' placeholder='--value "{VALUE}"'></el-input>
</el-form-item>
<el-form-item label="">
<p>{{ formatterPreview(formatter) }}</p>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="addDialog=false">{{ $t('el.messagebox.cancel') }}</el-button>
<el-button type="primary" @click="editFormatter">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
</el-dialog>
</template>
<script type="text/javascript">
import storage from '@/storage';
import FileInput from '@/components/FileInput';
export default {
data() {
return {
visible: false,
addDialog: false,
editMode: false,
formatter: { name: '', command: '', params: '' },
};
},
components: { FileInput },
computed: {
formatters() {
return storage.getCustomFormatter();
},
},
created() {
this.$bus.$on('addCustomFormatter', () => {
this.show();
});
},
methods: {
show() {
this.visible = true;
},
reset() {
this.editMode = false;
this.formatter = { name: '', command: '', params: '' };
},
formatterPreview(row) {
return `${row.command} ${row.params}`;
},
showEditDialog(row) {
this.formatter = row;
this.addDialog = true;
this.editMode = true;
},
editFormatter() {
if (!this.formatter.name || !this.formatter.command) {
return false;
}
// add mode
if (!this.editMode) {
this.formatters.push(this.formatter);
}
this.saveSetting();
this.addDialog = false;
},
removeFormatter(index) {
this.formatters.splice(index, 1);
this.saveSetting();
},
saveSetting() {
storage.saveCustomFormatters(this.formatters);
this.$bus.$emit('refreshViewers');
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/CustomFormatter.vue
|
Vue
|
mit
| 5,766
|
<template>
<div>
<el-card class="box-card del-batch-card">
<!-- card title -->
<div slot="header" class="clearfix">
<span class="del-title"><i class="fa fa-exclamation-triangle"></i> {{ $t('message.keys_to_be_deleted') }}</span>
<i v-if="loadingScan||loadingDelete" class='el-icon-loading'></i>
<el-tag size="mini">
<span v-if="loadingScan">Scanning... </span>
<span v-if="loadingDelete">Deleting... </span>
Total: {{ allKeysList.length }}
</el-tag>
<!-- del btn -->
<el-button @click="confirmDelete" :disabled="loadingScan||loadingDelete||allKeysList.length == 0" style="float: right;" type="danger">{{ $t('message.delete_all') }}</el-button>
<!-- toggle scanning btn -->
<el-button v-if="rule.pattern.length && !scanningEnd" @click="toggleScanning()" type="text" style="float: right;">{{loadingScan ? $t('message.pause') : $t('message.begin')}} </el-button>
</div>
<!-- scan pattern -->
<el-tag v-if="rule.pattern && rule.pattern.length" size="mini" style="margin-left: 10px;">
<i class="fa fa-search"></i> {{rule.pattern.join(' ')}}
</el-tag>
<!-- key list -->
<RecycleScroller
class="del-batch-key-list"
:items="allKeysList"
:item-size="20"
key-field="str"
v-slot="{ item, index }"
>
<li>
<span class="list-index">{{ index + 1 }}.</span>
<span class="key-name" :title="item.str">{{ item.str }}</span>
</li>
</RecycleScroller>
</el-card>
</div>
</template>
<script type="text/javascript">
import { RecycleScroller } from 'vue-virtual-scroller';
export default {
data() {
return {
loadingScan: false,
loadingDelete: false,
scanStreams: [],
allKeysList: [],
scanningEnd: false,
};
},
props: ['client', 'rule', 'hotKeyScope'],
components: { RecycleScroller },
methods: {
initKeys() {
this.allKeysList = [];
this.rule.key && this.rule.key.length && this.addToList(this.rule.key);
if (this.rule.pattern && this.rule.pattern.length) {
this.loadingScan = true;
for (const pattern of this.rule.pattern) {
this.initScanStreamsAndScan(pattern);
}
}
},
initScanStreamsAndScan(pattern) {
const nodes = this.client.nodes ? this.client.nodes('master') : [this.client];
this.scanningCount = nodes.length;
nodes.map((node) => {
const scanOption = {
match: `${pattern}*`,
count: 20000,
};
const stream = node.scanBufferStream(scanOption);
this.scanStreams.push(stream);
stream.on('data', (keys) => {
this.addToList(keys.sort());
// pause for dom rendering
stream.pause();
setTimeout(() => {
this.loadingScan && stream.resume();
}, 100);
});
stream.on('error', (e) => {
this.loadingScan = false;
this.$message.error({
message: `Delete Batch Stream On Error: ${e.message}`,
duration: 1500,
});
});
stream.on('end', () => {
// all nodes scan finished(cusor back to 0)
if (--this.scanningCount <= 0) {
this.loadingScan = false;
this.scanningEnd = true;
}
});
});
},
addToList(keys) {
const list = [];
for (const key of keys) {
list.push({ key, str: this.$util.bufToString(key) });
}
this.allKeysList = this.allKeysList.concat(list);
},
toggleScanning(forcePause = null) {
this.loadingScan = (forcePause === null ? !this.loadingScan : !forcePause);
if (this.scanStreams.length) {
for (const stream of this.scanStreams) {
this.loadingScan ? stream.resume() : stream.pause();
}
}
},
confirmDelete() {
const keys = this.allKeysList;
const total = keys.length;
if (total <= 0) {
return;
}
this.loadingDelete = true;
let delPromise = null;
// standalone Redis, batch delete
if (!this.client.nodes) {
let chunked = [];
for (let i = 0; i < total; i++) {
chunked.push(keys[i].key);
// del 5000 keys one time
if (chunked.length >= 5000) {
delPromise = this.client.del(chunked);
chunked = [];
}
}
if (chunked.length) {
delPromise = this.client.del(chunked);
}
// use final promise
delPromise.then((reply) => {
if (reply > 0) {
this.afterDelete();
} else {
this.deleteFailed(this.$t('message.delete_failed'));
}
}).catch((e) => {
this.deleteFailed(e.message);
});
}
// cluster, one key per time instead of batch
else {
for (let i = 0; i < total; i++) {
delPromise = this.client.del(keys[i].key);
delPromise.catch((e) => {});
}
// use final promise
delPromise.then((reply) => {
if (reply == 1) {
this.afterDelete();
} else {
this.deleteFailed(this.$t('message.delete_failed'));
}
}).catch((e) => {
this.deleteFailed(e.message);
});
}
},
afterDelete() {
this.loadingDelete = false;
this.allKeysList = [];
// empty the specified keys
// this.rule.key = [];
this.$message.success(this.$t('message.delete_success'));
this.$bus.$emit('refreshKeyList', this.client);
// except pattern mode scanning not to end, close pre tab
if (!this.rule.pattern.length || this.scanningEnd) {
this.$bus.$emit('removePreTab');
}
},
deleteFailed(msg = '') {
msg && this.$message.error(msg);
this.loadingScan = false;
this.loadingDelete = false;
},
initShortcut() {
this.$shortcut.bind('ctrl+r, ⌘+r, f5', this.hotKeyScope, () => {
this.initKeys();
return false;
});
},
},
mounted() {
this.initKeys();
// disable f5 for streams on event cannot stop
// this.initShortcut();
},
beforeDestroy() {
// this.$shortcut.deleteScope(this.hotKeyScope);
// cancel scanning
this.toggleScanning(true);
},
};
</script>
<style type="text/css" >
.del-title {
color: #f56c6c;
font-weight: bold;
font-size: 120%;
}
.del-batch-card {
/*margin-top: 10px;*/
}
.del-batch-key-list {
height: calc(100vh - 204px);
overflow: auto;
padding-left: 10px;
list-style: none;
margin-top: 10px;
}
.del-batch-key-list li {
color: #333;
font-size: 92%;
display: flex;
}
.dark-mode .del-batch-key-list li {
color: #f7f7f7;
}
.del-batch-key-list li .key-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/DeleteBatch.vue
|
Vue
|
mit
| 6,962
|
<template>
<el-input
:value='file'
clearable
@clear='clearFile'
@focus='focus'
:placeholder='placeholder'>
<template slot="append">
<el-button @click='showFileSelector'>...</el-button>
</template>
</el-input>
</template>
<script type="text/javascript">
import { remote } from 'electron';
export default {
props: {
file: { default: '' },
bookmark: { default: '' },
placeholder: { default: 'Select File' },
},
methods: {
clearFile() {
this.$emit('update:file', '');
this.$emit('update:bookmark', '');
},
focus(e) {
// edit is forbidden, input blur
e.target.blur();
},
showFileSelector() {
remote.dialog.showOpenDialog(remote.getCurrentWindow(), {
securityScopedBookmarks: true,
properties: ['openFile', 'showHiddenFiles'],
}).then((reply) => {
if (reply.canceled) {
return;
}
reply.filePaths && this.$emit('update:file', reply.filePaths[0]);
reply.bookmarks && this.$emit('update:bookmark', reply.bookmarks[0]);
}).catch((e) => {
this.$message.error(`File Input Error: ${e.message}`);
});
},
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/FileInput.vue
|
Vue
|
mit
| 1,205
|
<template>
<div class="format-viewer-container">
<el-select v-model="selectedView" :disabled='overSize' class='format-selector' :style='selectStyle' size='mini' placeholder='Text'>
<span slot="prefix" class="fa fa-sitemap"></span>
<el-option
v-for="item of viewers"
:key="item.text"
:label="item.text"
:value="item.text">
</el-option>
<!-- add custom -->
<el-option
@click.native.stop.prevent='addCustomFormatter'
value='addCustomFormatter'>
<el-button type='text' icon="el-icon-edit-outline">{{$t('message.custom')}}</el-button>
</el-option>
</el-select>
<el-tag v-if='!contentVisible' size="mini" class='formater-binary-tag' :disable-transitions='true'>[Hex]</el-tag>
<el-tag class='formater-binary-tag' size="mini" :disable-transitions='true'>Size: {{ $util.humanFileSize(buffSize) }}</el-tag>
<el-button @click='copyContent' :title='$t("message.copy")' type='text' size='mini'>
<i class="el-icon-document"></i>{{$t("message.copy")}}
</el-button>
<br>
<component
ref='viewer'
:is='viewerComponent'
:content='content'
:name="selectedView"
:contentVisible='contentVisible'
:disabled='disabled'
:redisKey="redisKey"
:dataMap="dataMap">
</component>
</div>
</template>
<script type="text/javascript">
import storage from '@/storage';
import ViewerText from '@/components/viewers/ViewerText';
import ViewerHex from '@/components/viewers/ViewerHex';
import ViewerJson from '@/components/viewers/ViewerJson';
import ViewerBinary from '@/components/viewers/ViewerBinary';
import ViewerPHPSerialize from '@/components/viewers/ViewerPHPSerialize';
import ViewerBrotli from '@/components/viewers/ViewerBrotli';
import ViewerGzip from '@/components/viewers/ViewerGzip';
import ViewerDeflate from '@/components/viewers/ViewerDeflate';
import ViewerMsgpack from '@/components/viewers/ViewerMsgpack';
import ViewerOverSize from '@/components/viewers/ViewerOverSize';
import ViewerCustom from '@/components/viewers/ViewerCustom';
import ViewerProtobuf from '@/components/viewers/ViewerProtobuf';
import ViewerDeflateRaw from '@/components/viewers/ViewerDeflateRaw';
import ViewerJavaSerialize from '@/components/viewers/ViewerJavaSerialize';
import ViewerPickle from '@/components/viewers/ViewerPickle';
export default {
data() {
return {
viewerComponent: 'ViewerText',
selectedView: 'Text',
viewers: [
{ value: 'ViewerText', text: 'Text' },
{ value: 'ViewerHex', text: 'Hex' },
{ value: 'ViewerJson', text: 'Json' },
{ value: 'ViewerBinary', text: 'Binary' },
{ value: 'ViewerMsgpack', text: 'Msgpack' },
{ value: 'ViewerPHPSerialize', text: 'PHPSerialize' },
{ value: 'ViewerJavaSerialize', text: 'JavaSerialize' },
{ value: 'ViewerPickle', text: 'Pickle' },
{ value: 'ViewerBrotli', text: 'Brotli' },
{ value: 'ViewerGzip', text: 'Gzip' },
{ value: 'ViewerDeflate', text: 'Deflate' },
{ value: 'ViewerDeflateRaw', text: 'DeflateRaw' },
{ value: 'ViewerProtobuf', text: 'Protobuf' },
],
selectStyle: {
float: this.float,
},
overSizeBytes: 20971520, // 20MB
autoFormated: false,
};
},
components: {
ViewerText,
ViewerHex,
ViewerJson,
ViewerBinary,
ViewerPHPSerialize,
ViewerMsgpack,
ViewerOverSize,
ViewerCustom,
ViewerBrotli,
ViewerGzip,
ViewerDeflate,
ViewerProtobuf,
ViewerDeflateRaw,
ViewerJavaSerialize,
ViewerPickle,
},
props: {
float: { default: 'right' },
content: { default: () => Buffer.from('') },
disabled: { type: Boolean, default: false },
redisKey: { default: () => Buffer.from('') },
dataMap: { type: Object, default: () => {} },
},
computed: {
contentVisible() {
// for better performance, oversize doesn't care visible.
if (this.overSize) {
return true;
}
return this.$util.bufVisible(this.content);
},
buffSize() {
return Buffer.byteLength(this.content);
},
overSize() {
return this.buffSize > this.overSizeBytes;
},
viewersMap() {
// add oversize tmp
const map = { OverSize: 'ViewerOverSize' };
this.viewers.forEach((item) => {
map[item.text] = item.value;
});
return map;
},
},
created() {
this.$bus.$on('refreshViewers', () => {
this.removeCustom();
this.loadCustomViewers();
});
},
watch: {
content() {
// auto format only when first in #920
if (this.autoFormated) {
return;
}
this.autoFormat();
this.autoFormated = true;
},
selectedView(viewer) {
// custom viewer com may same, force change
this.viewerComponent = '';
this.$nextTick(() => {
this.viewerComponent = this.viewersMap[viewer];
});
},
},
methods: {
getContent() {
if (typeof this.$refs.viewer.getContent === 'function') {
return this.$refs.viewer.getContent();
}
return this.content;
},
changeViewer(viewer) {
this.selectedView = viewer;
this.viewerComponent = this.viewersMap[viewer];
},
addCustomFormatter() {
this.$bus.$emit('addCustomFormatter');
this.autoFormat();
},
autoFormat() {
if (!this.content || !this.content.length) {
return this.changeViewer('Text');
}
if (this.overSize) {
return this.changeViewer('OverSize');
}
// json
if (this.$util.isJson(this.content)) {
return this.changeViewer('Json');
}
// php unserialize
if (this.$util.isPHPSerialize(this.content)) {
return this.changeViewer('PHPSerialize');
}
// java unserialize
if (this.$util.isJavaSerialize(this.content)) {
return this.changeViewer('JavaSerialize');
}
// pickle
if (this.$util.isPickle(this.content)) {
return this.changeViewer('Pickle');
}
// msgpack
if (this.$util.isMsgpack(this.content)) {
return this.changeViewer('Msgpack');
}
// brotli unserialize
if (this.$util.isBrotli(this.content)) {
return this.changeViewer('Brotli');
}
// gzip
if (this.$util.isGzip(this.content)) {
return this.changeViewer('Gzip');
}
// deflate
if (this.$util.isDeflate(this.content)) {
return this.changeViewer('Deflate');
}
// protobuf
if (this.$util.isProtobuf(this.content)) {
return this.changeViewer('Protobuf');
}
// deflateRaw
if (this.$util.isDeflateRaw(this.content)) {
return this.changeViewer('DeflateRaw');
}
// hex
if (!this.contentVisible) {
return this.changeViewer('Hex');
}
return this.changeViewer('Text');
},
copyContent() {
const content = (typeof this.$refs.viewer.copyContent === 'function')
? this.$refs.viewer.copyContent()
: this.content;
this.$util.copyToClipboard(content);
this.$message.success(this.$t('message.copy_success'));
},
loadCustomViewers() {
const formatters = storage.getCustomFormatter();
if (!formatters || !formatters.length) {
return;
}
formatters.forEach((formatter) => {
this.viewers.push({ value: 'ViewerCustom', text: formatter.name, type: 'custom' });
});
},
removeCustom() {
this.viewers = this.viewers.filter(item => item.type !== 'custom');
},
},
mounted() {
this.autoFormat();
this.loadCustomViewers();
},
};
</script>
<style type="text/css">
.format-selector {
width: 130px;
}
.format-selector .el-input__inner {
height: 22px !important;
}
/*outline same with text viewer's .el-textarea__inner*/
.text-formated-container {
border: 1px solid #dcdfe6;
padding: 5px 10px;
border-radius: 4px;
}
.dark-mode .text-formated-container {
border-color: #7f8ea5;
}
.format-viewer-container textarea {
min-height: 194px !important;
height: calc(100vh - 686px);
}
.collapse-container {
height: 27px;
}
.collapse-container .collapse-btn {
float: right;
padding: 9px 0;
}
.formater-binary-tag {
font-size: 80%;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/FormatViewer.vue
|
Vue
|
mit
| 8,423
|
<template>
<el-dialog :title="$t('message.hotkey')" :visible.sync="visible" custom-class='hotkey-tips-dialog' append-to-body>
<el-table :data='keys'>
<el-table-column
prop="key"
width="180"
label="Key">
</el-table-column>
<el-table-column
prop="desc"
label="Description">
</el-table-column>
</el-table>
</el-dialog>
</template>
<script type="text/javascript">
export default {
data() {
return {
visible: false,
};
},
computed: {
keys() {
return [
{ key: 'Ctrl + n / ⌘ + n', desc: this.$t('message.new_connection') },
{ key: 'Ctrl + , / ⌘ + ,', desc: this.$t('message.settings') },
{ key: 'Ctrl + g / ⌘ + g', desc: this.$t('message.command_log') },
{ key: 'Ctrl + w / ⌘ + w', desc: `${this.$t('message.close')} Tab` },
{ key: '⌘ + h', desc: this.$t('message.hide_window') },
{ key: 'Ctrl + [h/m] / ⌘ + m', desc: this.$t('message.minimize_window') },
{ key: 'Ctrl + Enter / ⌘ + Enter', desc: this.$t('message.maximize_window') },
{ key: 'Ctrl + r / ⌘ + r / F5', desc: `${this.$t('message.refresh_connection')} [Key tab, Info tab]` },
{ key: 'Ctrl + d / ⌘ + d', desc: `${this.$t('el.upload.delete')} [Key tab]` },
{ key: 'Ctrl + s / ⌘ + s', desc: `${this.$t('message.save')} [Key tab]` },
// {key: 'Ctrl + c / ⌘ + c', desc: 'Ctrl + c [Console tab]'},
{ key: 'Ctrl + l / ⌘ + l', desc: `${this.$t('message.clean_up')} [Console tab]` },
{ key: 'Ctrl / ⌘ + click key', desc: this.$t('message.open_new_tab') },
{ key: 'Ctrl + ? / ⌘ + ?', desc: `${this.$t('message.hotkey')} Tips` },
];
},
},
methods: {
show() {
this.visible = true;
},
},
mounted() {
this.$shortcut.bind('ctrl+/, ⌘+/', () => {
this.show();
return false;
});
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/HotKeys.vue
|
Vue
|
mit
| 1,910
|
<template>
<div>
<!-- <el-tag v-if="!buffVisible" class='input-binary-tag' size="mini">[Hex]</el-tag> -->
<el-input :disabled='disabled' :value='contentDisplay' @change="updateContent($event)" :placeholder="placeholder">
<template v-if="!buffVisible" slot="prefix">Hex</template>
</el-input>
</div>
</template>
<script type="text/javascript">
export default {
props: {
content: { default: () => Buffer.from('') },
disabled: { type: Boolean, default: false },
placeholder: { type: String, default: '' },
},
computed: {
contentDisplay() {
if (!this.content) {
return '';
}
return this.$util.bufToString(this.content);
},
buffVisible() {
if (!this.content) {
return true;
}
return this.$util.bufVisible(this.content);
},
},
methods: {
updateContent(value) {
const newContent = this.buffVisible ? Buffer.from(value) : this.$util.xToBuffer(value);
this.$emit('update:content', newContent);
},
},
};
</script>
<style type="text/css">
.input-binary-tag {
font-size: 80%;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/InputBinary.vue
|
Vue
|
mit
| 1,121
|
<template>
<el-input :value="value" @input="handleInput" :type="inputType" :placeholder="placeholder">
<i ref="toggler" slot="suffix" class="toggler el-icon-view" @click="togglePassword"></i>
</el-input>
</template>
<script type="text/javascript">
export default {
data() {
return {
inputType: 'password',
hideTextTime: 6000,
};
},
props: ['value', 'placeholder'],
methods: {
handleInput(newValue) {
this.$emit('input', newValue);
},
togglePassword() {
clearTimeout(this.recoverTimer);
if (!this.$refs.toggler) {
return;
}
// show text
if (this.inputType == 'password') {
this.inputType = 'text';
this.$refs.toggler.classList.add('toggler-text');
// set time to hide text
this.recoverTimer = setTimeout(() => {
this.togglePassword();
}, this.hideTextTime);
}
// back to password
else {
this.inputType = 'password';
this.$refs.toggler.classList.remove('toggler-text');
}
},
},
destroyed() {
clearTimeout(this.recoverTimer);
},
};
</script>
<style type="text/css" scoped>
.toggler {
cursor: pointer;
font-weight: bold;
margin-right: 4px;
}
.toggler:hover {
color: #6895ee;
}
.toggler.toggler-text {
color: #6895ee;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/InputPassword.vue
|
Vue
|
mit
| 1,358
|
<template>
<div class="text-formated-container">
<slot name='default'></slot>
<!-- collapse btn -->
<div class="collapse-container">
<el-button class="collapse-btn" type="text" @click="toggleCollapse">{{ $t('message.' + collapseText) }}</el-button>
</div>
<!-- monaco editor div -->
<div class="monaco-editor-con" ref="editor"></div>
</div>
</template>
<script type="text/javascript">
// import * as monaco from 'monaco-editor';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
const JSONbig = require('@qii404/json-bigint')({ useNativeBigInt: false });
export default {
data() {
return {
collapseText: 'collapse_all',
};
},
props: {
content: { type: Array | String, default: () => {} },
readOnly: { type: Boolean, default: true },
},
created() {
// listen font family change and reset options
// to avoid cursor offset
this.$bus.$on('fontInited', this.changeFont);
},
computed: {
newContentStr() {
if (typeof this.content === 'string') {
return this.content;
}
return JSONbig.stringify(this.content, null, 4);
},
},
watch: {
// refresh
content() {
this.$nextTick(() => {
this.monacoEditor.setValue(this.newContentStr);
});
},
},
methods: {
getContent() {
const content = this.monacoEditor.getValue();
if (!this.$util.isJson(content)) {
this.$message.error(this.$t('message.json_format_failed'));
return false;
}
return Buffer.from(JSONbig.stringify(JSONbig.parse(content), null, 0));
},
getRawContent(removeJsonSpace = false) {
let content = this.monacoEditor.getValue();
if (removeJsonSpace) {
if (this.$util.isJson(content)) {
content = JSONbig.stringify(JSONbig.parse(content), null, 0);
}
}
return content;
},
toggleCollapse() {
this.collapseText == 'expand_all' ? this.monacoEditor.trigger('fold', 'editor.unfoldAll')
: this.monacoEditor.trigger('fold', 'editor.foldAll');
this.collapseText = this.collapseText == 'expand_all' ? 'collapse_all' : 'expand_all';
},
onResize() {
// init resizeDebounce
if (!this.resizeDebounce) {
this.resizeDebounce = this.$util.debounce(() => {
this.monacoEditor && this.monacoEditor.layout();
}, 200);
}
this.resizeDebounce();
},
changeFont(fontFamily) {
this.monacoEditor && this.monacoEditor.updateOptions({
fontFamily,
});
},
},
mounted() {
this.monacoEditor = monaco.editor.create(
this.$refs.editor,
{
value: this.newContentStr,
theme: 'vs-dark',
language: 'json',
links: false,
readOnly: this.readOnly,
cursorStyle: this.readOnly ? 'underline-thin' : 'line',
lineNumbers: 'off',
contextmenu: false,
// set fontsize and family to avoid cursor offset
fontSize: 14,
fontFamily: this.$storage.getFontFamily(),
showFoldingControls: 'always',
// auto layout, performance cost
automaticLayout: true,
wordWrap: 'on',
// long text indent when wrapped
wrappingIndent: 'indent',
// cursor line highlight
renderLineHighlight: 'none',
// highlight word when cursor in
occurrencesHighlight: false,
// disable scroll one page at last line
scrollBeyondLastLine: false,
// hide scroll sign of current line
hideCursorInOverviewRuler: true,
// fix #1097 additional vertical cursor
accessibilitySupport: 'off',
minimap: {
enabled: false,
},
// vertical line
guides: {
indentation: false,
highlightActiveIndentation: false,
},
scrollbar: {
useShadows: false,
verticalScrollbarSize: '9px',
horizontalScrollbarSize: '9px',
},
},
);
// window.addEventListener("resize", this.onResize);
// this.monacoEditor.getAction('editor.foldLevel3').run();
// this.monacoEditor.getAction('editor.action.formatDocument').run();
},
destroyed() {
// window.removeEventListener("resize", this.onResize);
this.monacoEditor.dispose();
this.$bus.$off('fontInited', this.changeFont);
},
};
</script>
<style type="text/css">
.text-formated-container .monaco-editor-con {
min-height: 150px;
height: calc(100vh - 730px);
clear: both;
overflow: hidden;
background: none;
}
/*recovery collapse icon font in monaco*/
.text-formated-container .monaco-editor .codicon {
font-family: codicon !important;
}
/*change default scrollbar style*/
.text-formated-container .monaco-editor .scrollbar {
background: #eaeaea;
border-radius: 4px;
}
.dark-mode .text-formated-container .monaco-editor .scrollbar {
background: #425057;
}
.text-formated-container .monaco-editor .scrollbar:hover {
background: #e0e0dd;
}
.dark-mode .text-formated-container .monaco-editor .scrollbar:hover {
background: #495961;
}
.text-formated-container .monaco-editor-con .monaco-editor .slider {
border-radius: 4px;
background: #c1c1c1;
}
.dark-mode .text-formated-container .monaco-editor-con .monaco-editor .slider {
background: #5a6f7a;
}
.text-formated-container .monaco-editor-con .monaco-editor .slider:hover {
background: #7f7f7f;
}
.dark-mode .text-formated-container .monaco-editor-con .monaco-editor .slider:hover {
background: #6a838f;
}
/*remove background color*/
.text-formated-container .monaco-editor .margin {
background-color: inherit;
}
.text-formated-container .monaco-editor-con .monaco-editor,
.text-formated-container .monaco-editor-con .monaco-editor-background,
.text-formated-container .monaco-editor-con .monaco-editor .inputarea.ime-input {
background-color: inherit;
}
/*json key color*/
.text-formated-container .monaco-editor-con .mtk4 {
color: #111111;
}
.dark-mode .text-formated-container .monaco-editor-con .mtk4 {
color: #ebebec;
}
/*json val string color*/
.text-formated-container .monaco-editor-con .mtk5 {
color: #42b983;
}
/*json val number color*/
.text-formated-container .monaco-editor-con .mtk6 {
color: #fc1e70;
}
/*json bracket color*/
.text-formated-container .monaco-editor-con .mtk9 {
color: #111111;
}
/*json bracket color*/
.dark-mode .text-formated-container .monaco-editor-con .mtk9 {
color: #b6b6b9;
}
/* common string in json editor*/
.text-formated-container .monaco-editor-con .mtk1 {
color: #606266;
}
.dark-mode .text-formated-container .monaco-editor-con .mtk1 {
color: #f3f3f4;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/JsonEditor.vue
|
Vue
|
mit
| 6,825
|
<template>
<div>
<el-container direction="vertical" class="key-tab-container">
<!-- key info -->
<KeyHeader
ref="keyHeader"
:client='client'
:redisKey="redisKey"
:keyType="keyType"
@refreshContent='refreshContent'
@dumpCommand='dumpCommand'
:hotKeyScope='hotKeyScope'
class="key-header-info">
</KeyHeader>
<!-- key content -->
<component
ref="keyContent"
:is="componentName"
:client='client'
:redisKey="redisKey"
:hotKeyScope='hotKeyScope'
class="key-content-container">
</component>
</el-container>
</div>
</template>
<script>
import KeyHeader from '@/components/KeyHeader';
import KeyContentString from '@/components/contents/KeyContentString';
import KeyContentHash from '@/components/contents/KeyContentHash';
import KeyContentSet from '@/components/contents/KeyContentSet';
import KeyContentZset from '@/components/contents/KeyContentZset';
import KeyContentList from '@/components/contents/KeyContentList';
import KeyContentStream from '@/components/contents/KeyContentStream';
import KeyContentReJson from '@/components/contents/KeyContentReJson';
export default {
data() {
return {};
},
props: ['client', 'redisKey', 'keyType', 'hotKeyScope'],
components: {
KeyHeader,
KeyContentString,
KeyContentHash,
KeyContentSet,
KeyContentZset,
KeyContentList,
KeyContentStream,
KeyContentReJson,
},
computed: {
componentName() {
return this.getComponentNameByType(this.keyType);
},
},
methods: {
getComponentNameByType(keyType) {
const map = {
string: 'KeyContentString',
hash: 'KeyContentHash',
zset: 'KeyContentZset',
set: 'KeyContentSet',
list: 'KeyContentList',
stream: 'KeyContentStream',
'ReJSON-RL': 'KeyContentReJson',
json: 'KeyContentReJson', // upstash
};
if (map[keyType]) {
return map[keyType];
}
// type not support, such as bf
this.$message.error(this.$t('message.key_type_not_support'));
return '';
},
refreshContent() {
this.client.exists(this.redisKey).then((reply) => {
if (reply == 0) {
// clear interval if auto refresh opened
// this.$refs.keyHeader.removeInterval();
return this.$message.error({
message: this.$t('message.key_not_exists'),
duration: 1000,
});
}
this.$refs.keyContent && this.$refs.keyContent.initShow();
}).catch((e) => {
this.$message.error(`Exists Error: ${e.message}`);
});
},
dumpCommand() {
this.$refs.keyContent && this.$refs.keyContent.dumpCommand();
},
},
};
</script>
<style type="text/css">
.key-tab-container {
/*padding-left: 5px;*/
}
.key-header-info {
margin-top: 6px;
}
.key-content-container {
margin-top: 12px;
}
.content-more-container {
text-align: center;
margin-top: 10px;
}
.content-more-container .content-more-btn {
width: 95%;
padding-top: 5px;
padding-bottom: 5px;
}
/*key content table wrapper*/
.key-content-container .content-table-container {
height: calc(100vh - 223px);
margin-top: 10px;
/*fix vex-table height*/
overflow-y: hidden;
}
/* vxe table cell */
.key-content-container .content-table-container .vxe-cell {
overflow: hidden !important;
line-height: 34px;
}
/* vxe table radius*/
.key-content-container .content-table-container .vxe-table--border-line {
border-radius: 3px;
}
/*key-content-string such as String,ReJSON*/
/*text viewer box*/
.key-content-string .el-textarea textarea {
font-size: 14px;
height: calc(100vh - 231px);
}
/*json in monaco editor*/
.key-content-string .text-formated-container .monaco-editor-con {
height: calc(100vh - 275px);
}
.key-content-string .content-string-save-btn {
width: 100px;
float: right;
}
/*end of key-content-string*/
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/KeyDetail.vue
|
Vue
|
mit
| 4,086
|
<template>
<div>
<!-- key name -->
<div class="key-header-item key-name-input">
<el-input
ref="keyNameInput"
:value="$util.bufToString(keyName)"
@change='changeKeyInput'
@keyup.enter.native="renameKey"
:title="$t('message.click_enter_to_rename')"
placeholder="KeyName">
<span slot="prepend" class="key-detail-type">{{ keyType }}</span>
<i class="el-icon-check el-input__icon cursor-pointer"
slot="suffix"
:title="$t('message.click_enter_to_rename')"
@click="renameKey">
</i>
</el-input>
</div>
<!-- key ttl -->
<div class="key-header-item key-ttl-input">
<el-input
type="number"
v-model="keyTTL"
@keyup.enter.native="ttlKey"
:title="$util.leftTime(keyTTL)">
<span slot="prepend">TTL</span>
<!-- remove expire -->
<i class="el-icon-close el-input__icon cursor-pointer"
slot="suffix"
:title="$t('message.persist')"
@click="persistKey">
</i>
<!-- save ttl -->
<i class="el-icon-check el-input__icon cursor-pointer"
slot="suffix"
:title="$t('message.click_enter_to_ttl')"
@click="ttlKey">
</i>
</el-input>
</div>
<!-- del & refresh btn -->
<div class='key-header-item key-header-btn-con'>
<!-- del btn -->
<el-button ref='deleteBtn' type="danger" @click="deleteKey" icon="el-icon-delete" :title="$t('el.upload.delete')+' Ctrl+d'"></el-button>
<!-- refresh btn -->
<!-- <el-button ref='refreshBtn' type="success" @click="refreshKey" icon="el-icon-refresh" :title="$t('message.refresh_connection')+' Ctrl+r / F5'"></el-button> -->
<!-- refresh btn component -->
<el-popover
placement="bottom"
:open-delay="500"
trigger="hover">
<el-tag type="info">
<i class="el-icon-refresh"></i>
{{ $t('message.auto_refresh') }}
</el-tag>
<el-tooltip :content="$t('message.auto_refresh_tip', {interval: refreshInterval / 1000})" effect="dark" placement="bottom">
<el-switch v-model='autoRefresh' @change="refreshInit"></el-switch>
</el-tooltip>
<!-- refresh btn -->
<el-button slot="reference" ref='refreshBtn' type="success" @click="refreshKey" icon="el-icon-refresh" :title="$t('message.refresh_connection')+' Ctrl+r / F5'" :class="autoRefresh?'rotating':''"></el-button>
</el-popover>
<!-- dump btn -->
<el-button ref='dumpBtn' type="primary" @click="dumpCommand" icon="fa fa-code" :title="$t('message.dump_to_clipboard')"></el-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
keyName: this.redisKey,
keyTTL: -1,
binary: false,
autoRefresh: false,
refreshInterval: 2000,
};
},
props: ['client', 'redisKey', 'keyType', 'hotKeyScope'],
methods: {
initShow() {
const key = this.redisKey;
const { client } = this;
// reset name input
this.keyName = key;
this.binary = !this.$util.bufVisible(key);
client.ttl(key).then((reply) => {
this.keyTTL = reply;
}).catch((e) => {
this.$message.error(`TTL Error: ${e.message}`);
});
},
changeKeyInput(keyInput) {
this.keyName = this.binary ? this.$util.xToBuffer(keyInput) : Buffer.from(keyInput);
},
refreshKey() {
this.initShow();
this.$emit('refreshContent');
},
refreshInit() {
this.refreshTimer && clearInterval(this.refreshTimer);
if (this.autoRefresh) {
this.refreshKey();
this.refreshTimer = setInterval(() => {
this.refreshKey();
}, this.refreshInterval);
}
},
removeInterval() {
this.autoRefresh = false;
this.refreshInit();
},
dumpCommand() {
this.$emit('dumpCommand');
},
deleteKey() {
this.$confirm(
this.$t('message.confirm_to_delete_key', { key: this.$util.bufToString(this.redisKey) }),
{ type: 'warning' },
)
.then(() => {
this.client.del(this.redisKey).then((reply) => {
if (reply == 1) {
this.$message.success({
message: this.$t('message.delete_success'),
duration: 1000,
});
this.$bus.$emit('removePreTab');
this.refreshKeyList(this.redisKey);
} else {
this.$message.error({
message: `${this.redisKey} ${this.$t('message.delete_failed')}`,
duration: 1000,
});
}
}).catch((e) => { this.$message.error(e.message); });
}).catch(() => {});
},
renameKey(e) {
// input blur to prevent trigger twice by enter
e && e.srcElement.blur();
if (this.keyName.equals(this.redisKey)) {
return;
}
this.$confirm(
this.$t('message.confirm_to_rename_key', {
old: this.$util.bufToString(this.redisKey),
new: this.$util.bufToString(this.keyName),
}),
{ type: 'warning' },
).then(() => {
this.client.rename(this.redisKey, this.keyName).then((reply) => {
if (reply === 'OK') {
this.$message.success({
message: this.$t('message.modify_success'),
duration: 1000,
});
this.refreshKeyList(this.redisKey);
this.refreshKeyList(this.keyName, 'add');
this.$bus.$emit('clickedKey', this.client, this.keyName);
}
}).catch((e) => {
this.$message.error(`Rename Error: ${e.message}`);
});
}).catch(() => {});
},
ttlKey() {
// -1 persist key
if (this.keyTTL == -1) {
return this.persistKey();
}
// ttl <= 0
if (this.keyTTL <= 0) {
this.$confirm(
this.$t('message.ttl_delete'),
{ type: 'warning' },
)
.then(() => {
this.setTTL(true);
})
.catch(() => {});
} else {
this.setTTL();
}
},
setTTL(keyDeleted = false) {
this.client.expire(this.redisKey, this.keyTTL).then((reply) => {
if (reply == 1) {
this.$message.success({
message: this.$t('message.modify_success'),
duration: 1000,
});
if (keyDeleted) {
this.refreshKeyList(this.redisKey);
this.$bus.$emit('removePreTab');
}
}
}).catch((e) => {
this.$message.error(`Expire Error: ${e.message}`);
});
},
persistKey() {
this.client.persist(this.redisKey).then(() => {
this.initShow();
this.$message.success(this.$t('message.modify_success'));
}).catch((e) => {
this.$message.error(`Persist Error: ${e.message}`);
});
},
refreshKeyList(key, type = 'del') {
this.$bus.$emit('refreshKeyList', this.client, key, type);
},
initShortcut() {
// refresh
this.$shortcut.bind('ctrl+r, ⌘+r, f5', this.hotKeyScope, () => {
// make input blur first
this.$refs.deleteBtn.$el.focus();
this.refreshKey();
return false;
});
// delete
this.$shortcut.bind('ctrl+d, ⌘+d', this.hotKeyScope, () => {
this.deleteKey();
return false;
});
},
},
mounted() {
this.initShow();
this.initShortcut();
},
beforeDestroy() {
clearInterval(this.refreshTimer);
this.$shortcut.deleteScope(this.hotKeyScope);
},
};
</script>
<style type="text/css">
.key-detail-type {
text-transform: capitalize;
text-align: center;
min-width: 34px;
display: inline-block;
}
.cursor-pointer {
cursor: pointer;
}
.key-header-item {
/*padding-right: 15px;*/
/*margin-bottom: 10px;*/
float: left;
}
.key-header-item.key-name-input {
width: calc(100% - 402px);
min-width: 218px;
max-width: 800px;
margin-right: 15px;
margin-bottom: 10px;
}
.key-header-item.key-ttl-input {
width: 218px;
margin-right: 15px;
margin-bottom: 10px;
}
/*hide number input button*/
.key-header-item.key-ttl-input input::-webkit-inner-spin-button,
.key-header-item.key-ttl-input input::-webkit-outer-spin-button {
appearance: none;
}
.key-header-item.key-header-btn-con .el-button+.el-button {
margin-left: 4px;
}
/*refresh btn rotating*/
.key-header-info .key-header-btn-con .rotating .el-icon-refresh{
animation: rotate 1.5s linear infinite;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/KeyHeader.vue
|
Vue
|
mit
| 8,667
|
<template>
<div>
<!-- key list -->
<component
:is="keyListType"
:config="config"
:client="client"
:keyList="keyList"
@exportBatch="exportBatch">
</component>
<div class='keys-load-more-wrapper'>
<!-- load more -->
<el-button
ref='scanMoreBtn'
class='load-more-keys'
:icon="searching && !loadingAll ? 'el-icon-loading' : ''"
:disabled='scanMoreDisabled || searching'
@click='refreshKeyList(false)'>
{{ $t('message.load_more_keys') }}
</el-button>
<!-- load all -->
<!-- fix el-tooltip 200ms delay when closing -->
<el-tooltip v-if='showLoadAllKeys' :disabled="!loadAllTooltip"
@mouseenter.native="loadAllTooltip=true" @mouseleave.native="loadAllTooltip=false"
effect="dark" :content="$t('message.load_all_keys_tip')"
placement="bottom" :open-delay=380 :enterable='false'>
<el-button
class='load-more-keys'
type= 'danger'
:icon="searching && loadingAll ? 'el-icon-loading' : ''"
:disabled='searching'
@click='loadAllKeys()'>
{{ $t('message.load_all_keys') }}
</el-button>
</el-tooltip>
</div>
</div>
</template>
<script type="text/javascript">
import KeyListVirtualTree from '@/components/KeyListVirtualTree';
export default {
data() {
return {
keyList: [],
keyListType: 'KeyListVirtualTree',
searchPageSize: 10000,
scanStreams: [],
scanningCount: 0,
scanMoreDisabled: false,
onePageKeysCount: 0,
loadAllTooltip: true,
loadingAll: false,
};
},
props: ['client', 'config', 'globalSettings'],
components: { KeyListVirtualTree },
computed: {
keysPageSize() {
const keysPageSize = parseInt(this.globalSettings.keysPageSize);
// custom defined size
if (keysPageSize) {
// cluster mode, pageSize = size / masterNodes
if (this.client.nodes) {
const nodeCount = this.client.nodes('master').length;
return nodeCount ? parseInt(keysPageSize / nodeCount) : keysPageSize;
}
// common mode
return keysPageSize;
}
return 500;
},
showLoadAllKeys() {
// force show
return true;
return this.globalSettings.showLoadAllKeys;
},
searching() {
return this.$parent.$parent.$parent.$refs.operateItem.searchIcon == 'el-icon-loading';
},
},
created() {
// add or remove key from key list directly
this.$bus.$on('refreshKeyList', (client, key = '', type = 'del') => {
// refresh only self connection key list
if (client !== this.client) {
return;
}
// refresh directly
if (!key) {
return this.refreshKeyList();
}
(type == 'del') && this.removeKeyFromKeyList(key);
(type == 'add') && this.addKeyToKeyList(key);
});
},
methods: {
initShow() {
this.refreshKeyList();
},
setDb(db) {
(this.client.condition.select != db) && this.client.select(db);
},
refreshKeyList(resetKeyList = true) {
// reset previous list, not append mode
resetKeyList && this.resetKeyList();
// show searching status
this.setSearchStatus();
// extract search
if (this.$parent.$parent.$parent.$refs.operateItem.searchExact === true) {
return this.refreshKeyListExact();
}
// init scanStream
if (!this.scanStreams.length) {
this.initScanStreamsAndScan();
}
// scan more, resume previous scanStream
else {
// reset one page scan param
this.onePageKeysCount = 0;
for (const stream of this.scanStreams) {
stream.resume();
}
}
},
loadAllKeys() {
this.resetKeyList();
this.loadingAll = true;
// show searching status
this.setSearchStatus();
this.initScanStreamsAndScan(true);
},
initScanStreamsAndScan(loadAll = false) {
const nodes = this.client.nodes ? this.client.nodes('master') : [this.client];
const keysPageSize = loadAll ? 50000 : this.keysPageSize;
this.scanningCount = nodes.length;
nodes.map((node) => {
const scanOption = {
match: this.getMatchMode(),
count: keysPageSize,
};
// scan count is bigger when in search mode
scanOption.match != '*' && (scanOption.count = this.searchPageSize);
const stream = node.scanBufferStream(scanOption);
this.scanStreams.push(stream);
stream.on('data', (keys) => {
if (!keys.length) {
return;
}
this.keyList = this.keyList.concat(keys);
this.onePageKeysCount += keys.length;
// scan once reaches page size
if (this.onePageKeysCount >= keysPageSize && loadAll === false) {
// temp stop
stream.pause();
this.resetSearchStatus();
}
});
stream.on('error', (e) => {
this.resetSearchStatus();
// scan command disabled, other functions may be used normally
if (
(e.message.includes('unknown command') && e.message.includes('scan'))
|| e.message.includes("command 'SCAN' is not allowed")
) {
return this.$message.error({
message: this.$t('message.scan_disabled'),
duration: 1500,
});
}
// other errors
this.$message.error({
message: `Stream On Error: ${e.message}`,
duration: 1500,
});
setTimeout(() => {
this.$bus.$emit('closeConnection');
}, 50);
});
stream.on('end', () => {
// all nodes scan finished(cusor back to 0)
if (--this.scanningCount <= 0) {
this.scanMoreDisabled = true;
this.resetSearchStatus();
}
});
});
},
resetKeyList() {
// cancel scanning
this.cancelScanning();
this.keyList = [];
this.scanStreams = [];
this.onePageKeysCount = 0;
this.scanMoreDisabled = false;
this.loadingAll = false;
},
setSearchStatus() {
// search loading
this.$parent.$parent.$parent.$refs.operateItem.searchIcon = 'el-icon-loading';
// show cancel scanning btn after scanning for a while
this.$parent.$parent.$parent.$refs.operateItem.toggleCancelIcon(true);
},
resetSearchStatus() {
// search input icon recover
this.$parent.$parent.$parent.$refs.operateItem.searchIcon = 'el-icon-search';
// remove cancel scanning btn
this.$parent.$parent.$parent.$refs.operateItem.toggleCancelIcon(false);
// reset loading all status
this.loadingAll = false;
},
refreshKeyListExact() {
const match = this.getMatchMode(false);
this.client.exists(match).then((reply) => {
this.keyList = (reply == 1) ? [Buffer.from(match)] : [];
}).catch((e) => {
this.$message.error(e.message);
}).finally(() => {
this.scanMoreDisabled = true;
this.resetSearchStatus();
});
},
cancelScanning() {
if (this.scanStreams.length) {
for (const stream of this.scanStreams) {
stream.pause && stream.pause();
}
}
},
getMatchMode(fillStar = true) {
let match = this.$parent.$parent.$parent.$refs.operateItem.searchMatch;
match = match || '*';
if (fillStar && !match.match(/\*/)) {
match = (`*${match}*`);
}
return match;
},
removeKeyFromKeyList(key) {
if (!this.keyList) {
return false;
}
for (const i in this.keyList) {
if (this.keyList[i].equals(key)) {
this.keyList.splice(i, 1);
break;
}
}
},
addKeyToKeyList(key) {
if (!this.keyList) {
return false;
}
for (const i in this.keyList) {
if (this.keyList[i].equals(key)) {
// exists already
return;
}
}
this.keyList.push(key);
},
exportBatch(keys) {
const lines = [];
const failed = [];
const promiseQueue = [];
for (const key of keys) {
const promise = this.client.callBuffer('DUMP', key);
const promise1 = this.client.callBuffer('PTTL', key);
promiseQueue.push(promise, promise1);
}
Promise.allSettled(promiseQueue).then((reply) => {
for (let i = 0; i < reply.length; i += 2) {
if (reply[i].status === 'fulfilled') {
const key = keys[i / 2].toString('hex');
const value = reply[i].value.toString('hex');
const ttl = reply[i + 1].value;
const line = `${key},${value},${ttl}`;
lines.push(line);
}
}
// save to file
const file = `Dump_${(new Date()).toISOString().substr(0, 10).replaceAll('-', '')}.csv`;
this.$util.createAndDownloadFile(file, lines.join('\n'));
});
},
},
watch: {
globalSettings(newSetting, oldSetting) {
if (!this.client) {
return;
}
// keys number changed, reload scan streams
if (newSetting.keysPageSize != oldSetting.keysPageSize) {
this.refreshKeyList();
}
},
},
};
</script>
<style type="text/css">
.keys-load-more-wrapper {
display: flex;
}
.keys-load-more-wrapper .load-more-keys {
margin: 10px 5px;
padding: 0;
display: block;
height: 22px;
width: 100%;
font-size: 75%;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/KeyList.vue
|
Vue
|
mit
| 9,646
|
<template>
<div>
<!-- key list -->
<ul class='key-list'>
<RightClickMenu
:items='rightMenus'
:clickValue='key'
:key='key.toString()'
v-for='key of keyList'>
<li class='key-item' :title='key' @click='clickKey(key, $event)'>{{$util.bufToString(key)}}</li>
</RightClickMenu>
</ul>
</div>
</template>
<script type="text/javascript">
import RightClickMenu from '@/components/RightClickMenu';
export default {
data() {
return {
rightMenus: [
{
name: this.$t('message.open'),
click: (clickValue, event) => {
this.clickKey(clickValue, event, false);
},
},
{
name: this.$t('message.open_new_tab'),
click: (clickValue, event) => {
this.clickKey(clickValue, event, true);
},
},
],
};
},
props: ['client', 'config', 'keyList'],
components: { RightClickMenu },
methods: {
clickKey(key, event = null, newTab = false) {
// highlight clicked key
event && this.hightKey(event);
event && (event.ctrlKey || event.metaKey) && (newTab = true);
this.$bus.$emit('clickedKey', this.client, key, newTab);
},
hightKey(event) {
for (const ele of document.querySelectorAll('.key-select')) {
ele.classList.remove('key-select');
}
if (event) {
event.target.classList.add('key-select');
}
},
},
};
</script>
<style type="text/css">
.connection-menu .key-list {
list-style-type: none;
padding-left: 0;
}
.connection-menu .key-list .key-item {
height: 22px;
white-space:nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
color: #292f31;
font-size: 0.9em;
line-height: 1.52;
/*margin-right: 3px;*/
padding-left: 6px;
}
.dark-mode .connection-menu .key-list .key-item {
color: #f7f7f7;
}
.connection-menu .key-list .key-item:hover {
/*color: #3c3d3e;*/
background: #e7ebec;
}
.dark-mode .connection-menu .key-list .key-item:hover {
color: #f7f7f7;
background: #50616b;
}
.connection-menu .key-list .key-item.key-select {
color: #0b7ff7;
background: #e7ebec;
box-sizing: border-box;
border-left: 2px solid #68acf3;
padding-left: 4px;
}
.dark-mode .connection-menu .key-list .key-item.key-select {
color: #f7f7f7;
background: #50616b;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/KeyListNormal.vue
|
Vue
|
mit
| 2,451
|
<template>
<div ref="treeWrapper" class='key-list-vtree'>
<!-- multi operate -->
<div class="batch-operate">
<div class="fixed-col">
<el-checkbox v-model='checkAllSelect' @change='toggleCheckAll' class='select-cancel-all' :title='$t("message.toggle_check_all")'></el-checkbox>
</div>
<div class="flex-col">
<el-row :gutter="6">
<el-col :span="8">
<el-button @click='deleteBatch' type="danger" size="mini">{{ $t('el.upload.delete') }}</el-button>
</el-col>
<el-col :span="8">
<el-button @click='clickItem("export")' type="primary" size="mini">{{ $t('message.export') }}</el-button>
</el-col>
<el-col :span="8">
<el-button @click="hideMultiSelect" type="primary" plain size="mini">{{ $t('el.messagebox.cancel') }}</el-button>
</el-col>
</el-row>
</div>
</div>
<!-- tree list -->
<VueEasyTree
ref="veTree"
node-key="key"
:show-checkbox='multiOperating'
:height="vtreeHeight"
:data="keyNodes"
:props="props"
:indent=10
:itemSize=22
iconClass="fa fa-chevron-right"
:expand-on-click-node='!multiOperating'
:check-on-click-node='multiOperating'
:emptyText="$t('el.tree.emptyText')"
@node-click="nodeClick"
@node-contextmenu="rightClick"
:default-expanded-keys="Array.from(expandedKeys)"
:default-checked-keys="[]"
:auto-expand-parent="false"
@node-expand="nodeExpand"
@node-collapse="nodeCollapse"
@check="nodeCheck"
@click-check="clickCheck"
@node-keydown="nodeKeyDown"
highlight-current
>
<span class="key-list-custom-node" slot-scope="{node, data}" :title="node.label">
<i v-if="!node.isLeaf" :class="node.expanded?'fa fa-folder-open':'fa fa-folder'"></i>
<span>{{ node.label }}</span>
<span v-if="!node.isLeaf" class="key-list-count">({{ data.keyCount }})</span>
</span>
</VueEasyTree>
<!-- right context menu -->
<div ref='rightMenu' class="key-list-right-menu">
<!-- folder right menu -->
<ul v-if="!rightClickNode.isLeaf">
<li @click='clickItem("multiple_select")'>{{ $t('message.multiple_select') }}</li>
<li @click='clickItem("memory_analysis")'>{{ $t('message.memory_analysis') }}</li>
<li @click='clickItem("load_cur_folder")'>{{ $t('message.load_current_folder') }}</li>
<li @click='clickItem("delete_folder")'>{{ $t('message.delete_folder') }}</li>
</ul>
<!-- key right menu -->
<ul v-else>
<li @click='clickItem("copy")'>{{ $t('message.copy') }}</li>
<li @click='clickItem("delete")'>{{ $t('el.upload.delete') }}</li>
<li @click='clickItem("multiple_select")'>{{ $t('message.multiple_select') }}</li>
<li @click='clickItem("open")'>{{ $t('message.open_new_tab') }}</li>
<li @click='clickItem("export")'>{{ $t('message.export') }}Key</li>
</ul>
</div>
</div>
</template>
<script type="text/javascript">
import VueEasyTree from '@qii404/vue-easy-tree';
export default {
data() {
return {
rightClickNode: {},
multiOperating: false,
checkAllSelect: false,
vtreeHeight: 0,
vtreeHeightRaw: 'calc(100vh - 248px)',
vtreeHeightMutiple: 'calc(100vh - 284px)',
treeNodesOverflow: 20e4, // 200k
keyNodes: [],
props: {
label: 'name',
children: 'children',
},
expandedKeys: new Set(),
checkedKeys: [],
rightClickItem: '',
};
},
props: ['client', 'config', 'keyList'],
components: { VueEasyTree },
computed: {
separator() {
return this.config.separator === undefined ? ':' : this.config.separator;
},
},
methods: {
rightClick(event, data, node) {
this.hideAllMenus();
this.$refs.veTree.setCurrentKey(node.key);
this.rightClickNode = node;
// nextTick for dom render
this.$nextTick(() => {
let top = event.clientY;
const menu = this.$refs.rightMenu;
menu.style.display = 'block';
// position in bottom
if (document.body.clientHeight - top < menu.clientHeight) {
top -= menu.clientHeight;
}
menu.style.left = `${event.clientX}px`;
menu.style.top = `${top}px`;
document.addEventListener('click', this.hideAllMenus, { once: true });
});
},
nodeClick(data, node, component, event) {
if (this.multiOperating) {
return;
}
// key clicked
if (!data.children) {
let newTab = false;
event && (event.ctrlKey || event.metaKey) && (newTab = true);
this.clickKey(Buffer.from(data.nameBuffer.data), newTab);
}
// folder click, do nothing
},
nodeExpand(data, node, component) {
this.expandedKeys.add(data.key);
// async sort nodes
if (!node.customSorted) {
node.customSorted = true;
this.$util.sortByTreeNodes(node.childNodes);
}
},
nodeCollapse(data, node, component) {
this.expandedKeys.delete(data.key);
},
nodeCheck(data, state) {
const node = this.$refs.veTree.getNode(data);
const event = (window.event.type === 'click') ? window.event : this.clickCheckEvent;
// handle shift to multi check
this.multipleCheck(node, event);
},
clickCheck(event) {
// add 'click' event when toggle checkbox, default only 'check' event
this.clickCheckEvent = event;
},
nodeKeyDown(node, event) {
if (!node) {
return;
}
const { data } = node;
this.$refs.veTree.setCurrentKey(node.key);
// up & down, key node
if (['ArrowUp', 'ArrowDown'].includes(event.key) && !data.children) {
this.clickKey(Buffer.from(data.nameBuffer.data));
}
},
showMultiSelect() {
this.multiOperating = true;
this.$refs.treeWrapper.classList.add('show-checkbox');
// adjust vtree height
this.vtreeHeight = this.vtreeHeightMutiple;
},
hideMultiSelect() {
this.multiOperating = false;
this.checkAllSelect = false;
this.$refs.veTree.setCheckedAll(false);
this.$refs.treeWrapper.classList.remove('show-checkbox');
// recover vtree height
this.vtreeHeight = this.vtreeHeightRaw;
},
hideAllMenus() {
const menus = document.querySelectorAll('.key-list-right-menu');
if (menus.length === 0) {
return;
}
for (const menu of menus) {
menu.style.display = 'none';
}
},
clickItem(type) {
this.rightClickItem = type;
switch (type) {
// copy key name
case 'copy': {
const { clipboard } = require('electron');
clipboard.writeText(this.rightClickNode.data.name);
break;
}
// del single key["delete" in the key right menu]
case 'delete': {
// del batch instead of single when multi operating
if (this.multiOperating) {
return this.deleteBatch();
}
const keyBuffer = Buffer.from(this.rightClickNode.data.nameBuffer.data);
this.client.del(keyBuffer).then((reply) => {
if (reply == 1) {
this.$message.success({
message: this.$t('message.delete_success'),
duration: 1000,
});
this.$bus.$emit('refreshKeyList', this.client, keyBuffer, 'del');
} else {
this.$message.error(this.$t('message.delete_failed'));
}
}).catch((e) => { this.$message.error(e.message); });
break;
}
// select multiple
case 'multiple_select': {
this.showMultiSelect();
break;
}
// open key in new tab
case 'open': {
this.clickKey(Buffer.from(this.rightClickNode.data.nameBuffer.data), true);
break;
}
// delete whole folder
case 'delete_folder': {
const rule = { pattern: [this.rightClickNode.data.fullName] };
this.$bus.$emit('openDelBatch', this.client, this.config.connectionName, rule);
break;
}
// memory analysis
case 'memory_analysis': {
const pattern = this.rightClickNode.data.fullName;
this.$bus.$emit('memoryAnalysis', this.client, this.config.connectionName, pattern);
break;
}
case 'export': {
this.showMultiSelect();
this.exportBatch();
break;
}
case 'load_cur_folder': {
const pattern = this.rightClickNode.data.fullName;
this.$bus.$emit('changeMatchMode', this.client, pattern);
break;
}
}
},
toggleCheckAll(checked) {
return this.$refs.veTree.setCheckedAll(checked);
},
deleteBatch() {
const rule = { key: [], pattern: [] };
const checkedNodes = this.$refs.veTree.getCheckedNodes();
for (const node of checkedNodes) {
// key node
if (!node.children) {
rule.key.push(Buffer.from(node.nameBuffer.data));
}
}
this.hideMultiSelect();
this.$bus.$emit('openDelBatch', this.client, this.config.connectionName, rule);
},
exportBatch() {
const checkedNodes = this.$refs.veTree.getCheckedNodes();
const keys = [];
if (!checkedNodes.length) {
this.$message.warning('Please select keys!');
return;
}
for (const node of checkedNodes) {
// key node
if (!node.children) {
keys.push(Buffer.from(node.nameBuffer.data));
}
}
this.hideMultiSelect();
this.$emit('exportBatch', keys);
},
clickKey(key, newTab = false) {
this.$bus.$emit('clickedKey', this.client, key, newTab);
},
multipleCheck(node, event) {
if (!event.shiftKey || !this.lastKey || node.key === this.lastKey) {
this.lastKey = node.key;
this.lastY = event.screenY;
this.lastChecked = node.checked;
return;
}
const tree = this.$refs.veTree;
const curKey = node.key;
const direction = (event.screenY - this.lastY) <= 0 ? 'up' : 'down';
const topKey = direction == 'up' ? curKey : this.lastKey;
const bottomKey = direction == 'up' ? this.lastKey : curKey;
let bottomNode = tree.getNode(bottomKey);
const bottomNodeParents = new Set();
// get all bottom node parents
while (bottomNode.parent) {
bottomNode = bottomNode.parent;
bottomNodeParents.add(bottomNode.key);
}
let start = false;
const selectedNodes = [];
// collect all nodes which need to be checked, from bottom to top
for (let i = tree.dataList.length - 1; i >= 0; i--) {
const item = tree.dataList[i];
if (!start) {
if (item.key === bottomKey) {
direction === 'down' && selectedNodes.push(item);
start = true;
}
continue;
}
if (item.key === topKey) {
direction === 'up' && selectedNodes.push(item);
break;
}
selectedNodes.push(item);
}
const checkRecursive = (node, checked = true) => {
node.checked = checked;
// folder node
if (node.childNodes.length) {
for (const item of node.childNodes) {
checkRecursive(item, checked);
}
}
};
for (const item of selectedNodes) {
if (bottomNodeParents.has(item.key)) {
continue;
}
checkRecursive(item, this.lastChecked);
}
// reinit folder node check status
this.$refs.veTree.store._initCheckRecursive(tree.root);
},
},
watch: {
keyList(newList) {
let newListCopy = newList;
// size limit
if (newList.length > this.treeNodesOverflow) {
// force cut
newListCopy = newList.slice(0, this.treeNodesOverflow);
// using nextTick to relieve msg missing caused by app stuck
this.$nextTick(() => {
this.$message.warning({
message: this.$t('message.tree_node_overflow', { num: this.treeNodesOverflow }),
duration: 6000,
});
});
}
// backup checked keys
this.checkedKeys = this.$refs.veTree.getCheckedKeys(true);
const keyNodes = this.separator
? this.$util.keysToTree(newListCopy, this.separator, this.expandedKeys, this.treeNodesOverflow)
: this.$util.keysToList(newListCopy);
this.keyNodes = keyNodes;
this.$nextTick(() => {
// sort outermost layer nodes
this.$util.sortByTreeNodes(this.$refs.veTree.root.childNodes);
// recheck checked nodes
this.$refs.veTree.setCheckedLeafKeys(this.checkedKeys);
// little keys such as extract search, expand all
if (newListCopy.length <= 20) {
this.$refs.veTree.setExpandAll(true);
}
});
},
},
created() {
this.vtreeHeight = this.vtreeHeightRaw;
},
};
</script>
<style>
.key-list-vtree {
height: calc(100vh - 250px);
}
/*vtree container*/
.key-list-vtree .vue-recycle-scroller {
width: calc(100% + 2px);
}
/*replace transform to avoid font blurry*/
.key-list-vtree .vue-recycle-scroller.ready .vue-recycle-scroller__item-view {
will-change: auto;
}
/*vtree scrollbat style*/
/*blur status*/
.key-list-vtree .vue-recycle-scroller::-webkit-scrollbar-thumb {
border: 3px dashed transparent;
background-clip: padding-box;
}
.key-list-vtree .vue-recycle-scroller::-webkit-scrollbar-track {
background: transparent;
}
/*focus status*/
.key-list-vtree .vue-recycle-scroller::-webkit-scrollbar-thumb:hover {
background: #7f7f7f;
}
.key-list-vtree .vue-recycle-scroller::-webkit-scrollbar-track:hover {
background: #e0e0dd;
}
/*focus status darkmode*/
.dark-mode .key-list-vtree .vue-recycle-scroller::-webkit-scrollbar-thumb:hover {
background: #6a838f;
}
.dark-mode .key-list-vtree .vue-recycle-scroller::-webkit-scrollbar-track:hover {
background: #495961;
}
/*vtree scrollbat style end*/
/*node item*/
.key-list-vtree .el-tree-node {
font-size: 14px;
}
.key-list-vtree .el-tree-node .el-tree-node__content {
padding-left: 3px;
padding-right: 3px;
margin-right: 1px;
}
/*node hover color*/
.key-list-vtree .el-tree-node > .el-tree-node__content:hover {
background-color: #e7e7e7;
}
.dark-mode .key-list-vtree .el-tree-node > .el-tree-node__content:hover {
background-color: #50616b;
}
/*current select node color*/
.key-list-vtree .el-tree-node.is-current > .el-tree-node__content {
background-color: #d4d4d4;
}
.dark-mode .key-list-vtree .el-tree-node.is-current > .el-tree-node__content {
background-color: #50616b;
}
/*inner custom node item*/
.key-list-vtree .key-list-custom-node {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
/*note the following 2 items should be same value, may not consist with itemSize*/
height: 22px;
line-height: 22px;
}
/*checkbox*/
.key-list-vtree .el-tree-node__content>label.el-checkbox {
margin-right: 4px;
}
/*expand icon*/
.key-list-vtree .el-tree-node__content>.el-tree-node__expand-icon {
padding: 0;
font-size: 76%;
}
/*expand icon for folder*/
.key-list-vtree .el-tree-node__content>.el-tree-node__expand-icon:not(.is-leaf) {
margin-right: 6px;
color: #7b7b7b;
}
/*expand icon for key, inner level key, align with folder*/
.key-list-vtree .el-tree-node__content>.el-tree-node__expand-icon.is-leaf {
margin-right: 6px;
}
/*expand icon for key, first level key, stay left*/
.key-list-vtree .el-tree-node__content>.el-tree-node__expand-icon.is-leaf.level1 {
margin-right: -4px;
}
/*folder icon*/
.key-list-vtree .key-list-custom-node .fa {
color: #848a90;
font-size: 115%;
}
.dark-mode .key-list-vtree .key-list-custom-node .fa {
color: #9ea4a9;
}
/*folder keys count*/
.key-list-vtree .key-list-count {
color: #848a90;
float: right;
}
.dark-mode .key-list-vtree .key-list-count {
color: #a3a6ad;
}
/*batch operate btn container*/
.key-list-vtree .batch-operate {
display: none;
margin-bottom: 8px;
}
.key-list-vtree.show-checkbox .batch-operate {
display: block;
}
/*select\cancel select all col*/
.key-list-vtree .batch-operate .fixed-col {
float: left;
width: 20px;
line-height: 22px;
}
/*second col*/
.key-list-vtree .batch-operate .flex-col {
margin-left: 25px;
}
.key-list-vtree .batch-operate .flex-col button {
width: 100%;
}
/*checkbox*/
.key-list-vtree .batch-operate .select-cancel-all {
padding: 3px;
}
/* right menu style start */
.key-list-right-menu {
display: none;
position: fixed;
top: 0;
left: 0;
padding: 0px;
z-index: 99999;
overflow: hidden;
border-radius: 3px;
border: 2px solid lightgrey;
background: #fafafa;
}
.dark-mode .key-list-right-menu {
background: #263238;
}
.key-list-right-menu ul {
list-style: none;
padding: 0px;
}
.key-list-right-menu ul li:not(:last-child) {
border-bottom: 1px solid lightgrey;
}
.key-list-right-menu ul li {
font-size: 13.4px;
padding: 6px 10px;
cursor: pointer;
color: #263238;
}
.dark-mode .key-list-right-menu ul li {
color: #fff;
}
.key-list-right-menu ul li:hover {
background: #e4e2e2;
}
.dark-mode .key-list-right-menu ul li:hover {
background: #344A4E;
}
/* right menu style end */
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/KeyListVirtualTree.vue
|
Vue
|
mit
| 17,453
|
<template>
<!-- language select -->
<el-select v-model="selectedLang" @change="changeLang" placeholder="Language">
<el-option
v-for="item in langItems"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script type="text/javascript">
export default {
data() {
return {
selectedLang: 'en',
langItems: [
{ value: 'en', label: 'English' },
{ value: 'cn', label: '简体中文' },
{ value: 'tw', label: '繁體中文' },
{ value: 'tr', label: 'Türkçe' },
{ value: 'ru', label: 'Русский' },
{ value: 'pt', label: 'Português' },
{ value: 'de', label: 'Deutsch' },
{ value: 'fr', label: 'Français' },
{ value: 'ua', label: 'Українською' },
{ value: 'it', label: 'Italiano' },
{ value: 'es', label: 'Español' },
{ value: 'ko', label: '한국어' },
],
};
},
methods: {
changeLang(lang) {
localStorage.lang = this.selectedLang;
this.$i18n.locale = this.selectedLang;
},
},
mounted() {
this.selectedLang = localStorage.lang || this.selectedLang;
},
};
</script>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/LanguageSelector.vue
|
Vue
|
mit
| 1,219
|
<template>
<div class="memory-analysis-container">
<el-card class="box-card">
<!-- card title -->
<div slot="header" class="clearfix">
<!-- setting dialog -->
<el-popover
placement="bottom"
width="40"
trigger="hover">
<div>
<p>If result is "0", the <b>MEMORY</b> command may be disabled on Redis.</p>
<p style="margin: 0;">Filter Min Size:</p>
<el-input v-model="minSizeKB" @keyup.native.enter="initKeys()" size="mini">
<i slot="suffix">KB</i>
</el-input>
</div>
<i slot="reference" class="el-icon-setting"></i>
</el-popover>
<span class="analysis-title">{{ $t('message.memory_analysis') }}</span>
<i v-if="isScanning" class='el-icon-loading'></i>
<el-tag size="mini">
Total: {{keysList.length}}
Size: {{$util.humanFileSize(totalSize)}}
</el-tag>
<!-- operate btn -->
<el-button v-if="scanningEnd" @click="initKeys" class="operate-btn" type="primary">
<i class="fa fa-refresh"> {{ $t('message.restart') }}</i>
</el-button>
<el-button v-else-if="isScanning" @click="toggleScanning(true)" class="operate-btn" type="danger">
<i class="fa fa-pause"> {{ $t('message.pause') }}</i>
</el-button>
<el-button v-else @click="toggleScanning(false)" class="operate-btn">
<i class="fa fa-play"> {{ $t('message.begin') }}</i>
</el-button>
</div>
<!-- table header -->
<div class="keys-header">
<span class="header-title">
Key
<el-tag v-if="pattern" size="mini"><i class="fa fa-search"></i> {{pattern}}</el-tag>
</span>
<span @click="toggleOrder" class="size-container">
<span class="header-title">Size</span>
<span class="el-icon-d-caret"></span>
</span>
</div>
<!-- keys list -->
<RecycleScroller
class="keys-body"
:items="keysList"
:item-size="24"
key-field="str"
v-slot="{ item, index }"
>
<li @click="clickJump(item)">
<span class="list-index">{{ index + 1 }}.</span>
<span class="key-name" :title="item.str">{{ item.str }}</span>
<!-- <span class="size">{{ item.human }}</span> -->
<span class="size">
<el-tag size="mini">{{ item.human }}</el-tag>
</span>
</li>
</RecycleScroller>
<!-- table footer -->
<div class="keys-footer">
<el-tag>{{ $t('message.max_display', {num: scanMax}) }}</el-tag>
</div>
</el-card>
</div>
</template>
<script type="text/javascript">
import { RecycleScroller } from 'vue-virtual-scroller';
export default {
data() {
return {
keysList: [],
isScanning: false,
scanningEnd: false,
scanStreams: [],
sortOrder: '',
scanMax: 200000,
scanPageSize: 2000,
totalSize: 0,
minSizeKB: 0,
};
},
props: ['client', 'hotKeyScope', 'pattern'],
components: { RecycleScroller },
computed: {
minSizeB() {
return parseInt(this.minSizeKB) * 1024;
},
},
methods: {
initKeys() {
this.keysList = [];
this.totalSize = 0;
this.isScanning = true;
this.scanningEnd = false;
this.initScanStreamsAndScan(this.pattern ? this.pattern : '');
},
initScanStreamsAndScan(pattern = '') {
const nodes = this.client.nodes ? this.client.nodes('master') : [this.client];
this.scanningCount = nodes.length;
nodes.map((node) => {
const scanOption = {
match: `${pattern}*`,
count: this.scanPageSize,
};
const stream = node.scanBufferStream(scanOption);
this.scanStreams.push(stream);
stream.on('data', (keys) => {
// waiting for memory analysis
stream.pause();
// limit scanning max count
if (this.keysList.length > this.scanMax) {
this.$message.warning(`${this.$t('message.max_scan', { num: this.scanMax })}, stopped.`);
this.scanningEnd = true;
return this.toggleScanning(true);
}
const keysWithMemory = [];
const promise = this.initKeysMemory(keys, keysWithMemory);
promise.then(() => {
// add interval between rendering
setTimeout(() => {
this.keysList = this.keysList.concat(keysWithMemory);
this.reOrder('desc');
this.isScanning && stream.resume();
}, 100);
// size count
this.totalSize += keysWithMemory.reduce((sum, item) => sum + parseInt(item.size), 0);
});
});
stream.on('error', (e) => {
this.toggleScanning(true);
this.$message.error(`Memory Analysis Stream On Error: ${e.messag}`);
});
stream.on('end', () => {
// all nodes scan finished(cusor back to 0)
if (--this.scanningCount <= 0) {
this.isScanning = false;
this.scanningEnd = true;
}
});
});
},
// todo: should avoid logging too many commands!
initKeysMemory(keys, keysWithMemory) {
if (!keys) {
return;
}
const allPromise = [];
for (const key of keys) {
// not logging
this.client.withoutLogging = true;
const promise = this.client.call('MEMORY', 'USAGE', key).then((reply) => {
// filter min size
if (this.minSizeB && reply < this.minSizeB) {
return;
}
keysWithMemory.push({
key, str: this.$util.bufToString(key), size: reply, human: this.$util.humanFileSize(reply),
});
}).catch((e) => {
keysWithMemory.push({
key, str: this.$util.bufToString(key), size: 0, human: 0,
});
});
allPromise.push(promise);
}
return Promise.all(allPromise);
},
clickJump(item) {
this.$bus.$emit('clickedKey', this.client, item.key, true);
},
toggleScanning(pause = true) {
// stop scanning
if (pause) {
this.isScanning = false;
if (this.scanStreams.length) {
for (const stream of this.scanStreams) {
stream.pause && stream.pause();
}
}
return;
}
if (this.scanningEnd) {
return;
}
// resume scanning
this.isScanning = true;
if (this.scanStreams.length) {
for (const stream of this.scanStreams) {
stream.pause && stream.resume();
}
}
},
toggleOrder() {
if (this.isScanning) {
return;
}
this.sortOrder = (this.sortOrder == 'desc' ? 'asc' : 'desc');
this.reOrder();
},
reOrder(order = null) {
order !== null && (this.sortOrder = order);
// sorting
if (this.sortOrder == 'asc') {
this.keysList.sort((a, b) => a.size - b.size);
} else {
this.keysList.sort((a, b) => b.size - a.size);
}
},
initShortcut() {
this.$shortcut.bind('ctrl+r, ⌘+r, f5', this.hotKeyScope, () => {
// scanning not finished, return
if (!this.scanningEnd) {
return false;
}
this.initKeys();
return false;
});
},
},
mounted() {
this.initKeys();
this.initShortcut();
},
beforeDestroy() {
this.$shortcut.deleteScope(this.hotKeyScope);
this.toggleScanning(true);
},
};
</script>
<style type="text/css">
.memory-analysis-container .analysis-title {
font-weight: bold;
font-size: 120%;
}
.memory-analysis-container .operate-btn {
float: right;
}
/*keys header container*/
.memory-analysis-container .keys-header {
margin: 2px 0 14px 0;
user-select: none;
}
.memory-analysis-container .keys-header .header-title {
font-weight: bold;
}
.memory-analysis-container .keys-header .size-container {
float: right;
cursor: pointer;
}
/*keys body list*/
.memory-analysis-container .keys-body {
height: calc(100vh - 268px);
}
/*keys body li*/
.memory-analysis-container .keys-body li {
border-bottom: 1px solid #e6e6e6;
cursor: pointer;
padding: 0 0 0 4px;
margin-right: 2px;
font-size: 92%;
list-style: none;
display: flex;
/*same with item-size*/
line-height: 24px;
}
.dark-mode .memory-analysis-container .keys-body li {
border-bottom: 1px solid #3b4d57;
}
.memory-analysis-container .keys-body li:hover {
background: #e6e6e6;
}
.dark-mode .memory-analysis-container .keys-body li:hover {
background: #3b4d57;
}
/*key name*/
.memory-analysis-container .keys-body li .key-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/*key size*/
.memory-analysis-container .keys-body .size {
/*font-size: 90%;*/
margin-left: 20px;
margin-right: 4px;
}
/*keys footer*/
.memory-analysis-container .keys-footer {
text-align: center;
line-height: 40px;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/MemoryAnalysis.vue
|
Vue
|
mit
| 9,051
|
<template>
<el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :append-to-body='true' :close-on-click-modal='false' class='new-connection-dailog' width='90%'>
<!-- redis connection form -->
<el-form :label-position="labelPosition" label-width="90px">
<el-row :gutter=20>
<!-- left col -->
<el-col :span=12>
<el-form-item :label="$t('message.host')" required>
<el-input v-model="connection.host" autocomplete="off" placeholder="127.0.0.1"></el-input>
</el-form-item>
<el-form-item :label="$t('message.password')">
<InputPassword v-model="connection.auth" placeholder="Auth"></InputPassword>
</el-form-item>
<el-form-item :label="$t('message.connection_name')">
<el-input v-model="connection.name" autocomplete="off"></el-input>
</el-form-item>
</el-col>
<!-- right col -->
<el-col :span=12>
<el-form-item :label="$t('message.port')" required>
<el-input type='number' v-model="connection.port" autocomplete="off" placeholder="6379"></el-input>
</el-form-item>
<el-form-item :label="$t('message.username')">
<el-input v-model="connection.username" placeholder='ACL in Redis >= 6.0' autocomplete="off"></el-input>
</el-form-item>
<el-form-item :label="$t('message.separator')">
<el-tooltip effect="dark">
<div slot="content">{{ $t('message.separator_tip') }}</div>
<el-input v-model="connection.separator" autocomplete="off" placeholder='Empty To Disable Tree View'></el-input>
</el-tooltip>
</el-form-item>
</el-col>
</el-row>
<!-- other operation -->
<el-form-item label="">
<el-checkbox v-model="sshOptionsShow">SSH</el-checkbox>
<el-checkbox v-model="sslOptionsShow">SSL</el-checkbox>
<el-checkbox v-model="sentinelOptionsShow">
Sentinel
<el-popover trigger="hover">
<i slot="reference" class="el-icon-question"></i>
{{ $t('message.sentinel_faq') }}
</el-popover>
</el-checkbox>
<el-checkbox v-model="connection.cluster">
Cluster
<el-popover trigger="hover">
<i slot="reference" class="el-icon-question"></i>
{{ $t('message.cluster_faq') }}
</el-popover>
</el-checkbox>
<el-checkbox v-model="connection.connectionReadOnly">
Readonly
<el-popover trigger="hover">
<i slot="reference" class="el-icon-question"></i>
{{ $t('message.connection_readonly') }}
</el-popover>
</el-checkbox>
</el-form-item>
</el-form>
<!-- ssh connection form -->
<el-form v-if="sshOptionsShow" v-show="sshOptionsShow" label-position='top' label-width="90px">
<fieldset>
<legend>SSH Tunnel</legend>
</fieldset>
<el-row :gutter=20>
<!-- left col -->
<el-col :span=12>
<el-form-item :label="$t('message.host')" required>
<el-input v-model="connection.sshOptions.host" autocomplete="off"></el-input>
</el-form-item>
<el-form-item :label="$t('message.username')" required>
<el-input v-model="connection.sshOptions.username" autocomplete="off"></el-input>
</el-form-item>
<el-form-item :label="$t('message.private_key')">
<FileInput
:file.sync='connection.sshOptions.privatekey'
:bookmark.sync='connection.sshOptions.privatekeybookmark'
placeholder='SSH Private Key'>
</FileInput>
</el-form-item>
<el-form-item label="Passphrase">
<InputPassword v-model="connection.sshOptions.passphrase" placeholder='Passphrase for Private Key'></InputPassword>
</el-form-item>
</el-col>
<!-- right col -->
<el-col :span=12>
<el-form-item :label="$t('message.port')" required>
<el-input type='number' v-model="connection.sshOptions.port" autocomplete="off"></el-input>
</el-form-item>
<el-form-item :label="$t('message.password')">
<InputPassword v-model="connection.sshOptions.password" placeholder="SSH Password"></InputPassword>
</el-form-item>
<el-form-item :label="$t('message.timeout')">
<el-input type='number' v-model="connection.sshOptions.timeout" autocomplete="off" placeholder='SSH Timeout (Seconds)'></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<!-- SSL connection form -->
<el-form v-if="sslOptionsShow" v-show="sslOptionsShow" label-position='top' label-width="90px">
<fieldset>
<legend>SSL</legend>
</fieldset>
<el-row :gutter=20>
<!-- left col -->
<el-col :span=12>
<el-form-item :label="$t('message.private_key')">
<FileInput
:file.sync='connection.sslOptions.key'
:bookmark.sync='connection.sslOptions.keybookmark'
placeholder='SSL Private Key Pem (key)'>
</FileInput>
</el-form-item>
<el-form-item :label="$t('message.authority')">
<FileInput
:file.sync='connection.sslOptions.ca'
:bookmark.sync='connection.sslOptions.cabookmark'
placeholder='SSL Certificate Authority (CA)'>
</FileInput>
</el-form-item>
</el-col>
<!-- right col -->
<el-col :span=12>
<el-form-item :label="$t('message.public_key')">
<FileInput
:file.sync='connection.sslOptions.cert'
:bookmark.sync='connection.sslOptions.certbookmark'
placeholder='SSL Public Key Pem (cert)'>
</FileInput>
</el-form-item>
</el-col>
</el-row>
</el-form>
<!-- Sentinel connection form -->
<el-form v-if="sentinelOptionsShow" v-show="sentinelOptionsShow" label-position='top' label-width="90px">
<fieldset>
<legend>Sentinel</legend>
</fieldset>
<el-row :gutter=20>
<!-- left col -->
<el-col :span=12>
<el-form-item :label="$t('message.redis_node_password')">
<InputPassword v-model="connection.sentinelOptions.nodePassword" placeholder='Redis Node Password'></InputPassword>
</el-form-item>
</el-col>
<!-- right col -->
<el-col :span=12>
<el-form-item :label="$t('message.master_group_name')" required>
<el-input v-model="connection.sentinelOptions.masterName" autocomplete="off" placeholder='Master Group Name'></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">{{ $t('el.messagebox.cancel') }}</el-button>
<el-button type="primary" @click="editConnection">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
</template>
<script type="text/javascript">
import storage from '@/storage';
import FileInput from '@/components/FileInput';
import InputPassword from '@/components/InputPassword';
export default {
data() {
return {
dialogVisible: false,
labelPosition: 'top',
oldKey: '',
connection: {
host: '',
port: '',
auth: '',
username: '',
name: '',
separator: ':',
cluster: false,
connectionReadOnly: false,
sshOptions: {
host: '',
port: 22,
username: '',
password: '',
privatekey: '',
passphrase: '',
timeout: 30,
},
sslOptions: {
key: '',
cert: '',
ca: '',
},
sentinelOptions: {
masterName: 'mymaster',
nodePassword: '',
},
},
connectionEmpty: {},
sshOptionsShow: false,
sslOptionsShow: false,
sentinelOptionsShow: false,
};
},
components: { FileInput, InputPassword },
props: {
config: {
default: _ => new Array(),
},
editMode: {
default: false,
},
},
computed: {
dialogTitle() {
return this.editMode ? this.$t('message.edit_connection')
: this.$t('message.new_connection');
},
},
methods: {
show() {
this.dialogVisible = true;
this.resetFields();
},
resetFields() {
// edit connection mode
if (this.editMode) {
this.sshOptionsShow = !!this.config.sshOptions;
this.sslOptionsShow = !!this.config.sslOptions;
this.sentinelOptionsShow = !!this.config.sentinelOptions;
// recovery connection before edit
const connection = Object.assign({}, this.connectionEmpty, this.config);
this.connection = JSON.parse(JSON.stringify(connection));
}
// new connection mode
else {
this.sshOptionsShow = false;
this.sslOptionsShow = false;
this.sentinelOptionsShow = false;
this.connection = JSON.parse(JSON.stringify(this.connectionEmpty));
}
},
editConnection() {
const config = JSON.parse(JSON.stringify(this.connection));
if (this.sentinelOptionsShow && config.cluster) {
return this.$message.error('Sentinel & Cluster cannot be checked together!');
}
!config.host && (config.host = '127.0.0.1');
!config.port && (config.port = 6379);
if (!this.sshOptionsShow || !config.sshOptions.host) {
delete config.sshOptions;
}
if (!this.sslOptionsShow) {
delete config.sslOptions;
}
if (!this.sentinelOptionsShow || !config.sentinelOptions.masterName) {
delete config.sentinelOptions;
}
const oldKey = storage.getConnectionKey(this.config);
storage.editConnectionByKey(config, oldKey);
this.dialogVisible = false;
this.$emit('editConnectionFinished', config);
},
},
mounted() {
// back up the empty connection
this.connectionEmpty = JSON.parse(JSON.stringify(this.connection));
// edit mode
if (this.editMode) {
this.sslOptionsShow = !!this.config.sslOptions;
this.sshOptionsShow = !!this.config.sshOptions;
this.sentinelOptionsShow = !!this.config.sentinelOptions;
this.connection = Object.assign({}, this.connection, this.config);
}
delete this.connection.connectionName;
},
};
</script>
<style type="text/css">
.new-connection-dailog .el-checkbox {
margin-left: 0;
margin-right: 15px;
}
.new-connection-dailog .el-dialog {
max-width: 900px;
}
.new-connection-dailog fieldset {
border-width: 2px 0 0 0;
border-color: #fff;
font-weight: bold;
color: #bdc5ce;
font-size: 105%;
margin-bottom: 3px;
}
.dark-mode .new-connection-dailog fieldset {
color: #416586;
border-color: #7b95ad;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/NewConnectionDialog.vue
|
Vue
|
mit
| 11,067
|
<template>
<!-- operate item -->
<el-form class="connection-form" size="mini">
<el-form-item>
<el-row :gutter="6">
<!-- db index select -->
<el-col :span="12">
<el-select class="db-select" v-model="selectedDbIndex" placeholder="DB" @change="changeDb()" filterable default-first-option>
<el-option
v-for="index in dbs"
:key="index"
:label="`DB${index}`"
:value="index">
<span>
{{`DB${index}`}}
<span class="db-select-key-count" v-if="dbKeysCount[index]">[{{dbKeysCount[index]}}]</span>
<span class="db-select-custom-name">
<span class="db-select-key-count">{{dbNames[index]}}</span>
<span class="el-icon-edit-outline" @click.stop.prevent='customDbName(index)'></span>
</span>
</span>
</el-option>
<!-- <span slot="prefix" class="fa fa-sitemap" style="font-size: 80%"></span> -->
</el-select>
</el-col>
<!-- new key btn -->
<el-col :span="12">
<el-button class="new-key-btn" @click="newKeyDialog=true">
<i class="el-icon-plus"></i>
{{ $t('message.add_new_key') }}
</el-button>
</el-col>
</el-row>
</el-form-item>
<!-- search match -->
<!-- <el-form-item class="search-item">
<el-row>
<el-col :span="24">
<el-input class="search-input" v-model="searchMatch" @keyup.enter.native="changeMatchMode()" :placeholder="$t('message.enter_to_search')" size="mini">
<span slot="suffix">
<i class="el-input__icon search-icon" :class="searchIcon" @click="changeMatchMode()"></i>
<el-tooltip effect="dark" :content="$t('message.exact_search')" placement="bottom">
<el-checkbox v-model="searchExact"></el-checkbox>
</el-tooltip>
</span>
</el-input>
</el-col>
</el-row>
</el-form-item> -->
<!-- autocomplete search input -->
<el-form-item class="search-item">
<el-autocomplete
class="search-input"
v-model="searchMatch"
@select="changeMatchMode"
@keyup.enter="changeMatchMode()"
:debounce="searchDebounce"
:fetch-suggestions="querySearch"
:placeholder="$t('message.enter_to_search')"
:trigger-on-focus="false"
:select-when-unmatched='true'>
<template slot="suffix">
<!-- cancel search -->
<i v-if="(searchIcon=='el-icon-loading') && showCancelIcon" class="el-input__icon search-icon el-icon-error" @click="cancelSearch()" :title="$t('el.messagebox.cancel')"></i>
<!-- start search -->
<i class="el-input__icon search-icon" :class="searchIcon" @click="changeMatchMode()"></i>
<!-- extract search -->
<el-tooltip effect="dark" :content="$t('message.exact_search')" placement="bottom">
<el-checkbox v-model="searchExact"></el-checkbox>
</el-tooltip>
</template>
</el-autocomplete>
</el-form-item>
<!-- new key dialog -->
<el-dialog :title="$t('message.add_new_key')" :visible.sync="newKeyDialog" :close-on-click-modal='false' append-to-body>
<el-form label-position="top" size="mini">
<el-form-item :label="$t('message.key_name')">
<el-input v-model='newKeyName'></el-input>
</el-form-item>
<el-form-item :label="$t('message.key_type')">
<el-select style='width: 100%' v-model="selectedNewKeyType">
<el-option
v-for="(type, showType) in newKeyTypes"
:key="type"
:label="showType"
:value="type">
</el-option>
</el-select>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="newKeyDialog = false">{{ $t('el.messagebox.cancel') }}</el-button>
<el-button type="primary" @click="addNewKey">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
</el-form>
</template>
<script type="text/javascript">
export default {
data() {
return {
dbs: [0],
selectedDbIndex: 0,
searchMatch: '',
searchExact: false,
searchIcon: 'el-icon-search',
searchHistory: new Set(),
searchDebounce: 100,
newKeyDialog: false,
newKeyName: '',
selectedNewKeyType: 'string',
newKeyTypes: {
String: 'string',
Hash: 'hash',
List: 'list',
Set: 'set',
Zset: 'zset',
Stream: 'stream',
ReJSON: 'rejson',
},
dbKeysCount: {},
dbNames: {},
showCancelIcon: false,
rmCancelIconTimer: null,
};
},
props: ['client', 'config'],
created() {
this.$bus.$on('changeDb', (client, dbIndex) => {
if (!this.client || client.options.connectionName != this.client.options.connectionName) {
return;
}
if (this.client.condition.select == dbIndex) {
return;
}
this.changeDb(dbIndex);
});
this.$bus.$on('changeMatchMode', (client, pattern) => {
if (client !== this.client) {
return;
}
this.searchMatch = pattern;
this.changeMatchMode();
});
},
methods: {
initShow() {
this.initDatabaseSelect();
this.initCustomDbName();
},
setDb(db) {
this.selectedDbIndex = db;
},
initDatabaseSelect() {
this.client.config('get', 'databases').then((reply) => {
this.dbs = [...Array(parseInt(reply[1])).keys()];
this.getDatabasesFromInfo();
}).catch((e) => {
// config command may be renamed
this.dbs = [...Array(16).keys()];
// read dbs from info
this.getDatabasesFromInfo(true);
});
},
initCustomDbName() {
const dbKey = this.$storage.getStorageKeyByName('custom_db', this.config.connectionName);
const customNames = JSON.parse(localStorage.getItem(dbKey));
if (customNames) {
this.dbNames = customNames;
}
},
getDatabasesFromInfo(guessMaxDb = false) {
if (!this.client) {
return;
}
this.dbKeysCount = {};
this.client.info().then((info) => {
const keyspace = info.split('# Keyspace')[1].trim().split('\n');
let keyCount = [];
for (const line of keyspace) {
keyCount = line.match(/db(\d+)\:keys=(\d+)/);
keyCount && this.$set(this.dbKeysCount, keyCount[1], keyCount[2]);
}
if (!guessMaxDb || !keyCount || !keyCount[1]) {
return;
}
// max/last db which exists keys
const maxDb = parseInt(keyCount[1]);
if (maxDb > 16) {
this.dbs = [...Array(maxDb + 1).keys()];
}
}).catch(() => {});
},
resetStatus() {
this.dbs = [0];
// this.selectedDbIndex = 0;
this.searchMatch = '';
this.searchExact = false;
},
changeDb(dbIndex = false) {
if (dbIndex !== false) {
this.selectedDbIndex = parseInt(dbIndex);
}
this.client.select(this.selectedDbIndex)
.then(() => {
// clear the search input
this.searchMatch = '';
this.$parent.$parent.$parent.$refs.keyList.refreshKeyList();
const dbKey = this.$storage.getStorageKeyByName('last_db', this.config.connectionName);
// store the last selected db
localStorage.setItem(dbKey, this.selectedDbIndex);
// tell cli to change db
this.client.options.db = this.selectedDbIndex;
this.$bus.$emit('changeDb', this.client, this.selectedDbIndex);
})
// select is not allowed in cluster mode
.catch((e) => {
this.$message.error({
message: e.message,
duration: 3000,
});
// reset to db0
this.selectedDbIndex = 0;
});
},
customDbName(db) {
const name = this.dbNames[db];
this.$prompt(this.$t('message.custom_name'), { inputValue: name }).then(({ value }) => {
this.$set(this.dbNames, db, value);
const dbKey = this.$storage.getStorageKeyByName('custom_db', this.config.connectionName);
localStorage.setItem(dbKey, JSON.stringify(this.dbNames));
}).catch(() => {});
},
addNewKey() {
if (!this.newKeyName) {
return;
}
// key to buffer
const key = Buffer.from(this.newKeyName);
const promise = this.setDefaultValue(key, this.selectedNewKeyType);
promise.then(() => {
this.$bus.$emit('refreshKeyList', this.client, key, 'add');
this.$bus.$emit('clickedKey', this.client, key, true);
}).catch((e) => {
this.$message.error(e.message);
});
this.newKeyDialog = false;
},
setDefaultValue(key, type) {
switch (type) {
case 'string': {
return this.client.set(key, '');
}
case 'hash': {
return this.client.hset(key, 'New field', 'New value');
}
case 'list': {
return this.client.lpush(key, 'New member');
}
case 'set': {
return this.client.sadd(key, 'New member');
}
case 'zset': {
return this.client.zadd(key, 0, 'New member');
}
case 'stream': {
return this.client.xadd(key, '*', 'New key', 'New value');
}
case 'rejson': {
return this.client.call('JSON.SET', [key, '$', '{"New key":"New value"}']);
}
}
},
toggleCancelIcon(show = false) {
this.showCancelIcon = false;
clearTimeout(this.rmCancelIconTimer);
if (show) {
this.rmCancelIconTimer = setTimeout(() => {
this.showCancelIcon = true;
}, 800);
}
},
changeMatchMode() {
// already searching status
// if (this.searchIcon == 'el-icon-loading') {
// return false;
// }
// prevent enter too fast but show candidate query
setTimeout(() => {
this.searchHistory.add(this.searchMatch);
}, this.searchDebounce + 100);
this.$parent.$parent.$parent.$refs.keyList.refreshKeyList();
},
querySearch(input, cb) {
const items = [];
if (!this.searchHistory.size) {
return cb([]);
}
this.searchHistory.forEach((value) => {
if (value.toLowerCase().indexOf(input.toLowerCase()) !== -1) {
items.push({ value });
}
});
cb(items);
},
cancelSearch() {
// stop scanning in keyList
this.$parent.$parent.$parent.$refs.keyList.cancelScanning();
// reset search status
this.$parent.$parent.$parent.$refs.keyList.resetSearchStatus();
},
},
};
</script>
<style type="text/css">
.connection-menu .db-select {
width: 100%;
}
.el-select-dropdown__item .db-select-key-count {
color: #a9a9ab;
font-size: 82%;
vertical-align: top;
}
.el-select-dropdown__item .db-select-custom-name {
float: right;
margin-left: 4px;
}
/*fix el-select height different from el-input*/
.connection-menu .db-select .el-input__inner, .connection-menu .new-key-btn {
/*margin-top: 0.5px;*/
height: 28px;
}
.connection-menu .new-key-btn {
width: 100%;
}
.connection-menu .search-item {
margin-top: -10px;
margin-bottom: 15px;
}
/*fix extract checkbox height*/
.connection-menu .search-item .el-input__suffix-inner {
display: inline-block;
}
.connection-menu .search-input {
width: 100%;
}
.connection-menu .search-input .el-input__inner {
padding-right: 62px;
/*margin-top: -10px;;
margin-bottom: 15px;*/
}
.connection-menu .el-submenu__title .el-submenu__icon-arrow {
right: 7px;
top: 54%;
}
.connection-menu .el-submenu [class^=el-icon-] {
font-size: 12px;
margin: 0px;
width: auto;
/*color: grey;*/
vertical-align: baseline;
}
.connection-menu .el-submenu.is-opened {
/*background: #ECF5FF;*/
}
.connection-menu .connection-form {
/*padding-right: 8px;*/
}
.connection-menu .search-item .search-icon {
font-size: 128%;
color: #a5a8ad;
cursor: pointer;
width: 20px;
}
.connection-menu .search-item .el-checkbox__input {
/*line-height: 28px;*/
display: inline;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/OperateItem.vue
|
Vue
|
mit
| 12,469
|
<template>
<div>
<el-table
:data="pagedData"
stripe
size="small"
border
min-height=300
>
<slot name="default"></slot>
</el-table>
<el-pagination
class="pagenation-table-page-container"
v-if="dataAfterFilter.length > pageSize"
:total="dataAfterFilter.length"
:page-size="pageSize"
:current-page.sync="pageIndex"
layout="total, prev, pager, next"
background
>
</el-pagination>
</div>
</template>
<script type="text/javascript">
export default {
data() {
return {
pageSize: 100,
pageIndex: 1,
};
},
props: ['data', 'filterKey', 'filterValue'],
computed: {
pagedData() {
const start = (this.pageIndex - 1) * this.pageSize;
return this.dataAfterFilter.slice(start, start + this.pageSize);
},
dataAfterFilter() {
const { filterKey } = this;
const { filterValue } = this;
this.$nextTick(() => {
this.pageIndex = 1;
});
if (!filterValue || !filterKey) {
return this.data;
}
return this.data.filter(line => line[filterKey].toLowerCase().includes(filterValue.toLowerCase()));
},
},
};
</script>
<style type="text/css">
.pagenation-table-page-container {
margin-top: 20px;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/PaginationTable.vue
|
Vue
|
mit
| 1,313
|
<template>
<div @contextmenu.prevent.stop="show($event)">
<!-- default slot -->
<slot name="default"></slot>
<!-- right menu -->
<div class="qii404-vue-right-menu" ref="menu">
<ul>
<li v-for="item of items" @click.stop="clickItem($event, item)">{{ item.name }}</li>
</ul>
</div>
</div>
</template>
<script type="text/javascript">
export default {
data() {
return {
triggerEvent: null,
};
},
props: ['items', 'clickValue'],
methods: {
show($event) {
this.triggerEvent = $event;
this.showMenus($event.clientX, $event.clientY);
document.addEventListener('click', this.removeMenus);
},
showMenus(x, y) {
this.hideAllMenus();
const { menu } = this.$refs;
menu.style.left = `${x}px`;
menu.style.top = `${y - 5}px`;
menu.style.display = 'block';
},
clickItem($event, item) {
if (item.click) {
item.click(this.clickValue, this.triggerEvent, $event);
}
this.removeMenus();
this.triggerEvent = null;
},
removeMenus() {
document.removeEventListener('click', this.removeMenus);
this.hideAllMenus();
},
hideAllMenus() {
const menus = document.querySelectorAll('.qii404-vue-right-menu');
if (menus.length === 0) {
return;
}
for (const menu of menus) {
menu.style.display = 'none';
}
},
},
};
</script>
<style type="text/css">
.qii404-vue-right-menu {
display: none;
position: fixed;
top: 0;
left: 0;
padding: 0px;
z-index: 99999;
overflow: hidden;
border-radius: 3px;
border: 2px solid lightgrey;
background: #fafafa;
}
.dark-mode .qii404-vue-right-menu {
background: #263238;
}
.qii404-vue-right-menu ul {
list-style: none;
padding: 0px;
}
.qii404-vue-right-menu ul li:not(:last-child) {
border-bottom: 1px solid lightgrey;
}
.qii404-vue-right-menu ul li {
font-size: 13.4px;
padding: 6px 10px;
cursor: pointer;
color: #263238;
}
.dark-mode .qii404-vue-right-menu ul li {
color: #fff;
}
.qii404-vue-right-menu ul li:hover {
background: #e4e2e2;
}
.dark-mode .qii404-vue-right-menu ul li:hover {
background: #344A4E;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/RightClickMenu.vue
|
Vue
|
mit
| 2,286
|
<template>
<transition name="bounce">
<div class="to-top-container" :style='style' @click="scrollToTop" v-if="toTopShow">
<i class="el-icon-to-top el-icon-arrow-up"></i>
</div>
</transition>
</template>
<script type="text/javascript">
export default {
data() {
return {
toTopShow: false,
scrollTop: 0,
realDom: null,
minShowHeight: 500,
};
},
computed: {
style() {
const style = { right: '50px' };
if (!this.posRight) {
style.right = 'inherit';
}
return style;
},
},
props: {
parentNum: { default: 3 },
posRight: { default: true },
},
methods: {
handleScroll() {
this.scrollTop = this.realDom.scrollTop;
this.toTopShow = (this.scrollTop > this.minShowHeight);
},
scrollToTop() {
let timer = null;
const that = this;
cancelAnimationFrame(timer);
timer = requestAnimationFrame(function fn() {
const nowTop = that.realDom.scrollTop;
// to top already
if (nowTop <= 0) {
cancelAnimationFrame(timer);
that.toTopShow = false;
} else if (nowTop < 50) {
that.realDom.scrollTop -= 5;
timer = requestAnimationFrame(fn);
} else {
that.realDom.scrollTop -= nowTop * 0.2;
timer = requestAnimationFrame(fn);
}
});
},
},
mounted() {
this.$nextTick(() => {
let vueCom = this.$parent;
for (let i = 0; i < this.parentNum - 1; i++) {
if (!vueCom.$parent) {
return;
}
vueCom = vueCom.$parent;
}
this.realDom = vueCom.$el;
if (!this.realDom) {
return;
}
this.realDom.addEventListener('scroll', this.handleScroll, true);
});
},
destroyed() {
this.realDom.removeEventListener('scroll', this.handleScroll, true);
},
};
</script>
<style type="text/css">
.to-top-container {
background-color: #409eff;
position: fixed;
/*right: 50px;*/
bottom: 30px;
width: 40px;
height: 40px;
border-radius: 20px;
cursor: pointer;
transition: .3s;
box-shadow: 0 3px 6px rgba(0, 0, 0, .5);
opacity: .5;
z-index: 10000;
}
.to-top-container:hover{
opacity: 1;
}
.to-top-container .el-icon-to-top{
color: #fff;
display: block;
line-height: 40px;
text-align: center;
font-size: 18px;
}
.bounce-enter-active {
animation: bounce-in .5s;
}
.bounce-leave-active {
animation: bounce-in .5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/ScrollToTop.vue
|
Vue
|
mit
| 2,713
|
<template>
<!-- setting dialog -->
<el-dialog :title="$t('message.settings')" :visible.sync="visible" custom-class="setting-main-dialog">
<el-form label-position="top" size="mini">
<el-card :header="$t('message.ui_settings')" class="setting-card">
<el-row :gutter="10" justify="space-between" type="flex" class="setting-row">
<el-col :sm="12" :lg="5">
<!-- theme select-->
<el-form-item :label="$t('message.dark_mode')">
<el-switch v-model='darkMode' @change="changeTheme"></el-switch>
</el-form-item>
</el-col>
<el-col :sm="12" :lg="7">
<!-- language select -->
<el-form-item :label="$t('message.select_lang')">
<LanguageSelector></LanguageSelector>
</el-form-item>
</el-col>
<el-col :sm="12" :lg="5">
<!-- zoom page -->
<el-form-item :label="$t('message.page_zoom')">
<el-input-number
size="mini"
placeholder='1.0'
:min=0.5
:max=2.0
:step=0.1
:precision=1
@change='changeZoom'
v-model='form.zoomFactor'>
</el-input-number>
</el-form-item>
</el-col>
<el-col :sm="12" :lg="7">
<!-- font-family -->
<el-form-item :label="$t('message.font_family')">
<span slot="label">
{{ $t('message.font_family') }}
<el-popover
placement="top-start"
:title="$t('message.font_faq_title')"
trigger="hover">
<i slot="reference" class="el-icon-question"></i>
<p v-html="$t('message.font_faq')"></p>
</el-popover>
<i v-if="loadingFonts" class="el-icon-loading"></i>
</span>
<!-- font-family select -->
<el-select v-model="form.fontFamily" @visible-change="getAllFonts" allow-create default-first-option
filterable multiple class="setting-font-select">
<el-option
v-for="(font, index) in allFonts"
:key="index"
:label="font"
:value="font">
<!-- for better performance, do not display font-family -->
<!-- :style="{'font-family': font}"> -->
</el-option>
</el-select>
</el-form-item>
</el-col>
</el-row>
</el-card>
<el-card :header="$t('message.common_settings')" class="setting-card">
<el-row :gutter="20" justify="space-between" type="flex" class="setting-row">
<el-col :sm="12" :lg="12">
<!-- keys per loading -->
<el-form-item>
<el-input-number
size="mini"
placeholder='500'
:min=10
:max=20000
:step=50
v-model='form.keysPageSize'>
</el-input-number>
<!-- load all switch -->
<!-- <el-switch v-model='form.showLoadAllKeys'></el-switch>
{{ $t('message.show_load_all_keys') }} -->
<span slot="label">
{{ $t('message.keys_per_loading') }}
<el-popover
:content="$t('message.keys_per_loading_tip')"
placement="top-start"
trigger="hover">
<i slot="reference" class="el-icon-question"></i>
</el-popover>
</span>
</el-form-item>
</el-col>
<el-col :sm="12" :lg="12">
<!-- export connections -->
<el-form-item :label="$t('message.config_connections')">
<el-button icon="el-icon-upload2" @click="exportConnection">{{ $t('message.export') }}</el-button>
<el-button icon="el-icon-download" @click="showImportDialog">{{ $t('message.import') }}</el-button>
</el-form-item>
</el-col>
</el-row>
</el-card>
<el-card class="setting-card">
<div slot="header">
{{$t('message.pre_version')}}
<el-tag type="info">{{ appVersion }}</el-tag>
</div>
<div class="current-version">
<a href="###" @click.stop.prevent="showHotkeys">{{ $t('message.hotkey') }}</a>
<a href="###" @click.stop.prevent="clearCache">{{ $t('message.clear_cache') }}</a>
<a href="###" @click.stop.prevent="checkUpdate">{{ $t('message.check_update') }}</a>
<a href="https://github.com/qishibo/AnotherRedisDesktopManager/releases">{{ $t('message.manual_update') }}</a>
<a href="https://github.com/qishibo/AnotherRedisDesktopManager/">{{ $t('message.project_home') }}</a>
</div>
</el-card>
</el-form>
<!-- import file dialog -->
<el-dialog
width="400px"
:title="$t('message.select_import_file')"
:visible.sync="importConnectionVisible"
append-to-body>
<el-upload
ref="configUpload"
:auto-upload="false"
:multiple="false"
action=""
:limit="1"
:on-change="loadConnectionFile"
drag>
<i class="el-icon-upload"></i>
<div class="el-upload__text">{{ $t('message.put_file_here') }}</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button @click="importConnnection">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
<div slot="footer" class="dialog-footer">
<el-button @click="visible = false">{{ $t('el.messagebox.cancel') }}</el-button>
<el-button type="primary" @click="saveSettings">{{ $t('el.messagebox.confirm') }}</el-button>
</div>
</el-dialog>
</template>
<script type="text/javascript">
import storage from '@/storage.js';
import { ipcRenderer } from 'electron';
import LanguageSelector from '@/components/LanguageSelector';
export default {
data() {
return {
visible: false,
form: {
fontFamily: '',
zoomFactor: 1.0,
keysPageSize: 500,
showLoadAllKeys: false,
},
importConnectionVisible: false,
connectionFileContent: '',
appVersion: (new URL(window.location.href)).searchParams.get('version'),
// electronVersion: process.versions.electron,
allFonts: [],
loadingFonts: false,
darkMode: localStorage.theme == 'dark',
};
},
components: { LanguageSelector },
methods: {
show() {
this.visible = true;
},
restoreSettings() {
const settings = storage.getSetting();
this.form = { ...this.form, ...settings };
},
saveSettings() {
storage.saveSettings(this.form);
this.visible = false;
this.$bus.$emit('reloadSettings', Object.assign({}, this.form));
},
changeTheme() {
const themeName = this.darkMode ? 'dark' : 'chalk';
globalChangeTheme(themeName);
},
changeZoom() {
const { webFrame } = require('electron');
let { zoomFactor } = this.form;
zoomFactor = zoomFactor || 1.0;
webFrame.setZoomFactor(zoomFactor);
},
showImportDialog() {
this.importConnectionVisible = true;
},
loadConnectionFile(file) {
const reader = new FileReader();
reader.onload = (event) => {
this.connectionFileContent = event.target.result;
};
reader.readAsText(file.raw);
},
importConnnection() {
this.importConnectionVisible = false;
let config = this.$util.base64Decode(this.connectionFileContent);
if (!config) {
return;
}
config = JSON.parse(config);
// remove all connections first
storage.setConnections({});
// close all connections
this.$bus.$emit('closeConnection');
this.$bus.$emit('refreshConnections');
for (const line of config) {
storage.addConnection(line);
}
this.$nextTick(() => {
this.$bus.$emit('refreshConnections');
});
this.$message.success({
message: this.$t('message.import_success'),
duration: 1000,
});
},
exportConnection() {
let connections = storage.getConnections(true);
connections = this.$util.base64Encode(JSON.stringify(connections));
this.$util.createAndDownloadFile('connections.ano', connections);
this.visible = false;
},
checkUpdate() {
this.$message.info({
message: `${this.$t('message.update_checking')}`,
duration: 1500,
});
this.$bus.$emit('update-check', true);
},
bindGetAllFonts() {
ipcRenderer.on('send-all-fonts', (event, fonts) => {
fonts.unshift('Default Initial');
this.allFonts = [...new Set(fonts)];
this.loadingFonts = false;
});
},
getAllFonts() {
if (this.allFonts.length === 0) {
this.loadingFonts = true;
ipcRenderer.send('get-all-fonts');
}
},
clearCache() {
this.$confirm(this.$t('message.clear_cache_tip')).then(() => {
localStorage.clear();
this.$message.success(this.$t('message.delete_success'));
window.location.reload();
}).catch((e) => {
});
},
showHotkeys() {
this.$parent.$refs.hotKeysDialog.show();
},
},
mounted() {
this.restoreSettings();
this.bindGetAllFonts();
},
};
</script>
<style type="text/css">
.setting-main-dialog {
width: 80%;
max-width: 900px;
margin-top: 7vh !important;
}
.dark-mode .el-upload-dragger {
background: inherit;
}
.setting-main-dialog .current-version a {
color: grey;
font-size: 95%;
}
.setting-main-dialog .setting-card {
margin-bottom: 8px;
}
.setting-main-dialog .setting-card .el-card__header {
font-size: 105%;
font-weight: bold;
}
.setting-main-dialog .setting-card .setting-row {
flex-wrap: wrap;
}
/* add height: fix el-select jitter when multiple*/
.setting-main-dialog .setting-card .setting-row .setting-font-select .el-select__tags .el-tag {
height: 21px;
max-width: 98%;
}
/*label style inside el-select multiple*/
.setting-main-dialog .setting-card .setting-row .setting-font-select .el-select__tags .el-tag .el-select__tags-text {
display: inline-block;
max-width: 90%;
overflow: hidden;
text-overflow: ellipsis;
}
/*fix close icon vertical align*/
.setting-main-dialog .setting-card .setting-row .setting-font-select .el-select__tags .el-tag .el-tag__close {
vertical-align: super;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/Setting.vue
|
Vue
|
mit
| 10,643
|
<template>
<div class="slowlog-container">
<el-card class="box-card">
<!-- card title -->
<div slot="header" class="clearfix">
<el-popover trigger="hover">
<i slot="reference" class="el-icon-question"></i>
Via <b><code>SLOWLOG GET</code></b>, the time threshold is: <b><pre>CONFIG GET slowlog-log-slower-than</pre></b>, and the total number is: <b><pre>CONFIG GET slowlog-max-len</pre></b>
Unit: <b>μs, 1000μs = 1ms</b>
</el-popover>
<span class="card-title">{{ $t('message.slow_log') }}</span>
<i v-if="isScanning" class='el-icon-loading'></i>
</div>
<div v-if="cmdList.length">
<!-- table header -->
<div class="table-header">
<span @click="toggleOrder" class="reorder-container" title="μs, 1000μs = 1ms">
<span>Cost</span>
<span class="el-icon-d-caret"></span>
</span>
</div>
<!-- content list -->
<RecycleScroller
class="list-body"
:items="cmdList"
:item-size="20"
key-field="id"
v-slot="{ item, index }"
>
<li>
<span class="list-index">{{ index + 1 }}.</span>
<span class="time" :title="item.timestring">{{ item.timestring }}</span>
<span class="cmd" :title="item.cmd">{{ item.cmd }}</span>
<span class="cost" :title="item.cost">{{ item.cost }}</span>
</li>
</RecycleScroller>
</div>
<p v-else class="list-body" style="text-align: center;">
<b class="el-icon-star-on"> No Slow Log</b>
</p>
<!-- table footer -->
<div class="table-footer">
<!-- <el-tag>{{ $t('message.max_display', {num: scanMax}) }}</el-tag> -->
<el-tag>slowlog-log-slower-than: {{ slowerThan }} slowlog-max-len: {{ maxLen }}</el-tag>
</div>
</el-card>
</div>
</template>
<script type="text/javascript">
import { RecycleScroller } from 'vue-virtual-scroller';
export default {
data() {
return {
cmdList: [],
isScanning: false,
sortOrder: '',
scanMax: 20000,
slowerThan: 0,
maxLen: 0,
};
},
props: ['client', 'hotKeyScope'],
components: { RecycleScroller },
methods: {
initShow() {
this.cmdList = [];
this.isScanning = true;
this.initCmdList();
this.initConfig();
},
initCmdList() {
const nodes = this.client.nodes ? this.client.nodes('master') : [this.client];
nodes.map((node) => {
const lines = [];
node.callBuffer('SLOWLOG', 'GET', this.scanMax).then((reply) => {
for (const item of reply) {
const line = {
id: item[0],
timestring: this.toLocalTime(item[1] * 1000),
cost: parseInt(item[2]),
cmd: item[3].join(' '),
source: item[4],
name: item[5],
};
lines.push(line);
}
this.cmdList = lines;
this.isScanning = false;
}).catch((e) => {
this.isScanning = false;
this.$message.error(e.message);
});
});
},
initConfig() {
this.client.call('CONFIG', 'GET', 'slowlog-log-slower-than').then((reply) => {
this.slowerThan = reply[1];
}).catch((e) => {});
this.client.call('CONFIG', 'GET', 'slowlog-max-len').then((reply) => {
this.maxLen = reply[1];
}).catch((e) => {});
},
toLocalTime(timestamp) {
const d = new Date(timestamp);
const h = `${d.getHours()}`.padStart(2, 0);
const m = `${d.getMinutes()}`.padStart(2, 0);
const s = `${d.getSeconds()}`.padStart(2, 0);
return `${h}:${m}:${s}`;
},
toggleOrder() {
if (this.isScanning) {
return;
}
this.sortOrder = (this.sortOrder == 'desc' ? 'asc' : 'desc');
this.reOrder();
},
reOrder(order = null) {
if (this.sortOrder == 'asc') {
this.cmdList.sort((a, b) => a.cost - b.cost);
} else {
this.cmdList.sort((a, b) => b.cost - a.cost);
}
},
initShortcut() {
this.$shortcut.bind('ctrl+r, ⌘+r, f5', this.hotKeyScope, () => {
// scanning not finished, return
if (this.isScanning) {
return false;
}
this.initShow();
return false;
});
},
},
mounted() {
this.initShow();
this.initShortcut();
},
beforeDestroy() {
this.$shortcut.deleteScope(this.hotKeyScope);
},
};
</script>
<style type="text/css">
.slowlog-container .card-title {
font-weight: bold;
font-size: 120%;
}
.slowlog-container .table-header {
margin: 2px 0 14px 0;
user-select: none;
display: flex;
font-weight: bold;
}
.slowlog-container .table-header .reorder-container {
margin-left: auto;
cursor: pointer;
}
/* list body*/
.slowlog-container .list-body {
height: calc(100vh - 290px);
}
.slowlog-container .list-body li {
border-bottom: 1px solid #e4e2e2;
padding: 0 2px;
font-size: 92%;
list-style: none;
height: 20px;
display: flex;
}
.slowlog-container .list-body .time {
width: 88px;
}
.slowlog-container .list-body .cmd {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
}
.slowlog-container .list-body .cost {
font-size: 90%;
margin-left: 16px;
margin-right: 4px;
}
.dark-mode .slowlog-container .list-body li {
border-bottom: 1px solid #444444;
}
.slowlog-container .list-body li:hover {
background: #c6c6c6;
}
.dark-mode .slowlog-container .list-body li:hover {
background: #3b4e57;
}
/* table footer*/
.slowlog-container .table-footer {
text-align: center;
margin-top: 6px;
}
</style>
|
2301_77204479/AnotherRedisDesktopManager
|
src/components/SlowLog.vue
|
Vue
|
mit
| 5,731
|