repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
catherinedevlin/ddl-generator
ddlgenerator/typehelpers.py
best_coercable
def best_coercable(data): """ Given an iterable of scalar data, returns the datum representing the most specific data type the list overall can be coerced into, preferring datetimes, then bools, then integers, then decimals, then floats, then strings. >>> best_coercable((6, '2', 9)) 6 >>> b...
python
def best_coercable(data): """ Given an iterable of scalar data, returns the datum representing the most specific data type the list overall can be coerced into, preferring datetimes, then bools, then integers, then decimals, then floats, then strings. >>> best_coercable((6, '2', 9)) 6 >>> b...
[ "def", "best_coercable", "(", "data", ")", ":", "preference", "=", "(", "datetime", ".", "datetime", ",", "bool", ",", "int", ",", "Decimal", ",", "float", ",", "str", ")", "worst_pref", "=", "0", "worst", "=", "''", "for", "datum", "in", "data", ":"...
Given an iterable of scalar data, returns the datum representing the most specific data type the list overall can be coerced into, preferring datetimes, then bools, then integers, then decimals, then floats, then strings. >>> best_coercable((6, '2', 9)) 6 >>> best_coercable((Decimal('6.1'), 2, 9)) ...
[ "Given", "an", "iterable", "of", "scalar", "data", "returns", "the", "datum", "representing", "the", "most", "specific", "data", "type", "the", "list", "overall", "can", "be", "coerced", "into", "preferring", "datetimes", "then", "bools", "then", "integers", "...
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L215-L247
catherinedevlin/ddl-generator
ddlgenerator/typehelpers.py
sqla_datatype_for
def sqla_datatype_for(datum): """ Given a scalar Python value, picks an appropriate SQLAlchemy data type. >>> sqla_datatype_for(7.2) DECIMAL(precision=2, scale=1) >>> sqla_datatype_for("Jan 17 2012") <class 'sqlalchemy.sql.sqltypes.DATETIME'> >>> sqla_datatype_for("something else") Unic...
python
def sqla_datatype_for(datum): """ Given a scalar Python value, picks an appropriate SQLAlchemy data type. >>> sqla_datatype_for(7.2) DECIMAL(precision=2, scale=1) >>> sqla_datatype_for("Jan 17 2012") <class 'sqlalchemy.sql.sqltypes.DATETIME'> >>> sqla_datatype_for("something else") Unic...
[ "def", "sqla_datatype_for", "(", "datum", ")", ":", "try", ":", "if", "len", "(", "_complex_enough_to_be_date", ".", "findall", "(", "datum", ")", ")", ">", "1", ":", "dateutil", ".", "parser", ".", "parse", "(", "datum", ")", "return", "sa", ".", "DAT...
Given a scalar Python value, picks an appropriate SQLAlchemy data type. >>> sqla_datatype_for(7.2) DECIMAL(precision=2, scale=1) >>> sqla_datatype_for("Jan 17 2012") <class 'sqlalchemy.sql.sqltypes.DATETIME'> >>> sqla_datatype_for("something else") Unicode(length=14)
[ "Given", "a", "scalar", "Python", "value", "picks", "an", "appropriate", "SQLAlchemy", "data", "type", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L249-L270
catherinedevlin/ddl-generator
ddlgenerator/console.py
generate_one
def generate_one(tbl, args, table_name=None, file=None): """ Prints code (SQL, SQLAlchemy, etc.) to define a table. """ table = Table(tbl, table_name=table_name, varying_length_text=args.text, uniques=args.uniques, pk_name = args.key, force_pk=args.force_key, reorder=args.reorder, data...
python
def generate_one(tbl, args, table_name=None, file=None): """ Prints code (SQL, SQLAlchemy, etc.) to define a table. """ table = Table(tbl, table_name=table_name, varying_length_text=args.text, uniques=args.uniques, pk_name = args.key, force_pk=args.force_key, reorder=args.reorder, data...
[ "def", "generate_one", "(", "tbl", ",", "args", ",", "table_name", "=", "None", ",", "file", "=", "None", ")", ":", "table", "=", "Table", "(", "tbl", ",", "table_name", "=", "table_name", ",", "varying_length_text", "=", "args", ".", "text", ",", "uni...
Prints code (SQL, SQLAlchemy, etc.) to define a table.
[ "Prints", "code", "(", "SQL", "SQLAlchemy", "etc", ".", ")", "to", "define", "a", "table", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/console.py#L51-L70
catherinedevlin/ddl-generator
ddlgenerator/console.py
generate
def generate(args=None, namespace=None, file=None): """ Genereate DDL from data sources named. :args: String or list of strings to be parsed for arguments :namespace: Namespace to extract arguments from :file: Write to this open file object (default stdout) """ if hasattr(args, 's...
python
def generate(args=None, namespace=None, file=None): """ Genereate DDL from data sources named. :args: String or list of strings to be parsed for arguments :namespace: Namespace to extract arguments from :file: Write to this open file object (default stdout) """ if hasattr(args, 's...
[ "def", "generate", "(", "args", "=", "None", ",", "namespace", "=", "None", ",", "file", "=", "None", ")", ":", "if", "hasattr", "(", "args", ",", "'split'", ")", ":", "args", "=", "args", ".", "split", "(", ")", "args", "=", "parser", ".", "pars...
Genereate DDL from data sources named. :args: String or list of strings to be parsed for arguments :namespace: Namespace to extract arguments from :file: Write to this open file object (default stdout)
[ "Genereate", "DDL", "from", "data", "sources", "named", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/console.py#L72-L112
catherinedevlin/ddl-generator
ddlgenerator/ddlgenerator.py
emit_db_sequence_updates
def emit_db_sequence_updates(engine): """Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.""" if engine and engine.name == 'postgresql': # not implemented for othe...
python
def emit_db_sequence_updates(engine): """Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.""" if engine and engine.name == 'postgresql': # not implemented for othe...
[ "def", "emit_db_sequence_updates", "(", "engine", ")", ":", "if", "engine", "and", "engine", ".", "name", "==", "'postgresql'", ":", "# not implemented for other RDBMS; necessity unknown", "conn", "=", "engine", ".", "connect", "(", ")", "qry", "=", "\"\"\"SELECT 'S...
Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.
[ "Set", "database", "sequence", "objects", "to", "match", "the", "source", "db" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/ddlgenerator.py#L557-L575
catherinedevlin/ddl-generator
ddlgenerator/ddlgenerator.py
Table.ddl
def ddl(self, dialect=None, creates=True, drops=True): """ Returns SQL to define the table. """ dialect = self._dialect(dialect) creator = CreateTable(self.table).compile(mock_engines[dialect]) creator = "\n".join(l for l in str(creator).splitlines() if l.strip()) # remov...
python
def ddl(self, dialect=None, creates=True, drops=True): """ Returns SQL to define the table. """ dialect = self._dialect(dialect) creator = CreateTable(self.table).compile(mock_engines[dialect]) creator = "\n".join(l for l in str(creator).splitlines() if l.strip()) # remov...
[ "def", "ddl", "(", "self", ",", "dialect", "=", "None", ",", "creates", "=", "True", ",", "drops", "=", "True", ")", ":", "dialect", "=", "self", ".", "_dialect", "(", "dialect", ")", "creator", "=", "CreateTable", "(", "self", ".", "table", ")", "...
Returns SQL to define the table.
[ "Returns", "SQL", "to", "define", "the", "table", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/ddlgenerator.py#L263-L281
catherinedevlin/ddl-generator
ddlgenerator/ddlgenerator.py
Table.sqlalchemy
def sqlalchemy(self, is_top=True): """Dumps Python code to set up the table's SQLAlchemy model""" table_def = self.table_backref_remover.sub('', self.table.__repr__()) # inject UNIQUE constraints into table definition constraint_defs = [] for constraint in self.table.constraint...
python
def sqlalchemy(self, is_top=True): """Dumps Python code to set up the table's SQLAlchemy model""" table_def = self.table_backref_remover.sub('', self.table.__repr__()) # inject UNIQUE constraints into table definition constraint_defs = [] for constraint in self.table.constraint...
[ "def", "sqlalchemy", "(", "self", ",", "is_top", "=", "True", ")", ":", "table_def", "=", "self", ".", "table_backref_remover", ".", "sub", "(", "''", ",", "self", ".", "table", ".", "__repr__", "(", ")", ")", "# inject UNIQUE constraints into table definition...
Dumps Python code to set up the table's SQLAlchemy model
[ "Dumps", "Python", "code", "to", "set", "up", "the", "table", "s", "SQLAlchemy", "model" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/ddlgenerator.py#L292-L320
catherinedevlin/ddl-generator
ddlgenerator/ddlgenerator.py
Table._prep_datum
def _prep_datum(self, datum, dialect, col, needs_conversion): """Puts a value in proper format for a SQL string""" if datum is None or (needs_conversion and not str(datum).strip()): return 'NULL' pytype = self.columns[col]['pytype'] if needs_conversion: if pytype...
python
def _prep_datum(self, datum, dialect, col, needs_conversion): """Puts a value in proper format for a SQL string""" if datum is None or (needs_conversion and not str(datum).strip()): return 'NULL' pytype = self.columns[col]['pytype'] if needs_conversion: if pytype...
[ "def", "_prep_datum", "(", "self", ",", "datum", ",", "dialect", ",", "col", ",", "needs_conversion", ")", ":", "if", "datum", "is", "None", "or", "(", "needs_conversion", "and", "not", "str", "(", "datum", ")", ".", "strip", "(", ")", ")", ":", "ret...
Puts a value in proper format for a SQL string
[ "Puts", "a", "value", "in", "proper", "format", "for", "a", "SQL", "string" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/ddlgenerator.py#L360-L385
catherinedevlin/ddl-generator
ddlgenerator/ddlgenerator.py
Table.emit_db_sequence_updates
def emit_db_sequence_updates(self): """Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.""" if self.source.db_engine and self.source.db_engine.name != 'pos...
python
def emit_db_sequence_updates(self): """Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.""" if self.source.db_engine and self.source.db_engine.name != 'pos...
[ "def", "emit_db_sequence_updates", "(", "self", ")", ":", "if", "self", ".", "source", ".", "db_engine", "and", "self", ".", "source", ".", "db_engine", ".", "name", "!=", "'postgresql'", ":", "# not implemented for other RDBMS; necessity unknown", "conn", "=", "s...
Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.
[ "Set", "database", "sequence", "objects", "to", "match", "the", "source", "db" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/ddlgenerator.py#L389-L407
catherinedevlin/ddl-generator
ddlgenerator/ddlgenerator.py
Table.sql
def sql(self, dialect=None, inserts=False, creates=True, drops=True, metadata_source=None): """ Combined results of ``.ddl(dialect)`` and, if ``inserts==True``, ``.inserts(dialect)``. """ result = [self.ddl(dialect, creates=creates, drops=drops)] if inserts: ...
python
def sql(self, dialect=None, inserts=False, creates=True, drops=True, metadata_source=None): """ Combined results of ``.ddl(dialect)`` and, if ``inserts==True``, ``.inserts(dialect)``. """ result = [self.ddl(dialect, creates=creates, drops=drops)] if inserts: ...
[ "def", "sql", "(", "self", ",", "dialect", "=", "None", ",", "inserts", "=", "False", ",", "creates", "=", "True", ",", "drops", "=", "True", ",", "metadata_source", "=", "None", ")", ":", "result", "=", "[", "self", ".", "ddl", "(", "dialect", ","...
Combined results of ``.ddl(dialect)`` and, if ``inserts==True``, ``.inserts(dialect)``.
[ "Combined", "results", "of", ".", "ddl", "(", "dialect", ")", "and", "if", "inserts", "==", "True", ".", "inserts", "(", "dialect", ")", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/ddlgenerator.py#L436-L446
catherinedevlin/ddl-generator
ddlgenerator/reshape.py
clean_key_name
def clean_key_name(key): """ Makes ``key`` a valid and appropriate SQL column name: 1. Replaces illegal characters in column names with ``_`` 2. Prevents name from beginning with a digit (prepends ``_``) 3. Lowercases name. If you want case-sensitive table or column names, you are a bad pers...
python
def clean_key_name(key): """ Makes ``key`` a valid and appropriate SQL column name: 1. Replaces illegal characters in column names with ``_`` 2. Prevents name from beginning with a digit (prepends ``_``) 3. Lowercases name. If you want case-sensitive table or column names, you are a bad pers...
[ "def", "clean_key_name", "(", "key", ")", ":", "result", "=", "_illegal_in_column_name", ".", "sub", "(", "\"_\"", ",", "key", ".", "strip", "(", ")", ")", "if", "result", "[", "0", "]", ".", "isdigit", "(", ")", ":", "result", "=", "'_%s'", "%", "...
Makes ``key`` a valid and appropriate SQL column name: 1. Replaces illegal characters in column names with ``_`` 2. Prevents name from beginning with a digit (prepends ``_``) 3. Lowercases name. If you want case-sensitive table or column names, you are a bad person and you should feel bad.
[ "Makes", "key", "a", "valid", "and", "appropriate", "SQL", "column", "name", ":" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/reshape.py#L18-L34
catherinedevlin/ddl-generator
ddlgenerator/reshape.py
walk_and_clean
def walk_and_clean(data): """ Recursively walks list of dicts (which may themselves embed lists and dicts), transforming namedtuples to OrderedDicts and using ``clean_key_name(k)`` to make keys into SQL-safe column names >>> data = [{'a': 1}, [{'B': 2}, {'B': 3}], {'F': {'G': 4}}] >>> pprint(wa...
python
def walk_and_clean(data): """ Recursively walks list of dicts (which may themselves embed lists and dicts), transforming namedtuples to OrderedDicts and using ``clean_key_name(k)`` to make keys into SQL-safe column names >>> data = [{'a': 1}, [{'B': 2}, {'B': 3}], {'F': {'G': 4}}] >>> pprint(wa...
[ "def", "walk_and_clean", "(", "data", ")", ":", "# transform namedtuples to OrderedDicts", "if", "hasattr", "(", "data", ",", "'_fields'", ")", ":", "data", "=", "OrderedDict", "(", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "zip", ...
Recursively walks list of dicts (which may themselves embed lists and dicts), transforming namedtuples to OrderedDicts and using ``clean_key_name(k)`` to make keys into SQL-safe column names >>> data = [{'a': 1}, [{'B': 2}, {'B': 3}], {'F': {'G': 4}}] >>> pprint(walk_and_clean(data)) [OrderedDi...
[ "Recursively", "walks", "list", "of", "dicts", "(", "which", "may", "themselves", "embed", "lists", "and", "dicts", ")", "transforming", "namedtuples", "to", "OrderedDicts", "and", "using", "clean_key_name", "(", "k", ")", "to", "make", "keys", "into", "SQL", ...
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/reshape.py#L36-L67
catherinedevlin/ddl-generator
ddlgenerator/reshape.py
_id_fieldname
def _id_fieldname(fieldnames, table_name = ''): """ Finds the field name from a dict likeliest to be its unique ID >>> _id_fieldname({'bar': True, 'id': 1}, 'foo') 'id' >>> _id_fieldname({'bar': True, 'foo_id': 1, 'goo_id': 2}, 'foo') 'foo_id' >>> _id_fieldname({'bar': True, 'baz': 1, 'baz_...
python
def _id_fieldname(fieldnames, table_name = ''): """ Finds the field name from a dict likeliest to be its unique ID >>> _id_fieldname({'bar': True, 'id': 1}, 'foo') 'id' >>> _id_fieldname({'bar': True, 'foo_id': 1, 'goo_id': 2}, 'foo') 'foo_id' >>> _id_fieldname({'bar': True, 'baz': 1, 'baz_...
[ "def", "_id_fieldname", "(", "fieldnames", ",", "table_name", "=", "''", ")", ":", "templates", "=", "[", "'%s_%%s'", "%", "table_name", ",", "'%s'", ",", "'_%s'", "]", "for", "stub", "in", "[", "'id'", ",", "'num'", ",", "'no'", ",", "'number'", "]", ...
Finds the field name from a dict likeliest to be its unique ID >>> _id_fieldname({'bar': True, 'id': 1}, 'foo') 'id' >>> _id_fieldname({'bar': True, 'foo_id': 1, 'goo_id': 2}, 'foo') 'foo_id' >>> _id_fieldname({'bar': True, 'baz': 1, 'baz_id': 3}, 'foo')
[ "Finds", "the", "field", "name", "from", "a", "dict", "likeliest", "to", "be", "its", "unique", "ID" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/reshape.py#L69-L83
catherinedevlin/ddl-generator
ddlgenerator/reshape.py
unnest_child_dict
def unnest_child_dict(parent, key, parent_name=''): """ If ``parent`` dictionary has a ``key`` whose ``val`` is a dict, unnest ``val``'s fields into ``parent`` and remove ``key``. >>> parent = {'province': 'Québec', 'capital': {'name': 'Québec City', 'pop': 491140}} >>> unnest_child_dict(parent, 'c...
python
def unnest_child_dict(parent, key, parent_name=''): """ If ``parent`` dictionary has a ``key`` whose ``val`` is a dict, unnest ``val``'s fields into ``parent`` and remove ``key``. >>> parent = {'province': 'Québec', 'capital': {'name': 'Québec City', 'pop': 491140}} >>> unnest_child_dict(parent, 'c...
[ "def", "unnest_child_dict", "(", "parent", ",", "key", ",", "parent_name", "=", "''", ")", ":", "val", "=", "parent", "[", "key", "]", "name", "=", "\"%s['%s']\"", "%", "(", "parent_name", ",", "key", ")", "logging", ".", "debug", "(", "\"Unnesting dict ...
If ``parent`` dictionary has a ``key`` whose ``val`` is a dict, unnest ``val``'s fields into ``parent`` and remove ``key``. >>> parent = {'province': 'Québec', 'capital': {'name': 'Québec City', 'pop': 491140}} >>> unnest_child_dict(parent, 'capital', 'provinces') >>> pprint(parent) {'capital_name'...
[ "If", "parent", "dictionary", "has", "a", "key", "whose", "val", "is", "a", "dict", "unnest", "val", "s", "fields", "into", "parent", "and", "remove", "key", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/reshape.py#L113-L165
catherinedevlin/ddl-generator
ddlgenerator/reshape.py
unnest_children
def unnest_children(data, parent_name='', pk_name=None, force_pk=False): """ For each ``key`` in each row of ``data`` (which must be a list of dicts), unnest any dict values into ``parent``, and remove list values into separate lists. Return (``data``, ``pk_name``, ``children``, ``child_fk_names``) whe...
python
def unnest_children(data, parent_name='', pk_name=None, force_pk=False): """ For each ``key`` in each row of ``data`` (which must be a list of dicts), unnest any dict values into ``parent``, and remove list values into separate lists. Return (``data``, ``pk_name``, ``children``, ``child_fk_names``) whe...
[ "def", "unnest_children", "(", "data", ",", "parent_name", "=", "''", ",", "pk_name", "=", "None", ",", "force_pk", "=", "False", ")", ":", "possible_fk_names", "=", "[", "'%s_id'", "%", "parent_name", ",", "'_%s_id'", "%", "parent_name", ",", "'parent_id'",...
For each ``key`` in each row of ``data`` (which must be a list of dicts), unnest any dict values into ``parent``, and remove list values into separate lists. Return (``data``, ``pk_name``, ``children``, ``child_fk_names``) where ``data`` the transformed input list ``pk_name`` field name of...
[ "For", "each", "key", "in", "each", "row", "of", "data", "(", "which", "must", "be", "a", "list", "of", "dicts", ")", "unnest", "any", "dict", "values", "into", "parent", "and", "remove", "list", "values", "into", "separate", "lists", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/reshape.py#L263-L318
catherinedevlin/ddl-generator
ddlgenerator/reshape.py
ParentTable.suitability_as_key
def suitability_as_key(self, key_name): """ Returns: (result, key_type) ``result`` is True, False, or 'absent' or 'partial' (both still usable) ``key_type`` is ``int`` for integer keys or ``str`` for hash keys """ pk_values = all_values_for(self, key_name) if not...
python
def suitability_as_key(self, key_name): """ Returns: (result, key_type) ``result`` is True, False, or 'absent' or 'partial' (both still usable) ``key_type`` is ``int`` for integer keys or ``str`` for hash keys """ pk_values = all_values_for(self, key_name) if not...
[ "def", "suitability_as_key", "(", "self", ",", "key_name", ")", ":", "pk_values", "=", "all_values_for", "(", "self", ",", "key_name", ")", "if", "not", "pk_values", ":", "return", "(", "'absent'", ",", "int", ")", "# could still use it", "key_type", "=", "t...
Returns: (result, key_type) ``result`` is True, False, or 'absent' or 'partial' (both still usable) ``key_type`` is ``int`` for integer keys or ``str`` for hash keys
[ "Returns", ":", "(", "result", "key_type", ")", "result", "is", "True", "False", "or", "absent", "or", "partial", "(", "both", "still", "usable", ")", "key_type", "is", "int", "for", "integer", "keys", "or", "str", "for", "hash", "keys" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/reshape.py#L220-L236
skelsec/minikerberos
minikerberos/ccache.py
Header.parse
def parse(data): """ returns a list of header tags """ reader = io.BytesIO(data) headers = [] while reader.tell() < len(data): h = Header() h.tag = int.from_bytes(reader.read(2), byteorder='big', signed=False) h.taglen = int.from_bytes(reader.read(2), byteorder='big', signed=False) h.tagdata = r...
python
def parse(data): """ returns a list of header tags """ reader = io.BytesIO(data) headers = [] while reader.tell() < len(data): h = Header() h.tag = int.from_bytes(reader.read(2), byteorder='big', signed=False) h.taglen = int.from_bytes(reader.read(2), byteorder='big', signed=False) h.tagdata = r...
[ "def", "parse", "(", "data", ")", ":", "reader", "=", "io", ".", "BytesIO", "(", "data", ")", "headers", "=", "[", "]", "while", "reader", ".", "tell", "(", ")", "<", "len", "(", "data", ")", ":", "h", "=", "Header", "(", ")", "h", ".", "tag"...
returns a list of header tags
[ "returns", "a", "list", "of", "header", "tags" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L29-L41
skelsec/minikerberos
minikerberos/ccache.py
Credential.to_tgt
def to_tgt(self): """ Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format """ enc_part = EncryptedData({'etype': 1, 'cipher': b''}) tgt_rep = {} tgt_rep['pvno'] = krb5_pvno tgt_rep['msg-type'] = MESSAGE_TYPE.KRB_AS_REP.value tgt_rep['crealm'] = self.server...
python
def to_tgt(self): """ Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format """ enc_part = EncryptedData({'etype': 1, 'cipher': b''}) tgt_rep = {} tgt_rep['pvno'] = krb5_pvno tgt_rep['msg-type'] = MESSAGE_TYPE.KRB_AS_REP.value tgt_rep['crealm'] = self.server...
[ "def", "to_tgt", "(", "self", ")", ":", "enc_part", "=", "EncryptedData", "(", "{", "'etype'", ":", "1", ",", "'cipher'", ":", "b''", "}", ")", "tgt_rep", "=", "{", "}", "tgt_rep", "[", "'pvno'", "]", "=", "krb5_pvno", "tgt_rep", "[", "'msg-type'", "...
Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format
[ "Returns", "the", "native", "format", "of", "an", "AS_REP", "message", "and", "the", "sessionkey", "in", "EncryptionKey", "native", "format" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L102-L118
skelsec/minikerberos
minikerberos/ccache.py
CCACHE.add_tgt
def add_tgt(self, as_rep, enc_as_rep_part, override_pp = True): #from AS_REP """ Creates credential object from the TGT and adds to the ccache file The TGT is basically the native representation of the asn1 encoded AS_REP data that the AD sends upon a succsessful TGT request. This function doesn't do decrypt...
python
def add_tgt(self, as_rep, enc_as_rep_part, override_pp = True): #from AS_REP """ Creates credential object from the TGT and adds to the ccache file The TGT is basically the native representation of the asn1 encoded AS_REP data that the AD sends upon a succsessful TGT request. This function doesn't do decrypt...
[ "def", "add_tgt", "(", "self", ",", "as_rep", ",", "enc_as_rep_part", ",", "override_pp", "=", "True", ")", ":", "#from AS_REP", "c", "=", "Credential", "(", ")", "c", ".", "client", "=", "CCACHEPrincipal", ".", "from_asn1", "(", "as_rep", "[", "'cname'", ...
Creates credential object from the TGT and adds to the ccache file The TGT is basically the native representation of the asn1 encoded AS_REP data that the AD sends upon a succsessful TGT request. This function doesn't do decryption of the encrypted part of the as_rep object, it is expected that the decrypted XXX...
[ "Creates", "credential", "object", "from", "the", "TGT", "and", "adds", "to", "the", "ccache", "file", "The", "TGT", "is", "basically", "the", "native", "representation", "of", "the", "asn1", "encoded", "AS_REP", "data", "that", "the", "AD", "sends", "upon",...
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L465-L489
skelsec/minikerberos
minikerberos/ccache.py
CCACHE.add_tgs
def add_tgs(self, tgs_rep, enc_tgs_rep_part, override_pp = False): #from AS_REP """ Creates credential object from the TGS and adds to the ccache file The TGS is the native representation of the asn1 encoded TGS_REP data when the user requests a tgs to a specific service principal with a valid TGT This funct...
python
def add_tgs(self, tgs_rep, enc_tgs_rep_part, override_pp = False): #from AS_REP """ Creates credential object from the TGS and adds to the ccache file The TGS is the native representation of the asn1 encoded TGS_REP data when the user requests a tgs to a specific service principal with a valid TGT This funct...
[ "def", "add_tgs", "(", "self", ",", "tgs_rep", ",", "enc_tgs_rep_part", ",", "override_pp", "=", "False", ")", ":", "#from AS_REP", "c", "=", "Credential", "(", ")", "c", ".", "client", "=", "CCACHEPrincipal", ".", "from_asn1", "(", "tgs_rep", "[", "'cname...
Creates credential object from the TGS and adds to the ccache file The TGS is the native representation of the asn1 encoded TGS_REP data when the user requests a tgs to a specific service principal with a valid TGT This function doesn't do decryption of the encrypted part of the tgs_rep object, it is expected th...
[ "Creates", "credential", "object", "from", "the", "TGS", "and", "adds", "to", "the", "ccache", "file", "The", "TGS", "is", "the", "native", "representation", "of", "the", "asn1", "encoded", "TGS_REP", "data", "when", "the", "user", "requests", "a", "tgs", ...
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L491-L515
skelsec/minikerberos
minikerberos/ccache.py
CCACHE.add_kirbi
def add_kirbi(self, krbcred, override_pp = True, include_expired = False): c = Credential() enc_credinfo = EncKrbCredPart.load(krbcred['enc-part']['cipher']).native ticket_info = enc_credinfo['ticket-info'][0] """ if ticket_info['endtime'] < datetime.datetime.now(datetime.timezone.utc): if include_expir...
python
def add_kirbi(self, krbcred, override_pp = True, include_expired = False): c = Credential() enc_credinfo = EncKrbCredPart.load(krbcred['enc-part']['cipher']).native ticket_info = enc_credinfo['ticket-info'][0] """ if ticket_info['endtime'] < datetime.datetime.now(datetime.timezone.utc): if include_expir...
[ "def", "add_kirbi", "(", "self", ",", "krbcred", ",", "override_pp", "=", "True", ",", "include_expired", "=", "False", ")", ":", "c", "=", "Credential", "(", ")", "enc_credinfo", "=", "EncKrbCredPart", ".", "load", "(", "krbcred", "[", "'enc-part'", "]", ...
if ticket_info['endtime'] < datetime.datetime.now(datetime.timezone.utc): if include_expired == True: logging.debug('This ticket has most likely expired, but include_expired is forcing me to add it to cache! This can cause problems!') else: logging.debug('This ticket has most likely expired, skipping') ...
[ "if", "ticket_info", "[", "endtime", "]", "<", "datetime", ".", "datetime", ".", "now", "(", "datetime", ".", "timezone", ".", "utc", ")", ":", "if", "include_expired", "==", "True", ":", "logging", ".", "debug", "(", "This", "ticket", "has", "most", "...
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L518-L557
skelsec/minikerberos
minikerberos/ccache.py
CCACHE.get_all_tgt
def get_all_tgt(self): """ Returns a list of AS_REP tickets in native format (dict). To determine which ticket are AP_REP we check for the server principal to be the kerberos service """ tgts = [] for cred in self.credentials: if cred.server.to_string().lower().find('krbtgt') != -1: tgts.append(cred...
python
def get_all_tgt(self): """ Returns a list of AS_REP tickets in native format (dict). To determine which ticket are AP_REP we check for the server principal to be the kerberos service """ tgts = [] for cred in self.credentials: if cred.server.to_string().lower().find('krbtgt') != -1: tgts.append(cred...
[ "def", "get_all_tgt", "(", "self", ")", ":", "tgts", "=", "[", "]", "for", "cred", "in", "self", ".", "credentials", ":", "if", "cred", ".", "server", ".", "to_string", "(", ")", ".", "lower", "(", ")", ".", "find", "(", "'krbtgt'", ")", "!=", "-...
Returns a list of AS_REP tickets in native format (dict). To determine which ticket are AP_REP we check for the server principal to be the kerberos service
[ "Returns", "a", "list", "of", "AS_REP", "tickets", "in", "native", "format", "(", "dict", ")", ".", "To", "determine", "which", "ticket", "are", "AP_REP", "we", "check", "for", "the", "server", "principal", "to", "be", "the", "kerberos", "service" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L566-L576
skelsec/minikerberos
minikerberos/ccache.py
CCACHE.get_hashes
def get_hashes(self, all_hashes = False): """ Returns a list of hashes in hashcat-firendly format for tickets with encryption type 23 (which is RC4) all_hashes: overrides the encryption type filtering and returns hash for all tickets """ hashes = [] for cred in self.credentials: res = Ticket.load(cred.t...
python
def get_hashes(self, all_hashes = False): """ Returns a list of hashes in hashcat-firendly format for tickets with encryption type 23 (which is RC4) all_hashes: overrides the encryption type filtering and returns hash for all tickets """ hashes = [] for cred in self.credentials: res = Ticket.load(cred.t...
[ "def", "get_hashes", "(", "self", ",", "all_hashes", "=", "False", ")", ":", "hashes", "=", "[", "]", "for", "cred", "in", "self", ".", "credentials", ":", "res", "=", "Ticket", ".", "load", "(", "cred", ".", "ticket", ".", "to_asn1", "(", ")", ")"...
Returns a list of hashes in hashcat-firendly format for tickets with encryption type 23 (which is RC4) all_hashes: overrides the encryption type filtering and returns hash for all tickets
[ "Returns", "a", "list", "of", "hashes", "in", "hashcat", "-", "firendly", "format", "for", "tickets", "with", "encryption", "type", "23", "(", "which", "is", "RC4", ")", "all_hashes", ":", "overrides", "the", "encryption", "type", "filtering", "and", "return...
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L578-L590
skelsec/minikerberos
minikerberos/ccache.py
CCACHE.from_kirbidir
def from_kirbidir(directory_path): """ Iterates trough all .kirbi files in a given directory and converts all of them into one CCACHE object """ cc = CCACHE() dir_path = os.path.join(os.path.abspath(directory_path), '*.kirbi') for filename in glob.glob(dir_path): with open(filename, 'rb') as f: kirbi...
python
def from_kirbidir(directory_path): """ Iterates trough all .kirbi files in a given directory and converts all of them into one CCACHE object """ cc = CCACHE() dir_path = os.path.join(os.path.abspath(directory_path), '*.kirbi') for filename in glob.glob(dir_path): with open(filename, 'rb') as f: kirbi...
[ "def", "from_kirbidir", "(", "directory_path", ")", ":", "cc", "=", "CCACHE", "(", ")", "dir_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "directory_path", ")", ",", "'*.kirbi'", ")", "for", "filename", "in",...
Iterates trough all .kirbi files in a given directory and converts all of them into one CCACHE object
[ "Iterates", "trough", "all", ".", "kirbi", "files", "in", "a", "given", "directory", "and", "converts", "all", "of", "them", "into", "one", "CCACHE", "object" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L638-L650
skelsec/minikerberos
minikerberos/ccache.py
CCACHE.to_kirbidir
def to_kirbidir(self, directory_path): """ Converts all credential object in the CCACHE object to the kirbi file format used by mimikatz. The kirbi file format supports one credential per file, so prepare for a lot of files being generated. directory_path: str the directory to write the kirbi files to """ ...
python
def to_kirbidir(self, directory_path): """ Converts all credential object in the CCACHE object to the kirbi file format used by mimikatz. The kirbi file format supports one credential per file, so prepare for a lot of files being generated. directory_path: str the directory to write the kirbi files to """ ...
[ "def", "to_kirbidir", "(", "self", ",", "directory_path", ")", ":", "kf_abs", "=", "os", ".", "path", ".", "abspath", "(", "directory_path", ")", "for", "cred", "in", "self", ".", "credentials", ":", "kirbi", ",", "filename", "=", "cred", ".", "to_kirbi"...
Converts all credential object in the CCACHE object to the kirbi file format used by mimikatz. The kirbi file format supports one credential per file, so prepare for a lot of files being generated. directory_path: str the directory to write the kirbi files to
[ "Converts", "all", "credential", "object", "in", "the", "CCACHE", "object", "to", "the", "kirbi", "file", "format", "used", "by", "mimikatz", ".", "The", "kirbi", "file", "format", "supports", "one", "credential", "per", "file", "so", "prepare", "for", "a", ...
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L652-L665
skelsec/minikerberos
minikerberos/ccache.py
CCACHE.to_file
def to_file(self, filename): """ Writes the contents of the CCACHE object to a file """ with open(filename, 'wb') as f: f.write(self.to_bytes())
python
def to_file(self, filename): """ Writes the contents of the CCACHE object to a file """ with open(filename, 'wb') as f: f.write(self.to_bytes())
[ "def", "to_file", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", "to_bytes", "(", ")", ")" ]
Writes the contents of the CCACHE object to a file
[ "Writes", "the", "contents", "of", "the", "CCACHE", "object", "to", "a", "file" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/ccache.py#L674-L679
skelsec/minikerberos
minikerberos/common.py
print_table
def print_table(lines, separate_head=True): """Prints a formatted table given a 2 dimensional array""" #Count the column width widths = [] for line in lines: for i,size in enumerate([len(x) for x in line]): while i >= len(widths): widths.append(0) if size > widths[i]: widths[i] = size ...
python
def print_table(lines, separate_head=True): """Prints a formatted table given a 2 dimensional array""" #Count the column width widths = [] for line in lines: for i,size in enumerate([len(x) for x in line]): while i >= len(widths): widths.append(0) if size > widths[i]: widths[i] = size ...
[ "def", "print_table", "(", "lines", ",", "separate_head", "=", "True", ")", ":", "#Count the column width", "widths", "=", "[", "]", "for", "line", "in", "lines", ":", "for", "i", ",", "size", "in", "enumerate", "(", "[", "len", "(", "x", ")", "for", ...
Prints a formatted table given a 2 dimensional array
[ "Prints", "a", "formatted", "table", "given", "a", "2", "dimensional", "array" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/common.py#L246-L269
skelsec/minikerberos
minikerberos/common.py
KerberosCredential.get_key_for_enctype
def get_key_for_enctype(self, etype): """ Returns the encryption key bytes for the enctryption type. """ if etype == EncryptionType.AES256_CTS_HMAC_SHA1_96: if self.kerberos_key_aes_256: return bytes.fromhex(self.kerberos_key_aes_256) if self.password is not None: salt = (self.domain.upper() + sel...
python
def get_key_for_enctype(self, etype): """ Returns the encryption key bytes for the enctryption type. """ if etype == EncryptionType.AES256_CTS_HMAC_SHA1_96: if self.kerberos_key_aes_256: return bytes.fromhex(self.kerberos_key_aes_256) if self.password is not None: salt = (self.domain.upper() + sel...
[ "def", "get_key_for_enctype", "(", "self", ",", "etype", ")", ":", "if", "etype", "==", "EncryptionType", ".", "AES256_CTS_HMAC_SHA1_96", ":", "if", "self", ".", "kerberos_key_aes_256", ":", "return", "bytes", ".", "fromhex", "(", "self", ".", "kerberos_key_aes_...
Returns the encryption key bytes for the enctryption type.
[ "Returns", "the", "encryption", "key", "bytes", "for", "the", "enctryption", "type", "." ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/common.py#L54-L101
skelsec/minikerberos
minikerberos/common.py
KerberosCredential.from_connection_string
def from_connection_string(s): """ Credential input format: <domain>/<username>/<secret_type>:<secret>@<dc_ip_or_hostname> """ cred = KerberosCredential() cred.domain, t = s.split('/', 1) cred.username, t = t.split('/', 1) secret_type, t = t.split(':', 1) secret, target = t.rsplit('@', 1) st =...
python
def from_connection_string(s): """ Credential input format: <domain>/<username>/<secret_type>:<secret>@<dc_ip_or_hostname> """ cred = KerberosCredential() cred.domain, t = s.split('/', 1) cred.username, t = t.split('/', 1) secret_type, t = t.split(':', 1) secret, target = t.rsplit('@', 1) st =...
[ "def", "from_connection_string", "(", "s", ")", ":", "cred", "=", "KerberosCredential", "(", ")", "cred", ".", "domain", ",", "t", "=", "s", ".", "split", "(", "'/'", ",", "1", ")", "cred", ".", "username", ",", "t", "=", "t", ".", "split", "(", ...
Credential input format: <domain>/<username>/<secret_type>:<secret>@<dc_ip_or_hostname>
[ "Credential", "input", "format", ":", "<domain", ">", "/", "<username", ">", "/", "<secret_type", ">", ":", "<secret", ">" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/common.py#L174-L208
skelsec/minikerberos
minikerberos/security.py
KerberosUserEnum.run
def run(self, realm, users): """ Requests a TGT in the name of the users specified in users. Returns a list of usernames that are in the domain. realm: kerberos realm (domain name of the corp) users: list : list of usernames to test """ existing_users = [] for user in users: logging.debug('Probing ...
python
def run(self, realm, users): """ Requests a TGT in the name of the users specified in users. Returns a list of usernames that are in the domain. realm: kerberos realm (domain name of the corp) users: list : list of usernames to test """ existing_users = [] for user in users: logging.debug('Probing ...
[ "def", "run", "(", "self", ",", "realm", ",", "users", ")", ":", "existing_users", "=", "[", "]", "for", "user", "in", "users", ":", "logging", ".", "debug", "(", "'Probing user %s'", "%", "user", ")", "req", "=", "KerberosUserEnum", ".", "construct_tgt_...
Requests a TGT in the name of the users specified in users. Returns a list of usernames that are in the domain. realm: kerberos realm (domain name of the corp) users: list : list of usernames to test
[ "Requests", "a", "TGT", "in", "the", "name", "of", "the", "users", "specified", "in", "users", ".", "Returns", "a", "list", "of", "usernames", "that", "are", "in", "the", "domain", "." ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/security.py#L43-L69
skelsec/minikerberos
minikerberos/security.py
APREPRoast.run
def run(self, creds, override_etype = [23]): """ Requests TGT tickets for all users specified in the targets list creds: list : the users to request the TGT tickets for override_etype: list : list of supported encryption types """ tgts = [] for cred in creds: try: kcomm = KerbrosComm(cred, self....
python
def run(self, creds, override_etype = [23]): """ Requests TGT tickets for all users specified in the targets list creds: list : the users to request the TGT tickets for override_etype: list : list of supported encryption types """ tgts = [] for cred in creds: try: kcomm = KerbrosComm(cred, self....
[ "def", "run", "(", "self", ",", "creds", ",", "override_etype", "=", "[", "23", "]", ")", ":", "tgts", "=", "[", "]", "for", "cred", "in", "creds", ":", "try", ":", "kcomm", "=", "KerbrosComm", "(", "cred", ",", "self", ".", "ksoc", ")", "kcomm",...
Requests TGT tickets for all users specified in the targets list creds: list : the users to request the TGT tickets for override_etype: list : list of supported encryption types
[ "Requests", "TGT", "tickets", "for", "all", "users", "specified", "in", "the", "targets", "list", "creds", ":", "list", ":", "the", "users", "to", "request", "the", "TGT", "tickets", "for", "override_etype", ":", "list", ":", "list", "of", "supported", "en...
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/security.py#L75-L96
skelsec/minikerberos
minikerberos/security.py
Kerberoast.run
def run(self, targets, override_etype = [2, 3, 16, 23, 17, 18]): """ Requests TGS tickets for all service users specified in the targets list targets: list : the SPN users to request the TGS tickets for allhash: bool : Return all enctype tickets, ot just 23 """ if not self.kcomm: try: self.kcomm = Ke...
python
def run(self, targets, override_etype = [2, 3, 16, 23, 17, 18]): """ Requests TGS tickets for all service users specified in the targets list targets: list : the SPN users to request the TGS tickets for allhash: bool : Return all enctype tickets, ot just 23 """ if not self.kcomm: try: self.kcomm = Ke...
[ "def", "run", "(", "self", ",", "targets", ",", "override_etype", "=", "[", "2", ",", "3", ",", "16", ",", "23", ",", "17", ",", "18", "]", ")", ":", "if", "not", "self", ".", "kcomm", ":", "try", ":", "self", ".", "kcomm", "=", "KerbrosComm", ...
Requests TGS tickets for all service users specified in the targets list targets: list : the SPN users to request the TGS tickets for allhash: bool : Return all enctype tickets, ot just 23
[ "Requests", "TGS", "tickets", "for", "all", "service", "users", "specified", "in", "the", "targets", "list", "targets", ":", "list", ":", "the", "SPN", "users", "to", "request", "the", "TGS", "tickets", "for", "allhash", ":", "bool", ":", "Return", "all", ...
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/security.py#L104-L132
skelsec/minikerberos
minikerberos/crypto/PBKDF2/pbkdf2.py
pbkdf2
def pbkdf2(password, salt, iters, keylen, digestmod = hashlib.sha1): """Run the PBKDF2 (Password-Based Key Derivation Function 2) algorithm and return the derived key. The arguments are: password (bytes or bytearray) -- the input password salt (bytes or bytearray) -- a cryptographic salt iters (int) -- number of ...
python
def pbkdf2(password, salt, iters, keylen, digestmod = hashlib.sha1): """Run the PBKDF2 (Password-Based Key Derivation Function 2) algorithm and return the derived key. The arguments are: password (bytes or bytearray) -- the input password salt (bytes or bytearray) -- a cryptographic salt iters (int) -- number of ...
[ "def", "pbkdf2", "(", "password", ",", "salt", ",", "iters", ",", "keylen", ",", "digestmod", "=", "hashlib", ".", "sha1", ")", ":", "h", "=", "hmac", ".", "new", "(", "password", ",", "digestmod", "=", "digestmod", ")", "def", "prf", "(", "data", ...
Run the PBKDF2 (Password-Based Key Derivation Function 2) algorithm and return the derived key. The arguments are: password (bytes or bytearray) -- the input password salt (bytes or bytearray) -- a cryptographic salt iters (int) -- number of iterations keylen (int) -- length of key to derive digestmod -- a crypt...
[ "Run", "the", "PBKDF2", "(", "Password", "-", "Based", "Key", "Derivation", "Function", "2", ")", "algorithm", "and", "return", "the", "derived", "key", ".", "The", "arguments", "are", ":" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/crypto/PBKDF2/pbkdf2.py#L7-L45
skelsec/minikerberos
minikerberos/communication.py
KerberosSocket.from_connection_string
def from_connection_string(s, soc_type = KerberosSocketType.TCP): """ <credentials>@<ip_or_hostname>:<port> """ ip = None port = 88 t, addr = s.rsplit('@') if addr.find(':') == -1: ip = addr else: ip, port = addr.split(':') return KerberosSocket(ip, port = int(port), soc_type = soc_type)
python
def from_connection_string(s, soc_type = KerberosSocketType.TCP): """ <credentials>@<ip_or_hostname>:<port> """ ip = None port = 88 t, addr = s.rsplit('@') if addr.find(':') == -1: ip = addr else: ip, port = addr.split(':') return KerberosSocket(ip, port = int(port), soc_type = soc_type)
[ "def", "from_connection_string", "(", "s", ",", "soc_type", "=", "KerberosSocketType", ".", "TCP", ")", ":", "ip", "=", "None", "port", "=", "88", "t", ",", "addr", "=", "s", ".", "rsplit", "(", "'@'", ")", "if", "addr", ".", "find", "(", "':'", ")...
<credentials>@<ip_or_hostname>:<port>
[ "<credentials", ">" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/communication.py#L42-L55
skelsec/minikerberos
minikerberos/communication.py
KerbrosComm.from_tgt
def from_tgt(ksoc, tgt, key): """ Sets up the kerberos object from tgt and the session key. Use this function when pulling the TGT from ccache file. """ kc = KerbrosComm(None, ksoc) kc.kerberos_TGT = tgt kc.kerberos_cipher_type = key['keytype'] kc.kerberos_session_key = Key(kc.kerberos_cipher_type, k...
python
def from_tgt(ksoc, tgt, key): """ Sets up the kerberos object from tgt and the session key. Use this function when pulling the TGT from ccache file. """ kc = KerbrosComm(None, ksoc) kc.kerberos_TGT = tgt kc.kerberos_cipher_type = key['keytype'] kc.kerberos_session_key = Key(kc.kerberos_cipher_type, k...
[ "def", "from_tgt", "(", "ksoc", ",", "tgt", ",", "key", ")", ":", "kc", "=", "KerbrosComm", "(", "None", ",", "ksoc", ")", "kc", ".", "kerberos_TGT", "=", "tgt", "kc", ".", "kerberos_cipher_type", "=", "key", "[", "'keytype'", "]", "kc", ".", "kerber...
Sets up the kerberos object from tgt and the session key. Use this function when pulling the TGT from ccache file.
[ "Sets", "up", "the", "kerberos", "object", "from", "tgt", "and", "the", "session", "key", ".", "Use", "this", "function", "when", "pulling", "the", "TGT", "from", "ccache", "file", "." ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/communication.py#L138-L149
skelsec/minikerberos
minikerberos/communication.py
KerbrosComm.get_TGT
def get_TGT(self, override_etype = None, decrypt_tgt = True): """ decrypt_tgt: used for asreproast attacks Steps performed: 1. Send and empty (no encrypted timestamp) AS_REQ with all the encryption types we support 2. Depending on the response (either error or AS_REP with TGT) we either send another AS_REQ ...
python
def get_TGT(self, override_etype = None, decrypt_tgt = True): """ decrypt_tgt: used for asreproast attacks Steps performed: 1. Send and empty (no encrypted timestamp) AS_REQ with all the encryption types we support 2. Depending on the response (either error or AS_REP with TGT) we either send another AS_REQ ...
[ "def", "get_TGT", "(", "self", ",", "override_etype", "=", "None", ",", "decrypt_tgt", "=", "True", ")", ":", "logger", ".", "debug", "(", "'Generating initial TGT without authentication data'", ")", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ...
decrypt_tgt: used for asreproast attacks Steps performed: 1. Send and empty (no encrypted timestamp) AS_REQ with all the encryption types we support 2. Depending on the response (either error or AS_REP with TGT) we either send another AS_REQ with the encrypted data or return the TGT (or fail miserably) 3. PR...
[ "decrypt_tgt", ":", "used", "for", "asreproast", "attacks", "Steps", "performed", ":", "1", ".", "Send", "and", "empty", "(", "no", "encrypted", "timestamp", ")", "AS_REQ", "with", "all", "the", "encryption", "types", "we", "support", "2", ".", "Depending", ...
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/communication.py#L215-L285
skelsec/minikerberos
minikerberos/communication.py
KerbrosComm.get_TGS
def get_TGS(self, spn_user, override_etype = None): """ Requests a TGS ticket for the specified user. Retruns the TGS ticket, end the decrpyted encTGSRepPart. spn_user: KerberosTarget: the service user you want to get TGS for. override_etype: None or list of etype values (int) Used mostly for kerberoasting, ...
python
def get_TGS(self, spn_user, override_etype = None): """ Requests a TGS ticket for the specified user. Retruns the TGS ticket, end the decrpyted encTGSRepPart. spn_user: KerberosTarget: the service user you want to get TGS for. override_etype: None or list of etype values (int) Used mostly for kerberoasting, ...
[ "def", "get_TGS", "(", "self", ",", "spn_user", ",", "override_etype", "=", "None", ")", ":", "#construct tgs_req", "logger", ".", "debug", "(", "'Constructing TGS request for user %s'", "%", "spn_user", ".", "get_formatted_pname", "(", ")", ")", "now", "=", "da...
Requests a TGS ticket for the specified user. Retruns the TGS ticket, end the decrpyted encTGSRepPart. spn_user: KerberosTarget: the service user you want to get TGS for. override_etype: None or list of etype values (int) Used mostly for kerberoasting, will override the AP_REQ supported etype values (which is de...
[ "Requests", "a", "TGS", "ticket", "for", "the", "specified", "user", ".", "Retruns", "the", "TGS", "ticket", "end", "the", "decrpyted", "encTGSRepPart", "." ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/communication.py#L287-L348
skelsec/minikerberos
minikerberos/communication.py
KerbrosComm.S4U2self
def S4U2self(self, user_to_impersonate, supp_enc_methods = [EncryptionType.DES_CBC_CRC,EncryptionType.DES_CBC_MD4,EncryptionType.DES_CBC_MD5,EncryptionType.DES3_CBC_SHA1,EncryptionType.ARCFOUR_HMAC_MD5,EncryptionType.AES256_CTS_HMAC_SHA1_96,EncryptionType.AES128_CTS_HMAC_SHA1_96]): #def S4U2self(self, user_to_imperson...
python
def S4U2self(self, user_to_impersonate, supp_enc_methods = [EncryptionType.DES_CBC_CRC,EncryptionType.DES_CBC_MD4,EncryptionType.DES_CBC_MD5,EncryptionType.DES3_CBC_SHA1,EncryptionType.ARCFOUR_HMAC_MD5,EncryptionType.AES256_CTS_HMAC_SHA1_96,EncryptionType.AES128_CTS_HMAC_SHA1_96]): #def S4U2self(self, user_to_imperson...
[ "def", "S4U2self", "(", "self", ",", "user_to_impersonate", ",", "supp_enc_methods", "=", "[", "EncryptionType", ".", "DES_CBC_CRC", ",", "EncryptionType", ".", "DES_CBC_MD4", ",", "EncryptionType", ".", "DES_CBC_MD5", ",", "EncryptionType", ".", "DES3_CBC_SHA1", ",...
user_to_impersonate : KerberosTarget class
[ "user_to_impersonate", ":", "KerberosTarget", "class" ]
train
https://github.com/skelsec/minikerberos/blob/caf14c1d0132119d6e8a8f05120efb7d0824b2c6/minikerberos/communication.py#L351-L453
project-rig/rig
rig/routing_table/remove_default_routes.py
minimise
def minimise(table, target_length, check_for_aliases=True): """Remove from the routing table any entries which could be replaced by default routing. Parameters ---------- routing_table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...] Routing table from which to remove entries which...
python
def minimise(table, target_length, check_for_aliases=True): """Remove from the routing table any entries which could be replaced by default routing. Parameters ---------- routing_table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...] Routing table from which to remove entries which...
[ "def", "minimise", "(", "table", ",", "target_length", ",", "check_for_aliases", "=", "True", ")", ":", "# If alias checking is required, see if we can cheaply prove that no", "# aliases exist in the table to skip this costly check.", "if", "check_for_aliases", ":", "# Aliases cann...
Remove from the routing table any entries which could be replaced by default routing. Parameters ---------- routing_table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...] Routing table from which to remove entries which could be handled by default routing. target_length : i...
[ "Remove", "from", "the", "routing", "table", "any", "entries", "which", "could", "be", "replaced", "by", "default", "routing", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/remove_default_routes.py#L5-L57
project-rig/rig
rig/routing_table/remove_default_routes.py
_is_defaultable
def _is_defaultable(i, entry, table, check_for_aliases=True): """Determine if an entry may be removed from a routing table and be replaced by a default route. Parameters ---------- i : int Position of the entry in the table entry : RoutingTableEntry The entry itself table : ...
python
def _is_defaultable(i, entry, table, check_for_aliases=True): """Determine if an entry may be removed from a routing table and be replaced by a default route. Parameters ---------- i : int Position of the entry in the table entry : RoutingTableEntry The entry itself table : ...
[ "def", "_is_defaultable", "(", "i", ",", "entry", ",", "table", ",", "check_for_aliases", "=", "True", ")", ":", "# May only have one source and sink (which may not be None)", "if", "(", "len", "(", "entry", ".", "sources", ")", "==", "1", "and", "len", "(", "...
Determine if an entry may be removed from a routing table and be replaced by a default route. Parameters ---------- i : int Position of the entry in the table entry : RoutingTableEntry The entry itself table : [RoutingTableEntry, ...] The table containing the entry. ...
[ "Determine", "if", "an", "entry", "may", "be", "removed", "from", "a", "routing", "table", "and", "be", "replaced", "by", "a", "default", "route", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/remove_default_routes.py#L60-L93
project-rig/rig
rig/routing_table/utils.py
routing_tree_to_tables
def routing_tree_to_tables(routes, net_keys): """Convert a set of :py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip set of routing tables. .. warning:: A :py:exc:`rig.routing_table.MultisourceRouteError` will be raised if entries with identical keys and masks b...
python
def routing_tree_to_tables(routes, net_keys): """Convert a set of :py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip set of routing tables. .. warning:: A :py:exc:`rig.routing_table.MultisourceRouteError` will be raised if entries with identical keys and masks b...
[ "def", "routing_tree_to_tables", "(", "routes", ",", "net_keys", ")", ":", "# Pairs of inbound and outbound routes.", "InOutPair", "=", "namedtuple", "(", "\"InOutPair\"", ",", "\"ins, outs\"", ")", "# {(x, y): {(key, mask): _InOutPair}}", "route_sets", "=", "defaultdict", ...
Convert a set of :py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip set of routing tables. .. warning:: A :py:exc:`rig.routing_table.MultisourceRouteError` will be raised if entries with identical keys and masks but with differing routes are generated. This ...
[ "Convert", "a", "set", "of", ":", "py", ":", "class", ":", "~rig", ".", "place_and_route", ".", "routing_tree", ".", "RoutingTree", "s", "into", "a", "per", "-", "chip", "set", "of", "routing", "tables", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/utils.py#L8-L83
project-rig/rig
rig/routing_table/utils.py
build_routing_table_target_lengths
def build_routing_table_target_lengths(system_info): """Build a dictionary of target routing table lengths from a :py:class:`~rig.machine_control.machine_controller.SystemInfo` object. Useful in conjunction with :py:func:`~rig.routing_table.minimise_tables`. Returns ------- {(x, y): num, ...} ...
python
def build_routing_table_target_lengths(system_info): """Build a dictionary of target routing table lengths from a :py:class:`~rig.machine_control.machine_controller.SystemInfo` object. Useful in conjunction with :py:func:`~rig.routing_table.minimise_tables`. Returns ------- {(x, y): num, ...} ...
[ "def", "build_routing_table_target_lengths", "(", "system_info", ")", ":", "return", "{", "(", "x", ",", "y", ")", ":", "ci", ".", "largest_free_rtr_mc_block", "for", "(", "x", ",", "y", ")", ",", "ci", "in", "iteritems", "(", "system_info", ")", "}" ]
Build a dictionary of target routing table lengths from a :py:class:`~rig.machine_control.machine_controller.SystemInfo` object. Useful in conjunction with :py:func:`~rig.routing_table.minimise_tables`. Returns ------- {(x, y): num, ...} A dictionary giving the number of free routing table...
[ "Build", "a", "dictionary", "of", "target", "routing", "table", "lengths", "from", "a", ":", "py", ":", "class", ":", "~rig", ".", "machine_control", ".", "machine_controller", ".", "SystemInfo", "object", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/utils.py#L86-L105
project-rig/rig
rig/routing_table/utils.py
table_is_subset_of
def table_is_subset_of(entries_a, entries_b): """Check that every key matched by every entry in one table results in the same route when checked against the other table. For example, the table:: >>> from rig.routing_table import Routes >>> table = [ ... RoutingTableEntry({Route...
python
def table_is_subset_of(entries_a, entries_b): """Check that every key matched by every entry in one table results in the same route when checked against the other table. For example, the table:: >>> from rig.routing_table import Routes >>> table = [ ... RoutingTableEntry({Route...
[ "def", "table_is_subset_of", "(", "entries_a", ",", "entries_b", ")", ":", "# Determine which bits we don't need to explicitly test for", "common_xs", "=", "get_common_xs", "(", "entries_b", ")", "# For every entry in the first table", "for", "entry", "in", "expand_entries", ...
Check that every key matched by every entry in one table results in the same route when checked against the other table. For example, the table:: >>> from rig.routing_table import Routes >>> table = [ ... RoutingTableEntry({Routes.north, Routes.north_east}, 0x0, 0xf), ... ...
[ "Check", "that", "every", "key", "matched", "by", "every", "entry", "in", "one", "table", "results", "in", "the", "same", "route", "when", "checked", "against", "the", "other", "table", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/utils.py#L108-L198
project-rig/rig
rig/routing_table/utils.py
expand_entry
def expand_entry(entry, ignore_xs=0x0): """Turn all Xs which are not marked in `ignore_xs` into ``0``\ s and ``1``\ s. The following will expand any Xs in bits ``1..3``\ :: >>> entry = RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100) >>> list(expand_entry(entry, 0xfffffff1)) == [ ...
python
def expand_entry(entry, ignore_xs=0x0): """Turn all Xs which are not marked in `ignore_xs` into ``0``\ s and ``1``\ s. The following will expand any Xs in bits ``1..3``\ :: >>> entry = RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100) >>> list(expand_entry(entry, 0xfffffff1)) == [ ...
[ "def", "expand_entry", "(", "entry", ",", "ignore_xs", "=", "0x0", ")", ":", "# Get all the Xs in the entry that are not ignored", "xs", "=", "(", "~", "entry", ".", "key", "&", "~", "entry", ".", "mask", ")", "&", "~", "ignore_xs", "# Find the most significant ...
Turn all Xs which are not marked in `ignore_xs` into ``0``\ s and ``1``\ s. The following will expand any Xs in bits ``1..3``\ :: >>> entry = RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100) >>> list(expand_entry(entry, 0xfffffff1)) == [ ... RoutingTableEntry(set(), 0b0100, 0x...
[ "Turn", "all", "Xs", "which", "are", "not", "marked", "in", "ignore_xs", "into", "0", "\\", "s", "and", "1", "\\", "s", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/utils.py#L234-L282
project-rig/rig
rig/routing_table/utils.py
expand_entries
def expand_entries(entries, ignore_xs=None): """Turn all Xs which are not ignored in all entries into ``0`` s and ``1`` s. For example:: >>> from rig.routing_table import RoutingTableEntry >>> entries = [ ... RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100), # 01XX ...
python
def expand_entries(entries, ignore_xs=None): """Turn all Xs which are not ignored in all entries into ``0`` s and ``1`` s. For example:: >>> from rig.routing_table import RoutingTableEntry >>> entries = [ ... RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100), # 01XX ...
[ "def", "expand_entries", "(", "entries", ",", "ignore_xs", "=", "None", ")", ":", "# Find the common Xs for the entries", "if", "ignore_xs", "is", "None", ":", "ignore_xs", "=", "get_common_xs", "(", "entries", ")", "# Keep a track of keys that we've seen", "seen_keys",...
Turn all Xs which are not ignored in all entries into ``0`` s and ``1`` s. For example:: >>> from rig.routing_table import RoutingTableEntry >>> entries = [ ... RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100), # 01XX ... RoutingTableEntry(set(), 0b0010, 0xfffffff...
[ "Turn", "all", "Xs", "which", "are", "not", "ignored", "in", "all", "entries", "into", "0", "s", "and", "1", "s", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/utils.py#L285-L366
project-rig/rig
rig/routing_table/utils.py
get_common_xs
def get_common_xs(entries): """Return a mask of where there are Xs in all routing table entries. For example ``01XX`` and ``XX1X`` have common Xs in the LSB only, for this input this method would return ``0b0001``:: >>> from rig.routing_table import RoutingTableEntry >>> entries = [ ...
python
def get_common_xs(entries): """Return a mask of where there are Xs in all routing table entries. For example ``01XX`` and ``XX1X`` have common Xs in the LSB only, for this input this method would return ``0b0001``:: >>> from rig.routing_table import RoutingTableEntry >>> entries = [ ...
[ "def", "get_common_xs", "(", "entries", ")", ":", "# Determine where there are never 1s in the key and mask", "key", "=", "0x00000000", "mask", "=", "0x00000000", "for", "entry", "in", "entries", ":", "key", "|=", "entry", ".", "key", "mask", "|=", "entry", ".", ...
Return a mask of where there are Xs in all routing table entries. For example ``01XX`` and ``XX1X`` have common Xs in the LSB only, for this input this method would return ``0b0001``:: >>> from rig.routing_table import RoutingTableEntry >>> entries = [ ... RoutingTableEntry(set(), ...
[ "Return", "a", "mask", "of", "where", "there", "are", "Xs", "in", "all", "routing", "table", "entries", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/utils.py#L369-L393
project-rig/rig
rig/place_and_route/allocate/utils.py
slices_overlap
def slices_overlap(slice_a, slice_b): """Test if the ranges covered by a pair of slices overlap.""" assert slice_a.step is None assert slice_b.step is None return max(slice_a.start, slice_b.start) \ < min(slice_a.stop, slice_b.stop)
python
def slices_overlap(slice_a, slice_b): """Test if the ranges covered by a pair of slices overlap.""" assert slice_a.step is None assert slice_b.step is None return max(slice_a.start, slice_b.start) \ < min(slice_a.stop, slice_b.stop)
[ "def", "slices_overlap", "(", "slice_a", ",", "slice_b", ")", ":", "assert", "slice_a", ".", "step", "is", "None", "assert", "slice_b", ".", "step", "is", "None", "return", "max", "(", "slice_a", ".", "start", ",", "slice_b", ".", "start", ")", "<", "m...
Test if the ranges covered by a pair of slices overlap.
[ "Test", "if", "the", "ranges", "covered", "by", "a", "pair", "of", "slices", "overlap", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/allocate/utils.py#L4-L10
project-rig/rig
rig/geometry.py
minimise_xyz
def minimise_xyz(xyz): """Minimise an (x, y, z) coordinate.""" x, y, z = xyz m = max(min(x, y), min(max(x, y), z)) return (x-m, y-m, z-m)
python
def minimise_xyz(xyz): """Minimise an (x, y, z) coordinate.""" x, y, z = xyz m = max(min(x, y), min(max(x, y), z)) return (x-m, y-m, z-m)
[ "def", "minimise_xyz", "(", "xyz", ")", ":", "x", ",", "y", ",", "z", "=", "xyz", "m", "=", "max", "(", "min", "(", "x", ",", "y", ")", ",", "min", "(", "max", "(", "x", ",", "y", ")", ",", "z", ")", ")", "return", "(", "x", "-", "m", ...
Minimise an (x, y, z) coordinate.
[ "Minimise", "an", "(", "x", "y", "z", ")", "coordinate", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/geometry.py#L19-L23
project-rig/rig
rig/geometry.py
concentric_hexagons
def concentric_hexagons(radius, start=(0, 0)): """A generator which produces coordinates of concentric rings of hexagons. Parameters ---------- radius : int Number of layers to produce (0 is just one hexagon) start : (x, y) The coordinate of the central hexagon. """ x, y = s...
python
def concentric_hexagons(radius, start=(0, 0)): """A generator which produces coordinates of concentric rings of hexagons. Parameters ---------- radius : int Number of layers to produce (0 is just one hexagon) start : (x, y) The coordinate of the central hexagon. """ x, y = s...
[ "def", "concentric_hexagons", "(", "radius", ",", "start", "=", "(", "0", ",", "0", ")", ")", ":", "x", ",", "y", "=", "start", "yield", "(", "x", ",", "y", ")", "for", "r", "in", "range", "(", "1", ",", "radius", "+", "1", ")", ":", "# Move ...
A generator which produces coordinates of concentric rings of hexagons. Parameters ---------- radius : int Number of layers to produce (0 is just one hexagon) start : (x, y) The coordinate of the central hexagon.
[ "A", "generator", "which", "produces", "coordinates", "of", "concentric", "rings", "of", "hexagons", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/geometry.py#L215-L235
project-rig/rig
rig/geometry.py
standard_system_dimensions
def standard_system_dimensions(num_boards): """Calculate the standard network dimensions (in chips) for a full torus system with the specified number of SpiNN-5 boards. Returns ------- (w, h) Width and height of the network in chips. Standard SpiNNaker systems are constructed as sq...
python
def standard_system_dimensions(num_boards): """Calculate the standard network dimensions (in chips) for a full torus system with the specified number of SpiNN-5 boards. Returns ------- (w, h) Width and height of the network in chips. Standard SpiNNaker systems are constructed as sq...
[ "def", "standard_system_dimensions", "(", "num_boards", ")", ":", "# Special case to avoid division by 0", "if", "num_boards", "==", "0", ":", "return", "(", "0", ",", "0", ")", "# Special case: meaningful systems with 1 board can exist", "if", "num_boards", "==", "1", ...
Calculate the standard network dimensions (in chips) for a full torus system with the specified number of SpiNN-5 boards. Returns ------- (w, h) Width and height of the network in chips. Standard SpiNNaker systems are constructed as squarely as possible given the number of boar...
[ "Calculate", "the", "standard", "network", "dimensions", "(", "in", "chips", ")", "for", "a", "full", "torus", "system", "with", "the", "specified", "number", "of", "SpiNN", "-", "5", "boards", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/geometry.py#L238-L278
project-rig/rig
rig/geometry.py
spinn5_eth_coords
def spinn5_eth_coords(width, height, root_x=0, root_y=0): """Generate a list of board coordinates with Ethernet connectivity in a SpiNNaker machine. Specifically, generates the coordinates for the Ethernet connected chips of SpiNN-5 boards arranged in a standard torus topology. .. warning:: ...
python
def spinn5_eth_coords(width, height, root_x=0, root_y=0): """Generate a list of board coordinates with Ethernet connectivity in a SpiNNaker machine. Specifically, generates the coordinates for the Ethernet connected chips of SpiNN-5 boards arranged in a standard torus topology. .. warning:: ...
[ "def", "spinn5_eth_coords", "(", "width", ",", "height", ",", "root_x", "=", "0", ",", "root_y", "=", "0", ")", ":", "# In oddly-shaped machines where chip (0, 0) does not exist, we must offset", "# the coordinates returned in accordance with the root chip's location.", "root_x",...
Generate a list of board coordinates with Ethernet connectivity in a SpiNNaker machine. Specifically, generates the coordinates for the Ethernet connected chips of SpiNN-5 boards arranged in a standard torus topology. .. warning:: In general, applications should use :py:class:`rig.mac...
[ "Generate", "a", "list", "of", "board", "coordinates", "with", "Ethernet", "connectivity", "in", "a", "SpiNNaker", "machine", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/geometry.py#L281-L328
project-rig/rig
rig/geometry.py
spinn5_local_eth_coord
def spinn5_local_eth_coord(x, y, w, h, root_x=0, root_y=0): """Get the coordinates of a chip's local ethernet connected chip. Returns the coordinates of the ethernet connected chip on the same board as the supplied chip. .. note:: This function assumes the system is constructed from SpiNN-5 bo...
python
def spinn5_local_eth_coord(x, y, w, h, root_x=0, root_y=0): """Get the coordinates of a chip's local ethernet connected chip. Returns the coordinates of the ethernet connected chip on the same board as the supplied chip. .. note:: This function assumes the system is constructed from SpiNN-5 bo...
[ "def", "spinn5_local_eth_coord", "(", "x", ",", "y", ",", "w", ",", "h", ",", "root_x", "=", "0", ",", "root_y", "=", "0", ")", ":", "dx", ",", "dy", "=", "SPINN5_ETH_OFFSET", "[", "(", "y", "-", "root_y", ")", "%", "12", "]", "[", "(", "x", ...
Get the coordinates of a chip's local ethernet connected chip. Returns the coordinates of the ethernet connected chip on the same board as the supplied chip. .. note:: This function assumes the system is constructed from SpiNN-5 boards .. warning:: In general, applications should int...
[ "Get", "the", "coordinates", "of", "a", "chip", "s", "local", "ethernet", "connected", "chip", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/geometry.py#L331-L371
project-rig/rig
rig/geometry.py
spinn5_chip_coord
def spinn5_chip_coord(x, y, root_x=0, root_y=0): """Get the coordinates of a chip on its board. Given the coordinates of a chip in a multi-board system, calculates the coordinates of the chip within its board. .. note:: This function assumes the system is constructed from SpiNN-5 boards P...
python
def spinn5_chip_coord(x, y, root_x=0, root_y=0): """Get the coordinates of a chip on its board. Given the coordinates of a chip in a multi-board system, calculates the coordinates of the chip within its board. .. note:: This function assumes the system is constructed from SpiNN-5 boards P...
[ "def", "spinn5_chip_coord", "(", "x", ",", "y", ",", "root_x", "=", "0", ",", "root_y", "=", "0", ")", ":", "dx", ",", "dy", "=", "SPINN5_ETH_OFFSET", "[", "(", "y", "-", "root_y", ")", "%", "12", "]", "[", "(", "x", "-", "root_x", ")", "%", ...
Get the coordinates of a chip on its board. Given the coordinates of a chip in a multi-board system, calculates the coordinates of the chip within its board. .. note:: This function assumes the system is constructed from SpiNN-5 boards Parameters ---------- x, y : int The coor...
[ "Get", "the", "coordinates", "of", "a", "chip", "on", "its", "board", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/geometry.py#L405-L424
project-rig/rig
rig/geometry.py
spinn5_fpga_link
def spinn5_fpga_link(x, y, link, root_x=0, root_y=0): """Get the identity of the FPGA link which corresponds with the supplied link. .. note:: This function assumes the system is constructed from SpiNN-5 boards whose FPGAs are loaded with the SpI/O 'spinnaker_fpgas' image. Parameters ...
python
def spinn5_fpga_link(x, y, link, root_x=0, root_y=0): """Get the identity of the FPGA link which corresponds with the supplied link. .. note:: This function assumes the system is constructed from SpiNN-5 boards whose FPGAs are loaded with the SpI/O 'spinnaker_fpgas' image. Parameters ...
[ "def", "spinn5_fpga_link", "(", "x", ",", "y", ",", "link", ",", "root_x", "=", "0", ",", "root_y", "=", "0", ")", ":", "x", ",", "y", "=", "spinn5_chip_coord", "(", "x", ",", "y", ",", "root_x", ",", "root_y", ")", "return", "SPINN5_FPGA_LINKS", "...
Get the identity of the FPGA link which corresponds with the supplied link. .. note:: This function assumes the system is constructed from SpiNN-5 boards whose FPGAs are loaded with the SpI/O 'spinnaker_fpgas' image. Parameters ---------- x, y : int The chip whose link is o...
[ "Get", "the", "identity", "of", "the", "FPGA", "link", "which", "corresponds", "with", "the", "supplied", "link", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/geometry.py#L427-L463
Metatab/metapack
metapack/package/csv.py
CsvPackageBuilder._load_resource
def _load_resource(self, source_r, abs_path=False): """The CSV package has no reseources, so we just need to resolve the URLs to them. Usually, the CSV package is built from a file system ackage on a publically acessible server. """ r = self.doc.resource(source_r.name) r.url = self...
python
def _load_resource(self, source_r, abs_path=False): """The CSV package has no reseources, so we just need to resolve the URLs to them. Usually, the CSV package is built from a file system ackage on a publically acessible server. """ r = self.doc.resource(source_r.name) r.url = self...
[ "def", "_load_resource", "(", "self", ",", "source_r", ",", "abs_path", "=", "False", ")", ":", "r", "=", "self", ".", "doc", ".", "resource", "(", "source_r", ".", "name", ")", "r", ".", "url", "=", "self", ".", "resource_root", ".", "join", "(", ...
The CSV package has no reseources, so we just need to resolve the URLs to them. Usually, the CSV package is built from a file system ackage on a publically acessible server.
[ "The", "CSV", "package", "has", "no", "reseources", "so", "we", "just", "need", "to", "resolve", "the", "URLs", "to", "them", ".", "Usually", "the", "CSV", "package", "is", "built", "from", "a", "file", "system", "ackage", "on", "a", "publically", "acess...
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/csv.py#L51-L57
NicolasLM/spinach
spinach/engine.py
Engine._reset
def _reset(self): """Initialization that must happen before the arbiter is (re)started""" self._arbiter = None self._workers = None self._working_queue = None self._must_stop = threading.Event()
python
def _reset(self): """Initialization that must happen before the arbiter is (re)started""" self._arbiter = None self._workers = None self._working_queue = None self._must_stop = threading.Event()
[ "def", "_reset", "(", "self", ")", ":", "self", ".", "_arbiter", "=", "None", "self", ".", "_workers", "=", "None", "self", ".", "_working_queue", "=", "None", "self", ".", "_must_stop", "=", "threading", ".", "Event", "(", ")" ]
Initialization that must happen before the arbiter is (re)started
[ "Initialization", "that", "must", "happen", "before", "the", "arbiter", "is", "(", "re", ")", "started" ]
train
https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/engine.py#L35-L40
NicolasLM/spinach
spinach/engine.py
Engine.attach_tasks
def attach_tasks(self, tasks: Tasks): """Attach a set of tasks. A task cannot be scheduled or executed before it is attached to an Engine. >>> tasks = Tasks() >>> spin.attach_tasks(tasks) """ if tasks._spin is not None and tasks._spin is not self: lo...
python
def attach_tasks(self, tasks: Tasks): """Attach a set of tasks. A task cannot be scheduled or executed before it is attached to an Engine. >>> tasks = Tasks() >>> spin.attach_tasks(tasks) """ if tasks._spin is not None and tasks._spin is not self: lo...
[ "def", "attach_tasks", "(", "self", ",", "tasks", ":", "Tasks", ")", ":", "if", "tasks", ".", "_spin", "is", "not", "None", "and", "tasks", ".", "_spin", "is", "not", "self", ":", "logger", ".", "warning", "(", "'Tasks already attached to a different Engine'...
Attach a set of tasks. A task cannot be scheduled or executed before it is attached to an Engine. >>> tasks = Tasks() >>> spin.attach_tasks(tasks)
[ "Attach", "a", "set", "of", "tasks", "." ]
train
https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/engine.py#L47-L59
NicolasLM/spinach
spinach/engine.py
Engine.schedule_at
def schedule_at(self, task: Schedulable, at: datetime, *args, **kwargs): """Schedule a job to be executed in the future. :arg task: the task or its name to execute in the background :arg at: date at which the job should start. It is advised to pass a timezone aware datetime to ...
python
def schedule_at(self, task: Schedulable, at: datetime, *args, **kwargs): """Schedule a job to be executed in the future. :arg task: the task or its name to execute in the background :arg at: date at which the job should start. It is advised to pass a timezone aware datetime to ...
[ "def", "schedule_at", "(", "self", ",", "task", ":", "Schedulable", ",", "at", ":", "datetime", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "task", "=", "self", ".", "_tasks", ".", "get", "(", "task", ")", "job", "=", "Job", "(", "task",...
Schedule a job to be executed in the future. :arg task: the task or its name to execute in the background :arg at: date at which the job should start. It is advised to pass a timezone aware datetime to lift any ambiguity. However if a timezone naive datetime if given, ...
[ "Schedule", "a", "job", "to", "be", "executed", "in", "the", "future", "." ]
train
https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/engine.py#L74-L88
NicolasLM/spinach
spinach/engine.py
Engine.schedule_batch
def schedule_batch(self, batch: Batch): """Schedule many jobs at once. Scheduling jobs in batches allows to enqueue them fast by avoiding round-trips to the broker. :arg batch: :class:`Batch` instance containing jobs to schedule """ jobs = list() for task, at, a...
python
def schedule_batch(self, batch: Batch): """Schedule many jobs at once. Scheduling jobs in batches allows to enqueue them fast by avoiding round-trips to the broker. :arg batch: :class:`Batch` instance containing jobs to schedule """ jobs = list() for task, at, a...
[ "def", "schedule_batch", "(", "self", ",", "batch", ":", "Batch", ")", ":", "jobs", "=", "list", "(", ")", "for", "task", ",", "at", ",", "args", ",", "kwargs", "in", "batch", ".", "jobs_to_create", ":", "task", "=", "self", ".", "_tasks", ".", "ge...
Schedule many jobs at once. Scheduling jobs in batches allows to enqueue them fast by avoiding round-trips to the broker. :arg batch: :class:`Batch` instance containing jobs to schedule
[ "Schedule", "many", "jobs", "at", "once", "." ]
train
https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/engine.py#L90-L105
NicolasLM/spinach
spinach/engine.py
Engine.start_workers
def start_workers(self, number: int=DEFAULT_WORKER_NUMBER, queue=DEFAULT_QUEUE, block=True, stop_when_queue_empty=False): """Start the worker threads. :arg number: number of worker threads to launch :arg queue: name of the queue to consume, see :doc:`...
python
def start_workers(self, number: int=DEFAULT_WORKER_NUMBER, queue=DEFAULT_QUEUE, block=True, stop_when_queue_empty=False): """Start the worker threads. :arg number: number of worker threads to launch :arg queue: name of the queue to consume, see :doc:`...
[ "def", "start_workers", "(", "self", ",", "number", ":", "int", "=", "DEFAULT_WORKER_NUMBER", ",", "queue", "=", "DEFAULT_QUEUE", ",", "block", "=", "True", ",", "stop_when_queue_empty", "=", "False", ")", ":", "if", "self", ".", "_arbiter", "or", "self", ...
Start the worker threads. :arg number: number of worker threads to launch :arg queue: name of the queue to consume, see :doc:`queues` :arg block: whether to block the calling thread until a signal arrives and workers get terminated :arg stop_when_queue_empty: automatically ...
[ "Start", "the", "worker", "threads", "." ]
train
https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/engine.py#L148-L207
NicolasLM/spinach
spinach/engine.py
Engine.stop_workers
def stop_workers(self, _join_arbiter=True): """Stop the workers and wait for them to terminate.""" # _join_arbiter is used internally when the arbiter is shutting down # the full engine itself. This is because the arbiter thread cannot # join itself. self._must_stop.set() ...
python
def stop_workers(self, _join_arbiter=True): """Stop the workers and wait for them to terminate.""" # _join_arbiter is used internally when the arbiter is shutting down # the full engine itself. This is because the arbiter thread cannot # join itself. self._must_stop.set() ...
[ "def", "stop_workers", "(", "self", ",", "_join_arbiter", "=", "True", ")", ":", "# _join_arbiter is used internally when the arbiter is shutting down", "# the full engine itself. This is because the arbiter thread cannot", "# join itself.", "self", ".", "_must_stop", ".", "set", ...
Stop the workers and wait for them to terminate.
[ "Stop", "the", "workers", "and", "wait", "for", "them", "to", "terminate", "." ]
train
https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/engine.py#L209-L220
openstack/networking-hyperv
networking_hyperv/neutron/trunk_driver.py
HyperVTrunkDriver.handle_trunks
def handle_trunks(self, trunks, event_type): """Trunk data model change from the server.""" LOG.debug("Trunks event received: %(event_type)s. Trunks: %(trunks)s", {'event_type': event_type, 'trunks': trunks}) if event_type == events.DELETED: # The port trunks have...
python
def handle_trunks(self, trunks, event_type): """Trunk data model change from the server.""" LOG.debug("Trunks event received: %(event_type)s. Trunks: %(trunks)s", {'event_type': event_type, 'trunks': trunks}) if event_type == events.DELETED: # The port trunks have...
[ "def", "handle_trunks", "(", "self", ",", "trunks", ",", "event_type", ")", ":", "LOG", ".", "debug", "(", "\"Trunks event received: %(event_type)s. Trunks: %(trunks)s\"", ",", "{", "'event_type'", ":", "event_type", ",", "'trunks'", ":", "trunks", "}", ")", "if",...
Trunk data model change from the server.
[ "Trunk", "data", "model", "change", "from", "the", "server", "." ]
train
https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/trunk_driver.py#L46-L59
openstack/networking-hyperv
networking_hyperv/neutron/trunk_driver.py
HyperVTrunkDriver.handle_subports
def handle_subports(self, subports, event_type): """Subport data model change from the server.""" LOG.debug("Subports event received: %(event_type)s. " "Subports: %(subports)s", {'event_type': event_type, 'subports': subports}) # update the cache. if...
python
def handle_subports(self, subports, event_type): """Subport data model change from the server.""" LOG.debug("Subports event received: %(event_type)s. " "Subports: %(subports)s", {'event_type': event_type, 'subports': subports}) # update the cache. if...
[ "def", "handle_subports", "(", "self", ",", "subports", ",", "event_type", ")", ":", "LOG", ".", "debug", "(", "\"Subports event received: %(event_type)s. \"", "\"Subports: %(subports)s\"", ",", "{", "'event_type'", ":", "event_type", ",", "'subports'", ":", "subports...
Subport data model change from the server.
[ "Subport", "data", "model", "change", "from", "the", "server", "." ]
train
https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/trunk_driver.py#L61-L85
openstack/networking-hyperv
networking_hyperv/neutron/trunk_driver.py
HyperVTrunkDriver._setup_trunk
def _setup_trunk(self, trunk, vlan_id=None): """Sets up VLAN trunk and updates the trunk status.""" LOG.info('Binding trunk port: %s.', trunk) try: # bind sub_ports to host. self._trunk_rpc.update_subport_bindings(self._context, ...
python
def _setup_trunk(self, trunk, vlan_id=None): """Sets up VLAN trunk and updates the trunk status.""" LOG.info('Binding trunk port: %s.', trunk) try: # bind sub_ports to host. self._trunk_rpc.update_subport_bindings(self._context, ...
[ "def", "_setup_trunk", "(", "self", ",", "trunk", ",", "vlan_id", "=", "None", ")", ":", "LOG", ".", "info", "(", "'Binding trunk port: %s.'", ",", "trunk", ")", "try", ":", "# bind sub_ports to host.", "self", ".", "_trunk_rpc", ".", "update_subport_bindings", ...
Sets up VLAN trunk and updates the trunk status.
[ "Sets", "up", "VLAN", "trunk", "and", "updates", "the", "trunk", "status", "." ]
train
https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/trunk_driver.py#L115-L133
openstack/networking-hyperv
networking_hyperv/neutron/agent/hnv_metadata_agent.py
main
def main(): """The entry point for neutron-hnv-metadata-proxy.""" register_config_opts() common_config.init(sys.argv[1:]) neutron_config.setup_logging() proxy = MetadataProxy() proxy.run()
python
def main(): """The entry point for neutron-hnv-metadata-proxy.""" register_config_opts() common_config.init(sys.argv[1:]) neutron_config.setup_logging() proxy = MetadataProxy() proxy.run()
[ "def", "main", "(", ")", ":", "register_config_opts", "(", ")", "common_config", ".", "init", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "neutron_config", ".", "setup_logging", "(", ")", "proxy", "=", "MetadataProxy", "(", ")", "proxy", ".", "ru...
The entry point for neutron-hnv-metadata-proxy.
[ "The", "entry", "point", "for", "neutron", "-", "hnv", "-", "metadata", "-", "proxy", "." ]
train
https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/hnv_metadata_agent.py#L227-L233
openstack/networking-hyperv
networking_hyperv/neutron/agent/hnv_metadata_agent.py
_MetadataProxyHandler._get_port_profile_id
def _get_port_profile_id(self, request): """Get the port profile ID from the request path.""" # Note(alexcoman): The port profile ID can be found as suffix # in request path. port_profile_id = request.path.split("/")[-1].strip() if uuidutils.is_uuid_like(port_profile_id): ...
python
def _get_port_profile_id(self, request): """Get the port profile ID from the request path.""" # Note(alexcoman): The port profile ID can be found as suffix # in request path. port_profile_id = request.path.split("/")[-1].strip() if uuidutils.is_uuid_like(port_profile_id): ...
[ "def", "_get_port_profile_id", "(", "self", ",", "request", ")", ":", "# Note(alexcoman): The port profile ID can be found as suffix", "# in request path.", "port_profile_id", "=", "request", ".", "path", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", ".", "st...
Get the port profile ID from the request path.
[ "Get", "the", "port", "profile", "ID", "from", "the", "request", "path", "." ]
train
https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/hnv_metadata_agent.py#L63-L74
openstack/networking-hyperv
networking_hyperv/neutron/agent/hnv_metadata_agent.py
MetadataProxy._setup_rpc
def _setup_rpc(self): """Setup the RPC client for the current agent.""" self._state_rpc = agent_rpc.PluginReportStateAPI(topics.REPORTS) report_interval = CONF.AGENT.report_interval if report_interval: heartbeat = loopingcall.FixedIntervalLoopingCall( self._re...
python
def _setup_rpc(self): """Setup the RPC client for the current agent.""" self._state_rpc = agent_rpc.PluginReportStateAPI(topics.REPORTS) report_interval = CONF.AGENT.report_interval if report_interval: heartbeat = loopingcall.FixedIntervalLoopingCall( self._re...
[ "def", "_setup_rpc", "(", "self", ")", ":", "self", ".", "_state_rpc", "=", "agent_rpc", ".", "PluginReportStateAPI", "(", "topics", ".", "REPORTS", ")", "report_interval", "=", "CONF", ".", "AGENT", ".", "report_interval", "if", "report_interval", ":", "heart...
Setup the RPC client for the current agent.
[ "Setup", "the", "RPC", "client", "for", "the", "current", "agent", "." ]
train
https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/hnv_metadata_agent.py#L186-L193
openstack/networking-hyperv
networking_hyperv/neutron/agent/hnv_metadata_agent.py
MetadataProxy._work
def _work(self): """Start the neutron-hnv-metadata-proxy agent.""" server = wsgi.Server( name=self._AGENT_BINARY, num_threads=CONF.AGENT.worker_count) server.start( application=_MetadataProxyHandler(), port=CONF.bind_port, host=CONF.bin...
python
def _work(self): """Start the neutron-hnv-metadata-proxy agent.""" server = wsgi.Server( name=self._AGENT_BINARY, num_threads=CONF.AGENT.worker_count) server.start( application=_MetadataProxyHandler(), port=CONF.bind_port, host=CONF.bin...
[ "def", "_work", "(", "self", ")", ":", "server", "=", "wsgi", ".", "Server", "(", "name", "=", "self", ".", "_AGENT_BINARY", ",", "num_threads", "=", "CONF", ".", "AGENT", ".", "worker_count", ")", "server", ".", "start", "(", "application", "=", "_Met...
Start the neutron-hnv-metadata-proxy agent.
[ "Start", "the", "neutron", "-", "hnv", "-", "metadata", "-", "proxy", "agent", "." ]
train
https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/hnv_metadata_agent.py#L202-L211
Microsoft/vsts-cd-manager
vsts_cd_manager/continuous_delivery_manager.py
ContinuousDeliveryManager.set_azure_web_info
def set_azure_web_info(self, resource_group_name, website_name, credentials, subscription_id, subscription_name, tenant_id, webapp_location): """ Call this method before attempting to setup continuous delivery to setup the azure settings :param resource_group_name: ...
python
def set_azure_web_info(self, resource_group_name, website_name, credentials, subscription_id, subscription_name, tenant_id, webapp_location): """ Call this method before attempting to setup continuous delivery to setup the azure settings :param resource_group_name: ...
[ "def", "set_azure_web_info", "(", "self", ",", "resource_group_name", ",", "website_name", ",", "credentials", ",", "subscription_id", ",", "subscription_name", ",", "tenant_id", ",", "webapp_location", ")", ":", "self", ".", "_azure_info", ".", "resource_group_name",...
Call this method before attempting to setup continuous delivery to setup the azure settings :param resource_group_name: :param website_name: :param credentials: :param subscription_id: :param subscription_name: :param tenant_id: :param webapp_location: :re...
[ "Call", "this", "method", "before", "attempting", "to", "setup", "continuous", "delivery", "to", "setup", "the", "azure", "settings", ":", "param", "resource_group_name", ":", ":", "param", "website_name", ":", ":", "param", "credentials", ":", ":", "param", "...
train
https://github.com/Microsoft/vsts-cd-manager/blob/2649d236be94d119b13e0ac607964c94a9e51fde/vsts_cd_manager/continuous_delivery_manager.py#L42-L61
Microsoft/vsts-cd-manager
vsts_cd_manager/continuous_delivery_manager.py
ContinuousDeliveryManager.set_repository_info
def set_repository_info(self, repo_url, branch, git_token, private_repo_username, private_repo_password): """ Call this method before attempting to setup continuous delivery to setup the source control settings :param repo_url: URL of the code repo :param branch: repo branch :par...
python
def set_repository_info(self, repo_url, branch, git_token, private_repo_username, private_repo_password): """ Call this method before attempting to setup continuous delivery to setup the source control settings :param repo_url: URL of the code repo :param branch: repo branch :par...
[ "def", "set_repository_info", "(", "self", ",", "repo_url", ",", "branch", ",", "git_token", ",", "private_repo_username", ",", "private_repo_password", ")", ":", "self", ".", "_repo_info", ".", "url", "=", "repo_url", "self", ".", "_repo_info", ".", "branch", ...
Call this method before attempting to setup continuous delivery to setup the source control settings :param repo_url: URL of the code repo :param branch: repo branch :param git_token: git token :param private_repo_username: private repo username :param private_repo_password: priv...
[ "Call", "this", "method", "before", "attempting", "to", "setup", "continuous", "delivery", "to", "setup", "the", "source", "control", "settings", ":", "param", "repo_url", ":", "URL", "of", "the", "code", "repo", ":", "param", "branch", ":", "repo", "branch"...
train
https://github.com/Microsoft/vsts-cd-manager/blob/2649d236be94d119b13e0ac607964c94a9e51fde/vsts_cd_manager/continuous_delivery_manager.py#L63-L77
Microsoft/vsts-cd-manager
vsts_cd_manager/continuous_delivery_manager.py
ContinuousDeliveryManager.setup_continuous_delivery
def setup_continuous_delivery(self, swap_with_slot, app_type_details, cd_project_url, create_account, vsts_app_auth_token, test, webapp_list): """ Use this method to setup Continuous Delivery of an Azure web site from a source control repository. :param swap_wit...
python
def setup_continuous_delivery(self, swap_with_slot, app_type_details, cd_project_url, create_account, vsts_app_auth_token, test, webapp_list): """ Use this method to setup Continuous Delivery of an Azure web site from a source control repository. :param swap_wit...
[ "def", "setup_continuous_delivery", "(", "self", ",", "swap_with_slot", ",", "app_type_details", ",", "cd_project_url", ",", "create_account", ",", "vsts_app_auth_token", ",", "test", ",", "webapp_list", ")", ":", "branch", "=", "self", ".", "_repo_info", ".", "br...
Use this method to setup Continuous Delivery of an Azure web site from a source control repository. :param swap_with_slot: the slot to use for deployment :param app_type_details: the details of app that will be deployed. i.e. app_type = Python, python_framework = Django etc. :param cd_project_ur...
[ "Use", "this", "method", "to", "setup", "Continuous", "Delivery", "of", "an", "Azure", "web", "site", "from", "a", "source", "control", "repository", ".", ":", "param", "swap_with_slot", ":", "the", "slot", "to", "use", "for", "deployment", ":", "param", "...
train
https://github.com/Microsoft/vsts-cd-manager/blob/2649d236be94d119b13e0ac607964c94a9e51fde/vsts_cd_manager/continuous_delivery_manager.py#L87-L139
project-rig/rig
rig/place_and_route/route/utils.py
longest_dimension_first
def longest_dimension_first(vector, start=(0, 0), width=None, height=None): """List the (x, y) steps on a longest-dimension first route. Note that when multiple dimensions are the same magnitude, one will be chosen at random with uniform probability. Parameters ---------- vector : (x, y, z) ...
python
def longest_dimension_first(vector, start=(0, 0), width=None, height=None): """List the (x, y) steps on a longest-dimension first route. Note that when multiple dimensions are the same magnitude, one will be chosen at random with uniform probability. Parameters ---------- vector : (x, y, z) ...
[ "def", "longest_dimension_first", "(", "vector", ",", "start", "=", "(", "0", ",", "0", ")", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "x", ",", "y", "=", "start", "out", "=", "[", "]", "for", "dimension", ",", "magnitude", ...
List the (x, y) steps on a longest-dimension first route. Note that when multiple dimensions are the same magnitude, one will be chosen at random with uniform probability. Parameters ---------- vector : (x, y, z) The vector which the path should cover. start : (x, y) The coordi...
[ "List", "the", "(", "x", "y", ")", "steps", "on", "a", "longest", "-", "dimension", "first", "route", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/route/utils.py#L9-L73
project-rig/rig
rig/place_and_route/route/utils.py
links_between
def links_between(a, b, machine): """Get the set of working links connecting chips a and b. Parameters ---------- a : (x, y) b : (x, y) machine : :py:class:`~rig.place_and_route.Machine` Returns ------- set([:py:class:`~rig.links.Links`, ...]) """ ax, ay = a bx, by = b ...
python
def links_between(a, b, machine): """Get the set of working links connecting chips a and b. Parameters ---------- a : (x, y) b : (x, y) machine : :py:class:`~rig.place_and_route.Machine` Returns ------- set([:py:class:`~rig.links.Links`, ...]) """ ax, ay = a bx, by = b ...
[ "def", "links_between", "(", "a", ",", "b", ",", "machine", ")", ":", "ax", ",", "ay", "=", "a", "bx", ",", "by", "=", "b", "return", "set", "(", "link", "for", "link", ",", "(", "dx", ",", "dy", ")", "in", "(", "(", "l", ",", "l", ".", "...
Get the set of working links connecting chips a and b. Parameters ---------- a : (x, y) b : (x, y) machine : :py:class:`~rig.place_and_route.Machine` Returns ------- set([:py:class:`~rig.links.Links`, ...])
[ "Get", "the", "set", "of", "working", "links", "connecting", "chips", "a", "and", "b", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/route/utils.py#L76-L94
Metatab/metapack
metapack/package/s3.py
set_s3_profile
def set_s3_profile(profile_name): """Load the credentials for an s3 profile into environmental variables""" import os session = boto3.Session(profile_name=profile_name) os.environ['AWS_ACCESS_KEY_ID'] = session.get_credentials().access_key os.environ['AWS_SECRET_ACCESS_KEY'] = session.get_credenti...
python
def set_s3_profile(profile_name): """Load the credentials for an s3 profile into environmental variables""" import os session = boto3.Session(profile_name=profile_name) os.environ['AWS_ACCESS_KEY_ID'] = session.get_credentials().access_key os.environ['AWS_SECRET_ACCESS_KEY'] = session.get_credenti...
[ "def", "set_s3_profile", "(", "profile_name", ")", ":", "import", "os", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "profile_name", ")", "os", ".", "environ", "[", "'AWS_ACCESS_KEY_ID'", "]", "=", "session", ".", "get_credentials", "(", ...
Load the credentials for an s3 profile into environmental variables
[ "Load", "the", "credentials", "for", "an", "s3", "profile", "into", "environmental", "variables" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/s3.py#L158-L165
NeuroML/NeuroMLlite
neuromllite/utils.py
create_new_model
def create_new_model(reference, duration, dt=0.025, # ms temperature=6.3, # degC default_region=None, parameters = None, cell_for_default_population=None, color_for_defaul...
python
def create_new_model(reference, duration, dt=0.025, # ms temperature=6.3, # degC default_region=None, parameters = None, cell_for_default_population=None, color_for_defaul...
[ "def", "create_new_model", "(", "reference", ",", "duration", ",", "dt", "=", "0.025", ",", "# ms ", "temperature", "=", "6.3", ",", "# degC", "default_region", "=", "None", ",", "parameters", "=", "None", ",", "cell_for_default_population", "=", "None", ",", ...
net.projections.append(Projection(id='proj0', presynaptic=p0.id, postsynaptic=p1.id, synapse='ampa')) net.projections[0].random_connectivity=RandomConnectivity(probability=0.5)
[ "net", ".", "projections", ".", "append", "(", "Projection", "(", "id", "=", "proj0", "presynaptic", "=", "p0", ".", "id", "postsynaptic", "=", "p1", ".", "id", "synapse", "=", "ampa", "))" ]
train
https://github.com/NeuroML/NeuroMLlite/blob/f3fa2ff662e40febfa97c045e7f0e6915ad04161/neuromllite/utils.py#L120-L241
NicolasLM/spinach
spinach/signals.py
SafeNamedSignal.send
def send(self, *sender, **kwargs): """Emit this signal on behalf of `sender`, passing on kwargs. This is an extension of `Signal.send` that changes one thing: Exceptions raised in calling the receiver are logged but do not fail """ if len(sender) == 0: sender = None ...
python
def send(self, *sender, **kwargs): """Emit this signal on behalf of `sender`, passing on kwargs. This is an extension of `Signal.send` that changes one thing: Exceptions raised in calling the receiver are logged but do not fail """ if len(sender) == 0: sender = None ...
[ "def", "send", "(", "self", ",", "*", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "sender", ")", "==", "0", ":", "sender", "=", "None", "elif", "len", "(", "sender", ")", ">", "1", ":", "raise", "TypeError", "(", "'send() accep...
Emit this signal on behalf of `sender`, passing on kwargs. This is an extension of `Signal.send` that changes one thing: Exceptions raised in calling the receiver are logged but do not fail
[ "Emit", "this", "signal", "on", "behalf", "of", "sender", "passing", "on", "kwargs", "." ]
train
https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/signals.py#L16-L40
Metatab/metapack
metapack/jupyter/exporters.py
DocumentationExporter.update_metatab
def update_metatab(self, doc, resources): """Add documentation entries for resources""" if not 'Documentation' in doc: doc.new_section("Documentation") ds = doc['Documentation'] if not 'Name' in ds.args: ds.add_arg('Name', prepend=True) # This is the ...
python
def update_metatab(self, doc, resources): """Add documentation entries for resources""" if not 'Documentation' in doc: doc.new_section("Documentation") ds = doc['Documentation'] if not 'Name' in ds.args: ds.add_arg('Name', prepend=True) # This is the ...
[ "def", "update_metatab", "(", "self", ",", "doc", ",", "resources", ")", ":", "if", "not", "'Documentation'", "in", "doc", ":", "doc", ".", "new_section", "(", "\"Documentation\"", ")", "ds", "=", "doc", "[", "'Documentation'", "]", "if", "not", "'Name'", ...
Add documentation entries for resources
[ "Add", "documentation", "entries", "for", "resources" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/exporters.py#L187-L218
Metatab/metapack
metapack/jupyter/exporters.py
NotebookExecutor.get_package_dir_name
def get_package_dir_name(self, nb): """This is the name of the package we will be creating. """ package_dir = self.package_dir if not package_dir: package_dir = getcwd() package_name = self.package_name if not package_name: doc = ExtractInlineMetatabDo...
python
def get_package_dir_name(self, nb): """This is the name of the package we will be creating. """ package_dir = self.package_dir if not package_dir: package_dir = getcwd() package_name = self.package_name if not package_name: doc = ExtractInlineMetatabDo...
[ "def", "get_package_dir_name", "(", "self", ",", "nb", ")", ":", "package_dir", "=", "self", ".", "package_dir", "if", "not", "package_dir", ":", "package_dir", "=", "getcwd", "(", ")", "package_name", "=", "self", ".", "package_name", "if", "not", "package_...
This is the name of the package we will be creating.
[ "This", "is", "the", "name", "of", "the", "package", "we", "will", "be", "creating", "." ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/exporters.py#L248-L271
Metatab/metapack
metapack/jupyter/exporters.py
NotebookExecutor.get_output_dir
def get_output_dir(self, nb): """Open a notebook and determine the output directory from the name""" self.package_dir, self.package_name = self.get_package_dir_name(nb) return join(self.package_dir, self.package_name)
python
def get_output_dir(self, nb): """Open a notebook and determine the output directory from the name""" self.package_dir, self.package_name = self.get_package_dir_name(nb) return join(self.package_dir, self.package_name)
[ "def", "get_output_dir", "(", "self", ",", "nb", ")", ":", "self", ".", "package_dir", ",", "self", ".", "package_name", "=", "self", ".", "get_package_dir_name", "(", "nb", ")", "return", "join", "(", "self", ".", "package_dir", ",", "self", ".", "packa...
Open a notebook and determine the output directory from the name
[ "Open", "a", "notebook", "and", "determine", "the", "output", "directory", "from", "the", "name" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/exporters.py#L273-L277
Metatab/metapack
metapack/jupyter/exporters.py
NotebookExecutor.extract_terms
def extract_terms(self, nb): """Extract some term values, usually set with tags or metadata""" emt = ExtractMetatabTerms() emt.preprocess(nb, {}) return emt.terms
python
def extract_terms(self, nb): """Extract some term values, usually set with tags or metadata""" emt = ExtractMetatabTerms() emt.preprocess(nb, {}) return emt.terms
[ "def", "extract_terms", "(", "self", ",", "nb", ")", ":", "emt", "=", "ExtractMetatabTerms", "(", ")", "emt", ".", "preprocess", "(", "nb", ",", "{", "}", ")", "return", "emt", ".", "terms" ]
Extract some term values, usually set with tags or metadata
[ "Extract", "some", "term", "values", "usually", "set", "with", "tags", "or", "metadata" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/exporters.py#L279-L284
Metatab/metapack
metapack/jupyter/exporters.py
NotebookExecutor.from_notebook_node
def from_notebook_node(self, nb, resources=None, **kw): """Create a Metatab package from a notebook node """ nb_copy = copy.deepcopy(nb) # The the package name and directory, either from the inlined Metatab doc, # or from the config try: self.output_dir = self.get_...
python
def from_notebook_node(self, nb, resources=None, **kw): """Create a Metatab package from a notebook node """ nb_copy = copy.deepcopy(nb) # The the package name and directory, either from the inlined Metatab doc, # or from the config try: self.output_dir = self.get_...
[ "def", "from_notebook_node", "(", "self", ",", "nb", ",", "resources", "=", "None", ",", "*", "*", "kw", ")", ":", "nb_copy", "=", "copy", ".", "deepcopy", "(", "nb", ")", "# The the package name and directory, either from the inlined Metatab doc,", "# or from the c...
Create a Metatab package from a notebook node
[ "Create", "a", "Metatab", "package", "from", "a", "notebook", "node" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/exporters.py#L292-L347
Metatab/metapack
metapack/jupyter/exporters.py
HugoOutputExtractor.preprocess_cell
def preprocess_cell(self, cell, resources, cell_index): """Also extracts attachments""" from nbformat.notebooknode import NotebookNode attach_names = [] # Just move the attachment into an output for k, attach in cell.get('attachments', {}).items(): for mime_type in...
python
def preprocess_cell(self, cell, resources, cell_index): """Also extracts attachments""" from nbformat.notebooknode import NotebookNode attach_names = [] # Just move the attachment into an output for k, attach in cell.get('attachments', {}).items(): for mime_type in...
[ "def", "preprocess_cell", "(", "self", ",", "cell", ",", "resources", ",", "cell_index", ")", ":", "from", "nbformat", ".", "notebooknode", "import", "NotebookNode", "attach_names", "=", "[", "]", "# Just move the attachment into an output", "for", "k", ",", "atta...
Also extracts attachments
[ "Also", "extracts", "attachments" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/exporters.py#L385-L427
project-rig/rig
rig/place_and_route/place/hilbert.py
hilbert
def hilbert(level, angle=1, s=None): """Generator of points along a 2D Hilbert curve. This implements the L-system as described on `http://en.wikipedia.org/wiki/Hilbert_curve`. Parameters ---------- level : int Number of levels of recursion to use in generating the curve. The r...
python
def hilbert(level, angle=1, s=None): """Generator of points along a 2D Hilbert curve. This implements the L-system as described on `http://en.wikipedia.org/wiki/Hilbert_curve`. Parameters ---------- level : int Number of levels of recursion to use in generating the curve. The r...
[ "def", "hilbert", "(", "level", ",", "angle", "=", "1", ",", "s", "=", "None", ")", ":", "# An internal (mutable) state object (note: used in place of a closure with", "# nonlocal variables for Python 2 support).", "class", "HilbertState", "(", "object", ")", ":", "def", ...
Generator of points along a 2D Hilbert curve. This implements the L-system as described on `http://en.wikipedia.org/wiki/Hilbert_curve`. Parameters ---------- level : int Number of levels of recursion to use in generating the curve. The resulting curve will be `(2**level)-1` wide/t...
[ "Generator", "of", "points", "along", "a", "2D", "Hilbert", "curve", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/hilbert.py#L10-L80
project-rig/rig
rig/place_and_route/place/hilbert.py
hilbert_chip_order
def hilbert_chip_order(machine): """A generator which iterates over a set of chips in a machine in a hilbert path. For use as a chip ordering for the sequential placer. """ max_dimen = max(machine.width, machine.height) hilbert_levels = int(ceil(log(max_dimen, 2.0))) if max_dimen >= 1 else 0 ...
python
def hilbert_chip_order(machine): """A generator which iterates over a set of chips in a machine in a hilbert path. For use as a chip ordering for the sequential placer. """ max_dimen = max(machine.width, machine.height) hilbert_levels = int(ceil(log(max_dimen, 2.0))) if max_dimen >= 1 else 0 ...
[ "def", "hilbert_chip_order", "(", "machine", ")", ":", "max_dimen", "=", "max", "(", "machine", ".", "width", ",", "machine", ".", "height", ")", "hilbert_levels", "=", "int", "(", "ceil", "(", "log", "(", "max_dimen", ",", "2.0", ")", ")", ")", "if", ...
A generator which iterates over a set of chips in a machine in a hilbert path. For use as a chip ordering for the sequential placer.
[ "A", "generator", "which", "iterates", "over", "a", "set", "of", "chips", "in", "a", "machine", "in", "a", "hilbert", "path", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/hilbert.py#L83-L91
project-rig/rig
rig/place_and_route/place/hilbert.py
place
def place(vertices_resources, nets, machine, constraints, breadth_first=True): """Places vertices in breadth-first order along a hilbert-curve path through the chips in the machine. This is a thin wrapper around the :py:func:`sequential <rig.place_and_route.place.sequential.place>` placement algorithm ...
python
def place(vertices_resources, nets, machine, constraints, breadth_first=True): """Places vertices in breadth-first order along a hilbert-curve path through the chips in the machine. This is a thin wrapper around the :py:func:`sequential <rig.place_and_route.place.sequential.place>` placement algorithm ...
[ "def", "place", "(", "vertices_resources", ",", "nets", ",", "machine", ",", "constraints", ",", "breadth_first", "=", "True", ")", ":", "return", "sequential_place", "(", "vertices_resources", ",", "nets", ",", "machine", ",", "constraints", ",", "(", "None",...
Places vertices in breadth-first order along a hilbert-curve path through the chips in the machine. This is a thin wrapper around the :py:func:`sequential <rig.place_and_route.place.sequential.place>` placement algorithm which optionally uses the :py:func:`breadth_first_vertex_order` vertex ordering ...
[ "Places", "vertices", "in", "breadth", "-", "first", "order", "along", "a", "hilbert", "-", "curve", "path", "through", "the", "chips", "in", "the", "machine", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/hilbert.py#L94-L115
project-rig/rig
rig/routing_table/minimise.py
minimise_tables
def minimise_tables(routing_tables, target_lengths, methods=(remove_default_entries, ordered_covering)): """Utility function which attempts to minimises routing tables for multiple chips. For each routing table supplied, this function will attempt to use the minimisation algorithms ...
python
def minimise_tables(routing_tables, target_lengths, methods=(remove_default_entries, ordered_covering)): """Utility function which attempts to minimises routing tables for multiple chips. For each routing table supplied, this function will attempt to use the minimisation algorithms ...
[ "def", "minimise_tables", "(", "routing_tables", ",", "target_lengths", ",", "methods", "=", "(", "remove_default_entries", ",", "ordered_covering", ")", ")", ":", "# Coerce the target lengths into the correct forms", "if", "not", "isinstance", "(", "target_lengths", ",",...
Utility function which attempts to minimises routing tables for multiple chips. For each routing table supplied, this function will attempt to use the minimisation algorithms given (or some sensible default algorithms), trying each sequentially until a target number of routing entries has been reac...
[ "Utility", "function", "which", "attempts", "to", "minimises", "routing", "tables", "for", "multiple", "chips", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/minimise.py#L9-L71
project-rig/rig
rig/routing_table/minimise.py
minimise_table
def minimise_table(table, target_length, methods=(remove_default_entries, ordered_covering)): """Apply different minimisation algorithms to minimise a single routing table. Parameters ---------- table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...] Routing table...
python
def minimise_table(table, target_length, methods=(remove_default_entries, ordered_covering)): """Apply different minimisation algorithms to minimise a single routing table. Parameters ---------- table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...] Routing table...
[ "def", "minimise_table", "(", "table", ",", "target_length", ",", "methods", "=", "(", "remove_default_entries", ",", "ordered_covering", ")", ")", ":", "# Add a final method which checks the size of the table and returns it if", "# the size is correct. NOTE: This method will avoid...
Apply different minimisation algorithms to minimise a single routing table. Parameters ---------- table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...] Routing table to minimise. NOTE: This is the data structure as returned by :py:meth:`~rig.routing_table.routing_tree_to_tabl...
[ "Apply", "different", "minimisation", "algorithms", "to", "minimise", "a", "single", "routing", "table", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/minimise.py#L74-L132
project-rig/rig
rig/routing_table/minimise.py
_identity
def _identity(table, target_length): """Identity minimisation function.""" if target_length is None or len(table) < target_length: return table raise MinimisationFailedError(target_length, len(table))
python
def _identity(table, target_length): """Identity minimisation function.""" if target_length is None or len(table) < target_length: return table raise MinimisationFailedError(target_length, len(table))
[ "def", "_identity", "(", "table", ",", "target_length", ")", ":", "if", "target_length", "is", "None", "or", "len", "(", "table", ")", "<", "target_length", ":", "return", "table", "raise", "MinimisationFailedError", "(", "target_length", ",", "len", "(", "t...
Identity minimisation function.
[ "Identity", "minimisation", "function", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/routing_table/minimise.py#L135-L139
Metatab/metapack
metapack/cli/metakan.py
configure_ckan
def configure_ckan(m): """Load groups and organizations, from a file in Metatab format""" from ckanapi import RemoteCKAN try: doc = MetapackDoc(m.mt_file, cache=m.cache) except (IOError, MetatabError) as e: err("Failed to open metatab '{}': {}".format(m.mt_file, e)) c = RemoteCKAN(...
python
def configure_ckan(m): """Load groups and organizations, from a file in Metatab format""" from ckanapi import RemoteCKAN try: doc = MetapackDoc(m.mt_file, cache=m.cache) except (IOError, MetatabError) as e: err("Failed to open metatab '{}': {}".format(m.mt_file, e)) c = RemoteCKAN(...
[ "def", "configure_ckan", "(", "m", ")", ":", "from", "ckanapi", "import", "RemoteCKAN", "try", ":", "doc", "=", "MetapackDoc", "(", "m", ".", "mt_file", ",", "cache", "=", "m", ".", "cache", ")", "except", "(", "IOError", ",", "MetatabError", ")", "as"...
Load groups and organizations, from a file in Metatab format
[ "Load", "groups", "and", "organizations", "from", "a", "file", "in", "Metatab", "format" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/metakan.py#L353-L386
Metatab/metapack
metapack/cli/metakan.py
package_load_instructions
def package_load_instructions(inst_distributions): """Load instructions, displayed in the package notes""" per_package_inst = '' for dist in inst_distributions: if dist.type == 'zip': per_package_inst += dedent( """ # Loading the ZIP Package ...
python
def package_load_instructions(inst_distributions): """Load instructions, displayed in the package notes""" per_package_inst = '' for dist in inst_distributions: if dist.type == 'zip': per_package_inst += dedent( """ # Loading the ZIP Package ...
[ "def", "package_load_instructions", "(", "inst_distributions", ")", ":", "per_package_inst", "=", "''", "for", "dist", "in", "inst_distributions", ":", "if", "dist", ".", "type", "==", "'zip'", ":", "per_package_inst", "+=", "dedent", "(", "\"\"\"\n #...
Load instructions, displayed in the package notes
[ "Load", "instructions", "displayed", "in", "the", "package", "notes" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/metakan.py#L403-L440
Metatab/metapack
metapack/cli/metakan.py
dump_ckan
def dump_ckan(m): """Create a groups and organization file""" doc = MetapackDoc(cache=m.cache) doc.new_section('Groups', 'Title Description Id Image_url'.split()) doc.new_section('Organizations', 'Title Description Id Image_url'.split()) c = RemoteCKAN(m.ckan_url, apikey=m.api_key) for...
python
def dump_ckan(m): """Create a groups and organization file""" doc = MetapackDoc(cache=m.cache) doc.new_section('Groups', 'Title Description Id Image_url'.split()) doc.new_section('Organizations', 'Title Description Id Image_url'.split()) c = RemoteCKAN(m.ckan_url, apikey=m.api_key) for...
[ "def", "dump_ckan", "(", "m", ")", ":", "doc", "=", "MetapackDoc", "(", "cache", "=", "m", ".", "cache", ")", "doc", ".", "new_section", "(", "'Groups'", ",", "'Title Description Id Image_url'", ".", "split", "(", ")", ")", "doc", ".", "new_section", "("...
Create a groups and organization file
[ "Create", "a", "groups", "and", "organization", "file" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/metakan.py#L442-L455
Metatab/metapack
metapack/cli/metakan.py
MetapackCliMemo.update_mt_arg
def update_mt_arg(self, metatabfile): """Return a new memo with a new metatabfile argument""" o = MetapackCliMemo(self.args) o.set_mt_arg(metatabfile) return o
python
def update_mt_arg(self, metatabfile): """Return a new memo with a new metatabfile argument""" o = MetapackCliMemo(self.args) o.set_mt_arg(metatabfile) return o
[ "def", "update_mt_arg", "(", "self", ",", "metatabfile", ")", ":", "o", "=", "MetapackCliMemo", "(", "self", ".", "args", ")", "o", ".", "set_mt_arg", "(", "metatabfile", ")", "return", "o" ]
Return a new memo with a new metatabfile argument
[ "Return", "a", "new", "memo", "with", "a", "new", "metatabfile", "argument" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/metakan.py#L45-L49
project-rig/rig
docs/source/conf.py
linkcode_resolve
def linkcode_resolve(domain, info): """Determine the URL corresponding to Python object on GitHub This code is derived from the version used by `Numpy <https://github.com/numpy/numpy/blob/v1.9.2/doc/source/conf.py#L286>`_. """ # Only link to Python source if domain != 'py': return N...
python
def linkcode_resolve(domain, info): """Determine the URL corresponding to Python object on GitHub This code is derived from the version used by `Numpy <https://github.com/numpy/numpy/blob/v1.9.2/doc/source/conf.py#L286>`_. """ # Only link to Python source if domain != 'py': return N...
[ "def", "linkcode_resolve", "(", "domain", ",", "info", ")", ":", "# Only link to Python source", "if", "domain", "!=", "'py'", ":", "return", "None", "# Get a reference to the object in question", "modname", "=", "info", "[", "'module'", "]", "fullname", "=", "info"...
Determine the URL corresponding to Python object on GitHub This code is derived from the version used by `Numpy <https://github.com/numpy/numpy/blob/v1.9.2/doc/source/conf.py#L286>`_.
[ "Determine", "the", "URL", "corresponding", "to", "Python", "object", "on", "GitHub", "This", "code", "is", "derived", "from", "the", "version", "used", "by", "Numpy", "<https", ":", "//", "github", ".", "com", "/", "numpy", "/", "numpy", "/", "blob", "/...
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/docs/source/conf.py#L144-L198
Metatab/metapack
metapack/util.py
declaration_path
def declaration_path(name): """Return the path to an included declaration""" from os.path import dirname, join, exists import metatab.declarations from metatab.exc import IncludeError d = dirname(metatab.declarations.__file__) path = join(d, name) if not exists(path): path = join(...
python
def declaration_path(name): """Return the path to an included declaration""" from os.path import dirname, join, exists import metatab.declarations from metatab.exc import IncludeError d = dirname(metatab.declarations.__file__) path = join(d, name) if not exists(path): path = join(...
[ "def", "declaration_path", "(", "name", ")", ":", "from", "os", ".", "path", "import", "dirname", ",", "join", ",", "exists", "import", "metatab", ".", "declarations", "from", "metatab", ".", "exc", "import", "IncludeError", "d", "=", "dirname", "(", "meta...
Return the path to an included declaration
[ "Return", "the", "path", "to", "an", "included", "declaration" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/util.py#L16-L32
Metatab/metapack
metapack/util.py
flatten
def flatten(d, sep='.'): """Flatten a data structure into tuples""" def _flatten(e, parent_key='', sep='.'): import collections prefix = parent_key + sep if parent_key else '' if isinstance(e, collections.MutableMapping): return tuple((prefix + k2, v2) for k, v in e.items(...
python
def flatten(d, sep='.'): """Flatten a data structure into tuples""" def _flatten(e, parent_key='', sep='.'): import collections prefix = parent_key + sep if parent_key else '' if isinstance(e, collections.MutableMapping): return tuple((prefix + k2, v2) for k, v in e.items(...
[ "def", "flatten", "(", "d", ",", "sep", "=", "'.'", ")", ":", "def", "_flatten", "(", "e", ",", "parent_key", "=", "''", ",", "sep", "=", "'.'", ")", ":", "import", "collections", "prefix", "=", "parent_key", "+", "sep", "if", "parent_key", "else", ...
Flatten a data structure into tuples
[ "Flatten", "a", "data", "structure", "into", "tuples" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/util.py#L59-L74
Metatab/metapack
metapack/util.py
make_dir_structure
def make_dir_structure(base_dir): """Make the build directory structure. """ def maybe_makedir(*args): p = join(base_dir, *args) if exists(p) and not isdir(p): raise IOError("File '{}' exists but is not a directory ".format(p)) if not exists(p): makedirs(p) ...
python
def make_dir_structure(base_dir): """Make the build directory structure. """ def maybe_makedir(*args): p = join(base_dir, *args) if exists(p) and not isdir(p): raise IOError("File '{}' exists but is not a directory ".format(p)) if not exists(p): makedirs(p) ...
[ "def", "make_dir_structure", "(", "base_dir", ")", ":", "def", "maybe_makedir", "(", "*", "args", ")", ":", "p", "=", "join", "(", "base_dir", ",", "*", "args", ")", "if", "exists", "(", "p", ")", "and", "not", "isdir", "(", "p", ")", ":", "raise",...
Make the build directory structure.
[ "Make", "the", "build", "directory", "structure", "." ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/util.py#L89-L104
Metatab/metapack
metapack/util.py
guess_format
def guess_format(url): """Try to guess the format of a resource, possibly with a HEAD request""" import requests from requests.exceptions import InvalidSchema from rowgenerators import parse_url_to_dict parts = parse_url_to_dict(url) # Guess_type fails for root urls like 'http://civicknowledg...
python
def guess_format(url): """Try to guess the format of a resource, possibly with a HEAD request""" import requests from requests.exceptions import InvalidSchema from rowgenerators import parse_url_to_dict parts = parse_url_to_dict(url) # Guess_type fails for root urls like 'http://civicknowledg...
[ "def", "guess_format", "(", "url", ")", ":", "import", "requests", "from", "requests", ".", "exceptions", "import", "InvalidSchema", "from", "rowgenerators", "import", "parse_url_to_dict", "parts", "=", "parse_url_to_dict", "(", "url", ")", "# Guess_type fails for roo...
Try to guess the format of a resource, possibly with a HEAD request
[ "Try", "to", "guess", "the", "format", "of", "a", "resource", "possibly", "with", "a", "HEAD", "request" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/util.py#L202-L229
Metatab/metapack
metapack/util.py
walk_up
def walk_up(bottom): """ mimic os.walk, but walk 'up' instead of down the directory tree :param bottom: :return: """ import os from os import path bottom = path.realpath(bottom) # get files in current dir try: names = os.listdir(bottom) except Exception as e: r...
python
def walk_up(bottom): """ mimic os.walk, but walk 'up' instead of down the directory tree :param bottom: :return: """ import os from os import path bottom = path.realpath(bottom) # get files in current dir try: names = os.listdir(bottom) except Exception as e: r...
[ "def", "walk_up", "(", "bottom", ")", ":", "import", "os", "from", "os", "import", "path", "bottom", "=", "path", ".", "realpath", "(", "bottom", ")", "# get files in current dir", "try", ":", "names", "=", "os", ".", "listdir", "(", "bottom", ")", "exce...
mimic os.walk, but walk 'up' instead of down the directory tree :param bottom: :return:
[ "mimic", "os", ".", "walk", "but", "walk", "up", "instead", "of", "down", "the", "directory", "tree", ":", "param", "bottom", ":", ":", "return", ":" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/util.py#L254-L286
Metatab/metapack
metapack/util.py
get_materialized_data_cache
def get_materialized_data_cache(doc=None): """Return the cache directory where data can be written during a build, usually for a Jupyter notebook that generates many files for each execution""" from metapack.constants import MATERIALIZED_DATA_PREFIX from os.path import join if not doc: fro...
python
def get_materialized_data_cache(doc=None): """Return the cache directory where data can be written during a build, usually for a Jupyter notebook that generates many files for each execution""" from metapack.constants import MATERIALIZED_DATA_PREFIX from os.path import join if not doc: fro...
[ "def", "get_materialized_data_cache", "(", "doc", "=", "None", ")", ":", "from", "metapack", ".", "constants", "import", "MATERIALIZED_DATA_PREFIX", "from", "os", ".", "path", "import", "join", "if", "not", "doc", ":", "from", "metapack", "import", "Downloader",...
Return the cache directory where data can be written during a build, usually for a Jupyter notebook that generates many files for each execution
[ "Return", "the", "cache", "directory", "where", "data", "can", "be", "written", "during", "a", "build", "usually", "for", "a", "Jupyter", "notebook", "that", "generates", "many", "files", "for", "each", "execution" ]
train
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/util.py#L339-L355
project-rig/rig
rig/place_and_route/routing_tree.py
RoutingTree.traverse
def traverse(self): """Traverse the tree yielding the direction taken to a node, the co-ordinates of that node and the directions leading from the Node. Yields ------ (direction, (x, y), {:py:class:`~rig.routing_table.Routes`, ...}) Direction taken to reach a Node in...
python
def traverse(self): """Traverse the tree yielding the direction taken to a node, the co-ordinates of that node and the directions leading from the Node. Yields ------ (direction, (x, y), {:py:class:`~rig.routing_table.Routes`, ...}) Direction taken to reach a Node in...
[ "def", "traverse", "(", "self", ")", ":", "# A queue of (direction, node) to visit. The direction is the Links", "# entry which describes the direction in which we last moved to reach", "# the node (or None for the root).", "to_visit", "=", "deque", "(", "[", "(", "None", ",", "sel...
Traverse the tree yielding the direction taken to a node, the co-ordinates of that node and the directions leading from the Node. Yields ------ (direction, (x, y), {:py:class:`~rig.routing_table.Routes`, ...}) Direction taken to reach a Node in the tree, the (x, y) co-ordina...
[ "Traverse", "the", "tree", "yielding", "the", "direction", "taken", "to", "a", "node", "the", "co", "-", "ordinates", "of", "that", "node", "and", "the", "directions", "leading", "from", "the", "Node", "." ]
train
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/routing_tree.py#L96-L128