_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q24600 | IRGenerator._inject_patched_examples | train | def _inject_patched_examples(self, existing_item, patched_item):
"""Injects patched examples into original examples."""
for key, _ in patched_item.examples.items():
patched_example = patched_item.examples[key]
existing_examples = existing_item.examples
| python | {
"resource": ""
} |
q24601 | IRGenerator._populate_type_attributes | train | def _populate_type_attributes(self):
"""
Converts each struct, union, and route from a forward reference to a
full definition.
"""
for namespace in self.api.namespaces.values():
env = self._get_or_create_env(namespace.name)
# do annotations before everyth... | python | {
"resource": ""
} |
q24602 | IRGenerator._populate_struct_type_attributes | train | def _populate_struct_type_attributes(self, env, data_type):
"""
Converts a forward reference of a struct into a complete definition.
"""
parent_type = None
extends = data_type._ast_node.extends
if extends:
# A parent type must be fully defined and not just a f... | python | {
"resource": ""
} |
q24603 | IRGenerator._populate_union_type_attributes | train | def _populate_union_type_attributes(self, env, data_type):
"""
Converts a forward reference of a union into a complete definition.
"""
parent_type = None
extends = data_type._ast_node.extends
if extends:
# A parent type must be fully defined and not just a for... | python | {
"resource": ""
} |
q24604 | IRGenerator._populate_field_defaults | train | def _populate_field_defaults(self):
"""
Populate the defaults of each field. This is done in a separate pass
because defaults that specify a union tag require the union to have
been defined.
"""
for namespace in self.api.namespaces.values():
for data_type in n... | python | {
"resource": ""
} |
q24605 | IRGenerator._populate_route_attributes | train | def _populate_route_attributes(self):
"""
Converts all routes from forward references to complete definitions.
"""
route_schema = self._validate_stone_cfg()
| python | {
"resource": ""
} |
q24606 | IRGenerator._populate_route_attributes_helper | train | def _populate_route_attributes_helper(self, env, route, schema):
"""
Converts a single forward reference of a route into a complete definition.
"""
arg_dt = self._resolve_type(env, route._ast_node.arg_type_ref)
result_dt = self._resolve_type(env, route._ast_node.result_type_ref)
... | python | {
"resource": ""
} |
q24607 | IRGenerator._instantiate_data_type | train | def _instantiate_data_type(self, data_type_class, data_type_args, loc):
"""
Responsible for instantiating a data type with additional attributes.
This method ensures that the specified attributes are valid.
Args:
data_type_class (DataType): The class to instantiate.
... | python | {
"resource": ""
} |
q24608 | IRGenerator._resolve_type | train | def _resolve_type(self, env, type_ref, enforce_fully_defined=False):
"""
Resolves the data type referenced by type_ref.
If `enforce_fully_defined` is True, then the referenced type must be
fully populated (fields, parent_type, ...), and not simply a forward
reference.
""... | python | {
"resource": ""
} |
q24609 | IRGenerator._resolve_annotation_type | train | def _resolve_annotation_type(self, env, annotation_ref):
"""
Resolves the annotation type referenced by annotation_ref.
"""
loc = annotation_ref.lineno, annotation_ref.path
if annotation_ref.ns:
if annotation_ref.ns not in env:
raise InvalidSpec(
... | python | {
"resource": ""
} |
q24610 | IRGenerator._resolve_args | train | def _resolve_args(self, env, args):
"""
Resolves type references in data type arguments to data types in
the environment.
"""
pos_args, kw_args = args
def check_value(v):
if isinstance(v, AstTypeRef):
return self._resolve_type(env, v)
... | python | {
"resource": ""
} |
q24611 | IRGenerator._create_route | train | def _create_route(self, env, item):
"""
Constructs a route and adds it to the environment.
Args:
env (dict): The environment of defined symbols. A new key is added
corresponding to the name of this new route.
item (AstRouteDef): Raw route definition from ... | python | {
"resource": ""
} |
q24612 | IRGenerator._populate_examples | train | def _populate_examples(self):
"""Construct every possible example for every type.
This is done in two passes. The first pass assigns examples to their
associated types, but does not resolve references between examples for
different types. This is because the referenced examples may not ... | python | {
"resource": ""
} |
q24613 | IRGenerator._validate_doc_refs | train | def _validate_doc_refs(self):
"""
Validates that all the documentation references across every docstring
in every spec are formatted properly, have valid values, and make
references to valid symbols.
"""
for namespace in self.api.namespaces.values():
env = sel... | python | {
"resource": ""
} |
q24614 | IRGenerator._validate_annotations | train | def _validate_annotations(self):
"""
Validates that all annotations are attached to proper types and that no field
has conflicting inherited or direct annotations. We need to go through all reference
chains to make sure we don't override a redactor set on a parent alias or type
"... | python | {
"resource": ""
} |
q24615 | IRGenerator._validate_field_can_be_tagged_with_redactor | train | def _validate_field_can_be_tagged_with_redactor(self, field):
"""
Validates that the field type can be annotated and that alias does not have
conflicting annotations.
"""
if is_alias(field.data_type):
raise InvalidSpec(
| python | {
"resource": ""
} |
q24616 | IRGenerator._validate_object_can_be_tagged_with_redactor | train | def _validate_object_can_be_tagged_with_redactor(self, annotated_object):
"""
Validates that the object type can be annotated and object does not have
conflicting annotations.
"""
data_type = annotated_object.data_type
name = annotated_object.name
loc = annotated_... | python | {
"resource": ""
} |
q24617 | ExampleBackend.generate | train | def generate(self, api):
"""Generates a file that lists each namespace."""
with self.output_to_relative_path('ex1.out'): | python | {
"resource": ""
} |
q24618 | get_zip_class | train | def get_zip_class():
"""
Supplement ZipFile class to support context manager for Python 2.6
"""
class ContextualZipFile(zipfile.ZipFile):
def __enter__(self):
return self
def __exit__(self, type, value, | python | {
"resource": ""
} |
q24619 | PythonTypeStubsBackend._generate_typevars | train | def _generate_typevars(self):
# type: () -> None
"""
Creates type variables that are used by the type signatures for
_process_custom_annotations.
"""
self.emit("T | python | {
"resource": ""
} |
q24620 | String.validate | train | def validate(self, val):
"""
A unicode string of the correct length and pattern will pass validation.
In PY2, we enforce that a str type must be valid utf-8, and a unicode
string will be returned.
"""
if not isinstance(val, six.string_types):
raise ValidationE... | python | {
"resource": ""
} |
q24621 | Struct.validate | train | def validate(self, val):
"""
For a val to pass validation, val must be of the correct type and have | python | {
"resource": ""
} |
q24622 | Struct.validate_with_permissions | train | def validate_with_permissions(self, val, caller_permissions):
"""
For a val to pass validation, val must be of the correct type and have
all required | python | {
"resource": ""
} |
q24623 | Struct.validate_fields_only | train | def validate_fields_only(self, val):
"""
To pass field validation, no required field should be missing.
This method assumes that the contents of each field have already been
validated on assignment, so it's merely a presence check.
FIXME(kelkabany): Since the definition object ... | python | {
"resource": ""
} |
q24624 | Struct.validate_fields_only_with_permissions | train | def validate_fields_only_with_permissions(self, val, caller_permissions):
"""
To pass field validation, no required field should be missing.
This method assumes that the contents of each field have already been
validated on assignment, so it's merely a presence check.
Should only... | python | {
"resource": ""
} |
q24625 | Union.validate | train | def validate(self, val):
"""
For a val to pass validation, it must have a _tag set. This assumes
that the object validated that _tag is a valid tag, and that any
associated value has also been validated.
"""
self.validate_type_only(val) | python | {
"resource": ""
} |
q24626 | Api.ensure_namespace | train | def ensure_namespace(self, name):
# type: (str) -> ApiNamespace
"""
Only creates a namespace if it hasn't yet been defined.
:param str name: Name of the namespace.
:return ApiNamespace:
"""
| python | {
"resource": ""
} |
q24627 | Api.normalize | train | def normalize(self):
# type: () -> None
"""
Alphabetizes namespaces and routes to make spec parsing order mostly
irrelevant.
"""
ordered_namespaces = OrderedDict() # type: NamespaceDict
# self.namespaces is currently ordered by declaration order.
for name... | python | {
"resource": ""
} |
q24628 | ApiNamespace.add_doc | train | def add_doc(self, docstring):
# type: (six.text_type) -> None
"""Adds a docstring for this namespace.
The input docstring is normalized to have no leading whitespace and
no trailing whitespace except for a newline at the end.
If a docstring already exists, the new normalized do... | python | {
"resource": ""
} |
q24629 | ApiNamespace.add_imported_namespace | train | def add_imported_namespace(self,
namespace,
imported_alias=False,
imported_data_type=False,
imported_annotation=False,
imported_annotation_type=False):
# typ... | python | {
"resource": ""
} |
q24630 | ApiNamespace.linearize_data_types | train | def linearize_data_types(self):
# type: () -> typing.List[UserDefined]
"""
Returns a list of all data types used in the namespace. Because the
inheritance of data types can be modeled as a DAG, the list will be a
linearization of the DAG. It's ideal to generate data types in this... | python | {
"resource": ""
} |
q24631 | ApiNamespace.linearize_aliases | train | def linearize_aliases(self):
# type: () -> typing.List[Alias]
"""
Returns a list of all aliases used in the namespace. The aliases are
ordered to ensure that if they reference other aliases those aliases
come earlier in the list.
"""
linearized_aliases = []
... | python | {
"resource": ""
} |
q24632 | ApiNamespace.get_route_io_data_types | train | def get_route_io_data_types(self):
# type: () -> typing.List[UserDefined]
"""
Returns a list of all user-defined data types that are referenced as
either an argument, result, or error of a route. If a List or Nullable
data type is referenced, then the contained data type is retur... | python | {
"resource": ""
} |
q24633 | ApiNamespace.get_imported_namespaces | train | def get_imported_namespaces(self,
must_have_imported_data_type=False,
consider_annotations=False,
consider_annotation_types=False):
# type: (bool, bool, bool) -> typing.List[ApiNamespace]
"""
Returns ... | python | {
"resource": ""
} |
q24634 | ApiNamespace.get_namespaces_imported_by_route_io | train | def get_namespaces_imported_by_route_io(self):
# type: () -> typing.List[ApiNamespace]
"""
Returns a list of Namespace objects. A namespace is a member of this
list if it is imported by the current namespace and has a data type
from it referenced as an argument, result, or error ... | python | {
"resource": ""
} |
q24635 | ApiNamespace.normalize | train | def normalize(self):
# type: () -> None
"""
Alphabetizes routes to make route declaration order irrelevant.
"""
self.routes.sort(key=lambda route: route.name)
self.data_types.sort(key=lambda data_type: data_type.name)
| python | {
"resource": ""
} |
q24636 | ApiRoute.set_attributes | train | def set_attributes(self, deprecated, doc, arg_data_type, result_data_type,
error_data_type, attrs):
"""
Converts a forward reference definition of a route into a full
definition.
:param DeprecationInfo deprecated: Set if this route is deprecated.
:param st... | python | {
"resource": ""
} |
q24637 | ApiRoute.name_with_version | train | def name_with_version(self):
"""
Get user-friendly representation of the route.
:return: Route name with version suffix. The | python | {
"resource": ""
} |
q24638 | UnstoneBackend.generate | train | def generate(self, api):
"""Main code generator entry point."""
# Create a file for each namespace.
for namespace in api.namespaces.values():
with self.output_to_relative_path('%s.stone' % namespace.name):
# Output a namespace header.
| python | {
"resource": ""
} |
q24639 | UnstoneBackend.generate_route | train | def generate_route(self, route):
"""Output a route definition."""
self.emit('')
self.emit('route %s (%s, %s, %s)' % (
route.name,
self.format_data_type(route.arg_data_type),
self.format_data_type(route.result_data_type),
self.format_data_type(route... | python | {
"resource": ""
} |
q24640 | UnstoneBackend.format_data_type | train | def format_data_type(self, data_type):
"""Helper function to format a data type.
This returns the name if it's a struct or union, otherwise
(i.e. for primitive types) it renders the name and the
parameters.
"""
s = data_type.name
for type_class, key_list in self.... | python | {
"resource": ""
} |
q24641 | UnstoneBackend.format_value | train | def format_value(self, val):
"""Helper function to format a value."""
if isinstance(val, | python | {
"resource": ""
} |
q24642 | _create_token | train | def _create_token(token_type, value, lineno, lexpos):
"""
Helper for creating ply.lex.LexToken objects. Unfortunately, LexToken
does not have a constructor defined to make settings these values easy.
"""
| python | {
"resource": ""
} |
q24643 | Lexer.token | train | def token(self):
"""
Returns the next LexToken. Returns None when all tokens have been
exhausted.
"""
if self.tokens_queue:
self.last_token = self.tokens_queue.pop(0)
else:
r = self.lex.token()
if isinstance(r, MultiToken):
... | python | {
"resource": ""
} |
q24644 | Lexer._create_tokens_for_next_line_dent | train | def _create_tokens_for_next_line_dent(self, newline_token):
"""
Starting from a newline token that isn't followed by another newline
token, returns any indent or dedent tokens that immediately follow.
If indentation doesn't change, returns None.
"""
indent_delta = self._g... | python | {
"resource": ""
} |
q24645 | Lexer._check_for_indent | train | def _check_for_indent(self, newline_token):
"""
Checks that the line following a newline is indented, otherwise a
parsing error is generated.
"""
indent_delta = self._get_next_line_indent_delta(newline_token)
if indent_delta is None or indent_delta == 1:
# Nex... | python | {
"resource": ""
} |
q24646 | ObjCBaseBackend._get_imports_m | train | def _get_imports_m(self, data_types, default_imports):
"""Emits all necessary implementation file imports for the given Stone data type."""
if not isinstance(data_types, list):
data_types = [data_types]
import_classes = default_imports
for data_type in data_types:
... | python | {
"resource": ""
} |
q24647 | ObjCBaseBackend._get_imports_h | train | def _get_imports_h(self, data_types):
"""Emits all necessary header file imports for the given Stone data type."""
if not isinstance(data_types, list):
data_types = [data_types]
import_classes = []
for data_type in data_types:
if is_user_defined_type(data_type)... | python | {
"resource": ""
} |
q24648 | ObjCBaseBackend._struct_has_defaults | train | def _struct_has_defaults(self, struct):
"""Returns whether the given struct has any default values."""
return [
| python | {
"resource": ""
} |
q24649 | Compiler.build | train | def build(self):
"""Creates outputs. Outputs are files made by a backend."""
if os.path.exists(self.build_path) and not os.path.isdir(self.build_path):
self._logger.error('Output path must be a folder | python | {
"resource": ""
} |
q24650 | Compiler._execute_backend_on_spec | train | def _execute_backend_on_spec(self):
"""Renders a source file into its final form."""
api_no_aliases_cache = None
for attr_key in dir(self.backend_module):
attr_value = getattr(self.backend_module, attr_key)
if (inspect.isclass(attr_value) and
issubcla... | python | {
"resource": ""
} |
q24651 | EndpointException.to_dict | train | def to_dict(self):
"""Return a dictionary representation of the exception."""
as_dict = dict(self.payload or ())
| python | {
"resource": ""
} |
q24652 | Model.required | train | def required(cls):
"""Return a list of all columns required by the database to create the
resource.
:param cls: The Model class to gather attributes from
:rtype: list
"""
columns = []
for column in cls.__table__.columns: # pylint: disable=no-member
i... | python | {
"resource": ""
} |
q24653 | Model.optional | train | def optional(cls):
"""Return a list of all nullable columns for the resource's table.
:rtype: list
"""
columns = []
| python | {
"resource": ""
} |
q24654 | Model.to_dict | train | def to_dict(self):
"""Return the resource as a dictionary.
:rtype: dict
"""
result_dict = {}
for column in self.__table__.columns.keys(): # pylint: disable=no-member
value = result_dict[column] = getattr(self, column, None)
if isinstance(value, Decimal):... | python | {
"resource": ""
} |
q24655 | Model.description | train | def description(cls):
"""Return a field->data type dictionary describing this model
as reported by the database.
:rtype: dict
"""
description = {}
for column in cls.__table__.columns: # pylint: disable=no-member
column_description = str(column.type)
... | python | {
"resource": ""
} |
q24656 | register_service | train | def register_service(cls, primary_key_type):
"""Register an API service endpoint.
:param cls: The class to register
:param str primary_key_type: The type (as a string) of the primary_key
field
"""
view_func = cls.as_view(cls.__name__.lower()) # pylint: disable=no-m... | python | {
"resource": ""
} |
q24657 | _reflect_all | train | def _reflect_all(exclude_tables=None, admin=None, read_only=False, schema=None):
"""Register all tables in the given database as services.
:param list exclude_tables: A list of tables to exclude from the API
service
"""
AutomapModel.prepare( # pylint:disable=maybe-no-me... | python | {
"resource": ""
} |
q24658 | _register_user_models | train | def _register_user_models(user_models, admin=None, schema=None):
"""Register any user-defined models with the API Service.
:param list user_models: A list of user-defined models to include in the
API service
"""
if any([issubclass(cls, AutomapModel) for cls | python | {
"resource": ""
} |
q24659 | is_valid_method | train | def is_valid_method(model, resource=None):
"""Return the error message to be sent to the client if the current
request passes fails any user-defined validation."""
validation_function_name = 'is_valid_{}'.format(
request.method.lower())
| python | {
"resource": ""
} |
q24660 | Service.delete | train | def delete(self, resource_id):
"""Return an HTTP response object resulting from a HTTP DELETE call.
:param resource_id: The value of the resource's primary key
"""
resource = self._resource(resource_id)
error_message = is_valid_method(self.__model__, resource)
if error_m... | python | {
"resource": ""
} |
q24661 | Service.get | train | def get(self, resource_id=None):
"""Return an HTTP response object resulting from an HTTP GET call.
If *resource_id* is provided, return just the single resource.
Otherwise, return the full collection.
:param resource_id: The value of the resource's primary key
"""
if r... | python | {
"resource": ""
} |
q24662 | Service.patch | train | def patch(self, resource_id):
"""Return an HTTP response object resulting from an HTTP PATCH call.
:returns: ``HTTP 200`` if the resource already exists
:returns: ``HTTP 400`` if the request is malformed
:returns: ``HTTP 404`` if the resource is not found
:param resource_id: The... | python | {
"resource": ""
} |
q24663 | Service.post | train | def post(self):
"""Return the JSON representation of a new resource created through
an HTTP POST call.
:returns: ``HTTP 201`` if a resource is properly created
:returns: ``HTTP 204`` if the resource already exists
:returns: ``HTTP 400`` if the request is malformed or missing dat... | python | {
"resource": ""
} |
q24664 | Service.put | train | def put(self, resource_id):
"""Return the JSON representation of a new resource created or updated
through an HTTP PUT call.
If resource_id is not provided, it is assumed the primary key field is
included and a totally new resource is created. Otherwise, the existing
resource re... | python | {
"resource": ""
} |
q24665 | Service._all_resources | train | def _all_resources(self):
"""Return the complete collection of resources as a list of
dictionaries.
:rtype: :class:`sandman2.model.Model`
"""
queryset = self.__model__.query
args = {k: v for (k, v) in request.args.items() if k not in ('page', 'export')}
limit = N... | python | {
"resource": ""
} |
q24666 | main | train | def main():
"""Main entry point for script."""
parser = argparse.ArgumentParser(
description='Auto-generate a RESTful API service '
'from an existing database.'
)
parser.add_argument(
'URI',
help='Database URI in the format '
'postgresql+psycopg2://user:p... | python | {
"resource": ""
} |
q24667 | etag | train | def etag(func):
"""Return a decorator that generates proper ETag values for a response.
:param func: view function
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
"""Call the view function and generate an ETag value, checking the
headers to determine what response to send."... | python | {
"resource": ""
} |
q24668 | validate_fields | train | def validate_fields(func):
"""A decorator to automatically detect missing required fields from
json data."""
@functools.wraps(func)
def decorated(instance, *args, **kwargs):
"""The decorator function."""
data = request.get_json(force=True, silent=True)
if not data:
ra... | python | {
"resource": ""
} |
q24669 | merge_record_extra | train | def merge_record_extra(record, target, reserved):
"""
Merges extra attributes from LogRecord object into target dictionary
:param record: logging.LogRecord
:param target: dict to update
:param reserved: dict or list with reserved keys to skip
"""
for key, value in record.__dict__.items():
... | python | {
"resource": ""
} |
q24670 | JsonFormatter._str_to_fn | train | def _str_to_fn(self, fn_as_str):
"""
If the argument is not a string, return whatever was passed in.
Parses a string such as package.module.function, imports the module
and returns the function.
:param fn_as_str: The string to parse. If not a string, return it.
"""
| python | {
"resource": ""
} |
q24671 | JsonFormatter.parse | train | def parse(self):
"""
Parses format string looking for substitutions
This method is responsible for returning a list of fields (as strings)
to include in all log messages.
"""
| python | {
"resource": ""
} |
q24672 | JsonFormatter.add_fields | train | def add_fields(self, log_record, record, message_dict):
"""
Override this method to implement custom logic for adding fields.
"""
for field in self._required_fields:
log_record[field] = record.__dict__.get(field)
log_record.update(message_dict)
| python | {
"resource": ""
} |
q24673 | JsonFormatter.jsonify_log_record | train | def jsonify_log_record(self, log_record):
"""Returns a json string of the log record."""
return self.json_serializer(log_record,
| python | {
"resource": ""
} |
q24674 | JsonFormatter.format | train | def format(self, record):
"""Formats a log record and serializes to json"""
message_dict = {}
if isinstance(record.msg, dict):
message_dict = record.msg
record.message = None
else:
record.message = record.getMessage()
# only format time if need... | python | {
"resource": ""
} |
q24675 | odometry._get_file_lists | train | def _get_file_lists(self):
"""Find and list data files for each sensor."""
self.cam0_files = sorted(glob.glob(
os.path.join(self.sequence_path, 'image_0',
'*.{}'.format(self.imtype))))
self.cam1_files = sorted(glob.glob(
os.path.join(self.sequence... | python | {
"resource": ""
} |
q24676 | rotx | train | def rotx(t):
"""Rotation about the x-axis."""
c = np.cos(t)
s = np.sin(t)
return np.array([[1, 0, 0],
| python | {
"resource": ""
} |
q24677 | roty | train | def roty(t):
"""Rotation about the y-axis."""
c = np.cos(t)
s = np.sin(t)
return np.array([[c, 0, s],
| python | {
"resource": ""
} |
q24678 | rotz | train | def rotz(t):
"""Rotation about the z-axis."""
c = np.cos(t)
s = np.sin(t)
return np.array([[c, -s, 0],
| python | {
"resource": ""
} |
q24679 | transform_from_rot_trans | train | def transform_from_rot_trans(R, t):
"""Transforation matrix from rotation matrix and translation | python | {
"resource": ""
} |
q24680 | read_calib_file | train | def read_calib_file(filepath):
"""Read in a calibration file and parse into a dictionary."""
data = {}
with open(filepath, 'r') as f:
for line in f.readlines():
key, value = line.split(':', 1)
# The only non-float values in these files are dates, which
| python | {
"resource": ""
} |
q24681 | load_oxts_packets_and_poses | train | def load_oxts_packets_and_poses(oxts_files):
"""Generator to read OXTS ground truth data.
Poses are given in an East-North-Up coordinate system
whose origin is the first GPS position.
"""
# Scale for Mercator projection (from first lat value)
scale = None
# Origin of the global coord... | python | {
"resource": ""
} |
q24682 | load_velo_scan | train | def load_velo_scan(file):
"""Load and parse a velodyne binary | python | {
"resource": ""
} |
q24683 | raw._load_calib_rigid | train | def _load_calib_rigid(self, filename):
"""Read a rigid transform calibration file as a numpy.array."""
filepath = os.path.join(self.calib_path, filename)
data | python | {
"resource": ""
} |
q24684 | SecretsCollection.load_baseline_from_string | train | def load_baseline_from_string(cls, string):
"""Initializes a SecretsCollection object from string.
:type string: str
:param string: string to load SecretsCollection from.
:rtype: SecretsCollection
:raises: IOError
"""
| python | {
"resource": ""
} |
q24685 | SecretsCollection.load_baseline_from_dict | train | def load_baseline_from_dict(cls, data):
"""Initializes a SecretsCollection object from dictionary.
:type data: dict
:param data: properly formatted dictionary to load SecretsCollection from.
:rtype: SecretsCollection
:raises: IOError
"""
result = SecretsCollecti... | python | {
"resource": ""
} |
q24686 | SecretsCollection.scan_diff | train | def scan_diff(
self,
diff,
baseline_filename='',
last_commit_hash='',
repo_name='',
):
"""For optimization purposes, our scanning strategy focuses on looking
at incremental differences, rather than re-scanning the codebase every time.
This function sup... | python | {
"resource": ""
} |
q24687 | SecretsCollection.scan_file | train | def scan_file(self, filename, filename_key=None):
"""Scans a specified file, and adds information to self.data
:type filename: str
:param filename: full path to file to scan.
:type filename_key: str
:param filename_key: key to store in self.data
:returns: boolean; thou... | python | {
"resource": ""
} |
q24688 | SecretsCollection.get_secret | train | def get_secret(self, filename, secret, type_=None):
"""Checks to see whether a secret is found in the collection.
:type filename: str
:param filename: the file to search in.
:type secret: str
:param secret: secret hash of secret to search for.
:type type_: str
... | python | {
"resource": ""
} |
q24689 | SecretsCollection._extract_secrets_from_file | train | def _extract_secrets_from_file(self, f, filename):
"""Extract secrets from a given file object.
:type f: File object
:type filename: string
"""
try:
log.info("Checking file: %s", filename)
for results, plugin in self._results_accumulator(filename)... | python | {
"resource": ""
} |
q24690 | SecretsCollection._extract_secrets_from_patch | train | def _extract_secrets_from_patch(self, f, plugin, filename):
"""Extract secrets from a given patch file object.
Note that we only want to capture incoming secrets (so added lines).
:type f: unidiff.patch.PatchedFile
:type plugin: detect_secrets.plugins.base.BasePlugin
:type file... | python | {
"resource": ""
} |
q24691 | YamlFileParser.get_ignored_lines | train | def get_ignored_lines(self):
"""
Return a set of integers that refer to line numbers that were
whitelisted by the user and should be ignored.
We need to parse the file separately from PyYAML parsing because
the parser drops the comments (at least up to version 3.13):
htt... | python | {
"resource": ""
} |
q24692 | IniFileParser._get_value_and_line_offset | train | def _get_value_and_line_offset(self, key, values):
"""Returns the index of the location of key, value pair in lines.
:type key: str
:param key: key, in config file.
:type values: str
:param values: values for key, in config file. This is plural,
because you can have... | python | {
"resource": ""
} |
q24693 | _get_baseline_string_from_file | train | def _get_baseline_string_from_file(filename): # pragma: no cover
"""Breaking this function up for mockability."""
try:
with open(filename) as f:
return f.read()
except IOError:
log.error(
'Unable to open | python | {
"resource": ""
} |
q24694 | raise_exception_if_baseline_file_is_unstaged | train | def raise_exception_if_baseline_file_is_unstaged(filename):
"""We want to make sure that if there are changes to the baseline
file, they will be included in the commit. This way, we can keep
our baselines up-to-date.
:raises: ValueError
"""
try:
files_changed_but_not_staged = subprocess... | python | {
"resource": ""
} |
q24695 | compare_baselines | train | def compare_baselines(old_baseline_filename, new_baseline_filename):
"""
This function enables developers to more easily configure plugin
settings, by comparing two generated baselines and highlighting
their differences.
For effective use, a few assumptions are made:
1. Baselines are sorted... | python | {
"resource": ""
} |
q24696 | _secret_generator | train | def _secret_generator(baseline):
"""Generates secrets to audit, from the baseline"""
for filename, secrets in baseline['results'].items(): | python | {
"resource": ""
} |
q24697 | _get_secret_with_context | train | def _get_secret_with_context(
filename,
secret,
plugin_settings,
lines_of_context=5,
force=False,
):
"""
Displays the secret, with surrounding lines of code for better context.
:type filename: str
:param filename: filename where secret resides in
:type secret: dict, PotentialSe... | python | {
"resource": ""
} |
q24698 | raw_secret_generator | train | def raw_secret_generator(plugin, secret_line, filetype):
"""Generates raw secrets by re-scanning the line, with the specified plugin
:type plugin: BasePlugin
:type secret_line: str
:type filetype: FileType
"""
for raw_secret in plugin.secret_generator(secret_line, filetype=filetype):
| python | {
"resource": ""
} |
q24699 | PluginOptions.consolidate_args | train | def consolidate_args(args):
"""There are many argument fields related to configuring plugins.
This function consolidates all of them, and saves the consolidated
information in args.plugins.
Note that we're deferring initialization of those plugins, because
plugins may have vario... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.