repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
dailymotion/tartiflette-aiohttp
tartiflette_aiohttp/__init__.py
register_graphql_handlers
def register_graphql_handlers( app: "Application", engine_sdl: str = None, engine_schema_name: str = "default", executor_context: dict = None, executor_http_endpoint: str = "/graphql", executor_http_methods: List[str] = None, engine: Engine = None, subscription_ws_endpoint: Optional[str] = None, graphiql_enabled: bool = False, graphiql_options: Optional[Dict[str, Any]] = None, ) -> "Application": """Register a Tartiflette Engine to an app Pass a SDL or an already initialized Engine, not both, not neither. Keyword Arguments: app {aiohttp.web.Application} -- The application to register to. engine_sdl {str} -- The SDL defining your API (default: {None}) engine_schema_name {str} -- The name of your sdl (default: {"default"}) executor_context {dict} -- Context dict that will be passed to the resolvers (default: {None}) executor_http_endpoint {str} -- Path part of the URL the graphql endpoint will listen on (default: {"/graphql"}) executor_http_methods {list[str]} -- List of HTTP methods allowed on the endpoint (only GET and POST are supported) (default: {None}) engine {Engine} -- An already initialized Engine (default: {None}) subscription_ws_endpoint {Optional[str]} -- Path part of the URL the WebSocket GraphQL subscription endpoint will listen on (default: {None}) graphiql_enabled {bool} -- Determines whether or not we should handle a GraphiQL endpoint (default: {False}) graphiql_options {dict} -- Customization options for the GraphiQL instance (default: {None}) Raises: Exception -- On bad sdl/engine parameter combinaison. Exception -- On unsupported HTTP Method. Return: The app object. """ # pylint: disable=too-many-arguments,too-many-locals if (not engine_sdl and not engine) or (engine and engine_sdl): raise Exception( "an engine OR an engine_sdl should be passed here, not both, not none" ) if not executor_context: executor_context = {} executor_context["app"] = app if not executor_http_methods: executor_http_methods = ["GET", "POST"] if not engine: engine = Engine(engine_sdl, engine_schema_name) app["ttftt_engine"] = engine for method in executor_http_methods: try: app.router.add_route( method, executor_http_endpoint, partial( getattr(Handlers, "handle_%s" % method.lower()), executor_context, ), ) except AttributeError: raise Exception("Unsupported < %s > http method" % method) _set_subscription_ws_handler(app, subscription_ws_endpoint, engine) _set_graphiql_handler( app, graphiql_enabled, graphiql_options, executor_http_endpoint, executor_http_methods, subscription_ws_endpoint, ) return app
python
def register_graphql_handlers( app: "Application", engine_sdl: str = None, engine_schema_name: str = "default", executor_context: dict = None, executor_http_endpoint: str = "/graphql", executor_http_methods: List[str] = None, engine: Engine = None, subscription_ws_endpoint: Optional[str] = None, graphiql_enabled: bool = False, graphiql_options: Optional[Dict[str, Any]] = None, ) -> "Application": """Register a Tartiflette Engine to an app Pass a SDL or an already initialized Engine, not both, not neither. Keyword Arguments: app {aiohttp.web.Application} -- The application to register to. engine_sdl {str} -- The SDL defining your API (default: {None}) engine_schema_name {str} -- The name of your sdl (default: {"default"}) executor_context {dict} -- Context dict that will be passed to the resolvers (default: {None}) executor_http_endpoint {str} -- Path part of the URL the graphql endpoint will listen on (default: {"/graphql"}) executor_http_methods {list[str]} -- List of HTTP methods allowed on the endpoint (only GET and POST are supported) (default: {None}) engine {Engine} -- An already initialized Engine (default: {None}) subscription_ws_endpoint {Optional[str]} -- Path part of the URL the WebSocket GraphQL subscription endpoint will listen on (default: {None}) graphiql_enabled {bool} -- Determines whether or not we should handle a GraphiQL endpoint (default: {False}) graphiql_options {dict} -- Customization options for the GraphiQL instance (default: {None}) Raises: Exception -- On bad sdl/engine parameter combinaison. Exception -- On unsupported HTTP Method. Return: The app object. """ # pylint: disable=too-many-arguments,too-many-locals if (not engine_sdl and not engine) or (engine and engine_sdl): raise Exception( "an engine OR an engine_sdl should be passed here, not both, not none" ) if not executor_context: executor_context = {} executor_context["app"] = app if not executor_http_methods: executor_http_methods = ["GET", "POST"] if not engine: engine = Engine(engine_sdl, engine_schema_name) app["ttftt_engine"] = engine for method in executor_http_methods: try: app.router.add_route( method, executor_http_endpoint, partial( getattr(Handlers, "handle_%s" % method.lower()), executor_context, ), ) except AttributeError: raise Exception("Unsupported < %s > http method" % method) _set_subscription_ws_handler(app, subscription_ws_endpoint, engine) _set_graphiql_handler( app, graphiql_enabled, graphiql_options, executor_http_endpoint, executor_http_methods, subscription_ws_endpoint, ) return app
[ "def", "register_graphql_handlers", "(", "app", ":", "\"Application\"", ",", "engine_sdl", ":", "str", "=", "None", ",", "engine_schema_name", ":", "str", "=", "\"default\"", ",", "executor_context", ":", "dict", "=", "None", ",", "executor_http_endpoint", ":", "str", "=", "\"/graphql\"", ",", "executor_http_methods", ":", "List", "[", "str", "]", "=", "None", ",", "engine", ":", "Engine", "=", "None", ",", "subscription_ws_endpoint", ":", "Optional", "[", "str", "]", "=", "None", ",", "graphiql_enabled", ":", "bool", "=", "False", ",", "graphiql_options", ":", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", "=", "None", ",", ")", "->", "\"Application\"", ":", "# pylint: disable=too-many-arguments,too-many-locals", "if", "(", "not", "engine_sdl", "and", "not", "engine", ")", "or", "(", "engine", "and", "engine_sdl", ")", ":", "raise", "Exception", "(", "\"an engine OR an engine_sdl should be passed here, not both, not none\"", ")", "if", "not", "executor_context", ":", "executor_context", "=", "{", "}", "executor_context", "[", "\"app\"", "]", "=", "app", "if", "not", "executor_http_methods", ":", "executor_http_methods", "=", "[", "\"GET\"", ",", "\"POST\"", "]", "if", "not", "engine", ":", "engine", "=", "Engine", "(", "engine_sdl", ",", "engine_schema_name", ")", "app", "[", "\"ttftt_engine\"", "]", "=", "engine", "for", "method", "in", "executor_http_methods", ":", "try", ":", "app", ".", "router", ".", "add_route", "(", "method", ",", "executor_http_endpoint", ",", "partial", "(", "getattr", "(", "Handlers", ",", "\"handle_%s\"", "%", "method", ".", "lower", "(", ")", ")", ",", "executor_context", ",", ")", ",", ")", "except", "AttributeError", ":", "raise", "Exception", "(", "\"Unsupported < %s > http method\"", "%", "method", ")", "_set_subscription_ws_handler", "(", "app", ",", "subscription_ws_endpoint", ",", "engine", ")", "_set_graphiql_handler", "(", "app", ",", "graphiql_enabled", ",", "graphiql_options", ",", "executor_http_endpoint", ",", "executor_http_methods", ",", "subscription_ws_endpoint", ",", ")", "return", "app" ]
Register a Tartiflette Engine to an app Pass a SDL or an already initialized Engine, not both, not neither. Keyword Arguments: app {aiohttp.web.Application} -- The application to register to. engine_sdl {str} -- The SDL defining your API (default: {None}) engine_schema_name {str} -- The name of your sdl (default: {"default"}) executor_context {dict} -- Context dict that will be passed to the resolvers (default: {None}) executor_http_endpoint {str} -- Path part of the URL the graphql endpoint will listen on (default: {"/graphql"}) executor_http_methods {list[str]} -- List of HTTP methods allowed on the endpoint (only GET and POST are supported) (default: {None}) engine {Engine} -- An already initialized Engine (default: {None}) subscription_ws_endpoint {Optional[str]} -- Path part of the URL the WebSocket GraphQL subscription endpoint will listen on (default: {None}) graphiql_enabled {bool} -- Determines whether or not we should handle a GraphiQL endpoint (default: {False}) graphiql_options {dict} -- Customization options for the GraphiQL instance (default: {None}) Raises: Exception -- On bad sdl/engine parameter combinaison. Exception -- On unsupported HTTP Method. Return: The app object.
[ "Register", "a", "Tartiflette", "Engine", "to", "an", "app" ]
a87e6aa7d1f18b2d700eeb799228745848c88088
https://github.com/dailymotion/tartiflette-aiohttp/blob/a87e6aa7d1f18b2d700eeb799228745848c88088/tartiflette_aiohttp/__init__.py#L92-L170
train
dailymotion/tartiflette-aiohttp
examples/aiohttp/starwars/app.py
on_shutdown
async def on_shutdown(app): """app SHUTDOWN event handler """ for method in app.get("close_methods", []): logger.debug("Calling < %s >", method) if asyncio.iscoroutinefunction(method): await method() else: method()
python
async def on_shutdown(app): """app SHUTDOWN event handler """ for method in app.get("close_methods", []): logger.debug("Calling < %s >", method) if asyncio.iscoroutinefunction(method): await method() else: method()
[ "async", "def", "on_shutdown", "(", "app", ")", ":", "for", "method", "in", "app", ".", "get", "(", "\"close_methods\"", ",", "[", "]", ")", ":", "logger", ".", "debug", "(", "\"Calling < %s >\"", ",", "method", ")", "if", "asyncio", ".", "iscoroutinefunction", "(", "method", ")", ":", "await", "method", "(", ")", "else", ":", "method", "(", ")" ]
app SHUTDOWN event handler
[ "app", "SHUTDOWN", "event", "handler" ]
a87e6aa7d1f18b2d700eeb799228745848c88088
https://github.com/dailymotion/tartiflette-aiohttp/blob/a87e6aa7d1f18b2d700eeb799228745848c88088/examples/aiohttp/starwars/app.py#L20-L28
train
davidmogar/cucco
cucco/config.py
Config._load_from_file
def _load_from_file(path): """Load a config file from the given path. Load all normalizations from the config file received as argument. It expects to find a YAML file with a list of normalizations and arguments under the key 'normalizations'. Args: path: Path to YAML file. """ config = [] try: with open(path, 'r') as config_file: config = yaml.load(config_file)['normalizations'] except EnvironmentError as e: raise ConfigError('Problem while loading file: %s' % e.args[1] if len(e.args) > 1 else e) except (TypeError, KeyError) as e: raise ConfigError('Config file has an unexpected structure: %s' % e) except yaml.YAMLError: raise ConfigError('Invalid YAML file syntax') return config
python
def _load_from_file(path): """Load a config file from the given path. Load all normalizations from the config file received as argument. It expects to find a YAML file with a list of normalizations and arguments under the key 'normalizations'. Args: path: Path to YAML file. """ config = [] try: with open(path, 'r') as config_file: config = yaml.load(config_file)['normalizations'] except EnvironmentError as e: raise ConfigError('Problem while loading file: %s' % e.args[1] if len(e.args) > 1 else e) except (TypeError, KeyError) as e: raise ConfigError('Config file has an unexpected structure: %s' % e) except yaml.YAMLError: raise ConfigError('Invalid YAML file syntax') return config
[ "def", "_load_from_file", "(", "path", ")", ":", "config", "=", "[", "]", "try", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "config_file", ":", "config", "=", "yaml", ".", "load", "(", "config_file", ")", "[", "'normalizations'", "]", "except", "EnvironmentError", "as", "e", ":", "raise", "ConfigError", "(", "'Problem while loading file: %s'", "%", "e", ".", "args", "[", "1", "]", "if", "len", "(", "e", ".", "args", ")", ">", "1", "else", "e", ")", "except", "(", "TypeError", ",", "KeyError", ")", "as", "e", ":", "raise", "ConfigError", "(", "'Config file has an unexpected structure: %s'", "%", "e", ")", "except", "yaml", ".", "YAMLError", ":", "raise", "ConfigError", "(", "'Invalid YAML file syntax'", ")", "return", "config" ]
Load a config file from the given path. Load all normalizations from the config file received as argument. It expects to find a YAML file with a list of normalizations and arguments under the key 'normalizations'. Args: path: Path to YAML file.
[ "Load", "a", "config", "file", "from", "the", "given", "path", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/config.py#L53-L76
train
davidmogar/cucco
cucco/config.py
Config._parse_normalization
def _parse_normalization(normalization): """Parse a normalization item. Transform dicts into a tuple containing the normalization options. If a string is found, the actual value is used. Args: normalization: Normalization to parse. Returns: Tuple or string containing the parsed normalization. """ parsed_normalization = None if isinstance(normalization, dict): if len(normalization.keys()) == 1: items = list(normalization.items())[0] if len(items) == 2: # Two elements tuple # Convert to string if no normalization options if items[1] and isinstance(items[1], dict): parsed_normalization = items else: parsed_normalization = items[0] elif isinstance(normalization, STR_TYPE): parsed_normalization = normalization return parsed_normalization
python
def _parse_normalization(normalization): """Parse a normalization item. Transform dicts into a tuple containing the normalization options. If a string is found, the actual value is used. Args: normalization: Normalization to parse. Returns: Tuple or string containing the parsed normalization. """ parsed_normalization = None if isinstance(normalization, dict): if len(normalization.keys()) == 1: items = list(normalization.items())[0] if len(items) == 2: # Two elements tuple # Convert to string if no normalization options if items[1] and isinstance(items[1], dict): parsed_normalization = items else: parsed_normalization = items[0] elif isinstance(normalization, STR_TYPE): parsed_normalization = normalization return parsed_normalization
[ "def", "_parse_normalization", "(", "normalization", ")", ":", "parsed_normalization", "=", "None", "if", "isinstance", "(", "normalization", ",", "dict", ")", ":", "if", "len", "(", "normalization", ".", "keys", "(", ")", ")", "==", "1", ":", "items", "=", "list", "(", "normalization", ".", "items", "(", ")", ")", "[", "0", "]", "if", "len", "(", "items", ")", "==", "2", ":", "# Two elements tuple", "# Convert to string if no normalization options", "if", "items", "[", "1", "]", "and", "isinstance", "(", "items", "[", "1", "]", ",", "dict", ")", ":", "parsed_normalization", "=", "items", "else", ":", "parsed_normalization", "=", "items", "[", "0", "]", "elif", "isinstance", "(", "normalization", ",", "STR_TYPE", ")", ":", "parsed_normalization", "=", "normalization", "return", "parsed_normalization" ]
Parse a normalization item. Transform dicts into a tuple containing the normalization options. If a string is found, the actual value is used. Args: normalization: Normalization to parse. Returns: Tuple or string containing the parsed normalization.
[ "Parse", "a", "normalization", "item", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/config.py#L79-L105
train
davidmogar/cucco
cucco/config.py
Config._parse_normalizations
def _parse_normalizations(self, normalizations): """Returns a list of parsed normalizations. Iterates over a list of normalizations, removing those not correctly defined. It also transform complex items to have a common format (list of tuples and strings). Args: normalizations: List of normalizations to parse. Returns: A list of normalizations after being parsed and curated. """ parsed_normalizations = [] if isinstance(normalizations, list): for item in normalizations: normalization = self._parse_normalization(item) if normalization: parsed_normalizations.append(normalization) else: raise ConfigError('List expected. Found %s' % type(normalizations)) return parsed_normalizations
python
def _parse_normalizations(self, normalizations): """Returns a list of parsed normalizations. Iterates over a list of normalizations, removing those not correctly defined. It also transform complex items to have a common format (list of tuples and strings). Args: normalizations: List of normalizations to parse. Returns: A list of normalizations after being parsed and curated. """ parsed_normalizations = [] if isinstance(normalizations, list): for item in normalizations: normalization = self._parse_normalization(item) if normalization: parsed_normalizations.append(normalization) else: raise ConfigError('List expected. Found %s' % type(normalizations)) return parsed_normalizations
[ "def", "_parse_normalizations", "(", "self", ",", "normalizations", ")", ":", "parsed_normalizations", "=", "[", "]", "if", "isinstance", "(", "normalizations", ",", "list", ")", ":", "for", "item", "in", "normalizations", ":", "normalization", "=", "self", ".", "_parse_normalization", "(", "item", ")", "if", "normalization", ":", "parsed_normalizations", ".", "append", "(", "normalization", ")", "else", ":", "raise", "ConfigError", "(", "'List expected. Found %s'", "%", "type", "(", "normalizations", ")", ")", "return", "parsed_normalizations" ]
Returns a list of parsed normalizations. Iterates over a list of normalizations, removing those not correctly defined. It also transform complex items to have a common format (list of tuples and strings). Args: normalizations: List of normalizations to parse. Returns: A list of normalizations after being parsed and curated.
[ "Returns", "a", "list", "of", "parsed", "normalizations", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/config.py#L107-L130
train
davidmogar/cucco
cucco/logging.py
initialize_logger
def initialize_logger(debug): """Set up logger to be used by the library. Args: debug: Wheter to use debug level or not. Returns: A logger ready to be used. """ level = logging.DEBUG if debug else logging.INFO logger = logging.getLogger('cucco') logger.setLevel(level) formatter = logging.Formatter('%(asctime)s %(levelname).1s %(message)s') console_handler = logging.StreamHandler() console_handler.setLevel(level) console_handler.setFormatter(formatter) logger.addHandler(console_handler) return logger
python
def initialize_logger(debug): """Set up logger to be used by the library. Args: debug: Wheter to use debug level or not. Returns: A logger ready to be used. """ level = logging.DEBUG if debug else logging.INFO logger = logging.getLogger('cucco') logger.setLevel(level) formatter = logging.Formatter('%(asctime)s %(levelname).1s %(message)s') console_handler = logging.StreamHandler() console_handler.setLevel(level) console_handler.setFormatter(formatter) logger.addHandler(console_handler) return logger
[ "def", "initialize_logger", "(", "debug", ")", ":", "level", "=", "logging", ".", "DEBUG", "if", "debug", "else", "logging", ".", "INFO", "logger", "=", "logging", ".", "getLogger", "(", "'cucco'", ")", "logger", ".", "setLevel", "(", "level", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s %(levelname).1s %(message)s'", ")", "console_handler", "=", "logging", ".", "StreamHandler", "(", ")", "console_handler", ".", "setLevel", "(", "level", ")", "console_handler", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "addHandler", "(", "console_handler", ")", "return", "logger" ]
Set up logger to be used by the library. Args: debug: Wheter to use debug level or not. Returns: A logger ready to be used.
[ "Set", "up", "logger", "to", "be", "used", "by", "the", "library", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/logging.py#L5-L23
train
davidmogar/cucco
cucco/cli.py
batch
def batch(ctx, path, recursive, watch): """ Normalize files in a path. Apply normalizations over all files found in a given path. The normalizations applied will be those defined in the config file. If no config is specified, the default normalizations will be used. """ batch = Batch(ctx.obj['config'], ctx.obj['cucco']) if os.path.exists(path): if watch: batch.watch(path, recursive) elif os.path.isfile(path): batch.process_file(path) else: batch.process_files(path, recursive) else: click.echo('Error: Specified path doesn\'t exists', err=True) sys.exit(-1)
python
def batch(ctx, path, recursive, watch): """ Normalize files in a path. Apply normalizations over all files found in a given path. The normalizations applied will be those defined in the config file. If no config is specified, the default normalizations will be used. """ batch = Batch(ctx.obj['config'], ctx.obj['cucco']) if os.path.exists(path): if watch: batch.watch(path, recursive) elif os.path.isfile(path): batch.process_file(path) else: batch.process_files(path, recursive) else: click.echo('Error: Specified path doesn\'t exists', err=True) sys.exit(-1)
[ "def", "batch", "(", "ctx", ",", "path", ",", "recursive", ",", "watch", ")", ":", "batch", "=", "Batch", "(", "ctx", ".", "obj", "[", "'config'", "]", ",", "ctx", ".", "obj", "[", "'cucco'", "]", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "watch", ":", "batch", ".", "watch", "(", "path", ",", "recursive", ")", "elif", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "batch", ".", "process_file", "(", "path", ")", "else", ":", "batch", ".", "process_files", "(", "path", ",", "recursive", ")", "else", ":", "click", ".", "echo", "(", "'Error: Specified path doesn\\'t exists'", ",", "err", "=", "True", ")", "sys", ".", "exit", "(", "-", "1", ")" ]
Normalize files in a path. Apply normalizations over all files found in a given path. The normalizations applied will be those defined in the config file. If no config is specified, the default normalizations will be used.
[ "Normalize", "files", "in", "a", "path", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cli.py#L23-L43
train
davidmogar/cucco
cucco/cli.py
normalize
def normalize(ctx, text): """ Normalize text or piped input. Normalize text passed as an argument to this command using the specified config (default values if --config option is not used). Pipes can be used along this command to process the output of another cli. This is the default behaviour when no text is defined. """ if text: click.echo(ctx.obj['cucco'].normalize(text)) else: for line in sys.stdin: click.echo(ctx.obj['cucco'].normalize(line))
python
def normalize(ctx, text): """ Normalize text or piped input. Normalize text passed as an argument to this command using the specified config (default values if --config option is not used). Pipes can be used along this command to process the output of another cli. This is the default behaviour when no text is defined. """ if text: click.echo(ctx.obj['cucco'].normalize(text)) else: for line in sys.stdin: click.echo(ctx.obj['cucco'].normalize(line))
[ "def", "normalize", "(", "ctx", ",", "text", ")", ":", "if", "text", ":", "click", ".", "echo", "(", "ctx", ".", "obj", "[", "'cucco'", "]", ".", "normalize", "(", "text", ")", ")", "else", ":", "for", "line", "in", "sys", ".", "stdin", ":", "click", ".", "echo", "(", "ctx", ".", "obj", "[", "'cucco'", "]", ".", "normalize", "(", "line", ")", ")" ]
Normalize text or piped input. Normalize text passed as an argument to this command using the specified config (default values if --config option is not used). Pipes can be used along this command to process the output of another cli. This is the default behaviour when no text is defined.
[ "Normalize", "text", "or", "piped", "input", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cli.py#L48-L64
train
davidmogar/cucco
cucco/cli.py
cli
def cli(ctx, config, debug, language, verbose): """ Cucco allows to apply normalizations to a given text or file. This normalizations include, among others, removal of accent marks, stop words an extra white spaces, replacement of punctuation symbols, emails, emojis, etc. For more info on how to use and configure Cucco, check the project website at https://cucco.io. """ ctx.obj = {} try: ctx.obj['config'] = Config(normalizations=config, language=language, debug=debug, verbose=verbose) except ConfigError as e: click.echo(e.message) sys.exit(-1) ctx.obj['cucco'] = Cucco(ctx.obj['config'])
python
def cli(ctx, config, debug, language, verbose): """ Cucco allows to apply normalizations to a given text or file. This normalizations include, among others, removal of accent marks, stop words an extra white spaces, replacement of punctuation symbols, emails, emojis, etc. For more info on how to use and configure Cucco, check the project website at https://cucco.io. """ ctx.obj = {} try: ctx.obj['config'] = Config(normalizations=config, language=language, debug=debug, verbose=verbose) except ConfigError as e: click.echo(e.message) sys.exit(-1) ctx.obj['cucco'] = Cucco(ctx.obj['config'])
[ "def", "cli", "(", "ctx", ",", "config", ",", "debug", ",", "language", ",", "verbose", ")", ":", "ctx", ".", "obj", "=", "{", "}", "try", ":", "ctx", ".", "obj", "[", "'config'", "]", "=", "Config", "(", "normalizations", "=", "config", ",", "language", "=", "language", ",", "debug", "=", "debug", ",", "verbose", "=", "verbose", ")", "except", "ConfigError", "as", "e", ":", "click", ".", "echo", "(", "e", ".", "message", ")", "sys", ".", "exit", "(", "-", "1", ")", "ctx", ".", "obj", "[", "'cucco'", "]", "=", "Cucco", "(", "ctx", ".", "obj", "[", "'config'", "]", ")" ]
Cucco allows to apply normalizations to a given text or file. This normalizations include, among others, removal of accent marks, stop words an extra white spaces, replacement of punctuation symbols, emails, emojis, etc. For more info on how to use and configure Cucco, check the project website at https://cucco.io.
[ "Cucco", "allows", "to", "apply", "normalizations", "to", "a", "given", "text", "or", "file", ".", "This", "normalizations", "include", "among", "others", "removal", "of", "accent", "marks", "stop", "words", "an", "extra", "white", "spaces", "replacement", "of", "punctuation", "symbols", "emails", "emojis", "etc", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cli.py#L77-L98
train
davidmogar/cucco
cucco/batch.py
files_generator
def files_generator(path, recursive): """Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively or not. Yields: A tuple for each file in the given path containing the path and the name of the file. """ if recursive: for (path, _, files) in os.walk(path): for file in files: if not file.endswith(BATCH_EXTENSION): yield (path, file) else: for file in os.listdir(path): if (os.path.isfile(os.path.join(path, file)) and not file.endswith(BATCH_EXTENSION)): yield (path, file)
python
def files_generator(path, recursive): """Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively or not. Yields: A tuple for each file in the given path containing the path and the name of the file. """ if recursive: for (path, _, files) in os.walk(path): for file in files: if not file.endswith(BATCH_EXTENSION): yield (path, file) else: for file in os.listdir(path): if (os.path.isfile(os.path.join(path, file)) and not file.endswith(BATCH_EXTENSION)): yield (path, file)
[ "def", "files_generator", "(", "path", ",", "recursive", ")", ":", "if", "recursive", ":", "for", "(", "path", ",", "_", ",", "files", ")", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "file", "in", "files", ":", "if", "not", "file", ".", "endswith", "(", "BATCH_EXTENSION", ")", ":", "yield", "(", "path", ",", "file", ")", "else", ":", "for", "file", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "(", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "file", ")", ")", "and", "not", "file", ".", "endswith", "(", "BATCH_EXTENSION", ")", ")", ":", "yield", "(", "path", ",", "file", ")" ]
Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively or not. Yields: A tuple for each file in the given path containing the path and the name of the file.
[ "Yield", "files", "found", "in", "a", "given", "path", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/batch.py#L11-L35
train
davidmogar/cucco
cucco/batch.py
Batch.process_file
def process_file(self, path): """Process a file applying normalizations. Get a file as input and generate a new file with the result of applying normalizations to every single line in the original file. The extension for the new file will be the one defined in BATCH_EXTENSION. Args: path: Path to the file. """ if self._config.verbose: self._logger.info('Processing file "%s"', path) output_path = '%s%s' % (path, BATCH_EXTENSION) with open(output_path, 'w') as file: for line in lines_generator(path): file.write('%s\n' % self._cucco.normalize( line.encode().decode('utf-8'))) self._logger.debug('Created file "%s"', output_path)
python
def process_file(self, path): """Process a file applying normalizations. Get a file as input and generate a new file with the result of applying normalizations to every single line in the original file. The extension for the new file will be the one defined in BATCH_EXTENSION. Args: path: Path to the file. """ if self._config.verbose: self._logger.info('Processing file "%s"', path) output_path = '%s%s' % (path, BATCH_EXTENSION) with open(output_path, 'w') as file: for line in lines_generator(path): file.write('%s\n' % self._cucco.normalize( line.encode().decode('utf-8'))) self._logger.debug('Created file "%s"', output_path)
[ "def", "process_file", "(", "self", ",", "path", ")", ":", "if", "self", ".", "_config", ".", "verbose", ":", "self", ".", "_logger", ".", "info", "(", "'Processing file \"%s\"'", ",", "path", ")", "output_path", "=", "'%s%s'", "%", "(", "path", ",", "BATCH_EXTENSION", ")", "with", "open", "(", "output_path", ",", "'w'", ")", "as", "file", ":", "for", "line", "in", "lines_generator", "(", "path", ")", ":", "file", ".", "write", "(", "'%s\\n'", "%", "self", ".", "_cucco", ".", "normalize", "(", "line", ".", "encode", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")", ")", "self", ".", "_logger", ".", "debug", "(", "'Created file \"%s\"'", ",", "output_path", ")" ]
Process a file applying normalizations. Get a file as input and generate a new file with the result of applying normalizations to every single line in the original file. The extension for the new file will be the one defined in BATCH_EXTENSION. Args: path: Path to the file.
[ "Process", "a", "file", "applying", "normalizations", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/batch.py#L76-L97
train
davidmogar/cucco
cucco/batch.py
Batch.process_files
def process_files(self, path, recursive=False): """Apply normalizations over all files in the given directory. Iterate over all files in a given directory. Normalizations will be applied to each file, storing the result in a new file. The extension for the new file will be the one defined in BATCH_EXTENSION. Args: path: Path to the directory. recursive: Whether to find files recursively or not. """ self._logger.info('Processing files in "%s"', path) for (path, file) in files_generator(path, recursive): if not file.endswith(BATCH_EXTENSION): self.process_file(os.path.join(path, file))
python
def process_files(self, path, recursive=False): """Apply normalizations over all files in the given directory. Iterate over all files in a given directory. Normalizations will be applied to each file, storing the result in a new file. The extension for the new file will be the one defined in BATCH_EXTENSION. Args: path: Path to the directory. recursive: Whether to find files recursively or not. """ self._logger.info('Processing files in "%s"', path) for (path, file) in files_generator(path, recursive): if not file.endswith(BATCH_EXTENSION): self.process_file(os.path.join(path, file))
[ "def", "process_files", "(", "self", ",", "path", ",", "recursive", "=", "False", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Processing files in \"%s\"'", ",", "path", ")", "for", "(", "path", ",", "file", ")", "in", "files_generator", "(", "path", ",", "recursive", ")", ":", "if", "not", "file", ".", "endswith", "(", "BATCH_EXTENSION", ")", ":", "self", ".", "process_file", "(", "os", ".", "path", ".", "join", "(", "path", ",", "file", ")", ")" ]
Apply normalizations over all files in the given directory. Iterate over all files in a given directory. Normalizations will be applied to each file, storing the result in a new file. The extension for the new file will be the one defined in BATCH_EXTENSION. Args: path: Path to the directory. recursive: Whether to find files recursively or not.
[ "Apply", "normalizations", "over", "all", "files", "in", "the", "given", "directory", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/batch.py#L99-L115
train
davidmogar/cucco
cucco/batch.py
Batch.stop_watching
def stop_watching(self): """Stop watching for files. Stop the observer started by watch function and finish thread life. """ self._watch = False if self._observer: self._logger.info('Stopping watcher') self._observer.stop() self._logger.info('Watcher stopped')
python
def stop_watching(self): """Stop watching for files. Stop the observer started by watch function and finish thread life. """ self._watch = False if self._observer: self._logger.info('Stopping watcher') self._observer.stop() self._logger.info('Watcher stopped')
[ "def", "stop_watching", "(", "self", ")", ":", "self", ".", "_watch", "=", "False", "if", "self", ".", "_observer", ":", "self", ".", "_logger", ".", "info", "(", "'Stopping watcher'", ")", "self", ".", "_observer", ".", "stop", "(", ")", "self", ".", "_logger", ".", "info", "(", "'Watcher stopped'", ")" ]
Stop watching for files. Stop the observer started by watch function and finish thread life.
[ "Stop", "watching", "for", "files", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/batch.py#L117-L128
train
davidmogar/cucco
cucco/batch.py
Batch.watch
def watch(self, path, recursive=False): """Watch for files in a directory and apply normalizations. Watch for new or changed files in a directory and apply normalizations over them. Args: path: Path to the directory. recursive: Whether to find files recursively or not. """ self._logger.info('Initializing watcher for path "%s"', path) handler = FileHandler(self) self._observer = Observer() self._observer.schedule(handler, path, recursive) self._logger.info('Starting watcher') self._observer.start() self._watch = True try: self._logger.info('Waiting for file events') while self._watch: time.sleep(1) except KeyboardInterrupt: # pragma: no cover self.stop_watching() self._observer.join()
python
def watch(self, path, recursive=False): """Watch for files in a directory and apply normalizations. Watch for new or changed files in a directory and apply normalizations over them. Args: path: Path to the directory. recursive: Whether to find files recursively or not. """ self._logger.info('Initializing watcher for path "%s"', path) handler = FileHandler(self) self._observer = Observer() self._observer.schedule(handler, path, recursive) self._logger.info('Starting watcher') self._observer.start() self._watch = True try: self._logger.info('Waiting for file events') while self._watch: time.sleep(1) except KeyboardInterrupt: # pragma: no cover self.stop_watching() self._observer.join()
[ "def", "watch", "(", "self", ",", "path", ",", "recursive", "=", "False", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Initializing watcher for path \"%s\"'", ",", "path", ")", "handler", "=", "FileHandler", "(", "self", ")", "self", ".", "_observer", "=", "Observer", "(", ")", "self", ".", "_observer", ".", "schedule", "(", "handler", ",", "path", ",", "recursive", ")", "self", ".", "_logger", ".", "info", "(", "'Starting watcher'", ")", "self", ".", "_observer", ".", "start", "(", ")", "self", ".", "_watch", "=", "True", "try", ":", "self", ".", "_logger", ".", "info", "(", "'Waiting for file events'", ")", "while", "self", ".", "_watch", ":", "time", ".", "sleep", "(", "1", ")", "except", "KeyboardInterrupt", ":", "# pragma: no cover", "self", ".", "stop_watching", "(", ")", "self", ".", "_observer", ".", "join", "(", ")" ]
Watch for files in a directory and apply normalizations. Watch for new or changed files in a directory and apply normalizations over them. Args: path: Path to the directory. recursive: Whether to find files recursively or not.
[ "Watch", "for", "files", "in", "a", "directory", "and", "apply", "normalizations", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/batch.py#L130-L157
train
davidmogar/cucco
cucco/batch.py
FileHandler._process_event
def _process_event(self, event): """Process received events. Process events received, applying normalization for those events referencing a new or changed file and only if it's not the result of a previous normalization. Args: event: Event to process. """ if (not event.is_directory and not event.src_path.endswith(BATCH_EXTENSION)): self._logger.info('Detected file change: %s', event.src_path) self._batch.process_file(event.src_path)
python
def _process_event(self, event): """Process received events. Process events received, applying normalization for those events referencing a new or changed file and only if it's not the result of a previous normalization. Args: event: Event to process. """ if (not event.is_directory and not event.src_path.endswith(BATCH_EXTENSION)): self._logger.info('Detected file change: %s', event.src_path) self._batch.process_file(event.src_path)
[ "def", "_process_event", "(", "self", ",", "event", ")", ":", "if", "(", "not", "event", ".", "is_directory", "and", "not", "event", ".", "src_path", ".", "endswith", "(", "BATCH_EXTENSION", ")", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Detected file change: %s'", ",", "event", ".", "src_path", ")", "self", ".", "_batch", ".", "process_file", "(", "event", ".", "src_path", ")" ]
Process received events. Process events received, applying normalization for those events referencing a new or changed file and only if it's not the result of a previous normalization. Args: event: Event to process.
[ "Process", "received", "events", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/batch.py#L175-L188
train
davidmogar/cucco
cucco/batch.py
FileHandler.on_created
def on_created(self, event): """Function called everytime a new file is created. Args: event: Event to process. """ self._logger.debug('Detected create event on watched path: %s', event.src_path) self._process_event(event)
python
def on_created(self, event): """Function called everytime a new file is created. Args: event: Event to process. """ self._logger.debug('Detected create event on watched path: %s', event.src_path) self._process_event(event)
[ "def", "on_created", "(", "self", ",", "event", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Detected create event on watched path: %s'", ",", "event", ".", "src_path", ")", "self", ".", "_process_event", "(", "event", ")" ]
Function called everytime a new file is created. Args: event: Event to process.
[ "Function", "called", "everytime", "a", "new", "file", "is", "created", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/batch.py#L190-L198
train
davidmogar/cucco
cucco/batch.py
FileHandler.on_modified
def on_modified(self, event): """Function called everytime a new file is modified. Args: event: Event to process. """ self._logger.debug('Detected modify event on watched path: %s', event.src_path) self._process_event(event)
python
def on_modified(self, event): """Function called everytime a new file is modified. Args: event: Event to process. """ self._logger.debug('Detected modify event on watched path: %s', event.src_path) self._process_event(event)
[ "def", "on_modified", "(", "self", ",", "event", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Detected modify event on watched path: %s'", ",", "event", ".", "src_path", ")", "self", ".", "_process_event", "(", "event", ")" ]
Function called everytime a new file is modified. Args: event: Event to process.
[ "Function", "called", "everytime", "a", "new", "file", "is", "modified", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/batch.py#L200-L208
train
davidmogar/cucco
cucco/cucco.py
Cucco._parse_normalizations
def _parse_normalizations(normalizations): """Parse and yield normalizations. Parse normalizations parameter that yield all normalizations and arguments found on it. Args: normalizations: List of normalizations. Yields: A tuple with a parsed normalization. The first item will contain the normalization name and the second will be a dict with the arguments to be used for the normalization. """ str_type = str if sys.version_info[0] > 2 else (str, unicode) for normalization in normalizations: yield (normalization, {}) if isinstance(normalization, str_type) else normalization
python
def _parse_normalizations(normalizations): """Parse and yield normalizations. Parse normalizations parameter that yield all normalizations and arguments found on it. Args: normalizations: List of normalizations. Yields: A tuple with a parsed normalization. The first item will contain the normalization name and the second will be a dict with the arguments to be used for the normalization. """ str_type = str if sys.version_info[0] > 2 else (str, unicode) for normalization in normalizations: yield (normalization, {}) if isinstance(normalization, str_type) else normalization
[ "def", "_parse_normalizations", "(", "normalizations", ")", ":", "str_type", "=", "str", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", "else", "(", "str", ",", "unicode", ")", "for", "normalization", "in", "normalizations", ":", "yield", "(", "normalization", ",", "{", "}", ")", "if", "isinstance", "(", "normalization", ",", "str_type", ")", "else", "normalization" ]
Parse and yield normalizations. Parse normalizations parameter that yield all normalizations and arguments found on it. Args: normalizations: List of normalizations. Yields: A tuple with a parsed normalization. The first item will contain the normalization name and the second will be a dict with the arguments to be used for the normalization.
[ "Parse", "and", "yield", "normalizations", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cucco.py#L65-L82
train
davidmogar/cucco
cucco/cucco.py
Cucco._parse_stop_words_file
def _parse_stop_words_file(self, path): """Load stop words from the given path. Parse the stop words file, saving each word found in it in a set for the language of the file. This language is obtained from the file name. If the file doesn't exist, the method will have no effect. Args: path: Path to the stop words file. Returns: A boolean indicating whether the file was loaded. """ language = None loaded = False if os.path.isfile(path): self._logger.debug('Loading stop words in %s', path) language = path.split('-')[-1] if not language in self.__stop_words: self.__stop_words[language] = set() with codecs.open(path, 'r', 'UTF-8') as file: loaded = True for word in file: self.__stop_words[language].add(word.strip()) return loaded
python
def _parse_stop_words_file(self, path): """Load stop words from the given path. Parse the stop words file, saving each word found in it in a set for the language of the file. This language is obtained from the file name. If the file doesn't exist, the method will have no effect. Args: path: Path to the stop words file. Returns: A boolean indicating whether the file was loaded. """ language = None loaded = False if os.path.isfile(path): self._logger.debug('Loading stop words in %s', path) language = path.split('-')[-1] if not language in self.__stop_words: self.__stop_words[language] = set() with codecs.open(path, 'r', 'UTF-8') as file: loaded = True for word in file: self.__stop_words[language].add(word.strip()) return loaded
[ "def", "_parse_stop_words_file", "(", "self", ",", "path", ")", ":", "language", "=", "None", "loaded", "=", "False", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Loading stop words in %s'", ",", "path", ")", "language", "=", "path", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", "if", "not", "language", "in", "self", ".", "__stop_words", ":", "self", ".", "__stop_words", "[", "language", "]", "=", "set", "(", ")", "with", "codecs", ".", "open", "(", "path", ",", "'r'", ",", "'UTF-8'", ")", "as", "file", ":", "loaded", "=", "True", "for", "word", "in", "file", ":", "self", ".", "__stop_words", "[", "language", "]", ".", "add", "(", "word", ".", "strip", "(", ")", ")", "return", "loaded" ]
Load stop words from the given path. Parse the stop words file, saving each word found in it in a set for the language of the file. This language is obtained from the file name. If the file doesn't exist, the method will have no effect. Args: path: Path to the stop words file. Returns: A boolean indicating whether the file was loaded.
[ "Load", "stop", "words", "from", "the", "given", "path", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cucco.py#L84-L114
train
davidmogar/cucco
cucco/cucco.py
Cucco.normalize
def normalize(self, text, normalizations=None): """Normalize a given text applying all normalizations. Normalizations to apply can be specified through a list of parameters and will be executed in that order. Args: text: The text to be processed. normalizations: List of normalizations to apply. Returns: The text normalized. """ for normalization, kwargs in self._parse_normalizations( normalizations or self._config.normalizations): try: text = getattr(self, normalization)(text, **kwargs) except AttributeError as e: self._logger.debug('Invalid normalization: %s', e) return text
python
def normalize(self, text, normalizations=None): """Normalize a given text applying all normalizations. Normalizations to apply can be specified through a list of parameters and will be executed in that order. Args: text: The text to be processed. normalizations: List of normalizations to apply. Returns: The text normalized. """ for normalization, kwargs in self._parse_normalizations( normalizations or self._config.normalizations): try: text = getattr(self, normalization)(text, **kwargs) except AttributeError as e: self._logger.debug('Invalid normalization: %s', e) return text
[ "def", "normalize", "(", "self", ",", "text", ",", "normalizations", "=", "None", ")", ":", "for", "normalization", ",", "kwargs", "in", "self", ".", "_parse_normalizations", "(", "normalizations", "or", "self", ".", "_config", ".", "normalizations", ")", ":", "try", ":", "text", "=", "getattr", "(", "self", ",", "normalization", ")", "(", "text", ",", "*", "*", "kwargs", ")", "except", "AttributeError", "as", "e", ":", "self", ".", "_logger", ".", "debug", "(", "'Invalid normalization: %s'", ",", "e", ")", "return", "text" ]
Normalize a given text applying all normalizations. Normalizations to apply can be specified through a list of parameters and will be executed in that order. Args: text: The text to be processed. normalizations: List of normalizations to apply. Returns: The text normalized.
[ "Normalize", "a", "given", "text", "applying", "all", "normalizations", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cucco.py#L116-L137
train
davidmogar/cucco
cucco/cucco.py
Cucco.remove_accent_marks
def remove_accent_marks(text, excluded=None): """Remove accent marks from input text. This function removes accent marks in the text, but leaves unicode characters defined in the 'excluded' parameter. Args: text: The text to be processed. excluded: Set of unicode characters to exclude. Returns: The text without accent marks. """ if excluded is None: excluded = set() return unicodedata.normalize( 'NFKC', ''.join( c for c in unicodedata.normalize( 'NFKD', text) if unicodedata.category(c) != 'Mn' or c in excluded))
python
def remove_accent_marks(text, excluded=None): """Remove accent marks from input text. This function removes accent marks in the text, but leaves unicode characters defined in the 'excluded' parameter. Args: text: The text to be processed. excluded: Set of unicode characters to exclude. Returns: The text without accent marks. """ if excluded is None: excluded = set() return unicodedata.normalize( 'NFKC', ''.join( c for c in unicodedata.normalize( 'NFKD', text) if unicodedata.category(c) != 'Mn' or c in excluded))
[ "def", "remove_accent_marks", "(", "text", ",", "excluded", "=", "None", ")", ":", "if", "excluded", "is", "None", ":", "excluded", "=", "set", "(", ")", "return", "unicodedata", ".", "normalize", "(", "'NFKC'", ",", "''", ".", "join", "(", "c", "for", "c", "in", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "text", ")", "if", "unicodedata", ".", "category", "(", "c", ")", "!=", "'Mn'", "or", "c", "in", "excluded", ")", ")" ]
Remove accent marks from input text. This function removes accent marks in the text, but leaves unicode characters defined in the 'excluded' parameter. Args: text: The text to be processed. excluded: Set of unicode characters to exclude. Returns: The text without accent marks.
[ "Remove", "accent", "marks", "from", "input", "text", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cucco.py#L140-L159
train
davidmogar/cucco
cucco/cucco.py
Cucco.replace_characters
def replace_characters(self, text, characters, replacement=''): """Remove characters from text. Removes custom characters from input text or replaces them with a string if specified. Args: text: The text to be processed. characters: Characters that will be replaced. replacement: New text that will replace the custom characters. Returns: The text without the given characters. """ if not characters: return text characters = ''.join(sorted(characters)) if characters in self._characters_regexes: characters_regex = self._characters_regexes[characters] else: characters_regex = re.compile("[%s]" % re.escape(characters)) self._characters_regexes[characters] = characters_regex return characters_regex.sub(replacement, text)
python
def replace_characters(self, text, characters, replacement=''): """Remove characters from text. Removes custom characters from input text or replaces them with a string if specified. Args: text: The text to be processed. characters: Characters that will be replaced. replacement: New text that will replace the custom characters. Returns: The text without the given characters. """ if not characters: return text characters = ''.join(sorted(characters)) if characters in self._characters_regexes: characters_regex = self._characters_regexes[characters] else: characters_regex = re.compile("[%s]" % re.escape(characters)) self._characters_regexes[characters] = characters_regex return characters_regex.sub(replacement, text)
[ "def", "replace_characters", "(", "self", ",", "text", ",", "characters", ",", "replacement", "=", "''", ")", ":", "if", "not", "characters", ":", "return", "text", "characters", "=", "''", ".", "join", "(", "sorted", "(", "characters", ")", ")", "if", "characters", "in", "self", ".", "_characters_regexes", ":", "characters_regex", "=", "self", ".", "_characters_regexes", "[", "characters", "]", "else", ":", "characters_regex", "=", "re", ".", "compile", "(", "\"[%s]\"", "%", "re", ".", "escape", "(", "characters", ")", ")", "self", ".", "_characters_regexes", "[", "characters", "]", "=", "characters_regex", "return", "characters_regex", ".", "sub", "(", "replacement", ",", "text", ")" ]
Remove characters from text. Removes custom characters from input text or replaces them with a string if specified. Args: text: The text to be processed. characters: Characters that will be replaced. replacement: New text that will replace the custom characters. Returns: The text without the given characters.
[ "Remove", "characters", "from", "text", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cucco.py#L202-L226
train
davidmogar/cucco
cucco/cucco.py
Cucco.replace_punctuation
def replace_punctuation(self, text, excluded=None, replacement=''): """Replace punctuation symbols in text. Removes punctuation from input text or replaces them with a string if specified. Characters replaced will be those in string.punctuation. Args: text: The text to be processed. excluded: Set of characters to exclude. replacement: New text that will replace punctuation. Returns: The text without punctuation. """ if excluded is None: excluded = set() elif not isinstance(excluded, set): excluded = set(excluded) punct = ''.join(self.__punctuation.difference(excluded)) return self.replace_characters( text, characters=punct, replacement=replacement)
python
def replace_punctuation(self, text, excluded=None, replacement=''): """Replace punctuation symbols in text. Removes punctuation from input text or replaces them with a string if specified. Characters replaced will be those in string.punctuation. Args: text: The text to be processed. excluded: Set of characters to exclude. replacement: New text that will replace punctuation. Returns: The text without punctuation. """ if excluded is None: excluded = set() elif not isinstance(excluded, set): excluded = set(excluded) punct = ''.join(self.__punctuation.difference(excluded)) return self.replace_characters( text, characters=punct, replacement=replacement)
[ "def", "replace_punctuation", "(", "self", ",", "text", ",", "excluded", "=", "None", ",", "replacement", "=", "''", ")", ":", "if", "excluded", "is", "None", ":", "excluded", "=", "set", "(", ")", "elif", "not", "isinstance", "(", "excluded", ",", "set", ")", ":", "excluded", "=", "set", "(", "excluded", ")", "punct", "=", "''", ".", "join", "(", "self", ".", "__punctuation", ".", "difference", "(", "excluded", ")", ")", "return", "self", ".", "replace_characters", "(", "text", ",", "characters", "=", "punct", ",", "replacement", "=", "replacement", ")" ]
Replace punctuation symbols in text. Removes punctuation from input text or replaces them with a string if specified. Characters replaced will be those in string.punctuation. Args: text: The text to be processed. excluded: Set of characters to exclude. replacement: New text that will replace punctuation. Returns: The text without punctuation.
[ "Replace", "punctuation", "symbols", "in", "text", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cucco.py#L276-L298
train
davidmogar/cucco
cucco/cucco.py
Cucco.replace_symbols
def replace_symbols( text, form='NFKD', excluded=None, replacement=''): """Replace symbols in text. Removes symbols from input text or replaces them with a string if specified. Args: text: The text to be processed. form: Unicode form. excluded: Set of unicode characters to exclude. replacement: New text that will replace symbols. Returns: The text without symbols. """ if excluded is None: excluded = set() categories = set(['Mn', 'Sc', 'Sk', 'Sm', 'So']) return ''.join(c if unicodedata.category(c) not in categories or c in excluded else replacement for c in unicodedata.normalize(form, text))
python
def replace_symbols( text, form='NFKD', excluded=None, replacement=''): """Replace symbols in text. Removes symbols from input text or replaces them with a string if specified. Args: text: The text to be processed. form: Unicode form. excluded: Set of unicode characters to exclude. replacement: New text that will replace symbols. Returns: The text without symbols. """ if excluded is None: excluded = set() categories = set(['Mn', 'Sc', 'Sk', 'Sm', 'So']) return ''.join(c if unicodedata.category(c) not in categories or c in excluded else replacement for c in unicodedata.normalize(form, text))
[ "def", "replace_symbols", "(", "text", ",", "form", "=", "'NFKD'", ",", "excluded", "=", "None", ",", "replacement", "=", "''", ")", ":", "if", "excluded", "is", "None", ":", "excluded", "=", "set", "(", ")", "categories", "=", "set", "(", "[", "'Mn'", ",", "'Sc'", ",", "'Sk'", ",", "'Sm'", ",", "'So'", "]", ")", "return", "''", ".", "join", "(", "c", "if", "unicodedata", ".", "category", "(", "c", ")", "not", "in", "categories", "or", "c", "in", "excluded", "else", "replacement", "for", "c", "in", "unicodedata", ".", "normalize", "(", "form", ",", "text", ")", ")" ]
Replace symbols in text. Removes symbols from input text or replaces them with a string if specified. Args: text: The text to be processed. form: Unicode form. excluded: Set of unicode characters to exclude. replacement: New text that will replace symbols. Returns: The text without symbols.
[ "Replace", "symbols", "in", "text", "." ]
e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cucco.py#L301-L326
train
tmr232/Sark
sark/graph.py
get_idb_graph
def get_idb_graph(): """Export IDB to a NetworkX graph. Use xrefs to and from functions to build a DiGraph containing all the functions in the IDB and all the links between them. The graph can later be used to perform analysis on the IDB. :return: nx.DiGraph() """ digraph = nx.DiGraph() for function in functions(): for xref in itertools.chain(function.xrefs_from, function.xrefs_to): frm = _try_get_function_start(xref.frm) to = _try_get_function_start(xref.to) digraph.add_edge(frm, to) return digraph
python
def get_idb_graph(): """Export IDB to a NetworkX graph. Use xrefs to and from functions to build a DiGraph containing all the functions in the IDB and all the links between them. The graph can later be used to perform analysis on the IDB. :return: nx.DiGraph() """ digraph = nx.DiGraph() for function in functions(): for xref in itertools.chain(function.xrefs_from, function.xrefs_to): frm = _try_get_function_start(xref.frm) to = _try_get_function_start(xref.to) digraph.add_edge(frm, to) return digraph
[ "def", "get_idb_graph", "(", ")", ":", "digraph", "=", "nx", ".", "DiGraph", "(", ")", "for", "function", "in", "functions", "(", ")", ":", "for", "xref", "in", "itertools", ".", "chain", "(", "function", ".", "xrefs_from", ",", "function", ".", "xrefs_to", ")", ":", "frm", "=", "_try_get_function_start", "(", "xref", ".", "frm", ")", "to", "=", "_try_get_function_start", "(", "xref", ".", "to", ")", "digraph", ".", "add_edge", "(", "frm", ",", "to", ")", "return", "digraph" ]
Export IDB to a NetworkX graph. Use xrefs to and from functions to build a DiGraph containing all the functions in the IDB and all the links between them. The graph can later be used to perform analysis on the IDB. :return: nx.DiGraph()
[ "Export", "IDB", "to", "a", "NetworkX", "graph", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/graph.py#L48-L66
train
tmr232/Sark
sark/code/instruction.py
OperandType.name
def name(self): """Name of the xref type.""" return self.TYPES.get(self._type, self.TYPES[idaapi.o_idpspec0])
python
def name(self): """Name of the xref type.""" return self.TYPES.get(self._type, self.TYPES[idaapi.o_idpspec0])
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "TYPES", ".", "get", "(", "self", ".", "_type", ",", "self", ".", "TYPES", "[", "idaapi", ".", "o_idpspec0", "]", ")" ]
Name of the xref type.
[ "Name", "of", "the", "xref", "type", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/instruction.py#L138-L140
train
tmr232/Sark
sark/code/instruction.py
Operand.reg
def reg(self): """Name of the register used in the operand.""" if self.type.is_displ or self.type.is_phrase: size = core.get_native_size() return base.get_register_name(self.reg_id, size) if self.type.is_reg: return base.get_register_name(self.reg_id, self.size) else: raise exceptions.SarkOperandWithoutReg("Operand does not have a register.")
python
def reg(self): """Name of the register used in the operand.""" if self.type.is_displ or self.type.is_phrase: size = core.get_native_size() return base.get_register_name(self.reg_id, size) if self.type.is_reg: return base.get_register_name(self.reg_id, self.size) else: raise exceptions.SarkOperandWithoutReg("Operand does not have a register.")
[ "def", "reg", "(", "self", ")", ":", "if", "self", ".", "type", ".", "is_displ", "or", "self", ".", "type", ".", "is_phrase", ":", "size", "=", "core", ".", "get_native_size", "(", ")", "return", "base", ".", "get_register_name", "(", "self", ".", "reg_id", ",", "size", ")", "if", "self", ".", "type", ".", "is_reg", ":", "return", "base", ".", "get_register_name", "(", "self", ".", "reg_id", ",", "self", ".", "size", ")", "else", ":", "raise", "exceptions", ".", "SarkOperandWithoutReg", "(", "\"Operand does not have a register.\"", ")" ]
Name of the register used in the operand.
[ "Name", "of", "the", "register", "used", "in", "the", "operand", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/instruction.py#L270-L280
train
tmr232/Sark
sark/code/instruction.py
Instruction.has_reg
def has_reg(self, reg_name): """Check if a register is used in the instruction.""" return any(operand.has_reg(reg_name) for operand in self.operands)
python
def has_reg(self, reg_name): """Check if a register is used in the instruction.""" return any(operand.has_reg(reg_name) for operand in self.operands)
[ "def", "has_reg", "(", "self", ",", "reg_name", ")", ":", "return", "any", "(", "operand", ".", "has_reg", "(", "reg_name", ")", "for", "operand", "in", "self", ".", "operands", ")" ]
Check if a register is used in the instruction.
[ "Check", "if", "a", "register", "is", "used", "in", "the", "instruction", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/instruction.py#L384-L386
train
tmr232/Sark
sark/code/instruction.py
Instruction.regs
def regs(self): """Names of all registers used by the instruction.""" regs = set() for operand in self.operands: if not operand.type.has_reg: continue regs.update(operand.regs) return regs
python
def regs(self): """Names of all registers used by the instruction.""" regs = set() for operand in self.operands: if not operand.type.has_reg: continue regs.update(operand.regs) return regs
[ "def", "regs", "(", "self", ")", ":", "regs", "=", "set", "(", ")", "for", "operand", "in", "self", ".", "operands", ":", "if", "not", "operand", ".", "type", ".", "has_reg", ":", "continue", "regs", ".", "update", "(", "operand", ".", "regs", ")", "return", "regs" ]
Names of all registers used by the instruction.
[ "Names", "of", "all", "registers", "used", "by", "the", "instruction", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/instruction.py#L397-L404
train
tmr232/Sark
sark/ui.py
NXGraph._pad
def _pad(self, text): """Pad the text.""" top_bottom = ("\n" * self._padding) + " " right_left = " " * self._padding * self.PAD_WIDTH return top_bottom + right_left + text + right_left + top_bottom
python
def _pad(self, text): """Pad the text.""" top_bottom = ("\n" * self._padding) + " " right_left = " " * self._padding * self.PAD_WIDTH return top_bottom + right_left + text + right_left + top_bottom
[ "def", "_pad", "(", "self", ",", "text", ")", ":", "top_bottom", "=", "(", "\"\\n\"", "*", "self", ".", "_padding", ")", "+", "\" \"", "right_left", "=", "\" \"", "*", "self", ".", "_padding", "*", "self", ".", "PAD_WIDTH", "return", "top_bottom", "+", "right_left", "+", "text", "+", "right_left", "+", "top_bottom" ]
Pad the text.
[ "Pad", "the", "text", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/ui.py#L234-L238
train
tmr232/Sark
sark/ui.py
NXGraph._make_unique_title
def _make_unique_title(self, title): """Make the title unique. Adds a counter to the title to prevent duplicates. Prior to IDA 6.8, two graphs with the same title could crash IDA. This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml). The code will not change for support of older versions and as it is more usable this way. """ unique_title = title for counter in itertools.count(): unique_title = "{}-{}".format(title, counter) if not idaapi.find_tform(unique_title): break return unique_title
python
def _make_unique_title(self, title): """Make the title unique. Adds a counter to the title to prevent duplicates. Prior to IDA 6.8, two graphs with the same title could crash IDA. This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml). The code will not change for support of older versions and as it is more usable this way. """ unique_title = title for counter in itertools.count(): unique_title = "{}-{}".format(title, counter) if not idaapi.find_tform(unique_title): break return unique_title
[ "def", "_make_unique_title", "(", "self", ",", "title", ")", ":", "unique_title", "=", "title", "for", "counter", "in", "itertools", ".", "count", "(", ")", ":", "unique_title", "=", "\"{}-{}\"", ".", "format", "(", "title", ",", "counter", ")", "if", "not", "idaapi", ".", "find_tform", "(", "unique_title", ")", ":", "break", "return", "unique_title" ]
Make the title unique. Adds a counter to the title to prevent duplicates. Prior to IDA 6.8, two graphs with the same title could crash IDA. This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml). The code will not change for support of older versions and as it is more usable this way.
[ "Make", "the", "title", "unique", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/ui.py#L240-L257
train
tmr232/Sark
sark/ui.py
NXGraph._get_handler
def _get_handler(self, node_id): """Get the handler of a given node.""" handler = self._get_attrs(node_id).get(self.HANDLER, self._default_handler) # Here we make sure the handler is an instance of `BasicNodeHandler` or inherited # types. While generally being bad Python practice, we still need it here as an # invalid handler can cause IDA to crash. if not isinstance(handler, BasicNodeHandler): idaapi.msg(("Invalid handler for node {}: {}. All handlers must inherit from" "`BasicNodeHandler`.").format(node_id, handler)) handler = self._default_handler return handler
python
def _get_handler(self, node_id): """Get the handler of a given node.""" handler = self._get_attrs(node_id).get(self.HANDLER, self._default_handler) # Here we make sure the handler is an instance of `BasicNodeHandler` or inherited # types. While generally being bad Python practice, we still need it here as an # invalid handler can cause IDA to crash. if not isinstance(handler, BasicNodeHandler): idaapi.msg(("Invalid handler for node {}: {}. All handlers must inherit from" "`BasicNodeHandler`.").format(node_id, handler)) handler = self._default_handler return handler
[ "def", "_get_handler", "(", "self", ",", "node_id", ")", ":", "handler", "=", "self", ".", "_get_attrs", "(", "node_id", ")", ".", "get", "(", "self", ".", "HANDLER", ",", "self", ".", "_default_handler", ")", "# Here we make sure the handler is an instance of `BasicNodeHandler` or inherited", "# types. While generally being bad Python practice, we still need it here as an", "# invalid handler can cause IDA to crash.", "if", "not", "isinstance", "(", "handler", ",", "BasicNodeHandler", ")", ":", "idaapi", ".", "msg", "(", "(", "\"Invalid handler for node {}: {}. All handlers must inherit from\"", "\"`BasicNodeHandler`.\"", ")", ".", "format", "(", "node_id", ",", "handler", ")", ")", "handler", "=", "self", ".", "_default_handler", "return", "handler" ]
Get the handler of a given node.
[ "Get", "the", "handler", "of", "a", "given", "node", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/ui.py#L259-L270
train
tmr232/Sark
sark/ui.py
NXGraph._OnNodeInfo
def _OnNodeInfo(self, node_id): """Sets the node info based on its attributes.""" handler, value, attrs = self._get_handling_triplet(node_id) frame_color = handler.on_frame_color(value, attrs) node_info = idaapi.node_info_t() if frame_color is not None: node_info.frame_color = frame_color flags = node_info.get_flags_for_valid() self.SetNodeInfo(node_id, node_info, flags)
python
def _OnNodeInfo(self, node_id): """Sets the node info based on its attributes.""" handler, value, attrs = self._get_handling_triplet(node_id) frame_color = handler.on_frame_color(value, attrs) node_info = idaapi.node_info_t() if frame_color is not None: node_info.frame_color = frame_color flags = node_info.get_flags_for_valid() self.SetNodeInfo(node_id, node_info, flags)
[ "def", "_OnNodeInfo", "(", "self", ",", "node_id", ")", ":", "handler", ",", "value", ",", "attrs", "=", "self", ".", "_get_handling_triplet", "(", "node_id", ")", "frame_color", "=", "handler", ".", "on_frame_color", "(", "value", ",", "attrs", ")", "node_info", "=", "idaapi", ".", "node_info_t", "(", ")", "if", "frame_color", "is", "not", "None", ":", "node_info", ".", "frame_color", "=", "frame_color", "flags", "=", "node_info", ".", "get_flags_for_valid", "(", ")", "self", ".", "SetNodeInfo", "(", "node_id", ",", "node_info", ",", "flags", ")" ]
Sets the node info based on its attributes.
[ "Sets", "the", "node", "info", "based", "on", "its", "attributes", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/ui.py#L284-L296
train
tmr232/Sark
sark/data.py
get_string
def get_string(ea): """Read the string at the given ea. This function uses IDA's string APIs and does not implement any special logic. """ # We get the item-head because the `GetStringType` function only works on the head of an item. string_type = idc.GetStringType(idaapi.get_item_head(ea)) if string_type is None: raise exceptions.SarkNoString("No string at 0x{:08X}".format(ea)) string = idc.GetString(ea, strtype=string_type) if not string: raise exceptions.SarkNoString("No string at 0x{:08X}".format(ea)) return string
python
def get_string(ea): """Read the string at the given ea. This function uses IDA's string APIs and does not implement any special logic. """ # We get the item-head because the `GetStringType` function only works on the head of an item. string_type = idc.GetStringType(idaapi.get_item_head(ea)) if string_type is None: raise exceptions.SarkNoString("No string at 0x{:08X}".format(ea)) string = idc.GetString(ea, strtype=string_type) if not string: raise exceptions.SarkNoString("No string at 0x{:08X}".format(ea)) return string
[ "def", "get_string", "(", "ea", ")", ":", "# We get the item-head because the `GetStringType` function only works on the head of an item.", "string_type", "=", "idc", ".", "GetStringType", "(", "idaapi", ".", "get_item_head", "(", "ea", ")", ")", "if", "string_type", "is", "None", ":", "raise", "exceptions", ".", "SarkNoString", "(", "\"No string at 0x{:08X}\"", ".", "format", "(", "ea", ")", ")", "string", "=", "idc", ".", "GetString", "(", "ea", ",", "strtype", "=", "string_type", ")", "if", "not", "string", ":", "raise", "exceptions", ".", "SarkNoString", "(", "\"No string at 0x{:08X}\"", ".", "format", "(", "ea", ")", ")", "return", "string" ]
Read the string at the given ea. This function uses IDA's string APIs and does not implement any special logic.
[ "Read", "the", "string", "at", "the", "given", "ea", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/data.py#L147-L163
train
tmr232/Sark
plugins/quick_copy.py
copy_current_file_offset
def copy_current_file_offset(): """Get the file-offset mapped to the current address.""" start, end = sark.get_selection() try: file_offset = sark.core.get_fileregion_offset(start) clipboard.copy("0x{:08X}".format(file_offset)) except sark.exceptions.NoFileOffset: message("The current address cannot be mapped to a valid offset of the input file.")
python
def copy_current_file_offset(): """Get the file-offset mapped to the current address.""" start, end = sark.get_selection() try: file_offset = sark.core.get_fileregion_offset(start) clipboard.copy("0x{:08X}".format(file_offset)) except sark.exceptions.NoFileOffset: message("The current address cannot be mapped to a valid offset of the input file.")
[ "def", "copy_current_file_offset", "(", ")", ":", "start", ",", "end", "=", "sark", ".", "get_selection", "(", ")", "try", ":", "file_offset", "=", "sark", ".", "core", ".", "get_fileregion_offset", "(", "start", ")", "clipboard", ".", "copy", "(", "\"0x{:08X}\"", ".", "format", "(", "file_offset", ")", ")", "except", "sark", ".", "exceptions", ".", "NoFileOffset", ":", "message", "(", "\"The current address cannot be mapped to a valid offset of the input file.\"", ")" ]
Get the file-offset mapped to the current address.
[ "Get", "the", "file", "-", "offset", "mapped", "to", "the", "current", "address", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/plugins/quick_copy.py#L17-L26
train
tmr232/Sark
sark/core.py
fix_addresses
def fix_addresses(start=None, end=None): """Set missing addresses to start and end of IDB. Take a start and end addresses. If an address is None or `BADADDR`, return start or end addresses of the IDB instead. Args start: Start EA. Use `None` to get IDB start. end: End EA. Use `None` to get IDB end. Returns: (start, end) """ if start in (None, idaapi.BADADDR): start = idaapi.cvar.inf.minEA if end in (None, idaapi.BADADDR): end = idaapi.cvar.inf.maxEA return start, end
python
def fix_addresses(start=None, end=None): """Set missing addresses to start and end of IDB. Take a start and end addresses. If an address is None or `BADADDR`, return start or end addresses of the IDB instead. Args start: Start EA. Use `None` to get IDB start. end: End EA. Use `None` to get IDB end. Returns: (start, end) """ if start in (None, idaapi.BADADDR): start = idaapi.cvar.inf.minEA if end in (None, idaapi.BADADDR): end = idaapi.cvar.inf.maxEA return start, end
[ "def", "fix_addresses", "(", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "start", "in", "(", "None", ",", "idaapi", ".", "BADADDR", ")", ":", "start", "=", "idaapi", ".", "cvar", ".", "inf", ".", "minEA", "if", "end", "in", "(", "None", ",", "idaapi", ".", "BADADDR", ")", ":", "end", "=", "idaapi", ".", "cvar", ".", "inf", ".", "maxEA", "return", "start", ",", "end" ]
Set missing addresses to start and end of IDB. Take a start and end addresses. If an address is None or `BADADDR`, return start or end addresses of the IDB instead. Args start: Start EA. Use `None` to get IDB start. end: End EA. Use `None` to get IDB end. Returns: (start, end)
[ "Set", "missing", "addresses", "to", "start", "and", "end", "of", "IDB", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/core.py#L81-L100
train
tmr232/Sark
sark/core.py
set_name
def set_name(address, name, anyway=False): """Set the name of an address. Sets the name of an address in IDA. If the name already exists, check the `anyway` parameter: True - Add `_COUNTER` to the name (default IDA behaviour) False - Raise an `exceptions.SarkErrorNameAlreadyExists` exception. Args address: The address to rename. name: The desired name. anyway: Set anyway or not. Defualt ``False``. """ success = idaapi.set_name(address, name, idaapi.SN_NOWARN | idaapi.SN_NOCHECK) if success: return if anyway: success = idaapi.do_name_anyway(address, name) if success: return raise exceptions.SarkSetNameFailed("Failed renaming 0x{:08X} to {!r}.".format(address, name)) raise exceptions.SarkErrorNameAlreadyExists( "Can't rename 0x{:08X}. Name {!r} already exists.".format(address, name))
python
def set_name(address, name, anyway=False): """Set the name of an address. Sets the name of an address in IDA. If the name already exists, check the `anyway` parameter: True - Add `_COUNTER` to the name (default IDA behaviour) False - Raise an `exceptions.SarkErrorNameAlreadyExists` exception. Args address: The address to rename. name: The desired name. anyway: Set anyway or not. Defualt ``False``. """ success = idaapi.set_name(address, name, idaapi.SN_NOWARN | idaapi.SN_NOCHECK) if success: return if anyway: success = idaapi.do_name_anyway(address, name) if success: return raise exceptions.SarkSetNameFailed("Failed renaming 0x{:08X} to {!r}.".format(address, name)) raise exceptions.SarkErrorNameAlreadyExists( "Can't rename 0x{:08X}. Name {!r} already exists.".format(address, name))
[ "def", "set_name", "(", "address", ",", "name", ",", "anyway", "=", "False", ")", ":", "success", "=", "idaapi", ".", "set_name", "(", "address", ",", "name", ",", "idaapi", ".", "SN_NOWARN", "|", "idaapi", ".", "SN_NOCHECK", ")", "if", "success", ":", "return", "if", "anyway", ":", "success", "=", "idaapi", ".", "do_name_anyway", "(", "address", ",", "name", ")", "if", "success", ":", "return", "raise", "exceptions", ".", "SarkSetNameFailed", "(", "\"Failed renaming 0x{:08X} to {!r}.\"", ".", "format", "(", "address", ",", "name", ")", ")", "raise", "exceptions", ".", "SarkErrorNameAlreadyExists", "(", "\"Can't rename 0x{:08X}. Name {!r} already exists.\"", ".", "format", "(", "address", ",", "name", ")", ")" ]
Set the name of an address. Sets the name of an address in IDA. If the name already exists, check the `anyway` parameter: True - Add `_COUNTER` to the name (default IDA behaviour) False - Raise an `exceptions.SarkErrorNameAlreadyExists` exception. Args address: The address to rename. name: The desired name. anyway: Set anyway or not. Defualt ``False``.
[ "Set", "the", "name", "of", "an", "address", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/core.py#L103-L130
train
tmr232/Sark
sark/core.py
is_same_function
def is_same_function(ea1, ea2): """Are both addresses in the same function?""" func1 = idaapi.get_func(ea1) func2 = idaapi.get_func(ea2) # This is bloated code. `None in (func1, func2)` will not work because of a # bug in IDAPython in the way functions are compared. if any(func is None for func in (func1, func2)): return False return func1.startEA == func2.startEA
python
def is_same_function(ea1, ea2): """Are both addresses in the same function?""" func1 = idaapi.get_func(ea1) func2 = idaapi.get_func(ea2) # This is bloated code. `None in (func1, func2)` will not work because of a # bug in IDAPython in the way functions are compared. if any(func is None for func in (func1, func2)): return False return func1.startEA == func2.startEA
[ "def", "is_same_function", "(", "ea1", ",", "ea2", ")", ":", "func1", "=", "idaapi", ".", "get_func", "(", "ea1", ")", "func2", "=", "idaapi", ".", "get_func", "(", "ea2", ")", "# This is bloated code. `None in (func1, func2)` will not work because of a", "# bug in IDAPython in the way functions are compared.", "if", "any", "(", "func", "is", "None", "for", "func", "in", "(", "func1", ",", "func2", ")", ")", ":", "return", "False", "return", "func1", ".", "startEA", "==", "func2", ".", "startEA" ]
Are both addresses in the same function?
[ "Are", "both", "addresses", "in", "the", "same", "function?" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/core.py#L133-L142
train
tmr232/Sark
sark/codeblock.py
get_nx_graph
def get_nx_graph(ea): """Convert an IDA flowchart to a NetworkX graph.""" nx_graph = networkx.DiGraph() func = idaapi.get_func(ea) flowchart = FlowChart(func) for block in flowchart: # Make sure all nodes are added (including edge-less nodes) nx_graph.add_node(block.startEA) for pred in block.preds(): nx_graph.add_edge(pred.startEA, block.startEA) for succ in block.succs(): nx_graph.add_edge(block.startEA, succ.startEA) return nx_graph
python
def get_nx_graph(ea): """Convert an IDA flowchart to a NetworkX graph.""" nx_graph = networkx.DiGraph() func = idaapi.get_func(ea) flowchart = FlowChart(func) for block in flowchart: # Make sure all nodes are added (including edge-less nodes) nx_graph.add_node(block.startEA) for pred in block.preds(): nx_graph.add_edge(pred.startEA, block.startEA) for succ in block.succs(): nx_graph.add_edge(block.startEA, succ.startEA) return nx_graph
[ "def", "get_nx_graph", "(", "ea", ")", ":", "nx_graph", "=", "networkx", ".", "DiGraph", "(", ")", "func", "=", "idaapi", ".", "get_func", "(", "ea", ")", "flowchart", "=", "FlowChart", "(", "func", ")", "for", "block", "in", "flowchart", ":", "# Make sure all nodes are added (including edge-less nodes)", "nx_graph", ".", "add_node", "(", "block", ".", "startEA", ")", "for", "pred", "in", "block", ".", "preds", "(", ")", ":", "nx_graph", ".", "add_edge", "(", "pred", ".", "startEA", ",", "block", ".", "startEA", ")", "for", "succ", "in", "block", ".", "succs", "(", ")", ":", "nx_graph", ".", "add_edge", "(", "block", ".", "startEA", ",", "succ", ".", "startEA", ")", "return", "nx_graph" ]
Convert an IDA flowchart to a NetworkX graph.
[ "Convert", "an", "IDA", "flowchart", "to", "a", "NetworkX", "graph", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/codeblock.py#L100-L114
train
tmr232/Sark
sark/codeblock.py
codeblocks
def codeblocks(start=None, end=None, full=True): """Get all `CodeBlock`s in a given range. Args: start - start address of the range. If `None` uses IDB start. end - end address of the range. If `None` uses IDB end. full - `True` is required to change node info (e.g. color). `False` causes faster iteration. """ if full: for function in functions(start, end): fc = FlowChart(f=function.func_t) for block in fc: yield block else: start, end = fix_addresses(start, end) for code_block in FlowChart(bounds=(start, end)): yield code_block
python
def codeblocks(start=None, end=None, full=True): """Get all `CodeBlock`s in a given range. Args: start - start address of the range. If `None` uses IDB start. end - end address of the range. If `None` uses IDB end. full - `True` is required to change node info (e.g. color). `False` causes faster iteration. """ if full: for function in functions(start, end): fc = FlowChart(f=function.func_t) for block in fc: yield block else: start, end = fix_addresses(start, end) for code_block in FlowChart(bounds=(start, end)): yield code_block
[ "def", "codeblocks", "(", "start", "=", "None", ",", "end", "=", "None", ",", "full", "=", "True", ")", ":", "if", "full", ":", "for", "function", "in", "functions", "(", "start", ",", "end", ")", ":", "fc", "=", "FlowChart", "(", "f", "=", "function", ".", "func_t", ")", "for", "block", "in", "fc", ":", "yield", "block", "else", ":", "start", ",", "end", "=", "fix_addresses", "(", "start", ",", "end", ")", "for", "code_block", "in", "FlowChart", "(", "bounds", "=", "(", "start", ",", "end", ")", ")", ":", "yield", "code_block" ]
Get all `CodeBlock`s in a given range. Args: start - start address of the range. If `None` uses IDB start. end - end address of the range. If `None` uses IDB end. full - `True` is required to change node info (e.g. color). `False` causes faster iteration.
[ "Get", "all", "CodeBlock", "s", "in", "a", "given", "range", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/codeblock.py#L117-L135
train
tmr232/Sark
sark/structure.py
struct_member_error
def struct_member_error(err, sid, name, offset, size): """Create and format a struct member exception. Args: err: The error value returned from struct member creation sid: The struct id name: The member name offset: Memeber offset size: Member size Returns: A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an informative message. """ exception, msg = STRUCT_ERROR_MAP[err] struct_name = idc.GetStrucName(sid) return exception(('AddStructMember(struct="{}", member="{}", offset={}, size={}) ' 'failed: {}').format( struct_name, name, offset, size, msg ))
python
def struct_member_error(err, sid, name, offset, size): """Create and format a struct member exception. Args: err: The error value returned from struct member creation sid: The struct id name: The member name offset: Memeber offset size: Member size Returns: A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an informative message. """ exception, msg = STRUCT_ERROR_MAP[err] struct_name = idc.GetStrucName(sid) return exception(('AddStructMember(struct="{}", member="{}", offset={}, size={}) ' 'failed: {}').format( struct_name, name, offset, size, msg ))
[ "def", "struct_member_error", "(", "err", ",", "sid", ",", "name", ",", "offset", ",", "size", ")", ":", "exception", ",", "msg", "=", "STRUCT_ERROR_MAP", "[", "err", "]", "struct_name", "=", "idc", ".", "GetStrucName", "(", "sid", ")", "return", "exception", "(", "(", "'AddStructMember(struct=\"{}\", member=\"{}\", offset={}, size={}) '", "'failed: {}'", ")", ".", "format", "(", "struct_name", ",", "name", ",", "offset", ",", "size", ",", "msg", ")", ")" ]
Create and format a struct member exception. Args: err: The error value returned from struct member creation sid: The struct id name: The member name offset: Memeber offset size: Member size Returns: A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an informative message.
[ "Create", "and", "format", "a", "struct", "member", "exception", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/structure.py#L33-L56
train
tmr232/Sark
sark/structure.py
create_struct
def create_struct(name): """Create a structure. Args: name: The structure's name Returns: The sturct ID Raises: exceptions.SarkStructAlreadyExists: A struct with the same name already exists exceptions.SarkCreationFailed: Struct creation failed """ sid = idc.GetStrucIdByName(name) if sid != idaapi.BADADDR: # The struct already exists. raise exceptions.SarkStructAlreadyExists("A struct names {!r} already exists.".format(name)) sid = idc.AddStrucEx(-1, name, 0) if sid == idaapi.BADADDR: raise exceptions.SarkStructCreationFailed("Struct creation failed.") return sid
python
def create_struct(name): """Create a structure. Args: name: The structure's name Returns: The sturct ID Raises: exceptions.SarkStructAlreadyExists: A struct with the same name already exists exceptions.SarkCreationFailed: Struct creation failed """ sid = idc.GetStrucIdByName(name) if sid != idaapi.BADADDR: # The struct already exists. raise exceptions.SarkStructAlreadyExists("A struct names {!r} already exists.".format(name)) sid = idc.AddStrucEx(-1, name, 0) if sid == idaapi.BADADDR: raise exceptions.SarkStructCreationFailed("Struct creation failed.") return sid
[ "def", "create_struct", "(", "name", ")", ":", "sid", "=", "idc", ".", "GetStrucIdByName", "(", "name", ")", "if", "sid", "!=", "idaapi", ".", "BADADDR", ":", "# The struct already exists.", "raise", "exceptions", ".", "SarkStructAlreadyExists", "(", "\"A struct names {!r} already exists.\"", ".", "format", "(", "name", ")", ")", "sid", "=", "idc", ".", "AddStrucEx", "(", "-", "1", ",", "name", ",", "0", ")", "if", "sid", "==", "idaapi", ".", "BADADDR", ":", "raise", "exceptions", ".", "SarkStructCreationFailed", "(", "\"Struct creation failed.\"", ")", "return", "sid" ]
Create a structure. Args: name: The structure's name Returns: The sturct ID Raises: exceptions.SarkStructAlreadyExists: A struct with the same name already exists exceptions.SarkCreationFailed: Struct creation failed
[ "Create", "a", "structure", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/structure.py#L59-L81
train
tmr232/Sark
sark/structure.py
get_struct
def get_struct(name): """Get a struct by it's name. Args: name: The name of the struct Returns: The struct's id Raises: exceptions.SarkStructNotFound: is the struct does not exist. """ sid = idc.GetStrucIdByName(name) if sid == idaapi.BADADDR: raise exceptions.SarkStructNotFound() return sid
python
def get_struct(name): """Get a struct by it's name. Args: name: The name of the struct Returns: The struct's id Raises: exceptions.SarkStructNotFound: is the struct does not exist. """ sid = idc.GetStrucIdByName(name) if sid == idaapi.BADADDR: raise exceptions.SarkStructNotFound() return sid
[ "def", "get_struct", "(", "name", ")", ":", "sid", "=", "idc", ".", "GetStrucIdByName", "(", "name", ")", "if", "sid", "==", "idaapi", ".", "BADADDR", ":", "raise", "exceptions", ".", "SarkStructNotFound", "(", ")", "return", "sid" ]
Get a struct by it's name. Args: name: The name of the struct Returns: The struct's id Raises: exceptions.SarkStructNotFound: is the struct does not exist.
[ "Get", "a", "struct", "by", "it", "s", "name", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/structure.py#L84-L100
train
tmr232/Sark
sark/structure.py
get_common_register
def get_common_register(start, end): """Get the register most commonly used in accessing structs. Access to is considered for every opcode that accesses memory in an offset from a register:: mov eax, [ebx + 5] For every access, the struct-referencing registers, in this case `ebx`, are counted. The most used one is returned. Args: start: The adderss to start at end: The address to finish at """ registers = defaultdict(int) for line in lines(start, end): insn = line.insn for operand in insn.operands: if not operand.type.has_phrase: continue if not operand.base: continue register_name = operand.base registers[register_name] += 1 return max(registers.iteritems(), key=operator.itemgetter(1))[0]
python
def get_common_register(start, end): """Get the register most commonly used in accessing structs. Access to is considered for every opcode that accesses memory in an offset from a register:: mov eax, [ebx + 5] For every access, the struct-referencing registers, in this case `ebx`, are counted. The most used one is returned. Args: start: The adderss to start at end: The address to finish at """ registers = defaultdict(int) for line in lines(start, end): insn = line.insn for operand in insn.operands: if not operand.type.has_phrase: continue if not operand.base: continue register_name = operand.base registers[register_name] += 1 return max(registers.iteritems(), key=operator.itemgetter(1))[0]
[ "def", "get_common_register", "(", "start", ",", "end", ")", ":", "registers", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "lines", "(", "start", ",", "end", ")", ":", "insn", "=", "line", ".", "insn", "for", "operand", "in", "insn", ".", "operands", ":", "if", "not", "operand", ".", "type", ".", "has_phrase", ":", "continue", "if", "not", "operand", ".", "base", ":", "continue", "register_name", "=", "operand", ".", "base", "registers", "[", "register_name", "]", "+=", "1", "return", "max", "(", "registers", ".", "iteritems", "(", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ")", "[", "0", "]" ]
Get the register most commonly used in accessing structs. Access to is considered for every opcode that accesses memory in an offset from a register:: mov eax, [ebx + 5] For every access, the struct-referencing registers, in this case `ebx`, are counted. The most used one is returned. Args: start: The adderss to start at end: The address to finish at
[ "Get", "the", "register", "most", "commonly", "used", "in", "accessing", "structs", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/structure.py#L143-L173
train
tmr232/Sark
sark/enum.py
_enum_member_error
def _enum_member_error(err, eid, name, value, bitmask): """Format enum member error.""" exception, msg = ENUM_ERROR_MAP[err] enum_name = idaapi.get_enum_name(eid) return exception(('add_enum_member(enum="{}", member="{}", value={}, bitmask=0x{:08X}) ' 'failed: {}').format( enum_name, name, value, bitmask, msg ))
python
def _enum_member_error(err, eid, name, value, bitmask): """Format enum member error.""" exception, msg = ENUM_ERROR_MAP[err] enum_name = idaapi.get_enum_name(eid) return exception(('add_enum_member(enum="{}", member="{}", value={}, bitmask=0x{:08X}) ' 'failed: {}').format( enum_name, name, value, bitmask, msg ))
[ "def", "_enum_member_error", "(", "err", ",", "eid", ",", "name", ",", "value", ",", "bitmask", ")", ":", "exception", ",", "msg", "=", "ENUM_ERROR_MAP", "[", "err", "]", "enum_name", "=", "idaapi", ".", "get_enum_name", "(", "eid", ")", "return", "exception", "(", "(", "'add_enum_member(enum=\"{}\", member=\"{}\", value={}, bitmask=0x{:08X}) '", "'failed: {}'", ")", ".", "format", "(", "enum_name", ",", "name", ",", "value", ",", "bitmask", ",", "msg", ")", ")" ]
Format enum member error.
[ "Format", "enum", "member", "error", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L21-L32
train
tmr232/Sark
sark/enum.py
_get_enum
def _get_enum(name): """Get an existing enum ID""" eid = idaapi.get_enum(name) if eid == idaapi.BADADDR: raise exceptions.EnumNotFound('Enum "{}" does not exist.'.format(name)) return eid
python
def _get_enum(name): """Get an existing enum ID""" eid = idaapi.get_enum(name) if eid == idaapi.BADADDR: raise exceptions.EnumNotFound('Enum "{}" does not exist.'.format(name)) return eid
[ "def", "_get_enum", "(", "name", ")", ":", "eid", "=", "idaapi", ".", "get_enum", "(", "name", ")", "if", "eid", "==", "idaapi", ".", "BADADDR", ":", "raise", "exceptions", ".", "EnumNotFound", "(", "'Enum \"{}\" does not exist.'", ".", "format", "(", "name", ")", ")", "return", "eid" ]
Get an existing enum ID
[ "Get", "an", "existing", "enum", "ID" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L35-L40
train
tmr232/Sark
sark/enum.py
add_enum
def add_enum(name=None, index=None, flags=idaapi.hexflag(), bitfield=False): """Create a new enum. Args: name: Name of the enum to create. index: The index of the enum. Leave at default to append the enum as the last enum. flags: Enum type flags. bitfield: Is the enum a bitfield. Returns: An `Enum` object. """ if name is not None: with ignored(exceptions.EnumNotFound): _get_enum(name) raise exceptions.EnumAlreadyExists() if index is None or index < 0: index = idaapi.get_enum_qty() eid = idaapi.add_enum(index, name, flags) if eid == idaapi.BADADDR: raise exceptions.EnumCreationFailed('Failed creating enum "{}"'.format(name)) if bitfield: idaapi.set_enum_bf(eid, bitfield) return Enum(eid=eid)
python
def add_enum(name=None, index=None, flags=idaapi.hexflag(), bitfield=False): """Create a new enum. Args: name: Name of the enum to create. index: The index of the enum. Leave at default to append the enum as the last enum. flags: Enum type flags. bitfield: Is the enum a bitfield. Returns: An `Enum` object. """ if name is not None: with ignored(exceptions.EnumNotFound): _get_enum(name) raise exceptions.EnumAlreadyExists() if index is None or index < 0: index = idaapi.get_enum_qty() eid = idaapi.add_enum(index, name, flags) if eid == idaapi.BADADDR: raise exceptions.EnumCreationFailed('Failed creating enum "{}"'.format(name)) if bitfield: idaapi.set_enum_bf(eid, bitfield) return Enum(eid=eid)
[ "def", "add_enum", "(", "name", "=", "None", ",", "index", "=", "None", ",", "flags", "=", "idaapi", ".", "hexflag", "(", ")", ",", "bitfield", "=", "False", ")", ":", "if", "name", "is", "not", "None", ":", "with", "ignored", "(", "exceptions", ".", "EnumNotFound", ")", ":", "_get_enum", "(", "name", ")", "raise", "exceptions", ".", "EnumAlreadyExists", "(", ")", "if", "index", "is", "None", "or", "index", "<", "0", ":", "index", "=", "idaapi", ".", "get_enum_qty", "(", ")", "eid", "=", "idaapi", ".", "add_enum", "(", "index", ",", "name", ",", "flags", ")", "if", "eid", "==", "idaapi", ".", "BADADDR", ":", "raise", "exceptions", ".", "EnumCreationFailed", "(", "'Failed creating enum \"{}\"'", ".", "format", "(", "name", ")", ")", "if", "bitfield", ":", "idaapi", ".", "set_enum_bf", "(", "eid", ",", "bitfield", ")", "return", "Enum", "(", "eid", "=", "eid", ")" ]
Create a new enum. Args: name: Name of the enum to create. index: The index of the enum. Leave at default to append the enum as the last enum. flags: Enum type flags. bitfield: Is the enum a bitfield. Returns: An `Enum` object.
[ "Create", "a", "new", "enum", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L43-L71
train
tmr232/Sark
sark/enum.py
_add_enum_member
def _add_enum_member(enum, name, value, bitmask=DEFMASK): """Add an enum member.""" error = idaapi.add_enum_member(enum, name, value, bitmask) if error: raise _enum_member_error(error, enum, name, value, bitmask)
python
def _add_enum_member(enum, name, value, bitmask=DEFMASK): """Add an enum member.""" error = idaapi.add_enum_member(enum, name, value, bitmask) if error: raise _enum_member_error(error, enum, name, value, bitmask)
[ "def", "_add_enum_member", "(", "enum", ",", "name", ",", "value", ",", "bitmask", "=", "DEFMASK", ")", ":", "error", "=", "idaapi", ".", "add_enum_member", "(", "enum", ",", "name", ",", "value", ",", "bitmask", ")", "if", "error", ":", "raise", "_enum_member_error", "(", "error", ",", "enum", ",", "name", ",", "value", ",", "bitmask", ")" ]
Add an enum member.
[ "Add", "an", "enum", "member", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L79-L84
train
tmr232/Sark
sark/enum.py
_iter_bitmasks
def _iter_bitmasks(eid): """Iterate all bitmasks in a given enum. Note that while `DEFMASK` indicates no-more-bitmasks, it is also a valid bitmask value. The only way to tell if it exists is when iterating the serials. """ bitmask = idaapi.get_first_bmask(eid) yield bitmask while bitmask != DEFMASK: bitmask = idaapi.get_next_bmask(eid, bitmask) yield bitmask
python
def _iter_bitmasks(eid): """Iterate all bitmasks in a given enum. Note that while `DEFMASK` indicates no-more-bitmasks, it is also a valid bitmask value. The only way to tell if it exists is when iterating the serials. """ bitmask = idaapi.get_first_bmask(eid) yield bitmask while bitmask != DEFMASK: bitmask = idaapi.get_next_bmask(eid, bitmask) yield bitmask
[ "def", "_iter_bitmasks", "(", "eid", ")", ":", "bitmask", "=", "idaapi", ".", "get_first_bmask", "(", "eid", ")", "yield", "bitmask", "while", "bitmask", "!=", "DEFMASK", ":", "bitmask", "=", "idaapi", ".", "get_next_bmask", "(", "eid", ",", "bitmask", ")", "yield", "bitmask" ]
Iterate all bitmasks in a given enum. Note that while `DEFMASK` indicates no-more-bitmasks, it is also a valid bitmask value. The only way to tell if it exists is when iterating the serials.
[ "Iterate", "all", "bitmasks", "in", "a", "given", "enum", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L352-L365
train
tmr232/Sark
sark/enum.py
_iter_enum_member_values
def _iter_enum_member_values(eid, bitmask): """Iterate member values with given bitmask inside the enum Note that `DEFMASK` can either indicate end-of-values or a valid value. Iterate serials to tell apart. """ value = idaapi.get_first_enum_member(eid, bitmask) yield value while value != DEFMASK: value = idaapi.get_next_enum_member(eid, value, bitmask) yield value
python
def _iter_enum_member_values(eid, bitmask): """Iterate member values with given bitmask inside the enum Note that `DEFMASK` can either indicate end-of-values or a valid value. Iterate serials to tell apart. """ value = idaapi.get_first_enum_member(eid, bitmask) yield value while value != DEFMASK: value = idaapi.get_next_enum_member(eid, value, bitmask) yield value
[ "def", "_iter_enum_member_values", "(", "eid", ",", "bitmask", ")", ":", "value", "=", "idaapi", ".", "get_first_enum_member", "(", "eid", ",", "bitmask", ")", "yield", "value", "while", "value", "!=", "DEFMASK", ":", "value", "=", "idaapi", ".", "get_next_enum_member", "(", "eid", ",", "value", ",", "bitmask", ")", "yield", "value" ]
Iterate member values with given bitmask inside the enum Note that `DEFMASK` can either indicate end-of-values or a valid value. Iterate serials to tell apart.
[ "Iterate", "member", "values", "with", "given", "bitmask", "inside", "the", "enum" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L368-L379
train
tmr232/Sark
sark/enum.py
_iter_serial_enum_member
def _iter_serial_enum_member(eid, value, bitmask): """Iterate serial and CID of enum members with given value and bitmask. Here only valid values are returned, as `idaapi.BADNODE` always indicates an invalid member. """ cid, serial = idaapi.get_first_serial_enum_member(eid, value, bitmask) while cid != idaapi.BADNODE: yield cid, serial cid, serial = idaapi.get_next_serial_enum_member(cid, serial)
python
def _iter_serial_enum_member(eid, value, bitmask): """Iterate serial and CID of enum members with given value and bitmask. Here only valid values are returned, as `idaapi.BADNODE` always indicates an invalid member. """ cid, serial = idaapi.get_first_serial_enum_member(eid, value, bitmask) while cid != idaapi.BADNODE: yield cid, serial cid, serial = idaapi.get_next_serial_enum_member(cid, serial)
[ "def", "_iter_serial_enum_member", "(", "eid", ",", "value", ",", "bitmask", ")", ":", "cid", ",", "serial", "=", "idaapi", ".", "get_first_serial_enum_member", "(", "eid", ",", "value", ",", "bitmask", ")", "while", "cid", "!=", "idaapi", ".", "BADNODE", ":", "yield", "cid", ",", "serial", "cid", ",", "serial", "=", "idaapi", ".", "get_next_serial_enum_member", "(", "cid", ",", "serial", ")" ]
Iterate serial and CID of enum members with given value and bitmask. Here only valid values are returned, as `idaapi.BADNODE` always indicates an invalid member.
[ "Iterate", "serial", "and", "CID", "of", "enum", "members", "with", "given", "value", "and", "bitmask", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L382-L391
train
tmr232/Sark
sark/enum.py
_iter_enum_constant_ids
def _iter_enum_constant_ids(eid): """Iterate the constant IDs of all members in the given enum""" for bitmask in _iter_bitmasks(eid): for value in _iter_enum_member_values(eid, bitmask): for cid, serial in _iter_serial_enum_member(eid, value, bitmask): yield cid
python
def _iter_enum_constant_ids(eid): """Iterate the constant IDs of all members in the given enum""" for bitmask in _iter_bitmasks(eid): for value in _iter_enum_member_values(eid, bitmask): for cid, serial in _iter_serial_enum_member(eid, value, bitmask): yield cid
[ "def", "_iter_enum_constant_ids", "(", "eid", ")", ":", "for", "bitmask", "in", "_iter_bitmasks", "(", "eid", ")", ":", "for", "value", "in", "_iter_enum_member_values", "(", "eid", ",", "bitmask", ")", ":", "for", "cid", ",", "serial", "in", "_iter_serial_enum_member", "(", "eid", ",", "value", ",", "bitmask", ")", ":", "yield", "cid" ]
Iterate the constant IDs of all members in the given enum
[ "Iterate", "the", "constant", "IDs", "of", "all", "members", "in", "the", "given", "enum" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L394-L399
train
tmr232/Sark
sark/enum.py
EnumMembers.add
def add(self, name, value, bitmask=DEFMASK): """Add an enum member Args: name: Name of the member value: value of the member bitmask: bitmask. Only use if enum is a bitfield. """ _add_enum_member(self._eid, name, value, bitmask)
python
def add(self, name, value, bitmask=DEFMASK): """Add an enum member Args: name: Name of the member value: value of the member bitmask: bitmask. Only use if enum is a bitfield. """ _add_enum_member(self._eid, name, value, bitmask)
[ "def", "add", "(", "self", ",", "name", ",", "value", ",", "bitmask", "=", "DEFMASK", ")", ":", "_add_enum_member", "(", "self", ".", "_eid", ",", "name", ",", "value", ",", "bitmask", ")" ]
Add an enum member Args: name: Name of the member value: value of the member bitmask: bitmask. Only use if enum is a bitfield.
[ "Add", "an", "enum", "member" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L141-L149
train
tmr232/Sark
sark/enum.py
EnumMembers.remove
def remove(self, name): """Remove an enum member by name""" member = self[name] serial = member.serial value = member.value bmask = member.bmask success = idaapi.del_enum_member(self._eid, value, serial, bmask) if not success: raise exceptions.CantDeleteEnumMember("Can't delete enum member {!r}.".format(name))
python
def remove(self, name): """Remove an enum member by name""" member = self[name] serial = member.serial value = member.value bmask = member.bmask success = idaapi.del_enum_member(self._eid, value, serial, bmask) if not success: raise exceptions.CantDeleteEnumMember("Can't delete enum member {!r}.".format(name))
[ "def", "remove", "(", "self", ",", "name", ")", ":", "member", "=", "self", "[", "name", "]", "serial", "=", "member", ".", "serial", "value", "=", "member", ".", "value", "bmask", "=", "member", ".", "bmask", "success", "=", "idaapi", ".", "del_enum_member", "(", "self", ".", "_eid", ",", "value", ",", "serial", ",", "bmask", ")", "if", "not", "success", ":", "raise", "exceptions", ".", "CantDeleteEnumMember", "(", "\"Can't delete enum member {!r}.\"", ".", "format", "(", "name", ")", ")" ]
Remove an enum member by name
[ "Remove", "an", "enum", "member", "by", "name" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L158-L167
train
tmr232/Sark
sark/enum.py
Enum.name
def name(self, name): """Set the enum name.""" success = idaapi.set_enum_name(self.eid, name) if not success: raise exceptions.CantRenameEnum("Cant rename enum {!r} to {!r}.".format(self.name, name))
python
def name(self, name): """Set the enum name.""" success = idaapi.set_enum_name(self.eid, name) if not success: raise exceptions.CantRenameEnum("Cant rename enum {!r} to {!r}.".format(self.name, name))
[ "def", "name", "(", "self", ",", "name", ")", ":", "success", "=", "idaapi", ".", "set_enum_name", "(", "self", ".", "eid", ",", "name", ")", "if", "not", "success", ":", "raise", "exceptions", ".", "CantRenameEnum", "(", "\"Cant rename enum {!r} to {!r}.\"", ".", "format", "(", "self", ".", "name", ",", "name", ")", ")" ]
Set the enum name.
[ "Set", "the", "enum", "name", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L201-L205
train
tmr232/Sark
sark/enum.py
EnumMember.name
def name(self, name): """Set the member name. Note that a member name cannot appear in other enums, or generally anywhere else in the IDB. """ success = idaapi.set_enum_member_name(self.cid, name) if not success: raise exceptions.CantRenameEnumMember( "Failed renaming {!r} to {!r}. Does the name exist somewhere else?".format(self.name, name))
python
def name(self, name): """Set the member name. Note that a member name cannot appear in other enums, or generally anywhere else in the IDB. """ success = idaapi.set_enum_member_name(self.cid, name) if not success: raise exceptions.CantRenameEnumMember( "Failed renaming {!r} to {!r}. Does the name exist somewhere else?".format(self.name, name))
[ "def", "name", "(", "self", ",", "name", ")", ":", "success", "=", "idaapi", ".", "set_enum_member_name", "(", "self", ".", "cid", ",", "name", ")", "if", "not", "success", ":", "raise", "exceptions", ".", "CantRenameEnumMember", "(", "\"Failed renaming {!r} to {!r}. Does the name exist somewhere else?\"", ".", "format", "(", "self", ".", "name", ",", "name", ")", ")" ]
Set the member name. Note that a member name cannot appear in other enums, or generally anywhere else in the IDB.
[ "Set", "the", "member", "name", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/enum.py#L310-L319
train
tmr232/Sark
sark/code/function.py
functions
def functions(start=None, end=None): """Get all functions in range. Args: start: Start address of the range. Defaults to IDB start. end: End address of the range. Defaults to IDB end. Returns: This is a generator that iterates over all the functions in the IDB. """ start, end = fix_addresses(start, end) for func_t in idautils.Functions(start, end): yield Function(func_t)
python
def functions(start=None, end=None): """Get all functions in range. Args: start: Start address of the range. Defaults to IDB start. end: End address of the range. Defaults to IDB end. Returns: This is a generator that iterates over all the functions in the IDB. """ start, end = fix_addresses(start, end) for func_t in idautils.Functions(start, end): yield Function(func_t)
[ "def", "functions", "(", "start", "=", "None", ",", "end", "=", "None", ")", ":", "start", ",", "end", "=", "fix_addresses", "(", "start", ",", "end", ")", "for", "func_t", "in", "idautils", ".", "Functions", "(", "start", ",", "end", ")", ":", "yield", "Function", "(", "func_t", ")" ]
Get all functions in range. Args: start: Start address of the range. Defaults to IDB start. end: End address of the range. Defaults to IDB end. Returns: This is a generator that iterates over all the functions in the IDB.
[ "Get", "all", "functions", "in", "range", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/function.py#L400-L413
train
tmr232/Sark
sark/code/function.py
Function.xrefs_from
def xrefs_from(self): """Xrefs from the function. This includes the xrefs from every line in the function, as `Xref` objects. Xrefs are filtered to exclude code references that are internal to the function. This means that every xrefs to the function's code will NOT be returned (yet, references to the function's data will be returnd). To get those extra xrefs, you need to iterate the function's lines yourself. """ for line in self.lines: for xref in line.xrefs_from: if xref.type.is_flow: continue if xref.to in self and xref.iscode: continue yield xref
python
def xrefs_from(self): """Xrefs from the function. This includes the xrefs from every line in the function, as `Xref` objects. Xrefs are filtered to exclude code references that are internal to the function. This means that every xrefs to the function's code will NOT be returned (yet, references to the function's data will be returnd). To get those extra xrefs, you need to iterate the function's lines yourself. """ for line in self.lines: for xref in line.xrefs_from: if xref.type.is_flow: continue if xref.to in self and xref.iscode: continue yield xref
[ "def", "xrefs_from", "(", "self", ")", ":", "for", "line", "in", "self", ".", "lines", ":", "for", "xref", "in", "line", ".", "xrefs_from", ":", "if", "xref", ".", "type", ".", "is_flow", ":", "continue", "if", "xref", ".", "to", "in", "self", "and", "xref", ".", "iscode", ":", "continue", "yield", "xref" ]
Xrefs from the function. This includes the xrefs from every line in the function, as `Xref` objects. Xrefs are filtered to exclude code references that are internal to the function. This means that every xrefs to the function's code will NOT be returned (yet, references to the function's data will be returnd). To get those extra xrefs, you need to iterate the function's lines yourself.
[ "Xrefs", "from", "the", "function", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/function.py#L234-L251
train
tmr232/Sark
sark/code/function.py
Function.set_name
def set_name(self, name, anyway=False): """Set Function Name. Default behavior throws an exception when setting to a name that already exists in the IDB. to make IDA automatically add a counter to the name (like in the GUI,) use `anyway=True`. Args: name: Desired name. anyway: `True` to set anyway. """ set_name(self.startEA, name, anyway=anyway)
python
def set_name(self, name, anyway=False): """Set Function Name. Default behavior throws an exception when setting to a name that already exists in the IDB. to make IDA automatically add a counter to the name (like in the GUI,) use `anyway=True`. Args: name: Desired name. anyway: `True` to set anyway. """ set_name(self.startEA, name, anyway=anyway)
[ "def", "set_name", "(", "self", ",", "name", ",", "anyway", "=", "False", ")", ":", "set_name", "(", "self", ".", "startEA", ",", "name", ",", "anyway", "=", "anyway", ")" ]
Set Function Name. Default behavior throws an exception when setting to a name that already exists in the IDB. to make IDA automatically add a counter to the name (like in the GUI,) use `anyway=True`. Args: name: Desired name. anyway: `True` to set anyway.
[ "Set", "Function", "Name", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/function.py#L308-L319
train
tmr232/Sark
sark/code/function.py
Function.color
def color(self): """Function color in IDA View""" color = idc.GetColor(self.ea, idc.CIC_FUNC) if color == 0xFFFFFFFF: return None return color
python
def color(self): """Function color in IDA View""" color = idc.GetColor(self.ea, idc.CIC_FUNC) if color == 0xFFFFFFFF: return None return color
[ "def", "color", "(", "self", ")", ":", "color", "=", "idc", ".", "GetColor", "(", "self", ".", "ea", ",", "idc", ".", "CIC_FUNC", ")", "if", "color", "==", "0xFFFFFFFF", ":", "return", "None", "return", "color" ]
Function color in IDA View
[ "Function", "color", "in", "IDA", "View" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/function.py#L336-L342
train
tmr232/Sark
sark/code/function.py
Function.color
def color(self, color): """Function Color in IDA View. Set color to `None` to clear the color. """ if color is None: color = 0xFFFFFFFF idc.SetColor(self.ea, idc.CIC_FUNC, color)
python
def color(self, color): """Function Color in IDA View. Set color to `None` to clear the color. """ if color is None: color = 0xFFFFFFFF idc.SetColor(self.ea, idc.CIC_FUNC, color)
[ "def", "color", "(", "self", ",", "color", ")", ":", "if", "color", "is", "None", ":", "color", "=", "0xFFFFFFFF", "idc", ".", "SetColor", "(", "self", ".", "ea", ",", "idc", ".", "CIC_FUNC", ",", "color", ")" ]
Function Color in IDA View. Set color to `None` to clear the color.
[ "Function", "Color", "in", "IDA", "View", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/function.py#L346-L354
train
tmr232/Sark
sark/code/line.py
lines
def lines(start=None, end=None, reverse=False, selection=False): """Iterate lines in range. Args: start: Starting address, start of IDB if `None`. end: End address, end of IDB if `None`. reverse: Set to true to iterate in reverse order. selection: If set to True, replaces start and end with current selection. Returns: iterator of `Line` objects. """ if selection: start, end = get_selection() else: start, end = fix_addresses(start, end) if not reverse: item = idaapi.get_item_head(start) while item < end: yield Line(item) item += idaapi.get_item_size(item) else: # if reverse: item = idaapi.get_item_head(end - 1) while item >= start: yield Line(item) item = idaapi.get_item_head(item - 1)
python
def lines(start=None, end=None, reverse=False, selection=False): """Iterate lines in range. Args: start: Starting address, start of IDB if `None`. end: End address, end of IDB if `None`. reverse: Set to true to iterate in reverse order. selection: If set to True, replaces start and end with current selection. Returns: iterator of `Line` objects. """ if selection: start, end = get_selection() else: start, end = fix_addresses(start, end) if not reverse: item = idaapi.get_item_head(start) while item < end: yield Line(item) item += idaapi.get_item_size(item) else: # if reverse: item = idaapi.get_item_head(end - 1) while item >= start: yield Line(item) item = idaapi.get_item_head(item - 1)
[ "def", "lines", "(", "start", "=", "None", ",", "end", "=", "None", ",", "reverse", "=", "False", ",", "selection", "=", "False", ")", ":", "if", "selection", ":", "start", ",", "end", "=", "get_selection", "(", ")", "else", ":", "start", ",", "end", "=", "fix_addresses", "(", "start", ",", "end", ")", "if", "not", "reverse", ":", "item", "=", "idaapi", ".", "get_item_head", "(", "start", ")", "while", "item", "<", "end", ":", "yield", "Line", "(", "item", ")", "item", "+=", "idaapi", ".", "get_item_size", "(", "item", ")", "else", ":", "# if reverse:", "item", "=", "idaapi", ".", "get_item_head", "(", "end", "-", "1", ")", "while", "item", ">=", "start", ":", "yield", "Line", "(", "item", ")", "item", "=", "idaapi", ".", "get_item_head", "(", "item", "-", "1", ")" ]
Iterate lines in range. Args: start: Starting address, start of IDB if `None`. end: End address, end of IDB if `None`. reverse: Set to true to iterate in reverse order. selection: If set to True, replaces start and end with current selection. Returns: iterator of `Line` objects.
[ "Iterate", "lines", "in", "range", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/line.py#L327-L355
train
tmr232/Sark
sark/code/line.py
Line.type
def type(self): """return the type of the Line """ properties = {self.is_code: "code", self.is_data: "data", self.is_string: "string", self.is_tail: "tail", self.is_unknown: "unknown"} for k, v in properties.items(): if k: return v
python
def type(self): """return the type of the Line """ properties = {self.is_code: "code", self.is_data: "data", self.is_string: "string", self.is_tail: "tail", self.is_unknown: "unknown"} for k, v in properties.items(): if k: return v
[ "def", "type", "(", "self", ")", ":", "properties", "=", "{", "self", ".", "is_code", ":", "\"code\"", ",", "self", ".", "is_data", ":", "\"data\"", ",", "self", ".", "is_string", ":", "\"string\"", ",", "self", ".", "is_tail", ":", "\"tail\"", ",", "self", ".", "is_unknown", ":", "\"unknown\"", "}", "for", "k", ",", "v", "in", "properties", ".", "items", "(", ")", ":", "if", "k", ":", "return", "v" ]
return the type of the Line
[ "return", "the", "type", "of", "the", "Line" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/line.py#L195-L203
train
tmr232/Sark
sark/code/line.py
Line.color
def color(self): """Line color in IDA View""" color = idc.GetColor(self.ea, idc.CIC_ITEM) if color == 0xFFFFFFFF: return None return color
python
def color(self): """Line color in IDA View""" color = idc.GetColor(self.ea, idc.CIC_ITEM) if color == 0xFFFFFFFF: return None return color
[ "def", "color", "(", "self", ")", ":", "color", "=", "idc", ".", "GetColor", "(", "self", ".", "ea", ",", "idc", ".", "CIC_ITEM", ")", "if", "color", "==", "0xFFFFFFFF", ":", "return", "None", "return", "color" ]
Line color in IDA View
[ "Line", "color", "in", "IDA", "View" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/line.py#L274-L280
train
tmr232/Sark
sark/code/line.py
Line.color
def color(self, color): """Line Color in IDA View. Set color to `None` to clear the color. """ if color is None: color = 0xFFFFFFFF idc.SetColor(self.ea, idc.CIC_ITEM, color)
python
def color(self, color): """Line Color in IDA View. Set color to `None` to clear the color. """ if color is None: color = 0xFFFFFFFF idc.SetColor(self.ea, idc.CIC_ITEM, color)
[ "def", "color", "(", "self", ",", "color", ")", ":", "if", "color", "is", "None", ":", "color", "=", "0xFFFFFFFF", "idc", ".", "SetColor", "(", "self", ".", "ea", ",", "idc", ".", "CIC_ITEM", ",", "color", ")" ]
Line Color in IDA View. Set color to `None` to clear the color.
[ "Line", "Color", "in", "IDA", "View", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/line.py#L284-L292
train
tmr232/Sark
sark/qt.py
capture_widget
def capture_widget(widget, path=None): """Grab an image of a Qt widget Args: widget: The Qt Widget to capture path (optional): The path to save to. If not provided - will return image data. Returns: If a path is provided, the image will be saved to it. If not, the PNG buffer will be returned. """ if use_qt5: pixmap = widget.grab() else: pixmap = QtGui.QPixmap.grabWidget(widget) if path: pixmap.save(path) else: image_buffer = QtCore.QBuffer() image_buffer.open(QtCore.QIODevice.ReadWrite) pixmap.save(image_buffer, "PNG") return image_buffer.data().data()
python
def capture_widget(widget, path=None): """Grab an image of a Qt widget Args: widget: The Qt Widget to capture path (optional): The path to save to. If not provided - will return image data. Returns: If a path is provided, the image will be saved to it. If not, the PNG buffer will be returned. """ if use_qt5: pixmap = widget.grab() else: pixmap = QtGui.QPixmap.grabWidget(widget) if path: pixmap.save(path) else: image_buffer = QtCore.QBuffer() image_buffer.open(QtCore.QIODevice.ReadWrite) pixmap.save(image_buffer, "PNG") return image_buffer.data().data()
[ "def", "capture_widget", "(", "widget", ",", "path", "=", "None", ")", ":", "if", "use_qt5", ":", "pixmap", "=", "widget", ".", "grab", "(", ")", "else", ":", "pixmap", "=", "QtGui", ".", "QPixmap", ".", "grabWidget", "(", "widget", ")", "if", "path", ":", "pixmap", ".", "save", "(", "path", ")", "else", ":", "image_buffer", "=", "QtCore", ".", "QBuffer", "(", ")", "image_buffer", ".", "open", "(", "QtCore", ".", "QIODevice", ".", "ReadWrite", ")", "pixmap", ".", "save", "(", "image_buffer", ",", "\"PNG\"", ")", "return", "image_buffer", ".", "data", "(", ")", ".", "data", "(", ")" ]
Grab an image of a Qt widget Args: widget: The Qt Widget to capture path (optional): The path to save to. If not provided - will return image data. Returns: If a path is provided, the image will be saved to it. If not, the PNG buffer will be returned.
[ "Grab", "an", "image", "of", "a", "Qt", "widget" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/qt.py#L14-L39
train
tmr232/Sark
sark/qt.py
get_widget
def get_widget(title): """Get the Qt widget of the IDA window with the given title.""" tform = idaapi.find_tform(title) if not tform: raise exceptions.FormNotFound("No form titled {!r} found.".format(title)) return form_to_widget(tform)
python
def get_widget(title): """Get the Qt widget of the IDA window with the given title.""" tform = idaapi.find_tform(title) if not tform: raise exceptions.FormNotFound("No form titled {!r} found.".format(title)) return form_to_widget(tform)
[ "def", "get_widget", "(", "title", ")", ":", "tform", "=", "idaapi", ".", "find_tform", "(", "title", ")", "if", "not", "tform", ":", "raise", "exceptions", ".", "FormNotFound", "(", "\"No form titled {!r} found.\"", ".", "format", "(", "title", ")", ")", "return", "form_to_widget", "(", "tform", ")" ]
Get the Qt widget of the IDA window with the given title.
[ "Get", "the", "Qt", "widget", "of", "the", "IDA", "window", "with", "the", "given", "title", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/qt.py#L42-L48
train
tmr232/Sark
sark/qt.py
get_window
def get_window(): """Get IDA's top level window.""" tform = idaapi.get_current_tform() # Required sometimes when closing IDBs and not IDA. if not tform: tform = idaapi.find_tform("Output window") widget = form_to_widget(tform) window = widget.window() return window
python
def get_window(): """Get IDA's top level window.""" tform = idaapi.get_current_tform() # Required sometimes when closing IDBs and not IDA. if not tform: tform = idaapi.find_tform("Output window") widget = form_to_widget(tform) window = widget.window() return window
[ "def", "get_window", "(", ")", ":", "tform", "=", "idaapi", ".", "get_current_tform", "(", ")", "# Required sometimes when closing IDBs and not IDA.", "if", "not", "tform", ":", "tform", "=", "idaapi", ".", "find_tform", "(", "\"Output window\"", ")", "widget", "=", "form_to_widget", "(", "tform", ")", "window", "=", "widget", ".", "window", "(", ")", "return", "window" ]
Get IDA's top level window.
[ "Get", "IDA", "s", "top", "level", "window", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/qt.py#L56-L66
train
tmr232/Sark
sark/qt.py
MenuManager.add_menu
def add_menu(self, name): """Add a top-level menu. The menu manager only allows one menu of the same name. However, it does not make sure that there are no pre-existing menus of that name. """ if name in self._menus: raise exceptions.MenuAlreadyExists("Menu name {!r} already exists.".format(name)) menu = self._menu.addMenu(name) self._menus[name] = menu
python
def add_menu(self, name): """Add a top-level menu. The menu manager only allows one menu of the same name. However, it does not make sure that there are no pre-existing menus of that name. """ if name in self._menus: raise exceptions.MenuAlreadyExists("Menu name {!r} already exists.".format(name)) menu = self._menu.addMenu(name) self._menus[name] = menu
[ "def", "add_menu", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_menus", ":", "raise", "exceptions", ".", "MenuAlreadyExists", "(", "\"Menu name {!r} already exists.\"", ".", "format", "(", "name", ")", ")", "menu", "=", "self", ".", "_menu", ".", "addMenu", "(", "name", ")", "self", ".", "_menus", "[", "name", "]", "=", "menu" ]
Add a top-level menu. The menu manager only allows one menu of the same name. However, it does not make sure that there are no pre-existing menus of that name.
[ "Add", "a", "top", "-", "level", "menu", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/qt.py#L109-L118
train
tmr232/Sark
sark/qt.py
MenuManager.remove_menu
def remove_menu(self, name): """Remove a top-level menu. Only removes menus created by the same menu manager. """ if name not in self._menus: raise exceptions.MenuNotFound( "Menu {!r} was not found. It might be deleted, or belong to another menu manager.".format(name)) self._menu.removeAction(self._menus[name].menuAction()) del self._menus[name]
python
def remove_menu(self, name): """Remove a top-level menu. Only removes menus created by the same menu manager. """ if name not in self._menus: raise exceptions.MenuNotFound( "Menu {!r} was not found. It might be deleted, or belong to another menu manager.".format(name)) self._menu.removeAction(self._menus[name].menuAction()) del self._menus[name]
[ "def", "remove_menu", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "_menus", ":", "raise", "exceptions", ".", "MenuNotFound", "(", "\"Menu {!r} was not found. It might be deleted, or belong to another menu manager.\"", ".", "format", "(", "name", ")", ")", "self", ".", "_menu", ".", "removeAction", "(", "self", ".", "_menus", "[", "name", "]", ".", "menuAction", "(", ")", ")", "del", "self", ".", "_menus", "[", "name", "]" ]
Remove a top-level menu. Only removes menus created by the same menu manager.
[ "Remove", "a", "top", "-", "level", "menu", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/qt.py#L120-L130
train
tmr232/Sark
sark/qt.py
MenuManager.clear
def clear(self): """Clear all menus created by this manager.""" for menu in self._menus.itervalues(): self._menu.removeAction(menu.menuAction()) self._menus = {}
python
def clear(self): """Clear all menus created by this manager.""" for menu in self._menus.itervalues(): self._menu.removeAction(menu.menuAction()) self._menus = {}
[ "def", "clear", "(", "self", ")", ":", "for", "menu", "in", "self", ".", "_menus", ".", "itervalues", "(", ")", ":", "self", ".", "_menu", ".", "removeAction", "(", "menu", ".", "menuAction", "(", ")", ")", "self", ".", "_menus", "=", "{", "}" ]
Clear all menus created by this manager.
[ "Clear", "all", "menus", "created", "by", "this", "manager", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/qt.py#L132-L136
train
tmr232/Sark
sark/debug.py
Registers.get_by_flags
def get_by_flags(self, flags): """Iterate all register infos matching the given flags.""" for reg in self._reg_infos: if reg.flags & flags == flags: yield reg
python
def get_by_flags(self, flags): """Iterate all register infos matching the given flags.""" for reg in self._reg_infos: if reg.flags & flags == flags: yield reg
[ "def", "get_by_flags", "(", "self", ",", "flags", ")", ":", "for", "reg", "in", "self", ".", "_reg_infos", ":", "if", "reg", ".", "flags", "&", "flags", "==", "flags", ":", "yield", "reg" ]
Iterate all register infos matching the given flags.
[ "Iterate", "all", "register", "infos", "matching", "the", "given", "flags", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/debug.py#L39-L43
train
tmr232/Sark
sark/debug.py
Registers.get_single_by_flags
def get_single_by_flags(self, flags): """Get the register info matching the flag. Raises ValueError if more than one are found.""" regs = list(self.get_by_flags(flags)) if len(regs) != 1: raise ValueError("Flags do not return unique resigter. {!r}", regs) return regs[0]
python
def get_single_by_flags(self, flags): """Get the register info matching the flag. Raises ValueError if more than one are found.""" regs = list(self.get_by_flags(flags)) if len(regs) != 1: raise ValueError("Flags do not return unique resigter. {!r}", regs) return regs[0]
[ "def", "get_single_by_flags", "(", "self", ",", "flags", ")", ":", "regs", "=", "list", "(", "self", ".", "get_by_flags", "(", "flags", ")", ")", "if", "len", "(", "regs", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Flags do not return unique resigter. {!r}\"", ",", "regs", ")", "return", "regs", "[", "0", "]" ]
Get the register info matching the flag. Raises ValueError if more than one are found.
[ "Get", "the", "register", "info", "matching", "the", "flag", ".", "Raises", "ValueError", "if", "more", "than", "one", "are", "found", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/debug.py#L45-L51
train
tmr232/Sark
sark/code/segment.py
segments
def segments(seg_type=None): """Iterate segments based on type Args: seg_type: type of segment e.g. SEG_CODE Returns: iterator of `Segment` objects. if seg_type is None , returns all segments otherwise returns only the relevant ones """ for index in xrange(idaapi.get_segm_qty()): seg = Segment(index=index) if (seg_type is None) or (seg.type == seg_type): yield Segment(index=index)
python
def segments(seg_type=None): """Iterate segments based on type Args: seg_type: type of segment e.g. SEG_CODE Returns: iterator of `Segment` objects. if seg_type is None , returns all segments otherwise returns only the relevant ones """ for index in xrange(idaapi.get_segm_qty()): seg = Segment(index=index) if (seg_type is None) or (seg.type == seg_type): yield Segment(index=index)
[ "def", "segments", "(", "seg_type", "=", "None", ")", ":", "for", "index", "in", "xrange", "(", "idaapi", ".", "get_segm_qty", "(", ")", ")", ":", "seg", "=", "Segment", "(", "index", "=", "index", ")", "if", "(", "seg_type", "is", "None", ")", "or", "(", "seg", ".", "type", "==", "seg_type", ")", ":", "yield", "Segment", "(", "index", "=", "index", ")" ]
Iterate segments based on type Args: seg_type: type of segment e.g. SEG_CODE Returns: iterator of `Segment` objects. if seg_type is None , returns all segments otherwise returns only the relevant ones
[ "Iterate", "segments", "based", "on", "type" ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/segment.py#L250-L264
train
tmr232/Sark
sark/code/segment.py
Segment.next
def next(self): """Get the next segment.""" seg = Segment(segment_t=idaapi.get_next_seg(self.ea)) if seg.ea <= self.ea: raise exceptions.NoMoreSegments("This is the last segment. No segments exist after it.") return seg
python
def next(self): """Get the next segment.""" seg = Segment(segment_t=idaapi.get_next_seg(self.ea)) if seg.ea <= self.ea: raise exceptions.NoMoreSegments("This is the last segment. No segments exist after it.") return seg
[ "def", "next", "(", "self", ")", ":", "seg", "=", "Segment", "(", "segment_t", "=", "idaapi", ".", "get_next_seg", "(", "self", ".", "ea", ")", ")", "if", "seg", ".", "ea", "<=", "self", ".", "ea", ":", "raise", "exceptions", ".", "NoMoreSegments", "(", "\"This is the last segment. No segments exist after it.\"", ")", "return", "seg" ]
Get the next segment.
[ "Get", "the", "next", "segment", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/segment.py#L211-L218
train
tmr232/Sark
sark/code/segment.py
Segment.prev
def prev(self): """Get the previous segment.""" seg = Segment(segment_t=idaapi.get_prev_seg(self.ea)) if seg.ea >= self.ea: raise exceptions.NoMoreSegments("This is the first segment. no segments exist before it.") return seg
python
def prev(self): """Get the previous segment.""" seg = Segment(segment_t=idaapi.get_prev_seg(self.ea)) if seg.ea >= self.ea: raise exceptions.NoMoreSegments("This is the first segment. no segments exist before it.") return seg
[ "def", "prev", "(", "self", ")", ":", "seg", "=", "Segment", "(", "segment_t", "=", "idaapi", ".", "get_prev_seg", "(", "self", ".", "ea", ")", ")", "if", "seg", ".", "ea", ">=", "self", ".", "ea", ":", "raise", "exceptions", ".", "NoMoreSegments", "(", "\"This is the first segment. no segments exist before it.\"", ")", "return", "seg" ]
Get the previous segment.
[ "Get", "the", "previous", "segment", "." ]
bee62879c2aea553a3924d887e2b30f2a6008581
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/code/segment.py#L221-L228
train
thoth-station/solver
thoth/solver/python/base.py
get_ecosystem_solver
def get_ecosystem_solver(ecosystem_name, parser_kwargs=None, fetcher_kwargs=None): """Get Solver subclass instance for particular ecosystem. :param ecosystem_name: name of ecosystem for which solver should be get :param parser_kwargs: parser key-value arguments for constructor :param fetcher_kwargs: fetcher key-value arguments for constructor :return: Solver """ from .python import PythonSolver if ecosystem_name.lower() == "pypi": source = Source(url="https://pypi.org/simple", warehouse_api_url="https://pypi.org/pypi", warehouse=True) return PythonSolver(parser_kwargs, fetcher_kwargs={"source": source}) raise NotImplementedError("Unknown ecosystem: {}".format(ecosystem_name))
python
def get_ecosystem_solver(ecosystem_name, parser_kwargs=None, fetcher_kwargs=None): """Get Solver subclass instance for particular ecosystem. :param ecosystem_name: name of ecosystem for which solver should be get :param parser_kwargs: parser key-value arguments for constructor :param fetcher_kwargs: fetcher key-value arguments for constructor :return: Solver """ from .python import PythonSolver if ecosystem_name.lower() == "pypi": source = Source(url="https://pypi.org/simple", warehouse_api_url="https://pypi.org/pypi", warehouse=True) return PythonSolver(parser_kwargs, fetcher_kwargs={"source": source}) raise NotImplementedError("Unknown ecosystem: {}".format(ecosystem_name))
[ "def", "get_ecosystem_solver", "(", "ecosystem_name", ",", "parser_kwargs", "=", "None", ",", "fetcher_kwargs", "=", "None", ")", ":", "from", ".", "python", "import", "PythonSolver", "if", "ecosystem_name", ".", "lower", "(", ")", "==", "\"pypi\"", ":", "source", "=", "Source", "(", "url", "=", "\"https://pypi.org/simple\"", ",", "warehouse_api_url", "=", "\"https://pypi.org/pypi\"", ",", "warehouse", "=", "True", ")", "return", "PythonSolver", "(", "parser_kwargs", ",", "fetcher_kwargs", "=", "{", "\"source\"", ":", "source", "}", ")", "raise", "NotImplementedError", "(", "\"Unknown ecosystem: {}\"", ".", "format", "(", "ecosystem_name", ")", ")" ]
Get Solver subclass instance for particular ecosystem. :param ecosystem_name: name of ecosystem for which solver should be get :param parser_kwargs: parser key-value arguments for constructor :param fetcher_kwargs: fetcher key-value arguments for constructor :return: Solver
[ "Get", "Solver", "subclass", "instance", "for", "particular", "ecosystem", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/base.py#L297-L311
train
thoth-station/solver
thoth/solver/python/base.py
Dependency.check
def check(self, version): # Ignore PyDocStyleBear """Check if `version` fits into our dependency specification. :param version: str :return: bool """ def _compare_spec(spec): if len(spec) == 1: spec = ("=", spec[0]) token = Tokens.operators.index(spec[0]) comparison = compare_version(version, spec[1]) if token in [Tokens.EQ1, Tokens.EQ2]: return comparison == 0 elif token == Tokens.GT: return comparison == 1 elif token == Tokens.LT: return comparison == -1 elif token == Tokens.GTE: return comparison >= 0 elif token == Tokens.LTE: return comparison <= 0 elif token == Tokens.NEQ: return comparison != 0 else: raise ValueError("Invalid comparison token") results, intermediaries = False, False for spec in self.spec: if isinstance(spec, list): intermediary = True for sub in spec: intermediary &= _compare_spec(sub) intermediaries |= intermediary elif isinstance(spec, tuple): results |= _compare_spec(spec) return results or intermediaries
python
def check(self, version): # Ignore PyDocStyleBear """Check if `version` fits into our dependency specification. :param version: str :return: bool """ def _compare_spec(spec): if len(spec) == 1: spec = ("=", spec[0]) token = Tokens.operators.index(spec[0]) comparison = compare_version(version, spec[1]) if token in [Tokens.EQ1, Tokens.EQ2]: return comparison == 0 elif token == Tokens.GT: return comparison == 1 elif token == Tokens.LT: return comparison == -1 elif token == Tokens.GTE: return comparison >= 0 elif token == Tokens.LTE: return comparison <= 0 elif token == Tokens.NEQ: return comparison != 0 else: raise ValueError("Invalid comparison token") results, intermediaries = False, False for spec in self.spec: if isinstance(spec, list): intermediary = True for sub in spec: intermediary &= _compare_spec(sub) intermediaries |= intermediary elif isinstance(spec, tuple): results |= _compare_spec(spec) return results or intermediaries
[ "def", "check", "(", "self", ",", "version", ")", ":", "# Ignore PyDocStyleBear", "def", "_compare_spec", "(", "spec", ")", ":", "if", "len", "(", "spec", ")", "==", "1", ":", "spec", "=", "(", "\"=\"", ",", "spec", "[", "0", "]", ")", "token", "=", "Tokens", ".", "operators", ".", "index", "(", "spec", "[", "0", "]", ")", "comparison", "=", "compare_version", "(", "version", ",", "spec", "[", "1", "]", ")", "if", "token", "in", "[", "Tokens", ".", "EQ1", ",", "Tokens", ".", "EQ2", "]", ":", "return", "comparison", "==", "0", "elif", "token", "==", "Tokens", ".", "GT", ":", "return", "comparison", "==", "1", "elif", "token", "==", "Tokens", ".", "LT", ":", "return", "comparison", "==", "-", "1", "elif", "token", "==", "Tokens", ".", "GTE", ":", "return", "comparison", ">=", "0", "elif", "token", "==", "Tokens", ".", "LTE", ":", "return", "comparison", "<=", "0", "elif", "token", "==", "Tokens", ".", "NEQ", ":", "return", "comparison", "!=", "0", "else", ":", "raise", "ValueError", "(", "\"Invalid comparison token\"", ")", "results", ",", "intermediaries", "=", "False", ",", "False", "for", "spec", "in", "self", ".", "spec", ":", "if", "isinstance", "(", "spec", ",", "list", ")", ":", "intermediary", "=", "True", "for", "sub", "in", "spec", ":", "intermediary", "&=", "_compare_spec", "(", "sub", ")", "intermediaries", "|=", "intermediary", "elif", "isinstance", "(", "spec", ",", "tuple", ")", ":", "results", "|=", "_compare_spec", "(", "spec", ")", "return", "results", "or", "intermediaries" ]
Check if `version` fits into our dependency specification. :param version: str :return: bool
[ "Check", "if", "version", "fits", "into", "our", "dependency", "specification", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/base.py#L143-L181
train
thoth-station/solver
thoth/solver/python/base.py
Solver.solve
def solve(self, dependencies, graceful=True, all_versions=False): # Ignore PyDocStyleBear """Solve `dependencies` against upstream repository. :param dependencies: List, List of dependencies in native format :param graceful: bool, Print info output to stdout :param all_versions: bool, Return all matched versions instead of the latest :return: Dict[str, str], Matched versions """ def _compare_version_index_url(v1, v2): """Get a wrapper around compare version to omit index url when sorting.""" return compare_version(v1[0], v2[0]) solved = {} for dep in self.dependency_parser.parse(dependencies): _LOGGER.debug("Fetching releases for: {}".format(dep)) name, releases = self.release_fetcher.fetch_releases(dep.name) if name in solved: raise SolverException("Dependency: {} is listed multiple times".format(name)) if not releases: if graceful: _LOGGER.info("No releases found for package %s", dep.name) else: raise SolverException("No releases found for package {}".format(dep.name)) releases = [release for release in releases if release in dep] matching = sorted(releases, key=cmp_to_key(_compare_version_index_url)) _LOGGER.debug(" matching: %s", matching) if all_versions: solved[name] = matching else: if not matching: solved[name] = None else: if self._highest_dependency_version: solved[name] = matching[-1] else: solved[name] = matching[0] return solved
python
def solve(self, dependencies, graceful=True, all_versions=False): # Ignore PyDocStyleBear """Solve `dependencies` against upstream repository. :param dependencies: List, List of dependencies in native format :param graceful: bool, Print info output to stdout :param all_versions: bool, Return all matched versions instead of the latest :return: Dict[str, str], Matched versions """ def _compare_version_index_url(v1, v2): """Get a wrapper around compare version to omit index url when sorting.""" return compare_version(v1[0], v2[0]) solved = {} for dep in self.dependency_parser.parse(dependencies): _LOGGER.debug("Fetching releases for: {}".format(dep)) name, releases = self.release_fetcher.fetch_releases(dep.name) if name in solved: raise SolverException("Dependency: {} is listed multiple times".format(name)) if not releases: if graceful: _LOGGER.info("No releases found for package %s", dep.name) else: raise SolverException("No releases found for package {}".format(dep.name)) releases = [release for release in releases if release in dep] matching = sorted(releases, key=cmp_to_key(_compare_version_index_url)) _LOGGER.debug(" matching: %s", matching) if all_versions: solved[name] = matching else: if not matching: solved[name] = None else: if self._highest_dependency_version: solved[name] = matching[-1] else: solved[name] = matching[0] return solved
[ "def", "solve", "(", "self", ",", "dependencies", ",", "graceful", "=", "True", ",", "all_versions", "=", "False", ")", ":", "# Ignore PyDocStyleBear", "def", "_compare_version_index_url", "(", "v1", ",", "v2", ")", ":", "\"\"\"Get a wrapper around compare version to omit index url when sorting.\"\"\"", "return", "compare_version", "(", "v1", "[", "0", "]", ",", "v2", "[", "0", "]", ")", "solved", "=", "{", "}", "for", "dep", "in", "self", ".", "dependency_parser", ".", "parse", "(", "dependencies", ")", ":", "_LOGGER", ".", "debug", "(", "\"Fetching releases for: {}\"", ".", "format", "(", "dep", ")", ")", "name", ",", "releases", "=", "self", ".", "release_fetcher", ".", "fetch_releases", "(", "dep", ".", "name", ")", "if", "name", "in", "solved", ":", "raise", "SolverException", "(", "\"Dependency: {} is listed multiple times\"", ".", "format", "(", "name", ")", ")", "if", "not", "releases", ":", "if", "graceful", ":", "_LOGGER", ".", "info", "(", "\"No releases found for package %s\"", ",", "dep", ".", "name", ")", "else", ":", "raise", "SolverException", "(", "\"No releases found for package {}\"", ".", "format", "(", "dep", ".", "name", ")", ")", "releases", "=", "[", "release", "for", "release", "in", "releases", "if", "release", "in", "dep", "]", "matching", "=", "sorted", "(", "releases", ",", "key", "=", "cmp_to_key", "(", "_compare_version_index_url", ")", ")", "_LOGGER", ".", "debug", "(", "\" matching: %s\"", ",", "matching", ")", "if", "all_versions", ":", "solved", "[", "name", "]", "=", "matching", "else", ":", "if", "not", "matching", ":", "solved", "[", "name", "]", "=", "None", "else", ":", "if", "self", ".", "_highest_dependency_version", ":", "solved", "[", "name", "]", "=", "matching", "[", "-", "1", "]", "else", ":", "solved", "[", "name", "]", "=", "matching", "[", "0", "]", "return", "solved" ]
Solve `dependencies` against upstream repository. :param dependencies: List, List of dependencies in native format :param graceful: bool, Print info output to stdout :param all_versions: bool, Return all matched versions instead of the latest :return: Dict[str, str], Matched versions
[ "Solve", "dependencies", "against", "upstream", "repository", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/base.py#L250-L294
train
thoth-station/solver
thoth/solver/compile.py
pip_compile
def pip_compile(*packages: str): """Run pip-compile to pin down packages, also resolve their transitive dependencies.""" result = None packages = "\n".join(packages) with tempfile.TemporaryDirectory() as tmp_dirname, cwd(tmp_dirname): with open("requirements.in", "w") as requirements_file: requirements_file.write(packages) runner = CliRunner() try: result = runner.invoke(cli, ["requirements.in"], catch_exceptions=False) except Exception as exc: raise ThothPipCompileError(str(exc)) from exc if result.exit_code != 0: error_msg = ( f"pip-compile returned non-zero ({result.exit_code:d}) " f"output: {result.output_bytes.decode():s}" ) raise ThothPipCompileError(error_msg) return result.output_bytes.decode()
python
def pip_compile(*packages: str): """Run pip-compile to pin down packages, also resolve their transitive dependencies.""" result = None packages = "\n".join(packages) with tempfile.TemporaryDirectory() as tmp_dirname, cwd(tmp_dirname): with open("requirements.in", "w") as requirements_file: requirements_file.write(packages) runner = CliRunner() try: result = runner.invoke(cli, ["requirements.in"], catch_exceptions=False) except Exception as exc: raise ThothPipCompileError(str(exc)) from exc if result.exit_code != 0: error_msg = ( f"pip-compile returned non-zero ({result.exit_code:d}) " f"output: {result.output_bytes.decode():s}" ) raise ThothPipCompileError(error_msg) return result.output_bytes.decode()
[ "def", "pip_compile", "(", "*", "packages", ":", "str", ")", ":", "result", "=", "None", "packages", "=", "\"\\n\"", ".", "join", "(", "packages", ")", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmp_dirname", ",", "cwd", "(", "tmp_dirname", ")", ":", "with", "open", "(", "\"requirements.in\"", ",", "\"w\"", ")", "as", "requirements_file", ":", "requirements_file", ".", "write", "(", "packages", ")", "runner", "=", "CliRunner", "(", ")", "try", ":", "result", "=", "runner", ".", "invoke", "(", "cli", ",", "[", "\"requirements.in\"", "]", ",", "catch_exceptions", "=", "False", ")", "except", "Exception", "as", "exc", ":", "raise", "ThothPipCompileError", "(", "str", "(", "exc", ")", ")", "from", "exc", "if", "result", ".", "exit_code", "!=", "0", ":", "error_msg", "=", "(", "f\"pip-compile returned non-zero ({result.exit_code:d}) \"", "f\"output: {result.output_bytes.decode():s}\"", ")", "raise", "ThothPipCompileError", "(", "error_msg", ")", "return", "result", ".", "output_bytes", ".", "decode", "(", ")" ]
Run pip-compile to pin down packages, also resolve their transitive dependencies.
[ "Run", "pip", "-", "compile", "to", "pin", "down", "packages", "also", "resolve", "their", "transitive", "dependencies", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/compile.py#L30-L52
train
thoth-station/solver
thoth/solver/cli.py
_print_version
def _print_version(ctx, _, value): """Print solver version and exit.""" if not value or ctx.resilient_parsing: return click.echo(analyzer_version) ctx.exit()
python
def _print_version(ctx, _, value): """Print solver version and exit.""" if not value or ctx.resilient_parsing: return click.echo(analyzer_version) ctx.exit()
[ "def", "_print_version", "(", "ctx", ",", "_", ",", "value", ")", ":", "if", "not", "value", "or", "ctx", ".", "resilient_parsing", ":", "return", "click", ".", "echo", "(", "analyzer_version", ")", "ctx", ".", "exit", "(", ")" ]
Print solver version and exit.
[ "Print", "solver", "version", "and", "exit", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/cli.py#L37-L42
train
thoth-station/solver
thoth/solver/cli.py
cli
def cli(ctx=None, verbose=0): """Thoth solver command line interface.""" if ctx: ctx.auto_envvar_prefix = "THOTH_SOLVER" if verbose: _LOG.setLevel(logging.DEBUG) _LOG.debug("Debug mode is on")
python
def cli(ctx=None, verbose=0): """Thoth solver command line interface.""" if ctx: ctx.auto_envvar_prefix = "THOTH_SOLVER" if verbose: _LOG.setLevel(logging.DEBUG) _LOG.debug("Debug mode is on")
[ "def", "cli", "(", "ctx", "=", "None", ",", "verbose", "=", "0", ")", ":", "if", "ctx", ":", "ctx", ".", "auto_envvar_prefix", "=", "\"THOTH_SOLVER\"", "if", "verbose", ":", "_LOG", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "_LOG", ".", "debug", "(", "\"Debug mode is on\"", ")" ]
Thoth solver command line interface.
[ "Thoth", "solver", "command", "line", "interface", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/cli.py#L56-L64
train
thoth-station/solver
thoth/solver/cli.py
pypi
def pypi( click_ctx, requirements, index=None, python_version=3, exclude_packages=None, output=None, subgraph_check_api=None, no_transitive=True, no_pretty=False, ): """Manipulate with dependency requirements using PyPI.""" requirements = [requirement.strip() for requirement in requirements.split("\\n") if requirement] if not requirements: _LOG.error("No requirements specified, exiting") sys.exit(1) if not subgraph_check_api: _LOG.info( "No subgraph check API provided, no queries will be done for dependency subgraphs that should be avoided" ) # Ignore PycodestyleBear (E501) result = resolve_python( requirements, index_urls=index.split(",") if index else ("https://pypi.org/simple",), python_version=int(python_version), transitive=not no_transitive, exclude_packages=set(map(str.strip, (exclude_packages or "").split(","))), subgraph_check_api=subgraph_check_api, ) print_command_result( click_ctx, result, analyzer=analyzer_name, analyzer_version=analyzer_version, output=output or "-", pretty=not no_pretty, )
python
def pypi( click_ctx, requirements, index=None, python_version=3, exclude_packages=None, output=None, subgraph_check_api=None, no_transitive=True, no_pretty=False, ): """Manipulate with dependency requirements using PyPI.""" requirements = [requirement.strip() for requirement in requirements.split("\\n") if requirement] if not requirements: _LOG.error("No requirements specified, exiting") sys.exit(1) if not subgraph_check_api: _LOG.info( "No subgraph check API provided, no queries will be done for dependency subgraphs that should be avoided" ) # Ignore PycodestyleBear (E501) result = resolve_python( requirements, index_urls=index.split(",") if index else ("https://pypi.org/simple",), python_version=int(python_version), transitive=not no_transitive, exclude_packages=set(map(str.strip, (exclude_packages or "").split(","))), subgraph_check_api=subgraph_check_api, ) print_command_result( click_ctx, result, analyzer=analyzer_name, analyzer_version=analyzer_version, output=output or "-", pretty=not no_pretty, )
[ "def", "pypi", "(", "click_ctx", ",", "requirements", ",", "index", "=", "None", ",", "python_version", "=", "3", ",", "exclude_packages", "=", "None", ",", "output", "=", "None", ",", "subgraph_check_api", "=", "None", ",", "no_transitive", "=", "True", ",", "no_pretty", "=", "False", ",", ")", ":", "requirements", "=", "[", "requirement", ".", "strip", "(", ")", "for", "requirement", "in", "requirements", ".", "split", "(", "\"\\\\n\"", ")", "if", "requirement", "]", "if", "not", "requirements", ":", "_LOG", ".", "error", "(", "\"No requirements specified, exiting\"", ")", "sys", ".", "exit", "(", "1", ")", "if", "not", "subgraph_check_api", ":", "_LOG", ".", "info", "(", "\"No subgraph check API provided, no queries will be done for dependency subgraphs that should be avoided\"", ")", "# Ignore PycodestyleBear (E501)", "result", "=", "resolve_python", "(", "requirements", ",", "index_urls", "=", "index", ".", "split", "(", "\",\"", ")", "if", "index", "else", "(", "\"https://pypi.org/simple\"", ",", ")", ",", "python_version", "=", "int", "(", "python_version", ")", ",", "transitive", "=", "not", "no_transitive", ",", "exclude_packages", "=", "set", "(", "map", "(", "str", ".", "strip", ",", "(", "exclude_packages", "or", "\"\"", ")", ".", "split", "(", "\",\"", ")", ")", ")", ",", "subgraph_check_api", "=", "subgraph_check_api", ",", ")", "print_command_result", "(", "click_ctx", ",", "result", ",", "analyzer", "=", "analyzer_name", ",", "analyzer_version", "=", "analyzer_version", ",", "output", "=", "output", "or", "\"-\"", ",", "pretty", "=", "not", "no_pretty", ",", ")" ]
Manipulate with dependency requirements using PyPI.
[ "Manipulate", "with", "dependency", "requirements", "using", "PyPI", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/cli.py#L110-L149
train
thoth-station/solver
thoth/solver/python/python.py
_create_entry
def _create_entry(entry: dict, source: Source = None) -> dict: """Filter and normalize the output of pipdeptree entry.""" entry["package_name"] = entry["package"].pop("package_name") entry["package_version"] = entry["package"].pop("installed_version") if source: entry["index_url"] = source.url entry["sha256"] = [] for item in source.get_package_hashes(entry["package_name"], entry["package_version"]): entry["sha256"].append(item["sha256"]) entry.pop("package") for dependency in entry["dependencies"]: dependency.pop("key", None) dependency.pop("installed_version", None) return entry
python
def _create_entry(entry: dict, source: Source = None) -> dict: """Filter and normalize the output of pipdeptree entry.""" entry["package_name"] = entry["package"].pop("package_name") entry["package_version"] = entry["package"].pop("installed_version") if source: entry["index_url"] = source.url entry["sha256"] = [] for item in source.get_package_hashes(entry["package_name"], entry["package_version"]): entry["sha256"].append(item["sha256"]) entry.pop("package") for dependency in entry["dependencies"]: dependency.pop("key", None) dependency.pop("installed_version", None) return entry
[ "def", "_create_entry", "(", "entry", ":", "dict", ",", "source", ":", "Source", "=", "None", ")", "->", "dict", ":", "entry", "[", "\"package_name\"", "]", "=", "entry", "[", "\"package\"", "]", ".", "pop", "(", "\"package_name\"", ")", "entry", "[", "\"package_version\"", "]", "=", "entry", "[", "\"package\"", "]", ".", "pop", "(", "\"installed_version\"", ")", "if", "source", ":", "entry", "[", "\"index_url\"", "]", "=", "source", ".", "url", "entry", "[", "\"sha256\"", "]", "=", "[", "]", "for", "item", "in", "source", ".", "get_package_hashes", "(", "entry", "[", "\"package_name\"", "]", ",", "entry", "[", "\"package_version\"", "]", ")", ":", "entry", "[", "\"sha256\"", "]", ".", "append", "(", "item", "[", "\"sha256\"", "]", ")", "entry", ".", "pop", "(", "\"package\"", ")", "for", "dependency", "in", "entry", "[", "\"dependencies\"", "]", ":", "dependency", ".", "pop", "(", "\"key\"", ",", "None", ")", "dependency", ".", "pop", "(", "\"installed_version\"", ",", "None", ")", "return", "entry" ]
Filter and normalize the output of pipdeptree entry.
[ "Filter", "and", "normalize", "the", "output", "of", "pipdeptree", "entry", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L40-L56
train
thoth-station/solver
thoth/solver/python/python.py
_get_environment_details
def _get_environment_details(python_bin: str) -> list: """Get information about packages in environment where packages get installed.""" cmd = "{} -m pipdeptree --json".format(python_bin) output = run_command(cmd, is_json=True).stdout return [_create_entry(entry) for entry in output]
python
def _get_environment_details(python_bin: str) -> list: """Get information about packages in environment where packages get installed.""" cmd = "{} -m pipdeptree --json".format(python_bin) output = run_command(cmd, is_json=True).stdout return [_create_entry(entry) for entry in output]
[ "def", "_get_environment_details", "(", "python_bin", ":", "str", ")", "->", "list", ":", "cmd", "=", "\"{} -m pipdeptree --json\"", ".", "format", "(", "python_bin", ")", "output", "=", "run_command", "(", "cmd", ",", "is_json", "=", "True", ")", ".", "stdout", "return", "[", "_create_entry", "(", "entry", ")", "for", "entry", "in", "output", "]" ]
Get information about packages in environment where packages get installed.
[ "Get", "information", "about", "packages", "in", "environment", "where", "packages", "get", "installed", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L59-L63
train
thoth-station/solver
thoth/solver/python/python.py
_should_resolve_subgraph
def _should_resolve_subgraph(subgraph_check_api: str, package_name: str, package_version: str, index_url: str) -> bool: """Ask the given subgraph check API if the given package in the given version should be included in the resolution. This subgraph resolving avoidence serves two purposes - we don't need to resolve dependency subgraphs that were already analyzed and we also avoid analyzing of "core" packages (like setuptools) where not needed as they can break installation environment. """ _LOGGER.info( "Checking if the given dependency subgraph for package %r in version %r from index %r should be resolved", package_name, package_version, index_url, ) response = requests.get( subgraph_check_api, params={"package_name": package_name, "package_version": package_version, "index_url": index_url}, ) if response.status_code == 200: return True elif response.status_code == 208: # This is probably not the correct HTTP status code to be used here, but which one should be used? return False response.raise_for_status() raise ValueError( "Unreachable code - subgraph check API responded with unknown HTTP status " "code %s for package %r in version %r from index %r", package_name, package_version, index_url, )
python
def _should_resolve_subgraph(subgraph_check_api: str, package_name: str, package_version: str, index_url: str) -> bool: """Ask the given subgraph check API if the given package in the given version should be included in the resolution. This subgraph resolving avoidence serves two purposes - we don't need to resolve dependency subgraphs that were already analyzed and we also avoid analyzing of "core" packages (like setuptools) where not needed as they can break installation environment. """ _LOGGER.info( "Checking if the given dependency subgraph for package %r in version %r from index %r should be resolved", package_name, package_version, index_url, ) response = requests.get( subgraph_check_api, params={"package_name": package_name, "package_version": package_version, "index_url": index_url}, ) if response.status_code == 200: return True elif response.status_code == 208: # This is probably not the correct HTTP status code to be used here, but which one should be used? return False response.raise_for_status() raise ValueError( "Unreachable code - subgraph check API responded with unknown HTTP status " "code %s for package %r in version %r from index %r", package_name, package_version, index_url, )
[ "def", "_should_resolve_subgraph", "(", "subgraph_check_api", ":", "str", ",", "package_name", ":", "str", ",", "package_version", ":", "str", ",", "index_url", ":", "str", ")", "->", "bool", ":", "_LOGGER", ".", "info", "(", "\"Checking if the given dependency subgraph for package %r in version %r from index %r should be resolved\"", ",", "package_name", ",", "package_version", ",", "index_url", ",", ")", "response", "=", "requests", ".", "get", "(", "subgraph_check_api", ",", "params", "=", "{", "\"package_name\"", ":", "package_name", ",", "\"package_version\"", ":", "package_version", ",", "\"index_url\"", ":", "index_url", "}", ",", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "True", "elif", "response", ".", "status_code", "==", "208", ":", "# This is probably not the correct HTTP status code to be used here, but which one should be used?", "return", "False", "response", ".", "raise_for_status", "(", ")", "raise", "ValueError", "(", "\"Unreachable code - subgraph check API responded with unknown HTTP status \"", "\"code %s for package %r in version %r from index %r\"", ",", "package_name", ",", "package_version", ",", "index_url", ",", ")" ]
Ask the given subgraph check API if the given package in the given version should be included in the resolution. This subgraph resolving avoidence serves two purposes - we don't need to resolve dependency subgraphs that were already analyzed and we also avoid analyzing of "core" packages (like setuptools) where not needed as they can break installation environment.
[ "Ask", "the", "given", "subgraph", "check", "API", "if", "the", "given", "package", "in", "the", "given", "version", "should", "be", "included", "in", "the", "resolution", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L66-L99
train
thoth-station/solver
thoth/solver/python/python.py
_install_requirement
def _install_requirement( python_bin: str, package: str, version: str = None, index_url: str = None, clean: bool = True ) -> None: """Install requirements specified using suggested pip binary.""" previous_version = _pipdeptree(python_bin, package) try: cmd = "{} -m pip install --force-reinstall --no-cache-dir --no-deps {}".format(python_bin, quote(package)) if version: cmd += "=={}".format(quote(version)) if index_url: cmd += ' --index-url "{}" '.format(quote(index_url)) # Supply trusted host by default so we do not get errors - it safe to # do it here as package indexes are managed by Thoth. trusted_host = urlparse(index_url).netloc cmd += " --trusted-host {}".format(trusted_host) _LOGGER.debug("Installing requirement %r in version %r", package, version) run_command(cmd) yield finally: if clean: _LOGGER.debug("Removing installed package %r", package) cmd = "{} -m pip uninstall --yes {}".format(python_bin, quote(package)) result = run_command(cmd, raise_on_error=False) if result.return_code != 0: _LOGGER.warning( "Failed to restore previous environment by removing package %r (installed version %r), " "the error is not fatal but can affect future actions: %s", package, version, result.stderr, ) _LOGGER.debug( "Restoring previous environment setup after installation of %r (%s)", package, previous_version ) if previous_version: cmd = "{} -m pip install --force-reinstall --no-cache-dir --no-deps {}=={}".format( python_bin, quote(package), quote(previous_version["package"]["installed_version"]) ) result = run_command(cmd, raise_on_error=False) if result.return_code != 0: _LOGGER.warning( "Failed to restore previous environment for package %r (installed version %r), " ", the error is not fatal but can affect future actions (previous version: %r): %s", package, version, previous_version, result.stderr, )
python
def _install_requirement( python_bin: str, package: str, version: str = None, index_url: str = None, clean: bool = True ) -> None: """Install requirements specified using suggested pip binary.""" previous_version = _pipdeptree(python_bin, package) try: cmd = "{} -m pip install --force-reinstall --no-cache-dir --no-deps {}".format(python_bin, quote(package)) if version: cmd += "=={}".format(quote(version)) if index_url: cmd += ' --index-url "{}" '.format(quote(index_url)) # Supply trusted host by default so we do not get errors - it safe to # do it here as package indexes are managed by Thoth. trusted_host = urlparse(index_url).netloc cmd += " --trusted-host {}".format(trusted_host) _LOGGER.debug("Installing requirement %r in version %r", package, version) run_command(cmd) yield finally: if clean: _LOGGER.debug("Removing installed package %r", package) cmd = "{} -m pip uninstall --yes {}".format(python_bin, quote(package)) result = run_command(cmd, raise_on_error=False) if result.return_code != 0: _LOGGER.warning( "Failed to restore previous environment by removing package %r (installed version %r), " "the error is not fatal but can affect future actions: %s", package, version, result.stderr, ) _LOGGER.debug( "Restoring previous environment setup after installation of %r (%s)", package, previous_version ) if previous_version: cmd = "{} -m pip install --force-reinstall --no-cache-dir --no-deps {}=={}".format( python_bin, quote(package), quote(previous_version["package"]["installed_version"]) ) result = run_command(cmd, raise_on_error=False) if result.return_code != 0: _LOGGER.warning( "Failed to restore previous environment for package %r (installed version %r), " ", the error is not fatal but can affect future actions (previous version: %r): %s", package, version, previous_version, result.stderr, )
[ "def", "_install_requirement", "(", "python_bin", ":", "str", ",", "package", ":", "str", ",", "version", ":", "str", "=", "None", ",", "index_url", ":", "str", "=", "None", ",", "clean", ":", "bool", "=", "True", ")", "->", "None", ":", "previous_version", "=", "_pipdeptree", "(", "python_bin", ",", "package", ")", "try", ":", "cmd", "=", "\"{} -m pip install --force-reinstall --no-cache-dir --no-deps {}\"", ".", "format", "(", "python_bin", ",", "quote", "(", "package", ")", ")", "if", "version", ":", "cmd", "+=", "\"=={}\"", ".", "format", "(", "quote", "(", "version", ")", ")", "if", "index_url", ":", "cmd", "+=", "' --index-url \"{}\" '", ".", "format", "(", "quote", "(", "index_url", ")", ")", "# Supply trusted host by default so we do not get errors - it safe to", "# do it here as package indexes are managed by Thoth.", "trusted_host", "=", "urlparse", "(", "index_url", ")", ".", "netloc", "cmd", "+=", "\" --trusted-host {}\"", ".", "format", "(", "trusted_host", ")", "_LOGGER", ".", "debug", "(", "\"Installing requirement %r in version %r\"", ",", "package", ",", "version", ")", "run_command", "(", "cmd", ")", "yield", "finally", ":", "if", "clean", ":", "_LOGGER", ".", "debug", "(", "\"Removing installed package %r\"", ",", "package", ")", "cmd", "=", "\"{} -m pip uninstall --yes {}\"", ".", "format", "(", "python_bin", ",", "quote", "(", "package", ")", ")", "result", "=", "run_command", "(", "cmd", ",", "raise_on_error", "=", "False", ")", "if", "result", ".", "return_code", "!=", "0", ":", "_LOGGER", ".", "warning", "(", "\"Failed to restore previous environment by removing package %r (installed version %r), \"", "\"the error is not fatal but can affect future actions: %s\"", ",", "package", ",", "version", ",", "result", ".", "stderr", ",", ")", "_LOGGER", ".", "debug", "(", "\"Restoring previous environment setup after installation of %r (%s)\"", ",", "package", ",", "previous_version", ")", "if", "previous_version", ":", "cmd", "=", "\"{} -m pip install --force-reinstall --no-cache-dir --no-deps {}=={}\"", ".", "format", "(", "python_bin", ",", "quote", "(", "package", ")", ",", "quote", "(", "previous_version", "[", "\"package\"", "]", "[", "\"installed_version\"", "]", ")", ")", "result", "=", "run_command", "(", "cmd", ",", "raise_on_error", "=", "False", ")", "if", "result", ".", "return_code", "!=", "0", ":", "_LOGGER", ".", "warning", "(", "\"Failed to restore previous environment for package %r (installed version %r), \"", "\", the error is not fatal but can affect future actions (previous version: %r): %s\"", ",", "package", ",", "version", ",", "previous_version", ",", "result", ".", "stderr", ",", ")" ]
Install requirements specified using suggested pip binary.
[ "Install", "requirements", "specified", "using", "suggested", "pip", "binary", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L103-L155
train
thoth-station/solver
thoth/solver/python/python.py
_pipdeptree
def _pipdeptree(python_bin, package_name: str = None, warn: bool = False) -> typing.Optional[dict]: """Get pip dependency tree by executing pipdeptree tool.""" cmd = "{} -m pipdeptree --json".format(python_bin) _LOGGER.debug("Obtaining pip dependency tree using: %r", cmd) output = run_command(cmd, is_json=True).stdout if not package_name: return output for entry in output: # In some versions pipdeptree does not work with --packages flag, do the logic on out own. # TODO: we should probably do difference of reference this output and original environment if entry["package"]["key"].lower() == package_name.lower(): return entry # The given package was not found. if warn: _LOGGER.warning("Package %r was not found in pipdeptree output %r", package_name, output) return None
python
def _pipdeptree(python_bin, package_name: str = None, warn: bool = False) -> typing.Optional[dict]: """Get pip dependency tree by executing pipdeptree tool.""" cmd = "{} -m pipdeptree --json".format(python_bin) _LOGGER.debug("Obtaining pip dependency tree using: %r", cmd) output = run_command(cmd, is_json=True).stdout if not package_name: return output for entry in output: # In some versions pipdeptree does not work with --packages flag, do the logic on out own. # TODO: we should probably do difference of reference this output and original environment if entry["package"]["key"].lower() == package_name.lower(): return entry # The given package was not found. if warn: _LOGGER.warning("Package %r was not found in pipdeptree output %r", package_name, output) return None
[ "def", "_pipdeptree", "(", "python_bin", ",", "package_name", ":", "str", "=", "None", ",", "warn", ":", "bool", "=", "False", ")", "->", "typing", ".", "Optional", "[", "dict", "]", ":", "cmd", "=", "\"{} -m pipdeptree --json\"", ".", "format", "(", "python_bin", ")", "_LOGGER", ".", "debug", "(", "\"Obtaining pip dependency tree using: %r\"", ",", "cmd", ")", "output", "=", "run_command", "(", "cmd", ",", "is_json", "=", "True", ")", ".", "stdout", "if", "not", "package_name", ":", "return", "output", "for", "entry", "in", "output", ":", "# In some versions pipdeptree does not work with --packages flag, do the logic on out own.", "# TODO: we should probably do difference of reference this output and original environment", "if", "entry", "[", "\"package\"", "]", "[", "\"key\"", "]", ".", "lower", "(", ")", "==", "package_name", ".", "lower", "(", ")", ":", "return", "entry", "# The given package was not found.", "if", "warn", ":", "_LOGGER", ".", "warning", "(", "\"Package %r was not found in pipdeptree output %r\"", ",", "package_name", ",", "output", ")", "return", "None" ]
Get pip dependency tree by executing pipdeptree tool.
[ "Get", "pip", "dependency", "tree", "by", "executing", "pipdeptree", "tool", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L158-L177
train
thoth-station/solver
thoth/solver/python/python.py
_get_dependency_specification
def _get_dependency_specification(dep_spec: typing.List[tuple]) -> str: """Get string representation of dependency specification as provided by PythonDependencyParser.""" return ",".join(dep_range[0] + dep_range[1] for dep_range in dep_spec)
python
def _get_dependency_specification(dep_spec: typing.List[tuple]) -> str: """Get string representation of dependency specification as provided by PythonDependencyParser.""" return ",".join(dep_range[0] + dep_range[1] for dep_range in dep_spec)
[ "def", "_get_dependency_specification", "(", "dep_spec", ":", "typing", ".", "List", "[", "tuple", "]", ")", "->", "str", ":", "return", "\",\"", ".", "join", "(", "dep_range", "[", "0", "]", "+", "dep_range", "[", "1", "]", "for", "dep_range", "in", "dep_spec", ")" ]
Get string representation of dependency specification as provided by PythonDependencyParser.
[ "Get", "string", "representation", "of", "dependency", "specification", "as", "provided", "by", "PythonDependencyParser", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L180-L182
train
thoth-station/solver
thoth/solver/python/python.py
resolve
def resolve( requirements: typing.List[str], index_urls: list = None, python_version: int = 3, exclude_packages: set = None, transitive: bool = True, subgraph_check_api: str = None, ) -> dict: """Resolve given requirements for the given Python version.""" assert python_version in (2, 3), "Unknown Python version" if subgraph_check_api and not transitive: _LOGGER.error("The check against subgraph API cannot be done if no transitive dependencies are resolved") sys.exit(2) python_bin = "python3" if python_version == 3 else "python2" run_command("virtualenv -p python3 venv") python_bin = "venv/bin/" + python_bin run_command("{} -m pip install pipdeptree".format(python_bin)) environment_details = _get_environment_details(python_bin) result = {"tree": [], "errors": [], "unparsed": [], "unresolved": [], "environment": environment_details} all_solvers = [] for index_url in index_urls: source = Source(index_url) all_solvers.append(PythonSolver(fetcher_kwargs={"source": source})) for solver in all_solvers: solver_result = _do_resolve_index( python_bin=python_bin, solver=solver, all_solvers=all_solvers, requirements=requirements, exclude_packages=exclude_packages, transitive=transitive, subgraph_check_api=subgraph_check_api, ) result["tree"].extend(solver_result["tree"]) result["errors"].extend(solver_result["errors"]) result["unparsed"].extend(solver_result["unparsed"]) result["unresolved"].extend(solver_result["unresolved"]) return result
python
def resolve( requirements: typing.List[str], index_urls: list = None, python_version: int = 3, exclude_packages: set = None, transitive: bool = True, subgraph_check_api: str = None, ) -> dict: """Resolve given requirements for the given Python version.""" assert python_version in (2, 3), "Unknown Python version" if subgraph_check_api and not transitive: _LOGGER.error("The check against subgraph API cannot be done if no transitive dependencies are resolved") sys.exit(2) python_bin = "python3" if python_version == 3 else "python2" run_command("virtualenv -p python3 venv") python_bin = "venv/bin/" + python_bin run_command("{} -m pip install pipdeptree".format(python_bin)) environment_details = _get_environment_details(python_bin) result = {"tree": [], "errors": [], "unparsed": [], "unresolved": [], "environment": environment_details} all_solvers = [] for index_url in index_urls: source = Source(index_url) all_solvers.append(PythonSolver(fetcher_kwargs={"source": source})) for solver in all_solvers: solver_result = _do_resolve_index( python_bin=python_bin, solver=solver, all_solvers=all_solvers, requirements=requirements, exclude_packages=exclude_packages, transitive=transitive, subgraph_check_api=subgraph_check_api, ) result["tree"].extend(solver_result["tree"]) result["errors"].extend(solver_result["errors"]) result["unparsed"].extend(solver_result["unparsed"]) result["unresolved"].extend(solver_result["unresolved"]) return result
[ "def", "resolve", "(", "requirements", ":", "typing", ".", "List", "[", "str", "]", ",", "index_urls", ":", "list", "=", "None", ",", "python_version", ":", "int", "=", "3", ",", "exclude_packages", ":", "set", "=", "None", ",", "transitive", ":", "bool", "=", "True", ",", "subgraph_check_api", ":", "str", "=", "None", ",", ")", "->", "dict", ":", "assert", "python_version", "in", "(", "2", ",", "3", ")", ",", "\"Unknown Python version\"", "if", "subgraph_check_api", "and", "not", "transitive", ":", "_LOGGER", ".", "error", "(", "\"The check against subgraph API cannot be done if no transitive dependencies are resolved\"", ")", "sys", ".", "exit", "(", "2", ")", "python_bin", "=", "\"python3\"", "if", "python_version", "==", "3", "else", "\"python2\"", "run_command", "(", "\"virtualenv -p python3 venv\"", ")", "python_bin", "=", "\"venv/bin/\"", "+", "python_bin", "run_command", "(", "\"{} -m pip install pipdeptree\"", ".", "format", "(", "python_bin", ")", ")", "environment_details", "=", "_get_environment_details", "(", "python_bin", ")", "result", "=", "{", "\"tree\"", ":", "[", "]", ",", "\"errors\"", ":", "[", "]", ",", "\"unparsed\"", ":", "[", "]", ",", "\"unresolved\"", ":", "[", "]", ",", "\"environment\"", ":", "environment_details", "}", "all_solvers", "=", "[", "]", "for", "index_url", "in", "index_urls", ":", "source", "=", "Source", "(", "index_url", ")", "all_solvers", ".", "append", "(", "PythonSolver", "(", "fetcher_kwargs", "=", "{", "\"source\"", ":", "source", "}", ")", ")", "for", "solver", "in", "all_solvers", ":", "solver_result", "=", "_do_resolve_index", "(", "python_bin", "=", "python_bin", ",", "solver", "=", "solver", ",", "all_solvers", "=", "all_solvers", ",", "requirements", "=", "requirements", ",", "exclude_packages", "=", "exclude_packages", ",", "transitive", "=", "transitive", ",", "subgraph_check_api", "=", "subgraph_check_api", ",", ")", "result", "[", "\"tree\"", "]", ".", "extend", "(", "solver_result", "[", "\"tree\"", "]", ")", "result", "[", "\"errors\"", "]", ".", "extend", "(", "solver_result", "[", "\"errors\"", "]", ")", "result", "[", "\"unparsed\"", "]", ".", "extend", "(", "solver_result", "[", "\"unparsed\"", "]", ")", "result", "[", "\"unresolved\"", "]", ".", "extend", "(", "solver_result", "[", "\"unresolved\"", "]", ")", "return", "result" ]
Resolve given requirements for the given Python version.
[ "Resolve", "given", "requirements", "for", "the", "given", "Python", "version", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L356-L401
train
thoth-station/solver
thoth/solver/python/python_solver.py
PythonReleasesFetcher.fetch_releases
def fetch_releases(self, package_name): """Fetch package and index_url for a package_name.""" package_name = self.source.normalize_package_name(package_name) releases = self.source.get_package_versions(package_name) releases_with_index_url = [(item, self.index_url) for item in releases] return package_name, releases_with_index_url
python
def fetch_releases(self, package_name): """Fetch package and index_url for a package_name.""" package_name = self.source.normalize_package_name(package_name) releases = self.source.get_package_versions(package_name) releases_with_index_url = [(item, self.index_url) for item in releases] return package_name, releases_with_index_url
[ "def", "fetch_releases", "(", "self", ",", "package_name", ")", ":", "package_name", "=", "self", ".", "source", ".", "normalize_package_name", "(", "package_name", ")", "releases", "=", "self", ".", "source", ".", "get_package_versions", "(", "package_name", ")", "releases_with_index_url", "=", "[", "(", "item", ",", "self", ".", "index_url", ")", "for", "item", "in", "releases", "]", "return", "package_name", ",", "releases_with_index_url" ]
Fetch package and index_url for a package_name.
[ "Fetch", "package", "and", "index_url", "for", "a", "package_name", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python_solver.py#L49-L54
train
thoth-station/solver
thoth/solver/python/python_solver.py
PythonDependencyParser.parse_python
def parse_python(spec): # Ignore PyDocStyleBear """Parse PyPI specification of a single dependency. :param spec: str, for example "Django>=1.5,<1.8" :return: [Django [[('>=', '1.5'), ('<', '1.8')]]] """ def _extract_op_version(spec): # https://www.python.org/dev/peps/pep-0440/#compatible-release if spec.operator == "~=": version = spec.version.split(".") if len(version) in {2, 3, 4}: if len(version) in {3, 4}: del version[-1] # will increase the last but one in next line version[-1] = str(int(version[-1]) + 1) else: raise ValueError("%r must not be used with %r" % (spec.operator, spec.version)) return [(">=", spec.version), ("<", ".".join(version))] # Trailing .* is permitted per # https://www.python.org/dev/peps/pep-0440/#version-matching elif spec.operator == "==" and spec.version.endswith(".*"): try: result = check_output(["/usr/bin/semver-ranger", spec.version], universal_newlines=True).strip() gte, lt = result.split() return [(">=", gte.lstrip(">=")), ("<", lt.lstrip("<"))] except ValueError: _LOGGER.warning("couldn't resolve ==%s", spec.version) return spec.operator, spec.version # https://www.python.org/dev/peps/pep-0440/#arbitrary-equality # Use of this operator is heavily discouraged, so just convert it to 'Version matching' elif spec.operator == "===": return "==", spec.version else: return spec.operator, spec.version def _get_pip_spec(requirements): """There is no `specs` field In Pip 8+, take info from `specifier` field.""" if hasattr(requirements, "specs"): return requirements.specs elif hasattr(requirements, "specifier"): specs = [_extract_op_version(spec) for spec in requirements.specifier] if len(specs) == 0: # TODO: I'm not sure with this one # we should probably return None instead and let pip deal with this specs = [(">=", "0.0.0")] return specs _LOGGER.info("Parsing dependency %r", spec) # create a temporary file and store the spec there since # `parse_requirements` requires a file with NamedTemporaryFile(mode="w+", suffix="pysolve") as f: f.write(spec) f.flush() parsed = parse_requirements(f.name, session=f.name) dependency = [Dependency(x.name, _get_pip_spec(x.req)) for x in parsed].pop() return dependency
python
def parse_python(spec): # Ignore PyDocStyleBear """Parse PyPI specification of a single dependency. :param spec: str, for example "Django>=1.5,<1.8" :return: [Django [[('>=', '1.5'), ('<', '1.8')]]] """ def _extract_op_version(spec): # https://www.python.org/dev/peps/pep-0440/#compatible-release if spec.operator == "~=": version = spec.version.split(".") if len(version) in {2, 3, 4}: if len(version) in {3, 4}: del version[-1] # will increase the last but one in next line version[-1] = str(int(version[-1]) + 1) else: raise ValueError("%r must not be used with %r" % (spec.operator, spec.version)) return [(">=", spec.version), ("<", ".".join(version))] # Trailing .* is permitted per # https://www.python.org/dev/peps/pep-0440/#version-matching elif spec.operator == "==" and spec.version.endswith(".*"): try: result = check_output(["/usr/bin/semver-ranger", spec.version], universal_newlines=True).strip() gte, lt = result.split() return [(">=", gte.lstrip(">=")), ("<", lt.lstrip("<"))] except ValueError: _LOGGER.warning("couldn't resolve ==%s", spec.version) return spec.operator, spec.version # https://www.python.org/dev/peps/pep-0440/#arbitrary-equality # Use of this operator is heavily discouraged, so just convert it to 'Version matching' elif spec.operator == "===": return "==", spec.version else: return spec.operator, spec.version def _get_pip_spec(requirements): """There is no `specs` field In Pip 8+, take info from `specifier` field.""" if hasattr(requirements, "specs"): return requirements.specs elif hasattr(requirements, "specifier"): specs = [_extract_op_version(spec) for spec in requirements.specifier] if len(specs) == 0: # TODO: I'm not sure with this one # we should probably return None instead and let pip deal with this specs = [(">=", "0.0.0")] return specs _LOGGER.info("Parsing dependency %r", spec) # create a temporary file and store the spec there since # `parse_requirements` requires a file with NamedTemporaryFile(mode="w+", suffix="pysolve") as f: f.write(spec) f.flush() parsed = parse_requirements(f.name, session=f.name) dependency = [Dependency(x.name, _get_pip_spec(x.req)) for x in parsed].pop() return dependency
[ "def", "parse_python", "(", "spec", ")", ":", "# Ignore PyDocStyleBear", "def", "_extract_op_version", "(", "spec", ")", ":", "# https://www.python.org/dev/peps/pep-0440/#compatible-release", "if", "spec", ".", "operator", "==", "\"~=\"", ":", "version", "=", "spec", ".", "version", ".", "split", "(", "\".\"", ")", "if", "len", "(", "version", ")", "in", "{", "2", ",", "3", ",", "4", "}", ":", "if", "len", "(", "version", ")", "in", "{", "3", ",", "4", "}", ":", "del", "version", "[", "-", "1", "]", "# will increase the last but one in next line", "version", "[", "-", "1", "]", "=", "str", "(", "int", "(", "version", "[", "-", "1", "]", ")", "+", "1", ")", "else", ":", "raise", "ValueError", "(", "\"%r must not be used with %r\"", "%", "(", "spec", ".", "operator", ",", "spec", ".", "version", ")", ")", "return", "[", "(", "\">=\"", ",", "spec", ".", "version", ")", ",", "(", "\"<\"", ",", "\".\"", ".", "join", "(", "version", ")", ")", "]", "# Trailing .* is permitted per", "# https://www.python.org/dev/peps/pep-0440/#version-matching", "elif", "spec", ".", "operator", "==", "\"==\"", "and", "spec", ".", "version", ".", "endswith", "(", "\".*\"", ")", ":", "try", ":", "result", "=", "check_output", "(", "[", "\"/usr/bin/semver-ranger\"", ",", "spec", ".", "version", "]", ",", "universal_newlines", "=", "True", ")", ".", "strip", "(", ")", "gte", ",", "lt", "=", "result", ".", "split", "(", ")", "return", "[", "(", "\">=\"", ",", "gte", ".", "lstrip", "(", "\">=\"", ")", ")", ",", "(", "\"<\"", ",", "lt", ".", "lstrip", "(", "\"<\"", ")", ")", "]", "except", "ValueError", ":", "_LOGGER", ".", "warning", "(", "\"couldn't resolve ==%s\"", ",", "spec", ".", "version", ")", "return", "spec", ".", "operator", ",", "spec", ".", "version", "# https://www.python.org/dev/peps/pep-0440/#arbitrary-equality", "# Use of this operator is heavily discouraged, so just convert it to 'Version matching'", "elif", "spec", ".", "operator", "==", "\"===\"", ":", "return", "\"==\"", ",", "spec", ".", "version", "else", ":", "return", "spec", ".", "operator", ",", "spec", ".", "version", "def", "_get_pip_spec", "(", "requirements", ")", ":", "\"\"\"There is no `specs` field In Pip 8+, take info from `specifier` field.\"\"\"", "if", "hasattr", "(", "requirements", ",", "\"specs\"", ")", ":", "return", "requirements", ".", "specs", "elif", "hasattr", "(", "requirements", ",", "\"specifier\"", ")", ":", "specs", "=", "[", "_extract_op_version", "(", "spec", ")", "for", "spec", "in", "requirements", ".", "specifier", "]", "if", "len", "(", "specs", ")", "==", "0", ":", "# TODO: I'm not sure with this one", "# we should probably return None instead and let pip deal with this", "specs", "=", "[", "(", "\">=\"", ",", "\"0.0.0\"", ")", "]", "return", "specs", "_LOGGER", ".", "info", "(", "\"Parsing dependency %r\"", ",", "spec", ")", "# create a temporary file and store the spec there since", "# `parse_requirements` requires a file", "with", "NamedTemporaryFile", "(", "mode", "=", "\"w+\"", ",", "suffix", "=", "\"pysolve\"", ")", "as", "f", ":", "f", ".", "write", "(", "spec", ")", "f", ".", "flush", "(", ")", "parsed", "=", "parse_requirements", "(", "f", ".", "name", ",", "session", "=", "f", ".", "name", ")", "dependency", "=", "[", "Dependency", "(", "x", ".", "name", ",", "_get_pip_spec", "(", "x", ".", "req", ")", ")", "for", "x", "in", "parsed", "]", ".", "pop", "(", ")", "return", "dependency" ]
Parse PyPI specification of a single dependency. :param spec: str, for example "Django>=1.5,<1.8" :return: [Django [[('>=', '1.5'), ('<', '1.8')]]]
[ "Parse", "PyPI", "specification", "of", "a", "single", "dependency", "." ]
de9bd6e744cb4d5f70320ba77d6875ccb8b876c4
https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python_solver.py#L66-L122
train
floyernick/fleep-py
fleep/__init__.py
get
def get(obj): """ Determines file format and picks suitable file types, extensions and MIME types Takes: obj (bytes) -> byte sequence (128 bytes are enough) Returns: (<class 'fleep.Info'>) -> Class instance """ if not isinstance(obj, bytes): raise TypeError("object type must be bytes") info = { "type": dict(), "extension": dict(), "mime": dict() } stream = " ".join(['{:02X}'.format(byte) for byte in obj]) for element in data: for signature in element["signature"]: offset = element["offset"] * 2 + element["offset"] if signature == stream[offset:len(signature) + offset]: for key in ["type", "extension", "mime"]: info[key][element[key]] = len(signature) for key in ["type", "extension", "mime"]: info[key] = [element for element in sorted(info[key], key=info[key].get, reverse=True)] return Info(info["type"], info["extension"], info["mime"])
python
def get(obj): """ Determines file format and picks suitable file types, extensions and MIME types Takes: obj (bytes) -> byte sequence (128 bytes are enough) Returns: (<class 'fleep.Info'>) -> Class instance """ if not isinstance(obj, bytes): raise TypeError("object type must be bytes") info = { "type": dict(), "extension": dict(), "mime": dict() } stream = " ".join(['{:02X}'.format(byte) for byte in obj]) for element in data: for signature in element["signature"]: offset = element["offset"] * 2 + element["offset"] if signature == stream[offset:len(signature) + offset]: for key in ["type", "extension", "mime"]: info[key][element[key]] = len(signature) for key in ["type", "extension", "mime"]: info[key] = [element for element in sorted(info[key], key=info[key].get, reverse=True)] return Info(info["type"], info["extension"], info["mime"])
[ "def", "get", "(", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"object type must be bytes\"", ")", "info", "=", "{", "\"type\"", ":", "dict", "(", ")", ",", "\"extension\"", ":", "dict", "(", ")", ",", "\"mime\"", ":", "dict", "(", ")", "}", "stream", "=", "\" \"", ".", "join", "(", "[", "'{:02X}'", ".", "format", "(", "byte", ")", "for", "byte", "in", "obj", "]", ")", "for", "element", "in", "data", ":", "for", "signature", "in", "element", "[", "\"signature\"", "]", ":", "offset", "=", "element", "[", "\"offset\"", "]", "*", "2", "+", "element", "[", "\"offset\"", "]", "if", "signature", "==", "stream", "[", "offset", ":", "len", "(", "signature", ")", "+", "offset", "]", ":", "for", "key", "in", "[", "\"type\"", ",", "\"extension\"", ",", "\"mime\"", "]", ":", "info", "[", "key", "]", "[", "element", "[", "key", "]", "]", "=", "len", "(", "signature", ")", "for", "key", "in", "[", "\"type\"", ",", "\"extension\"", ",", "\"mime\"", "]", ":", "info", "[", "key", "]", "=", "[", "element", "for", "element", "in", "sorted", "(", "info", "[", "key", "]", ",", "key", "=", "info", "[", "key", "]", ".", "get", ",", "reverse", "=", "True", ")", "]", "return", "Info", "(", "info", "[", "\"type\"", "]", ",", "info", "[", "\"extension\"", "]", ",", "info", "[", "\"mime\"", "]", ")" ]
Determines file format and picks suitable file types, extensions and MIME types Takes: obj (bytes) -> byte sequence (128 bytes are enough) Returns: (<class 'fleep.Info'>) -> Class instance
[ "Determines", "file", "format", "and", "picks", "suitable", "file", "types", "extensions", "and", "MIME", "types" ]
994bc2c274482d80ab13d89d8f7343eb316d3e44
https://github.com/floyernick/fleep-py/blob/994bc2c274482d80ab13d89d8f7343eb316d3e44/fleep/__init__.py#L50-L82
train
scikit-tda/persim
persim/plot.py
bottleneck_matching
def bottleneck_matching(I1, I2, matchidx, D, labels=["dgm1", "dgm2"], ax=None): """ Visualize bottleneck matching between two diagrams Parameters =========== I1: array A diagram I2: array A diagram matchidx: tuples of matched indices if input `matching=True`, then return matching D: array cross-similarity matrix labels: list of strings names of diagrams for legend. Default = ["dgm1", "dgm2"], ax: matplotlib Axis object For plotting on a particular axis. """ plot_diagrams([I1, I2], labels=labels, ax=ax) cp = np.cos(np.pi / 4) sp = np.sin(np.pi / 4) R = np.array([[cp, -sp], [sp, cp]]) if I1.size == 0: I1 = np.array([[0, 0]]) if I2.size == 0: I2 = np.array([[0, 0]]) I1Rot = I1.dot(R) I2Rot = I2.dot(R) dists = [D[i, j] for (i, j) in matchidx] (i, j) = matchidx[np.argmax(dists)] if i >= I1.shape[0] and j >= I2.shape[0]: return if i >= I1.shape[0]: diagElem = np.array([I2Rot[j, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I2[j, 0], diagElem[0]], [I2[j, 1], diagElem[1]], "g") elif j >= I2.shape[0]: diagElem = np.array([I1Rot[i, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I1[i, 0], diagElem[0]], [I1[i, 1], diagElem[1]], "g") else: plt.plot([I1[i, 0], I2[j, 0]], [I1[i, 1], I2[j, 1]], "g")
python
def bottleneck_matching(I1, I2, matchidx, D, labels=["dgm1", "dgm2"], ax=None): """ Visualize bottleneck matching between two diagrams Parameters =========== I1: array A diagram I2: array A diagram matchidx: tuples of matched indices if input `matching=True`, then return matching D: array cross-similarity matrix labels: list of strings names of diagrams for legend. Default = ["dgm1", "dgm2"], ax: matplotlib Axis object For plotting on a particular axis. """ plot_diagrams([I1, I2], labels=labels, ax=ax) cp = np.cos(np.pi / 4) sp = np.sin(np.pi / 4) R = np.array([[cp, -sp], [sp, cp]]) if I1.size == 0: I1 = np.array([[0, 0]]) if I2.size == 0: I2 = np.array([[0, 0]]) I1Rot = I1.dot(R) I2Rot = I2.dot(R) dists = [D[i, j] for (i, j) in matchidx] (i, j) = matchidx[np.argmax(dists)] if i >= I1.shape[0] and j >= I2.shape[0]: return if i >= I1.shape[0]: diagElem = np.array([I2Rot[j, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I2[j, 0], diagElem[0]], [I2[j, 1], diagElem[1]], "g") elif j >= I2.shape[0]: diagElem = np.array([I1Rot[i, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I1[i, 0], diagElem[0]], [I1[i, 1], diagElem[1]], "g") else: plt.plot([I1[i, 0], I2[j, 0]], [I1[i, 1], I2[j, 1]], "g")
[ "def", "bottleneck_matching", "(", "I1", ",", "I2", ",", "matchidx", ",", "D", ",", "labels", "=", "[", "\"dgm1\"", ",", "\"dgm2\"", "]", ",", "ax", "=", "None", ")", ":", "plot_diagrams", "(", "[", "I1", ",", "I2", "]", ",", "labels", "=", "labels", ",", "ax", "=", "ax", ")", "cp", "=", "np", ".", "cos", "(", "np", ".", "pi", "/", "4", ")", "sp", "=", "np", ".", "sin", "(", "np", ".", "pi", "/", "4", ")", "R", "=", "np", ".", "array", "(", "[", "[", "cp", ",", "-", "sp", "]", ",", "[", "sp", ",", "cp", "]", "]", ")", "if", "I1", ".", "size", "==", "0", ":", "I1", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", "]", "]", ")", "if", "I2", ".", "size", "==", "0", ":", "I2", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", "]", "]", ")", "I1Rot", "=", "I1", ".", "dot", "(", "R", ")", "I2Rot", "=", "I2", ".", "dot", "(", "R", ")", "dists", "=", "[", "D", "[", "i", ",", "j", "]", "for", "(", "i", ",", "j", ")", "in", "matchidx", "]", "(", "i", ",", "j", ")", "=", "matchidx", "[", "np", ".", "argmax", "(", "dists", ")", "]", "if", "i", ">=", "I1", ".", "shape", "[", "0", "]", "and", "j", ">=", "I2", ".", "shape", "[", "0", "]", ":", "return", "if", "i", ">=", "I1", ".", "shape", "[", "0", "]", ":", "diagElem", "=", "np", ".", "array", "(", "[", "I2Rot", "[", "j", ",", "0", "]", ",", "0", "]", ")", "diagElem", "=", "diagElem", ".", "dot", "(", "R", ".", "T", ")", "plt", ".", "plot", "(", "[", "I2", "[", "j", ",", "0", "]", ",", "diagElem", "[", "0", "]", "]", ",", "[", "I2", "[", "j", ",", "1", "]", ",", "diagElem", "[", "1", "]", "]", ",", "\"g\"", ")", "elif", "j", ">=", "I2", ".", "shape", "[", "0", "]", ":", "diagElem", "=", "np", ".", "array", "(", "[", "I1Rot", "[", "i", ",", "0", "]", ",", "0", "]", ")", "diagElem", "=", "diagElem", ".", "dot", "(", "R", ".", "T", ")", "plt", ".", "plot", "(", "[", "I1", "[", "i", ",", "0", "]", ",", "diagElem", "[", "0", "]", "]", ",", "[", "I1", "[", "i", ",", "1", "]", ",", "diagElem", "[", "1", "]", "]", ",", "\"g\"", ")", "else", ":", "plt", ".", "plot", "(", "[", "I1", "[", "i", ",", "0", "]", ",", "I2", "[", "j", ",", "0", "]", "]", ",", "[", "I1", "[", "i", ",", "1", "]", ",", "I2", "[", "j", ",", "1", "]", "]", ",", "\"g\"", ")" ]
Visualize bottleneck matching between two diagrams Parameters =========== I1: array A diagram I2: array A diagram matchidx: tuples of matched indices if input `matching=True`, then return matching D: array cross-similarity matrix labels: list of strings names of diagrams for legend. Default = ["dgm1", "dgm2"], ax: matplotlib Axis object For plotting on a particular axis.
[ "Visualize", "bottleneck", "matching", "between", "two", "diagrams" ]
f234f543058bdedb9729bf8c4a90da41e57954e0
https://github.com/scikit-tda/persim/blob/f234f543058bdedb9729bf8c4a90da41e57954e0/persim/plot.py#L9-L53
train
scikit-tda/persim
persim/images.py
PersImage.transform
def transform(self, diagrams): """ Convert diagram or list of diagrams to a persistence image. Parameters ----------- diagrams : list of or singleton diagram, list of pairs. [(birth, death)] Persistence diagrams to be converted to persistence images. It is assumed they are in (birth, death) format. Can input a list of diagrams or a single diagram. """ # if diagram is empty, return empty image if len(diagrams) == 0: return np.zeros((self.nx, self.ny)) # if first entry of first entry is not iterable, then diagrams is singular and we need to make it a list of diagrams try: singular = not isinstance(diagrams[0][0], collections.Iterable) except IndexError: singular = False if singular: diagrams = [diagrams] dgs = [np.copy(diagram, np.float64) for diagram in diagrams] landscapes = [PersImage.to_landscape(dg) for dg in dgs] if not self.specs: self.specs = { "maxBD": np.max([np.max(np.vstack((landscape, np.zeros((1, 2))))) for landscape in landscapes] + [0]), "minBD": np.min([np.min(np.vstack((landscape, np.zeros((1, 2))))) for landscape in landscapes] + [0]), } imgs = [self._transform(dgm) for dgm in landscapes] # Make sure we return one item. if singular: imgs = imgs[0] return imgs
python
def transform(self, diagrams): """ Convert diagram or list of diagrams to a persistence image. Parameters ----------- diagrams : list of or singleton diagram, list of pairs. [(birth, death)] Persistence diagrams to be converted to persistence images. It is assumed they are in (birth, death) format. Can input a list of diagrams or a single diagram. """ # if diagram is empty, return empty image if len(diagrams) == 0: return np.zeros((self.nx, self.ny)) # if first entry of first entry is not iterable, then diagrams is singular and we need to make it a list of diagrams try: singular = not isinstance(diagrams[0][0], collections.Iterable) except IndexError: singular = False if singular: diagrams = [diagrams] dgs = [np.copy(diagram, np.float64) for diagram in diagrams] landscapes = [PersImage.to_landscape(dg) for dg in dgs] if not self.specs: self.specs = { "maxBD": np.max([np.max(np.vstack((landscape, np.zeros((1, 2))))) for landscape in landscapes] + [0]), "minBD": np.min([np.min(np.vstack((landscape, np.zeros((1, 2))))) for landscape in landscapes] + [0]), } imgs = [self._transform(dgm) for dgm in landscapes] # Make sure we return one item. if singular: imgs = imgs[0] return imgs
[ "def", "transform", "(", "self", ",", "diagrams", ")", ":", "# if diagram is empty, return empty image", "if", "len", "(", "diagrams", ")", "==", "0", ":", "return", "np", ".", "zeros", "(", "(", "self", ".", "nx", ",", "self", ".", "ny", ")", ")", "# if first entry of first entry is not iterable, then diagrams is singular and we need to make it a list of diagrams", "try", ":", "singular", "=", "not", "isinstance", "(", "diagrams", "[", "0", "]", "[", "0", "]", ",", "collections", ".", "Iterable", ")", "except", "IndexError", ":", "singular", "=", "False", "if", "singular", ":", "diagrams", "=", "[", "diagrams", "]", "dgs", "=", "[", "np", ".", "copy", "(", "diagram", ",", "np", ".", "float64", ")", "for", "diagram", "in", "diagrams", "]", "landscapes", "=", "[", "PersImage", ".", "to_landscape", "(", "dg", ")", "for", "dg", "in", "dgs", "]", "if", "not", "self", ".", "specs", ":", "self", ".", "specs", "=", "{", "\"maxBD\"", ":", "np", ".", "max", "(", "[", "np", ".", "max", "(", "np", ".", "vstack", "(", "(", "landscape", ",", "np", ".", "zeros", "(", "(", "1", ",", "2", ")", ")", ")", ")", ")", "for", "landscape", "in", "landscapes", "]", "+", "[", "0", "]", ")", ",", "\"minBD\"", ":", "np", ".", "min", "(", "[", "np", ".", "min", "(", "np", ".", "vstack", "(", "(", "landscape", ",", "np", ".", "zeros", "(", "(", "1", ",", "2", ")", ")", ")", ")", ")", "for", "landscape", "in", "landscapes", "]", "+", "[", "0", "]", ")", ",", "}", "imgs", "=", "[", "self", ".", "_transform", "(", "dgm", ")", "for", "dgm", "in", "landscapes", "]", "# Make sure we return one item.", "if", "singular", ":", "imgs", "=", "imgs", "[", "0", "]", "return", "imgs" ]
Convert diagram or list of diagrams to a persistence image. Parameters ----------- diagrams : list of or singleton diagram, list of pairs. [(birth, death)] Persistence diagrams to be converted to persistence images. It is assumed they are in (birth, death) format. Can input a list of diagrams or a single diagram.
[ "Convert", "diagram", "or", "list", "of", "diagrams", "to", "a", "persistence", "image", "." ]
f234f543058bdedb9729bf8c4a90da41e57954e0
https://github.com/scikit-tda/persim/blob/f234f543058bdedb9729bf8c4a90da41e57954e0/persim/images.py#L72-L110
train
scikit-tda/persim
persim/images.py
PersImage.weighting
def weighting(self, landscape=None): """ Define a weighting function, for stability results to hold, the function must be 0 at y=0. """ # TODO: Implement a logistic function # TODO: use self.weighting_type to choose function if landscape is not None: if len(landscape) > 0: maxy = np.max(landscape[:, 1]) else: maxy = 1 def linear(interval): # linear function of y such that f(0) = 0 and f(max(y)) = 1 d = interval[1] return (1 / maxy) * d if landscape is not None else d def pw_linear(interval): """ This is the function defined as w_b(t) in the original PI paper Take b to be maxy/self.ny to effectively zero out the bottom pixel row """ t = interval[1] b = maxy / self.ny if t <= 0: return 0 if 0 < t < b: return t / b if b <= t: return 1 return linear
python
def weighting(self, landscape=None): """ Define a weighting function, for stability results to hold, the function must be 0 at y=0. """ # TODO: Implement a logistic function # TODO: use self.weighting_type to choose function if landscape is not None: if len(landscape) > 0: maxy = np.max(landscape[:, 1]) else: maxy = 1 def linear(interval): # linear function of y such that f(0) = 0 and f(max(y)) = 1 d = interval[1] return (1 / maxy) * d if landscape is not None else d def pw_linear(interval): """ This is the function defined as w_b(t) in the original PI paper Take b to be maxy/self.ny to effectively zero out the bottom pixel row """ t = interval[1] b = maxy / self.ny if t <= 0: return 0 if 0 < t < b: return t / b if b <= t: return 1 return linear
[ "def", "weighting", "(", "self", ",", "landscape", "=", "None", ")", ":", "# TODO: Implement a logistic function", "# TODO: use self.weighting_type to choose function", "if", "landscape", "is", "not", "None", ":", "if", "len", "(", "landscape", ")", ">", "0", ":", "maxy", "=", "np", ".", "max", "(", "landscape", "[", ":", ",", "1", "]", ")", "else", ":", "maxy", "=", "1", "def", "linear", "(", "interval", ")", ":", "# linear function of y such that f(0) = 0 and f(max(y)) = 1", "d", "=", "interval", "[", "1", "]", "return", "(", "1", "/", "maxy", ")", "*", "d", "if", "landscape", "is", "not", "None", "else", "d", "def", "pw_linear", "(", "interval", ")", ":", "\"\"\" This is the function defined as w_b(t) in the original PI paper\n\n Take b to be maxy/self.ny to effectively zero out the bottom pixel row\n \"\"\"", "t", "=", "interval", "[", "1", "]", "b", "=", "maxy", "/", "self", ".", "ny", "if", "t", "<=", "0", ":", "return", "0", "if", "0", "<", "t", "<", "b", ":", "return", "t", "/", "b", "if", "b", "<=", "t", ":", "return", "1", "return", "linear" ]
Define a weighting function, for stability results to hold, the function must be 0 at y=0.
[ "Define", "a", "weighting", "function", "for", "stability", "results", "to", "hold", "the", "function", "must", "be", "0", "at", "y", "=", "0", "." ]
f234f543058bdedb9729bf8c4a90da41e57954e0
https://github.com/scikit-tda/persim/blob/f234f543058bdedb9729bf8c4a90da41e57954e0/persim/images.py#L143-L178
train
scikit-tda/persim
persim/images.py
PersImage.show
def show(self, imgs, ax=None): """ Visualize the persistence image """ ax = ax or plt.gca() if type(imgs) is not list: imgs = [imgs] for i, img in enumerate(imgs): ax.imshow(img, cmap=plt.get_cmap("plasma")) ax.axis("off")
python
def show(self, imgs, ax=None): """ Visualize the persistence image """ ax = ax or plt.gca() if type(imgs) is not list: imgs = [imgs] for i, img in enumerate(imgs): ax.imshow(img, cmap=plt.get_cmap("plasma")) ax.axis("off")
[ "def", "show", "(", "self", ",", "imgs", ",", "ax", "=", "None", ")", ":", "ax", "=", "ax", "or", "plt", ".", "gca", "(", ")", "if", "type", "(", "imgs", ")", "is", "not", "list", ":", "imgs", "=", "[", "imgs", "]", "for", "i", ",", "img", "in", "enumerate", "(", "imgs", ")", ":", "ax", ".", "imshow", "(", "img", ",", "cmap", "=", "plt", ".", "get_cmap", "(", "\"plasma\"", ")", ")", "ax", ".", "axis", "(", "\"off\"", ")" ]
Visualize the persistence image
[ "Visualize", "the", "persistence", "image" ]
f234f543058bdedb9729bf8c4a90da41e57954e0
https://github.com/scikit-tda/persim/blob/f234f543058bdedb9729bf8c4a90da41e57954e0/persim/images.py#L200-L212
train
pivotal-energy-solutions/django-datatable-view
datatableview/utils.py
resolve_orm_path
def resolve_orm_path(model, orm_path): """ Follows the queryset-style query path of ``orm_path`` starting from ``model`` class. If the path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will be raised. """ bits = orm_path.split('__') endpoint_model = reduce(get_model_at_related_field, [model] + bits[:-1]) if bits[-1] == 'pk': field = endpoint_model._meta.pk else: field = endpoint_model._meta.get_field(bits[-1]) return field
python
def resolve_orm_path(model, orm_path): """ Follows the queryset-style query path of ``orm_path`` starting from ``model`` class. If the path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will be raised. """ bits = orm_path.split('__') endpoint_model = reduce(get_model_at_related_field, [model] + bits[:-1]) if bits[-1] == 'pk': field = endpoint_model._meta.pk else: field = endpoint_model._meta.get_field(bits[-1]) return field
[ "def", "resolve_orm_path", "(", "model", ",", "orm_path", ")", ":", "bits", "=", "orm_path", ".", "split", "(", "'__'", ")", "endpoint_model", "=", "reduce", "(", "get_model_at_related_field", ",", "[", "model", "]", "+", "bits", "[", ":", "-", "1", "]", ")", "if", "bits", "[", "-", "1", "]", "==", "'pk'", ":", "field", "=", "endpoint_model", ".", "_meta", ".", "pk", "else", ":", "field", "=", "endpoint_model", ".", "_meta", ".", "get_field", "(", "bits", "[", "-", "1", "]", ")", "return", "field" ]
Follows the queryset-style query path of ``orm_path`` starting from ``model`` class. If the path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will be raised.
[ "Follows", "the", "queryset", "-", "style", "query", "path", "of", "orm_path", "starting", "from", "model", "class", ".", "If", "the", "path", "ends", "up", "referring", "to", "a", "bad", "field", "name", "django", ".", "db", ".", "models", ".", "fields", ".", "FieldDoesNotExist", "will", "be", "raised", "." ]
00b77a9b5051c34e258c51b06c020e92edf15034
https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/utils.py#L56-L70
train
pivotal-energy-solutions/django-datatable-view
datatableview/utils.py
get_model_at_related_field
def get_model_at_related_field(model, attr): """ Looks up ``attr`` as a field of ``model`` and returns the related model class. If ``attr`` is not a relationship field, ``ValueError`` is raised. """ field = model._meta.get_field(attr) if hasattr(field, 'related_model'): return field.related_model raise ValueError("{model}.{attr} ({klass}) is not a relationship field.".format(**{ 'model': model.__name__, 'attr': attr, 'klass': field.__class__.__name__, }))
python
def get_model_at_related_field(model, attr): """ Looks up ``attr`` as a field of ``model`` and returns the related model class. If ``attr`` is not a relationship field, ``ValueError`` is raised. """ field = model._meta.get_field(attr) if hasattr(field, 'related_model'): return field.related_model raise ValueError("{model}.{attr} ({klass}) is not a relationship field.".format(**{ 'model': model.__name__, 'attr': attr, 'klass': field.__class__.__name__, }))
[ "def", "get_model_at_related_field", "(", "model", ",", "attr", ")", ":", "field", "=", "model", ".", "_meta", ".", "get_field", "(", "attr", ")", "if", "hasattr", "(", "field", ",", "'related_model'", ")", ":", "return", "field", ".", "related_model", "raise", "ValueError", "(", "\"{model}.{attr} ({klass}) is not a relationship field.\"", ".", "format", "(", "*", "*", "{", "'model'", ":", "model", ".", "__name__", ",", "'attr'", ":", "attr", ",", "'klass'", ":", "field", ".", "__class__", ".", "__name__", ",", "}", ")", ")" ]
Looks up ``attr`` as a field of ``model`` and returns the related model class. If ``attr`` is not a relationship field, ``ValueError`` is raised.
[ "Looks", "up", "attr", "as", "a", "field", "of", "model", "and", "returns", "the", "related", "model", "class", ".", "If", "attr", "is", "not", "a", "relationship", "field", "ValueError", "is", "raised", "." ]
00b77a9b5051c34e258c51b06c020e92edf15034
https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/utils.py#L72-L88
train
pivotal-energy-solutions/django-datatable-view
datatableview/utils.py
contains_plural_field
def contains_plural_field(model, fields): """ Returns a boolean indicating if ``fields`` contains a relationship to multiple items. """ source_model = model for orm_path in fields: model = source_model bits = orm_path.lstrip('+-').split('__') for bit in bits[:-1]: field = model._meta.get_field(bit) if field.many_to_many or field.one_to_many: return True model = get_model_at_related_field(model, bit) return False
python
def contains_plural_field(model, fields): """ Returns a boolean indicating if ``fields`` contains a relationship to multiple items. """ source_model = model for orm_path in fields: model = source_model bits = orm_path.lstrip('+-').split('__') for bit in bits[:-1]: field = model._meta.get_field(bit) if field.many_to_many or field.one_to_many: return True model = get_model_at_related_field(model, bit) return False
[ "def", "contains_plural_field", "(", "model", ",", "fields", ")", ":", "source_model", "=", "model", "for", "orm_path", "in", "fields", ":", "model", "=", "source_model", "bits", "=", "orm_path", ".", "lstrip", "(", "'+-'", ")", ".", "split", "(", "'__'", ")", "for", "bit", "in", "bits", "[", ":", "-", "1", "]", ":", "field", "=", "model", ".", "_meta", ".", "get_field", "(", "bit", ")", "if", "field", ".", "many_to_many", "or", "field", ".", "one_to_many", ":", "return", "True", "model", "=", "get_model_at_related_field", "(", "model", ",", "bit", ")", "return", "False" ]
Returns a boolean indicating if ``fields`` contains a relationship to multiple items.
[ "Returns", "a", "boolean", "indicating", "if", "fields", "contains", "a", "relationship", "to", "multiple", "items", "." ]
00b77a9b5051c34e258c51b06c020e92edf15034
https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/utils.py#L97-L108
train