index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
37,003 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/commands/execute_code.py | 16,18 | 1,185 | execute_python_file | 26,100 | 18,100 | """Execute code in a Docker container"""
import os
import subprocess
from pathlib import Path
import docker
from docker.errors import ImageNotFound
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger
CFG = Config()
@command("execute_python_file", "Execute ... | """Execute code in a Docker container"""
import os
import subprocess
from pathlib import Path
import docker
from docker.errors import ImageNotFound
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger
CFG = Config()
@command("execute_python_file", "Execute ... | logger.info(f"Executing file '{filename}'")
if not filename.endswith(".py"):
return "Error: Invalid file type. Only .py files are allowed."
if not os.path.isfile(filename):
return f"Error: File '{filename}' does not exist."
if we_are_running_in_a_docker_container():
result = s... | """Execute a Python file in a Docker container and return the output
Args:
filename (str): The name of the file to execute
Returns:
str: The output of the file
"""
logger.info(f"Executing file '{filename}'")
if not filename.endswith(".py"):
return "Error: Invalid file ... | 204 | 997 | 773 | 1,770 | """Execute code in a Docker container"""
import os
import subprocess
from pathlib import Path
import docker
from docker.errors import ImageNotFound
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger
CFG = Config()
@command("execute_python_file", "Execute ... | """Execute code in a Docker container"""
import os
import subprocess
from pathlib import Path
import docker
from docker.errors import ImageNotFound
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger
CFG = Config()
@command("execute_python_file", "Execute ... | |
37,004 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/commands/git_operations.py | 11,20 | 1,36 | clone_repository | 29,36 | 20,36 | """Git operations for autogpt"""
from git.repo import Repo
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.url_utils.validators import validate_url
CFG = Config()
@command(
"clone_repository",
"Clone Repository",
'"url": "<repository_url>", "clone_path": "<clo... | """Git operations for autogpt"""
from git.repo import Repo
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.url_utils.validators import validate_url
CFG = Config()
@command(
"clone_repository",
"Clone Repository",
'"url": "<repository_url>", "clone_path": "<clo... | split_url = url.split("//")
auth_repo_url = f"//{CFG.github_username}:{CFG.github_api_key}@".join(split_url)
try:
Repo.clone_from(url=auth_repo_url, to_path=clone_path)
return f"""Cloned {url} to {clone_path}"""
except Exception as e:
return f"Error: {str(e)}"
| """Clone a GitHub repository locally.
Args:
url (str): The URL of the repository to clone.
clone_path (str): The path to clone the repository to.
Returns:
str: The result of the clone operation.
"""
split_url = url.split("//")
auth_repo_url = f"//{CFG.github_username}:{... | 21 | 247 | 122 | 369 | """Git operations for autogpt"""
from git.repo import Repo
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.url_utils.validators import validate_url
CFG = Config()
@command(
"clone_repository",
"Clone Repository",
'"url": "<repository_url>", "clone_path": "<clo... | """Git operations for autogpt"""
from git.repo import Repo
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.url_utils.validators import validate_url
CFG = Config()
@command(
"clone_repository",
"Clone Repository",
'"url": "<repository_url>", "clone_path": "<clo... | |
37,005 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/commands/image_gen.py | 118,125 | 1,166 | generate_image_with_sd_webui | 135,166 | 125,166 | """ Image Generation Module for AutoGPT."""
import io
import uuid
from base64 import b64decode
import openai
import requests
from PIL import Image
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger
CFG = Config()
@command("generate_image", "Generate Image... | """ Image Generation Module for AutoGPT."""
import io
import uuid
from base64 import b64decode
import openai
import requests
from PIL import Image
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger
CFG = Config()
@command("generate_image", "Generate Image... | # Create a session and set the basic auth if needed
s = requests.Session()
if CFG.sd_webui_auth:
username, password = CFG.sd_webui_auth.split(":")
s.auth = (username, password or "")
# Generate the images
response = requests.post(
f"{CFG.sd_webui_url}/sdapi/v1/txt2img",
... | """Generate an image with Stable Diffusion webui.
Args:
prompt (str): The prompt to use
filename (str): The filename to save the image to
size (int, optional): The size of the image. Defaults to 256.
negative_prompt (str, optional): The negative prompt to use. Defaults to "".
... | 79 | 1,276 | 339 | 1,615 | """ Image Generation Module for AutoGPT."""
import io
import uuid
from base64 import b64decode
import openai
import requests
from PIL import Image
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger
CFG = Config()
@command("generate_image", "Generate Image... | """ Image Generation Module for AutoGPT."""
import io
import uuid
from base64 import b64decode
import openai
import requests
from PIL import Image
from autogpt.commands.command import command
from autogpt.config import Config
from autogpt.logs import logger
CFG = Config()
@command("generate_image", "Generate Image... | |
37,006 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/commands/improve_code.py | 9,15 | 1,36 | improve_code | 25,36 | 15,36 | from __future__ import annotations
import json
from autogpt.commands.command import command
from autogpt.llm import call_ai_function
@command(
"improve_code",
"Get Improved Code",
'"suggestions": "<list_of_suggestions>", "code": "<full_code_string>"',
)
def improve_code(suggestions: list[str], code: str... | from __future__ import annotations
import json
from autogpt.commands.command import command
from autogpt.llm import call_ai_function
@command(
"improve_code",
"Get Improved Code",
'"suggestions": "<list_of_suggestions>", "code": "<full_code_string>"',
)
def improve_code(suggestions: list[str], code: str... |
function_string = (
"def generate_improved_code(suggestions: list[str], code: str) -> str:"
)
args = [json.dumps(suggestions), code]
description_string = (
"Improves the provided code based on the suggestions"
" provided, making no other changes."
)
return call_ai_funct... | """
A function that takes in code and suggestions and returns a response from create
chat completion api call.
Parameters:
suggestions (list): A list of suggestions around what needs to be improved.
code (str): Code to be improved.
Returns:
A result string from create chat... | 37 | 206 | 117 | 323 | from __future__ import annotations
import json
from autogpt.commands.command import command
from autogpt.llm import call_ai_function
@command(
"improve_code",
"Get Improved Code",
'"suggestions": "<list_of_suggestions>", "code": "<full_code_string>"',
)
def improve_code(suggestions: list[str], code: str... | from __future__ import annotations
import json
from autogpt.commands.command import command
from autogpt.llm import call_ai_function
@command(
"improve_code",
"Get Improved Code",
'"suggestions": "<list_of_suggestions>", "code": "<full_code_string>"',
)
def improve_code(suggestions: list[str], code: str... | |
37,007 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/commands/times.py | 4,5 | 1,11 | get_datetime | 10,11 | 5,11 | from datetime import datetime
def get_datetime() -> str:
FILL_FUNC_BODY | from datetime import datetime
def get_datetime() -> str:
"""Return the current date and time
Returns:
str: The current date and time
"""
FILL_FUNC_BODY | return "Current date and time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
| """Return the current date and time
Returns:
str: The current date and time
"""
return "Current date and time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
| 9 | 53 | 36 | 89 | from datetime import datetime
def get_datetime() -> str:
FILL_FUNC_BODY | from datetime import datetime
def get_datetime() -> str:
"""Return the current date and time
Returns:
str: The current date and time
"""
FILL_FUNC_BODY | |
37,008 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/commands/web_playwright.py | 17,18 | 1,83 | scrape_text | 26,52 | 18,52 | """Web scraping commands using Playwright"""
from __future__ import annotations
from autogpt.logs import logger
try:
from playwright.sync_api import sync_playwright
except ImportError:
logger.info(
"Playwright not installed. Please install it with 'pip install playwright' to use."
)
from bs4 impor... | """Web scraping commands using Playwright"""
from __future__ import annotations
from autogpt.logs import logger
try:
from playwright.sync_api import sync_playwright
except ImportError:
logger.info(
"Playwright not installed. Please install it with 'pip install playwright' to use."
)
from bs4 impor... | with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
try:
page.goto(url)
html_content = page.content()
soup = BeautifulSoup(html_content, "html.parser")
for script in soup(["script", "style"]):
... | """Scrape text from a webpage
Args:
url (str): The URL to scrape text from
Returns:
str: The scraped text
"""
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
try:
page.goto(url)
html_content = pag... | 68 | 431 | 233 | 664 | """Web scraping commands using Playwright"""
from __future__ import annotations
from autogpt.logs import logger
try:
from playwright.sync_api import sync_playwright
except ImportError:
logger.info(
"Playwright not installed. Please install it with 'pip install playwright' to use."
)
from bs4 impor... | """Web scraping commands using Playwright"""
from __future__ import annotations
from autogpt.logs import logger
try:
from playwright.sync_api import sync_playwright
except ImportError:
logger.info(
"Playwright not installed. Please install it with 'pip install playwright' to use."
)
from bs4 impor... | |
37,009 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/commands/web_requests.py | 53,54 | 1,113 | scrape_text | 62,81 | 54,81 | """Browse a webpage and summarize it using the LLM model"""
from __future__ import annotations
import requests
from bs4 import BeautifulSoup
from requests import Response
from autogpt.config import Config
from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
from autogpt.url_utils.validators impor... | """Browse a webpage and summarize it using the LLM model"""
from __future__ import annotations
import requests
from bs4 import BeautifulSoup
from requests import Response
from autogpt.config import Config
from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
from autogpt.url_utils.validators impor... | response, error_message = get_response(url)
if error_message:
return error_message
if not response:
return "Error: Could not get response"
soup = BeautifulSoup(response.text, "html.parser")
for script in soup(["script", "style"]):
script.extract()
text = soup.get_text(... | """Scrape text from a webpage
Args:
url (str): The URL to scrape text from
Returns:
str: The scraped text
"""
response, error_message = get_response(url)
if error_message:
return error_message
if not response:
return "Error: Could not get response"
soup... | 60 | 773 | 182 | 955 | """Browse a webpage and summarize it using the LLM model"""
from __future__ import annotations
import requests
from bs4 import BeautifulSoup
from requests import Response
from autogpt.config import Config
from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
from autogpt.url_utils.validators impor... | """Browse a webpage and summarize it using the LLM model"""
from __future__ import annotations
import requests
from bs4 import BeautifulSoup
from requests import Response
from autogpt.config import Config
from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
from autogpt.url_utils.validators impor... | |
37,010 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/commands/web_selenium.py | 31,38 | 1,184 | browse_website | 47,66 | 38,66 | """Selenium web scraping module."""
from __future__ import annotations
import logging
from pathlib import Path
from sys import platform
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options as Chrome... | """Selenium web scraping module."""
from __future__ import annotations
import logging
from pathlib import Path
from sys import platform
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options as Chrome... | try:
driver, text = scrape_text_with_selenium(url)
except WebDriverException as e:
# These errors are often quite long and include lots of context.
# Just grab the first line.
msg = e.msg.split("\n")[0]
return f"Error: {msg}", None
add_header(driver)
summary_text... | """Browse a website and return the answer and links to the user
Args:
url (str): The url of the website to browse
question (str): The question asked by the user
Returns:
Tuple[str, WebDriver]: The answer and links to the user and the webdriver
"""
try:
driver, text ... | 69 | 1,641 | 218 | 1,859 | """Selenium web scraping module."""
from __future__ import annotations
import logging
from pathlib import Path
from sys import platform
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options as Chrome... | """Selenium web scraping module."""
from __future__ import annotations
import logging
from pathlib import Path
from sys import platform
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options as Chrome... | |
37,011 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/commands/write_tests.py | 10,16 | 1,38 | write_tests | 27,38 | 16,38 | """A module that contains a function to generate test cases for the submitted code."""
from __future__ import annotations
import json
from autogpt.commands.command import command
from autogpt.llm import call_ai_function
@command(
"write_tests",
"Write Tests",
'"code": "<full_code_string>", "focus": "<li... | """A module that contains a function to generate test cases for the submitted code."""
from __future__ import annotations
import json
from autogpt.commands.command import command
from autogpt.llm import call_ai_function
@command(
"write_tests",
"Write Tests",
'"code": "<full_code_string>", "focus": "<li... |
function_string = (
"def create_test_cases(code: str, focus: Optional[str] = None) -> str:"
)
args = [code, json.dumps(focus)]
description_string = (
"Generates test cases for the existing code, focusing on"
" specific areas if required."
)
return call_ai_function(funct... | """
A function that takes in code and focus topics and returns a response from create
chat completion api call.
Parameters:
focus (list): A list of suggestions around what needs to be improved.
code (str): Code for test cases to be generated against.
Returns:
A result stri... | 39 | 231 | 116 | 347 | """A module that contains a function to generate test cases for the submitted code."""
from __future__ import annotations
import json
from autogpt.commands.command import command
from autogpt.llm import call_ai_function
@command(
"write_tests",
"Write Tests",
'"code": "<full_code_string>", "focus": "<li... | """A module that contains a function to generate test cases for the submitted code."""
from __future__ import annotations
import json
from autogpt.commands.command import command
from autogpt.llm import call_ai_function
@command(
"write_tests",
"Write Tests",
'"code": "<full_code_string>", "focus": "<li... | |
37,014 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/configurator.py | 13,27 | 1,135 | create_config | 43,135 | 27,135 | """Configurator module."""
import click
from colorama import Back, Fore, Style
from autogpt import utils
from autogpt.config import Config
from autogpt.logs import logger
from autogpt.memory import get_supported_memory_backends
CFG = Config()
def create_config(
continuous: bool,
continuous_limit: int,
a... | """Configurator module."""
import click
from colorama import Back, Fore, Style
from autogpt import utils
from autogpt.config import Config
from autogpt.logs import logger
from autogpt.memory import get_supported_memory_backends
CFG = Config()
def create_config(
continuous: bool,
continuous_limit: int,
a... | CFG.set_debug_mode(False)
CFG.set_continuous_mode(False)
CFG.set_speak_mode(False)
if debug:
logger.typewriter_log("Debug Mode: ", Fore.GREEN, "ENABLED")
CFG.set_debug_mode(True)
if continuous:
logger.typewriter_log("Continuous Mode: ", Fore.RED, "ENABLED")
logger.t... | """Updates the config object with the given arguments.
Args:
continuous (bool): Whether to run in continuous mode
continuous_limit (int): The number of times to run in continuous mode
ai_settings_file (str): The path to the ai_settings.yaml file
skip_reprompt (bool): Whether to ... | 228 | 431 | 1,114 | 1,545 | """Configurator module."""
import click
from colorama import Back, Fore, Style
from autogpt import utils
from autogpt.config import Config
from autogpt.logs import logger
from autogpt.memory import get_supported_memory_backends
CFG = Config()
def create_config(
continuous: bool,
continuous_limit: int,
a... | """Configurator module."""
import click
from colorama import Back, Fore, Style
from autogpt import utils
from autogpt.config import Config
from autogpt.logs import logger
from autogpt.memory import get_supported_memory_backends
CFG = Config()
def create_config(
continuous: bool,
continuous_limit: int,
a... | |
37,016 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/llm/api_manager.py | 68,69 | 11,129 | update_cost | ApiManager | 77,85 | 69,85 | class ApiManager(metaclass=Singleton):
def __init__(self):
self.total_prompt_tokens = 0
self.total_completion_tokens = 0
self.total_cost = 0
self.total_budget = 0
def reset(self):
self.total_prompt_tokens = 0
self.total_completion_tokens = 0
self.total_co... | class ApiManager(metaclass=Singleton):
def __init__(self):
self.total_prompt_tokens = 0
self.total_completion_tokens = 0
self.total_cost = 0
self.total_budget = 0
def reset(self):
self.total_prompt_tokens = 0
self.total_completion_tokens = 0
self.total_co... | self.total_prompt_tokens += prompt_tokens
self.total_completion_tokens += completion_tokens
self.total_cost += (
prompt_tokens * COSTS[model]["prompt"]
+ completion_tokens * COSTS[model]["completion"]
) / 1000
logger.debug(f"Total running cost: ${self.tota... | """
Update the total cost, prompt tokens, and completion tokens.
Args:
prompt_tokens (int): The number of tokens used in the prompt.
completion_tokens (int): The number of tokens used in the completion.
model (str): The model used for the API call.
"""
se... | 23 | 942 | 118 | 1,060 | from __future__ import annotations
import openai
from autogpt.config import Config
from autogpt.llm.modelsinfo import COSTS
from autogpt.logs import logger
from autogpt.singleton import Singleton
class ApiManager(metaclass=Singleton):
def __init__(self):
self.total_prompt_tokens = 0
self.total_c... | from __future__ import annotations
import openai
from autogpt.config import Config
from autogpt.llm.modelsinfo import COSTS
from autogpt.logs import logger
from autogpt.singleton import Singleton
class ApiManager(metaclass=Singleton):
def __init__(self):
self.total_prompt_tokens = 0
self.total_c... |
37,018 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/llm/token_counter.py | 12,15 | 1,77 | count_message_tokens | 27,64 | 15,64 | """Functions for counting the number of tokens in a message or string."""
from __future__ import annotations
from typing import List
import tiktoken
from autogpt.llm.base import Message
from autogpt.logs import logger
def count_message_tokens(
messages: List[Message], model: str = "gpt-3.5-turbo-0301"
) -> int... | """Functions for counting the number of tokens in a message or string."""
from __future__ import annotations
from typing import List
import tiktoken
from autogpt.llm.base import Message
from autogpt.logs import logger
def count_message_tokens(
messages: List[Message], model: str = "gpt-3.5-turbo-0301"
) -> int... | try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
logger.warn("Warning: model not found. Using cl100k_base encoding.")
encoding = tiktoken.get_encoding("cl100k_base")
if model == "gpt-3.5-turbo":
# !Note: gpt-3.5-turbo may change over time.
# Returni... | """
Returns the number of tokens used by a list of messages.
Args:
messages (list): A list of messages, each of which is a dictionary
containing the role and content of the message.
model (str): The name of the model to use for tokenization.
Defaults to "gpt-3.5-turb... | 152 | 365 | 574 | 939 | """Functions for counting the number of tokens in a message or string."""
from __future__ import annotations
from typing import List
import tiktoken
from autogpt.llm.base import Message
from autogpt.logs import logger
def count_message_tokens(
messages: List[Message], model: str = "gpt-3.5-turbo-0301"
) -> int... | """Functions for counting the number of tokens in a message or string."""
from __future__ import annotations
from typing import List
import tiktoken
from autogpt.llm.base import Message
from autogpt.logs import logger
def count_message_tokens(
messages: List[Message], model: str = "gpt-3.5-turbo-0301"
) -> int... | |
37,020 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/logs.py | 198,199 | 192,215 | format | AutoGptFormatter | 199,215 | 199,215 | class AutoGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
FILL_FUNC_BODY | class AutoGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
FILL_FUNC_BODY | if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title")
if hasattr(rec... | if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title")
if hasattr(rec... | 35 | 91 | 158 | 249 | """Logging module for Auto-GPT."""
import logging
import os
import random
import re
import time
from logging import LogRecord
from colorama import Fore, Style
from autogpt.singleton import Singleton
from autogpt.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in diffe... | """Logging module for Auto-GPT."""
import logging
import os
import random
import re
import time
from logging import LogRecord
from colorama import Fore, Style
from autogpt.singleton import Singleton
from autogpt.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in diffe... |
37,021 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/logs.py | 184,185 | 183,192 | emit | ConsoleHandler | 185,192 | 185,192 | class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
FILL_FUNC_BODY | class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
FILL_FUNC_BODY | msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
| msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
| 8 | 33 | 43 | 76 | """Logging module for Auto-GPT."""
import logging
import os
import random
import re
import time
from logging import LogRecord
from colorama import Fore, Style
from autogpt.singleton import Singleton
from autogpt.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in diffe... | """Logging module for Auto-GPT."""
import logging
import os
import random
import re
import time
from logging import LogRecord
from colorama import Fore, Style
from autogpt.singleton import Singleton
from autogpt.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in diffe... |
37,022 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/logs.py | 80,83 | 15,156 | typewriter_log | Logger | 83,99 | 83,99 | class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirn... | class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirn... | if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content =... | if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content =... | 33 | 1,272 | 143 | 1,415 | """Logging module for Auto-GPT."""
import logging
import os
import random
import re
import time
from logging import LogRecord
from colorama import Fore, Style
from autogpt.singleton import Singleton
from autogpt.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in diffe... | """Logging module for Auto-GPT."""
import logging
import os
import random
import re
import time
from logging import LogRecord
from colorama import Fore, Style
from autogpt.singleton import Singleton
from autogpt.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in diffe... |
37,023 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/logs.py | 162,163 | 161,183 | emit | TypingConsoleHandler | 163,183 | 163,183 | class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
FILL_FUNC_BODY | class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
FILL_FUNC_BODY | min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush... | min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush... | 56 | 31 | 226 | 257 | """Logging module for Auto-GPT."""
import logging
import os
import random
import re
import time
from logging import LogRecord
from colorama import Fore, Style
from autogpt.singleton import Singleton
from autogpt.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in diffe... | """Logging module for Auto-GPT."""
import logging
import os
import random
import re
import time
from logging import LogRecord
from colorama import Fore, Style
from autogpt.singleton import Singleton
from autogpt.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in diffe... |
37,024 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/main.py | 25,41 | 1,150 | run_auto_gpt | 41,150 | 41,150 | """The application entry point. Can be invoked by a CLI or any other front end application."""
import logging
import sys
from pathlib import Path
from colorama import Fore, Style
from autogpt.agent.agent import Agent
from autogpt.commands.command import CommandRegistry
from autogpt.config import Config, check_openai... | """The application entry point. Can be invoked by a CLI or any other front end application."""
import logging
import sys
from pathlib import Path
from colorama import Fore, Style
from autogpt.agent.agent import Agent
from autogpt.commands.command import CommandRegistry
from autogpt.config import Config, check_openai... | # Configure logging before we do anything else.
logger.set_level(logging.DEBUG if debug else logging.INFO)
logger.speak_mode = speak
cfg = Config()
# TODO: fill in llm values here
check_openai_api_key()
create_config(
continuous,
continuous_limit,
ai_settings,
... | # Configure logging before we do anything else.
logger.set_level(logging.DEBUG if debug else logging.INFO)
logger.speak_mode = speak
cfg = Config()
# TODO: fill in llm values here
check_openai_api_key()
create_config(
continuous,
continuous_limit,
ai_settings,
... | 300 | 385 | 1,444 | 1,829 | """The application entry point. Can be invoked by a CLI or any other front end application."""
import logging
import sys
from pathlib import Path
from colorama import Fore, Style
from autogpt.agent.agent import Agent
from autogpt.commands.command import CommandRegistry
from autogpt.config import Config, check_openai... | """The application entry point. Can be invoked by a CLI or any other front end application."""
import logging
import sys
from pathlib import Path
from colorama import Fore, Style
from autogpt.agent.agent import Agent
from autogpt.commands.command import CommandRegistry
from autogpt.config import Config, check_openai... | |
37,025 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/memory/local.py | 17,18 | 1,127 | create_default_embeddings | 18,21 | 18,21 | from __future__ import annotations
import dataclasses
from pathlib import Path
from typing import Any, List
import numpy as np
import orjson
from autogpt.llm import get_ada_embedding
from autogpt.memory.base import MemoryProviderSingleton
EMBED_DIM = 1536
SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIA... | from __future__ import annotations
import dataclasses
from pathlib import Path
from typing import Any, List
import numpy as np
import orjson
from autogpt.llm import get_ada_embedding
from autogpt.memory.base import MemoryProviderSingleton
EMBED_DIM = 1536
SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIA... | return np.zeros((0, EMBED_DIM)).astype(np.float32)
| return np.zeros((0, EMBED_DIM)).astype(np.float32)
| 3 | 986 | 31 | 1,017 | from __future__ import annotations
import dataclasses
from pathlib import Path
from typing import Any, List
import numpy as np
import orjson
from autogpt.llm import get_ada_embedding
from autogpt.memory.base import MemoryProviderSingleton
EMBED_DIM = 1536
SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIA... | from __future__ import annotations
import dataclasses
from pathlib import Path
from typing import Any, List
import numpy as np
import orjson
from autogpt.llm import get_ada_embedding
from autogpt.memory.base import MemoryProviderSingleton
EMBED_DIM = 1536
SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIA... | |
37,026 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/memory/local.py | 103,104 | 29,127 | get_relevant | LocalCache | 114,122 | 104,122 | class LocalCache(MemoryProviderSingleton):
"""A class that stores the memory in a local file"""
def __init__(self, cfg) -> None:
"""Initialize a class instance
Args:
cfg: Config object
Returns:
None
"""
workspace_path = Path(cfg.workspace_path)
... | class LocalCache(MemoryProviderSingleton):
"""A class that stores the memory in a local file"""
def __init__(self, cfg) -> None:
"""Initialize a class instance
Args:
cfg: Config object
Returns:
None
"""
workspace_path = Path(cfg.workspace_path)
... | embedding = get_ada_embedding(text)
scores = np.dot(self.data.embeddings, embedding)
top_k_indices = np.argsort(scores)[-k:][::-1]
return [self.data.texts[i] for i in top_k_indices]
| """ "
matrix-vector mult to find score-for-each-row-of-matrix
get indices for top-k winning scores
return texts for those indices
Args:
text: str
k: int
Returns: List[str]
"""
embedding = get_ada_embedding(text)
scores =... | 16 | 704 | 90 | 794 | from __future__ import annotations
import dataclasses
from pathlib import Path
from typing import Any, List
import numpy as np
import orjson
from autogpt.llm import get_ada_embedding
from autogpt.memory.base import MemoryProviderSingleton
EMBED_DIM = 1536
SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIA... | from __future__ import annotations
import dataclasses
from pathlib import Path
from typing import Any, List
import numpy as np
import orjson
from autogpt.llm import get_ada_embedding
from autogpt.memory.base import MemoryProviderSingleton
EMBED_DIM = 1536
SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIA... |
37,027 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/memory/no_memory.py | 56,57 | 9,74 | get_relevant | NoMemory | 67,69 | 57,69 | class NoMemory(MemoryProviderSingleton):
"""
A class that does not store any data. This is the default memory provider.
"""
def __init__(self, cfg):
"""
Initializes the NoMemory provider.
Args:
cfg: The config object.
Returns: None
"""
pass
... | class NoMemory(MemoryProviderSingleton):
"""
A class that does not store any data. This is the default memory provider.
"""
def __init__(self, cfg):
"""
Initializes the NoMemory provider.
Args:
cfg: The config object.
Returns: None
"""
pass
... | return None
| """
Returns all the data in the memory that is relevant to the given data.
NoMemory always returns None.
Args:
data: The data to compare to.
num_relevant: The number of relevant data to return.
Returns: None
"""
return None
| 2 | 424 | 7 | 431 | """A class that does not store any data. This is the default memory provider."""
from __future__ import annotations
from typing import Any
from autogpt.memory.base import MemoryProviderSingleton
class NoMemory(MemoryProviderSingleton):
"""
A class that does not store any data. This is the default memory pro... | """A class that does not store any data. This is the default memory provider."""
from __future__ import annotations
from typing import Any
from autogpt.memory.base import MemoryProviderSingleton
class NoMemory(MemoryProviderSingleton):
"""
A class that does not store any data. This is the default memory pro... |
37,028 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/memory/pinecone.py | 49,50 | 9,79 | add | PineconeMemory | 50,57 | 50,57 | class PineconeMemory(MemoryProviderSingleton):
def __init__(self, cfg):
pinecone_api_key = cfg.pinecone_api_key
pinecone_region = cfg.pinecone_region
pinecone.init(api_key=pinecone_api_key, environment=pinecone_region)
dimension = 1536
metric = "cosine"
pod_type = "p1... | class PineconeMemory(MemoryProviderSingleton):
def __init__(self, cfg):
pinecone_api_key = cfg.pinecone_api_key
pinecone_region = cfg.pinecone_region
pinecone.init(api_key=pinecone_api_key, environment=pinecone_region)
dimension = 1536
metric = "cosine"
pod_type = "p1... | vector = get_ada_embedding(data)
# no metadata here. We may wish to change that long term.
self.index.upsert([(str(self.vec_num), vector, {"raw_text": data})])
_text = f"Inserting data into memory at index: {self.vec_num}:\n data: {data}"
self.vec_num += 1
return _text
| vector = get_ada_embedding(data)
# no metadata here. We may wish to change that long term.
self.index.upsert([(str(self.vec_num), vector, {"raw_text": data})])
_text = f"Inserting data into memory at index: {self.vec_num}:\n data: {data}"
self.vec_num += 1
return _text
| 35 | 744 | 108 | 852 | import pinecone
from colorama import Fore, Style
from autogpt.llm import get_ada_embedding
from autogpt.logs import logger
from autogpt.memory.base import MemoryProviderSingleton
class PineconeMemory(MemoryProviderSingleton):
def __init__(self, cfg):
pinecone_api_key = cfg.pinecone_api_key
pineco... | import pinecone
from colorama import Fore, Style
from autogpt.llm import get_ada_embedding
from autogpt.logs import logger
from autogpt.memory.base import MemoryProviderSingleton
class PineconeMemory(MemoryProviderSingleton):
def __init__(self, cfg):
pinecone_api_key = cfg.pinecone_api_key
pineco... |
37,029 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/memory/redismem.py | 80,81 | 27,157 | add | RedisMemory | 89,104 | 81,104 | class RedisMemory(MemoryProviderSingleton):
def __init__(self, cfg):
"""
Initializes the Redis memory provider.
Args:
cfg: The config object.
Returns: None
"""
redis_host = cfg.redis_host
redis_port = cfg.redis_port
redis_password = cfg.r... | class RedisMemory(MemoryProviderSingleton):
def __init__(self, cfg):
"""
Initializes the Redis memory provider.
Args:
cfg: The config object.
Returns: None
"""
redis_host = cfg.redis_host
redis_port = cfg.redis_port
redis_password = cfg.r... | if "Command Error:" in data:
return ""
vector = get_ada_embedding(data)
vector = np.array(vector).astype(np.float32).tobytes()
data_dict = {b"data": data, "embedding": vector}
pipe = self.redis.pipeline()
pipe.hset(f"{self.cfg.memory_index}:{self.vec_num}", ma... | """
Adds a data point to the memory.
Args:
data: The data to add.
Returns: Message indicating that the data has been added.
"""
if "Command Error:" in data:
return ""
vector = get_ada_embedding(data)
vector = np.array(vector).asty... | 45 | 1,118 | 213 | 1,331 | """Redis memory provider."""
from __future__ import annotations
from typing import Any
import numpy as np
import redis
from colorama import Fore, Style
from redis.commands.search.field import TextField, VectorField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search... | """Redis memory provider."""
from __future__ import annotations
from typing import Any
import numpy as np
import redis
from colorama import Fore, Style
from redis.commands.search.field import TextField, VectorField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search... |
37,030 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/memory_management/store_memory.py | 22,25 | 1,34 | save_memory_trimmed_from_context_window | 25,34 | 25,34 | from autogpt.json_utils.utilities import (
LLM_DEFAULT_RESPONSE_FORMAT,
is_string_valid_json,
)
from autogpt.logs import logger
def format_memory(assistant_reply, next_message_content):
# the next_message_content is a variable to stores either the user_input or the command following the assistant_reply
... | from autogpt.json_utils.utilities import (
LLM_DEFAULT_RESPONSE_FORMAT,
is_string_valid_json,
)
from autogpt.logs import logger
def format_memory(assistant_reply, next_message_content):
# the next_message_content is a variable to stores either the user_input or the command following the assistant_reply
... | while next_message_to_add_index >= 0:
message_content = full_message_history[next_message_to_add_index]["content"]
if is_string_valid_json(message_content, LLM_DEFAULT_RESPONSE_FORMAT):
next_message = full_message_history[next_message_to_add_index + 1]
memory_to_add = format_... | while next_message_to_add_index >= 0:
message_content = full_message_history[next_message_to_add_index]["content"]
if is_string_valid_json(message_content, LLM_DEFAULT_RESPONSE_FORMAT):
next_message = full_message_history[next_message_to_add_index + 1]
memory_to_add = format_... | 28 | 255 | 174 | 429 | from autogpt.json_utils.utilities import (
LLM_DEFAULT_RESPONSE_FORMAT,
is_string_valid_json,
)
from autogpt.logs import logger
def format_memory(assistant_reply, next_message_content):
# the next_message_content is a variable to stores either the user_input or the command following the assistant_reply
... | from autogpt.json_utils.utilities import (
LLM_DEFAULT_RESPONSE_FORMAT,
is_string_valid_json,
)
from autogpt.logs import logger
def format_memory(assistant_reply, next_message_content):
# the next_message_content is a variable to stores either the user_input or the command following the assistant_reply
... | |
37,031 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/memory_management/summary_memory.py | 11,16 | 1,122 | get_newly_trimmed_messages | 29,48 | 16,48 | import copy
import json
from typing import Dict, List, Tuple
from autogpt.config import Config
from autogpt.llm.llm_utils import create_chat_completion
cfg = Config()
def get_newly_trimmed_messages(
full_message_history: List[Dict[str, str]],
current_context: List[Dict[str, str]],
last_memory_index: int... | import copy
import json
from typing import Dict, List, Tuple
from autogpt.config import Config
from autogpt.llm.llm_utils import create_chat_completion
cfg = Config()
def get_newly_trimmed_messages(
full_message_history: List[Dict[str, str]],
current_context: List[Dict[str, str]],
last_memory_index: int... | # Select messages in full_message_history with an index higher than last_memory_index
new_messages = [
msg for i, msg in enumerate(full_message_history) if i > last_memory_index
]
# Remove messages that are already present in current_context
new_messages_not_in_context = [
msg for m... | """
This function returns a list of dictionaries contained in full_message_history
with an index higher than prev_index that are absent from current_context.
Args:
full_message_history (list): A list of dictionaries representing the full message history.
current_context (list): A list o... | 71 | 1,026 | 212 | 1,238 | import copy
import json
from typing import Dict, List, Tuple
from autogpt.config import Config
from autogpt.llm.llm_utils import create_chat_completion
cfg = Config()
def get_newly_trimmed_messages(
full_message_history: List[Dict[str, str]],
current_context: List[Dict[str, str]],
last_memory_index: int... | import copy
import json
from typing import Dict, List, Tuple
from autogpt.config import Config
from autogpt.llm.llm_utils import create_chat_completion
cfg = Config()
def get_newly_trimmed_messages(
full_message_history: List[Dict[str, str]],
current_context: List[Dict[str, str]],
last_memory_index: int... | |
37,032 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/models/base_open_ai_plugin.py | 156,157 | 14,200 | can_handle_post_command | BaseOpenAIPlugin | 161,163 | 157,163 | class BaseOpenAIPlugin(AutoGPTPluginTemplate):
"""
This is a BaseOpenAIPlugin class for generating Auto-GPT plugins.
"""
def __init__(self, manifests_specs_clients: dict):
# super().__init__()
self._name = manifests_specs_clients["manifest"]["name_for_model"]
self._version = man... | class BaseOpenAIPlugin(AutoGPTPluginTemplate):
"""
This is a BaseOpenAIPlugin class for generating Auto-GPT plugins.
"""
def __init__(self, manifests_specs_clients: dict):
# super().__init__()
self._name = manifests_specs_clients["manifest"]["name_for_model"]
self._version = man... | return False
| """This method is called to check that the plugin can
handle the post_command method.
Returns:
bool: True if the plugin can handle the post_command method."""
return False
| 2 | 1,787 | 7 | 1,794 | """Handles loading of plugins."""
from typing import Any, Dict, List, Optional, Tuple, TypedDict, TypeVar
from auto_gpt_plugin_template import AutoGPTPluginTemplate
PromptGenerator = TypeVar("PromptGenerator")
class Message(TypedDict):
role: str
content: str
class BaseOpenAIPlugin(AutoGPTPluginTemplate):
... | """Handles loading of plugins."""
from typing import Any, Dict, List, Optional, Tuple, TypedDict, TypeVar
from auto_gpt_plugin_template import AutoGPTPluginTemplate
PromptGenerator = TypeVar("PromptGenerator")
class Message(TypedDict):
role: str
content: str
class BaseOpenAIPlugin(AutoGPTPluginTemplate):
... |
37,033 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/processing/html.py | 8,9 | 1,34 | extract_hyperlinks | 18,24 | 9,24 | """HTML processing functions"""
from __future__ import annotations
from bs4 import BeautifulSoup
from requests.compat import urljoin
def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]:
FILL_FUNC_BODYdef format_hyperlinks(hyperlinks: list[tuple[str, str]]) -> list[str]:
"""Format ... | """HTML processing functions"""
from __future__ import annotations
from bs4 import BeautifulSoup
from requests.compat import urljoin
def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]:
"""Extract hyperlinks from a BeautifulSoup object
Args:
soup (BeautifulSoup): The ... | return [
(link.text, urljoin(base_url, link["href"]))
for link in soup.find_all("a", href=True)
]
| """Extract hyperlinks from a BeautifulSoup object
Args:
soup (BeautifulSoup): The BeautifulSoup object
base_url (str): The base URL
Returns:
List[Tuple[str, str]]: The extracted hyperlinks
"""
return [
(link.text, urljoin(base_url, link["href"]))
for link in... | 11 | 262 | 51 | 313 | """HTML processing functions"""
from __future__ import annotations
from bs4 import BeautifulSoup
from requests.compat import urljoin
def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]:
FILL_FUNC_BODYdef format_hyperlinks(hyperlinks: list[tuple[str, str]]) -> list[str]:
"""Format ... | """HTML processing functions"""
from __future__ import annotations
from bs4 import BeautifulSoup
from requests.compat import urljoin
def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]:
"""Extract hyperlinks from a BeautifulSoup object
Args:
soup (BeautifulSoup): The ... | |
37,034 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/processing/text.py | 155,156 | 1,171 | create_message | 165,171 | 156,171 | """Text processing functions"""
from typing import Dict, Generator, Optional
import spacy
from selenium.webdriver.remote.webdriver import WebDriver
from autogpt.config import Config
from autogpt.llm import count_message_tokens, create_chat_completion
from autogpt.logs import logger
from autogpt.memory import get_memo... | """Text processing functions"""
from typing import Dict, Generator, Optional
import spacy
from selenium.webdriver.remote.webdriver import WebDriver
from autogpt.config import Config
from autogpt.llm import count_message_tokens, create_chat_completion
from autogpt.logs import logger
from autogpt.memory import get_memo... | return {
"role": "user",
"content": f'"""{chunk}""" 使用以上文本回答以下问题'
f' 问题: "{question}" -- 如果问题无法使用文本回答,'
" 请总结文本.",
}
| """Create a message for the chat completion
Args:
chunk (str): The chunk of text to summarize
question (str): The question to answer
Returns:
Dict[str, str]: The message to send to the chat completion
"""
return {
"role": "user",
"content": f'"""{chunk}""" 使... | 15 | 1,561 | 73 | 1,634 | """Text processing functions"""
from typing import Dict, Generator, Optional
import spacy
from selenium.webdriver.remote.webdriver import WebDriver
from autogpt.config import Config
from autogpt.llm import count_message_tokens, create_chat_completion
from autogpt.logs import logger
from autogpt.memory import get_memo... | """Text processing functions"""
from typing import Dict, Generator, Optional
import spacy
from selenium.webdriver.remote.webdriver import WebDriver
from autogpt.config import Config
from autogpt.llm import count_message_tokens, create_chat_completion
from autogpt.logs import logger
from autogpt.memory import get_memo... | |
37,035 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/prompts/generator.py | 45,52 | 6,156 | add_command | PromptGenerator | 63,77 | 52,77 | class PromptGenerator:
"""
A class for generating custom prompt strings based on constraints, commands,
resources, and performance evaluations.
"""
def __init__(self) -> None:
"""
Initialize the PromptGenerator object with empty lists of constraints,
commands, resour... | class PromptGenerator:
"""
A class for generating custom prompt strings based on constraints, commands,
resources, and performance evaluations.
"""
def __init__(self) -> None:
"""
Initialize the PromptGenerator object with empty lists of constraints,
commands, resour... | if args is None:
args = {}
command_args = {arg_key: arg_value for arg_key, arg_value in args.items()}
command = {
"label": command_label,
"name": command_name,
"args": command_args,
"function": function,
}
self.comman... | """
Add a command to the commands list with a label, name, and optional arguments.
Args:
command_label (str): The label of the command.
command_name (str): The name of the command.
args (dict, optional): A dictionary containing argument names and their
... | 29 | 1,332 | 111 | 1,443 | """ A module for generating custom prompt strings."""
import json
from typing import Any, Callable, Dict, List, Optional
class PromptGenerator:
"""
A class for generating custom prompt strings based on constraints, commands,
resources, and performance evaluations.
"""
def __init__(self) -> No... | """ A module for generating custom prompt strings."""
import json
from typing import Any, Callable, Dict, List, Optional
class PromptGenerator:
"""
A class for generating custom prompt strings based on constraints, commands,
resources, and performance evaluations.
"""
def __init__(self) -> No... |
37,036 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/speech/base.py | 24,25 | 8,51 | say | VoiceBase | 32,35 | 25,35 | class VoiceBase(AbstractSingleton):
"""
Base class for all voice classes.
"""
def __init__(self):
"""
Initialize the voice class.
"""
self._url = None
self._headers = None
self._api_key = None
self._voices = []
self._mutex = Lock()
... | class VoiceBase(AbstractSingleton):
"""
Base class for all voice classes.
"""
def __init__(self):
"""
Initialize the voice class.
"""
self._url = None
self._headers = None
self._api_key = None
self._voices = []
self._mutex = Lock()
... | with self._mutex:
return self._speech(text, voice_index)
| """
Say the given text.
Args:
text (str): The text to say.
voice_index (int): The index of the voice to use.
"""
with self._mutex:
return self._speech(text, voice_index)
| 5 | 282 | 26 | 308 | """Base class for all voice classes."""
import abc
from threading import Lock
from autogpt.singleton import AbstractSingleton
class VoiceBase(AbstractSingleton):
"""
Base class for all voice classes.
"""
def __init__(self):
"""
Initialize the voice class.
"""
self._ur... | """Base class for all voice classes."""
import abc
from threading import Lock
from autogpt.singleton import AbstractSingleton
class VoiceBase(AbstractSingleton):
"""
Base class for all voice classes.
"""
def __init__(self):
"""
Initialize the voice class.
"""
self._ur... |
37,037 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/speech/brian.py | 17,18 | 10,44 | _speech | BrianSpeech | 26,44 | 18,44 | class BrianSpeech(VoiceBase):
"""Brian speech module for autogpt"""
def _setup(self) -> None:
"""Setup the voices, API key, etc."""
pass
def _speech(self, text: str, _: int = 0) -> bool:
FILL_FUNC_BODY | class BrianSpeech(VoiceBase):
"""Brian speech module for autogpt"""
def _setup(self) -> None:
"""Setup the voices, API key, etc."""
pass
def _speech(self, text: str, _: int = 0) -> bool:
"""Speak text using Brian with the streamelements API
Args:
text (str): Th... | tts_url = (
f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}"
)
response = requests.get(tts_url)
if response.status_code == 200:
with open("speech.mp3", "wb") as f:
f.write(response.content)
playsound("speech.mp... | """Speak text using Brian with the streamelements API
Args:
text (str): The text to speak
Returns:
bool: True if the request was successful, False otherwise
"""
tts_url = (
f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={te... | 38 | 135 | 193 | 328 | import logging
import os
import requests
from playsound import playsound
from autogpt.speech.base import VoiceBase
class BrianSpeech(VoiceBase):
"""Brian speech module for autogpt"""
def _setup(self) -> None:
"""Setup the voices, API key, etc."""
pass
def _speech(self, text: str, _: in... | import logging
import os
import requests
from playsound import playsound
from autogpt.speech.base import VoiceBase
class BrianSpeech(VoiceBase):
"""Brian speech module for autogpt"""
def _setup(self) -> None:
"""Setup the voices, API key, etc."""
pass
def _speech(self, text: str, _: in... |
37,038 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/speech/eleven_labs.py | 16,17 | 13,89 | _setup | ElevenLabsSpeech | 22,48 | 17,48 | class ElevenLabsSpeech(VoiceBase):
"""ElevenLabs speech class"""
def _setup(self) -> None:
FILL_FUNC_BODY def _use_custom_voice(self, voice, voice_index) -> None:
"""Use a custom voice if provided and not a placeholder
Args:
voice (str): The voice ID
voice_index (int... | class ElevenLabsSpeech(VoiceBase):
"""ElevenLabs speech class"""
def _setup(self) -> None:
"""Set up the voices, API key, etc.
Returns:
None: None
"""
FILL_FUNC_BODY def _use_custom_voice(self, voice, voice_index) -> None:
"""Use a custom voice if provided and no... |
cfg = Config()
default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"]
voice_options = {
"Rachel": "21m00Tcm4TlvDq8ikWAM",
"Domi": "AZnzlk1XvdvUeBnXmlld",
"Bella": "EXAVITQu4vr4xnSDxMaL",
"Antoni": "ErXwobaYiN019PkySvjV",
"El... | """Set up the voices, API key, etc.
Returns:
None: None
"""
cfg = Config()
default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"]
voice_options = {
"Rachel": "21m00Tcm4TlvDq8ikWAM",
"Domi": "AZnzlk1XvdvUeBnXmlld",
... | 58 | 481 | 514 | 995 | """ElevenLabs speech module"""
import os
import requests
from playsound import playsound
from autogpt.config import Config
from autogpt.speech.base import VoiceBase
PLACEHOLDERS = {"your-voice-id"}
class ElevenLabsSpeech(VoiceBase):
"""ElevenLabs speech class"""
def _setup(self) -> None:
FILL_FUNC_BODY ... | """ElevenLabs speech module"""
import os
import requests
from playsound import playsound
from autogpt.config import Config
from autogpt.speech.base import VoiceBase
PLACEHOLDERS = {"your-voice-id"}
class ElevenLabsSpeech(VoiceBase):
"""ElevenLabs speech class"""
def _setup(self) -> None:
"""Set up... |
37,039 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/speech/gtts.py | 16,17 | 10,23 | _speech | GTTSVoice | 18,23 | 17,23 | class GTTSVoice(VoiceBase):
"""GTTS Voice."""
def _setup(self) -> None:
pass
def _speech(self, text: str, _: int = 0) -> bool:
FILL_FUNC_BODY | class GTTSVoice(VoiceBase):
"""GTTS Voice."""
def _setup(self) -> None:
pass
def _speech(self, text: str, _: int = 0) -> bool:
"""Play the given text."""
FILL_FUNC_BODY | tts = gtts.gTTS(text)
tts.save("speech.mp3")
playsound("speech.mp3", True)
os.remove("speech.mp3")
return True
| """Play the given text."""
tts = gtts.gTTS(text)
tts.save("speech.mp3")
playsound("speech.mp3", True)
os.remove("speech.mp3")
return True
| 9 | 77 | 62 | 139 | """ GTTS Voice. """
import os
import gtts
from playsound import playsound
from autogpt.speech.base import VoiceBase
class GTTSVoice(VoiceBase):
"""GTTS Voice."""
def _setup(self) -> None:
pass
def _speech(self, text: str, _: int = 0) -> bool:
FILL_FUNC_BODY | """ GTTS Voice. """
import os
import gtts
from playsound import playsound
from autogpt.speech.base import VoiceBase
class GTTSVoice(VoiceBase):
"""GTTS Voice."""
def _setup(self) -> None:
pass
def _speech(self, text: str, _: int = 0) -> bool:
"""Play the given text."""
FILL_FUNC_BODY |
37,040 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/speech/macos_tts.py | 13,14 | 7,22 | _speech | MacOSTTS | 15,22 | 14,22 | class MacOSTTS(VoiceBase):
"""MacOS TTS Voice."""
def _setup(self) -> None:
pass
def _speech(self, text: str, voice_index: int = 0) -> bool:
FILL_FUNC_BODY | class MacOSTTS(VoiceBase):
"""MacOS TTS Voice."""
def _setup(self) -> None:
pass
def _speech(self, text: str, voice_index: int = 0) -> bool:
"""Play the given text."""
FILL_FUNC_BODY | if voice_index == 0:
os.system(f'say "{text}"')
elif voice_index == 1:
os.system(f'say -v "Ava (Premium)" "{text}"')
else:
os.system(f'say -v Samantha "{text}"')
return True
| """Play the given text."""
if voice_index == 0:
os.system(f'say "{text}"')
elif voice_index == 1:
os.system(f'say -v "Ava (Premium)" "{text}"')
else:
os.system(f'say -v Samantha "{text}"')
return True
| 22 | 80 | 89 | 169 | """ MacOS TTS Voice. """
import os
from autogpt.speech.base import VoiceBase
class MacOSTTS(VoiceBase):
"""MacOS TTS Voice."""
def _setup(self) -> None:
pass
def _speech(self, text: str, voice_index: int = 0) -> bool:
FILL_FUNC_BODY | """ MacOS TTS Voice. """
import os
from autogpt.speech.base import VoiceBase
class MacOSTTS(VoiceBase):
"""MacOS TTS Voice."""
def _setup(self) -> None:
pass
def _speech(self, text: str, voice_index: int = 0) -> bool:
"""Play the given text."""
FILL_FUNC_BODY |
37,041 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/speech/say.py | 17,18 | 1,47 | say_text | 19,34 | 18,34 | """ Text to speech module """
import threading
from threading import Semaphore
from autogpt.config import Config
from autogpt.speech.base import VoiceBase
from autogpt.speech.brian import BrianSpeech
from autogpt.speech.eleven_labs import ElevenLabsSpeech
from autogpt.speech.gtts import GTTSVoice
from autogpt.speech.m... | """ Text to speech module """
import threading
from threading import Semaphore
from autogpt.config import Config
from autogpt.speech.base import VoiceBase
from autogpt.speech.brian import BrianSpeech
from autogpt.speech.eleven_labs import ElevenLabsSpeech
from autogpt.speech.gtts import GTTSVoice
from autogpt.speech.m... | cfg = Config()
default_voice_engine, voice_engine = _get_voice_engine(cfg)
def speak() -> None:
success = voice_engine.say(text, voice_index)
if not success:
default_voice_engine.say(text)
_QUEUE_SEMAPHORE.release()
_QUEUE_SEMAPHORE.acquire(True)
thread = threa... | """Speak the given text using the given voice index"""
cfg = Config()
default_voice_engine, voice_engine = _get_voice_engine(cfg)
def speak() -> None:
success = voice_engine.say(text, voice_index)
if not success:
default_voice_engine.say(text)
_QUEUE_SEMAPHORE.relea... | 25 | 354 | 140 | 494 | """ Text to speech module """
import threading
from threading import Semaphore
from autogpt.config import Config
from autogpt.speech.base import VoiceBase
from autogpt.speech.brian import BrianSpeech
from autogpt.speech.eleven_labs import ElevenLabsSpeech
from autogpt.speech.gtts import GTTSVoice
from autogpt.speech.m... | """ Text to speech module """
import threading
from threading import Semaphore
from autogpt.config import Config
from autogpt.speech.base import VoiceBase
from autogpt.speech.brian import BrianSpeech
from autogpt.speech.eleven_labs import ElevenLabsSpeech
from autogpt.speech.gtts import GTTSVoice
from autogpt.speech.m... | |
37,042 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/spinner.py | 24,25 | 8,66 | spin | Spinner | 26,32 | 25,32 | class Spinner:
"""A simple spinner class"""
def __init__(self, message: str = "Loading...", delay: float = 0.1) -> None:
"""Initialize the spinner class
Args:
message (str): The message to display.
delay (float): The delay between each spinner update.
"""
... | class Spinner:
"""A simple spinner class"""
def __init__(self, message: str = "Loading...", delay: float = 0.1) -> None:
"""Initialize the spinner class
Args:
message (str): The message to display.
delay (float): The delay between each spinner update.
"""
... | while self.running:
sys.stdout.write(f"{next(self.spinner)} {self.message}\r")
sys.stdout.flush()
time.sleep(self.delay)
sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r")
| """Spin the spinner"""
while self.running:
sys.stdout.write(f"{next(self.spinner)} {self.message}\r")
sys.stdout.flush()
time.sleep(self.delay)
sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r")
| 12 | 509 | 87 | 596 | """A simple spinner module"""
import itertools
import sys
import threading
import time
class Spinner:
"""A simple spinner class"""
def __init__(self, message: str = "Loading...", delay: float = 0.1) -> None:
"""Initialize the spinner class
Args:
message (str): The message to disp... | """A simple spinner module"""
import itertools
import sys
import threading
import time
class Spinner:
"""A simple spinner class"""
def __init__(self, message: str = "Loading...", delay: float = 0.1) -> None:
"""Initialize the spinner class
Args:
message (str): The message to disp... |
37,043 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/url_utils/validators.py | 8,9 | 1,104 | validate_url | 11,39 | 9,39 | import functools
from typing import Any, Callable
from urllib.parse import urljoin, urlparse
from requests.compat import urljoin
def validate_url(func: Callable[..., Any]) -> Any:
FILL_FUNC_BODYdef is_valid_url(url: str) -> bool:
"""Check if the URL is valid
Args:
url (str): The URL to check
Re... | import functools
from typing import Any, Callable
from urllib.parse import urljoin, urlparse
from requests.compat import urljoin
def validate_url(func: Callable[..., Any]) -> Any:
"""The method decorator validate_url is used to validate urls for any command that requires
a url as an arugment"""
FILL_FUNC_BOD... |
@functools.wraps(func)
def wrapper(url: str, *args, **kwargs) -> Any:
"""Check if the URL is valid using a basic check, urllib check, and local file check
Args:
url (str): The URL to check
Returns:
the result of the wrapped function
Raises:
... | """The method decorator validate_url is used to validate urls for any command that requires
a url as an arugment"""
@functools.wraps(func)
def wrapper(url: str, *args, **kwargs) -> Any:
"""Check if the URL is valid using a basic check, urllib check, and local file check
Args:
... | 99 | 691 | 269 | 960 | import functools
from typing import Any, Callable
from urllib.parse import urljoin, urlparse
from requests.compat import urljoin
def validate_url(func: Callable[..., Any]) -> Any:
FILL_FUNC_BODYdef is_valid_url(url: str) -> bool:
"""Check if the URL is valid
Args:
url (str): The URL to check
Re... | import functools
from typing import Any, Callable
from urllib.parse import urljoin, urlparse
from requests.compat import urljoin
def validate_url(func: Callable[..., Any]) -> Any:
"""The method decorator validate_url is used to validate urls for any command that requires
a url as an arugment"""
FILL_FUNC_BOD... | |
37,044 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/utils.py | 103,104 | 1,155 | get_current_git_branch | 104,112 | 104,112 | import os
import re
import requests
import yaml
from colorama import Fore, Style
from git.repo import Repo
from autogpt.logs import logger
# Use readline if available (for clean_input)
try:
import readline
except ImportError:
pass
from autogpt.config import Config
def clean_input(prompt: str = "", talk=Fa... | import os
import re
import requests
import yaml
from colorama import Fore, Style
from git.repo import Repo
from autogpt.logs import logger
# Use readline if available (for clean_input)
try:
import readline
except ImportError:
pass
from autogpt.config import Config
def clean_input(prompt: str = "", talk=Fa... | try:
repo = Repo(search_parent_directories=True)
branch = repo.active_branch
return branch.name
except:
return ""
| try:
repo = Repo(search_parent_directories=True)
branch = repo.active_branch
return branch.name
except:
return ""
| 12 | 1,408 | 53 | 1,461 | import os
import re
import requests
import yaml
from colorama import Fore, Style
from git.repo import Repo
from autogpt.logs import logger
# Use readline if available (for clean_input)
try:
import readline
except ImportError:
pass
from autogpt.config import Config
def clean_input(prompt: str = "", talk=Fa... | import os
import re
import requests
import yaml
from colorama import Fore, Style
from git.repo import Repo
from autogpt.logs import logger
# Use readline if available (for clean_input)
try:
import readline
except ImportError:
pass
from autogpt.config import Config
def clean_input(prompt: str = "", talk=Fa... | |
37,045 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/autogpt/workspace/workspace.py | 76,82 | 17,138 | _sanitize_path | Workspace | 106,138 | 82,138 | class Workspace:
"""A class that represents a workspace for an AutoGPT agent."""
NULL_BYTES = ["\0", "\000", "\x00", r"\z", "\u0000", "%00"]
def __init__(self, workspace_root: str | Path, restrict_to_workspace: bool):
self._root = self._sanitize_path(workspace_root)
self._restrict_to_works... | class Workspace:
"""A class that represents a workspace for an AutoGPT agent."""
NULL_BYTES = ["\0", "\000", "\x00", r"\z", "\u0000", "%00"]
def __init__(self, workspace_root: str | Path, restrict_to_workspace: bool):
self._root = self._sanitize_path(workspace_root)
self._restrict_to_works... |
# Posix systems disallow null bytes in paths. Windows is agnostic about it.
# Do an explicit check here for all sorts of null byte representations.
for null_byte in Workspace.NULL_BYTES:
if null_byte in str(relative_path) or null_byte in str(root):
raise ValueError(... | """Resolve the relative path within the given root if possible.
Parameters
----------
relative_path
The relative path to resolve.
root
The root path to resolve the relative path within.
restrict_to_root
Whether to restrict the path to ... | 103 | 705 | 353 | 1,058 | """
=========
Workspace
=========
The workspace is a directory containing configuration and working files for an AutoGPT
agent.
"""
from __future__ import annotations
from pathlib import Path
from autogpt.logs import logger
class Workspace:
"""A class that represents a workspace for an AutoGPT agent."""
... | """
=========
Workspace
=========
The workspace is a directory containing configuration and working files for an AutoGPT
agent.
"""
from __future__ import annotations
from pathlib import Path
from autogpt.logs import logger
class Workspace:
"""A class that represents a workspace for an AutoGPT agent."""
... |
37,046 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/benchmark/benchmark_entrepreneur_gpt_with_difficult_user.py | 6,7 | 1,106 | benchmark_entrepreneur_gpt_with_difficult_user | 7,104 | 7,104 | import os
import subprocess
import sys
def benchmark_entrepreneur_gpt_with_difficult_user():
FILL_FUNC_BODYif __name__ == "__main__":
benchmark_entrepreneur_gpt_with_difficult_user()
| import os
import subprocess
import sys
def benchmark_entrepreneur_gpt_with_difficult_user():
FILL_FUNC_BODYif __name__ == "__main__":
benchmark_entrepreneur_gpt_with_difficult_user()
| # Test case to check if the write_file command can successfully write 'Hello World' to a file
# named 'hello_world.txt'.
# Read the current ai_settings.yaml file and store its content.
ai_settings = None
if os.path.exists("ai_settings.yaml"):
with open("ai_settings.yaml", "r") as f:
... | # Test case to check if the write_file command can successfully write 'Hello World' to a file
# named 'hello_world.txt'.
# Read the current ai_settings.yaml file and store its content.
ai_settings = None
if os.path.exists("ai_settings.yaml"):
with open("ai_settings.yaml", "r") as f:
... | 476 | 67 | 1,143 | 1,210 | import os
import subprocess
import sys
def benchmark_entrepreneur_gpt_with_difficult_user():
FILL_FUNC_BODYif __name__ == "__main__":
benchmark_entrepreneur_gpt_with_difficult_user()
| import os
import subprocess
import sys
def benchmark_entrepreneur_gpt_with_difficult_user():
FILL_FUNC_BODYif __name__ == "__main__":
benchmark_entrepreneur_gpt_with_difficult_user()
| |
37,047 | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH | /home/hieuvd/dung_repo/raw/stars_02/kaqijiang_Auto-GPT-ZH/Auto-GPT-ZH/scripts/install_plugin_deps.py | 8,9 | 1,36 | install_plugin_dependencies | 18,34 | 9,34 | import os
import subprocess
import sys
import zipfile
from pathlib import Path
def install_plugin_dependencies():
FILL_FUNC_BODYif __name__ == "__main__":
install_plugin_dependencies()
| import os
import subprocess
import sys
import zipfile
from pathlib import Path
def install_plugin_dependencies():
"""
Installs dependencies for all plugins in the plugins dir.
Args:
None
Returns:
None
"""
FILL_FUNC_BODYif __name__ == "__main__":
install_plugin_dependencies()
| plugins_dir = Path(os.getenv("PLUGINS_DIR", "plugins"))
for plugin in plugins_dir.glob("*.zip"):
with zipfile.ZipFile(str(plugin), "r") as zfile:
try:
basedir = zfile.namelist()[0]
basereqs = os.path.join(basedir, "requirements.txt")
extracted ... | """
Installs dependencies for all plugins in the plugins dir.
Args:
None
Returns:
None
"""
plugins_dir = Path(os.getenv("PLUGINS_DIR", "plugins"))
for plugin in plugins_dir.glob("*.zip"):
with zipfile.ZipFile(str(plugin), "r") as zfile:
try:
... | 39 | 97 | 209 | 306 | import os
import subprocess
import sys
import zipfile
from pathlib import Path
def install_plugin_dependencies():
FILL_FUNC_BODYif __name__ == "__main__":
install_plugin_dependencies()
| import os
import subprocess
import sys
import zipfile
from pathlib import Path
def install_plugin_dependencies():
"""
Installs dependencies for all plugins in the plugins dir.
Args:
None
Returns:
None
"""
FILL_FUNC_BODYif __name__ == "__main__":
install_plugin_dependencies()
| |
37,417 | /home/hieuvd/dung_repo/raw/stars_02/lucasjinreal_weibo_terminater/weibo_terminater | /home/hieuvd/dung_repo/raw/stars_02/lucasjinreal_weibo_terminater/weibo_terminater/utils/string.py | 21,22 | 1,36 | is_valid_id | 22,29 | 22,29 | # -*- coding: utf-8 -*-
# file: string.py
# author: JinTian
# time: 17/04/2017 7:06 PM
# Copyright 2017 JinTian. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# h... | # -*- coding: utf-8 -*-
# file: string.py
# author: JinTian
# time: 17/04/2017 7:06 PM
# Copyright 2017 JinTian. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# h... | try:
a = float(s)
return True
except ValueError as e:
return False
| try:
a = float(s)
return True
except ValueError as e:
return False
| 12 | 273 | 37 | 310 | # -*- coding: utf-8 -*-
# file: string.py
# author: JinTian
# time: 17/04/2017 7:06 PM
# Copyright 2017 JinTian. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# h... | # -*- coding: utf-8 -*-
# file: string.py
# author: JinTian
# time: 17/04/2017 7:06 PM
# Copyright 2017 JinTian. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# h... | |
37,475 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/action/column_group.py | 25,26 | 1,73 | column_group | 26,73 | 26,73 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | recommendation = {
"action": "Column Groups",
"description": "Shows charts of possible visualizations with respect to the column-wise index.",
"long_description": 'A column index can be thought of as an extra column that indicates the values that the user is interested in. \
Lux ... | recommendation = {
"action": "Column Groups",
"description": "Shows charts of possible visualizations with respect to the column-wise index.",
"long_description": 'A column index can be thought of as an extra column that indicates the values that the user is interested in. \
Lux ... | 213 | 255 | 635 | 890 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
37,476 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/action/correlation.py | 24,25 | 1,104 | correlation | 41,93 | 25,93 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
import numpy as np
filter_specs = utils.get_filter_specs(ldf._intent)
intent = [
lux.Clause("?", data_model="measure"),
lux.Clause("?", data_model="measure"),
]
intent.extend(filter_specs)
vlist = VisList(intent, ldf)
examples = ""
if len(vlist) > 1:
measures = ... | """
Generates bivariate visualizations that represent all pairwise relationships in the data.
Parameters
----------
ldf : LuxDataFrame
LuxDataFrame with underspecified intent.
ignore_transpose: bool
Boolean flag to ignore pairs of attributes whose transpose are already ... | 193 | 530 | 619 | 1,149 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
37,477 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/action/custom.py | 22,23 | 1,81 | custom | 36,53 | 23,53 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | recommendation = {
"action": "Current Vis",
"description": "Shows the list of visualizations generated based on user specified intent",
"long_description": "Shows the list of visualizations generated based on user specified intent",
}
recommendation["collection"] = ldf.current_vis
... | """
Generates user-defined vis based on the intent.
Parameters
----------
ldf : lux.core.frame
LuxDataFrame with underspecified intent.
Returns
-------
recommendations : Dict[str,obj]
object with a collection of visualizations that result from the Distribution action.
... | 52 | 606 | 170 | 776 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
37,478 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/action/default.py | 1,2 | 1,30 | register_default_actions | 2,30 | 2,30 | def register_default_actions():
FILL_FUNC_BODY | def register_default_actions():
FILL_FUNC_BODY | import lux
from lux.action.custom import custom
from lux.action.correlation import correlation
from lux.action.univariate import univariate
from lux.action.enhance import enhance
from lux.action.filter import add_filter
from lux.action.generalize import generalize
from lux.action.tempora... | import lux
from lux.action.custom import custom
from lux.action.correlation import correlation
from lux.action.univariate import univariate
from lux.action.enhance import enhance
from lux.action.filter import add_filter
from lux.action.generalize import generalize
from lux.action.tempora... | 113 | 18 | 451 | 469 | def register_default_actions():
FILL_FUNC_BODY | def register_default_actions():
FILL_FUNC_BODY | |
37,479 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/action/enhance.py | 21,22 | 1,75 | enhance | 35,75 | 22,75 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
filters = utils.get_filter_specs(ldf._intent)
# Collect variables that already exist in the intent
attr_specs = list(filter(lambda x: x.value == "" and x.attribute != "Record", ldf._intent))
fltr_str = [fltr.attribute + fltr.filter_op + str(fltr.value) for fltr in filters]
attr_str = [str(clause.at... | """
Given a set of vis, generates possible visualizations when an additional attribute is added to the current vis.
Parameters
----------
ldf : lux.core.frame
LuxDataFrame with underspecified intent.
Returns
-------
recommendations : Dict[str,obj]
object with a ... | 215 | 321 | 586 | 907 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
37,480 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/action/generalize.py | 22,23 | 1,100 | generalize | 36,100 | 23,100 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # takes in a dataObject and generates a list of new dataObjects, each with a single measure from the original object removed
# --> return list of dataObjects with corresponding interestingness scores
output = []
excluded_columns = []
attributes = list(filter(lambda x: x.value == "" and x.attribute... | """
Generates all possible visualizations when one attribute or filter from the current vis is removed.
Parameters
----------
ldf : lux.core.frame
LuxDataFrame with underspecified intent.
Returns
-------
recommendations : Dict[str,obj]
object with a collection o... | 308 | 327 | 909 | 1,236 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
37,481 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/action/row_group.py | 25,26 | 1,66 | row_group | 26,66 | 26,66 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | recommendation = {
"action": "Row Groups",
"description": "Shows charts of possible visualizations with respect to the row-wise index.",
"long_description": 'A row index can be thought of as an extra row that indicates the values that the user is interested in. \
Lux focuses on v... | recommendation = {
"action": "Row Groups",
"description": "Shows charts of possible visualizations with respect to the row-wise index.",
"long_description": 'A row index can be thought of as an extra row that indicates the values that the user is interested in. \
Lux focuses on v... | 195 | 255 | 588 | 843 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
37,482 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/action/temporal.py | 24,25 | 1,129 | temporal | 36,73 | 25,73 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | vlist = []
recommendation = {
"action": "Temporal",
"description": "Show trends over <p class='highlight-descriptor'>time-related</p> attributes.",
"long_description": "Temporal displays line charts for all attributes related to datetimes in the dataframe.",
}
for c in ldf.column... | """
Generates line charts for temporal fields at different granularities.
Parameters
----------
ldf : lux.core.frame
LuxDataFrame with underspecified intent.
Returns
-------
recommendations : Dict[str,obj]
Object with a collection of visualizations that result fro... | 142 | 1,050 | 438 | 1,488 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
37,483 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/core/frame.py | 869,871 | 864,878 | _constructor_sliced | LuxDataFrame | 871,878 | 871,878 | class LuxDataFrame(LuxDataFrameMixin, pd.DataFrame):
@property
def _constructor(self):
return LuxDataFrame
@property
def _constructor_sliced(self):
FILL_FUNC_BODY | class LuxDataFrame(LuxDataFrameMixin, pd.DataFrame):
@property
def _constructor(self):
return LuxDataFrame
@property
def _constructor_sliced(self):
FILL_FUNC_BODY | def f(*args, **kwargs):
s = LuxSeries(*args, **kwargs)
for attr in self._metadata: # propagate metadata
s.__dict__[attr] = getattr(self, attr, None)
return s
return f
| def f(*args, **kwargs):
s = LuxSeries(*args, **kwargs)
for attr in self._metadata: # propagate metadata
s.__dict__[attr] = getattr(self, attr, None)
return s
return f
| 23 | 64 | 71 | 135 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,485 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/core/groupby.py | 39,40 | 4,81 | _cython_agg_general | LuxGroupByMixin | 40,45 | 40,45 | class LuxGroupByMixin:
_metadata = [
"_intent",
"_inferred_intent",
"_data_type",
"unique_values",
"cardinality",
"_rec_info",
"_min_max",
"_current_vis",
"_widget",
"_recommendation",
"_prev",
"_history",
"_save... | class LuxGroupByMixin:
_metadata = [
"_intent",
"_inferred_intent",
"_data_type",
"unique_values",
"cardinality",
"_rec_info",
"_min_max",
"_current_vis",
"_widget",
"_recommendation",
"_prev",
"_history",
"_save... | ret_val = super()._cython_agg_general(*args, **kwargs)
for attr in self._metadata:
ret_val.__dict__[attr] = getattr(self, attr, None)
return ret_val
| ret_val = super()._cython_agg_general(*args, **kwargs)
for attr in self._metadata:
ret_val.__dict__[attr] = getattr(self, attr, None)
return ret_val
| 15 | 746 | 63 | 809 | import pandas as pd
class LuxGroupByMixin:
_metadata = [
"_intent",
"_inferred_intent",
"_data_type",
"unique_values",
"cardinality",
"_rec_info",
"_min_max",
"_current_vis",
"_widget",
"_recommendation",
"_prev",
"_hi... | import pandas as pd
class LuxGroupByMixin:
_metadata = [
"_intent",
"_inferred_intent",
"_data_type",
"unique_values",
"cardinality",
"_rec_info",
"_min_max",
"_current_vis",
"_widget",
"_recommendation",
"_prev",
"_hi... |
37,486 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/core/series.py | 250,252 | 245,266 | _constructor_expanddim | LuxSeries | 252,266 | 252,266 | class LuxSeries(LuxSeriesMixin, pd.Series):
@property
def _constructor(self):
return LuxSeries
@property
def _constructor_expanddim(self):
FILL_FUNC_BODY | class LuxSeries(LuxSeriesMixin, pd.Series):
@property
def _constructor(self):
return LuxSeries
@property
def _constructor_expanddim(self):
FILL_FUNC_BODY | from lux.core.frame import LuxDataFrame
def f(*args, **kwargs):
df = LuxDataFrame(*args, **kwargs)
for attr in self._metadata:
# if attr in self._default_metadata:
# default = self._default_metadata[attr]
# else:
... | from lux.core.frame import LuxDataFrame
def f(*args, **kwargs):
df = LuxDataFrame(*args, **kwargs)
for attr in self._metadata:
# if attr in self._default_metadata:
# default = self._default_metadata[attr]
# else:
... | 42 | 59 | 144 | 203 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,488 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/core/sqltable.py | 121,122 | 32,207 | _ipython_display_ | LuxSQLTable | 122,207 | 122,207 | class LuxSQLTable(lux.LuxDataFrame):
"""
A subclass of Lux.LuxDataFrame that houses other variables and functions for generating visual recommendations. Does not support normal pandas functionality.
"""
# MUST register here for new properties!!
_metadata = [
"_intent",
"_inferred_in... | class LuxSQLTable(lux.LuxDataFrame):
"""
A subclass of Lux.LuxDataFrame that houses other variables and functions for generating visual recommendations. Does not support normal pandas functionality.
"""
# MUST register here for new properties!!
_metadata = [
"_intent",
"_inferred_in... | from IPython.display import HTML, Markdown, display
from IPython.display import clear_output
import ipywidgets as widgets
try:
if self._pandas_only:
display(self.display_pandas())
self._pandas_only = False
if not self.index.nlevels... | from IPython.display import HTML, Markdown, display
from IPython.display import clear_output
import ipywidgets as widgets
try:
if self._pandas_only:
display(self.display_pandas())
self._pandas_only = False
if not self.index.nlevels... | 245 | 830 | 1,071 | 1,901 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,489 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/executor/Executor.py | 78,79 | 20,109 | mapping | Executor | 79,86 | 79,86 | class Executor:
"""
Abstract class for the execution engine that fetches data for a given vis on a LuxDataFrame
"""
def __init__(self):
self.name = "Executor"
def __repr__(self):
return f"<Executor>"
@staticmethod
def execute(vislist: VisList, ldf: LuxDataFrame, approx: bo... | class Executor:
"""
Abstract class for the execution engine that fetches data for a given vis on a LuxDataFrame
"""
def __init__(self):
self.name = "Executor"
def __repr__(self):
return f"<Executor>"
@staticmethod
def execute(vislist: VisList, ldf: LuxDataFrame, approx: bo... | group_map = {}
if rmap == {}:
return {}
for val in ["quantitative", "id", "nominal", "temporal", "geographical"]:
group_map[val] = list(filter(lambda x: rmap[x] == val, rmap))
return group_map
| group_map = {}
if rmap == {}:
return {}
for val in ["quantitative", "id", "nominal", "temporal", "geographical"]:
group_map[val] = list(filter(lambda x: rmap[x] == val, rmap))
return group_map
| 27 | 662 | 86 | 748 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,490 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/history/history.py | 47,48 | 19,51 | copy | History | 48,51 | 48,51 | class History:
"""
History maintains a list of past Pandas operations performed on the dataframe
Currently only supports custom overridden functions (head, tail, info, describe)
"""
def __init__(self):
self._events = []
def __getitem__(self, key):
return self._events[key]
... | class History:
"""
History maintains a list of past Pandas operations performed on the dataframe
Currently only supports custom overridden functions (head, tail, info, describe)
"""
def __init__(self):
self._events = []
def __getitem__(self, key):
return self._events[key]
... | history_copy = History()
history_copy._events.extend(self._events)
return history_copy
| history_copy = History()
history_copy._events.extend(self._events)
return history_copy
| 6 | 246 | 31 | 277 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,491 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/interestingness/similarity.py | 23,24 | 1,145 | interpolate | 38,79 | 24,79 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | if vis.get_attr_by_channel("x") and vis.get_attr_by_channel("y"):
xAxis = vis.get_attr_by_channel("x")[0].attribute
yAxis = vis.get_attr_by_channel("y")[0].attribute
if xAxis and yAxis:
yVals = vis.data[yAxis]
xVals = vis.data[xAxis]
n = length
... | """
Interpolates the vis data so that the number of data points is fixed to a constant
Parameters
----------
vis : lux.vis.Vis
vis that represents the candidate visualization
length : int
number of points a vis should have
Returns
-------
None
"""
if vis.get... | 121 | 834 | 494 | 1,328 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
37,493 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/processor/Parser.py | 26,28 | 20,117 | parse | Parser | 42,117 | 28,117 | class Parser:
"""
The parser takes in the user's input specifications (with string `description` fields),
then generates the Lux internal specification through lux.Clause.
"""
@staticmethod
def parse(intent: List[Union[Clause, str]]) -> List[Clause]:
FILL_FUNC_BODY | class Parser:
"""
The parser takes in the user's input specifications (with string `description` fields),
then generates the Lux internal specification through lux.Clause.
"""
@staticmethod
def parse(intent: List[Union[Clause, str]]) -> List[Clause]:
"""
Given the string descrip... | if type(intent) != list:
raise TypeError(
"Input intent must be a list consisting of string descriptions or lux.Clause objects."
"\nSee more at: https://lux-api.readthedocs.io/en/latest/source/guide/intent.html"
)
import re
new_context = [... | """
Given the string description from a list of input Clauses (intent),
assign the appropriate clause.attribute, clause.filter_op, and clause.value.
Parameters
----------
intent : List[Clause]
Underspecified list of lux.Clause objects.
Returns
... | 307 | 188 | 983 | 1,171 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,494 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/processor/Validator.py | 38,40 | 26,116 | validate_intent | Validator | 59,116 | 40,116 | class Validator:
"""
Contains methods for validating lux.Clause objects in the intent.
"""
def __init__(self):
self.name = "Validator"
warnings.formatwarning = lux.warning_format
def __repr__(self):
return f"<Validator>"
@staticmethod
def validate_intent(intent: Li... | class Validator:
"""
Contains methods for validating lux.Clause objects in the intent.
"""
def __init__(self):
self.name = "Validator"
warnings.formatwarning = lux.warning_format
def __repr__(self):
return f"<Validator>"
@staticmethod
def validate_intent(intent: Li... |
def validate_clause(clause):
warn_msg = ""
if not (clause.attribute == "?" or clause.value == "?" or clause.attribute == ""):
if isinstance(clause.attribute, list):
for attr in clause.attribute:
if attr not in list(ldf.columns)... | """
Validates input specifications from the user to find inconsistencies and errors.
Parameters
----------
ldf : lux.core.frame
LuxDataFrame with underspecified intent.
Returns
-------
Boolean
True if the intent passed in ... | 271 | 226 | 747 | 973 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,496 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/utils/message.py | 28,29 | 16,39 | to_html | Message | 29,39 | 29,39 | class Message:
def __init__(self):
self.messages = []
def add_unique(self, item, priority=-1):
msg = {"text": item, "priority": priority}
if msg not in self.messages:
self.messages.append(msg)
def add(self, item, priority=-1):
self.messages.append({"text": item,... | class Message:
def __init__(self):
self.messages = []
def add_unique(self, item, priority=-1):
msg = {"text": item, "priority": priority}
if msg not in self.messages:
self.messages.append(msg)
def add(self, item, priority=-1):
self.messages.append({"text": item,... | if len(self.messages) == 0:
return ""
else:
sorted_msgs = sorted(self.messages, key=lambda i: i["priority"], reverse=True)
html = "<ul>"
for msg in sorted_msgs:
msgTxt = msg["text"]
html += f"<li>{msgTxt}</li>"
h... | if len(self.messages) == 0:
return ""
else:
sorted_msgs = sorted(self.messages, key=lambda i: i["priority"], reverse=True)
html = "<ul>"
for msg in sorted_msgs:
msgTxt = msg["text"]
html += f"<li>{msgTxt}</li>"
h... | 32 | 125 | 119 | 244 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,498 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/utils/utils.py | 30,31 | 1,150 | pandas_to_lux | 31,38 | 31,38 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | from lux.core.frame import LuxDataFrame
values = df.values.tolist()
ldf = LuxDataFrame(values, columns=df.columns)
return ldf
| from lux.core.frame import LuxDataFrame
values = df.values.tolist()
ldf = LuxDataFrame(values, columns=df.columns)
return ldf
| 13 | 1,468 | 56 | 1,524 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
37,499 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vis/Clause.py | 120,121 | 18,154 | to_string | Clause | 121,129 | 121,129 | class Clause:
"""
Clause is the object representation of a single unit of the specification.
"""
def __init__(
self,
description: typing.Union[str, list] = "",
attribute: typing.Union[str, list] = "",
value: typing.Union[str, list] = "",
filter_op: str = "=",
... | class Clause:
"""
Clause is the object representation of a single unit of the specification.
"""
def __init__(
self,
description: typing.Union[str, list] = "",
attribute: typing.Union[str, list] = "",
value: typing.Union[str, list] = "",
filter_op: str = "=",
... | if isinstance(self.attribute, list):
clauseStr = "|".join(self.attribute)
elif self.value == "":
clauseStr = str(self.attribute)
else:
clauseStr = f"{self.attribute}{self.filter_op}{self.value}"
return clauseStr
| if isinstance(self.attribute, list):
clauseStr = "|".join(self.attribute)
elif self.value == "":
clauseStr = str(self.attribute)
else:
clauseStr = f"{self.attribute}{self.filter_op}{self.value}"
return clauseStr
| 19 | 1,633 | 86 | 1,719 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,501 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/altair/AltairChart.py | 91,92 | 25,146 | encode_color | AltairChart | 92,117 | 92,117 | class AltairChart:
"""
AltairChart is a representation of a chart.
Common utilities for charts that is independent of chart types should go here.
See Also
--------
altair-viz.github.io
"""
def __init__(self, vis):
self.vis = vis
self.data = vis.data
self.toolti... | class AltairChart:
"""
AltairChart is a representation of a chart.
Common utilities for charts that is independent of chart types should go here.
See Also
--------
altair-viz.github.io
"""
def __init__(self, vis):
self.vis = vis
self.data = vis.data
self.toolti... | color_attr = self.vis.get_attr_by_channel("color")
if len(color_attr) == 1:
color_attr_name = color_attr[0].attribute
color_attr_type = color_attr[0].data_type
if color_attr_type == "temporal":
timeUnit = compute_date_granularity(self.vis.data[color_at... | color_attr = self.vis.get_attr_by_channel("color")
if len(color_attr) == 1:
color_attr_name = color_attr[0].attribute
color_attr_type = color_attr[0].data_type
if color_attr_type == "temporal":
timeUnit = compute_date_granularity(self.vis.data[color_at... | 67 | 1,197 | 376 | 1,573 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,504 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/altair/Heatmap.py | 37,38 | 21,104 | initialize_chart | Heatmap | 38,104 | 38,104 | class Heatmap(AltairChart):
"""
Heatmap is a subclass of AltairChart that render as a heatmap.
All rendering properties for heatmap are set here.
See Also
--------
altair-viz.github.io
"""
def __init__(self, vis):
super().__init__(vis)
def __repr__(self):
return f"... | class Heatmap(AltairChart):
"""
Heatmap is a subclass of AltairChart that render as a heatmap.
All rendering properties for heatmap are set here.
See Also
--------
altair-viz.github.io
"""
def __init__(self, vis):
super().__init__(vis)
def __repr__(self):
return f"... | # return NotImplemented
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = str(x_attr.attribute)
y_attr_abv = str(y_attr.attribute)
if len(x_attr_abv) > 25:
x_attr_abv = x_attr.attribute[:15] + "..." + x_... | # return NotImplemented
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = str(x_attr.attribute)
y_attr_abv = str(y_attr.attribute)
if len(x_attr_abv) > 25:
x_attr_abv = x_attr.attribute[:15] + "..." + x_... | 159 | 136 | 959 | 1,095 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,505 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/altair/LineChart.py | 38,39 | 22,104 | initialize_chart | LineChart | 39,104 | 39,104 | class LineChart(AltairChart):
"""
LineChart is a subclass of AltairChart that render as a line charts.
All rendering properties for line charts are set here.
See Also
--------
altair-viz.github.io
"""
def __init__(self, dobj):
super().__init__(dobj)
def __repr__(self):
... | class LineChart(AltairChart):
"""
LineChart is a subclass of AltairChart that render as a line charts.
All rendering properties for line charts are set here.
See Also
--------
altair-viz.github.io
"""
def __init__(self, dobj):
super().__init__(dobj)
def __repr__(self):
... | self.tooltip = False # tooltip looks weird for line chart
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = str(x_attr.attribute)
y_attr_abv = str(y_attr.attribute)
if x_attr.timescale != "":
x_attr.dat... | self.tooltip = False # tooltip looks weird for line chart
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = str(x_attr.attribute)
y_attr_abv = str(y_attr.attribute)
if x_attr.timescale != "":
x_attr.dat... | 211 | 138 | 1,166 | 1,304 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,506 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/altair/ScatterChart.py | 37,38 | 21,97 | initialize_chart | ScatterChart | 38,97 | 38,97 | class ScatterChart(AltairChart):
"""
ScatterChart is a subclass of AltairChart that render as a scatter charts.
All rendering properties for scatter charts are set here.
See Also
--------
altair-viz.github.io
"""
def __init__(self, vis):
super().__init__(vis)
def __repr__(... | class ScatterChart(AltairChart):
"""
ScatterChart is a subclass of AltairChart that render as a scatter charts.
All rendering properties for scatter charts are set here.
See Also
--------
altair-viz.github.io
"""
def __init__(self, vis):
super().__init__(vis)
def __repr__(... | x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = str(x_attr.attribute)
y_attr_abv = str(y_attr.attribute)
if len(x_attr_abv) > 25:
x_attr_abv = x_attr.attribute[:15] + "..." + x_attr.attribute[-10:]
if ... | x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = str(x_attr.attribute)
y_attr_abv = str(y_attr.attribute)
if len(x_attr_abv) > 25:
x_attr_abv = x_attr.attribute[:15] + "..." + x_attr.attribute[-10:]
if ... | 150 | 140 | 907 | 1,047 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,507 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/matplotlib/BarChart.py | 44,45 | 28,144 | initialize_chart | BarChart | 45,144 | 45,144 | class BarChart(MatplotlibChart):
"""
BarChart is a subclass of MatplotlibChart that render as a bar charts.
All rendering properties for bar charts are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, dobj, fig, ax):
super().__init__(dobj, fig, ax)
def __r... | class BarChart(MatplotlibChart):
"""
BarChart is a subclass of MatplotlibChart that render as a bar charts.
All rendering properties for bar charts are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, dobj, fig, ax):
super().__init__(dobj, fig, ax)
def __r... | self.tooltip = False
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
# Deal with overlong string axes labels
x_attr_abv = str(x_attr.attribute)
y_attr_abv = str(y_attr.attribute)
label_len = lux.config.label_len
... | self.tooltip = False
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
# Deal with overlong string axes labels
x_attr_abv = str(x_attr.attribute)
y_attr_abv = str(y_attr.attribute)
label_len = lux.config.label_len
... | 291 | 142 | 1,467 | 1,609 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,508 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/matplotlib/Heatmap.py | 38,39 | 22,110 | initialize_chart | Heatmap | 39,110 | 39,110 | class Heatmap(MatplotlibChart):
"""
Heatmap is a subclass of MatplotlibChart that render as a heatmap.
All rendering properties for heatmap are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, vis, fig, ax):
super().__init__(vis, fig, ax)
def __repr__(self... | class Heatmap(MatplotlibChart):
"""
Heatmap is a subclass of MatplotlibChart that render as a heatmap.
All rendering properties for heatmap are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, vis, fig, ax):
super().__init__(vis, fig, ax)
def __repr__(self... | # return NotImplemented
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = x_attr.attribute
y_attr_abv = y_attr.attribute
if len(x_attr.attribute) > 25:
x_attr_abv = x_attr.attribute[:15] + "..." + x_attr... | # return NotImplemented
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = x_attr.attribute
y_attr_abv = y_attr.attribute
if len(x_attr.attribute) > 25:
x_attr_abv = x_attr.attribute[:15] + "..." + x_attr... | 194 | 140 | 1,077 | 1,217 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,509 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/matplotlib/Histogram.py | 37,38 | 21,86 | initialize_chart | Histogram | 38,86 | 38,86 | class Histogram(MatplotlibChart):
"""
Histogram is a subclass of AltairChart that render as a histograms.
All rendering properties for histograms are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, vis, fig, ax):
super().__init__(vis, fig, ax)
def __repr_... | class Histogram(MatplotlibChart):
"""
Histogram is a subclass of AltairChart that render as a histograms.
All rendering properties for histograms are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, vis, fig, ax):
super().__init__(vis, fig, ax)
def __repr_... | self.tooltip = False
measure = self.vis.get_attr_by_data_model("measure", exclude_record=True)[0]
msr_attr = self.vis.get_attr_by_channel(measure.channel)[0]
msr_attr_abv = msr_attr.attribute
if len(msr_attr.attribute) > 17:
msr_attr_abv = msr_attr.attribute[:10] + ... | self.tooltip = False
measure = self.vis.get_attr_by_data_model("measure", exclude_record=True)[0]
msr_attr = self.vis.get_attr_by_channel(measure.channel)[0]
msr_attr_abv = msr_attr.attribute
if len(msr_attr.attribute) > 17:
msr_attr_abv = msr_attr.attribute[:10] + ... | 144 | 141 | 662 | 803 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,510 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/matplotlib/LineChart.py | 40,41 | 24,123 | initialize_chart | LineChart | 41,123 | 41,123 | class LineChart(MatplotlibChart):
"""
LineChart is a subclass of MatplotlibChart that render as a line charts.
All rendering properties for line charts are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, dobj, fig, ax):
super().__init__(dobj, fig, ax)
def... | class LineChart(MatplotlibChart):
"""
LineChart is a subclass of MatplotlibChart that render as a line charts.
All rendering properties for line charts are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, dobj, fig, ax):
super().__init__(dobj, fig, ax)
def... | self.tooltip = False # tooltip looks weird for line chart
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = x_attr.attribute
y_attr_abv = y_attr.attribute
if len(x_attr.attribute) > 25:
x_attr_abv = x_a... | self.tooltip = False # tooltip looks weird for line chart
x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = x_attr.attribute
y_attr_abv = y_attr.attribute
if len(x_attr.attribute) > 25:
x_attr_abv = x_a... | 226 | 142 | 1,203 | 1,345 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,511 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/matplotlib/MatplotlibChart.py | 68,69 | 19,78 | add_title | MatplotlibChart | 69,76 | 69,76 | class MatplotlibChart:
"""
MatplotlibChart is a representation of a chart.
Common utilities for charts that is independent of chart types should go here.
See Also
--------
https://matplotlib.org/
"""
def __init__(self, vis, fig, ax):
self.vis = vis
self.data = vis.data... | class MatplotlibChart:
"""
MatplotlibChart is a representation of a chart.
Common utilities for charts that is independent of chart types should go here.
See Also
--------
https://matplotlib.org/
"""
def __init__(self, vis, fig, ax):
self.vis = vis
self.data = vis.data... | chart_title = self.vis.title
if chart_title:
if len(chart_title) > 25:
chart_title = chart_title[:15] + "..." + chart_title[-10:]
self.ax.set_title(chart_title)
self.code += f"ax.set_title('{chart_title}')\n"
| chart_title = self.vis.title
if chart_title:
if len(chart_title) > 25:
chart_title = chart_title[:15] + "..." + chart_title[-10:]
self.ax.set_title(chart_title)
self.code += f"ax.set_title('{chart_title}')\n"
| 20 | 444 | 99 | 543 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,512 | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux | /home/hieuvd/dung_repo/raw/stars_02/lux-org_lux/lux/lux/vislib/matplotlib/ScatterChart.py | 39,40 | 23,151 | initialize_chart | ScatterChart | 40,151 | 40,151 | class ScatterChart(MatplotlibChart):
"""
ScatterChart is a subclass of MatplotlibChart that render as a scatter charts.
All rendering properties for scatter charts are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, vis, fig, ax):
super().__init__(vis, fig, ax... | class ScatterChart(MatplotlibChart):
"""
ScatterChart is a subclass of MatplotlibChart that render as a scatter charts.
All rendering properties for scatter charts are set here.
See Also
--------
matplotlib.org
"""
def __init__(self, vis, fig, ax):
super().__init__(vis, fig, ax... | x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = x_attr.attribute
y_attr_abv = y_attr.attribute
if len(x_attr.attribute) > 25:
x_attr_abv = x_attr.attribute[:15] + "..." + x_attr.attribute[-10:]
if len(... | x_attr = self.vis.get_attr_by_channel("x")[0]
y_attr = self.vis.get_attr_by_channel("y")[0]
x_attr_abv = x_attr.attribute
y_attr_abv = y_attr.attribute
if len(x_attr.attribute) > 25:
x_attr_abv = x_attr.attribute[:15] + "..." + x_attr.attribute[-10:]
if len(... | 336 | 144 | 1,821 | 1,965 | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright 2019-2020 The Lux Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
37,683 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/arbitrage.py | 125,126 | 1,132 | main | 126,130 | 126,130 | # Copyright (C) 2013, Maxime Biais <maxime@biais.org>
import logging
import argparse
import sys
import glob
import os
import inspect
from arbitrage.arbitrer import Arbitrer
from arbitrage import public_markets
class ArbitrerCLI:
def __init__(self):
self.inject_verbose_info()
def inject_verbose_info(... | # Copyright (C) 2013, Maxime Biais <maxime@biais.org>
import logging
import argparse
import sys
import glob
import os
import inspect
from arbitrage.arbitrer import Arbitrer
from arbitrage import public_markets
class ArbitrerCLI:
def __init__(self):
self.inject_verbose_info()
def inject_verbose_info(... | cli = ArbitrerCLI()
cli.main()
| cli = ArbitrerCLI()
cli.main()
| 4 | 1,388 | 24 | 1,412 | # Copyright (C) 2013, Maxime Biais <maxime@biais.org>
import logging
import argparse
import sys
import glob
import os
import inspect
from arbitrage.arbitrer import Arbitrer
from arbitrage import public_markets
class ArbitrerCLI:
def __init__(self):
self.inject_verbose_info()
def inject_verbose_info(... | # Copyright (C) 2013, Maxime Biais <maxime@biais.org>
import logging
import argparse
import sys
import glob
import os
import inspect
from arbitrage.arbitrer import Arbitrer
from arbitrage import public_markets
class ArbitrerCLI:
def __init__(self):
self.inject_verbose_info()
def inject_verbose_info(... | |
37,684 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/arbitrage.py | 55,56 | 13,125 | generate_sample_config | ArbitrerCLI | 56,74 | 56,74 | class ArbitrerCLI:
def __init__(self):
self.inject_verbose_info()
def inject_verbose_info(self):
logging.VERBOSE = 15
logging.verbose = lambda x: logging.log(logging.VERBOSE, x)
logging.addLevelName(logging.VERBOSE, "VERBOSE")
def exec_command(self, args):
if "watch... | class ArbitrerCLI:
def __init__(self):
self.inject_verbose_info()
def inject_verbose_info(self):
logging.VERBOSE = 15
logging.verbose = lambda x: logging.log(logging.VERBOSE, x)
logging.addLevelName(logging.VERBOSE, "VERBOSE")
def exec_command(self, args):
if "watch... | markets = self.get_market_list()
markets.sort()
print("markets = [")
print('",\n'.join([' "' + i for i in markets]) + '"')
print("]")
print('observers = ["Logger"]')
print("""
refresh_rate = 60
market_expiration_time = 120 # in seconds: 2 minutes
# SafeGuards
m... | markets = self.get_market_list()
markets.sort()
print("markets = [")
print('",\n'.join([' "' + i for i in markets]) + '"')
print("]")
print('observers = ["Logger"]')
print("""
refresh_rate = 60
market_expiration_time = 120 # in seconds: 2 minutes
# SafeGuards
m... | 65 | 1,119 | 199 | 1,318 | # Copyright (C) 2013, Maxime Biais <maxime@biais.org>
import logging
import argparse
import sys
import glob
import os
import inspect
from arbitrage.arbitrer import Arbitrer
from arbitrage import public_markets
class ArbitrerCLI:
def __init__(self):
self.inject_verbose_info()
def inject_verbose_info(... | # Copyright (C) 2013, Maxime Biais <maxime@biais.org>
import logging
import argparse
import sys
import glob
import os
import inspect
from arbitrage.arbitrer import Arbitrer
from arbitrage import public_markets
class ArbitrerCLI:
def __init__(self):
self.inject_verbose_info()
def inject_verbose_info(... |
37,685 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/fiatconverter.py | 39,40 | 26,66 | change_pivot | FiatConverter | 40,45 | 40,45 | class FiatConverter:
__shared_state = {}
# Europa.eu is the official european central bank
rate_exchange_url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
def __init__(self):
self.__dict__ = self.__shared_state
self.rates = {}
self.update_delay = 60 * 60 * 6 ... | class FiatConverter:
__shared_state = {}
# Europa.eu is the official european central bank
rate_exchange_url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
def __init__(self):
self.__dict__ = self.__shared_state
self.rates = {}
self.update_delay = 60 * 60 * 6 ... | PVTEUR = 1.0 / rates[pivot]
for k in rates:
rates[k] = rates[k] * PVTEUR
return rates
| PVTEUR = 1.0 / rates[pivot]
for k in rates:
rates[k] = rates[k] * PVTEUR
return rates
| 16 | 391 | 49 | 440 | # Copyright (C) 2013-2019, Maxime Biais <maxime@bia.is>
import urllib.request
import sys
import xml.sax
import logging
import time
class XmlHandler(xml.sax.ContentHandler):
def __init__(self):
self.currentTag = ""
self.rates = {}
def startElement(self, tag, attributes):
if "currency"... | # Copyright (C) 2013-2019, Maxime Biais <maxime@bia.is>
import urllib.request
import sys
import xml.sax
import logging
import time
class XmlHandler(xml.sax.ContentHandler):
def __init__(self):
self.currentTag = ""
self.rates = {}
def startElement(self, tag, attributes):
if "currency"... |
37,686 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/fiatconverter.py | 15,16 | 10,26 | startElement | XmlHandler | 16,19 | 16,19 | class XmlHandler(xml.sax.ContentHandler):
def __init__(self):
self.currentTag = ""
self.rates = {}
def startElement(self, tag, attributes):
FILL_FUNC_BODY def endElement(self, tag):
pass
def characters(self, content):
pass
| class XmlHandler(xml.sax.ContentHandler):
def __init__(self):
self.currentTag = ""
self.rates = {}
def startElement(self, tag, attributes):
FILL_FUNC_BODY def endElement(self, tag):
pass
def characters(self, content):
pass
| if "currency" in attributes and "rate" in attributes:
self.rates[attributes["currency"]] = float(attributes["rate"])
| if "currency" in attributes and "rate" in attributes:
self.rates[attributes["currency"]] = float(attributes["rate"])
| 11 | 88 | 38 | 126 | # Copyright (C) 2013-2019, Maxime Biais <maxime@bia.is>
import urllib.request
import sys
import xml.sax
import logging
import time
class XmlHandler(xml.sax.ContentHandler):
def __init__(self):
self.currentTag = ""
self.rates = {}
def startElement(self, tag, attributes):
FILL_FUNC_BODY def... | # Copyright (C) 2013-2019, Maxime Biais <maxime@bia.is>
import urllib.request
import sys
import xml.sax
import logging
import time
class XmlHandler(xml.sax.ContentHandler):
def __init__(self):
self.currentTag = ""
self.rates = {}
def startElement(self, tag, attributes):
FILL_FUNC_BODY def... |
37,687 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/observers/detailedlogger.py | 6,18 | 5,22 | opportunity | DetailedLogger | 18,22 | 18,22 | class DetailedLogger(Observer):
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
perc,
weighted_buyprice,
weighted_sellprice,
):
FILL_FUNC_BODY | class DetailedLogger(Observer):
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
perc,
weighted_buyprice,
weighted_sellprice,
):
FILL_FUNC_BODY | logging.info(
"profit: %f USD with volume: %f BTC - buy at %.4f (%s) sell at %.4f (%s) ~%.2f%%"
% (profit, volume, buyprice, kask, sellprice, kbid, perc)
)
| logging.info(
"profit: %f USD with volume: %f BTC - buy at %.4f (%s) sell at %.4f (%s) ~%.2f%%"
% (profit, volume, buyprice, kask, sellprice, kbid, perc)
)
| 27 | 79 | 77 | 156 | import logging
from arbitrage.observers.observer import Observer
class DetailedLogger(Observer):
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
perc,
weighted_buyprice,
weighted_sellprice,
):
FILL_FUNC_BOD... | import logging
from arbitrage.observers.observer import Observer
class DetailedLogger(Observer):
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
perc,
weighted_buyprice,
weighted_sellprice,
):
FILL_FUNC_BOD... |
37,688 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/observers/historydumper.py | 16,17 | 7,37 | begin_opportunity_finder | HistoryDumper | 17,21 | 17,21 | class HistoryDumper(Observer):
out_dir = "history/"
def __init__(self):
try:
os.mkdir(self.out_dir)
except:
pass
def begin_opportunity_finder(self, depths):
FILL_FUNC_BODY def end_opportunity_finder(self):
pass
def opportunity(
self,
... | class HistoryDumper(Observer):
out_dir = "history/"
def __init__(self):
try:
os.mkdir(self.out_dir)
except:
pass
def begin_opportunity_finder(self, depths):
FILL_FUNC_BODY def end_opportunity_finder(self):
pass
def opportunity(
self,
... | filename = self.out_dir + "order-book-" + str(int(time.time())) + ".json"
fp = open(filename, "w")
json.dump(depths, fp)
| filename = self.out_dir + "order-book-" + str(int(time.time())) + ".json"
fp = open(filename, "w")
json.dump(depths, fp)
| 15 | 159 | 57 | 216 | from arbitrage.observers.observer import Observer
import json
import time
import os
class HistoryDumper(Observer):
out_dir = "history/"
def __init__(self):
try:
os.mkdir(self.out_dir)
except:
pass
def begin_opportunity_finder(self, depths):
FILL_FUNC_BODY def e... | from arbitrage.observers.observer import Observer
import json
import time
import os
class HistoryDumper(Observer):
out_dir = "history/"
def __init__(self):
try:
os.mkdir(self.out_dir)
except:
pass
def begin_opportunity_finder(self, depths):
FILL_FUNC_BODY def e... |
37,689 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/observers/logger.py | 6,18 | 5,22 | opportunity | Logger | 18,22 | 18,22 | class Logger(Observer):
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
perc,
weighted_buyprice,
weighted_sellprice,
):
FILL_FUNC_BODY | class Logger(Observer):
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
perc,
weighted_buyprice,
weighted_sellprice,
):
FILL_FUNC_BODY | logging.info(
"profit: %f USD with volume: %f BTC - buy from %s sell to %s ~%.2f%%"
% (profit, volume, kask, kbid, perc)
)
| logging.info(
"profit: %f USD with volume: %f BTC - buy from %s sell to %s ~%.2f%%"
% (profit, volume, kask, kbid, perc)
)
| 23 | 78 | 59 | 137 | import logging
from arbitrage.observers.observer import Observer
class Logger(Observer):
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
perc,
weighted_buyprice,
weighted_sellprice,
):
FILL_FUNC_BODY | import logging
from arbitrage.observers.observer import Observer
class Logger(Observer):
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
perc,
weighted_buyprice,
weighted_sellprice,
):
FILL_FUNC_BODY |
37,690 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/observers/observer.py | 8,9 | 4,26 | end_opportunity_finder | Observer | 9,12 | 9,12 | class Observer(object, metaclass=abc.ABCMeta):
def begin_opportunity_finder(self, depths):
pass
def end_opportunity_finder(self):
FILL_FUNC_BODY @abc.abstractmethod
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
... | class Observer(object, metaclass=abc.ABCMeta):
def begin_opportunity_finder(self, depths):
pass
def end_opportunity_finder(self):
FILL_FUNC_BODY @abc.abstractmethod
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
... | pass
## abstract
| pass
## abstract
| 3 | 133 | 12 | 145 | import abc
class Observer(object, metaclass=abc.ABCMeta):
def begin_opportunity_finder(self, depths):
pass
def end_opportunity_finder(self):
FILL_FUNC_BODY @abc.abstractmethod
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
... | import abc
class Observer(object, metaclass=abc.ABCMeta):
def begin_opportunity_finder(self, depths):
pass
def end_opportunity_finder(self):
FILL_FUNC_BODY @abc.abstractmethod
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
... |
37,691 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_binance.py | 28,29 | 8,32 | format_depth | Binance | 29,32 | 29,32 | class Binance(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = "https://api.binance.com/api/v1/depth?symbol=%s" % self.code
req = urllib.request.Request(url, headers={"Accept": "*... | class Binance(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = "https://api.binance.com/api/v1/depth?symbol=%s" % self.code
req = urllib.request.Request(url, headers={"Accept": "*... | bids = self.sort_and_format(depth["bids"], True)
asks = self.sort_and_format(depth["asks"], False)
return {"asks": asks, "bids": bids}
| bids = self.sort_and_format(depth["bids"], True)
asks = self.sort_and_format(depth["asks"], False)
return {"asks": asks, "bids": bids}
| 13 | 263 | 56 | 319 | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class Binance(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url... | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class Binance(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url... |
37,692 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_bitfinex.py | 24,25 | 9,35 | sort_and_format | Bitfinex | 25,31 | 25,31 | class Bitfinex(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(self):
res = urllib.request.urlopen("https://api.bitfinex.com/v1/book/" + self.code)
jsonstr = res.read().decode("utf8")
... | class Bitfinex(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(self):
res = urllib.request.urlopen("https://api.bitfinex.com/v1/book/" + self.code)
jsonstr = res.read().decode("utf8")
... | l.sort(key=lambda x: float(x["price"]), reverse=reverse)
r = []
for i in l:
r.append({"price": float(i["price"]), "amount": float(i["amount"])})
return r
| l.sort(key=lambda x: float(x["price"]), reverse=reverse)
r = []
for i in l:
r.append({"price": float(i["price"]), "amount": float(i["amount"])})
return r
| 17 | 259 | 73 | 332 | import urllib.request
import urllib.error
import urllib.parse
import json
import logging
from arbitrage.public_markets.market import Market
class Bitfinex(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(se... | import urllib.request
import urllib.error
import urllib.parse
import json
import logging
from arbitrage.public_markets.market import Market
class Bitfinex(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(se... |
37,693 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_bitflyer.py | 38,39 | 32,58 | update_depth | BitFlyer | 39,47 | 39,47 | class BitFlyer(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x["price"]), reverse=reverse)
r... | class BitFlyer(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x["price"]), reverse=reverse)
r... | res = urllib.request.urlopen("https://api.bitflyer.com/v1/board?product_code=" + self.code)
jsonstr = res.read().decode("utf8")
try:
depth = json.loads(jsonstr)
except Exception:
logging.error("%s - Can't parse json: %s" % (self.name, jsonstr))
self.depth ... | res = urllib.request.urlopen("https://api.bitflyer.com/v1/board?product_code=" + self.code)
jsonstr = res.read().decode("utf8")
try:
depth = json.loads(jsonstr)
except Exception:
logging.error("%s - Can't parse json: %s" % (self.name, jsonstr))
self.depth ... | 26 | 216 | 122 | 338 | import urllib.request
import urllib.error
import urllib.parse
import json
import logging
from arbitrage.public_markets.market import Market
# {
# "mid_price": 33320,
# "bids": [
# {
# "price": 30000,
# "size": 0.1
# },
# {
# "price": 25570,
# "size": 3
# }
# ],
# "asks"... | import urllib.request
import urllib.error
import urllib.parse
import json
import logging
from arbitrage.public_markets.market import Market
# {
# "mid_price": 33320,
# "bids": [
# {
# "price": 30000,
# "size": 0.1
# },
# {
# "price": 25570,
# "size": 3
# }
# ],
# "asks"... |
37,694 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_bitstamp.py | 15,16 | 9,41 | update_depth | Bitstamp | 16,30 | 16,30 | class Bitstamp(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse):
r = []
for i in l:
r.append({"price": float(i[0]), "... | class Bitstamp(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse):
r = []
for i in l:
r.append({"price": float(i[0]), "... | url = "https://www.bitstamp.net/api/v2/order_book/" + self.code
req = urllib.request.Request(
url,
None,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-... | url = "https://www.bitstamp.net/api/v2/order_book/" + self.code
req = urllib.request.Request(
url,
None,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-... | 29 | 212 | 183 | 395 | import urllib.request
import urllib.error
import urllib.parse
import json
import sys
from arbitrage.public_markets.market import Market
class Bitstamp(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(self):... | import urllib.request
import urllib.error
import urllib.parse
import json
import sys
from arbitrage.public_markets.market import Market
class Bitstamp(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 20
def update_depth(self):... |
37,695 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_btcc.py | 14,15 | 8,39 | update_depth | BTCC | 15,28 | 15,28 | class BTCC(Market):
def __init__(self, currency, symbol):
super().__init__(currency)
self.symbol = symbol
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x[0]), reverse=reverse)
r = [... | class BTCC(Market):
def __init__(self, currency, symbol):
super().__init__(currency)
self.symbol = symbol
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x[0]), reverse=reverse)
r = [... | url = "https://data.btcc.com/data/orderbook?market=" + self.symbol
req = urllib.request.Request(
url,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.... | url = "https://data.btcc.com/data/orderbook?market=" + self.symbol
req = urllib.request.Request(
url,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.... | 28 | 213 | 176 | 389 | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class BTCC(Market):
def __init__(self, currency, symbol):
super().__init__(currency)
self.symbol = symbol
self.update_rate = 30
def update_depth(self):
FILL_FUN... | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class BTCC(Market):
def __init__(self, currency, symbol):
super().__init__(currency)
self.symbol = symbol
self.update_rate = 30
def update_depth(self):
FILL_FUN... |
37,696 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_cex.py | 35,36 | 8,39 | format_depth | CEX | 36,39 | 36,39 | class CEX(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = "https://cex.io/api/order_book/BTC/%s/" % self.code
req = urllib.request.Request(
url,
headers={... | class CEX(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = "https://cex.io/api/order_book/BTC/%s/" % self.code
req = urllib.request.Request(
url,
headers={... | bids = self.sort_and_format(depth["bids"], True)
asks = self.sort_and_format(depth["asks"], False)
return {"asks": asks, "bids": bids}
| bids = self.sort_and_format(depth["bids"], True)
asks = self.sort_and_format(depth["asks"], False)
return {"asks": asks, "bids": bids}
| 13 | 325 | 56 | 381 | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class CEX(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = "... | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class CEX(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = "... |
37,697 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_gdax.py | 28,29 | 8,39 | sort_and_format | GDAX | 29,35 | 29,35 | class GDAX(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = "https://api.gdax.com/products/%s/book?level=2" % self.code
req = urllib.request.Request(
url,
... | class GDAX(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = "https://api.gdax.com/products/%s/book?level=2" % self.code
req = urllib.request.Request(
url,
... | l.sort(key=lambda x: float(x[0]), reverse=reverse)
r = []
for i in l:
r.append({"price": float(i[0]), "amount": float(i[1])})
return r
| l.sort(key=lambda x: float(x[0]), reverse=reverse)
r = []
for i in l:
r.append({"price": float(i[0]), "amount": float(i[1])})
return r
| 17 | 315 | 72 | 387 | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class GDAX(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = ... | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class GDAX(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
url = ... |
37,698 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_gemini.py | 14,15 | 8,39 | update_depth | Gemini | 15,28 | 15,28 | class Gemini(Market):
def __init__(self, currency, symbol):
super().__init__(currency)
self.symbol = symbol
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x["price"]), reverse=reverse)
... | class Gemini(Market):
def __init__(self, currency, symbol):
super().__init__(currency)
self.symbol = symbol
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x["price"]), reverse=reverse)
... | url = "https://api.gemini.com/v1/book/" + self.symbol
req = urllib.request.Request(
url,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.0)",
... | url = "https://api.gemini.com/v1/book/" + self.symbol
req = urllib.request.Request(
url,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.0)",
... | 28 | 215 | 174 | 389 | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class Gemini(Market):
def __init__(self, currency, symbol):
super().__init__(currency)
self.symbol = symbol
self.update_rate = 30
def update_depth(self):
FILL_F... | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class Gemini(Market):
def __init__(self, currency, symbol):
super().__init__(currency)
self.symbol = symbol
self.update_rate = 30
def update_depth(self):
FILL_F... |
37,699 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_kraken.py | 14,15 | 8,40 | update_depth | Kraken | 15,29 | 15,29 | class Kraken(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x[0]), reverse=reverse)
r = []
... | class Kraken(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x[0]), reverse=reverse)
r = []
... | url = "https://api.kraken.com/0/public/Depth"
req = urllib.request.Request(
url,
b"pair=" + bytes(self.code, "ascii"),
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7... | url = "https://api.kraken.com/0/public/Depth"
req = urllib.request.Request(
url,
b"pair=" + bytes(self.code, "ascii"),
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7... | 30 | 230 | 191 | 421 | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class Kraken(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BO... | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class Kraken(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BO... |
37,700 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/_okcoin.py | 14,15 | 8,39 | update_depth | OKCoin | 15,28 | 15,28 | class OKCoin(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x[0]), reverse=reverse)
r = []
... | class OKCoin(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, reverse=False):
l.sort(key=lambda x: float(x[0]), reverse=reverse)
r = []
... | url = "https://www.okcoin.cn/api/depth.do?symbol=" + self.code
req = urllib.request.Request(
url,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.0)",... | url = "https://www.okcoin.cn/api/depth.do?symbol=" + self.code
req = urllib.request.Request(
url,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.0)",... | 28 | 214 | 177 | 391 | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class OKCoin(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BO... | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class OKCoin(Market):
def __init__(self, currency, code):
super().__init__(currency)
self.code = code
self.update_rate = 30
def update_depth(self):
FILL_FUNC_BO... |
37,701 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/public_markets/paymiumeur.py | 15,16 | 8,42 | update_depth | PaymiumEUR | 16,29 | 16,29 | class PaymiumEUR(Market):
def __init__(self):
super(PaymiumEUR, self).__init__("EUR")
# bitcoin central maximum call / day = 5000
# keep 2500 for other operations
self.update_rate = 24 * 60 * 60 / 2500
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, revers... | class PaymiumEUR(Market):
def __init__(self):
super(PaymiumEUR, self).__init__("EUR")
# bitcoin central maximum call / day = 5000
# keep 2500 for other operations
self.update_rate = 24 * 60 * 60 / 2500
def update_depth(self):
FILL_FUNC_BODY def sort_and_format(self, l, revers... | url = "https://paymium.com/api/data/eur/depth"
req = urllib.request.Request(
url,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.0)",
},
... | url = "https://paymium.com/api/data/eur/depth"
req = urllib.request.Request(
url,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.0)",
},
... | 26 | 259 | 171 | 430 | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class PaymiumEUR(Market):
def __init__(self):
super(PaymiumEUR, self).__init__("EUR")
# bitcoin central maximum call / day = 5000
# keep 2500 for other operations
... | import urllib.request
import urllib.error
import urllib.parse
import json
from arbitrage.public_markets.market import Market
class PaymiumEUR(Market):
def __init__(self):
super(PaymiumEUR, self).__init__("EUR")
# bitcoin central maximum call / day = 5000
# keep 2500 for other operations
... |
37,702 | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage | /home/hieuvd/dung_repo/raw/stars_02/maxme_bitcoin-arbitrage/bitcoin-arbitrage/arbitrage/utils.py | 7,8 | 1,14 | log_exception | 8,14 | 8,14 | import os
import sys
import traceback
import logging
def log_exception(level):
FILL_FUNC_BODY | import os
import sys
import traceback
import logging
def log_exception(level):
FILL_FUNC_BODY | exc_type, exc_value, exc_traceback = sys.exc_info()
for i in traceback.extract_tb(exc_traceback):
# line = (os.path.basename(i[0]), i[1], i[2])
line = (i[0], i[1], i[2])
logging.log(level, 'File "%s", line %d, in %s' % line)
logging.log(level, "\t%s" % i[3])
| exc_type, exc_value, exc_traceback = sys.exc_info()
for i in traceback.extract_tb(exc_traceback):
# line = (os.path.basename(i[0]), i[1], i[2])
line = (i[0], i[1], i[2])
logging.log(level, 'File "%s", line %d, in %s' % line)
logging.log(level, "\t%s" % i[3])
| 33 | 33 | 130 | 163 | import os
import sys
import traceback
import logging
def log_exception(level):
FILL_FUNC_BODY | import os
import sys
import traceback
import logging
def log_exception(level):
FILL_FUNC_BODY | |
37,703 | /home/hieuvd/dung_repo/raw/stars_02/metavoiceio_metavoice-src/metavoice-src | /home/hieuvd/dung_repo/raw/stars_02/metavoiceio_metavoice-src/metavoice-src/fam/llm/adapters/flattened_encodec.py | 8,9 | 4,39 | decode | FlattenedInterleavedEncodec2Codebook | 9,34 | 9,34 | class FlattenedInterleavedEncodec2Codebook(BaseDataAdapter):
def __init__(self, end_of_audio_token):
self._end_of_audio_token = end_of_audio_token
def decode(self, tokens: list[list[int]]) -> tuple[list[int], list[list[int]]]:
FILL_FUNC_BODY def encode(self, text_tokens: list[int], audio_tokens: lis... | class FlattenedInterleavedEncodec2Codebook(BaseDataAdapter):
def __init__(self, end_of_audio_token):
self._end_of_audio_token = end_of_audio_token
def decode(self, tokens: list[list[int]]) -> tuple[list[int], list[list[int]]]:
FILL_FUNC_BODY def encode(self, text_tokens: list[int], audio_tokens: lis... | assert len(tokens) == 1
tokens = tokens[0]
text_ids = []
extracted_audio_ids = [[], []]
for t in tokens:
if t < self._end_of_audio_token:
extracted_audio_ids[0].append(t)
elif t >= self._end_of_audio_token and t < 2 * self._end_of_audio_t... | assert len(tokens) == 1
tokens = tokens[0]
text_ids = []
extracted_audio_ids = [[], []]
for t in tokens:
if t < self._end_of_audio_token:
extracted_audio_ids[0].append(t)
elif t >= self._end_of_audio_token and t < 2 * self._end_of_audio_t... | 119 | 151 | 379 | 530 | from fam.llm.adapters.base import BaseDataAdapter
class FlattenedInterleavedEncodec2Codebook(BaseDataAdapter):
def __init__(self, end_of_audio_token):
self._end_of_audio_token = end_of_audio_token
def decode(self, tokens: list[list[int]]) -> tuple[list[int], list[list[int]]]:
FILL_FUNC_BODY def en... | from fam.llm.adapters.base import BaseDataAdapter
class FlattenedInterleavedEncodec2Codebook(BaseDataAdapter):
def __init__(self, end_of_audio_token):
self._end_of_audio_token = end_of_audio_token
def decode(self, tokens: list[list[int]]) -> tuple[list[int], list[list[int]]]:
FILL_FUNC_BODY def en... |
37,704 | /home/hieuvd/dung_repo/raw/stars_02/metavoiceio_metavoice-src/metavoice-src | /home/hieuvd/dung_repo/raw/stars_02/metavoiceio_metavoice-src/metavoice-src/fam/llm/adapters/tilted_encodec.py | 8,9 | 4,46 | decode | TiltedEncodec | 9,41 | 9,41 | class TiltedEncodec(BaseDataAdapter):
def __init__(self, end_of_audio_token):
self._end_of_audio_token = end_of_audio_token
def decode(self, tokens: list[list[int]]) -> tuple[list[int], list[list[int]]]:
FILL_FUNC_BODY def encode(self, text_tokens: list[int], audio_tokens: list[list[int]]):
... | class TiltedEncodec(BaseDataAdapter):
def __init__(self, end_of_audio_token):
self._end_of_audio_token = end_of_audio_token
def decode(self, tokens: list[list[int]]) -> tuple[list[int], list[list[int]]]:
FILL_FUNC_BODY def encode(self, text_tokens: list[int], audio_tokens: list[list[int]]):
... | assert len(tokens) > 1
text_ids = []
extracted_audio_ids = []
extracted_audio_ids.append([])
# Handle first hierarchy as special case as it contains text tokens as well
# TODO: maybe it doesn't need special case, and can be handled on it's own :)
for t in tokens... | assert len(tokens) > 1
text_ids = []
extracted_audio_ids = []
extracted_audio_ids.append([])
# Handle first hierarchy as special case as it contains text tokens as well
# TODO: maybe it doesn't need special case, and can be handled on it's own :)
for t in tokens... | 140 | 145 | 441 | 586 | from fam.llm.adapters.base import BaseDataAdapter
class TiltedEncodec(BaseDataAdapter):
def __init__(self, end_of_audio_token):
self._end_of_audio_token = end_of_audio_token
def decode(self, tokens: list[list[int]]) -> tuple[list[int], list[list[int]]]:
FILL_FUNC_BODY def encode(self, text_tokens:... | from fam.llm.adapters.base import BaseDataAdapter
class TiltedEncodec(BaseDataAdapter):
def __init__(self, end_of_audio_token):
self._end_of_audio_token = end_of_audio_token
def decode(self, tokens: list[list[int]]) -> tuple[list[int], list[list[int]]]:
FILL_FUNC_BODY def encode(self, text_tokens:... |
38,038 | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/ability_api.py | 16,17 | 10,113 | add_routes | AbilityApi | 17,25 | 17,25 | class AbilityApi(BaseObjectApi):
def __init__(self, services):
super().__init__(description='ability', obj_class=Ability, schema=AbilitySchema, ram_key='abilities',
id_property='ability_id', auth_svc=services['auth_svc'])
self._api_manager = AbilityApiManager(data_svc=servic... | class AbilityApi(BaseObjectApi):
def __init__(self, services):
super().__init__(description='ability', obj_class=Ability, schema=AbilitySchema, ram_key='abilities',
id_property='ability_id', auth_svc=services['auth_svc'])
self._api_manager = AbilityApiManager(data_svc=servic... | router = app.router
router.add_get('/abilities', self.get_abilities)
router.add_get('/abilities/{ability_id}', self.get_ability_by_id)
router.add_post('/abilities', self.create_ability)
router.add_put('/abilities/{ability_id}', self.create_or_update_ability)
router.add_pa... | router = app.router
router.add_get('/abilities', self.get_abilities)
router.add_get('/abilities/{ability_id}', self.get_ability_by_id)
router.add_post('/abilities', self.create_ability)
router.add_put('/abilities/{ability_id}', self.create_or_update_ability)
router.add_pa... | 15 | 1,354 | 140 | 1,494 | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_object_api import BaseObjectApi
from app.api.v2.managers.ability_api_manager import AbilityApiManager
from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema
from app.objects.c_ability import Ability, AbilityS... | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_object_api import BaseObjectApi
from app.api.v2.managers.ability_api_manager import AbilityApiManager
from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema
from app.objects.c_ability import Ability, AbilityS... |
38,040 | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/agent_api.py | 17,18 | 11,153 | add_routes | AgentApi | 18,29 | 18,29 | class AgentApi(BaseObjectApi):
def __init__(self, services):
super().__init__(description='agent', obj_class=Agent, schema=AgentSchema, ram_key='agents',
id_property='paw', auth_svc=services['auth_svc'])
self._api_manager = AgentApiManager(data_svc=services['data_svc'], file... | class AgentApi(BaseObjectApi):
def __init__(self, services):
super().__init__(description='agent', obj_class=Agent, schema=AgentSchema, ram_key='agents',
id_property='paw', auth_svc=services['auth_svc'])
self._api_manager = AgentApiManager(data_svc=services['data_svc'], file... | router = app.router
router.add_get('/agents', self.get_agents)
router.add_get('/agents/{paw}', self.get_agent_by_id)
router.add_post('/agents', self.create_agent)
router.add_patch('/agents/{paw}', self.update_agent)
router.add_put('/agents/{paw}', self.create_or_update_ag... | router = app.router
router.add_get('/agents', self.get_agents)
router.add_get('/agents/{paw}', self.get_agent_by_id)
router.add_post('/agents', self.create_agent)
router.add_patch('/agents/{paw}', self.update_agent)
router.add_put('/agents/{paw}', self.create_or_update_ag... | 19 | 1,803 | 204 | 2,007 | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_object_api import BaseObjectApi
from app.api.v2.managers.agent_api_manager import AgentApiManager
from app.api.v2.schemas.deploy_command_schemas import DeployCommandsSchema
from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, Ba... | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_object_api import BaseObjectApi
from app.api.v2.managers.agent_api_manager import AgentApiManager
from app.api.v2.schemas.deploy_command_schemas import DeployCommandsSchema
from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, Ba... |
38,041 | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/base_object_api.py | 35,36 | 10,149 | get_object | BaseObjectApi | 36,49 | 36,49 | class BaseObjectApi(BaseApi):
def __init__(self, description, obj_class, schema, ram_key, id_property, auth_svc, logger=None):
super().__init__(auth_svc=auth_svc, logger=logger)
self.description = description
self.obj_class = obj_class
self.schema = schema
self.ram_key = ram... | class BaseObjectApi(BaseApi):
def __init__(self, description, obj_class, schema, ram_key, id_property, auth_svc, logger=None):
super().__init__(auth_svc=auth_svc, logger=logger)
self.description = description
self.obj_class = obj_class
self.schema = schema
self.ram_key = ram... | data, access, obj_id, query, search = await self._parse_common_data_from_request(request)
obj = self._api_manager.find_object(self.ram_key, query)
if not obj:
raise JsonHttpNotFound(f'{self.description.capitalize()} not found: {obj_id}')
elif obj.access not in access['access... | data, access, obj_id, query, search = await self._parse_common_data_from_request(request)
obj = self._api_manager.find_object(self.ram_key, query)
if not obj:
raise JsonHttpNotFound(f'{self.description.capitalize()} not found: {obj_id}')
elif obj.access not in access['access... | 44 | 1,704 | 198 | 1,902 | import abc
import json
from aiohttp import web
from app.api.v2.handlers.base_api import BaseApi
from app.api.v2.responses import JsonHttpBadRequest, JsonHttpForbidden, JsonHttpNotFound
class BaseObjectApi(BaseApi):
def __init__(self, description, obj_class, schema, ram_key, id_property, auth_svc, logger=None):
... | import abc
import json
from aiohttp import web
from app.api.v2.handlers.base_api import BaseApi
from app.api.v2.responses import JsonHttpBadRequest, JsonHttpForbidden, JsonHttpNotFound
class BaseObjectApi(BaseApi):
def __init__(self, description, obj_class, schema, ram_key, id_property, auth_svc, logger=None):
... |
38,042 | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/config_api.py | 21,31 | 10,76 | get_config_with_name | ConfigApi | 31,39 | 31,39 | class ConfigApi(BaseApi):
def __init__(self, services):
super().__init__(auth_svc=services['auth_svc'])
self._api_manager = ConfigApiManager(data_svc=services['data_svc'], file_svc=services['file_svc'])
def add_routes(self, app: web.Application):
router = app.router
router.add_g... | class ConfigApi(BaseApi):
def __init__(self, services):
super().__init__(auth_svc=services['auth_svc'])
self._api_manager = ConfigApiManager(data_svc=services['data_svc'], file_svc=services['file_svc'])
def add_routes(self, app: web.Application):
router = app.router
router.add_g... | config_name = request.match_info['name']
try:
config = self._api_manager.get_filtered_config(config_name)
except ConfigNotFound:
raise JsonHttpNotFound(f'Config not found: {config_name}')
return web.json_response(config)
| config_name = request.match_info['name']
try:
config = self._api_manager.get_filtered_config(config_name)
except ConfigNotFound:
raise JsonHttpNotFound(f'Config not found: {config_name}')
return web.json_response(config)
| 16 | 741 | 85 | 826 | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_api import BaseApi
from app.api.v2.responses import JsonHttpForbidden, JsonHttpNotFound
from app.api.v2.schemas.config_schemas import ConfigUpdateSchema, AgentConfigUpdateSchema
from app.api.v2.managers.config_api_manager import ConfigApiMana... | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_api import BaseApi
from app.api.v2.responses import JsonHttpForbidden, JsonHttpNotFound
from app.api.v2.schemas.config_schemas import ConfigUpdateSchema, AgentConfigUpdateSchema
from app.api.v2.managers.config_api_manager import ConfigApiMana... |
38,043 | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/contact_api.py | 20,35 | 8,51 | get_contact_report | ContactApi | 35,39 | 35,39 | class ContactApi(BaseApi):
def __init__(self, services):
super().__init__(auth_svc=services['auth_svc'])
self._api_manager = ContactApiManager(data_svc=services['data_svc'], file_svc=services['file_svc'],
contact_svc=services['contact_svc'])
def add... | class ContactApi(BaseApi):
def __init__(self, services):
super().__init__(auth_svc=services['auth_svc'])
self._api_manager = ContactApiManager(data_svc=services['data_svc'], file_svc=services['file_svc'],
contact_svc=services['contact_svc'])
def add... | contact_name = request.match_info['name']
report = self._api_manager.get_contact_report(contact_name)
return web.json_response(report)
| contact_name = request.match_info['name']
report = self._api_manager.get_contact_report(contact_name)
return web.json_response(report)
| 8 | 639 | 50 | 689 | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_api import BaseApi
from app.api.v2.managers.contact_api_manager import ContactApiManager
class ContactApi(BaseApi):
def __init__(self, services):
super().__init__(auth_svc=services['auth_svc'])
self._api_manager = Contac... | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_api import BaseApi
from app.api.v2.managers.contact_api_manager import ContactApiManager
class ContactApi(BaseApi):
def __init__(self, services):
super().__init__(auth_svc=services['auth_svc'])
self._api_manager = Contac... |
38,045 | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/fact_source_api.py | 25,31 | 10,106 | get_fact_sources | FactSourceApi | 31,34 | 31,34 | class FactSourceApi(BaseObjectApi):
def __init__(self, services):
super().__init__(description='Fact Source', obj_class=Source, schema=SourceSchema, ram_key='sources',
id_property='id', auth_svc=services['auth_svc'])
self._api_manager = BaseApiManager(data_svc=services['data... | class FactSourceApi(BaseObjectApi):
def __init__(self, services):
super().__init__(description='Fact Source', obj_class=Source, schema=SourceSchema, ram_key='sources',
id_property='id', auth_svc=services['auth_svc'])
self._api_manager = BaseApiManager(data_svc=services['data... | sources = await self.get_all_objects(request)
return web.json_response(sources)
| sources = await self.get_all_objects(request)
return web.json_response(sources)
| 6 | 1,399 | 30 | 1,429 | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_object_api import BaseObjectApi
from app.api.v2.managers.base_api_manager import BaseApiManager
from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema
from app.objects.c_source import Source, SourceSchema
c... | import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_object_api import BaseObjectApi
from app.api.v2.managers.base_api_manager import BaseApiManager
from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema
from app.objects.c_source import Source, SourceSchema
c... |
38,046 | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera | /home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/health_api.py | 21,26 | 12,37 | get_health_info | HealthApi | 26,37 | 26,37 | class HealthApi(BaseApi):
def __init__(self, services):
super().__init__(auth_svc=services['auth_svc'])
self._app_svc = services['app_svc']
def add_routes(self, app: web.Application):
router = app.router
router.add_get('/health', security.authentication_exempt(self.get_health_in... | class HealthApi(BaseApi):
def __init__(self, services):
super().__init__(auth_svc=services['auth_svc'])
self._app_svc = services['app_svc']
def add_routes(self, app: web.Application):
router = app.router
router.add_get('/health', security.authentication_exempt(self.get_health_in... | loaded_plugins_sorted = sorted(self._app_svc.get_loaded_plugins(), key=operator.attrgetter('name'))
access = await self._auth_svc.get_permissions(request)
mapping = {
'application': 'Caldera',
'version': app.get_version(),
'access': access[0].name,
... | loaded_plugins_sorted = sorted(self._app_svc.get_loaded_plugins(), key=operator.attrgetter('name'))
access = await self._auth_svc.get_permissions(request)
mapping = {
'application': 'Caldera',
'version': app.get_version(),
'access': access[0].name,
... | 22 | 220 | 136 | 356 | import operator
import aiohttp_apispec
from aiohttp import web
import app
from app.api.v2 import security
from app.api.v2.handlers.base_api import BaseApi
from app.api.v2.schemas.caldera_info_schemas import CalderaInfoSchema
class HealthApi(BaseApi):
def __init__(self, services):
super().__init__(auth_s... | import operator
import aiohttp_apispec
from aiohttp import web
import app
from app.api.v2 import security
from app.api.v2.handlers.base_api import BaseApi
from app.api.v2.schemas.caldera_info_schemas import CalderaInfoSchema
class HealthApi(BaseApi):
def __init__(self, services):
super().__init__(auth_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.