code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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 = reader.read(h.taglen)
headers.append(h)
return headers | def parse(data) | returns a list of header tags | 2.207223 | 2.030053 | 1.087273 |
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.realm.to_string()
tgt_rep['cname'] = self.client.to_asn1()[0]
tgt_rep['ticket'] = Ticket.load(self.ticket.to_asn1()).nati... | def to_tgt(self) | Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format | 4.133769 | 3.759897 | 1.099437 |
self.primary_principal = c.client
c.server = CCACHEPrincipal.from_asn1(enc_as_rep_part['sname'], enc_as_rep_part['srealm'])
c.time = Times.from_asn1(enc_as_rep_part)
c.key = Keyblock.from_asn1(enc_as_rep_part['key'])
c.is_skey = 0 #not sure!
c.tktflags = TicketFlags(enc_as_rep_part['flags']).cast(core.I... | 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'], as_rep['crealm'])
if override_pp == True | 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... | 3.996099 | 3.898018 | 1.025162 |
self.primary_principal = c.client
c.server = CCACHEPrincipal.from_asn1(enc_tgs_rep_part['sname'], enc_tgs_rep_part['srealm'])
c.time = Times.from_asn1(enc_tgs_rep_part)
c.key = Keyblock.from_asn1(enc_tgs_rep_part['key'])
c.is_skey = 0 #not sure!
c.tktflags = TicketFlags(enc_tgs_rep_part['flags']).cast(c... | 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'], tgs_rep['crealm'])
if override_pp == True | 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... | 3.76474 | 3.781259 | 0.995631 |
c = Credential()
enc_credinfo = EncKrbCredPart.load(krbcred['enc-part']['cipher']).native
ticket_info = enc_credinfo['ticket-info'][0]
c.client = CCACHEPrincipal.from_asn1(ticket_info['pname'], ticket_info['prealm'])
if override_pp == True:
self.primary_principal = c.client
#yaaaaay 4 additio... | def add_kirbi(self, krbcred, override_pp = True, include_expired = False) | 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')
... | 5.380602 | 5.139135 | 1.046986 |
tgts = []
for cred in self.credentials:
if cred.server.to_string().lower().find('krbtgt') != -1:
tgts.append(cred.to_tgt())
return tgts | 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 | 5.623881 | 4.622597 | 1.216606 |
hashes = []
for cred in self.credentials:
res = Ticket.load(cred.ticket.to_asn1()).native
if int(res['enc-part']['etype']) == 23 or all_hashes == True:
hashes.append(cred.to_hash())
return 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 | 6.804901 | 6.121322 | 1.111672 |
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:
kirbidata = f.read()
kirbi = KRBCRED.load(kirbidata).native
cc.add_kirbi(kirbi)
return cc | def from_kirbidir(directory_path) | Iterates trough all .kirbi files in a given directory and converts all of them into one CCACHE object | 4.343057 | 3.262785 | 1.331089 |
kf_abs = os.path.abspath(directory_path)
for cred in self.credentials:
kirbi, filename = cred.to_kirbi()
filename = '%s.kirbi' % filename.replace('..','!')
filepath = os.path.join(kf_abs, filename)
with open(filepath, 'wb') as o:
o.write(kirbi.dump()) | 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 | 4.147414 | 3.907965 | 1.061272 |
with open(filename, 'wb') as f:
f.write(self.to_bytes()) | def to_file(self, filename) | Writes the contents of the CCACHE object to a file | 2.39004 | 2.747331 | 0.86995 |
#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
#Generate the format string to pad the columns
print_string = ""
for i,width in enumerate(widths)... | def print_table(lines, separate_head=True) | Prints a formatted table given a 2 dimensional array | 2.495118 | 2.456234 | 1.015831 |
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() + self.username).encode()
return string_to_key(Enctype.AES256, self.password.encode(), salt).contents
rais... | def get_key_for_enctype(self, etype) | Returns the encryption key bytes for the enctryption type. | 1.64519 | 1.616757 | 1.017586 |
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 = KerberosSecretType(secret_type.upper())
if st == KerberosSecretType.PASSWORD or st == KerberosSecretType.PW or st == KerberosSecr... | def from_connection_string(s) | Credential input format:
<domain>/<username>/<secret_type>:<secret>@<dc_ip_or_hostname> | 2.641009 | 2.41928 | 1.091651 |
existing_users = []
for user in users:
logging.debug('Probing user %s' % user)
req = KerberosUserEnum.construct_tgt_req(realm, user)
rep = self.ksoc.sendrecv(req.dump(), throw = False)
if rep.name != 'KRB_ERROR':
# user doesnt need preauth, but it exists
existing_users.append(user)
... | 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 | 5.549038 | 5.561014 | 0.997846 |
tgts = []
for cred in creds:
try:
kcomm = KerbrosComm(cred, self.ksoc)
kcomm.get_TGT(override_etype = override_etype, decrypt_tgt = False)
tgts.append(kcomm.kerberos_TGT)
except Exception as e:
logger.debug('Error while roasting client %s/%s Reason: %s' % (cred.domain, cred.username, str... | 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 | 5.930646 | 5.284772 | 1.122214 |
if not self.kcomm:
try:
self.kcomm = KerbrosComm(self.ccred, self.ksoc)
self.kcomm.get_TGT()
except Exception as e:
logger.exception('Failed to get TGT ticket! Reason: %s' % str(e))
tgss = []
for target in targets:
try:
tgs, encTGSRepPart, key = self.kcomm.get_TGS(target, overr... | 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 | 4.413929 | 3.941577 | 1.119838 |
h = hmac.new(password, digestmod=digestmod)
def prf(data):
hm = h.copy()
hm.update(data)
return bytearray(hm.digest())
key = bytearray()
i = 1
while len(key) < keylen:
T = U = prf(salt + struct.pack('>i', i))
for _ in range(iters - 1):
U = prf(U)
T = bytearray(x ^ y for x, y in zip(T, U))
key ... | 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 iterations
keylen (int) -- length of key to derive
digestmod -- a crypt... | 2.143309 | 2.661021 | 0.805446 |
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) | <credentials>@<ip_or_hostname>:<port> | 3.493312 | 3.487433 | 1.001686 |
kc = KerbrosComm(None, ksoc)
kc.kerberos_TGT = tgt
kc.kerberos_cipher_type = key['keytype']
kc.kerberos_session_key = Key(kc.kerberos_cipher_type, key['keyvalue'])
kc.kerberos_cipher = _enctype_table[kc.kerberos_cipher_type]
return kc | 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. | 5.375702 | 4.746064 | 1.132665 |
#construct tgs_req
logger.debug('Constructing TGS request for user %s' % spn_user.get_formatted_pname())
now = datetime.datetime.utcnow()
kdc_req_body = {}
kdc_req_body['kdc-options'] = KDCOptions(set(['forwardable','renewable','renewable_ok', 'canonicalize']))
kdc_req_body['realm'] = spn_user.domain.up... | 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, will override the AP_REQ supported etype values (which is de... | 2.294195 | 2.235132 | 1.026425 |
# 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 cannot exist when all entries share the same mask and all
# keys are unique.
if len(set(e.mask for e in table)) == 1 and \... | 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 could be handled by
default routing.
target_length : i... | 4.629097 | 4.087335 | 1.132547 |
# May only have one source and sink (which may not be None)
if (len(entry.sources) == 1 and
len(entry.route) == 1 and
None not in entry.sources):
# Neither the source nor sink may be a core
source = next(iter(entry.sources))
sink = next(iter(entry.route))
... | 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 : [RoutingTableEntry, ...]
The table containing the entry.
... | 5.393569 | 5.129909 | 1.051397 |
# Pairs of inbound and outbound routes.
InOutPair = namedtuple("InOutPair", "ins, outs")
# {(x, y): {(key, mask): _InOutPair}}
route_sets = defaultdict(OrderedDict)
for net, routing_tree in iteritems(routes):
key, mask = net_keys[net]
# The direction is the Links entry which ... | 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 but with differing
routes are generated. This ... | 4.027647 | 3.641667 | 1.10599 |
return {
(x, y): ci.largest_free_rtr_mc_block
for (x, y), ci in iteritems(system_info)
} | 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, ...}
A dictionary giving the number of free routing table... | 12.140639 | 13.28133 | 0.914113 |
# 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(entries_a, ignore_xs=common_xs):
# Look at every entry in the second table
for other_entry in entries_b:
# I... | 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({Routes.north, Routes.north_east}, 0x0, 0xf),
... ... | 4.280561 | 4.1642 | 1.027943 |
# Get all the Xs in the entry that are not ignored
xs = (~entry.key & ~entry.mask) & ~ignore_xs
# Find the most significant X
for bit in (1 << i for i in range(31, -1, -1)):
if bit & xs:
# Yield all the entries with this bit set as 0
entry_0 = RoutingTableEntry(entr... | 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)) == [
... RoutingTableEntry(set(), 0b0100, 0x... | 3.400461 | 3.185204 | 1.06758 |
# 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 = set({})
# Expand each entry in turn
for entry in entries:
for new_entry in expand_entry(entry, ignore_xs):
if new_en... | 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
... RoutingTableEntry(set(), 0b0010, 0xfffffff... | 3.967067 | 3.698636 | 1.072576 |
# Determine where there are never 1s in the key and mask
key = 0x00000000
mask = 0x00000000
for entry in entries:
key |= entry.key
mask |= entry.mask
# Where there are never 1s in the key or the mask there are Xs which are
# common to all entries.
return (~(key | mask)... | 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 = [
... RoutingTableEntry(set(), ... | 5.402901 | 5.107146 | 1.05791 |
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) | Test if the ranges covered by a pair of slices overlap. | 2.474816 | 2.537303 | 0.975372 |
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) | Minimise an (x, y, z) coordinate. | 2.921765 | 2.624305 | 1.113348 |
x, y = start
yield (x, y)
for r in range(1, radius + 1):
# Move to the next layer
y -= 1
# Walk around the hexagon of this radius
for dx, dy in [(1, 1), (0, 1), (-1, 0), (-1, -1), (0, -1), (1, 0)]:
for _ in range(r):
yield (x, y)
... | 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. | 2.831878 | 2.936109 | 0.9645 |
# 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:
return (8, 8)
if num_boards % 3 != 0:
raise ValueError("{} is not a multiple of 3".format(num_boards))
# Find the ... | 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 squarely as possible
given the number of boar... | 4.902951 | 4.277845 | 1.146126 |
# 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 %= 12
root_x %= 12
# Internally, work with the width and height rounded up to the next
# multiple of 12
w = ((width + 11) // 12) * ... | 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::
In general, applications should use
:py:class:`rig.mac... | 3.94803 | 3.663276 | 1.077732 |
dx, dy = SPINN5_ETH_OFFSET[(y - root_y) % 12][(x - root_x) % 12]
return ((x + int(dx)) % w), ((y + int(dy)) % h) | 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 boards
.. warning::
In general, applications should int... | 4.069013 | 6.058096 | 0.671665 |
dx, dy = SPINN5_ETH_OFFSET[(y - root_y) % 12][(x - root_x) % 12]
return (-int(dx), -int(dy)) | 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
Parameters
----------
x, y : int
The coor... | 5.16875 | 7.652778 | 0.675408 |
x, y = spinn5_chip_coord(x, y, root_x, root_y)
return SPINN5_FPGA_LINKS.get((x, y, 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
----------
x, y : int
The chip whose link is o... | 3.660535 | 4.774671 | 0.766657 |
r = self.doc.resource(source_r.name)
r.url = self.resource_root.join(r.url).inner | 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. | 10.777936 | 11.086195 | 0.972194 |
self._arbiter = None
self._workers = None
self._working_queue = None
self._must_stop = threading.Event() | def _reset(self) | Initialization that must happen before the arbiter is (re)started | 7.921196 | 4.84868 | 1.633681 |
if tasks._spin is not None and tasks._spin is not self:
logger.warning('Tasks already attached to a different Engine')
self._tasks.update(tasks)
tasks._spin = self | 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) | 7.980034 | 6.530052 | 1.222048 |
task = self._tasks.get(task)
job = Job(task.name, task.queue, at, task.max_retries, task_args=args,
task_kwargs=kwargs)
return self._broker.enqueue_jobs([job]) | 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 lift any ambiguity. However if a
timezone naive datetime if given, ... | 6.498255 | 5.718786 | 1.1363 |
jobs = list()
for task, at, args, kwargs in batch.jobs_to_create:
task = self._tasks.get(task)
jobs.append(
Job(task.name, task.queue, at, task.max_retries,
task_args=args, task_kwargs=kwargs)
)
return self._broker.... | 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 | 5.076111 | 5.298975 | 0.957942 |
if self._arbiter or self._workers:
raise RuntimeError('Workers are already running')
self._working_queue = queue
tasks_names = '\n'.join(
[' - ' + task.name for task in self._tasks.tasks.values()
if task.queue == self._working_queue]
)
... | 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:`queues`
:arg block: whether to block the calling thread until a signal arrives
and workers get terminated
:arg stop_when_queue_empty: automatically ... | 3.211669 | 3.258508 | 0.985626 |
# _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()
self._workers.stop()
self._result_notifier.join()
self._broker.stop()
if ... | def stop_workers(self, _join_arbiter=True) | Stop the workers and wait for them to terminate. | 6.272151 | 5.821697 | 1.077375 |
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 been deleted. Remove them from cache.
for trunk in trunks:
sel... | def handle_trunks(self, trunks, event_type) | Trunk data model change from the server. | 2.557136 | 2.452081 | 1.042843 |
LOG.debug("Subports event received: %(event_type)s. "
"Subports: %(subports)s",
{'event_type': event_type, 'subports': subports})
# update the cache.
if event_type == events.CREATED:
for subport in subports:
trunk = self.... | def handle_subports(self, subports, event_type) | Subport data model change from the server. | 2.078501 | 2.032844 | 1.02246 |
LOG.info('Binding trunk port: %s.', trunk)
try:
# bind sub_ports to host.
self._trunk_rpc.update_subport_bindings(self._context,
trunk.sub_ports)
vlan_trunk = [s.segmentation_id for s in trunk.sub_ports]
... | def _setup_trunk(self, trunk, vlan_id=None) | Sets up VLAN trunk and updates the trunk status. | 3.770891 | 3.670147 | 1.027449 |
register_config_opts()
common_config.init(sys.argv[1:])
neutron_config.setup_logging()
proxy = MetadataProxy()
proxy.run() | def main() | The entry point for neutron-hnv-metadata-proxy. | 6.490912 | 4.166494 | 1.557883 |
# 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):
LOG.debug("The instance id was found in request path.")
return port_profile... | def _get_port_profile_id(self, request) | Get the port profile ID from the request path. | 5.078993 | 4.487841 | 1.131723 |
self._state_rpc = agent_rpc.PluginReportStateAPI(topics.REPORTS)
report_interval = CONF.AGENT.report_interval
if report_interval:
heartbeat = loopingcall.FixedIntervalLoopingCall(
self._report_state)
heartbeat.start(interval=report_interval) | def _setup_rpc(self) | Setup the RPC client for the current agent. | 2.900715 | 2.744659 | 1.056858 |
server = wsgi.Server(
name=self._AGENT_BINARY,
num_threads=CONF.AGENT.worker_count)
server.start(
application=_MetadataProxyHandler(),
port=CONF.bind_port,
host=CONF.bind_host)
server.wait() | def _work(self) | Start the neutron-hnv-metadata-proxy agent. | 9.80271 | 6.388099 | 1.534527 |
self._azure_info.resource_group_name = resource_group_name
self._azure_info.website_name = website_name
self._azure_info.credentials = credentials
self._azure_info.subscription_id = subscription_id
self._azure_info.subscription_name = subscription_name
self._azur... | 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:
:param website_name:
:param credentials:
:param subscription_id:
:param subscription_name:
:param tenant_id:
:param webapp_location:
:re... | 1.329642 | 1.379285 | 0.964008 |
self._repo_info.url = repo_url
self._repo_info.branch = branch
self._repo_info.git_token = git_token
self._repo_info._private_repo_username = private_repo_username
self._repo_info._private_repo_password = private_repo_password | 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
:param git_token: git token
:param private_repo_username: private repo username
:param private_repo_password: priv... | 1.603437 | 1.685241 | 0.951458 |
branch = self._repo_info.branch or 'refs/heads/master'
self._validate_cd_project_url(cd_project_url)
vsts_account_name = self._get_vsts_account_name(cd_project_url)
# Verify inputs before we start generating tokens
source_repository, account_name, team_project_name = s... | 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_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... | 4.337012 | 4.318976 | 1.004176 |
x, y = start
out = []
for dimension, magnitude in sorted(enumerate(vector),
key=(lambda x:
abs(x[1]) + random.random()),
reverse=True):
if magnitude == 0:
brea... | 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)
The vector which the path should cover.
start : (x, y)
The coordi... | 3.356816 | 3.01268 | 1.114229 |
ax, ay = a
bx, by = b
return set(link for link, (dx, dy) in ((l, l.to_vector()) for l in Links)
if (ax + dx) % machine.width == bx and
(ay + dy) % machine.height == by and
(ax, ay, link) in machine) | 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`, ...]) | 5.653067 | 5.139929 | 1.099834 |
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_credentials().secret_key | def set_s3_profile(profile_name) | Load the credentials for an s3 profile into environmental variables | 1.791593 | 1.657961 | 1.0806 |
################################################################################
### Build a new network
net = Network(id=reference)
net.notes = "A network model: %s"%reference
net.temperature = temperature # degC
if parameters:
net.parameters = parameters
#########... | 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... | net.projections.append(Projection(id='proj0',
presynaptic=p0.id,
postsynaptic=p1.id,
synapse='ampa'))
net.projections[0].random_connectivity=RandomConnectivity(probability=0.5) | 2.850543 | 2.529151 | 1.127075 |
if len(sender) == 0:
sender = None
elif len(sender) > 1:
raise TypeError('send() accepts only one positional argument, '
'%s given' % len(sender))
else:
sender = sender[0]
if not self.receivers:
return ... | 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 | 2.942332 | 2.968529 | 0.991175 |
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 main output from the HTML exporter, not a resource.
ds.new_term('Root.Documenta... | def update_metatab(self, doc, resources) | Add documentation entries for resources | 3.564072 | 3.555671 | 1.002363 |
package_dir = self.package_dir
if not package_dir:
package_dir = getcwd()
package_name = self.package_name
if not package_name:
doc = ExtractInlineMetatabDoc(package_url="metapack+file:" + package_dir).run(nb)
if not doc:
... | def get_package_dir_name(self, nb) | This is the name of the package we will be creating. | 6.908593 | 6.937404 | 0.995847 |
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) | Open a notebook and determine the output directory from the name | 3.90999 | 3.803442 | 1.028014 |
emt = ExtractMetatabTerms()
emt.preprocess(nb, {})
return emt.terms | def extract_terms(self, nb) | Extract some term values, usually set with tags or metadata | 21.064198 | 18.296062 | 1.151297 |
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_output_dir(nb)
except NotebookError as e:
# Notebook probably lacks a metatab doc.
... | def from_notebook_node(self, nb, resources=None, **kw) | Create a Metatab package from a notebook node | 5.498902 | 5.30384 | 1.036778 |
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 self.extract_output_types:
if mime_type in attach:
... | def preprocess_cell(self, cell, resources, cell_index) | Also extracts attachments | 6.097423 | 5.687124 | 1.072145 |
# An internal (mutable) state object (note: used in place of a closure with
# nonlocal variables for Python 2 support).
class HilbertState(object):
def __init__(self, x=0, y=0, dx=1, dy=0):
self.x, self.y, self.dx, self.dy = x, y, dx, dy
# Create state object first time we're c... | 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
resulting curve will be `(2**level)-1` wide/t... | 1.946372 | 1.868176 | 1.041857 |
max_dimen = max(machine.width, machine.height)
hilbert_levels = int(ceil(log(max_dimen, 2.0))) if max_dimen >= 1 else 0
return hilbert(hilbert_levels) | 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. | 3.966789 | 4.585825 | 0.865011 |
return sequential_place(vertices_resources, nets,
machine, constraints,
(None if not breadth_first else
breadth_first_vertex_order(vertices_resources,
nets)),
... | 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 which
optionally uses the :py:func:`breadth_first_vertex_order` vertex ordering
... | 6.255115 | 4.029128 | 1.552474 |
# Coerce the target lengths into the correct forms
if not isinstance(target_lengths, dict):
lengths = collections.defaultdict(lambda: target_lengths)
else:
lengths = target_lengths
# Minimise the routing tables
new_tables = dict()
for chip, table in iteritems(routing_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 given (or some sensible default algorithms), trying
each sequentially until a target number of routing entries has been
reac... | 2.88467 | 2.884684 | 0.999995 |
# Add a final method which checks the size of the table and returns it if
# the size is correct. NOTE: This method will avoid running any other
# minimisers if the table is already sufficiently small.
methods = list(methods)
methods.insert(0, _identity)
if target_length is not None:
... | 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 to minimise. NOTE: This is the data structure as
returned by :py:meth:`~rig.routing_table.routing_tree_to_tabl... | 4.007511 | 4.00624 | 1.000317 |
if target_length is None or len(table) < target_length:
return table
raise MinimisationFailedError(target_length, len(table)) | def _identity(table, target_length) | Identity minimisation function. | 5.512406 | 4.3545 | 1.26591 |
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(m.ckan_url, apikey=m.api_key)
groups = { g['name']:g for g in c.action.group_list(al... | def configure_ckan(m) | Load groups and organizations, from a file in Metatab format | 2.324903 | 2.149992 | 1.081354 |
per_package_inst = ''
for dist in inst_distributions:
if dist.type == 'zip':
per_package_inst += dedent(
.format(url=dist.package_url.inner))
elif dist.type == 'csv':
per_package_inst += dedent(
.format(url=dist.package_url.inner))... | def package_load_instructions(inst_distributions) | Load instructions, displayed in the package notes | 4.370867 | 4.180207 | 1.04561 |
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 g in c.action.group_list(all_fields=True):
print(g.k... | def dump_ckan(m) | Create a groups and organization file | 4.994025 | 4.583848 | 1.089483 |
o = MetapackCliMemo(self.args)
o.set_mt_arg(metatabfile)
return o | def update_mt_arg(self, metatabfile) | Return a new memo with a new metatabfile argument | 9.630579 | 5.795054 | 1.661862 |
# Only link to Python source
if domain != 'py':
return None
# Get a reference to the object in question
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for part in fullname.spli... | 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>`_. | 2.798926 | 2.746628 | 1.019041 |
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(d, name + '.csv')
if not exists(path):
raise IncludeError("No l... | def declaration_path(name) | Return the path to an included declaration | 4.047321 | 3.755617 | 1.077671 |
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() for k2, v2 in _flatten(v, k, sep))
elif isinstance(e, col... | def flatten(d, sep='.') | Flatten a data structure into tuples | 2.142347 | 2.028711 | 1.056014 |
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)
maybe_makedir(DOWNLOAD_DIR)
maybe_makedir(PACKAGE_DIR)
maybe_make... | def make_dir_structure(base_dir) | Make the build directory structure. | 3.365975 | 3.407774 | 0.987734 |
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://civicknowledge.com'
if parts.get('path'):
type, encoding = mimetypes.guess_type(url)
elif part... | def guess_format(url) | Try to guess the format of a resource, possibly with a HEAD request | 4.085713 | 4.026115 | 1.014803 |
import os
from os import path
bottom = path.realpath(bottom)
# get files in current dir
try:
names = os.listdir(bottom)
except Exception as e:
raise e
dirs, nondirs = [], []
for name in names:
if path.isdir(path.join(bottom, name)):
dirs.append... | def walk_up(bottom) | mimic os.walk, but walk 'up' instead of down the directory tree
:param bottom:
:return: | 2.287985 | 2.092636 | 1.093351 |
from metapack.constants import MATERIALIZED_DATA_PREFIX
from os.path import join
if not doc:
from metapack import Downloader
downloader = Downloader()
return downloader.cache.getsyspath(MATERIALIZED_DATA_PREFIX)
else:
dr = doc._cache.getsyspath(join(MATERIALIZED_DA... | 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 | 4.613468 | 4.580241 | 1.007254 |
# 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, self)])
while to_visit:
direction, node = to_visit.popleft()
... | 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 the tree, the (x, y) co-ordina... | 6.072778 | 5.599622 | 1.084498 |
this_node = DependencyNode(doc, None)
for r in doc.references():
other_node = DependencyNode(r, this_node)
yield (this_node, other_node)
if isinstance(other_node, PackageDependencyNode):
yield from yield_deps(other_node.doc) | def yield_deps(doc) | TODO: This implementation is very specific to a particular environment and project, and should be generalized.
:param doc:
:return: | 4.038372 | 4.242512 | 0.951882 |
parts = s.split('/')
if len(parts) == 1:
return parts[0]
else:
i = 0
lines = []
for j in range(i, len(parts) + 1):
tv = '/'.join(parts[i:j])
nv = '/'.join(parts[i:j + 1])
if len(nv) > l or nv == tv:
i = j
... | def wrap_url(s, l) | Wrap a URL string | 3.18947 | 3.208938 | 0.993933 |
lsb = 0
while not (w & arr[lsb]):
lsb += 1
return lsb + 1 | def _get_rho(self, w, arr) | Return the least signifiant bit
O(N) in the worst case | 5.920175 | 4.65696 | 1.271253 |
if uuid:
# Computing the hash
try:
x = hash64(uuid)
except UnicodeEncodeError:
x = hash64(uuid.encode('ascii', 'ignore'))
# Finding the register to update by using the first b bits as an index
j = x & ((1 << sel... | def add(self, uuid) | Adds a key to the HyperLogLog | 8.068553 | 7.443166 | 1.084022 |
E = self.alpha * float(self.m ** 2) / np.power(2.0, - self.M).sum()
if E <= 2.5 * self.m: # Small range correction
V = self.m - np.count_nonzero(self.M)
return int(self.m * np.log(self.m / float(V))) if V > 0 else int(E)
# intermidiate range correctio... | def estimate(self) | Returns the estimate of the cardinality | 6.728847 | 6.504582 | 1.034478 |
if self.doc.package_url:
return self.doc.package_url
return self.doc._ref | def base_url(self) | Base URL for resolving resource URLs | 10.461677 | 8.382375 | 1.248056 |
from copy import copy
env = copy(self.doc.env)
assert env is not None, 'Got a null execution context'
env.update(self._envvar_env)
env.update(self.all_props)
return env | def env(self) | The execution context for rowprocessors and row-generating notebooks and functions. | 9.97459 | 7.990983 | 1.248231 |
if not self.url:
return None
u = parse_app_url(self.url)
if u.scheme == 'index':
u = u.resolve()
if u.scheme != 'file':
# Hopefully means the URL is http, https, ftp, etc.
return u
elif u.resource_format == 'ipynb':
... | def _resolved_url(self) | Return a URL that properly combines the base_url and a possibly relative
resource url | 5.700925 | 5.668108 | 1.00579 |
if not self.name:
raise MetapackError("Resource for url '{}' doe not have name".format(self.url))
t = self.doc.find_first('Root.Table', value=self.get_value('name'))
frm = 'name'
if not t:
t = self.doc.find_first('Root.Table', value=self.get_value('sch... | def schema_term(self) | Return the Table term for this resource, which is referenced either by the `table` property or the
`schema` property | 6.420059 | 5.244294 | 1.224199 |
t = self.schema_term
if t:
return [self._name_for_col_term(c, i)
for i, c in enumerate(t.children, 1) if c.term_is("Table.Column")]
else:
return None | def headers(self) | Return the headers for the resource. Returns the AltName, if specified; if not, then the
Name, and if that is empty, a name based on the column position. These headers
are specifically applicable to the output table, and may not apply to the resource source. FOr those headers,
use source_headers | 10.024229 | 8.57064 | 1.169601 |
t = self.schema_term
if t:
return [self._name_for_col_term(c, i)
for i, c in enumerate(t.children, 1) if c.term_is("Table.Column")
and c.get_value('name') != EMPTY_SOURCE_HEADER
]
else:
return None | def source_headers(self) | Returns the headers for the resource source. Specifically, does not include any header that is
the EMPTY_SOURCE_HEADER value of _NONE_ | 9.684679 | 7.401608 | 1.308456 |
try:
# For resources that are metapack packages.
r = self.expanded_url.resource.columns()
return list(r)
except AttributeError as e:
pass
return self.schema_columns | def columns(self) | Return column information from the schema or from an upstreram package | 19.472128 | 15.462015 | 1.259353 |
t = self.schema_term
columns = []
if t:
for i, c in enumerate(t.children):
if c.term_is("Table.Column"):
p = c.all_props
p['pos'] = i
p['name'] = c.value
p['header'] = self._n... | def schema_columns(self) | Return column informatino only from this schema | 7.134218 | 6.882671 | 1.036548 |
from rowgenerators.rowpipe import Table
type_map = {
None: None,
'string': 'str',
'text': 'str',
'number': 'float',
'integer': 'int'
}
def map_type(v):
return type_map.get(v, v)
if self.schema_ter... | def row_processor_table(self, ignore_none=False) | Create a row processor from the schema, to convert the text values from the
CSV into real types | 3.520411 | 3.674796 | 0.957988 |
from rowgenerators import get_generator
self.doc.set_sys_path() # Set sys path to package 'lib' dir in case of python function generator
ru = self.resolved_url
try:
resource = ru.resource # For Metapack urls
return resource.row_generator
exce... | def raw_row_generator(self) | Like rowgenerator, but does not try to create a row processor table | 11.664265 | 11.554265 | 1.00952 |
try:
header_lines = [int(e) for e in str(self.get_value('headerlines', 0)).split(',')]
except ValueError as e:
header_lines = [0]
# We're processing the raw datafile, with no schema.
header_rows = islice(self.row_generator, min(header_lines), max(header... | def _get_header(self) | Get the header from the deinfed header rows, for use on references or resources where the schema
has not been run | 6.989083 | 6.224659 | 1.122806 |
from collections import OrderedDict
headers = None
for row in self:
if headers is None:
headers = row
continue
yield OrderedDict(zip(headers, row)) | def iterdict(self) | Iterate over the resource in dict records | 4.769342 | 4.61222 | 1.034066 |
row_proxy = None
headers = None
for row in self:
if not headers:
headers = row
row_proxy = RowProxy(headers)
continue
yield row_proxy.set_row(row) | def iterrows(self) | Iterate over the resource as row proxy objects, which allow acessing colums as attributes | 7.25494 | 5.188881 | 1.39817 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.