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 _capture_onecmd(self, line): """ Run one Pdb command, but capture and return stdout. """ stdout = self.stdout lastcmd = self.lastcmd try: self.stdout = StringIO() super().onecmd(line) result = self.stdout.getvalue().rstrip() ...
Run one Pdb command, but capture and return stdout.
_capture_onecmd
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def _getval(self, arg): """ Sandbox for evaluating expressions from the LLM. """ try: if chatdbg_config.unsafe: return super()._getval(arg) else: return sandbox_eval(arg, self.curframe.f_globals, self.curframe_locals) except...
Sandbox for evaluating expressions from the LLM.
_getval
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def _getval_except(self, arg, frame=None): """ Sandbox in case an LLM ever tries to use the display features... """ try: if frame is None: return sandbox_eval(arg, self.curframe.f_globals, self.curframe_locals) else: return sandbox_...
Sandbox in case an LLM ever tries to use the display features...
_getval_except
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_pydoc(self, arg): """pydoc name Print the pydoc string for a name. """ try: obj = self._getval(arg) if obj.__doc__ != None: pydoc.doc(obj, output=self.stdout) else: self.message(f"No documentation is available.") ...
pydoc name Print the pydoc string for a name.
do_pydoc
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_info(self, arg): """info name Print the pydoc string (and source code, if available) for a name. """ try: # try both given and unqualified form incase LLM biffs args_to_try = [arg, arg.split(".")[-1]] obj = None for x in args_to_try...
info name Print the pydoc string (and source code, if available) for a name.
do_info
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_slice(self, arg): """ slice Print the backwards slice for a variable used in the current cell but defined in an earlier cell. [interactive IPython / Jupyter only] """ if not self._supports_flow: self.message("*** `slice` is only supported in Jupyter no...
slice Print the backwards slice for a variable used in the current cell but defined in an earlier cell. [interactive IPython / Jupyter only]
do_slice
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_test_prompt(self, arg): """test_prompt [For debugging] Prints the prompts to be sent to the assistant. """ self.message("Instructions:") self.message(self._initial_prompt_instructions()) self.message("-" * 80) self.message("Prompt:") self.message(se...
test_prompt [For debugging] Prints the prompts to be sent to the assistant.
do_test_prompt
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def _hidden_predicate(self, frame): """ Given a frame return whether it it should be hidden or not by IPython. """ if self._predicates["readonly"]: fname = frame.f_code.co_filename # we need to check for file existence and interactively define # funct...
Given a frame return whether it it should be hidden or not by IPython.
_hidden_predicate
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_renew(self, arg): """renew End the current chat dialog and prepare to start a new one. """ if self._assistant != None: self._assistant.close() self._assistant = None self.was_chat_or_renew = True self.message(f"Ready to start a new dialog.")
renew End the current chat dialog and prepare to start a new one.
do_renew
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def do_config(self, arg): """ config Print out the ChatDBG config options. """ args = arg.split() message = chatdbg_config.parse_only_user_flags(args) self.message(message)
config Print out the ChatDBG config options.
do_config
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def info(self, value): """ { "name": "info", "description": "Call the `info` function to get the documentation and source code for any variable, function, package, class, method reference, field reference, or dotted reference visible in the current frame. Examples include: n, e....
{ "name": "info", "description": "Call the `info` function to get the documentation and source code for any variable, function, package, class, method reference, field reference, or dotted reference visible in the current frame. Examples include: n, e.n where e is an expression, and t....
info
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def debug(self, command): """ { "name": "debug", "description": "Call the `debug` function to run Pdb debugger commands on the stopped program. You may call the `pdb` function to run the following commands: `bt`, `up`, `down`, `p expression`, `list`. Call `debug` to print any va...
{ "name": "debug", "description": "Call the `debug` function to run Pdb debugger commands on the stopped program. You may call the `pdb` function to run the following commands: `bt`, `up`, `down`, `p expression`, `list`. Call `debug` to print any variable value or expression that you b...
debug
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def slice(self, name): """ { "name": "slice", "description": "Call the `slice` function to get the code used to produce the value currently stored a variable. You MUST call `slice` exactly once on any variable used but not defined in the current frame's code.", "para...
{ "name": "slice", "description": "Call the `slice` function to get the code used to produce the value currently stored a variable. You MUST call `slice` exactly once on any variable used but not defined in the current frame's code.", "parameters": { "type":...
slice
python
plasma-umass/ChatDBG
src/chatdbg/chatdbg_pdb.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/chatdbg_pdb.py
Apache-2.0
def query(self, prompt: str, user_text): """ Send a query to the LLM. - prompt is the prompt to send. - user_text is what the user typed (which may or not be the same as prompt) Returns a dictionary containing: - "completed": True of the query ran to com...
Send a query to the LLM. - prompt is the prompt to send. - user_text is what the user typed (which may or not be the same as prompt) Returns a dictionary containing: - "completed": True of the query ran to completion. - "cost": Cost of...
query
python
plasma-umass/ChatDBG
src/chatdbg/assistant/assistant.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/assistant/assistant.py
Apache-2.0
def _add_function(self, function): """ Add a new function to the list of function tools. The function should have the necessary json spec as its docstring """ schema = json.loads(function.__doc__) assert "name" in schema, "Bad JSON in docstring for function tool." ...
Add a new function to the list of function tools. The function should have the necessary json spec as its docstring
_add_function
python
plasma-umass/ChatDBG
src/chatdbg/assistant/assistant.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/assistant/assistant.py
Apache-2.0
def make_arrow(pad): """generate the leading arrow in front of traceback or debugger""" if pad >= 2: return "-" * (pad - 2) + "> " elif pad == 1: return ">" return ""
generate the leading arrow in front of traceback or debugger
make_arrow
python
plasma-umass/ChatDBG
src/chatdbg/custom_pdb/text.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/custom_pdb/text.py
Apache-2.0
def llm_get_code_surrounding(self, filename: str, line_number: int) -> str: """ { "name": "get_code_surrounding", "description": "The `get_code_surrounding` function returns the source code in the given file surrounding and including the provided line number.", "param...
{ "name": "get_code_surrounding", "description": "The `get_code_surrounding` function returns the source code in the given file surrounding and including the provided line number.", "parameters": { "type": "object", "properties": { ...
llm_get_code_surrounding
python
plasma-umass/ChatDBG
src/chatdbg/native_util/dbg_dialog.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/native_util/dbg_dialog.py
Apache-2.0
def llm_find_definition(self, filename: str, line_number: int, symbol: str) -> str: """ { "name": "find_definition", "description": "The `find_definition` function returns the source code for the definition for the given symbol at the given source line number. Call `find_definit...
{ "name": "find_definition", "description": "The `find_definition` function returns the source code for the definition for the given symbol at the given source line number. Call `find_definition` on every symbol that could be linked to the issue.", "parameters": { ...
llm_find_definition
python
plasma-umass/ChatDBG
src/chatdbg/native_util/dbg_dialog.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/native_util/dbg_dialog.py
Apache-2.0
def _sandboxed_call(func, *args, **kwargs): """ Check if the function is in the module whitelist before calling it. """ allowed_modules = chatdbg_config.get_module_whitelist() # Get the module name of the function. # If the module name is None, use the __name__ attribute of the globals dictiona...
Check if the function is in the module whitelist before calling it.
_sandboxed_call
python
plasma-umass/ChatDBG
src/chatdbg/pdb_util/sandbox.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/pdb_util/sandbox.py
Apache-2.0
def sandbox_eval(expression, globals, locals): """ Wrap all function calls in the expression with a call to _sandboxed_call. This function will raise an ImportError if the function is not in the module whitelist. """ tree = ast.parse(expression, mode="eval") tree = SandboxTransformer().visit(tre...
Wrap all function calls in the expression with a call to _sandboxed_call. This function will raise an ImportError if the function is not in the module whitelist.
sandbox_eval
python
plasma-umass/ChatDBG
src/chatdbg/pdb_util/sandbox.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/pdb_util/sandbox.py
Apache-2.0
def to_json(self) -> dict[str, Union[int, str, bool]]: """Serialize the object to a JSON string.""" return { "model": self.model, "log": self.log, "tag": self.tag, "rc_lines": self.rc_lines, "context": self.context, "show_locals": s...
Serialize the object to a JSON string.
to_json
python
plasma-umass/ChatDBG
src/chatdbg/util/config.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/util/config.py
Apache-2.0
def make_arrow(pad): """generate the leading arrow in front of traceback or debugger""" if pad >= 2: return "-" * (pad - 2) + "> " elif pad == 1: return ">" return ""
generate the leading arrow in front of traceback or debugger
make_arrow
python
plasma-umass/ChatDBG
src/chatdbg/util/text.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/util/text.py
Apache-2.0
def word_wrap_except_code_blocks(text: str, width: int = 80) -> str: """ Wraps text except for code blocks for nice terminal formatting. Splits the text into paragraphs and wraps each paragraph, except for paragraphs that are inside of code blocks denoted by ` ``` `. Returns the updated text. ...
Wraps text except for code blocks for nice terminal formatting. Splits the text into paragraphs and wraps each paragraph, except for paragraphs that are inside of code blocks denoted by ` ``` `. Returns the updated text. Args: text (str): The text to wrap. width (int): The width o...
word_wrap_except_code_blocks
python
plasma-umass/ChatDBG
src/chatdbg/util/wrap.py
https://github.com/plasma-umass/ChatDBG/blob/master/src/chatdbg/util/wrap.py
Apache-2.0
async def generate_code_and_time( image_url: str, stack: Stack, model: Llm, original_input_filename: str, attempt_idx: int, ) -> Tuple[str, int, Optional[str], Optional[float], Optional[Exception]]: """ Generates code for an image, measures the time taken, and returns identifiers along w...
Generates code for an image, measures the time taken, and returns identifiers along with success/failure status. Returns a tuple: (original_input_filename, attempt_idx, content, duration, error_object) content and duration are None if an error occurs during generation.
generate_code_and_time
python
abi/screenshot-to-code
backend/evals/runner.py
https://github.com/abi/screenshot-to-code/blob/master/backend/evals/runner.py
MIT
def convert_openai_messages_to_claude( messages: List[ChatCompletionMessageParam], ) -> Tuple[str, List[Dict[str, Any]]]: """ Convert OpenAI format messages to Claude format, handling image content properly. Args: messages: List of messages in OpenAI format Returns: Tuple of (syste...
Convert OpenAI format messages to Claude format, handling image content properly. Args: messages: List of messages in OpenAI format Returns: Tuple of (system_prompt, claude_messages)
convert_openai_messages_to_claude
python
abi/screenshot-to-code
backend/models/claude.py
https://github.com/abi/screenshot-to-code/blob/master/backend/models/claude.py
MIT
def extract_image_from_messages( messages: List[ChatCompletionMessageParam], ) -> Dict[str, str]: """ Extracts image data from OpenAI-style chat completion messages. Args: messages: List of ChatCompletionMessageParam containing message content Returns: Dictionary with mime_type and...
Extracts image data from OpenAI-style chat completion messages. Args: messages: List of ChatCompletionMessageParam containing message content Returns: Dictionary with mime_type and data keys for the first image found
extract_image_from_messages
python
abi/screenshot-to-code
backend/models/gemini.py
https://github.com/abi/screenshot-to-code/blob/master/backend/models/gemini.py
MIT
async def get_eval_input_files(): """Get a list of all input files available for evaluations""" input_dir = os.path.join(EVALS_DIR, "inputs") try: files: list[InputFile] = [] for filename in os.listdir(input_dir): if filename.endswith(".png"): file_path = os.path....
Get a list of all input files available for evaluations
get_eval_input_files
python
abi/screenshot-to-code
backend/routes/evals.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/evals.py
MIT
async def run_evals(request: RunEvalsRequest) -> List[str]: """Run evaluations on selected images in the inputs directory for multiple models""" all_output_files: List[str] = [] for model in request.models: output_files = await run_image_evals( model=model, stack=request.stack, input_fi...
Run evaluations on selected images in the inputs directory for multiple models
run_evals
python
abi/screenshot-to-code
backend/routes/evals.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/evals.py
MIT
async def get_output_folders(): """Get a list of all output folders available for evaluations, sorted by recently modified""" output_dir = os.path.join(EVALS_DIR, "results") try: folders: list[OutputFolder] = [] for folder_name in os.listdir(output_dir): folder_path = os.path.joi...
Get a list of all output folders available for evaluations, sorted by recently modified
get_output_folders
python
abi/screenshot-to-code
backend/routes/evals.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/evals.py
MIT
async def process( self, context: PipelineContext, next_func: Callable[[], Awaitable[None]] ) -> None: """Process the context and call the next middleware""" pass
Process the context and call the next middleware
process
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def execute(self, websocket: WebSocket) -> None: """Execute the pipeline with the given WebSocket""" context = PipelineContext(websocket=websocket) # Build the middleware chain async def start(ctx: PipelineContext): pass # End of pipeline chain = start ...
Execute the pipeline with the given WebSocket
execute
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def _wrap_middleware( self, middleware: Middleware, next_func: Callable[[PipelineContext], Awaitable[None]], ) -> Callable[[PipelineContext], Awaitable[None]]: """Wrap a middleware with its next function""" async def wrapped(context: PipelineContext) -> None: awa...
Wrap a middleware with its next function
_wrap_middleware
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def send_message( self, type: MessageType, value: str, variantIndex: int, ) -> None: """Send a message to the client with debug logging""" # Print for debugging on the backend if type == "error": print(f"Error (variant {variantIndex}): {value...
Send a message to the client with debug logging
send_message
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def throw_error(self, message: str) -> None: """Send an error message and close the connection""" print(message) if not self.is_closed: await self.websocket.send_json({"type": "error", "value": message}) await self.websocket.close(APP_ERROR_WEB_SOCKET_CODE) ...
Send an error message and close the connection
throw_error
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def extract_and_validate(self, params: Dict[str, str]) -> ExtractedParams: """Extract and validate all parameters from the request""" # Read the code config settings (stack) from the request. generated_code_config = params.get("generatedCodeConfig", "") if generated_code_config not...
Extract and validate all parameters from the request
extract_and_validate
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def _get_from_settings_dialog_or_env( self, params: dict[str, str], key: str, env_var: str | None ) -> str | None: """Get value from client settings or environment variable""" value = params.get(key) if value: print(f"Using {key} from client-side settings dialog") ...
Get value from client settings or environment variable
_get_from_settings_dialog_or_env
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def select_models( self, generation_type: Literal["create", "update"], input_mode: InputMode, openai_api_key: str | None, anthropic_api_key: str | None, gemini_api_key: str | None = None, ) -> List[Llm]: """Select appropriate models based on available AP...
Select appropriate models based on available API keys
select_models
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def _get_variant_models( self, generation_type: Literal["create", "update"], input_mode: InputMode, num_variants: int, openai_api_key: str | None, anthropic_api_key: str | None, gemini_api_key: str | None, ) -> List[Llm]: """Simple model cycling that s...
Simple model cycling that scales with num_variants
_get_variant_models
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def create_prompt( self, params: Dict[str, str], stack: Stack, input_mode: InputMode, ) -> tuple[List[ChatCompletionMessageParam], Dict[str, str]]: """Create prompt messages and return image cache""" try: prompt_messages, image_cache = await create_p...
Create prompt messages and return image cache
create_prompt
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def generate_video_code( self, prompt_messages: List[ChatCompletionMessageParam], anthropic_api_key: str | None, ) -> List[str]: """Generate code for video input mode""" if not anthropic_api_key: await self.throw_error( "Video only works with...
Generate code for video input mode
generate_video_code
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def process_variants( self, variant_models: List[Llm], prompt_messages: List[ChatCompletionMessageParam], image_cache: Dict[str, str], params: Dict[str, str], ) -> Dict[int, str]: """Process all variants in parallel and return completions""" tasks = self...
Process all variants in parallel and return completions
process_variants
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def _create_generation_tasks( self, variant_models: List[Llm], prompt_messages: List[ChatCompletionMessageParam], params: Dict[str, str], ) -> List[Coroutine[Any, Any, Completion]]: """Create generation tasks for each variant model""" tasks: List[Coroutine[Any, Any, C...
Create generation tasks for each variant model
_create_generation_tasks
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def _stream_openai_with_error_handling( self, prompt_messages: List[ChatCompletionMessageParam], model_name: str, index: int, ) -> Completion: """Wrap OpenAI streaming with specific error handling""" try: assert self.openai_api_key is not None ...
Wrap OpenAI streaming with specific error handling
_stream_openai_with_error_handling
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def _perform_image_generation( self, completion: str, image_cache: dict[str, str], ): """Generate images for the completion if needed""" if not self.should_generate_images: return completion replicate_api_key = REPLICATE_API_KEY if replicate...
Generate images for the completion if needed
_perform_image_generation
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def _process_variant_completion( self, index: int, task: asyncio.Task[Completion], model: Llm, image_cache: Dict[str, str], variant_completions: Dict[int, str], ): """Process a single variant completion including image generation""" try: ...
Process a single variant completion including image generation
_process_variant_completion
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
async def stream_code(websocket: WebSocket): """Handle WebSocket code generation requests using a pipeline pattern""" pipeline = Pipeline() # Configure the pipeline pipeline.use(WebSocketSetupMiddleware()) pipeline.use(ParameterExtractionMiddleware()) pipeline.use(StatusBroadcastMiddleware()) ...
Handle WebSocket code generation requests using a pipeline pattern
stream_code
python
abi/screenshot-to-code
backend/routes/generate_code.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/generate_code.py
MIT
def normalize_url(url: str) -> str: """ Normalize URL to ensure it has a proper protocol. If no protocol is specified, default to https:// """ url = url.strip() # Parse the URL parsed = urlparse(url) # Check if we have a scheme if not parsed.scheme: # No scheme, add...
Normalize URL to ensure it has a proper protocol. If no protocol is specified, default to https://
normalize_url
python
abi/screenshot-to-code
backend/routes/screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/routes/screenshot.py
MIT
def test_url_without_protocol(self): """Test that URLs without protocol get https:// added.""" assert normalize_url("example.com") == "https://example.com" assert normalize_url("www.example.com") == "https://www.example.com" assert normalize_url("subdomain.example.com") == "https://subdo...
Test that URLs without protocol get https:// added.
test_url_without_protocol
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def test_url_with_http_protocol(self): """Test that existing http protocol is preserved.""" assert normalize_url("http://example.com") == "http://example.com" assert normalize_url("http://www.example.com") == "http://www.example.com"
Test that existing http protocol is preserved.
test_url_with_http_protocol
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def test_url_with_https_protocol(self): """Test that existing https protocol is preserved.""" assert normalize_url("https://example.com") == "https://example.com" assert normalize_url("https://www.example.com") == "https://www.example.com"
Test that existing https protocol is preserved.
test_url_with_https_protocol
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def test_url_with_path_and_params(self): """Test URLs with paths and query parameters.""" assert normalize_url("example.com/path") == "https://example.com/path" assert normalize_url("example.com/path?param=value") == "https://example.com/path?param=value" assert normalize_url("example.co...
Test URLs with paths and query parameters.
test_url_with_path_and_params
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def test_invalid_protocols(self): """Test that unsupported protocols raise ValueError.""" with pytest.raises(ValueError, match="Unsupported protocol: ftp"): normalize_url("ftp://example.com") with pytest.raises(ValueError, match="Unsupported protocol: file"): nor...
Test that unsupported protocols raise ValueError.
test_invalid_protocols
python
abi/screenshot-to-code
backend/tests/test_screenshot.py
https://github.com/abi/screenshot-to-code/blob/master/backend/tests/test_screenshot.py
MIT
def extract_tag_content(tag: str, text: str) -> str: """ Extracts content for a given tag from the provided text. :param tag: The tag to search for. :param text: The text to search within. :return: The content found within the tag, if any. """ tag_start = f"<{tag}>" tag_end = f"</{tag}>...
Extracts content for a given tag from the provided text. :param tag: The tag to search for. :param text: The text to search within. :return: The content found within the tag, if any.
extract_tag_content
python
abi/screenshot-to-code
backend/video/utils.py
https://github.com/abi/screenshot-to-code/blob/master/backend/video/utils.py
MIT
def count(start: int = 0, step: int = 1): """Local implementation of `itertools.count()` to allow v2.6 compatibility.""" n = start while True: yield n n += step
Local implementation of `itertools.count()` to allow v2.6 compatibility.
count
python
scanny/python-pptx
features/steps/helpers.py
https://github.com/scanny/python-pptx/blob/master/features/steps/helpers.py
MIT
def then_the_size_of_the_text_is_10pt(context): """Size depends on Pillow version, probably algorithm isn't quite right either.""" text_frame = context.text_frame for paragraph in text_frame.paragraphs: for run in paragraph.runs: assert run.font.size in (Pt(10.0), Pt(11.0)), "got %s" % r...
Size depends on Pillow version, probably algorithm isn't quite right either.
then_the_size_of_the_text_is_10pt
python
scanny/python-pptx
features/steps/text_frame.py
https://github.com/scanny/python-pptx/blob/master/features/steps/text_frame.py
MIT
def _child(element, child_tagname): """ Return direct child of *element* having *child_tagname* or :class:`None` if no such child element is present. """ xpath = './%s' % child_tagname matching_children = element.xpath(xpath, namespaces=nsmap) return matching_children[0] if len(matching_chil...
Return direct child of *element* having *child_tagname* or :class:`None` if no such child element is present.
_child
python
scanny/python-pptx
lab/cust-elm-classes/main.py
https://github.com/scanny/python-pptx/blob/master/lab/cust-elm-classes/main.py
MIT
def _child_list(element, child_tagname): """ Return list containing the direct children of *element* having *child_tagname*. """ xpath = './%s' % child_tagname return element.xpath(xpath, namespaces=nsmap)
Return list containing the direct children of *element* having *child_tagname*.
_child_list
python
scanny/python-pptx
lab/cust-elm-classes/main.py
https://github.com/scanny/python-pptx/blob/master/lab/cust-elm-classes/main.py
MIT
def _nsmap(*prefixes): """ Return a dict containing the subset namespace prefix mappings specified by *prefixes*. Any number of namespace prefixes can be supplied, e.g. namespaces('a', 'r', 'p'). """ namespaces = {} for prefix in prefixes: namespaces[prefix] = nsmap[prefix] retur...
Return a dict containing the subset namespace prefix mappings specified by *prefixes*. Any number of namespace prefixes can be supplied, e.g. namespaces('a', 'r', 'p').
_nsmap
python
scanny/python-pptx
lab/cust-elm-classes/main.py
https://github.com/scanny/python-pptx/blob/master/lab/cust-elm-classes/main.py
MIT
def pfxdtag(tag): """ Return short-form prefixed tag from fully qualified (Clark notation) tagname. """ uri, tagroot = tag[1:].split('}') prefix = reverse_nsmap[uri] return '%s:%s' % (prefix, tagroot)
Return short-form prefixed tag from fully qualified (Clark notation) tagname.
pfxdtag
python
scanny/python-pptx
lab/parse_xsd/objectify_lab.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/objectify_lab.py
MIT
def qn(tag): """ qn is short for *qualified name*. Return fully qualified (Clark notation) tagname corresponding to short-form prefixed tagname *tag*. """ prefix, tagroot = tag.split(':') uri = nsmap[prefix] return '{%s}%s' % (uri, tagroot)
qn is short for *qualified name*. Return fully qualified (Clark notation) tagname corresponding to short-form prefixed tagname *tag*.
qn
python
scanny/python-pptx
lab/parse_xsd/objectify_lab.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/objectify_lab.py
MIT
def pfxdtag(tag): """ Return short-form prefixed tag from fully qualified (Clark notation) tagname. """ uri, tagroot = tag[1:].split('}') prefix = reverse_nsmap[uri] return '%s:%s' % (prefix, tagroot)
Return short-form prefixed tag from fully qualified (Clark notation) tagname.
pfxdtag
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def qtag(tag): """ Return fully qualified (Clark notation) tagname corresponding to short-form prefixed tagname *tag*. """ prefix, tagroot = tag.split(':') uri = nsmap[prefix] return '{%s}%s' % (uri, tagroot)
Return fully qualified (Clark notation) tagname corresponding to short-form prefixed tagname *tag*.
qtag
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def get_complexType(self, typename): """Return complex type element with name *typename*""" if typename.startswith('a:'): typename = typename[2:] xpath = "./xsd:complexType[@name='%s']" % typename for xsd in self.__xsd_trees: elms = xsd.xpath(xpath) if...
Return complex type element with name *typename*
get_complexType
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def getdef(self, defname, tag='*'): """Return definition element with name *defname*""" if defname.startswith('a:'): defname = defname[2:] for xsd in self.__xsd_trees: xpath = "./%s[@name='%s']" % (tag, defname) elements = xsd.xpath(xpath) if eleme...
Return definition element with name *defname*
getdef
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def element_def(self): """ blipFill = ElementDef('p:blipFill', 'CT_BlipFillProperties') blipFill.add_child('a:blip', cardinality='?') blipFill.add_attributes('dpi', 'rotWithShape') """ s = ("%s = ElementDef('%s', '%s')\n" % (self.name, self.name, self.name)) ...
blipFill = ElementDef('p:blipFill', 'CT_BlipFillProperties') blipFill.add_child('a:blip', cardinality='?') blipFill.add_attributes('dpi', 'rotWithShape')
element_def
python
scanny/python-pptx
lab/parse_xsd/parse_xsd.py
https://github.com/scanny/python-pptx/blob/master/lab/parse_xsd/parse_xsd.py
MIT
def load_adjustment_values(self, c): """load adjustment values for auto shape types in self""" # retrieve auto shape types in const_name order -------- for mast in self: # retriev adj vals for this auto shape type -------- c.execute( ' SELECT name, val\n'...
load adjustment values for auto shape types in self
load_adjustment_values
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def create_tables(c): """create (or recreate) the auto shape type tables""" # auto_shape_types --------------------- c.execute( 'DROP TABLE IF EXISTS auto_shape_types' ) c.execute( 'CREATE TABLE auto_shape_types (\n' ' id integer,\n' ' prst text,\n...
create (or recreate) the auto shape type tables
create_tables
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def insert_adjustment_values(c): """insert adjustment values into their table""" adjustment_values = load_adjustment_values() # insert into table ------------------------------------ q_insert = ( 'INSERT INTO adjustment_values\n' ' (prst, seq_nmbr, name, val)\n' ' ...
insert adjustment values into their table
insert_adjustment_values
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def load_adjustment_values(): """load adjustment values and their default values from XML""" # parse XML -------------------------------------------- thisdir = os.path.split(__file__)[0] prst_defs_relpath = ( 'ISO-IEC-29500-1/schemas/dml-geometries/OfficeOpenXML-DrawingMLGeomet' 'ries/pr...
load adjustment values and their default values from XML
load_adjustment_values
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def print_mso_auto_shape_type_constants(): """print symbolic constant definitions for msoAutoShapeType""" auto_shape_types = MsoAutoShapeTypeCollection.load(sort='const_name') out = render_mso_auto_shape_type_constants(auto_shape_types) print out
print symbolic constant definitions for msoAutoShapeType
print_mso_auto_shape_type_constants
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def print_mso_auto_shape_type_enum(): """print symbolic constant definitions for msoAutoShapeType""" auto_shape_types = MsoAutoShapeTypeCollection.load(sort='const_name') out = render_mso_auto_shape_type_enum(auto_shape_types) print out
print symbolic constant definitions for msoAutoShapeType
print_mso_auto_shape_type_enum
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def render_desc(desc): """calculate desc string, wrapped if too long""" desc = desc + '.' desc_lines = split_len(desc, 54) if len(desc_lines) > 1: join_str = "'\n%s'" % (' '*21) lines_str = join_str.join(desc_lines) out = "('%s')" % lines_str else: out = "'%s'" % desc...
calculate desc string, wrapped if too long
render_desc
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def to_mixed_case(s): """ convert upper snake case string to mixed case, e.g. MIXED_CASE becomes MixedCase """ out = '' last_c = '' for c in s: if c == '_': pass elif last_c in ('', '_'): out += c.upper() else: out += c.lower() ...
convert upper snake case string to mixed case, e.g. MIXED_CASE becomes MixedCase
to_mixed_case
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def parse_args(spectypes): """ Return arguments object formed by parsing the command line used to launch the program. """ arg_parser = argparse.ArgumentParser() arg_parser.add_argument( "-c", "--constants", help="emit constants instead of spec dict", action="store_true" ...
Return arguments object formed by parsing the command line used to launch the program.
parse_args
python
scanny/python-pptx
spec/gen_spec/gen_spec.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/gen_spec.py
MIT
def msdn_msoAutoShapeTypes(): """ Return sequence of tuples representing the msoAutoShapeType enumeration as defined in the MS Office API. Access with:: for ms_name, id_, desc in msdn_msoAutoShapeTypes(): ... This is structured as a function simply so code folding will work on...
Return sequence of tuples representing the msoAutoShapeType enumeration as defined in the MS Office API. Access with:: for ms_name, id_, desc in msdn_msoAutoShapeTypes(): ... This is structured as a function simply so code folding will work on it.
msdn_msoAutoShapeTypes
python
scanny/python-pptx
spec/gen_spec/src_data/msoAutoShapeType.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/src_data/msoAutoShapeType.py
MIT
def prst_map(): """ Sequence of tuples representing the mapping of names in the msoAutoShapeType enumeration to the 'prst' and 'name' values used in the XML to specify and identify that auto shape type. These were discovered using the VBA editor in PowerPoint for Windows. Access with:: ...
Sequence of tuples representing the mapping of names in the msoAutoShapeType enumeration to the 'prst' and 'name' values used in the XML to specify and identify that auto shape type. These were discovered using the VBA editor in PowerPoint for Windows. Access with:: for ms_name, prst, bas...
prst_map
python
scanny/python-pptx
spec/gen_spec/src_data/msoAutoShapeType.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/src_data/msoAutoShapeType.py
MIT
def const_name_map(): """ Sequence of tuples representing the mapping of msoAutoShapeType enumeration names to the constant names used in python-pptx to identify an auto shape type. The mapping is largely coercing the camel case to upper snake case, but some names produced by that transformation req...
Sequence of tuples representing the mapping of msoAutoShapeType enumeration names to the constant names used in python-pptx to identify an auto shape type. The mapping is largely coercing the camel case to upper snake case, but some names produced by that transformation require transformation to be...
const_name_map
python
scanny/python-pptx
spec/gen_spec/src_data/msoAutoShapeType.py
https://github.com/scanny/python-pptx/blob/master/spec/gen_spec/src_data/msoAutoShapeType.py
MIT
def action(self): """Member of :ref:`PpActionType` enumeration, such as `PP_ACTION.HYPERLINK`. The returned member indicates the type of action that will result when the specified shape or text is clicked or the mouse pointer is positioned over the shape during a slide show. If...
Member of :ref:`PpActionType` enumeration, such as `PP_ACTION.HYPERLINK`. The returned member indicates the type of action that will result when the specified shape or text is clicked or the mouse pointer is positioned over the shape during a slide show. If there is no click-action or ...
action
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def target_slide(self) -> Slide | None: """ A reference to the slide in this presentation that is the target of the slide jump action in this shape. Slide jump actions include `PP_ACTION.FIRST_SLIDE`, `LAST_SLIDE`, `NEXT_SLIDE`, `PREVIOUS_SLIDE`, and `NAMED_SLIDE`. Returns |None|...
A reference to the slide in this presentation that is the target of the slide jump action in this shape. Slide jump actions include `PP_ACTION.FIRST_SLIDE`, `LAST_SLIDE`, `NEXT_SLIDE`, `PREVIOUS_SLIDE`, and `NAMED_SLIDE`. Returns |None| for all other actions. In particular, the ...
target_slide
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def _hlink(self) -> CT_Hyperlink | None: """ Reference to the `a:hlinkClick` or `a:hlinkHover` element for this click action. Returns |None| if the element is not present. """ if self._hover: assert isinstance(self._element, CT_NonVisualDrawingProps) retur...
Reference to the `a:hlinkClick` or `a:hlinkHover` element for this click action. Returns |None| if the element is not present.
_hlink
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def address(self) -> str | None: """Read/write. The URL of the hyperlink. URL can be on http, https, mailto, or file scheme; others may work. Returns |None| if no hyperlink is defined, including when another action such as `RUN_MACRO` is defined on the object. Assigning |None| removes a...
Read/write. The URL of the hyperlink. URL can be on http, https, mailto, or file scheme; others may work. Returns |None| if no hyperlink is defined, including when another action such as `RUN_MACRO` is defined on the object. Assigning |None| removes any action defined on the object, whether it ...
address
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def _get_or_add_hlink(self) -> CT_Hyperlink: """Get the `a:hlinkClick` or `a:hlinkHover` element for the Hyperlink object. The actual element depends on the value of `self._hover`. Create the element if not present. """ if self._hover: return cast("CT_NonVisualDrawingProps",...
Get the `a:hlinkClick` or `a:hlinkHover` element for the Hyperlink object. The actual element depends on the value of `self._hover`. Create the element if not present.
_get_or_add_hlink
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def _hlink(self) -> CT_Hyperlink | None: """Reference to the `a:hlinkClick` or `h:hlinkHover` element for this click action. Returns |None| if the element is not present. """ if self._hover: return cast("CT_NonVisualDrawingProps", self._element).hlinkHover return sel...
Reference to the `a:hlinkClick` or `h:hlinkHover` element for this click action. Returns |None| if the element is not present.
_hlink
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def _remove_hlink(self): """Remove the a:hlinkClick or a:hlinkHover element. Also drops any relationship it might have. """ hlink = self._hlink if hlink is None: return rId = hlink.rId if rId: self.part.drop_rel(rId) self._element....
Remove the a:hlinkClick or a:hlinkHover element. Also drops any relationship it might have.
_remove_hlink
python
scanny/python-pptx
src/pptx/action.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/action.py
MIT
def Presentation(pptx: str | IO[bytes] | None = None) -> presentation.Presentation: """ Return a |Presentation| object loaded from *pptx*, where *pptx* can be either a path to a ``.pptx`` file (a string) or a file-like object. If *pptx* is missing or ``None``, the built-in default presentation "temp...
Return a |Presentation| object loaded from *pptx*, where *pptx* can be either a path to a ``.pptx`` file (a string) or a file-like object. If *pptx* is missing or ``None``, the built-in default presentation "template" is loaded.
Presentation
python
scanny/python-pptx
src/pptx/api.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/api.py
MIT
def _default_pptx_path() -> str: """Return the path to the built-in default .pptx package.""" _thisdir = os.path.split(__file__)[0] return os.path.join(_thisdir, "templates", "default.pptx")
Return the path to the built-in default .pptx package.
_default_pptx_path
python
scanny/python-pptx
src/pptx/api.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/api.py
MIT
def _is_pptx_package(prs_part: PresentationPart): """Return |True| if *prs_part* is a valid main document part, |False| otherwise.""" valid_content_types = (CT.PML_PRESENTATION_MAIN, CT.PML_PRES_MACRO_MAIN) return prs_part.content_type in valid_content_types
Return |True| if *prs_part* is a valid main document part, |False| otherwise.
_is_pptx_package
python
scanny/python-pptx
src/pptx/api.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/api.py
MIT
def from_path_or_file_like(cls, movie_file: str | IO[bytes], mime_type: str | None) -> Video: """Return a new |Video| object containing video in *movie_file*. *movie_file* can be either a path (string) or a file-like (e.g. StringIO) object. """ if isinstance(movie_file, str): ...
Return a new |Video| object containing video in *movie_file*. *movie_file* can be either a path (string) or a file-like (e.g. StringIO) object.
from_path_or_file_like
python
scanny/python-pptx
src/pptx/media.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/media.py
MIT
def ext(self): """Return the file extension for this video, e.g. 'mp4'. The extension is that from the actual filename if known. Otherwise it is the lowercase canonical extension for the video's MIME type. 'vid' is used if the MIME type is 'video/unknown'. """ if self._f...
Return the file extension for this video, e.g. 'mp4'. The extension is that from the actual filename if known. Otherwise it is the lowercase canonical extension for the video's MIME type. 'vid' is used if the MIME type is 'video/unknown'.
ext
python
scanny/python-pptx
src/pptx/media.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/media.py
MIT
def filename(self) -> str: """Return a filename.ext string appropriate to this video. The base filename from the original path is used if this image was loaded from the filesystem. If no filename is available, such as when the video object is created from an in-memory stream, the string...
Return a filename.ext string appropriate to this video. The base filename from the original path is used if this image was loaded from the filesystem. If no filename is available, such as when the video object is created from an in-memory stream, the string 'movie.{ext}' is used where '...
filename
python
scanny/python-pptx
src/pptx/media.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/media.py
MIT
def core_properties(self) -> CorePropertiesPart: """Instance of |CoreProperties| holding read/write Dublin Core doc properties. Creates a default core properties part if one is not present (not common). """ try: return self.part_related_by(RT.CORE_PROPERTIES) except ...
Instance of |CoreProperties| holding read/write Dublin Core doc properties. Creates a default core properties part if one is not present (not common).
core_properties
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def next_image_partname(self, ext: str) -> PackURI: """Return a |PackURI| instance representing the next available image partname. Partname uses the next available sequence number. *ext* is used as the extention on the returned partname. """ def first_available_image_idx(): ...
Return a |PackURI| instance representing the next available image partname. Partname uses the next available sequence number. *ext* is used as the extention on the returned partname.
next_image_partname
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def next_media_partname(self, ext): """Return |PackURI| instance for next available media partname. Partname is first available, starting at sequence number 1. Empty sequence numbers are reused. *ext* is used as the extension on the returned partname. """ def first_avai...
Return |PackURI| instance for next available media partname. Partname is first available, starting at sequence number 1. Empty sequence numbers are reused. *ext* is used as the extension on the returned partname.
next_media_partname
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def __iter__(self) -> Iterator[ImagePart]: """Generate a reference to each |ImagePart| object in the package.""" image_parts = [] for rel in self._package.iter_rels(): if rel.is_external: continue if rel.reltype != RT.IMAGE: continue ...
Generate a reference to each |ImagePart| object in the package.
__iter__
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def get_or_add_image_part(self, image_file: str | IO[bytes]) -> ImagePart: """Return |ImagePart| object containing the image in `image_file`. `image_file` can be either a path to an image file or a file-like object containing an image. If an image part containing this same image already exists,...
Return |ImagePart| object containing the image in `image_file`. `image_file` can be either a path to an image file or a file-like object containing an image. If an image part containing this same image already exists, that instance is returned, otherwise a new image part is created.
get_or_add_image_part
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def _find_by_sha1(self, sha1: str) -> ImagePart | None: """ Return an |ImagePart| object belonging to this package or |None| if no matching image part is found. The image part is identified by the SHA1 hash digest of the image binary it contains. """ for image_part in sel...
Return an |ImagePart| object belonging to this package or |None| if no matching image part is found. The image part is identified by the SHA1 hash digest of the image binary it contains.
_find_by_sha1
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def __iter__(self): """Generate a reference to each |MediaPart| object in the package.""" # A media part can appear in more than one relationship (and commonly # does in the case of video). Use media_parts to keep track of those # that have been "yielded"; they can be skipped if they occ...
Generate a reference to each |MediaPart| object in the package.
__iter__
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def get_or_add_media_part(self, media): """Return a |MediaPart| object containing the media in *media*. If this package already contains a media part for the same bytestream, that instance is returned, otherwise a new media part is created. """ media_part = self._find_by...
Return a |MediaPart| object containing the media in *media*. If this package already contains a media part for the same bytestream, that instance is returned, otherwise a new media part is created.
get_or_add_media_part
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def _find_by_sha1(self, sha1): """Return |MediaPart| object having *sha1* hash or None if not found. All media parts belonging to this package are considered. A media part is identified by the SHA1 hash digest of its bytestream ("file"). """ for media_part in self: ...
Return |MediaPart| object having *sha1* hash or None if not found. All media parts belonging to this package are considered. A media part is identified by the SHA1 hash digest of its bytestream ("file").
_find_by_sha1
python
scanny/python-pptx
src/pptx/package.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/package.py
MIT
def slide_height(self) -> Length | None: """Height of slides in this presentation, in English Metric Units (EMU). Returns |None| if no slide width is defined. Read/write. """ sldSz = self._element.sldSz if sldSz is None: return None return sldSz.cy
Height of slides in this presentation, in English Metric Units (EMU). Returns |None| if no slide width is defined. Read/write.
slide_height
python
scanny/python-pptx
src/pptx/presentation.py
https://github.com/scanny/python-pptx/blob/master/src/pptx/presentation.py
MIT