Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
safe_version
(version)
Convert an arbitrary string to a standard version string Spaces become dots, and all other non-alphanumeric characters become dashes, with runs of multiple dashes condensed to a single dash.
Convert an arbitrary string to a standard version string
def safe_version(version): """Convert an arbitrary string to a standard version string Spaces become dots, and all other non-alphanumeric characters become dashes, with runs of multiple dashes condensed to a single dash. """ version = version.replace(' ','.') return re.sub('[^A-Za-z0-9.]+', '-'...
[ "def", "safe_version", "(", "version", ")", ":", "version", "=", "version", ".", "replace", "(", "' '", ",", "'.'", ")", "return", "re", ".", "sub", "(", "'[^A-Za-z0-9.]+'", ",", "'-'", ",", "version", ")" ]
[ 61, 0 ]
[ 68, 49 ]
python
en
['en', 'en', 'en']
True
to_filename
(name)
Convert a project or version name to its filename-escaped form Any '-' characters are currently replaced with '_'.
Convert a project or version name to its filename-escaped form
def to_filename(name): """Convert a project or version name to its filename-escaped form Any '-' characters are currently replaced with '_'. """ return name.replace('-','_')
[ "def", "to_filename", "(", "name", ")", ":", "return", "name", ".", "replace", "(", "'-'", ",", "'_'", ")" ]
[ 71, 0 ]
[ 76, 32 ]
python
en
['en', 'en', 'en']
True
read_markdown
(parser, path)
Get YAML and AST for Markdown file, returning {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}.
Get YAML and AST for Markdown file, returning {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}.
def read_markdown(parser, path): """ Get YAML and AST for Markdown file, returning {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}. """ # Split and extract YAML (if present). with open(path, 'r', encoding='utf-8') as reader: body = reader.read() ...
[ "def", "read_markdown", "(", "parser", ",", "path", ")", ":", "# Split and extract YAML (if present).", "with", "open", "(", "path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "reader", ":", "body", "=", "reader", ".", "read", "(", ")", "metad...
[ 100, 0 ]
[ 129, 5 ]
python
en
['en', 'error', 'th']
False
split_metadata
(path, text)
Get raw (text) metadata, metadata as YAML, and rest of body. If no metadata, return (None, None, body).
Get raw (text) metadata, metadata as YAML, and rest of body. If no metadata, return (None, None, body).
def split_metadata(path, text): """ Get raw (text) metadata, metadata as YAML, and rest of body. If no metadata, return (None, None, body). """ metadata_raw = None metadata_yaml = None pieces = text.split('---', 2) if len(pieces) == 3: metadata_raw = pieces[1] text = pi...
[ "def", "split_metadata", "(", "path", ",", "text", ")", ":", "metadata_raw", "=", "None", "metadata_yaml", "=", "None", "pieces", "=", "text", ".", "split", "(", "'---'", ",", "2", ")", "if", "len", "(", "pieces", ")", "==", "3", ":", "metadata_raw", ...
[ 132, 0 ]
[ 152, 44 ]
python
en
['en', 'error', 'th']
False
load_yaml
(filename)
Wrapper around YAML loading so that 'import yaml' is only needed in one file.
Wrapper around YAML loading so that 'import yaml' is only needed in one file.
def load_yaml(filename): """ Wrapper around YAML loading so that 'import yaml' is only needed in one file. """ try: with open(filename, 'r', encoding='utf-8') as reader: return yaml.load(reader, Loader=yaml.SafeLoader) except (yaml.YAMLError, IOError) as e: print('Un...
[ "def", "load_yaml", "(", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "reader", ":", "return", "yaml", ".", "load", "(", "reader", ",", "Loader", "=", "yaml", ".", "SafeLoa...
[ 155, 0 ]
[ 167, 19 ]
python
en
['en', 'error', 'th']
False
check_unwanted_files
(dir_path, reporter)
Check that unwanted files are not present.
Check that unwanted files are not present.
def check_unwanted_files(dir_path, reporter): """ Check that unwanted files are not present. """ for filename in UNWANTED_FILES: path = os.path.join(dir_path, filename) reporter.check(not os.path.exists(path), path, "Unwanted file found")
[ "def", "check_unwanted_files", "(", "dir_path", ",", "reporter", ")", ":", "for", "filename", "in", "UNWANTED_FILES", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "filename", ")", "reporter", ".", "check", "(", "not", "os", "."...
[ 170, 0 ]
[ 179, 45 ]
python
en
['en', 'error', 'th']
False
require
(condition, message)
Fail if condition not met.
Fail if condition not met.
def require(condition, message): """Fail if condition not met.""" if not condition: print(message, file=sys.stderr) sys.exit(1)
[ "def", "require", "(", "condition", ",", "message", ")", ":", "if", "not", "condition", ":", "print", "(", "message", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")" ]
[ 182, 0 ]
[ 187, 19 ]
python
en
['en', 'en', 'en']
True
Reporter.__init__
(self)
Constructor.
Constructor.
def __init__(self): """Constructor.""" self.messages = []
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "messages", "=", "[", "]" ]
[ 34, 4 ]
[ 36, 26 ]
python
en
['en', 'en', 'en']
False
Reporter.check_field
(self, filename, name, values, key, expected=REPORTER_NOT_SET)
Check that a dictionary has an expected value.
Check that a dictionary has an expected value.
def check_field(self, filename, name, values, key, expected=REPORTER_NOT_SET): """Check that a dictionary has an expected value.""" if key not in values: self.add(filename, '{0} does not contain {1}', name, key) elif expected is REPORTER_NOT_SET: pass elif type(e...
[ "def", "check_field", "(", "self", ",", "filename", ",", "name", ",", "values", ",", "key", ",", "expected", "=", "REPORTER_NOT_SET", ")", ":", "if", "key", "not", "in", "values", ":", "self", ".", "add", "(", "filename", ",", "'{0} does not contain {1}'",...
[ 38, 4 ]
[ 51, 54 ]
python
en
['en', 'en', 'en']
True
Reporter.check
(self, condition, location, fmt, *args)
Append error if condition not met.
Append error if condition not met.
def check(self, condition, location, fmt, *args): """Append error if condition not met.""" if not condition: self.add(location, fmt, *args)
[ "def", "check", "(", "self", ",", "condition", ",", "location", ",", "fmt", ",", "*", "args", ")", ":", "if", "not", "condition", ":", "self", ".", "add", "(", "location", ",", "fmt", ",", "*", "args", ")" ]
[ 53, 4 ]
[ 57, 42 ]
python
en
['en', 'nl', 'en']
True
Reporter.add
(self, location, fmt, *args)
Append error unilaterally.
Append error unilaterally.
def add(self, location, fmt, *args): """Append error unilaterally.""" self.messages.append((location, fmt.format(*args)))
[ "def", "add", "(", "self", ",", "location", ",", "fmt", ",", "*", "args", ")", ":", "self", ".", "messages", ".", "append", "(", "(", "location", ",", "fmt", ".", "format", "(", "*", "args", ")", ")", ")" ]
[ 59, 4 ]
[ 62, 59 ]
python
en
['en', 'it', 'en']
True
Reporter.report
(self, stream=sys.stdout)
Report all messages in order.
Report all messages in order.
def report(self, stream=sys.stdout): """Report all messages in order.""" if not self.messages: return for m in sorted(self.messages, key=self.key): print(self.pretty(m), file=stream)
[ "def", "report", "(", "self", ",", "stream", "=", "sys", ".", "stdout", ")", ":", "if", "not", "self", ".", "messages", ":", "return", "for", "m", "in", "sorted", "(", "self", ".", "messages", ",", "key", "=", "self", ".", "key", ")", ":", "print...
[ 90, 4 ]
[ 97, 46 ]
python
en
['en', 'en', 'en']
True
user_passes_test
( test_func: Callable[[HttpResponse], bool], login_url: Optional[str] = None, redirect_field_name: str = REDIRECT_FIELD_NAME, )
Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes.
Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes.
def user_passes_test( test_func: Callable[[HttpResponse], bool], login_url: Optional[str] = None, redirect_field_name: str = REDIRECT_FIELD_NAME, ) -> Callable[[ViewFuncT], ViewFuncT]: """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if nece...
[ "def", "user_passes_test", "(", "test_func", ":", "Callable", "[", "[", "HttpResponse", "]", ",", "bool", "]", ",", "login_url", ":", "Optional", "[", "str", "]", "=", "None", ",", "redirect_field_name", ":", "str", "=", "REDIRECT_FIELD_NAME", ",", ")", "-...
[ 365, 0 ]
[ 401, 20 ]
python
en
['en', 'error', 'th']
False
do_login
(request: HttpRequest, user_profile: UserProfile)
Creates a session, logging in the user, using the Django method, and also adds helpful data needed by our server logs.
Creates a session, logging in the user, using the Django method, and also adds helpful data needed by our server logs.
def do_login(request: HttpRequest, user_profile: UserProfile) -> None: """Creates a session, logging in the user, using the Django method, and also adds helpful data needed by our server logs. """ django_login(request, user_profile) request._requestor_for_logs = user_profile.format_requestor_for_log...
[ "def", "do_login", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "UserProfile", ")", "->", "None", ":", "django_login", "(", "request", ",", "user_profile", ")", "request", ".", "_requestor_for_logs", "=", "user_profile", ".", "format_requestor_for...
[ 420, 0 ]
[ 429, 50 ]
python
en
['en', 'en', 'en']
True
web_public_view
( view_func: ViewFuncT, redirect_field_name: str = REDIRECT_FIELD_NAME, login_url: str = settings.HOME_NOT_LOGGED_IN, )
This wrapper adds client info for unauthenticated users but forces authenticated users to go through 2fa. NOTE: This function == zulip_login_required in a production environment as web_public_view path has only been enabled for development purposes currently.
This wrapper adds client info for unauthenticated users but forces authenticated users to go through 2fa.
def web_public_view( view_func: ViewFuncT, redirect_field_name: str = REDIRECT_FIELD_NAME, login_url: str = settings.HOME_NOT_LOGGED_IN, ) -> Union[Callable[[ViewFuncT], ViewFuncT], ViewFuncT]: """ This wrapper adds client info for unauthenticated users but forces authenticated users to go throu...
[ "def", "web_public_view", "(", "view_func", ":", "ViewFuncT", ",", "redirect_field_name", ":", "str", "=", "REDIRECT_FIELD_NAME", ",", "login_url", ":", "str", "=", "settings", ".", "HOME_NOT_LOGGED_IN", ",", ")", "->", "Union", "[", "Callable", "[", "[", "Vie...
[ 482, 0 ]
[ 503, 38 ]
python
en
['en', 'error', 'th']
False
internal_notify_view
(is_tornado_view: bool)
Used for situations where something running on the Zulip server needs to make a request to the (other) Django/Tornado processes running on the server.
Used for situations where something running on the Zulip server needs to make a request to the (other) Django/Tornado processes running on the server.
def internal_notify_view(is_tornado_view: bool) -> Callable[[ViewFuncT], ViewFuncT]: # The typing here could be improved by using the extended Callable types: # https://mypy.readthedocs.io/en/stable/additional_features.html#extended-callable-types """Used for situations where something running on the Zulip ...
[ "def", "internal_notify_view", "(", "is_tornado_view", ":", "bool", ")", "->", "Callable", "[", "[", "ViewFuncT", "]", ",", "ViewFuncT", "]", ":", "# The typing here could be improved by using the extended Callable types:", "# https://mypy.readthedocs.io/en/stable/additional_feat...
[ 785, 0 ]
[ 813, 29 ]
python
en
['en', 'en', 'en']
True
statsd_increment
(counter: str, val: int = 1)
Increments a statsd counter on completion of the decorated function. Pass the name of the counter to this decorator-returning function.
Increments a statsd counter on completion of the decorated function.
def statsd_increment(counter: str, val: int = 1) -> Callable[[FuncT], FuncT]: """Increments a statsd counter on completion of the decorated function. Pass the name of the counter to this decorator-returning function.""" def wrapper(func: FuncT) -> FuncT: @wraps(func) def wrapped_func(*...
[ "def", "statsd_increment", "(", "counter", ":", "str", ",", "val", ":", "int", "=", "1", ")", "->", "Callable", "[", "[", "FuncT", "]", ",", "FuncT", "]", ":", "def", "wrapper", "(", "func", ":", "FuncT", ")", "->", "FuncT", ":", "@", "wraps", "(...
[ 820, 0 ]
[ 835, 18 ]
python
en
['en', 'en', 'en']
True
rate_limit_user
(request: HttpRequest, user: UserProfile, domain: str)
Returns whether or not a user was rate limited. Will raise a RateLimited exception if the user has been rate limited, otherwise returns and modifies request to contain the rate limit information
Returns whether or not a user was rate limited. Will raise a RateLimited exception if the user has been rate limited, otherwise returns and modifies request to contain the rate limit information
def rate_limit_user(request: HttpRequest, user: UserProfile, domain: str) -> None: """Returns whether or not a user was rate limited. Will raise a RateLimited exception if the user has been rate limited, otherwise returns and modifies request to contain the rate limit information""" RateLimitedUser(use...
[ "def", "rate_limit_user", "(", "request", ":", "HttpRequest", ",", "user", ":", "UserProfile", ",", "domain", ":", "str", ")", "->", "None", ":", "RateLimitedUser", "(", "user", ",", "domain", "=", "domain", ")", ".", "rate_limit_request", "(", "request", ...
[ 838, 0 ]
[ 843, 68 ]
python
en
['en', 'en', 'en']
True
rate_limit
(domain: str = "api_by_user")
Rate-limits a view. Takes an optional 'domain' param if you wish to rate limit different types of API calls independently. Returns a decorator
Rate-limits a view. Takes an optional 'domain' param if you wish to rate limit different types of API calls independently.
def rate_limit(domain: str = "api_by_user") -> Callable[[ViewFuncT], ViewFuncT]: """Rate-limits a view. Takes an optional 'domain' param if you wish to rate limit different types of API calls independently. Returns a decorator""" def wrapper(func: ViewFuncT) -> ViewFuncT: @wraps(func) ...
[ "def", "rate_limit", "(", "domain", ":", "str", "=", "\"api_by_user\"", ")", "->", "Callable", "[", "[", "ViewFuncT", "]", ",", "ViewFuncT", "]", ":", "def", "wrapper", "(", "func", ":", "ViewFuncT", ")", "->", "ViewFuncT", ":", "@", "wraps", "(", "fun...
[ 846, 0 ]
[ 883, 18 ]
python
en
['en', 'en', 'en']
True
zulip_otp_required
( redirect_field_name: str = "next", login_url: str = settings.HOME_NOT_LOGGED_IN, )
The reason we need to create this function is that the stock otp_required decorator doesn't play well with tests. We cannot enable/disable if_configured parameter during tests since the decorator retains its value due to closure. Similar to :func:`~django.contrib.auth.decorators.login_required`, b...
The reason we need to create this function is that the stock otp_required decorator doesn't play well with tests. We cannot enable/disable if_configured parameter during tests since the decorator retains its value due to closure.
def zulip_otp_required( redirect_field_name: str = "next", login_url: str = settings.HOME_NOT_LOGGED_IN, ) -> Callable[[ViewFuncT], ViewFuncT]: """ The reason we need to create this function is that the stock otp_required decorator doesn't play well with tests. We cannot enable/disable if_config...
[ "def", "zulip_otp_required", "(", "redirect_field_name", ":", "str", "=", "\"next\"", ",", "login_url", ":", "str", "=", "settings", ".", "HOME_NOT_LOGGED_IN", ",", ")", "->", "Callable", "[", "[", "ViewFuncT", "]", ",", "ViewFuncT", "]", ":", "def", "test",...
[ 896, 0 ]
[ 945, 20 ]
python
en
['en', 'error', 'th']
False
OGRGeomType.__init__
(self, type_input)
Figures out the correct OGR Type based upon the input.
Figures out the correct OGR Type based upon the input.
def __init__(self, type_input): "Figures out the correct OGR Type based upon the input." if isinstance(type_input, OGRGeomType): num = type_input.num elif isinstance(type_input, six.string_types): type_input = type_input.lower() if type_input == 'geometry': ...
[ "def", "__init__", "(", "self", ",", "type_input", ")", ":", "if", "isinstance", "(", "type_input", ",", "OGRGeomType", ")", ":", "num", "=", "type_input", ".", "num", "elif", "isinstance", "(", "type_input", ",", "six", ".", "string_types", ")", ":", "t...
[ 32, 4 ]
[ 51, 22 ]
python
en
['en', 'en', 'en']
True
OGRGeomType.__str__
(self)
Returns the value of the name property.
Returns the value of the name property.
def __str__(self): "Returns the value of the name property." return self.name
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "name" ]
[ 53, 4 ]
[ 55, 24 ]
python
en
['en', 'en', 'en']
True
OGRGeomType.__eq__
(self, other)
Does an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer.
Does an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer.
def __eq__(self, other): """ Does an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer. """ if isinstance(other, OGRGeomType): return self.num == other.num elif isinstance(other, six.string_types): ...
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "OGRGeomType", ")", ":", "return", "self", ".", "num", "==", "other", ".", "num", "elif", "isinstance", "(", "other", ",", "six", ".", "string_types", ")", "...
[ 57, 4 ]
[ 69, 24 ]
python
en
['en', 'error', 'th']
False
OGRGeomType.name
(self)
Returns a short-hand string form of the OGR Geometry type.
Returns a short-hand string form of the OGR Geometry type.
def name(self): "Returns a short-hand string form of the OGR Geometry type." return self._types[self.num]
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_types", "[", "self", ".", "num", "]" ]
[ 75, 4 ]
[ 77, 36 ]
python
en
['en', 'en', 'en']
True
OGRGeomType.django
(self)
Returns the Django GeometryField for this OGR Type.
Returns the Django GeometryField for this OGR Type.
def django(self): "Returns the Django GeometryField for this OGR Type." s = self.name.replace('25D', '') if s in ('LinearRing', 'None'): return None elif s == 'Unknown': s = 'Geometry' elif s == 'PointZ': s = 'Point' return s + 'Field'
[ "def", "django", "(", "self", ")", ":", "s", "=", "self", ".", "name", ".", "replace", "(", "'25D'", ",", "''", ")", "if", "s", "in", "(", "'LinearRing'", ",", "'None'", ")", ":", "return", "None", "elif", "s", "==", "'Unknown'", ":", "s", "=", ...
[ 80, 4 ]
[ 89, 26 ]
python
en
['en', 'en', 'en']
True
OGRGeomType.to_multi
(self)
Transform Point, LineString, Polygon, and their 25D equivalents to their Multi... counterpart.
Transform Point, LineString, Polygon, and their 25D equivalents to their Multi... counterpart.
def to_multi(self): """ Transform Point, LineString, Polygon, and their 25D equivalents to their Multi... counterpart. """ if self.name.startswith(('Point', 'LineString', 'Polygon')): self.num += 3
[ "def", "to_multi", "(", "self", ")", ":", "if", "self", ".", "name", ".", "startswith", "(", "(", "'Point'", ",", "'LineString'", ",", "'Polygon'", ")", ")", ":", "self", ".", "num", "+=", "3" ]
[ 91, 4 ]
[ 97, 25 ]
python
en
['en', 'error', 'th']
False
Index.clone
(self)
Create a copy of this Index.
Create a copy of this Index.
def clone(self): """Create a copy of this Index.""" path, args, kwargs = self.deconstruct() return self.__class__(*args, **kwargs)
[ "def", "clone", "(", "self", ")", ":", "path", ",", "args", ",", "kwargs", "=", "self", ".", "deconstruct", "(", ")", "return", "self", ".", "__class__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 79, 4 ]
[ 82, 46 ]
python
en
['en', 'en', 'en']
True
Index._hash_generator
(*args)
Generate a 32-bit digest of a set of arguments that can be used to shorten identifying names.
Generate a 32-bit digest of a set of arguments that can be used to shorten identifying names.
def _hash_generator(*args): """ Generate a 32-bit digest of a set of arguments that can be used to shorten identifying names. """ h = hashlib.md5() for arg in args: h.update(force_bytes(arg)) return h.hexdigest()[:6]
[ "def", "_hash_generator", "(", "*", "args", ")", ":", "h", "=", "hashlib", ".", "md5", "(", ")", "for", "arg", "in", "args", ":", "h", ".", "update", "(", "force_bytes", "(", "arg", ")", ")", "return", "h", ".", "hexdigest", "(", ")", "[", ":", ...
[ 85, 4 ]
[ 93, 32 ]
python
en
['en', 'error', 'th']
False
Index.set_name_with_model
(self, model)
Generate a unique name for the index. The name is divided into 3 parts - table name (12 chars), field name (8 chars) and unique hash + suffix (10 chars). Each part is made to fit its size by truncating the excess length.
Generate a unique name for the index.
def set_name_with_model(self, model): """ Generate a unique name for the index. The name is divided into 3 parts - table name (12 chars), field name (8 chars) and unique hash + suffix (10 chars). Each part is made to fit its size by truncating the excess length. """ ...
[ "def", "set_name_with_model", "(", "self", ",", "model", ")", ":", "table_name", "=", "model", ".", "_meta", ".", "db_table", "column_names", "=", "[", "model", ".", "_meta", ".", "get_field", "(", "field_name", ")", ".", "column", "for", "field_name", ","...
[ 95, 4 ]
[ 121, 25 ]
python
en
['en', 'error', 'th']
False
connect
(*args, **kwargs)
connect(dsn, ...) -> new psycopg 1.1.x compatible connection object
connect(dsn, ...) -> new psycopg 1.1.x compatible connection object
def connect(*args, **kwargs): """connect(dsn, ...) -> new psycopg 1.1.x compatible connection object""" kwargs['connection_factory'] = connection conn = _2connect(*args, **kwargs) conn.set_isolation_level(_ext.ISOLATION_LEVEL_READ_COMMITTED) return conn
[ "def", "connect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'connection_factory'", "]", "=", "connection", "conn", "=", "_2connect", "(", "*", "args", ",", "*", "*", "kwargs", ")", "conn", ".", "set_isolation_level", "(", "_e...
[ 39, 0 ]
[ 44, 15 ]
python
en
['en', 'en', 'en']
True
connection.cursor
(self)
cursor() -> new psycopg 1.1.x compatible cursor object
cursor() -> new psycopg 1.1.x compatible cursor object
def cursor(self): """cursor() -> new psycopg 1.1.x compatible cursor object""" return _2connection.cursor(self, cursor_factory=cursor)
[ "def", "cursor", "(", "self", ")", ":", "return", "_2connection", ".", "cursor", "(", "self", ",", "cursor_factory", "=", "cursor", ")" ]
[ 50, 4 ]
[ 52, 63 ]
python
ca
['en', 'ca', 'pt']
False
connection.autocommit
(self, on_off=1)
autocommit(on_off=1) -> switch autocommit on (1) or off (0)
autocommit(on_off=1) -> switch autocommit on (1) or off (0)
def autocommit(self, on_off=1): """autocommit(on_off=1) -> switch autocommit on (1) or off (0)""" if on_off > 0: self.set_isolation_level(_ext.ISOLATION_LEVEL_AUTOCOMMIT) else: self.set_isolation_level(_ext.ISOLATION_LEVEL_READ_COMMITTED)
[ "def", "autocommit", "(", "self", ",", "on_off", "=", "1", ")", ":", "if", "on_off", ">", "0", ":", "self", ".", "set_isolation_level", "(", "_ext", ".", "ISOLATION_LEVEL_AUTOCOMMIT", ")", "else", ":", "self", ".", "set_isolation_level", "(", "_ext", ".", ...
[ 54, 4 ]
[ 59, 73 ]
python
en
['en', 'en', 'en']
True
WorkflowJobTemplate.launch
(self, payload={})
Launch using related->launch endpoint.
Launch using related->launch endpoint.
def launch(self, payload={}): """Launch using related->launch endpoint.""" # get related->launch launch_pg = self.get_related('launch') # launch the workflow_job_template result = launch_pg.post(payload) # return job jobs_pg = self.related.workflow_jobs.get(id=r...
[ "def", "launch", "(", "self", ",", "payload", "=", "{", "}", ")", ":", "# get related->launch", "launch_pg", "=", "self", ".", "get_related", "(", "'launch'", ")", "# launch the workflow_job_template", "result", "=", "launch_pg", ".", "post", "(", "payload", "...
[ 18, 4 ]
[ 31, 33 ]
python
en
['en', 'en', 'en']
True
Engine.__init__
(self, parent_logger)
:type parent_logger: logging.Logger
def __init__(self, parent_logger): """ :type parent_logger: logging.Logger """ self.file_search_paths = [] self.services = [] self.__artifacts = [] self.reporters = [] self.artifacts_dir = None self.log = parent_logger.getChild(self.__class__.__na...
[ "def", "__init__", "(", "self", ",", "parent_logger", ")", ":", "self", ".", "file_search_paths", "=", "[", "]", "self", ".", "services", "=", "[", "]", "self", ".", "__artifacts", "=", "[", "]", "self", ".", "reporters", "=", "[", "]", "self", ".", ...
[ 57, 4 ]
[ 92, 32 ]
python
en
['en', 'error', 'th']
False
Engine.configure
(self, user_configs, read_config_files=True)
Load configuration files :type user_configs: list[str] :type read_config_files: bool
Load configuration files :type user_configs: list[str] :type read_config_files: bool
def configure(self, user_configs, read_config_files=True): """ Load configuration files :type user_configs: list[str] :type read_config_files: bool """ self.log.info("Configuring...") if read_config_files: self._load_base_configs() merged_con...
[ "def", "configure", "(", "self", ",", "user_configs", ",", "read_config_files", "=", "True", ")", ":", "self", ".", "log", ".", "info", "(", "\"Configuring...\"", ")", "if", "read_config_files", ":", "self", ".", "_load_base_configs", "(", ")", "merged_config"...
[ 112, 4 ]
[ 145, 28 ]
python
en
['en', 'error', 'th']
False
Engine.prepare
(self)
Prepare engine for work, will call preparing of Provisioning and add downstream EngineModule instances
Prepare engine for work, will call preparing of Provisioning and add downstream EngineModule instances
def prepare(self): """ Prepare engine for work, will call preparing of Provisioning and add downstream EngineModule instances """ self.log.info("Preparing...") self.unify_config() interval = self.config.get(SETTINGS).get("check-interval", self.check_interval) ...
[ "def", "prepare", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"Preparing...\"", ")", "self", ".", "unify_config", "(", ")", "interval", "=", "self", ".", "config", ".", "get", "(", "SETTINGS", ")", ".", "get", "(", "\"check-interval\...
[ 203, 4 ]
[ 222, 17 ]
python
en
['en', 'error', 'th']
False
Engine.run
(self)
Run the job. Calls `startup`, does periodic `check`, calls `shutdown` in any case
Run the job. Calls `startup`, does periodic `check`, calls `shutdown` in any case
def run(self): """ Run the job. Calls `startup`, does periodic `check`, calls `shutdown` in any case """ self.log.info("Starting...") exc_info = exc_value = None try: self._startup() self.logging_level_down() self._wait() ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"Starting...\"", ")", "exc_info", "=", "exc_value", "=", "None", "try", ":", "self", ".", "_startup", "(", ")", "self", ".", "logging_level_down", "(", ")", "self", ".", "_w...
[ 238, 4 ]
[ 269, 40 ]
python
en
['en', 'error', 'th']
False
Engine._wait
(self)
Wait modules for finish :return:
Wait modules for finish :return:
def _wait(self): """ Wait modules for finish :return: """ prev = time.time() while not self._check_modules_list(): now = time.time() diff = now - prev delay = self.check_interval - diff self.engine_loop_utilization = diff /...
[ "def", "_wait", "(", "self", ")", ":", "prev", "=", "time", ".", "time", "(", ")", "while", "not", "self", ".", "_check_modules_list", "(", ")", ":", "now", "=", "time", ".", "time", "(", ")", "diff", "=", "now", "-", "prev", "delay", "=", "self"...
[ 283, 4 ]
[ 301, 26 ]
python
en
['en', 'error', 'th']
False
Engine._shutdown
(self)
Shutdown modules :return:
Shutdown modules :return:
def _shutdown(self): """ Shutdown modules :return: """ self.log.info("Shutting down...") self.log.debug("Current stop reason: %s", self.stopping_reason) exc_info = exc_value = None modules = [self.provisioning, self.aggregator] + self.reporters + self.serv...
[ "def", "_shutdown", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"Shutting down...\"", ")", "self", ".", "log", ".", "debug", "(", "\"Current stop reason: %s\"", ",", "self", ".", "stopping_reason", ")", "exc_info", "=", "exc_value", "=", ...
[ 303, 4 ]
[ 326, 40 ]
python
en
['en', 'error', 'th']
False
Engine.post_process
(self)
Do post-run analysis and processing for the results.
Do post-run analysis and processing for the results.
def post_process(self): """ Do post-run analysis and processing for the results. """ self.log.info("Post-processing...") # :type exception: BaseException exc_info = exc_value = None modules = [self.provisioning, self.aggregator] + self.reporters + self.services #...
[ "def", "post_process", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"Post-processing...\"", ")", "# :type exception: BaseException", "exc_info", "=", "exc_value", "=", "None", "modules", "=", "[", "self", ".", "provisioning", ",", "self", "."...
[ 328, 4 ]
[ 354, 40 ]
python
en
['en', 'error', 'th']
False
Engine.create_artifact
(self, prefix, suffix)
Create new artifact in artifacts dir with given prefix and suffix :type prefix: str :type suffix: str :return: Path to created file :rtype: str :raise TaurusInternalException: if no artifacts dir set
Create new artifact in artifacts dir with given prefix and suffix
def create_artifact(self, prefix, suffix): """ Create new artifact in artifacts dir with given prefix and suffix :type prefix: str :type suffix: str :return: Path to created file :rtype: str :raise TaurusInternalException: if no artifacts dir set """ ...
[ "def", "create_artifact", "(", "self", ",", "prefix", ",", "suffix", ")", ":", "if", "not", "self", ".", "artifacts_dir", ":", "raise", "TaurusInternalException", "(", "\"Cannot create artifact: no artifacts_dir set up\"", ")", "filename", "=", "get_uniq_name", "(", ...
[ 356, 4 ]
[ 372, 23 ]
python
en
['en', 'error', 'th']
False
Engine.existing_artifact
(self, filename, move=False, target_filename=None)
Add existing artifact, it will be collected into artifact_dir. If move=True, the original file will be deleted :type filename: str :type move: bool :type target_filename: str
Add existing artifact, it will be collected into artifact_dir. If move=True, the original file will be deleted
def existing_artifact(self, filename, move=False, target_filename=None): """ Add existing artifact, it will be collected into artifact_dir. If move=True, the original file will be deleted :type filename: str :type move: bool :type target_filename: str """ ...
[ "def", "existing_artifact", "(", "self", ",", "filename", ",", "move", "=", "False", ",", "target_filename", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Add existing artifact (move=%s): %s\"", ",", "move", ",", "filename", ")", "if", "se...
[ 374, 4 ]
[ 405, 43 ]
python
en
['en', 'error', 'th']
False
Engine.create_artifacts_dir
(self, existing_artifacts=(), merged_config=None)
Create directory for artifacts, directory name based on datetime.now()
Create directory for artifacts, directory name based on datetime.now()
def create_artifacts_dir(self, existing_artifacts=(), merged_config=None): """ Create directory for artifacts, directory name based on datetime.now() """ if not self.artifacts_dir: artifacts_dir = self.config.get(SETTINGS, force_set=True).get("artifacts-dir", self.ARTIFACTS_D...
[ "def", "create_artifacts_dir", "(", "self", ",", "existing_artifacts", "=", "(", ")", ",", "merged_config", "=", "None", ")", ":", "if", "not", "self", ".", "artifacts_dir", ":", "artifacts_dir", "=", "self", ".", "config", ".", "get", "(", "SETTINGS", ","...
[ 407, 4 ]
[ 433, 44 ]
python
en
['en', 'error', 'th']
False
Engine.__load_module
(self, alias)
Load module class by alias :param alias: str :return: class
Load module class by alias :param alias: str :return: class
def __load_module(self, alias): """ Load module class by alias :param alias: str :return: class """ if alias in self.modules: return self.modules[alias] mod_conf = self.config.get('modules') if alias not in mod_conf: msg = "Module ...
[ "def", "__load_module", "(", "self", ",", "alias", ")", ":", "if", "alias", "in", "self", ".", "modules", ":", "return", "self", ".", "modules", "[", "alias", "]", "mod_conf", "=", "self", ".", "config", ".", "get", "(", "'modules'", ")", "if", "alia...
[ 445, 4 ]
[ 472, 34 ]
python
en
['en', 'error', 'th']
False
Engine.instantiate_module
(self, alias)
Create new instance for module using its alias from module settings section of config. Thus, to instantiate module it should be mentioned in settings. :type alias: str :rtype: EngineModule
Create new instance for module using its alias from module settings section of config. Thus, to instantiate module it should be mentioned in settings.
def instantiate_module(self, alias): """ Create new instance for module using its alias from module settings section of config. Thus, to instantiate module it should be mentioned in settings. :type alias: str :rtype: EngineModule """ classobj = self.__loa...
[ "def", "instantiate_module", "(", "self", ",", "alias", ")", ":", "classobj", "=", "self", ".", "__load_module", "(", "alias", ")", "instance", "=", "classobj", "(", ")", "assert", "isinstance", "(", "instance", ",", "EngineModule", ")", "instance", ".", "...
[ 474, 4 ]
[ 490, 23 ]
python
en
['en', 'error', 'th']
False
Engine.find_file
(self, filename)
Try to find file or dir in search_path if it was specified. Helps finding files in non-CLI environments or relative to config path Return path is full and mustn't treat with abspath/etc. :param filename: file basename to find :type filename: str
Try to find file or dir in search_path if it was specified. Helps finding files in non-CLI environments or relative to config path Return path is full and mustn't treat with abspath/etc. :param filename: file basename to find :type filename: str
def find_file(self, filename): """ Try to find file or dir in search_path if it was specified. Helps finding files in non-CLI environments or relative to config path Return path is full and mustn't treat with abspath/etc. :param filename: file basename to find :type filen...
[ "def", "find_file", "(", "self", ",", "filename", ")", ":", "if", "not", "filename", ":", "return", "filename", "if", "filename", ".", "lower", "(", ")", ".", "startswith", "(", "\"http://\"", ")", "or", "filename", ".", "lower", "(", ")", ".", "starts...
[ 492, 4 ]
[ 531, 23 ]
python
en
['en', 'error', 'th']
False
Engine._load_user_configs
(self, user_configs)
:type user_configs: list[str] :rtype: Configuration
:type user_configs: list[str] :rtype: Configuration
def _load_user_configs(self, user_configs): """ :type user_configs: list[str] :rtype: Configuration """ # "tab-replacement-spaces" is not documented 'cause it loads only from base configs # so it's sort of half-working last resort self.config.tab_replacement_space...
[ "def", "_load_user_configs", "(", "self", ",", "user_configs", ")", ":", "# \"tab-replacement-spaces\" is not documented 'cause it loads only from base configs", "# so it's sort of half-working last resort", "self", ".", "config", ".", "tab_replacement_spaces", "=", "self", ".", ...
[ 591, 4 ]
[ 606, 26 ]
python
en
['en', 'error', 'th']
False
Engine.__prepare_provisioning
(self)
Instantiate provisioning class
Instantiate provisioning class
def __prepare_provisioning(self): """ Instantiate provisioning class """ err = TaurusConfigError("Please check global config availability or configure provisioning settings") cls = self.config.get(Provisioning.PROV, err) self.provisioning = self.instantiate_module(cls) ...
[ "def", "__prepare_provisioning", "(", "self", ")", ":", "err", "=", "TaurusConfigError", "(", "\"Please check global config availability or configure provisioning settings\"", ")", "cls", "=", "self", ".", "config", ".", "get", "(", "Provisioning", ".", "PROV", ",", "...
[ 611, 4 ]
[ 619, 35 ]
python
en
['en', 'error', 'th']
False
Engine.__prepare_reporters
(self)
Instantiate reporters, then prepare them in case they would like to interact
Instantiate reporters, then prepare them in case they would like to interact
def __prepare_reporters(self): """ Instantiate reporters, then prepare them in case they would like to interact """ reporting = self.config.get(Reporter.REP, []) for index, reporter in enumerate(reporting): msg = "reporter 'module' field isn't recognized: %s" ...
[ "def", "__prepare_reporters", "(", "self", ")", ":", "reporting", "=", "self", ".", "config", ".", "get", "(", "Reporter", ".", "REP", ",", "[", "]", ")", "for", "index", ",", "reporter", "in", "enumerate", "(", "reporting", ")", ":", "msg", "=", "\"...
[ 621, 4 ]
[ 643, 28 ]
python
en
['en', 'error', 'th']
False
Engine.__prepare_services
(self)
Instantiate service modules, then prepare them
Instantiate service modules, then prepare them
def __prepare_services(self): """ Instantiate service modules, then prepare them """ srv_config = self.config.get(Service.SERV, []) services = [] for index, config in enumerate(srv_config): cls = config.get('module', '') instance = self.instantiate...
[ "def", "__prepare_services", "(", "self", ")", ":", "srv_config", "=", "self", ".", "config", ".", "get", "(", "Service", ".", "SERV", ",", "[", "]", ")", "services", "=", "[", "]", "for", "index", ",", "config", "in", "enumerate", "(", "srv_config", ...
[ 645, 4 ]
[ 668, 28 ]
python
en
['en', 'error', 'th']
False
Engine.__singletone_exists
(self, instance, mods_list)
:type instance: EngineModule :type mods_list: list[EngineModule] :rtype: bool
:type instance: EngineModule :type mods_list: list[EngineModule] :rtype: bool
def __singletone_exists(self, instance, mods_list): """ :type instance: EngineModule :type mods_list: list[EngineModule] :rtype: bool """ if not isinstance(instance, Singletone): return False for mod in mods_list: if mod.parameters.get("mo...
[ "def", "__singletone_exists", "(", "self", ",", "instance", ",", "mods_list", ")", ":", "if", "not", "isinstance", "(", "instance", ",", "Singletone", ")", ":", "return", "False", "for", "mod", "in", "mods_list", ":", "if", "mod", ".", "parameters", ".", ...
[ 670, 4 ]
[ 685, 20 ]
python
en
['en', 'error', 'th']
False
Engine.__prepare_aggregator
(self)
Instantiate aggregators :return:
Instantiate aggregators :return:
def __prepare_aggregator(self): """ Instantiate aggregators :return: """ cls = self.config.get(SETTINGS).get("aggregator", "") if not cls: self.log.warning("Proceeding without aggregator, no results analysis") else: self.aggregator = self.i...
[ "def", "__prepare_aggregator", "(", "self", ")", ":", "cls", "=", "self", ".", "config", ".", "get", "(", "SETTINGS", ")", ".", "get", "(", "\"aggregator\"", ",", "\"\"", ")", "if", "not", "cls", ":", "self", ".", "log", ".", "warning", "(", "\"Proce...
[ 687, 4 ]
[ 699, 33 ]
python
en
['en', 'error', 'th']
False
Engine.eval_env
(self)
Should be done after `configure`
Should be done after `configure`
def eval_env(self): """ Should be done after `configure` """ envs = self.__get_envs_from_config() envs = expand_envs_with_os(envs) def apply_env(value, key, container): if isinstance(value, str): container[key] = custom_expandvars(value, envs)...
[ "def", "eval_env", "(", "self", ")", ":", "envs", "=", "self", ".", "__get_envs_from_config", "(", ")", "envs", "=", "expand_envs_with_os", "(", "envs", ")", "def", "apply_env", "(", "value", ",", "key", ",", "container", ")", ":", "if", "isinstance", "(...
[ 730, 4 ]
[ 743, 39 ]
python
en
['en', 'error', 'th']
False
Engine.__export_variables_to_os
(self)
Export all user-defined environment variables to the system. Example: settings: env: FOO: bbb/ccc BAR: aaa
Export all user-defined environment variables to the system. Example:
def __export_variables_to_os(self): """ Export all user-defined environment variables to the system. Example: settings: env: FOO: bbb/ccc BAR: aaa """ envs = self.__get_envs_from_config() for var_name in envs: if env...
[ "def", "__export_variables_to_os", "(", "self", ")", ":", "envs", "=", "self", ".", "__get_envs_from_config", "(", ")", "for", "var_name", "in", "envs", ":", "if", "envs", "[", "var_name", "]", "is", "None", ":", "if", "var_name", "in", "os", ".", "envir...
[ 745, 4 ]
[ 763, 73 ]
python
en
['en', 'error', 'th']
False
get_page_instance
(context)
Given a template context, try and find a Page variable in the common places. Returns None if a page can not be found.
Given a template context, try and find a Page variable in the common places. Returns None if a page can not be found.
def get_page_instance(context): """ Given a template context, try and find a Page variable in the common places. Returns None if a page can not be found. """ possible_names = [PAGE_TEMPLATE_VAR, 'self'] for name in possible_names: if name in context: page = context[name] ...
[ "def", "get_page_instance", "(", "context", ")", ":", "possible_names", "=", "[", "PAGE_TEMPLATE_VAR", ",", "'self'", "]", "for", "name", "in", "possible_names", ":", "if", "name", "in", "context", ":", "page", "=", "context", "[", "name", "]", "if", "isin...
[ 15, 0 ]
[ 25, 27 ]
python
en
['en', 'error', 'th']
False
patch_cache_control
(response, **kwargs)
This function patches the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a parameter is True (exactly True, not just a true valu...
This function patches the Cache-Control header by adding all keyword arguments to it. The transformation is as follows:
def patch_cache_control(response, **kwargs): """ This function patches the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a paramet...
[ "def", "patch_cache_control", "(", "response", ",", "*", "*", "kwargs", ")", ":", "def", "dictitem", "(", "s", ")", ":", "t", "=", "s", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "t", ")", ">", "1", ":", "return", "(", "t", "[...
[ 42, 0 ]
[ 88, 34 ]
python
en
['en', 'error', 'th']
False
get_max_age
(response)
Returns the max-age from the response Cache-Control header as an integer (or ``None`` if it wasn't found or wasn't an integer.
Returns the max-age from the response Cache-Control header as an integer (or ``None`` if it wasn't found or wasn't an integer.
def get_max_age(response): """ Returns the max-age from the response Cache-Control header as an integer (or ``None`` if it wasn't found or wasn't an integer. """ if not response.has_header('Cache-Control'): return cc = dict(_to_tuple(el) for el in cc_delim_re.split(response['Cache-Contro...
[ "def", "get_max_age", "(", "response", ")", ":", "if", "not", "response", ".", "has_header", "(", "'Cache-Control'", ")", ":", "return", "cc", "=", "dict", "(", "_to_tuple", "(", "el", ")", "for", "el", "in", "cc_delim_re", ".", "split", "(", "response",...
[ 91, 0 ]
[ 103, 16 ]
python
en
['en', 'error', 'th']
False
_if_match_passes
(target_etag, etags)
Test the If-Match comparison as defined in section 3.1 of RFC 7232.
Test the If-Match comparison as defined in section 3.1 of RFC 7232.
def _if_match_passes(target_etag, etags): """ Test the If-Match comparison as defined in section 3.1 of RFC 7232. """ if not target_etag: # If there isn't an ETag, then there can't be a match. return False elif etags == ['*']: # The existence of an ETag means that there is "a...
[ "def", "_if_match_passes", "(", "target_etag", ",", "etags", ")", ":", "if", "not", "target_etag", ":", "# If there isn't an ETag, then there can't be a match.", "return", "False", "elif", "etags", "==", "[", "'*'", "]", ":", "# The existence of an ETag means that there i...
[ 183, 0 ]
[ 201, 35 ]
python
en
['en', 'error', 'th']
False
_if_unmodified_since_passes
(last_modified, if_unmodified_since)
Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232.
Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232.
def _if_unmodified_since_passes(last_modified, if_unmodified_since): """ Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232. """ return last_modified and last_modified <= if_unmodified_since
[ "def", "_if_unmodified_since_passes", "(", "last_modified", ",", "if_unmodified_since", ")", ":", "return", "last_modified", "and", "last_modified", "<=", "if_unmodified_since" ]
[ 204, 0 ]
[ 209, 65 ]
python
en
['en', 'error', 'th']
False
_if_none_match_passes
(target_etag, etags)
Test the If-None-Match comparison as defined in section 3.2 of RFC 7232.
Test the If-None-Match comparison as defined in section 3.2 of RFC 7232.
def _if_none_match_passes(target_etag, etags): """ Test the If-None-Match comparison as defined in section 3.2 of RFC 7232. """ if not target_etag: # If there isn't an ETag, then there isn't a match. return True elif etags == ['*']: # The existence of an ETag means that there...
[ "def", "_if_none_match_passes", "(", "target_etag", ",", "etags", ")", ":", "if", "not", "target_etag", ":", "# If there isn't an ETag, then there isn't a match.", "return", "True", "elif", "etags", "==", "[", "'*'", "]", ":", "# The existence of an ETag means that there ...
[ 212, 0 ]
[ 228, 39 ]
python
en
['en', 'error', 'th']
False
_if_modified_since_passes
(last_modified, if_modified_since)
Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232.
Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232.
def _if_modified_since_passes(last_modified, if_modified_since): """ Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232. """ return not last_modified or last_modified > if_modified_since
[ "def", "_if_modified_since_passes", "(", "last_modified", ",", "if_modified_since", ")", ":", "return", "not", "last_modified", "or", "last_modified", ">", "if_modified_since" ]
[ 231, 0 ]
[ 235, 65 ]
python
en
['en', 'error', 'th']
False
patch_response_headers
(response, cache_timeout=None)
Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control. Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default.
Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control.
def patch_response_headers(response, cache_timeout=None): """ Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control. Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default. """ if c...
[ "def", "patch_response_headers", "(", "response", ",", "cache_timeout", "=", "None", ")", ":", "if", "cache_timeout", "is", "None", ":", "cache_timeout", "=", "settings", ".", "CACHE_MIDDLEWARE_SECONDS", "if", "cache_timeout", "<", "0", ":", "cache_timeout", "=", ...
[ 238, 0 ]
[ 266, 56 ]
python
en
['en', 'error', 'th']
False
add_never_cache_headers
(response)
Adds headers to a response to indicate that a page should never be cached.
Adds headers to a response to indicate that a page should never be cached.
def add_never_cache_headers(response): """ Adds headers to a response to indicate that a page should never be cached. """ patch_response_headers(response, cache_timeout=-1) patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
[ "def", "add_never_cache_headers", "(", "response", ")", ":", "patch_response_headers", "(", "response", ",", "cache_timeout", "=", "-", "1", ")", "patch_cache_control", "(", "response", ",", "no_cache", "=", "True", ",", "no_store", "=", "True", ",", "must_reval...
[ 269, 0 ]
[ 274, 85 ]
python
en
['en', 'error', 'th']
False
patch_vary_headers
(response, newheaders)
Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed.
Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed.
def patch_vary_headers(response, newheaders): """ Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed. """ # Note that we need to keep the original order intact, because cac...
[ "def", "patch_vary_headers", "(", "response", ",", "newheaders", ")", ":", "# Note that we need to keep the original order intact, because cache", "# implementations may rely on the order of the Vary contents in, say,", "# computing an MD5 hash.", "if", "response", ".", "has_header", "...
[ 277, 0 ]
[ 294, 67 ]
python
en
['en', 'error', 'th']
False
has_vary_header
(response, header_query)
Checks to see if the response has a given header name in its Vary header.
Checks to see if the response has a given header name in its Vary header.
def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set(header.lower() for header in vary_head...
[ "def", "has_vary_header", "(", "response", ",", "header_query", ")", ":", "if", "not", "response", ".", "has_header", "(", "'Vary'", ")", ":", "return", "False", "vary_headers", "=", "cc_delim_re", ".", "split", "(", "response", "[", "'Vary'", "]", ")", "e...
[ 297, 0 ]
[ 305, 51 ]
python
en
['en', 'error', 'th']
False
_i18n_cache_key_suffix
(request, cache_key)
If necessary, adds the current locale or time zone to the cache key.
If necessary, adds the current locale or time zone to the cache key.
def _i18n_cache_key_suffix(request, cache_key): """If necessary, adds the current locale or time zone to the cache key.""" if settings.USE_I18N or settings.USE_L10N: # first check if LocaleMiddleware or another middleware added # LANGUAGE_CODE to request, then fall back to the active language ...
[ "def", "_i18n_cache_key_suffix", "(", "request", ",", "cache_key", ")", ":", "if", "settings", ".", "USE_I18N", "or", "settings", ".", "USE_L10N", ":", "# first check if LocaleMiddleware or another middleware added", "# LANGUAGE_CODE to request, then fall back to the active langu...
[ 308, 0 ]
[ 322, 20 ]
python
en
['en', 'en', 'en']
True
_generate_cache_key
(request, method, headerlist, key_prefix)
Returns a cache key from the headers given in the header list.
Returns a cache key from the headers given in the header list.
def _generate_cache_key(request, method, headerlist, key_prefix): """Returns a cache key from the headers given in the header list.""" ctx = hashlib.md5() for header in headerlist: value = request.META.get(header) if value is not None: ctx.update(force_bytes(value)) url = has...
[ "def", "_generate_cache_key", "(", "request", ",", "method", ",", "headerlist", ",", "key_prefix", ")", ":", "ctx", "=", "hashlib", ".", "md5", "(", ")", "for", "header", "in", "headerlist", ":", "value", "=", "request", ".", "META", ".", "get", "(", "...
[ 325, 0 ]
[ 335, 53 ]
python
en
['en', 'en', 'en']
True
_generate_cache_header_key
(key_prefix, request)
Returns a cache key for the header cache.
Returns a cache key for the header cache.
def _generate_cache_header_key(key_prefix, request): """Returns a cache key for the header cache.""" url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri()))) cache_key = 'views.decorators.cache.cache_header.%s.%s' % ( key_prefix, url.hexdigest()) return _i18n_cache_key_suffix(req...
[ "def", "_generate_cache_header_key", "(", "key_prefix", ",", "request", ")", ":", "url", "=", "hashlib", ".", "md5", "(", "force_bytes", "(", "iri_to_uri", "(", "request", ".", "build_absolute_uri", "(", ")", ")", ")", ")", "cache_key", "=", "'views.decorators...
[ 338, 0 ]
[ 343, 53 ]
python
en
['en', 'en', 'en']
True
get_cache_key
(request, key_prefix=None, method='GET', cache=None)
Returns a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against. If there is no headerlist stored, the page needs to be rebuilt, s...
Returns a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against.
def get_cache_key(request, key_prefix=None, method='GET', cache=None): """ Returns a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check a...
[ "def", "get_cache_key", "(", "request", ",", "key_prefix", "=", "None", ",", "method", "=", "'GET'", ",", "cache", "=", "None", ")", ":", "if", "key_prefix", "is", "None", ":", "key_prefix", "=", "settings", ".", "CACHE_MIDDLEWARE_KEY_PREFIX", "cache_key", "...
[ 346, 0 ]
[ 365, 19 ]
python
en
['en', 'error', 'th']
False
learn_cache_key
(request, response, cache_timeout=None, key_prefix=None, cache=None)
Learns what headers to take into account for some request URL from the response object. It stores those headers in a global URL registry so that later access to that URL will know what headers to take into account without building the response object itself. The headers are named in the Vary header...
Learns what headers to take into account for some request URL from the response object. It stores those headers in a global URL registry so that later access to that URL will know what headers to take into account without building the response object itself. The headers are named in the Vary header...
def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None): """ Learns what headers to take into account for some request URL from the response object. It stores those headers in a global URL registry so that later access to that URL will know what headers to take into accou...
[ "def", "learn_cache_key", "(", "request", ",", "response", ",", "cache_timeout", "=", "None", ",", "key_prefix", "=", "None", ",", "cache", "=", "None", ")", ":", "if", "key_prefix", "is", "None", ":", "key_prefix", "=", "settings", ".", "CACHE_MIDDLEWARE_KE...
[ 368, 0 ]
[ 407, 75 ]
python
en
['en', 'error', 'th']
False
detect
(byte_str)
Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray``
Detect the encoding of the given byte string.
def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expecte...
[ "def", "detect", "(", "byte_str", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytearray", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'Expected object of type bytes or bytearray, got: ...
[ 23, 0 ]
[ 38, 27 ]
python
en
['en', 'error', 'th']
False
mordred
(smiles_list, name='', dropna=False)
Compute chemical descriptors for a list of SMILES strings. Parameters ---------- smiles_list : list List of SMILES strings. name : str Name prepended to each descriptor name (e.g., nBase --> name_nBase). dropna : bool If true, drop columns which contain np.NaNs. ...
Compute chemical descriptors for a list of SMILES strings. Parameters ---------- smiles_list : list List of SMILES strings. name : str Name prepended to each descriptor name (e.g., nBase --> name_nBase). dropna : bool If true, drop columns which contain np.NaNs. ...
def mordred(smiles_list, name='', dropna=False): """Compute chemical descriptors for a list of SMILES strings. Parameters ---------- smiles_list : list List of SMILES strings. name : str Name prepended to each descriptor name (e.g., nBase --> name_nBase). dropna : bool ...
[ "def", "mordred", "(", "smiles_list", ",", "name", "=", "''", ",", "dropna", "=", "False", ")", ":", "smiles_list", "=", "list", "(", "smiles_list", ")", "# Initialize descriptor calculator with all descriptors", "calc", "=", "Calculator", "(", "descriptors", ")",...
[ 19, 0 ]
[ 64, 13 ]
python
en
['en', 'en', 'en']
True
one_hot_row
(value, possible_values)
One-hot-encode a row of data. Parameters ---------- value : obj Any one of the possible values to be one-hot-encoded. possible_values : list List of possible values. Returns ---------- list One-hot-encoded value.
One-hot-encode a row of data. Parameters ---------- value : obj Any one of the possible values to be one-hot-encoded. possible_values : list List of possible values. Returns ---------- list One-hot-encoded value.
def one_hot_row(value, possible_values): """One-hot-encode a row of data. Parameters ---------- value : obj Any one of the possible values to be one-hot-encoded. possible_values : list List of possible values. Returns ---------- list One-hot-encoded valu...
[ "def", "one_hot_row", "(", "value", ",", "possible_values", ")", ":", "ohe", "=", "[", "]", "for", "entry", "in", "possible_values", ":", "if", "entry", "==", "value", ":", "ohe", ".", "append", "(", "1", ")", "else", ":", "ohe", ".", "append", "(", ...
[ 68, 0 ]
[ 91, 14 ]
python
en
['en', 'en', 'en']
True
one_hot_encode
(data_column, name='')
Generate a one-hot-encoded data column. Parameters ---------- data_column : pandas.Series DataFrame column to be one-hot-encoded. name : str Name prepended to each descriptor name (e.g., KOH --> name=KOH). Returns ---------- pandas.DataFrame DataFrame contai...
Generate a one-hot-encoded data column. Parameters ---------- data_column : pandas.Series DataFrame column to be one-hot-encoded. name : str Name prepended to each descriptor name (e.g., KOH --> name=KOH). Returns ---------- pandas.DataFrame DataFrame contai...
def one_hot_encode(data_column, name=''): """Generate a one-hot-encoded data column. Parameters ---------- data_column : pandas.Series DataFrame column to be one-hot-encoded. name : str Name prepended to each descriptor name (e.g., KOH --> name=KOH). Returns ----...
[ "def", "one_hot_encode", "(", "data_column", ",", "name", "=", "''", ")", ":", "possible_values", "=", "list", "(", "data_column", ".", "drop_duplicates", "(", ")", ")", "ohe", "=", "[", "]", "for", "value", "in", "list", "(", "possible_values", ")", ":"...
[ 93, 0 ]
[ 123, 14 ]
python
en
['en', 'en', 'it']
True
encode_component
(df_column, encoding, name='')
Encode an experiment index column. Function will attempt to encode a data column according to specified encoding. If it encounters an issue, an edbo bot is spawned to help resulve the issue. Parameters ---------- df_column : pandas.Series DataFrame column to be encoded. encodin...
Encode an experiment index column. Function will attempt to encode a data column according to specified encoding. If it encounters an issue, an edbo bot is spawned to help resulve the issue. Parameters ---------- df_column : pandas.Series DataFrame column to be encoded. encodin...
def encode_component(df_column, encoding, name=''): """Encode an experiment index column. Function will attempt to encode a data column according to specified encoding. If it encounters an issue, an edbo bot is spawned to help resulve the issue. Parameters ---------- df_column : pandas...
[ "def", "encode_component", "(", "df_column", ",", "encoding", ",", "name", "=", "''", ")", ":", "# Spawn a bot to deal with issues", "edbo_bot", "=", "bot", "(", ")", "# Encode components", "if", "encoding", ".", "lower", "(", ")", "==", "'ohe'", ":", "descrip...
[ 127, 0 ]
[ 258, 28 ]
python
en
['en', 'su', 'it']
False
expand_space
(index, descriptor_dict)
Generate reaction space from individual descriptor matrices. Parameters ---------- index : pandas.DataFrame Index of experiments with columns corresponding to keys in the descriptor dictionary and values corresponding to rows in each descriptor matrix. descriptor_dict: dict ...
Generate reaction space from individual descriptor matrices. Parameters ---------- index : pandas.DataFrame Index of experiments with columns corresponding to keys in the descriptor dictionary and values corresponding to rows in each descriptor matrix. descriptor_dict: dict ...
def expand_space(index, descriptor_dict): """Generate reaction space from individual descriptor matrices. Parameters ---------- index : pandas.DataFrame Index of experiments with columns corresponding to keys in the descriptor dictionary and values corresponding to rows in each desc...
[ "def", "expand_space", "(", "index", ",", "descriptor_dict", ")", ":", "descriptor_matrix", "=", "pd", ".", "DataFrame", "(", ")", "for", "col", "in", "index", ".", "columns", ".", "values", ":", "submatrix", "=", "descriptor_dict", "[", "col", "]", ".", ...
[ 260, 0 ]
[ 288, 28 ]
python
en
['en', 'en', 'en']
True
reaction_space
(component_dict, encoding={}, descriptor_matrices={}, clean=True, decorrelate=True, decorrelation_threshold=0.95, standardize=True)
Build a reaction space object form component lists. Parameters ---------- reaction_components : dict Dictionary of reaction components of the form: Example ------- Defining reaction components :: {'A': [a1, a2, a3, ...], ...
Build a reaction space object form component lists. Parameters ---------- reaction_components : dict Dictionary of reaction components of the form: Example ------- Defining reaction components :: {'A': [a1, a2, a3, ...], ...
def reaction_space(component_dict, encoding={}, descriptor_matrices={}, clean=True, decorrelate=True, decorrelation_threshold=0.95, standardize=True): """Build a reaction space object form component lists. Parameters ---------- reaction_components : dict ...
[ "def", "reaction_space", "(", "component_dict", ",", "encoding", "=", "{", "}", ",", "descriptor_matrices", "=", "{", "}", ",", "clean", "=", "True", ",", "decorrelate", "=", "True", ",", "decorrelation_threshold", "=", "0.95", ",", "standardize", "=", "True...
[ 290, 0 ]
[ 447, 19 ]
python
en
['en', 'en', 'en']
True
descriptor_matrix
(molecule_index, lookup_table, lookup='SMILES', name='')
Generate a descriptor matrix.
Generate a descriptor matrix.
def descriptor_matrix(molecule_index, lookup_table, lookup='SMILES', name=''): """Generate a descriptor matrix.""" # New column names columns = list(lookup_table.columns.values) new_columns = [] for column in columns: if name != '': new_columns.append(name + '_' + str(c...
[ "def", "descriptor_matrix", "(", "molecule_index", ",", "lookup_table", ",", "lookup", "=", "'SMILES'", ",", "name", "=", "''", ")", ":", "# New column names", "columns", "=", "list", "(", "lookup_table", ".", "columns", ".", "values", ")", "new_columns", "=",...
[ 451, 0 ]
[ 476, 16 ]
python
ca
['es', 'ca', 'it']
False
build_experiment_index
(index, index_list, lookup_table_list, lookup_list)
Build a descriptor matrix.
Build a descriptor matrix.
def build_experiment_index(index, index_list, lookup_table_list, lookup_list): """Build a descriptor matrix.""" matrix = descriptor_matrix(index_list[0], lookup_table_list[0], lookup=lookup_list[0]) matrix.insert(0, 'entry', list(index)) ...
[ "def", "build_experiment_index", "(", "index", ",", "index_list", ",", "lookup_table_list", ",", "lookup_list", ")", ":", "matrix", "=", "descriptor_matrix", "(", "index_list", "[", "0", "]", ",", "lookup_table_list", "[", "0", "]", ",", "lookup", "=", "lookup...
[ 480, 0 ]
[ 496, 17 ]
python
ca
['en', 'ca', 'it']
False
register.check_metadata
(self)
Deprecated API.
Deprecated API.
def check_metadata(self): """Deprecated API.""" warn("distutils.command.register.check_metadata is deprecated, \ use the check command instead", PendingDeprecationWarning) check = self.distribution.get_command_obj('check') check.ensure_finalized() check.strict = sel...
[ "def", "check_metadata", "(", "self", ")", ":", "warn", "(", "\"distutils.command.register.check_metadata is deprecated, \\\n use the check command instead\"", ",", "PendingDeprecationWarning", ")", "check", "=", "self", ".", "distribution", ".", "get_command_obj", ...
[ 57, 4 ]
[ 65, 19 ]
python
en
['en', 'pt', 'en']
False
register._set_config
(self)
Reads the configuration file and set attributes.
Reads the configuration file and set attributes.
def _set_config(self): ''' Reads the configuration file and set attributes. ''' config = self._read_pypirc() if config != {}: self.username = config['username'] self.password = config['password'] self.repository = config['repository'] self....
[ "def", "_set_config", "(", "self", ")", ":", "config", "=", "self", ".", "_read_pypirc", "(", ")", "if", "config", "!=", "{", "}", ":", "self", ".", "username", "=", "config", "[", "'username'", "]", "self", ".", "password", "=", "config", "[", "'pas...
[ 67, 4 ]
[ 82, 35 ]
python
en
['en', 'en', 'en']
True
register.classifiers
(self)
Fetch the list of classifiers from the server.
Fetch the list of classifiers from the server.
def classifiers(self): ''' Fetch the list of classifiers from the server. ''' url = self.repository+'?:action=list_classifiers' response = urllib.request.urlopen(url) log.info(self._read_pypi_response(response))
[ "def", "classifiers", "(", "self", ")", ":", "url", "=", "self", ".", "repository", "+", "'?:action=list_classifiers'", "response", "=", "urllib", ".", "request", ".", "urlopen", "(", "url", ")", "log", ".", "info", "(", "self", ".", "_read_pypi_response", ...
[ 84, 4 ]
[ 89, 52 ]
python
en
['en', 'en', 'en']
True
register.verify_metadata
(self)
Send the metadata to the package index server to be checked.
Send the metadata to the package index server to be checked.
def verify_metadata(self): ''' Send the metadata to the package index server to be checked. ''' # send the info to the server and report the result (code, result) = self.post_to_server(self.build_post_data('verify')) log.info('Server response (%s): %s', code, result)
[ "def", "verify_metadata", "(", "self", ")", ":", "# send the info to the server and report the result", "(", "code", ",", "result", ")", "=", "self", ".", "post_to_server", "(", "self", ".", "build_post_data", "(", "'verify'", ")", ")", "log", ".", "info", "(", ...
[ 91, 4 ]
[ 96, 58 ]
python
en
['en', 'en', 'en']
True
register.send_metadata
(self)
Send the metadata to the package index server. Well, do the following: 1. figure who the user is, and then 2. send the data as a Basic auth'ed POST. First we try to read the username/password from $HOME/.pypirc, which is a ConfigParser-formatted file with a...
Send the metadata to the package index server.
def send_metadata(self): ''' Send the metadata to the package index server. Well, do the following: 1. figure who the user is, and then 2. send the data as a Basic auth'ed POST. First we try to read the username/password from $HOME/.pypirc, which is ...
[ "def", "send_metadata", "(", "self", ")", ":", "# see if we can short-cut and get the username/password from the", "# config", "if", "self", ".", "has_config", ":", "choice", "=", "'1'", "username", "=", "self", ".", "username", "password", "=", "self", ".", "passwo...
[ 98, 4 ]
[ 218, 62 ]
python
en
['en', 'en', 'en']
True
register.post_to_server
(self, data, auth=None)
Post a query to the server, and return a string response.
Post a query to the server, and return a string response.
def post_to_server(self, data, auth=None): ''' Post a query to the server, and return a string response. ''' if 'name' in data: self.announce('Registering %s to %s' % (data['name'], self.repository), ...
[ "def", "post_to_server", "(", "self", ",", "data", ",", "auth", "=", "None", ")", ":", "if", "'name'", "in", "data", ":", "self", ".", "announce", "(", "'Registering %s to %s'", "%", "(", "data", "[", "'name'", "]", ",", "self", ".", "repository", ")",...
[ 248, 4 ]
[ 303, 21 ]
python
en
['en', 'en', 'en']
True
chunk_list
(list_in, chunk_size)
Split a list into chunks.
Split a list into chunks.
def chunk_list(list_in, chunk_size): """ Split a list into chunks. """ return [list_in[i:i + chunk_size] for i in range(0, len(list_in), chunk_size)]
[ "def", "chunk_list", "(", "list_in", ",", "chunk_size", ")", ":", "return", "[", "list_in", "[", "i", ":", "i", "+", "chunk_size", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "list_in", ")", ",", "chunk_size", ")", "]" ]
[ 277, 0 ]
[ 281, 82 ]
python
en
['en', 'error', 'th']
False
ErrorLogs.truncate
(cls, n=100)
Truncate the DB and keep only N latest exceptions
Truncate the DB and keep only N latest exceptions
def truncate(cls, n=100): """ Truncate the DB and keep only N latest exceptions """ db = cls.get_db() cursor = db.execute( "DELETE FROM error_logs WHERE time IN " "(SELECT time FROM error_logs ORDER BY time DESC LIMIT -1 OFFSET ?)", (int(n),)) db.c...
[ "def", "truncate", "(", "cls", ",", "n", "=", "100", ")", ":", "db", "=", "cls", ".", "get_db", "(", ")", "cursor", "=", "db", ".", "execute", "(", "\"DELETE FROM error_logs WHERE time IN \"", "\"(SELECT time FROM error_logs ORDER BY time DESC LIMIT -1 OFFSET ?)\"", ...
[ 73, 4 ]
[ 83, 19 ]
python
en
['en', 'error', 'th']
False
test_copy_tables_unified_job_query
(sqlite_copy_expert, project, inventory, job_template)
Ensure that various unified job types are in the output of the query.
Ensure that various unified job types are in the output of the query.
def test_copy_tables_unified_job_query(sqlite_copy_expert, project, inventory, job_template): """ Ensure that various unified job types are in the output of the query. """ time_start = now() - timedelta(hours=9) inv_src = InventorySource.objects.create(name="inventory_update1", inventory=inventory,...
[ "def", "test_copy_tables_unified_job_query", "(", "sqlite_copy_expert", ",", "project", ",", "inventory", ",", "job_template", ")", ":", "time_start", "=", "now", "(", ")", "-", "timedelta", "(", "hours", "=", "9", ")", "inv_src", "=", "InventorySource", ".", ...
[ 75, 0 ]
[ 94, 36 ]
python
en
['en', 'error', 'th']
False
workflow_job
(states=["new", "new", "new", "new", "new"])
Workflow topology: node[0] /\ s/ \f / \ node[1,5] node[3] / \ s/ \f / \ node[2] node[4]
Workflow topology: node[0] /\ s/ \f / \ node[1,5] node[3] / \ s/ \f / \ node[2] node[4]
def workflow_job(states=["new", "new", "new", "new", "new"]): """ Workflow topology: node[0] /\ s/ \f / \ node[1,5] node[3] / \ s/ \f / \ node[2] node[4] """ wfj = WorkflowJob.objects.create() ...
[ "def", "workflow_job", "(", "states", "=", "[", "\"new\"", ",", "\"new\"", ",", "\"new\"", ",", "\"new\"", ",", "\"new\"", "]", ")", ":", "wfj", "=", "WorkflowJob", ".", "objects", ".", "create", "(", ")", "jt", "=", "JobTemplate", ".", "objects", ".",...
[ 98, 0 ]
[ 125, 14 ]
python
en
['en', 'error', 'th']
False
TestApiritifScriptGeneration.test_complex_codegen
(self)
This test serves code review purposes, to make changes more visible
This test serves code review purposes, to make changes more visible
def test_complex_codegen(self): """ This test serves code review purposes, to make changes more visible """ self.obj.engine.config.load([RESOURCES_DIR + 'apiritif/test_codegen.yml']) self.configure(self.obj.engine.config['execution'][0]) self.obj.settings['verbose'] = True self.o...
[ "def", "test_complex_codegen", "(", "self", ")", ":", "self", ".", "obj", ".", "engine", ".", "config", ".", "load", "(", "[", "RESOURCES_DIR", "+", "'apiritif/test_codegen.yml'", "]", ")", "self", ".", "configure", "(", "self", ".", "obj", ".", "engine", ...
[ 475, 4 ]
[ 483, 75 ]
python
en
['en', 'en', 'en']
True
TestApiritifScriptGeneration.test_delimiter_tab
(self)
Check if 'tab' is converted to '\t' ('\\t' when read from .py file)
Check if 'tab' is converted to '\t' ('\\t' when read from .py file)
def test_delimiter_tab(self): """ Check if 'tab' is converted to '\t' ('\\t' when read from .py file) """ self.configure({ "execution": [{ "test-mode": "apiritif", "scenario": { "requests": ["http://blazedemo.com/"], ...
[ "def", "test_delimiter_tab", "(", "self", ")", ":", "self", ".", "configure", "(", "{", "\"execution\"", ":", "[", "{", "\"test-mode\"", ":", "\"apiritif\"", ",", "\"scenario\"", ":", "{", "\"requests\"", ":", "[", "\"http://blazedemo.com/\"", "]", ",", "\"dat...
[ 896, 4 ]
[ 913, 116 ]
python
en
['en', 'error', 'th']
False
SunPowerPVSEntity.__init__
(self, coordinator, pvs_info)
Initialize the sensor.
Initialize the sensor.
def __init__(self, coordinator, pvs_info): """Initialize the sensor.""" super().__init__(coordinator) self.base_unique_id = pvs_info["SERIAL"] self._pvs_info = pvs_info
[ "def", "__init__", "(", "self", ",", "coordinator", ",", "pvs_info", ")", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ")", "self", ".", "base_unique_id", "=", "pvs_info", "[", "\"SERIAL\"", "]", "self", ".", "_pvs_info", "=", "pvs_info" ]
[ 10, 4 ]
[ 14, 33 ]
python
en
['en', 'en', 'en']
True
SunPowerPVSEntity.device_info
(self)
Sunpower PVS device info.
Sunpower PVS device info.
def device_info(self): """Sunpower PVS device info.""" device_info = { "identifiers": {(DOMAIN, self.base_unique_id)}, "name": "{} {}".format(self._pvs_info["MODEL"], self._pvs_info["SERIAL"]), "manufacturer": "SunPower", "model": self._pvs_info["MODEL"], ...
[ "def", "device_info", "(", "self", ")", ":", "device_info", "=", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "base_unique_id", ")", "}", ",", "\"name\"", ":", "\"{} {}\"", ".", "format", "(", "self", ".", "_pvs_info", "[", "\"MODEL...
[ 17, 4 ]
[ 28, 26 ]
python
en
['es', 'lb', 'en']
False
SunPowerMeterEntity.__init__
(self, coordinator, meter_info, pvs_info)
Initialize the sensor.
Initialize the sensor.
def __init__(self, coordinator, meter_info, pvs_info): """Initialize the sensor.""" super().__init__(coordinator) self.base_unique_id = meter_info["SERIAL"] self._pvs_info = pvs_info self._meter_info = meter_info
[ "def", "__init__", "(", "self", ",", "coordinator", ",", "meter_info", ",", "pvs_info", ")", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ")", "self", ".", "base_unique_id", "=", "meter_info", "[", "\"SERIAL\"", "]", "self", ".", "_pvs_info...
[ 34, 4 ]
[ 39, 37 ]
python
en
['en', 'en', 'en']
True
SunPowerMeterEntity.device_info
(self)
Sunpower Inverter device info.
Sunpower Inverter device info.
def device_info(self): """Sunpower Inverter device info.""" device_info = { "identifiers": {(DOMAIN, self.base_unique_id)}, "name": self._meter_info["DESCR"], "manufacturer": "SunPower", "model": self._meter_info["MODEL"], "sw_version": self._m...
[ "def", "device_info", "(", "self", ")", ":", "device_info", "=", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "base_unique_id", ")", "}", ",", "\"name\"", ":", "self", ".", "_meter_info", "[", "\"DESCR\"", "]", ",", "\"manufacturer\""...
[ 42, 4 ]
[ 52, 26 ]
python
de
['de', 'no', 'en']
False
SunPowerInverterEntity.__init__
(self, coordinator, inverter_info, pvs_info)
Initialize the sensor.
Initialize the sensor.
def __init__(self, coordinator, inverter_info, pvs_info): """Initialize the sensor.""" super().__init__(coordinator) self.base_unique_id = inverter_info["SERIAL"] self._pvs_info = pvs_info self._inverter_info = inverter_info
[ "def", "__init__", "(", "self", ",", "coordinator", ",", "inverter_info", ",", "pvs_info", ")", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ")", "self", ".", "base_unique_id", "=", "inverter_info", "[", "\"SERIAL\"", "]", "self", ".", "_pv...
[ 58, 4 ]
[ 63, 43 ]
python
en
['en', 'en', 'en']
True
SunPowerInverterEntity.device_info
(self)
Sunpower Inverter device info.
Sunpower Inverter device info.
def device_info(self): """Sunpower Inverter device info.""" device_info = { "identifiers": {(DOMAIN, self.base_unique_id)}, "name": self._inverter_info["DESCR"], "manufacturer": self._inverter_info["TYPE"], "model": self._inverter_info["MODEL"], ...
[ "def", "device_info", "(", "self", ")", ":", "device_info", "=", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "base_unique_id", ")", "}", ",", "\"name\"", ":", "self", ".", "_inverter_info", "[", "\"DESCR\"", "]", ",", "\"manufacturer...
[ 66, 4 ]
[ 76, 26 ]
python
de
['de', 'no', 'en']
False
RAIDHelper.view_storage
(self, controller=None, virtual_disk=None)
view storage hierarchy as a json :param controller: contoller id :param controller: str :param virtual_disk: virtual disk id :param virtual_disk: str :return: returns json accoring to the parameter provided
view storage hierarchy as a json
def view_storage(self, controller=None, virtual_disk=None): """ view storage hierarchy as a json :param controller: contoller id :param controller: str :param virtual_disk: virtual disk id :param virtual_disk: str :return: returns json accoring to the parameter provided ...
[ "def", "view_storage", "(", "self", ",", "controller", "=", "None", ",", "virtual_disk", "=", "None", ")", ":", "try", ":", "logger", ".", "info", "(", "self", ".", "entity", ".", "ipaddr", "+", "\" : getting storage tree\"", ")", "storage_tree", "=", "sel...
[ 497, 4 ]
[ 550, 77 ]
python
en
['en', 'en', 'en']
True
Loader.get_template
(self, template_name, template_dirs=None, skip=None)
Perform the caching that gives this loader its name. Often many of the templates attempted will be missing, so memory use is of concern here. To keep it in check, caching behavior is a little complicated when a template is not found. See ticket #26306 for more details. With tem...
Perform the caching that gives this loader its name. Often many of the templates attempted will be missing, so memory use is of concern here. To keep it in check, caching behavior is a little complicated when a template is not found. See ticket #26306 for more details.
def get_template(self, template_name, template_dirs=None, skip=None): """ Perform the caching that gives this loader its name. Often many of the templates attempted will be missing, so memory use is of concern here. To keep it in check, caching behavior is a little complicated when a ...
[ "def", "get_template", "(", "self", ",", "template_name", ",", "template_dirs", "=", "None", ",", "skip", "=", "None", ")", ":", "key", "=", "self", ".", "cache_key", "(", "template_name", ",", "template_dirs", ",", "skip", ")", "cached", "=", "self", "....
[ 29, 4 ]
[ 67, 23 ]
python
en
['en', 'error', 'th']
False
Loader.cache_key
(self, template_name, template_dirs, skip=None)
Generate a cache key for the template name, dirs, and skip. If skip is provided, only origins that match template_name are included in the cache key. This ensures each template is only parsed and cached once if contained in different extend chains like: x -> a -> a ...
Generate a cache key for the template name, dirs, and skip.
def cache_key(self, template_name, template_dirs, skip=None): """ Generate a cache key for the template name, dirs, and skip. If skip is provided, only origins that match template_name are included in the cache key. This ensures each template is only parsed and cached once if co...
[ "def", "cache_key", "(", "self", ",", "template_name", ",", "template_dirs", ",", "skip", "=", "None", ")", ":", "dirs_prefix", "=", "''", "skip_prefix", "=", "''", "if", "skip", ":", "matching", "=", "[", "origin", ".", "name", "for", "origin", "in", ...
[ 79, 4 ]
[ 102, 92 ]
python
en
['en', 'error', 'th']
False