code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def open_atomic(filepath, *args, **kwargs):
""" Open temporary file object that atomically moves to destination upon
exiting.
Allows reading and writing to and from the same filename.
Parameters
----------
filepath : string
the file path to be opened
fsync : bool
whether to... | Open temporary file object that atomically moves to destination upon
exiting.
Allows reading and writing to and from the same filename.
Parameters
----------
filepath : string
the file path to be opened
fsync : bool
whether to force write the file to disk
kwargs : mixed
... | open_atomic | python | karpathy/arxiv-sanity-preserver | utils.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/utils.py | MIT |
async def generate_report_plan(state: ReportState, config: RunnableConfig):
"""Generate the initial report plan with sections.
This node:
1. Gets configuration for the report structure and search parameters
2. Generates search queries to gather context for planning
3. Performs web searches usin... | Generate the initial report plan with sections.
This node:
1. Gets configuration for the report structure and search parameters
2. Generates search queries to gather context for planning
3. Performs web searches using those queries
4. Uses an LLM to generate a structured plan with sections
... | generate_report_plan | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def human_feedback(state: ReportState, config: RunnableConfig) -> Command[Literal["generate_report_plan","build_section_with_web_research"]]:
"""Get human feedback on the report plan and route to next steps.
This node:
1. Formats the current report plan for human review
2. Gets feedback via an inte... | Get human feedback on the report plan and route to next steps.
This node:
1. Formats the current report plan for human review
2. Gets feedback via an interrupt
3. Routes to either:
- Section writing if plan is approved
- Plan regeneration if feedback is provided
Args:
... | human_feedback | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
async def generate_queries(state: SectionState, config: RunnableConfig):
"""Generate search queries for researching a specific section.
This node uses an LLM to generate targeted search queries based on the
section topic and description.
Args:
state: Current state containing section d... | Generate search queries for researching a specific section.
This node uses an LLM to generate targeted search queries based on the
section topic and description.
Args:
state: Current state containing section details
config: Configuration including number of queries to generate
... | generate_queries | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
async def search_web(state: SectionState, config: RunnableConfig):
"""Execute web searches for the section queries.
This node:
1. Takes the generated queries
2. Executes searches using configured search API
3. Formats results into usable context
Args:
state: Current state with ... | Execute web searches for the section queries.
This node:
1. Takes the generated queries
2. Executes searches using configured search API
3. Formats results into usable context
Args:
state: Current state with search queries
config: Search API configuration
Retur... | search_web | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
async def write_section(state: SectionState, config: RunnableConfig) -> Command[Literal[END, "search_web"]]:
"""Write a section of the report and evaluate if more research is needed.
This node:
1. Writes section content using search results
2. Evaluates the quality of the section
3. Either:
... | Write a section of the report and evaluate if more research is needed.
This node:
1. Writes section content using search results
2. Evaluates the quality of the section
3. Either:
- Completes the section if quality passes
- Triggers more research if quality fails
Args:
... | write_section | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
async def write_final_sections(state: SectionState, config: RunnableConfig):
"""Write sections that don't require research using completed sections as context.
This node handles sections like conclusions or summaries that build on
the researched sections rather than requiring direct research.
... | Write sections that don't require research using completed sections as context.
This node handles sections like conclusions or summaries that build on
the researched sections rather than requiring direct research.
Args:
state: Current state with completed sections as context
config... | write_final_sections | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def gather_completed_sections(state: ReportState):
"""Format completed sections as context for writing final sections.
This node takes all completed research sections and formats them into
a single context string for writing summary sections.
Args:
state: Current state with completed s... | Format completed sections as context for writing final sections.
This node takes all completed research sections and formats them into
a single context string for writing summary sections.
Args:
state: Current state with completed sections
Returns:
Dict with formatted ... | gather_completed_sections | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def compile_final_report(state: ReportState, config: RunnableConfig):
"""Compile all sections into the final report.
This node:
1. Gets all completed sections
2. Orders them according to original plan
3. Combines them into the final report
Args:
state: Current state with all co... | Compile all sections into the final report.
This node:
1. Gets all completed sections
2. Orders them according to original plan
3. Combines them into the final report
Args:
state: Current state with all completed sections
Returns:
Dict containing the complete r... | compile_final_report | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def initiate_final_section_writing(state: ReportState):
"""Create parallel tasks for writing non-research sections.
This edge function identifies sections that don't need research and
creates parallel writing tasks for each one.
Args:
state: Current state with all sections and research... | Create parallel tasks for writing non-research sections.
This edge function identifies sections that don't need research and
creates parallel writing tasks for each one.
Args:
state: Current state with all sections and research context
Returns:
List of Send commands fo... | initiate_final_section_writing | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def get_search_tool(config: RunnableConfig):
"""Get the appropriate search tool based on configuration"""
configurable = MultiAgentConfiguration.from_runnable_config(config)
search_api = get_config_value(configurable.search_api)
# Return None if no search tool is requested
if search_api.lower() == ... | Get the appropriate search tool based on configuration | get_search_tool | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def get_supervisor_tools(config: RunnableConfig) -> list[BaseTool]:
"""Get supervisor tools based on configuration"""
configurable = MultiAgentConfiguration.from_runnable_config(config)
search_tool = get_search_tool(config)
tools = [tool(Sections), tool(Introduction), tool(Conclusion), tool(Finish... | Get supervisor tools based on configuration | get_supervisor_tools | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def get_research_tools(config: RunnableConfig) -> list[BaseTool]:
"""Get research tools based on configuration"""
search_tool = get_search_tool(config)
tools = [tool(Section), tool(FinishResearch)]
if search_tool is not None:
tools.append(search_tool) # Add search tool, if available
e... | Get research tools based on configuration | get_research_tools | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def supervisor(state: ReportState, config: RunnableConfig):
"""LLM decides whether to call a tool or not"""
# Messages
messages = state["messages"]
# Get configuration
configurable = MultiAgentConfiguration.from_runnable_config(config)
supervisor_model = get_config_value(configurable.sup... | LLM decides whether to call a tool or not | supervisor | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def supervisor_tools(state: ReportState, config: RunnableConfig) -> Command[Literal["supervisor", "research_team", "__end__"]]:
"""Performs the tool call and sends to the research agent"""
configurable = MultiAgentConfiguration.from_runnable_config(config)
result = []
sections_list = []
intr... | Performs the tool call and sends to the research agent | supervisor_tools | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def supervisor_should_continue(state: ReportState) -> str:
"""Decide if we should continue the loop or stop based upon whether the LLM made a tool call"""
messages = state["messages"]
last_message = messages[-1]
# End because the supervisor asked a question or is finished
if not last_message.... | Decide if we should continue the loop or stop based upon whether the LLM made a tool call | supervisor_should_continue | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def research_agent(state: SectionState, config: RunnableConfig):
"""LLM decides whether to call a tool or not"""
# Get configuration
configurable = MultiAgentConfiguration.from_runnable_config(config)
researcher_model = get_config_value(configurable.researcher_model)
# Initialize the... | LLM decides whether to call a tool or not | research_agent | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def research_agent_tools(state: SectionState, config: RunnableConfig):
"""Performs the tool call and route to supervisor or continue the research loop"""
configurable = MultiAgentConfiguration.from_runnable_config(config)
result = []
completed_section = None
source_str = ""
# Get too... | Performs the tool call and route to supervisor or continue the research loop | research_agent_tools | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def research_agent_should_continue(state: SectionState) -> str:
"""Decide if we should continue the loop or stop based upon whether the LLM made a tool call"""
messages = state["messages"]
last_message = messages[-1]
if last_message.tool_calls[0]["name"] == "FinishResearch":
# Research i... | Decide if we should continue the loop or stop based upon whether the LLM made a tool call | research_agent_should_continue | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
def get_config_value(value):
"""
Helper function to handle string, dict, and enum cases of configuration values
"""
if isinstance(value, str):
return value
elif isinstance(value, dict):
return value
else:
return value.value |
Helper function to handle string, dict, and enum cases of configuration values
| get_config_value | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
def get_search_params(search_api: str, search_api_config: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""
Filters the search_api_config dictionary to include only parameters accepted by the specified search API.
Args:
search_api (str): The search API identifier (e.g., "exa", "tavily").
sea... |
Filters the search_api_config dictionary to include only parameters accepted by the specified search API.
Args:
search_api (str): The search API identifier (e.g., "exa", "tavily").
search_api_config (Optional[Dict[str, Any]]): The configuration dictionary for the search API.
Returns:
... | get_search_params | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
def format_sections(sections: list[Section]) -> str:
""" Format a list of sections into a string """
formatted_str = ""
for idx, section in enumerate(sections, 1):
formatted_str += f"""
{'='*60}
Section {idx}: {section.name}
{'='*60}
Description:
{section.description}
Requires Research:
{section.re... | Format a list of sections into a string | format_sections | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def tavily_search_async(search_queries, max_results: int = 5, topic: Literal["general", "news", "finance"] = "general", include_raw_content: bool = True):
"""
Performs concurrent web searches with the Tavily API
Args:
search_queries (List[str]): List of search queries to process
max_r... |
Performs concurrent web searches with the Tavily API
Args:
search_queries (List[str]): List of search queries to process
max_results (int): Maximum number of results to return
topic (Literal["general", "news", "finance"]): Topic to filter results by
include_raw_content (bool): ... | tavily_search_async | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def azureaisearch_search_async(search_queries: list[str], max_results: int = 5, topic: str = "general", include_raw_content: bool = True) -> list[dict]:
"""
Performs concurrent web searches using the Azure AI Search API.
Args:
search_queries (List[str]): list of search queries to process
... |
Performs concurrent web searches using the Azure AI Search API.
Args:
search_queries (List[str]): list of search queries to process
max_results (int): maximum number of results to return for each query
topic (str): semantic topic filter for the search.
include_raw_content (bool... | azureaisearch_search_async | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
def perplexity_search(search_queries):
"""Search the web using the Perplexity API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
Returns:
List[dict]: List of search responses from Perplexity API, one per query. Each response has format:
{
... | Search the web using the Perplexity API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
Returns:
List[dict]: List of search responses from Perplexity API, one per query. Each response has format:
{
'query': str, ... | perplexity_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def exa_search(search_queries, max_characters: Optional[int] = None, num_results=5,
include_domains: Optional[List[str]] = None,
exclude_domains: Optional[List[str]] = None,
subpages: Optional[int] = None):
"""Search the web using the Exa API.
... | Search the web using the Exa API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
max_characters (int, optional): Maximum number of characters to retrieve for each result's raw content.
If None, the text parameter will be set to... | exa_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def arxiv_search_async(search_queries, load_max_docs=5, get_full_documents=True, load_all_available_meta=True):
"""
Performs concurrent searches on arXiv using the ArxivRetriever.
Args:
search_queries (List[str]): List of search queries or article IDs
load_max_docs (int, optional): Ma... |
Performs concurrent searches on arXiv using the ArxivRetriever.
Args:
search_queries (List[str]): List of search queries or article IDs
load_max_docs (int, optional): Maximum number of documents to return per query. Default is 5.
get_full_documents (bool, optional): Whether to fetch fu... | arxiv_search_async | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def linkup_search(search_queries, depth: Optional[str] = "standard"):
"""
Performs concurrent web searches using the Linkup API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
depth (str, optional): "standard" (default) or "deep". More details here https:... |
Performs concurrent web searches using the Linkup API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
depth (str, optional): "standard" (default) or "deep". More details here https://docs.linkup.so/pages/documentation/get-started/concepts
Returns:
Lis... | linkup_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def google_search_async(search_queries: Union[str, List[str]], max_results: int = 5, include_raw_content: bool = True):
"""
Performs concurrent web searches using Google.
Uses Google Custom Search API if environment variables are set, otherwise falls back to web scraping.
Args:
search_que... |
Performs concurrent web searches using Google.
Uses Google Custom Search API if environment variables are set, otherwise falls back to web scraping.
Args:
search_queries (List[str]): List of search queries to process
max_results (int): Maximum number of results to return per query
... | google_search_async | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def scrape_pages(titles: List[str], urls: List[str]) -> str:
"""
Scrapes content from a list of URLs and formats it into a readable markdown document.
This function:
1. Takes a list of page titles and URLs
2. Makes asynchronous HTTP requests to each URL
3. Converts HTML content to mar... |
Scrapes content from a list of URLs and formats it into a readable markdown document.
This function:
1. Takes a list of page titles and URLs
2. Makes asynchronous HTTP requests to each URL
3. Converts HTML content to markdown
4. Formats all content with clear source attribution
Ar... | scrape_pages | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def tavily_search(
queries: List[str],
max_results: Annotated[int, InjectedToolArg] = 5,
topic: Annotated[Literal["general", "news", "finance"], InjectedToolArg] = "general",
config: RunnableConfig = None
) -> str:
"""
Fetches results from Tavily search API.
Args:
queries (Lis... |
Fetches results from Tavily search API.
Args:
queries (List[str]): List of search queries
max_results (int): Maximum number of results to return
topic (Literal['general', 'news', 'finance']): Topic to filter results by
Returns:
str: A formatted string of search results
... | tavily_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def azureaisearch_search(queries: List[str], max_results: int = 5, topic: str = "general") -> str:
"""
Fetches results from Azure AI Search API.
Args:
queries (List[str]): List of search queries
Returns:
str: A formatted string of search results
"""
# Use azur... |
Fetches results from Azure AI Search API.
Args:
queries (List[str]): List of search queries
Returns:
str: A formatted string of search results
| azureaisearch_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def select_and_execute_search(search_api: str, query_list: list[str], params_to_pass: dict) -> str:
"""Select and execute the appropriate search API.
Args:
search_api: Name of the search API to use
query_list: List of search queries to execute
params_to_pass: Parameters to pas... | Select and execute the appropriate search API.
Args:
search_api: Name of the search API to use
query_list: List of search queries to execute
params_to_pass: Parameters to pass to the search API
Returns:
Formatted string containing search results
Raises:... | select_and_execute_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def load_mcp_server_config(path: str) -> dict:
"""Load MCP server configuration from a file."""
def _load():
with open(path, "r") as f:
config = json.load(f)
return config
config = await asyncio.to_thread(_load)
return config | Load MCP server configuration from a file. | load_mcp_server_config | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
def pytest_addoption(parser):
"""Add command-line options to pytest."""
parser.addoption("--research-agent", action="store", help="Agent type: multi_agent or graph")
parser.addoption("--search-api", action="store", help="Search API to use")
parser.addoption("--eval-model", action="store", help="Model fo... | Add command-line options to pytest. | pytest_addoption | python | langchain-ai/open_deep_research | tests/conftest.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/conftest.py | MIT |
def add_model_configs(cmd, args):
"""Add model configuration arguments to command."""
if args.supervisor_model:
cmd.append(f"--supervisor-model={args.supervisor_model}")
if args.researcher_model:
cmd.append(f"--researcher-model={args.researcher_model}")
if args.planner_provider:
... | Add model configuration arguments to command. | add_model_configs | python | langchain-ai/open_deep_research | tests/run_test.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/run_test.py | MIT |
def get_evaluation_llm(eval_model=None):
"""Create and return an evaluation LLM.
Args:
eval_model: Model identifier to use for evaluation
Format: "provider:model_name" (e.g., "anthropic:claude-3-7-sonnet-latest")
If None, it will use environment variable or d... | Create and return an evaluation LLM.
Args:
eval_model: Model identifier to use for evaluation
Format: "provider:model_name" (e.g., "anthropic:claude-3-7-sonnet-latest")
If None, it will use environment variable or default
Returns:
Structured LLM ... | get_evaluation_llm | python | langchain-ai/open_deep_research | tests/test_report_quality.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/test_report_quality.py | MIT |
def models(request, research_agent):
"""Get model configurations based on agent type."""
if research_agent == "multi_agent":
return {
"supervisor_model": (
request.config.getoption("--supervisor-model") or
os.environ.get("SUPERVISOR_MODEL", "anthropic:claude-... | Get model configurations based on agent type. | models | python | langchain-ai/open_deep_research | tests/test_report_quality.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/test_report_quality.py | MIT |
def test_response_criteria_evaluation(research_agent, search_api, models, eval_model):
"""Test if a report meets the specified quality criteria."""
console.print(Panel.fit(
f"[bold blue]Testing {research_agent} report generation with {search_api} search[/bold blue]",
title="Test Configuration"
... | Test if a report meets the specified quality criteria. | test_response_criteria_evaluation | python | langchain-ai/open_deep_research | tests/test_report_quality.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/test_report_quality.py | MIT |
async def generate_report_multi_agent(
messages: list[MessageLikeRepresentation],
process_search_results: Literal["summarize", "split_and_rerank"] | None = None,
include_source: bool = True,
summarization_model: str = summarization_model,
summarization_model_provider: str = summarization_model_provi... | Generate a report using the open deep research multi-agent architecture | generate_report_multi_agent | python | langchain-ai/open_deep_research | tests/evals/run_evaluate.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/evals/run_evaluate.py | MIT |
async def generate_report_workflow(
query: str,
process_search_results: Literal["summarize", "split_and_rerank"] | None = None,
include_source: bool = True
):
"""Generate a report using the open deep research workflow"""
graph = builder.compile(checkpointer=MemorySaver())
config = {
"con... | Generate a report using the open deep research workflow | generate_report_workflow | python | langchain-ai/open_deep_research | tests/evals/target.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/evals/target.py | MIT |
async def generate_report_multi_agent(
messages: list[MessageLikeRepresentation],
process_search_results: Literal["summarize", "split_and_rerank"] | None = None,
include_source: bool = True
):
"""Generate a report using the open deep research multi-agent architecture"""
graph = supervisor_builder.co... | Generate a report using the open deep research multi-agent architecture | generate_report_multi_agent | python | langchain-ai/open_deep_research | tests/evals/target.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/evals/target.py | MIT |
def write_file_prefix(f: IO[Any], interpreter: str) -> None:
"""Write a shebang line.
:param f: An open file handle.
:param interpreter: A path to a python interpreter.
"""
# if the provided path is too long for a shebang we should error out
if len(interpreter) > BINPRM_BUF_SIZE:
sys.ex... | Write a shebang line.
:param f: An open file handle.
:param interpreter: A path to a python interpreter.
| write_file_prefix | python | linkedin/shiv | src/shiv/builder.py | https://github.com/linkedin/shiv/blob/master/src/shiv/builder.py | BSD-2-Clause |
def write_to_zipapp(
archive: zipfile.ZipFile,
arcname: str,
data: bytes,
date_time: Tuple[int, int, int, int, int, int],
compression: int,
stat: Optional[os.stat_result] = None,
) -> None:
"""Write a file or a bytestring to a ZipFile as a separate entry and update contents_hash as a side ef... | Write a file or a bytestring to a ZipFile as a separate entry and update contents_hash as a side effect. | write_to_zipapp | python | linkedin/shiv | src/shiv/builder.py | https://github.com/linkedin/shiv/blob/master/src/shiv/builder.py | BSD-2-Clause |
def rglob_follow_symlinks(path: Path, glob: str) -> Generator[Path, None, None]:
"""Path.rglob extended to follow symlinks, while we wait for Python 3.13."""
for p in path.rglob('*'):
if p.is_symlink() and p.is_dir():
yield from chain([p], rglob_follow_symlinks(p, glob))
else:
... | Path.rglob extended to follow symlinks, while we wait for Python 3.13. | rglob_follow_symlinks | python | linkedin/shiv | src/shiv/builder.py | https://github.com/linkedin/shiv/blob/master/src/shiv/builder.py | BSD-2-Clause |
def create_archive(
sources: List[Path], target: Path, interpreter: str, main: str, env: Environment, compressed: bool = True
) -> None:
"""Create an application archive from SOURCE.
This function is a heavily modified version of stdlib's
`zipapp.create_archive <https://docs.python.org/3/library/zipapp... | Create an application archive from SOURCE.
This function is a heavily modified version of stdlib's
`zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archive>`_
| create_archive | python | linkedin/shiv | src/shiv/builder.py | https://github.com/linkedin/shiv/blob/master/src/shiv/builder.py | BSD-2-Clause |
def find_entry_point(site_packages_dirs: List[Path], console_script: str) -> str:
"""Find a console_script in a site-packages directory.
Console script metadata is stored in entry_points.txt per setuptools
convention. This function searches all entry_points.txt files and
returns the import string for a... | Find a console_script in a site-packages directory.
Console script metadata is stored in entry_points.txt per setuptools
convention. This function searches all entry_points.txt files and
returns the import string for a given console_script argument.
:param site_packages_dirs: Paths to site-packages di... | find_entry_point | python | linkedin/shiv | src/shiv/cli.py | https://github.com/linkedin/shiv/blob/master/src/shiv/cli.py | BSD-2-Clause |
def console_script_exists(site_packages_dirs: List[Path], console_script: str) -> bool:
"""Return true if the console script with provided name exists in one of the site-packages directories.
Console script is expected to be in the 'bin' directory of site packages.
:param site_packages_dirs: Paths to site... | Return true if the console script with provided name exists in one of the site-packages directories.
Console script is expected to be in the 'bin' directory of site packages.
:param site_packages_dirs: Paths to site-packages directories on disk.
:param console_script: A console script name.
| console_script_exists | python | linkedin/shiv | src/shiv/cli.py | https://github.com/linkedin/shiv/blob/master/src/shiv/cli.py | BSD-2-Clause |
def copytree(src: Path, dst: Path) -> None:
"""A utility function for syncing directories.
This function is based on shutil.copytree. In Python versions that are
older than 3.8, shutil.copytree would raise FileExistsError if the "dst"
directory already existed.
"""
# Make our target (if it do... | A utility function for syncing directories.
This function is based on shutil.copytree. In Python versions that are
older than 3.8, shutil.copytree would raise FileExistsError if the "dst"
directory already existed.
| copytree | python | linkedin/shiv | src/shiv/cli.py | https://github.com/linkedin/shiv/blob/master/src/shiv/cli.py | BSD-2-Clause |
def main(
output_file: str,
entry_point: Optional[str],
console_script: Optional[str],
python: Optional[str],
site_packages: Optional[str],
build_id: Optional[str],
compressed: bool,
compile_pyc: bool,
extend_pythonpath: bool,
reproducible: bool,
no_modify: bool,
preamble... |
Shiv is a command line utility for building fully self-contained Python zipapps
as outlined in PEP 441, but with all their dependencies included!
| main | python | linkedin/shiv | src/shiv/cli.py | https://github.com/linkedin/shiv/blob/master/src/shiv/cli.py | BSD-2-Clause |
def main(print_as_json, pyz):
"""A simple utility to print debugging information about PYZ files created with ``shiv``"""
zip_file = zipfile.ZipFile(pyz)
data = json.loads(zip_file.read("environment.json"))
if print_as_json:
click.echo(json.dumps(data, indent=4, sort_keys=True))
else:
... | A simple utility to print debugging information about PYZ files created with ``shiv`` | main | python | linkedin/shiv | src/shiv/info.py | https://github.com/linkedin/shiv/blob/master/src/shiv/info.py | BSD-2-Clause |
def clean_pip_env() -> Generator[None, None, None]:
"""A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment.
Since shiv installs via `--target`, we need to ignore venv requirements if they exist.
"""
require_venv = os.environ.pop(PIP_REQUIRE_VIRTUALENV, None)
t... | A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment.
Since shiv installs via `--target`, we need to ignore venv requirements if they exist.
| clean_pip_env | python | linkedin/shiv | src/shiv/pip.py | https://github.com/linkedin/shiv/blob/master/src/shiv/pip.py | BSD-2-Clause |
def install(args: List[str]) -> None:
"""`pip install` as a function.
Accepts a list of pip arguments.
.. code-block:: py
>>> install(['numpy', '--target', 'site-packages'])
Collecting numpy
Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB)
100% || 16.... | `pip install` as a function.
Accepts a list of pip arguments.
.. code-block:: py
>>> install(['numpy', '--target', 'site-packages'])
Collecting numpy
Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB)
100% || 16.9MB 53kB/s
Installing collected packa... | install | python | linkedin/shiv | src/shiv/pip.py | https://github.com/linkedin/shiv/blob/master/src/shiv/pip.py | BSD-2-Clause |
def acquire_nix(lock_file): # pragma: no cover
"""Acquire a lock file on linux or osx."""
fd = os.open(lock_file, OPEN_MODE)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (IOError, OSError):
os.close(fd)
else:
return fd | Acquire a lock file on linux or osx. | acquire_nix | python | linkedin/shiv | src/shiv/bootstrap/filelock.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/filelock.py | BSD-2-Clause |
def run(module): # pragma: no cover
"""Run a module in a scrubbed environment.
If a single pyz has multiple callers, we want to remove these vars as we no longer need them
and they can cause subprocesses to fail with a ModuleNotFoundError.
:param Callable module: The entry point to invoke the pyz wit... | Run a module in a scrubbed environment.
If a single pyz has multiple callers, we want to remove these vars as we no longer need them
and they can cause subprocesses to fail with a ModuleNotFoundError.
:param Callable module: The entry point to invoke the pyz with.
| run | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def current_zipfile():
"""A function to vend the current zipfile, if any"""
if zipfile.is_zipfile(sys.argv[0]):
with zipfile.ZipFile(sys.argv[0]) as fd:
yield fd
else:
yield None | A function to vend the current zipfile, if any | current_zipfile | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def import_string(import_name):
"""Returns a callable for a given setuptools style import string
:param str import_name: A console_scripts style import string
"""
import_name = str(import_name).replace(":", ".")
try:
import_module(import_name)
except ImportError:
if "." not in... | Returns a callable for a given setuptools style import string
:param str import_name: A console_scripts style import string
| import_string | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def cache_path(archive, root_dir, build_id):
"""Returns a ~/.shiv cache directory for unzipping site-packages during bootstrap.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param str root_dir: Optional, either a path or environment variable pointing to a SHIV_ROOT.
:param str ... | Returns a ~/.shiv cache directory for unzipping site-packages during bootstrap.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param str root_dir: Optional, either a path or environment variable pointing to a SHIV_ROOT.
:param str build_id: The build id generated at zip creation.
... | cache_path | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def extract_site_packages(archive, target_path, compile_pyc=False, compile_workers=0, force=False):
"""Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
:param bool comp... | Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
:param bool compile_pyc: A boolean to dictate whether we pre-compile pyc.
:param int compile_workers: An int representi... | extract_site_packages | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def extend_python_path(environ, additional_paths):
"""Create or extend a PYTHONPATH variable with the frozen environment we are bootstrapping with."""
# we don't want to clobber any existing PYTHONPATH value, so check for it.
python_path = environ["PYTHONPATH"].split(os.pathsep) if "PYTHONPATH" in environ ... | Create or extend a PYTHONPATH variable with the frozen environment we are bootstrapping with. | extend_python_path | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def ensure_no_modify(site_packages, hashes):
"""Compare the sha256 hash of the unpacked source files to the files when they were added to the pyz."""
for path in site_packages.rglob("**/*.py"):
if hashlib.sha256(path.read_bytes()).hexdigest() != hashes.get(str(path.relative_to(site_packages))):
... | Compare the sha256 hash of the unpacked source files to the files when they were added to the pyz. | ensure_no_modify | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def test_extend_path_existing_pythonpath(self):
"""When PYTHONPATH exists, extending it preserves the existing values."""
env = {"PYTHONPATH": "hello"}
extend_python_path(env, ["test", ".pth"])
assert env["PYTHONPATH"] == os.pathsep.join(["hello", "test", ".pth"]) | When PYTHONPATH exists, extending it preserves the existing values. | test_extend_path_existing_pythonpath | python | linkedin/shiv | test/test_bootstrap.py | https://github.com/linkedin/shiv/blob/master/test/test_bootstrap.py | BSD-2-Clause |
def test_find_entry_point(self, tmpdir, package_location):
"""Test that we can find console_script metadata."""
install(["-t", str(tmpdir), str(package_location)])
assert find_entry_point([Path(tmpdir)], "hello") == "hello:main" | Test that we can find console_script metadata. | test_find_entry_point | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_find_entry_point_two_points(self, tmpdir, package_location):
"""Test that we can find console_script metadata."""
install(["-t", str(tmpdir), str(package_location)])
assert find_entry_point([Path(tmpdir)], "hello") == "hello:main" | Test that we can find console_script metadata. | test_find_entry_point_two_points | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_console_script_exists(self, tmp_path, package_location):
"""Test that we can check console_script presence."""
install_dir = tmp_path / "install"
install(["-t", str(install_dir), str(package_location)])
empty_dir = tmp_path / "empty"
empty_dir.mkdir()
assert con... | Test that we can check console_script presence. | test_console_script_exists | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_no_args(self, runner):
"""This should fail with a warning about supplying pip arguments"""
result = runner([])
assert result.exit_code == 1
assert NO_PIP_ARGS_OR_SITE_PACKAGES in result.output | This should fail with a warning about supplying pip arguments | test_no_args | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_no_outfile(self, runner):
"""This should fail with a warning about not providing an outfile"""
result = runner(["-e", "test", "flask"])
assert result.exit_code == 1
assert NO_OUTFILE in result.output | This should fail with a warning about not providing an outfile | test_no_outfile | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_disallowed_args(self, runner, arg):
"""This method tests that all the potential disallowed arguments match their error messages."""
# run shiv with a disallowed argument
result = runner(["-o", "tmp", arg])
# get the 'reason' message:
reason = next(iter([DISALLOWED_ARGS... | This method tests that all the potential disallowed arguments match their error messages. | test_disallowed_args | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_preamble_no_pip(self, shiv_root, runner, package_location, tmp_path):
"""Test that the preamble script is created even with no pip installed packages."""
output_file = shiv_root / "test.pyz"
target = tmp_path / "target"
preamble = tmp_path / "preamble.py"
preamble.write... | Test that the preamble script is created even with no pip installed packages. | test_preamble_no_pip | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_alternate_root(self, runner, package_location, tmp_path):
"""Test that the --root argument properly sets the extraction root."""
output_file = tmp_path / "test.pyz"
shiv_root = tmp_path / "root"
result = runner(
["-e", "hello:main", "--root", str(shiv_root), "-o", s... | Test that the --root argument properly sets the extraction root. | test_alternate_root | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_alternate_root_environment_variable(self, runner, package_location, tmp_path, env_var):
"""Test that the --root argument works with environment variables."""
output_file = tmp_path / "test.pyz"
shiv_root_var = "NEW_ROOT"
shiv_root_path = tmp_path / 'new_root'
result = r... | Test that the --root argument works with environment variables. | test_alternate_root_environment_variable | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def forward(self, inputs, outputs, labels):
"""
Args:
inputs: The original inputs that are feed to the teacher model
outputs: the outputs of the model to be trained. It is expected to be
either a Tensor, or a Tuple[Tensor, Tensor], with the original output
... |
Args:
inputs: The original inputs that are feed to the teacher model
outputs: the outputs of the model to be trained. It is expected to be
either a Tensor, or a Tuple[Tensor, Tensor], with the original output
in the first position and the distillation pre... | forward | python | facebookresearch/deit | losses.py | https://github.com/facebookresearch/deit/blob/master/losses.py | Apache-2.0 |
def _load_checkpoint_for_ema(model_ema, checkpoint):
"""
Workaround for ModelEma._load_checkpoint to accept an already-loaded object
"""
mem_file = io.BytesIO()
torch.save({'state_dict_ema':checkpoint}, mem_file)
mem_file.seek(0)
model_ema._load_checkpoint(mem_file) |
Workaround for ModelEma._load_checkpoint to accept an already-loaded object
| _load_checkpoint_for_ema | python | facebookresearch/deit | utils.py | https://github.com/facebookresearch/deit/blob/master/utils.py | Apache-2.0 |
def __init__(
self,
target: Target,
user: str,
dns: Optional[str] = None,
upn: Optional[str] = None,
sam: Optional[str] = None,
spns: Optional[str] = None,
passw: Optional[str] = None,
group: Optional[str] = None,
connection: Optional[LDAPC... |
Initialize account management with target and account options.
Args:
target: Target environment information (domain, credentials)
user: Username for the account to manage
dns: DNS hostname for the account
upn: UserPrincipalName to set
sam: sA... | __init__ | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def connection(self) -> LDAPConnection:
"""
Get or establish an LDAP connection to the target.
Returns:
Active LDAP connection
"""
if self._connection is not None:
return self._connection
self._connection = LDAPConnection(self.target)
sel... |
Get or establish an LDAP connection to the target.
Returns:
Active LDAP connection
| connection | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def create(self) -> bool:
"""
Create a new computer account in Active Directory.
This method creates a computer account with the specified properties,
or with reasonable defaults if not provided.
Returns:
True if account creation succeeded, False otherwise
"... |
Create a new computer account in Active Directory.
This method creates a computer account with the specified properties,
or with reasonable defaults if not provided.
Returns:
True if account creation succeeded, False otherwise
| create | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def read(self) -> bool:
"""
Read and display account attributes.
This method retrieves and displays key attributes of the specified account.
Returns:
True if account was found and attributes read, False otherwise
"""
# Get user object
user = self.con... |
Read and display account attributes.
This method retrieves and displays key attributes of the specified account.
Returns:
True if account was found and attributes read, False otherwise
| read | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def update(self) -> bool:
"""
Update an existing account's attributes.
This method modifies specified attributes of an existing account.
Returns:
True if account was successfully updated, False otherwise
"""
# Get user object
user = self.connection.g... |
Update an existing account's attributes.
This method modifies specified attributes of an existing account.
Returns:
True if account was successfully updated, False otherwise
| update | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def delete(self) -> bool:
"""
Delete an account from Active Directory.
This method permanently removes the specified account.
Returns:
True if account was successfully deleted, False otherwise
"""
# Get user object
user = self.connection.get_user(sel... |
Delete an account from Active Directory.
This method permanently removes the specified account.
Returns:
True if account was successfully deleted, False otherwise
| delete | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def entry(options: argparse.Namespace) -> None:
"""
Entry point for the 'account' command.
This function creates the Account object and dispatches to the appropriate method
based on the specified action.
Args:
options: Command line options
"""
# Create target from command line opti... |
Entry point for the 'account' command.
This function creates the Account object and dispatches to the appropriate method
based on the specified action.
Args:
options: Command line options
| entry | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def __init__(self, tcp_shell: Any, domain_dumper: Any, client: Any):
"""
Initialize the LDAP shell.
Args:
tcp_shell: Shell to use for I/O
domain_dumper: Domain information provider
client: LDAP client connection
"""
super().__init__(tcp_shell,... |
Initialize the LDAP shell.
Args:
tcp_shell: Shell to use for I/O
domain_dumper: Domain information provider
client: LDAP client connection
| __init__ | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def truncate_key(value: bytes, keysize: int) -> bytes:
"""
Truncate a key to the specified size using SHA1 hashing.
Args:
value: Input key material
keysize: Desired key size in bytes
Returns:
Truncated key of exactly keysize bytes
"""
output = b""
current_num = 0
... |
Truncate a key to the specified size using SHA1 hashing.
Args:
value: Input key material
keysize: Desired key size in bytes
Returns:
Truncated key of exactly keysize bytes
| truncate_key | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def __init__(
self,
target: Target,
pfx: Optional[str] = None,
username: Optional[str] = None,
domain: Optional[str] = None,
password: Optional[str] = None,
cert: Optional[x509.Certificate] = None,
key: Optional[PrivateKeyTypes] = None,
no_save: bo... |
Initialize authentication parameters.
Args:
target: Target information (domain, DC IP, etc.)
pfx: Path to PFX/P12 certificate file
username: Username to authenticate as
domain: Domain to authenticate to
password: Password for PFX file
... | __init__ | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def authenticate(
self,
username: Optional[str] = None,
domain: Optional[str] = None,
is_key_credential: bool = False,
) -> Union[str, bool, None]:
"""
Authenticate using a certificate.
This is the main entry point for authentication. It will determine
... |
Authenticate using a certificate.
This is the main entry point for authentication. It will determine
whether to use LDAP or Kerberos authentication based on configuration.
Args:
username: Username to authenticate as
domain: Domain to authenticate to
... | authenticate | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def _check_identity_mismatches(
self,
username: Optional[str],
domain: Optional[str],
cert_username: Optional[str],
cert_domain: Optional[str],
) -> Optional[bool]:
"""
Check for mismatches between provided identity and certificate identity.
Args:
... |
Check for mismatches between provided identity and certificate identity.
Args:
username: Provided username
domain: Provided domain
cert_username: Username from certificate
cert_domain: Domain from certificate
Returns:
None if checks ... | _check_identity_mismatches | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def ldap_authentication(self, domain: Optional[str] = None) -> bool:
"""
Authenticate to LDAP using a certificate.
Args:
domain: Domain to authenticate to
Returns:
True if successful, False otherwise
"""
if self.key is None:
raise Val... |
Authenticate to LDAP using a certificate.
Args:
domain: Domain to authenticate to
Returns:
True if successful, False otherwise
| ldap_authentication | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def kerberos_authentication(
self,
username: str,
domain: str,
is_key_credential: bool = False,
id_type: Optional[str] = None,
identity: Optional[str] = None,
object_sid: Optional[str] = None,
upn: Optional[str] = None,
) -> Union[str, bool, None]:
... |
Authenticate to Kerberos using PKINIT with a certificate.
Args:
username: Username to authenticate as
domain: Domain to authenticate to
is_key_credential: Whether we're using a key credential
id_type: Type of identity in certificate
identity:... | kerberos_authentication | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def entry(options: argparse.Namespace) -> None:
"""
Entry point for the 'auth' command.
Args:
options: Command-line arguments
"""
# Ensure we don't try to use password authentication
options.no_pass = True
# Create target from options
target = Target.from_options(options, dc_as... |
Entry point for the 'auth' command.
Args:
options: Command-line arguments
| entry | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def request(self, req: Any, *args, **kwargs): # type: ignore
"""
Send a request to the CA service.
Args:
req: Request object
*args: Additional arguments
**kwargs: Additional keyword arguments
Returns:
Response from the CA service
... |
Send a request to the CA service.
Args:
req: Request object
*args: Additional arguments
**kwargs: Additional keyword arguments
Returns:
Response from the CA service
Raises:
DCERPCException: If the RPC call fails
| request | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def __init__(
self,
target: Target,
ca: Optional[str] = None,
template: Optional[str] = None,
officer: Optional[str] = None,
request_id: Optional[int] = None,
connection: Optional[LDAPConnection] = None,
scheme: str = "ldaps",
dynamic: bool = False... |
Initialize CA management object.
Args:
target: Target information (hostname, credentials, etc.)
ca: CA name
template: Certificate template name
officer: Officer username
request_id: Certificate request ID
connection: Existing LDAP... | __init__ | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def connection(self) -> LDAPConnection:
"""
Get or create an LDAP connection to the domain.
Returns:
Active LDAP connection
Raises:
ValueError: If target resolution fails
"""
if self._connection:
return self._connection
targe... |
Get or create an LDAP connection to the domain.
Returns:
Active LDAP connection
Raises:
ValueError: If target resolution fails
| connection | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def cert_admin(self) -> ICertAdminD:
"""
Get or create an ICertAdminD interface.
Returns:
ICertAdminD interface
"""
if self._cert_admin is not None:
return self._cert_admin
dcom = get_dcom_connection(self.target)
interface = dcom.CoCreate... |
Get or create an ICertAdminD interface.
Returns:
ICertAdminD interface
| cert_admin | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def cert_admin2(self) -> ICertAdminD2:
"""
Get or create an ICertAdminD2 interface.
Returns:
ICertAdminD2 interface
"""
if self._cert_admin2 is not None:
return self._cert_admin2
dcom = get_dcom_connection(self.target)
interface = dcom.Co... |
Get or create an ICertAdminD2 interface.
Returns:
ICertAdminD2 interface
| cert_admin2 | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def cert_request2(self) -> ICertRequestD2:
"""
Get or create an ICertRequestD2 interface.
Returns:
ICertRequestD2 interface
"""
if self._cert_request2 is not None:
return self._cert_request2
dcom = get_dcom_connection(self.target)
interfa... |
Get or create an ICertRequestD2 interface.
Returns:
ICertRequestD2 interface
| cert_request2 | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def rrp_dce(self):
"""
Get or create a connection to the remote registry service.
Returns:
RRP DCE/RPC connection or None if connection fails
"""
if self._rrp_dce is not None:
return self._rrp_dce
dce = get_dce_rpc_from_string_binding(
... |
Get or create a connection to the remote registry service.
Returns:
RRP DCE/RPC connection or None if connection fails
| rrp_dce | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_exchange_certificate(self) -> x509.Certificate:
"""
Get the CA exchange certificate.
Returns:
CA exchange certificate
Raises:
Exception: If the certificate retrieval fails
"""
request = ICertRequestD2GetCAProperty()
request["pwszA... |
Get the CA exchange certificate.
Returns:
CA exchange certificate
Raises:
Exception: If the certificate retrieval fails
| get_exchange_certificate | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_config_rrp(self) -> "CAConfiguration":
"""
Get CA configuration via the Remote Registry Protocol.
Used as a fallback when CSRA fails.
This method navigates the Windows registry structure to extract CA configuration
settings including policy modules, edit flags, request d... |
Get CA configuration via the Remote Registry Protocol.
Used as a fallback when CSRA fails.
This method navigates the Windows registry structure to extract CA configuration
settings including policy modules, edit flags, request disposition,
disabled extensions, interface flags, ... | get_config_rrp | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_config(self) -> Optional["CAConfiguration"]:
"""
Get CA configuration using the Remote Registry Protocol (RRP).
This method attempts to retrieve the CA configuration using RRP
and handles any exceptions that might occur during the process.
Returns:
CAConfigu... |
Get CA configuration using the Remote Registry Protocol (RRP).
This method attempts to retrieve the CA configuration using RRP
and handles any exceptions that might occur during the process.
Returns:
CAConfiguration object containing configuration settings or None if retri... | get_config | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def issue(self) -> bool:
"""
Issue (approve) a pending certificate request.
Returns:
True if successful, False otherwise
"""
if self.request_id is None:
logging.error(
"A request ID (-request-id) is required in order to issue a pending or ... |
Issue (approve) a pending certificate request.
Returns:
True if successful, False otherwise
| issue | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def deny(self) -> bool:
"""
Deny a pending certificate request.
Returns:
True if successful, False otherwise
"""
if self.request_id is None:
logging.error(
"A request ID (-request-id) is required in order to deny a pending certificate requ... |
Deny a pending certificate request.
Returns:
True if successful, False otherwise
| deny | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.