text stringlengths 81 112k |
|---|
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 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)
def sqla_datatype_for(datu... |
Prints code (SQL, SQLAlchemy, etc.) to define a table.
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.... |
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)
def generate(args=None, namespace=None, file=None):
"""
Genereate DDL from data source... |
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.
def emit_db_sequence_updates(engine):
"""Set database sequence objects to match the source db
Relevant only when gene... |
Returns SQL to define the table.
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).... |
Dumps Python code to set up the table's SQLAlchemy model
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
constrain... |
Puts a value in proper format for a SQL string
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']
... |
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.
def emit_db_sequence_updates(self):
"""Set database sequence objects to match the source db
Relevant ... |
Combined results of ``.ddl(dialect)`` and, if ``inserts==True``,
``.inserts(dialect)``.
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)``.
... |
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.
def clea... |
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... |
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')
def _id_fieldname(fieldnames, table_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, 'capital', 'provinces')
>>> pprint(parent)
{'capital_name'... |
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... |
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
def suitability_as_key(self, key_name):
"""
Returns: (result, key_type)
``result`` is True, False, or 'absent' or... |
returns a list of header tags
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',... |
Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format
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'] =... |
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 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... |
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')
... |
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
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 princip... |
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
def get_hashes(self, all_hashes = False):
"""
Returns a list of hashes in hashcat-firendly format for tickets with encryption... |
Iterates trough all .kirbi files in a given directory and converts all of them into one CCACHE object
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(director... |
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):
"""
Conve... |
Writes the contents of the CCACHE object to a 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()) |
Prints a formatted table given a 2 dimensional array
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)... |
Returns the encryption key bytes for the enctryption type.
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... |
Credential input format:
<domain>/<username>/<secret_type>:<secret>@<dc_ip_or_hostname>
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.spl... |
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
def run(self, realm, users):
"""
Requests a TGT in the name of the users specified in users.
Returns a l... |
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
def run(self, creds, override_etype = [23]):
"""
Requests TGT tickets for all users specified in the targets list
creds: list : the... |
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
def run(self, targets, override_etype = [2, 3, 16, 23, 17, 18]):
"""
Requests TGS tickets for all service users specified ... |
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... |
<credentials>@<ip_or_hostname>:<port>
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, ... |
Sets up the kerberos object from tgt and the session key.
Use this function when pulling the TGT from ccache file.
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.kerbe... |
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... |
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... |
user_to_impersonate : KerberosTarget class
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... |
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... |
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.
... |
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 ... |
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... |
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),
... ... |
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 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... |
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(), ... |
Test if the ranges covered by a pair of 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) |
Minimise an (x, y, z) coordinate.
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) |
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.
def concentric_hexagons(radius, start=(0, 0)):
"""A generator which p... |
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... |
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... |
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 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 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... |
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.
def _load_resource(self, source_r, abs_path=False):
"""The CSV package has no reseources, so we just need to resolve the URLs... |
Initialization that must happen before the arbiter is (re)started
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() |
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)
def attach_tasks(self, tasks: Tasks):
"""Attach a set of tasks.
A task cannot be scheduled or executed before it is attac... |
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 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
def schedule_batch(self, batch: Batch):
"""Schedule many jobs at once.
Scheduling jobs in ... |
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 ... |
Stop the workers and wait for them to terminate.
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
# ... |
Trunk data model change from the server.
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.D... |
Subport data model change from the server.
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': subpor... |
Sets up VLAN trunk and updates the trunk status.
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._c... |
The entry point for neutron-hnv-metadata-proxy.
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() |
Get the port profile ID from the request path.
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... |
Setup the RPC client for the current agent.
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.Fixed... |
Start the neutron-hnv-metadata-proxy agent.
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(),
p... |
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 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... |
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... |
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... |
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`, ...])
def links_between(a, b, machine):
"""Get the set of working links connecti... |
Load the credentials for an s3 profile into environmental variables
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().acce... |
net.projections.append(Projection(id='proj0',
presynaptic=p0.id,
postsynaptic=p1.id,
synapse='ampa'))
net.projections[0].random_connectivity=RandomConnectivity(probability=0.5)
def create_new_model(r... |
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
def send(self, *sender, **kwargs):
"""Emit this signal on behalf of `sender`, passing on kwargs.
... |
Add documentation entries for resources
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('Nam... |
This is the name of the package we will be creating.
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 ... |
Open a notebook and determine the output directory from the name
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) |
Extract some term values, usually set with tags or metadata
def extract_terms(self, nb):
"""Extract some term values, usually set with tags or metadata"""
emt = ExtractMetatabTerms()
emt.preprocess(nb, {})
return emt.terms |
Create a Metatab package from a 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
... |
Also extracts attachments
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():
... |
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... |
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.
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 pla... |
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
... |
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... |
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... |
Identity minimisation function.
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)) |
Load groups and organizations, from a file in Metatab format
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 ope... |
Load instructions, displayed in the package notes
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(
"""
... |
Create a groups and organization file
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... |
Return a new memo with a new metatabfile argument
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 |
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>`_.
def linkcode_resolve(domain, info):
"""Determine the URL corresponding to Python object on GitHub
This code i... |
Return the path to an included declaration
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)
... |
Flatten a data structure into tuples
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(... |
Make the build directory 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 ... |
Try to guess the format of a resource, possibly with a HEAD request
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... |
mimic os.walk, but walk 'up' instead of down the directory tree
:param bottom:
:return:
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 file... |
Return the cache directory where data can be written during a build, usually for
a Jupyter notebook that generates many files for each execution
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 m... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.