_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q226400
SoftDeletingScope.apply
train
def apply(self, builder, model): """ Apply the scope to a given query builder. :param builder: The query builder :type builder: orator.orm.builder.Builder :param model: The model :type model: orator.orm.Model """ builder.where_null(model.get_qualified_de...
python
{ "resource": "" }
q226401
SoftDeletingScope._on_delete
train
def _on_delete(self, builder): """ The delete replacement function. :param builder: The query builder :type builder: orator.orm.builder.Builder """ column = self._get_deleted_at_column(builder) return builder.update({column: builder.get_model().fresh_timestamp()...
python
{ "resource": "" }
q226402
SoftDeletingScope._get_deleted_at_column
train
def _get_deleted_at_column(self, builder): """ Get the "deleted at" column for the builder. :param builder: The query builder :type builder: orator.orm.builder.Builder :rtype: str """ if len(builder.get_query().joins) > 0: return builder.get_model()....
python
{ "resource": "" }
q226403
SoftDeletingScope._restore
train
def _restore(self, builder): """ The restore extension. :param builder: The query builder :type builder: orator.orm.builder.Builder """ builder.with_trashed() return builder.update({builder.get_model().get_deleted_at_column(): None})
python
{ "resource": "" }
q226404
SchemaBuilder.has_table
train
def has_table(self, table): """ Determine if the given table exists. :param table: The table :type table: str :rtype: bool """ sql = self._grammar.compile_table_exists() table = self._connection.get_table_prefix() + table return len(self._conne...
python
{ "resource": "" }
q226405
SchemaBuilder.has_column
train
def has_column(self, table, column): """ Determine if the given table has a given column. :param table: The table :type table: str :type column: str :rtype: bool """ column = column.lower() return column in list(map(lambda x: x.lower(), self.ge...
python
{ "resource": "" }
q226406
SchemaBuilder.table
train
def table(self, table): """ Modify a table on the schema. :param table: The table """ try: blueprint = self._create_blueprint(table) yield blueprint except Exception as e: raise try: self._build(blueprint) ...
python
{ "resource": "" }
q226407
SchemaBuilder.rename
train
def rename(self, from_, to): """ Rename a table on the schema. """ blueprint = self._create_blueprint(from_) blueprint.rename(to) self._build(blueprint)
python
{ "resource": "" }
q226408
MigrateMakeCommand._write_migration
train
def _write_migration(self, creator, name, table, create, path): """ Write the migration file to disk. """ file_ = os.path.basename(creator.create(name, path, table, create)) return file_
python
{ "resource": "" }
q226409
MySQLQueryGrammar.compile_delete
train
def compile_delete(self, query): """ Compile a delete statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled update :rtype: str """ table = self.wrap_table(query.from__) if isinstance(query.where...
python
{ "resource": "" }
q226410
Command._check_config
train
def _check_config(self): """ Check presence of default config files. :rtype: bool """ current_path = os.path.relpath(os.getcwd()) accepted_files = ["orator.yml", "orator.py"] for accepted_file in accepted_files: config_file = os.path.join(current_pat...
python
{ "resource": "" }
q226411
Command._handle_config
train
def _handle_config(self, config_file): """ Check and handle a config file. :param config_file: The path to the config file :type config_file: str :rtype: bool """ config = self._get_config(config_file) self.resolver = DatabaseManager( config...
python
{ "resource": "" }
q226412
DatabaseMigrationRepository.log
train
def log(self, file, batch): """ Log that a migration was run. :type file: str :type batch: int """ record = {"migration": file, "batch": batch} self.table().insert(**record)
python
{ "resource": "" }
q226413
DatabaseMigrationRepository.create_repository
train
def create_repository(self): """ Create the migration repository data store. """ schema = self.get_connection().get_schema_builder() with schema.create(self._table) as table: # The migrations table is responsible for keeping track of which of the # migrat...
python
{ "resource": "" }
q226414
DatabaseMigrationRepository.repository_exists
train
def repository_exists(self): """ Determine if the repository exists. :rtype: bool """ schema = self.get_connection().get_schema_builder() return schema.has_table(self._table)
python
{ "resource": "" }
q226415
MigrationCreator.create
train
def create(self, name, path, table=None, create=False): """ Create a new migration at the given path. :param name: The name of the migration :type name: str :param path: The path of the migrations :type path: str :param table: The table name :type table: ...
python
{ "resource": "" }
q226416
MigrationCreator._get_stub
train
def _get_stub(self, table, create): """ Get the migration stub template :param table: The table name :type table: str :param create: Whether it's a create migration or not :type create: bool :rtype: str """ if table is None: return B...
python
{ "resource": "" }
q226417
ForeignKeyConstraint.get_quoted_local_columns
train
def get_quoted_local_columns(self, platform): """ Returns the quoted representation of the referencing table column names the foreign key constraint is associated with. But only if they were defined with one or the referencing table column name is a keyword reserved by the platf...
python
{ "resource": "" }
q226418
ForeignKeyConstraint.get_quoted_foreign_columns
train
def get_quoted_foreign_columns(self, platform): """ Returns the quoted representation of the referenced table column names the foreign key constraint is associated with. But only if they were defined with one or the referenced table column name is a keyword reserved by the platf...
python
{ "resource": "" }
q226419
ForeignKeyConstraint._on_event
train
def _on_event(self, event): """ Returns the referential action for a given database operation on the referenced table the foreign key constraint is associated with. :param event: Name of the database operation/event to return the referential action for. :type event: str ...
python
{ "resource": "" }
q226420
Migrator.run
train
def run(self, path, pretend=False): """ Run the outstanding migrations for a given path. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool """ self._notes = [] files = self._get...
python
{ "resource": "" }
q226421
Migrator.run_migration_list
train
def run_migration_list(self, path, migrations, pretend=False): """ Run a list of migrations. :type migrations: list :type pretend: bool """ if not migrations: self._note("<info>Nothing to migrate</info>") return batch = self._repository...
python
{ "resource": "" }
q226422
Migrator.reset
train
def reset(self, path, pretend=False): """ Rolls all of the currently applied migrations back. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool :rtype: count """ self._notes = ...
python
{ "resource": "" }
q226423
Migrator._get_migration_files
train
def _get_migration_files(self, path): """ Get all of the migration files in a given path. :type path: str :rtype: list """ files = glob.glob(os.path.join(path, "[0-9]*_*.py")) if not files: return [] files = list(map(lambda f: os.path.basen...
python
{ "resource": "" }
q226424
PostgresQueryGrammar._compile_update_columns
train
def _compile_update_columns(self, values): """ Compile the columns for the update statement :param values: The columns :type values: dict :return: The compiled columns :rtype: str """ columns = [] for key, value in values.items(): co...
python
{ "resource": "" }
q226425
PostgresQueryGrammar._compile_update_from
train
def _compile_update_from(self, query): """ Compile the "from" clause for an update with a join. :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled sql :rtype: str """ if not query.joins: return "" f...
python
{ "resource": "" }
q226426
PostgresQueryGrammar._compile_update_wheres
train
def _compile_update_wheres(self, query): """ Compile the additional where clauses for updates with joins. :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled sql :rtype: str """ base_where = self._compile_wheres(query) ...
python
{ "resource": "" }
q226427
PostgresQueryGrammar._compile_update_join_wheres
train
def _compile_update_join_wheres(self, query): """ Compile the "join" clauses for an update. :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled sql :rtype: str """ join_wheres = [] for join in query.joins: ...
python
{ "resource": "" }
q226428
PostgresQueryGrammar.compile_insert_get_id
train
def compile_insert_get_id(self, query, values, sequence=None): """ Compile an insert and get ID statement into SQL. :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict :param sequence: The id se...
python
{ "resource": "" }
q226429
Qmarker.qmark
train
def qmark(cls, query): """ Convert a "qmark" query into "format" style. """ def sub_sequence(m): s = m.group(0) if s == "??": return "?" if s == "%": return "%%" else: return "%s" re...
python
{ "resource": "" }
q226430
Relation.touch
train
def touch(self): """ Touch all of the related models for the relationship. """ column = self.get_related().get_updated_at_column() self.raw_update({column: self.get_related().fresh_timestamp()})
python
{ "resource": "" }
q226431
Relation.raw_update
train
def raw_update(self, attributes=None): """ Run a raw update against the base query. :type attributes: dict :rtype: int """ if attributes is None: attributes = {} if self._query is not None: return self._query.update(attributes)
python
{ "resource": "" }
q226432
Relation.wrap
train
def wrap(self, value): """ Wrap the given value with the parent's query grammar. :rtype: str """ return self._parent.new_query().get_query().get_grammar().wrap(value)
python
{ "resource": "" }
q226433
load
train
def load(template): """ Try to guess the input format """ try: data = load_json(template) return data, "json" except ValueError as e: try: data = load_yaml(template) return data, "yaml" except Exception: raise e
python
{ "resource": "" }
q226434
dump_yaml
train
def dump_yaml(data, clean_up=False, long_form=False): """ Output some YAML """ return yaml.dump( data, Dumper=get_dumper(clean_up, long_form), default_flow_style=False, allow_unicode=True )
python
{ "resource": "" }
q226435
to_json
train
def to_json(template, clean_up=False): """ Assume the input is YAML and convert to JSON """ data = load_yaml(template) if clean_up: data = clean(data) return dump_json(data)
python
{ "resource": "" }
q226436
to_yaml
train
def to_yaml(template, clean_up=False, long_form=False): """ Assume the input is JSON and convert to YAML """ data = load_json(template) if clean_up: data = clean(data) return dump_yaml(data, clean_up, long_form)
python
{ "resource": "" }
q226437
flip
train
def flip(template, in_format=None, out_format=None, clean_up=False, no_flip=False, long_form=False): """ Figure out the input format and convert the data to the opposing output format """ # Do we need to figure out the input format? if not in_format: # Load the template as JSON? if ...
python
{ "resource": "" }
q226438
convert_join
train
def convert_join(value): """ Fix a Join ;) """ if not isinstance(value, list) or len(value) != 2: # Cowardly refuse return value sep, parts = value[0], value[1] if isinstance(parts, six.string_types): return parts if not isinstance(parts, list): # This loo...
python
{ "resource": "" }
q226439
map_representer
train
def map_representer(dumper, value): """ Deal with !Ref style function format and OrderedDict """ value = ODict(value.items()) if len(value.keys()) == 1: key = list(value.keys())[0] if key in CONVERTED_SUFFIXES: return fn_representer(dumper, key, value[key]) if...
python
{ "resource": "" }
q226440
multi_constructor
train
def multi_constructor(loader, tag_suffix, node): """ Deal with !Ref style function format """ if tag_suffix not in UNCONVERTED_SUFFIXES: tag_suffix = "{}{}".format(FN_PREFIX, tag_suffix) constructor = None if tag_suffix == "Fn::GetAtt": constructor = construct_getatt elif ...
python
{ "resource": "" }
q226441
construct_getatt
train
def construct_getatt(node): """ Reconstruct !GetAtt into a list """ if isinstance(node.value, six.text_type): return node.value.split(".", 1) elif isinstance(node.value, list): return [s.value for s in node.value] else: raise ValueError("Unexpected node type: {}".format(...
python
{ "resource": "" }
q226442
construct_mapping
train
def construct_mapping(self, node, deep=False): """ Use ODict for maps """ mapping = ODict() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mappin...
python
{ "resource": "" }
q226443
main
train
def main(ctx, **kwargs): """ AWS CloudFormation Template Flip is a tool that converts AWS CloudFormation templates between JSON and YAML formats, making use of the YAML format's short function syntax where possible. """ in_format = kwargs.pop('in_format') out_format = kwargs.pop('out_format'...
python
{ "resource": "" }
q226444
updateVersions
train
def updateVersions(region="us-east-1", table="credential-store"): ''' do a full-table scan of the credential-store, and update the version format of every credential if it is an integer ''' dynamodb = boto3.resource('dynamodb', region_name=region) secrets = dynamodb.Table(table) response = ...
python
{ "resource": "" }
q226445
paddedInt
train
def paddedInt(i): ''' return a string that contains `i`, left-padded with 0's up to PAD_LEN digits ''' i_str = str(i) pad = PAD_LEN - len(i_str) return (pad * "0") + i_str
python
{ "resource": "" }
q226446
getHighestVersion
train
def getHighestVersion(name, region=None, table="credential-store", **kwargs): ''' Return the highest version of `name` in the table ''' session = get_session(**kwargs) dynamodb = session.resource('dynamodb', region_name=region) secrets = dynamodb.Table(table) response...
python
{ "resource": "" }
q226447
clean_fail
train
def clean_fail(func): ''' A decorator to cleanly exit on a failed call to AWS. catch a `botocore.exceptions.ClientError` raised from an action. This sort of error is raised if you are targeting a region that isn't set up (see, `credstash setup`. ''' def func_wrapper(*args, **kwargs): ...
python
{ "resource": "" }
q226448
listSecrets
train
def listSecrets(region=None, table="credential-store", **kwargs): ''' do a full-table scan of the credential-store, and return the names and versions of every credential ''' session = get_session(**kwargs) dynamodb = session.resource('dynamodb', region_name=region) secrets = dynamodb.Table(...
python
{ "resource": "" }
q226449
putSecret
train
def putSecret(name, secret, version="", kms_key="alias/credstash", region=None, table="credential-store", context=None, digest=DEFAULT_DIGEST, comment="", **kwargs): ''' put a secret called `name` into the secret-store, protected by the key kms_key ''' if not context: ...
python
{ "resource": "" }
q226450
getAllSecrets
train
def getAllSecrets(version="", region=None, table="credential-store", context=None, credential=None, session=None, **kwargs): ''' fetch and decrypt all secrets ''' if session is None: session = get_session(**kwargs) dynamodb = session.resource('dynamodb', region_name=region)...
python
{ "resource": "" }
q226451
getSecret
train
def getSecret(name, version="", region=None, table="credential-store", context=None, dynamodb=None, kms=None, **kwargs): ''' fetch and decrypt the secret called `name` ''' if not context: context = {} # Can we cache if dynamodb is None or kms is None: ...
python
{ "resource": "" }
q226452
createDdbTable
train
def createDdbTable(region=None, table="credential-store", **kwargs): ''' create the secret store table in DDB in the specified region ''' session = get_session(**kwargs) dynamodb = session.resource("dynamodb", region_name=region) if table in (t.name for t in dynamodb.tables.all()): print...
python
{ "resource": "" }
q226453
seal_aes_ctr_legacy
train
def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST): """ Encrypts `secret` using the key service. You can decrypt with the companion method `open_aes_ctr_legacy`. """ # generate a a 64 byte key. # Half will be for data encryption, the other half for HMAC key, encoded_k...
python
{ "resource": "" }
q226454
RabbitMQHealthCheck.check_status
train
def check_status(self): """Check RabbitMQ service by opening and closing a broker channel.""" logger.debug("Checking for a broker_url on django settings...") broker_url = getattr(settings, "BROKER_URL", None) logger.debug("Got %s as the broker_url. Connecting to rabbit...", broker_url)...
python
{ "resource": "" }
q226455
MediaType.from_string
train
def from_string(cls, value): """Return single instance parsed from given accept header string.""" match = cls.pattern.search(value) if match is None: raise ValueError('"%s" is not a valid media type' % value) try: return cls(match.group('mime_type'), float(match.g...
python
{ "resource": "" }
q226456
MediaType.parse_header
train
def parse_header(cls, value='*/*'): """Parse HTTP accept header and return instances sorted by weight.""" yield from sorted(( cls.from_string(token.strip()) for token in value.split(',') if token.strip() ), reverse=True)
python
{ "resource": "" }
q226457
convert_to_timezone_naive
train
def convert_to_timezone_naive(time_to_freeze): """ Converts a potentially timezone-aware datetime to be a naive UTC datetime """ if time_to_freeze.tzinfo: time_to_freeze -= time_to_freeze.utcoffset() time_to_freeze = time_to_freeze.replace(tzinfo=None) return time_to_freeze
python
{ "resource": "" }
q226458
FrozenDateTimeFactory.move_to
train
def move_to(self, target_datetime): """Moves frozen date to the given ``target_datetime``""" target_datetime = _parse_time_to_freeze(target_datetime) delta = target_datetime - self.time_to_freeze self.tick(delta=delta)
python
{ "resource": "" }
q226459
JsonXslPlugin.process_module
train
def process_module(self, yam): """Process data nodes, RPCs and notifications in a single module.""" for ann in yam.search(("ietf-yang-metadata", "annotation")): self.process_annotation(ann) for ch in yam.i_children[:]: if ch.keyword == "rpc": self.process_...
python
{ "resource": "" }
q226460
JsonXslPlugin.process_annotation
train
def process_annotation(self, ann): """Process metadata annotation.""" tmpl = self.xsl_template("@" + self.qname(ann)) ET.SubElement(tmpl, "param", name="level", select="0") ct = self.xsl_calltemplate("leaf", tmpl) ET.SubElement(ct, "with-param", name="level", select="$level") ...
python
{ "resource": "" }
q226461
JsonXslPlugin.process_rpc
train
def process_rpc(self, rpc): """Process input and output parts of `rpc`.""" p = "/nc:rpc/" + self.qname(rpc) tmpl = self.xsl_template(p) inp = rpc.search_one("input") if inp is not None: ct = self.xsl_calltemplate("rpc-input", tmpl) self.xsl_withparam("nsid...
python
{ "resource": "" }
q226462
JsonXslPlugin.process_notification
train
def process_notification(self, ntf): """Process event notification `ntf`.""" p = "/en:notification/" + self.qname(ntf) tmpl = self.xsl_template(p) ct = self.xsl_calltemplate("container", tmpl) self.xsl_withparam("level", "1", ct) if ntf.arg == "eventTime": # lo...
python
{ "resource": "" }
q226463
JsonXslPlugin.process_children
train
def process_children(self, node, path, level, parent=None): """Process all children of `node`. `path` is the Xpath of `node` which is used in the 'select' attribute of XSLT templates. """ data_parent = parent if parent else node chs = node.i_children for ch in ch...
python
{ "resource": "" }
q226464
JsonXslPlugin.type_param
train
def type_param(self, node, ct): """Resolve the type of a leaf or leaf-list node for JSON. """ types = self.get_types(node) ftyp = types[0] if len(types) == 1: if ftyp in type_class: jtyp = type_class[ftyp] else: jtyp = "othe...
python
{ "resource": "" }
q226465
JsonXslPlugin.xsl_text
train
def xsl_text(self, text, parent): """Construct an XSLT 'text' element containing `text`. `parent` is this element's parent. """ res = ET.SubElement(parent, "text") res.text = text return res
python
{ "resource": "" }
q226466
JsonXslPlugin.xsl_withparam
train
def xsl_withparam(self, name, value, parent): """Construct an XSLT 'with-param' element. `parent` is this element's parent. `name` is the parameter name. `value` is the parameter value. """ res = ET.SubElement(parent, "with-param", name=name) res.text = value ...
python
{ "resource": "" }
q226467
SchemaNode.element
train
def element(cls, name, parent=None, interleave=None, occur=0): """Create an element node.""" node = cls("element", parent, interleave=interleave) node.attr["name"] = name node.occur = occur return node
python
{ "resource": "" }
q226468
SchemaNode.leaf_list
train
def leaf_list(cls, name, parent=None, interleave=None): """Create _list_ node for a leaf-list.""" node = cls("_list_", parent, interleave=interleave) node.attr["name"] = name node.keys = None node.minEl = "0" node.maxEl = None node.occur = 3 return node
python
{ "resource": "" }
q226469
SchemaNode.list
train
def list(cls, name, parent=None, interleave=None): """Create _list_ node for a list.""" node = cls.leaf_list(name, parent, interleave=interleave) node.keys = [] node.keymap = {} return node
python
{ "resource": "" }
q226470
SchemaNode.choice
train
def choice(cls, parent=None, occur=0): """Create choice node.""" node = cls("choice", parent) node.occur = occur node.default_case = None return node
python
{ "resource": "" }
q226471
SchemaNode.define
train
def define(cls, name, parent=None, interleave=False): """Create define node.""" node = cls("define", parent, interleave=interleave) node.occur = 0 node.attr["name"] = name return node
python
{ "resource": "" }
q226472
SchemaNode.adjust_interleave
train
def adjust_interleave(self, interleave): """Inherit interleave status from parent if undefined.""" if interleave == None and self.parent: self.interleave = self.parent.interleave else: self.interleave = interleave
python
{ "resource": "" }
q226473
SchemaNode.subnode
train
def subnode(self, node): """Make `node` receiver's child.""" self.children.append(node) node.parent = self node.adjust_interleave(node.interleave)
python
{ "resource": "" }
q226474
SchemaNode.annot
train
def annot(self, node): """Add `node` as an annotation of the receiver.""" self.annots.append(node) node.parent = self
python
{ "resource": "" }
q226475
SchemaNode.start_tag
train
def start_tag(self, alt=None, empty=False): """Return XML start tag for the receiver.""" if alt: name = alt else: name = self.name result = "<" + name for it in self.attr: result += ' %s="%s"' % (it, escape(self.attr[it], {'"':"&quot;", '%': "%...
python
{ "resource": "" }
q226476
SchemaNode.end_tag
train
def end_tag(self, alt=None): """Return XML end tag for the receiver.""" if alt: name = alt else: name = self.name return "</" + name + ">"
python
{ "resource": "" }
q226477
SchemaNode.serialize
train
def serialize(self, occur=None): """Return RELAX NG representation of the receiver and subtree. """ fmt = self.ser_format.get(self.name, SchemaNode._default_format) return fmt(self, occur) % (escape(self.text) + self.serialize_children())
python
{ "resource": "" }
q226478
SchemaNode._default_format
train
def _default_format(self, occur): """Return the default serialization format.""" if self.text or self.children: return self.start_tag() + "%s" + self.end_tag() return self.start_tag(empty=True)
python
{ "resource": "" }
q226479
SchemaNode._define_format
train
def _define_format(self, occur): """Return the serialization format for a define node.""" if hasattr(self, "default"): self.attr["nma:default"] = self.default middle = self._chorder() if self.rng_children() else "<empty/>%s" return (self.start_tag() + self.serialize_annots()...
python
{ "resource": "" }
q226480
SchemaNode._element_format
train
def _element_format(self, occur): """Return the serialization format for an element node.""" if occur: occ = occur else: occ = self.occur if occ == 1: if hasattr(self, "default"): self.attr["nma:default"] = self.default els...
python
{ "resource": "" }
q226481
SchemaNode._list_format
train
def _list_format(self, occur): """Return the serialization format for a _list_ node.""" if self.keys: self.attr["nma:key"] = " ".join(self.keys) keys = ''.join([self.keymap[k].serialize(occur=2) for k in self.keys]) else: keys = ""...
python
{ "resource": "" }
q226482
SchemaNode._choice_format
train
def _choice_format(self, occur): """Return the serialization format for a choice node.""" middle = "%s" if self.rng_children() else "<empty/>%s" fmt = self.start_tag() + middle + self.end_tag() if self.occur != 2: return "<optional>" + fmt + "</optional>" else: ...
python
{ "resource": "" }
q226483
SchemaNode._case_format
train
def _case_format(self, occur): """Return the serialization format for a case node.""" if self.occur == 1: self.attr["nma:implicit"] = "true" ccnt = len(self.rng_children()) if ccnt == 0: return "<empty/>%s" if ccnt == 1 or not self.interleave: return self...
python
{ "resource": "" }
q226484
JtoXPlugin.process_children
train
def process_children(self, node, parent, pmod): """Process all children of `node`, except "rpc" and "notification". """ for ch in node.i_children: if ch.keyword in ["rpc", "notification"]: continue if ch.keyword in ["choice", "case"]: self.process_children...
python
{ "resource": "" }
q226485
JtoXPlugin.base_type
train
def base_type(self, type): """Return the base type of `type`.""" while 1: if type.arg == "leafref": node = type.i_type_spec.i_target_node elif type.i_typedef is None: break else: node = type.i_typedef type = ...
python
{ "resource": "" }
q226486
YangTokenizer.skip
train
def skip(self): """Skip whitespace and count position""" buflen = len(self.buf) while True: self.buf = self.buf.lstrip() if self.buf == '': self.readline() buflen = len(self.buf) else: self.offset += (buflen - l...
python
{ "resource": "" }
q226487
YangParser.parse
train
def parse(self, ctx, ref, text): """Parse the string `text` containing a YANG statement. Return a Statement on success or None on failure """ self.ctx = ctx self.pos = error.Position(ref) self.top = None try: self.tokenizer = YangTokenizer(text, self...
python
{ "resource": "" }
q226488
add_validation_phase
train
def add_validation_phase(phase, before=None, after=None): """Add a validation phase to the framework. Can be used by plugins to do special validation of extensions.""" idx = 0 for x in _validation_phases: if x == before: _validation_phases.insert(idx, phase) return ...
python
{ "resource": "" }
q226489
add_validation_fun
train
def add_validation_fun(phase, keywords, f): """Add a validation function to some phase in the framework. Function `f` is called for each valid occurance of each keyword in `keywords`. Can be used by plugins to do special validation of extensions.""" for keyword in keywords: if (phase, keywo...
python
{ "resource": "" }
q226490
v_init_extension
train
def v_init_extension(ctx, stmt): """find the modulename of the prefix, and set `stmt.keyword`""" (prefix, identifier) = stmt.raw_keyword (modname, revision) = \ prefix_to_modulename_and_revision(stmt.i_module, prefix, stmt.pos, ctx.errors) stmt.keyword =...
python
{ "resource": "" }
q226491
v_grammar_unique_defs
train
def v_grammar_unique_defs(ctx, stmt): """Verify that all typedefs and groupings are unique Called for every statement. Stores all typedefs in stmt.i_typedef, groupings in stmt.i_grouping """ defs = [('typedef', 'TYPE_ALREADY_DEFINED', stmt.i_typedefs), ('grouping', 'GROUPING_ALREADY_DEFI...
python
{ "resource": "" }
q226492
v_type_extension
train
def v_type_extension(ctx, stmt): """verify that the extension matches the extension definition""" (modulename, identifier) = stmt.keyword revision = stmt.i_extension_revision module = modulename_to_module(stmt.i_module, modulename, revision) if module is None: return if identifier not in...
python
{ "resource": "" }
q226493
v_type_if_feature
train
def v_type_if_feature(ctx, stmt, no_error_report=False): """verify that the referenced feature exists.""" stmt.i_feature = None # Verify the argument type expr = syntax.parse_if_feature_expr(stmt.arg) if stmt.i_module.i_version == '1': # version 1 allows only a single value as if-feature ...
python
{ "resource": "" }
q226494
v_type_base
train
def v_type_base(ctx, stmt, no_error_report=False): """verify that the referenced identity exists.""" # Find the identity name = stmt.arg stmt.i_identity = None if name.find(":") == -1: prefix = None else: [prefix, name] = name.split(':', 1) if prefix is None or stmt.i_module....
python
{ "resource": "" }
q226495
v_unique_name_defintions
train
def v_unique_name_defintions(ctx, stmt): """Make sure that all top-level definitions in a module are unique""" defs = [('typedef', 'TYPE_ALREADY_DEFINED', stmt.i_typedefs), ('grouping', 'GROUPING_ALREADY_DEFINED', stmt.i_groupings)] def f(s): for (keyword, errcode, dict) in defs: ...
python
{ "resource": "" }
q226496
v_unique_name_children
train
def v_unique_name_children(ctx, stmt): """Make sure that each child of stmt has a unique name""" def sort_pos(p1, p2): if p1.line < p2.line: return (p1,p2) else: return (p2,p1) dict = {} chs = stmt.i_children def check(c): key = (c.i_module.i_module...
python
{ "resource": "" }
q226497
v_unique_name_leaf_list
train
def v_unique_name_leaf_list(ctx, stmt): """Make sure config true leaf-lists do nothave duplicate defaults""" if not stmt.i_config: return seen = [] for defval in stmt.i_default: if defval in seen: err_add(ctx.errors, stmt.pos, 'DUPLICATE_DEFAULT', (defval)) else: ...
python
{ "resource": "" }
q226498
v_reference_choice
train
def v_reference_choice(ctx, stmt): """Make sure that the default case exists""" d = stmt.search_one('default') if d is not None: m = stmt.search_one('mandatory') if m is not None and m.arg == 'true': err_add(ctx.errors, stmt.pos, 'DEFAULT_AND_MANDATORY', ()) ptr = attrsea...
python
{ "resource": "" }
q226499
v_reference_leaf_leafref
train
def v_reference_leaf_leafref(ctx, stmt): """Verify that all leafrefs in a leaf or leaf-list have correct path""" if (hasattr(stmt, 'i_leafref') and stmt.i_leafref is not None and stmt.i_leafref_expanded is False): path_type_spec = stmt.i_leafref not_req_inst = not(path_type_spec...
python
{ "resource": "" }