code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
constraints = [] # Find the set of cores which are universally reserved globally_reserved = None for chip_info in itervalues(system_info): reserved = sum(1 << c for c, state in enumerate(chip_info.core_states) if state != AppState.idle) if globally_reserved i...
def build_core_constraints(system_info, core_resource=Cores)
Return a set of place-and-route :py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint` which reserve any cores that that are already in use. The returned list of :py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint`\ s reserves all cores not in an Idle state (i.e. n...
3.863345
3.998956
0.966088
application_map = defaultdict(lambda: defaultdict(set)) for vertex, application in iteritems(vertices_applications): chip_cores = application_map[application][placements[vertex]] core_slice = allocations[vertex].get(core_resource, slice(0, 0)) chip_cores.update(range(core_slice.sta...
def build_application_map(vertices_applications, placements, allocations, core_resource=Cores)
Build a mapping from application to a list of cores where the application is used. This utility function assumes that each vertex is associated with a specific application. Parameters ---------- vertices_applications : {vertex: application, ...} Applications are represented by the path...
3.077067
2.915763
1.055322
from rig.routing_table import routing_tree_to_tables, remove_default_routes warnings.warn( "build_routing_tables() is deprecated, see " "rig.routing_table.routing_tree_to_tables()" "and rig.routing_table.minimise()", DeprecationWarning ) # Build full routing tables and the...
def build_routing_tables(routes, net_keys, omit_default_routes=True)
**DEPRECATED** Convert a set of RoutingTrees into a per-chip set of routing tables. .. warning:: This method has been deprecated in favour of :py:meth:`rig.routing_table.routing_tree_to_tables` and :py:meth:`rig.routing_table.minimise`. E.g. most applications should use somethi...
4.837366
3.480243
1.38995
@signals.job_started.connect_via(namespace) def job_started(namespace, job, **kwargs): raven_client.context.activate() raven_client.transaction.push(job.task_name) @signals.job_finished.connect_via(namespace) def job_finished(namespace, job, **kwargs): raven_client.transac...
def register_sentry(raven_client, namespace: Optional[str]=None, send_retries: bool=False)
Register the Sentry integration. Exceptions making jobs fail are sent to Sentry. :param raven_client: configured Raven client used to sent errors to Sentry :param namespace: optionally only register the Sentry integration for a particular Spinach :class:`Engine` :param send_retries: whether...
2.117088
2.021069
1.047509
if isinstance(mt_file, MetapackDoc): doc = mt_file else: doc = MetapackDoc(mt_file) if not 'Resources' in doc: doc.new_section('Resources') doc['Resources'].args = [e for e in set(doc['Resources'].args + ['Name', 'StartLine', 'HeaderLines', 'Encoding']) if ...
def add_resource(mt_file, ref, cache)
Add a resources entry, downloading the intuiting the file, replacing entries with the same reference
5.675852
5.588088
1.015706
left = self._left bottom = self._bottom right = self._right top = self._top if pixelbuffer: offset = self.pixel_x_size * float(pixelbuffer) left -= offset bottom -= offset right += offset top += offset #...
def bounds(self, pixelbuffer=0)
Return Tile boundaries. - pixelbuffer: tile buffer in pixels
4.300742
4.333596
0.992419
return Affine( self.pixel_x_size, 0, self.bounds(pixelbuffer).left, 0, -self.pixel_y_size, self.bounds(pixelbuffer).top )
def affine(self, pixelbuffer=0)
Return an Affine object of tile. - pixelbuffer: tile buffer in pixels
3.938896
3.911835
1.006918
# apply pixelbuffers height = self._base_shape.height + 2 * pixelbuffer width = self._base_shape.width + 2 * pixelbuffer if pixelbuffer and self.tp.grid.is_global: # on first and last row, remove pixelbuffer on top or bottom matrix_height = self.tile_pyra...
def shape(self, pixelbuffer=0)
Return a tuple of tile height and width. - pixelbuffer: tile buffer in pixels
4.727535
4.726383
1.000244
if not all([ isinstance(self.zoom, int), self.zoom >= 0, isinstance(self.row, int), self.row >= 0, isinstance(self.col, int), self.col >= 0 ]): raise TypeError("zoom, col and row must be integers >= 0") ...
def is_valid(self)
Return True if tile is available in tile pyramid.
2.171476
1.920889
1.130454
return None if self.zoom == 0 else self.tile_pyramid.tile( self.zoom - 1, self.row // 2, self.col // 2 )
def get_parent(self)
Return tile from previous zoom level.
6.514618
3.751414
1.736577
next_zoom = self.zoom + 1 return [ self.tile_pyramid.tile( next_zoom, self.row * 2 + row_offset, self.col * 2 + col_offset ) for row_offset, col_offset in [ (0, 0), # top left (0...
def get_children(self)
Return tiles from next zoom level.
2.618977
2.304476
1.136474
if connectedness not in [4, 8]: raise ValueError("only connectedness values 8 or 4 are allowed") unique_neighbors = {} # 4-connected neighborsfor pyramid matrix_offsets = [ (-1, 0), # 1: above (0, 1), # 2: right (1, 0), # 3: ...
def get_neighbors(self, connectedness=8)
Return tile neighbors. Tile neighbors are unique, i.e. in some edge cases, where both the left and right neighbor wrapped around the antimeridian is the same. Also, neighbors ouside the northern and southern TilePyramid boundaries are excluded, because they are invalid. -------...
2.31106
2.249595
1.027323
assert not (tag is not None and field is not None), \ "Cannot filter by tag and field simultaneously." selected_fields = self._select_by_field_or_tag(tag, field) # Check all selected fields have values defined missing_fields_idents = set(selected_fields) - set(self...
def get_value(self, tag=None, field=None)
Generate an integer whose bits are set according to the values of fields in this bit field. All other bits are set to zero. Parameters ---------- tag : str Optionally specifies that the value should only include fields with the specified tag. field : str ...
3.891077
3.631131
1.071588
if tag is not None and field is not None: raise TypeError("get_mask() takes exactly one keyword argument, " "either 'field' or 'tag' (both given)") selected_fields = self._select_by_field_or_tag(tag, field) # Build the mask (and throw an excepti...
def get_mask(self, tag=None, field=None)
Get the mask for all fields which exist in the current bit field. Parameters ---------- tag : str Optionally specifies that the mask should only include fields with the specified tag. field : str Optionally specifies that the mask should only include ...
4.404374
4.046807
1.088358
# Get the set of fields whose values will be included in the value if field is not None: # Select just the specified field (checking the field exists) field_obj = self.fields.get_field(field, self.field_values) selected_fields = OrderedDict([(field, field_obj...
def _select_by_field_or_tag(self, tag=None, field=None)
For internal use only. Returns an OrderedDict of {identifier: field} representing fields which match the supplied field/tag. Parameters ---------- tag : str Optionally specifies that the mask should only include fields with the specified tag. field : str ...
3.91947
3.802908
1.030651
return self.fields.get_field(field, self.field_values).tags.copy()
def get_tags(self, field)
Get the set of tags for a given field. .. note:: The named field must be accessible given the current set of values defined. Parameters ---------- field : str The field whose tag should be read. Returns ------- set([tag, ...]...
12.879248
17.75655
0.725324
field_obj = self.fields.get_field(field, self.field_values) if field_obj.length is None or field_obj.start_at is None: raise ValueError( "Field '{}' does not have a fixed size/position.".format( field)) return (field_obj.start_at, field_...
def get_location_and_length(self, field)
Get the location and length of a field within the bitfield. .. note:: The named field must be accessible given the current set of values defined. Parameters ---------- field : str The field of interest. Returns ------- locati...
4.291806
4.184316
1.025689
# We must fix fields at every level of the hierarchy separately # (otherwise fields of children won't be allowed to overlap). Here we # do a breadth-first iteration over the hierarchy to fix fields with # given starting positions; then we do depth-first to fix other fields. ...
def assign_fields(self)
Assign a position & length to any fields which do not have one. Users should typically call this method after all field values have been assigned, otherwise fields may be fixed at an inadequate size.
5.231155
5.15488
1.014797
# Calculate a mask of already allocated fields' bits for i, f in self.fields.potential_fields(field_values): if f.length is not None and f.start_at is not None: assigned_bits |= ((1 << f.length) - 1) << f.start_at # Allocate all specified fields for ...
def _assign_fields(self, identifiers, field_values, assign_positions, assigned_bits=0)
For internal use only. Assign lengths & positions to a subset of all potential fields with the supplied field_values. This method will check for any assigned bits of all potential fields but will only assign those fields whose identifiers are provided. Parameters ---------- ...
3.747468
3.581716
1.046277
field = self.fields.get_field(identifier, field_values) length = field.length if length is None: # Assign lengths based on values length = int(log(field.max_value, 2)) + 1 start_at = field.start_at if start_at is None: # Force a fail...
def _assign_field(self, assigned_bits, identifier, field_values)
For internal use only. Assign a length and position to a field which may have either one of these values missing. Parameters ---------- assigned_bits : int A bit mask of bits already in use by other fields identifier : str The identifier of the field to ...
3.265268
3.304379
0.988164
for t in self.doc.find('Root.Table'): for c in t.find('Table.Column'): if c.get_value('datatype') == 'geometry': c['transform'] = '^empty_str' c['datatype'] = 'text' return super()._load_resources()
def _load_resources(self)
Remove the geography from the files, since it isn't particularly useful in Excel
9.799386
8.203122
1.194592
import json if not isinstance(doc, dict): doc = json.loads(doc) d = {} def get_statement(name): for s in doc['Statement']: if s['Sid'] == name: return s for r in get_statement('read')['Principal']['AWS']: bucket, prefix = r.replace(arn_pr...
def user_policy_to_dict(doc)
Convert a bucket policy to a dict mapping principal/prefix names to 'R' or 'W'
3.125516
2.742599
1.139618
import yaml from os.path import dirname, join, abspath import copy import metatab with open(join(dirname(abspath(metatab.__file__)), 'support', 'policy_parts.yaml')) as f: parts = yaml.load(f) statements = {} cl = copy.deepcopy(parts['list']) cl['Resource'] = arn_prefix +...
def make_bucket_policy_statements(bucket)
Return the statemtns in a bucket policy as a dict of dicts
2.5124
2.464299
1.019519
import json iam = get_resource(args, 'iam') statements = make_bucket_policy_statements(bucket_name) user_stats = set() # statement tripples for (user, prefix), mode in d.items(): user_stats.add((user, 'list')) user_stats.add((user, 'bucket')) if mode == 'R': ...
def bucket_dict_to_policy(args, bucket_name, d)
Create a bucket policy document from a permissions dict. The dictionary d maps (user, prefix) to 'R' or 'W'. :param bucket_name: :param d: :return:
2.941214
2.679857
1.097526
import json if not isinstance(policy, dict): policy = json.loads(policy) statements = {s['Sid']: s for s in policy['Statement']} d = {} for rw in ('Read', 'Write'): for prefix in TOP_LEVEL_DIRS: sid = rw.title() + prefix.title() if sid in statements:...
def bucket_policy_to_dict(policy)
Produce a dictionary of read, write permissions for an existing bucket policy document
3.238269
2.970403
1.090178
iam = get_resource(args, 'iam') user = iam.User(user_name) user.load() return l.find_or_new_account(user.arn)
def get_iam_account(l, args, user_name)
Return the local Account for a user name, by fetching User and looking up the arn.
5.22224
4.854122
1.075836
if normalization == 'nanmean': data2 = data.tordd().sortByKey().values().map(lambda x: _convert_to_vector(x.flatten() - np.nanmean(x))) elif normalization == 'mean': data2 = data.tordd().sortByKey().values().map(lambda x: _convert_to_vector(x.flatten() - x.mean())) elif normalization is...
def getSVD(data, k, getComponents=False, getS=False, normalization='mean')
Wrapper for computeSVD that will normalize and handle a Thunder Images object :param data: Thunder Images object :param k: number of components to keep :param getComponents: will return the components if true, otherwise will return None :returns: projections, components, s
2.926454
3.053521
0.958387
if duration_seconds < 0.001: return '0 ms' if duration_seconds < 1: return '{} ms'.format(int(duration_seconds * 1000)) return '{} s'.format(int(duration_seconds))
def human_duration(duration_seconds: float) -> str
Convert a duration in seconds into a human friendly string.
2.598351
2.237147
1.161457
attempt = 0 while True: try: return func(*args, **kwargs) except exceptions as e: attempt += 1 if attempt >= max_retries: raise delay = exponential_backoff(attempt, cap=60) logger.warning('%s: retrying in %s', e, d...
def call_with_retry(func: Callable, exceptions, max_retries: int, logger: Logger, *args, **kwargs)
Call a function and retry it on failure.
2.907979
2.720438
1.068938
base = 3 temp = min(base * 2 ** attempt, cap) return timedelta(seconds=temp / 2 + random.randint(0, temp / 2))
def exponential_backoff(attempt: int, cap: int=1200) -> timedelta
Calculate a delay to retry using an exponential backoff algorithm. It is an exponential backoff with random jitter to prevent failures from being retried at the same time. It is a good fit for most applications. :arg attempt: the number of attempts made :arg cap: maximum delay, defaults to 20 minu...
4.979519
7.037253
0.707594
original_sigterm_handler = signal.getsignal(signal.SIGTERM) signal.signal(signal.SIGTERM, signal.default_int_handler) try: yield finally: signal.signal(signal.SIGTERM, original_sigterm_handler)
def handle_sigterm()
Handle SIGTERM like a normal SIGINT (KeyboardInterrupt). By default Docker sends a SIGTERM for stopping containers, giving them time to terminate before getting killed. If a process does not catch this signal and does nothing, it just gets killed. Handling SIGTERM like SIGINT allows to gracefully term...
1.935365
1.967046
0.983894
# Calculate the maximum and minimum values if signed: max_v = (1 << (n_bits - 1)) - 1 min_v = -max_v - 1 else: min_v = 0 max_v = (1 << n_bits) - 1 # Compute the scale scale = 2.0**n_frac def bitsk(value): int_val = int(scale * value) ...
def float_to_fp(signed, n_bits, n_frac)
Return a function to convert a floating point value to a fixed point value. For example, a function to convert a float to a signed fractional representation with 8 bits overall and 4 fractional bits (S3.4) can be constructed and used with:: >>> s34 = float_to_fp(signed=True, n_bits=8, n_frac=4...
3.25809
3.670785
0.887573
warnings.warn("float_to_fix() is deprecated, see float_to_fp", DeprecationWarning) mask = int(2**n_bits - 1) min_v, max_v = validate_fp_params(signed, n_bits, n_frac) # Saturate values def bitsk(value): value = np.clip(value, min_v, max_v) if value ...
def float_to_fix(signed, n_bits, n_frac)
**DEPRECATED** Return a function to convert a floating point value to a fixed point value. .. warning:: This function is deprecated in favour of :py:meth:`~.float_to_fp`. For example, a function to convert a float to a signed fractional representation with 8 bits overall and 4 fractional bits ...
3.535578
4.045259
0.874005
warnings.warn("fix_to_float() is deprecated, see fp_to_float", DeprecationWarning) validate_fp_params(signed, n_bits, n_frac) def kbits(value): if signed and value & (1 << (n_bits - 1)): # If signed and negative value -= (1 << n_bits) ...
def fix_to_float(signed, n_bits, n_frac)
**DEPRECATED** Return a function to convert a fixed point value to a floating point value. .. warning:: This function is deprecated in favour of :py:meth:`~.fp_to_float`. For example, a function to convert from signed fractional representations with 8 bits overall and 4 fractional representati...
5.177888
6.018929
0.860267
return pkg_resources.resource_filename('voobly', os.path.join(METADATA_PATH, '{}.json'.format(name)))
def get_metadata_path(name)
Get reference metadata file path.
5.779051
5.862312
0.985797
with open(filename, 'wb') as handle: pickle.dump(requests_cookiejar, handle)
def _save_cookies(requests_cookiejar, filename)
Save cookies to a file.
2.489203
2.386429
1.043066
if not params: params = {} params['key'] = session.auth.key try: if argument: request_url = '{}{}{}{}'.format(session.auth.base_url, VOOBLY_API_URL, url, argument) else: request_url = '{}{}'.format(VOOBLY_API_URL, url) resp = session.get(request_u...
def _make_request(session, url, argument=None, params=None, raw=False)
Make a request to API endpoint.
3.04609
3.00901
1.012323
try: html = session.request(mode, url, data=data) except RequestException: raise VooblyError('failed to connect') if SCRAPE_FETCH_ERROR in html.text: raise VooblyError('not logged in') if html.status_code != 200 or SCRAPE_PAGE_NOT_FOUND in html.text: raise VooblyErro...
def make_scrape_request(session, url, mode='get', data=None)
Make a request to URL.
3.351387
3.4165
0.980941
params = { 'start': start, 'limit': limit } if isinstance(ladder_id, str): ladder_id = lookup_ladder_id(ladder_id) if limit > LADDER_RESULT_LIMIT: raise VooblyError('limited to 40 rows') if user_ids: params['uidlist'] = ','.join([str(uid) for uid in user_...
def get_ladder(session, ladder_id, user_id=None, user_ids=None, start=0, limit=LADDER_RESULT_LIMIT)
Get ladder.
2.95215
2.935823
1.005561
if isinstance(game_id, str): game_id = lookup_game_id(game_id) lobbies = _make_request(session, LOBBY_URL, game_id) for lobby in lobbies: # pylint: disable=len-as-condition if len(lobby['ladders']) > 0: lobby['ladders'] = lobby['ladders'][:-1].split('|') return l...
def get_lobbies(session, game_id)
Get lobbies for a game.
3.049254
2.926673
1.041884
try: user_id = int(user_id) except ValueError: user_id = find_user(session, user_id) resp = _make_request(session, USER_URL, user_id) if not resp: raise VooblyError('user id not found') return resp[0]
def get_user(session, user_id)
Get user.
4.419532
4.428073
0.998071
resp = _make_request(session, FIND_USER_URL, username) if not resp: raise VooblyError('user not found') try: return int(resp[0]['uid']) except ValueError: raise VooblyError('user not found')
def find_user(session, username)
Find user by name - returns user ID.
5.114092
4.549471
1.124107
user_string = ','.join(usernames) return _make_request(session, FIND_USERS_URL, user_string)
def find_users(session, *usernames)
Find multiple users by name.
5.337738
4.829819
1.105163
data = get_user(session, uid) resp = dict(data) if not ladder_ids: return resp resp['ladders'] = {} for ladder_id in ladder_ids: if isinstance(ladder_id, str): ladder_id = lookup_ladder_id(ladder_id) try: ladder_data = dict(get_ladder(session, lad...
def user(session, uid, ladder_ids=None)
Get all possible user info by name.
2.910896
2.886262
1.008535
if isinstance(game_id, str): game_id = lookup_game_id(game_id) lobbies = get_lobbies(session, game_id) ladder_ids = set() for lobby in lobbies: ladder_ids |= set(lobby['ladders']) return list(ladder_ids)
def ladders(session, game_id)
Get a list of ladder IDs.
2.420387
2.273171
1.064762
def wrapped(session, *args, **kwargs): try: return function(session, *args, **kwargs) except VooblyError: with session.cache_disabled(): _LOGGER.info("attempted to access page before login") login(session) return f...
def authenticated(function)
Re-authenticate if session expired.
5.120044
5.311016
0.964042
return get_recent_matches(session, 'https://{}.voobly.com/{}/{}/0'.format( subdomain, TEAM_MATCHES_URL, clan_id), from_timestamp, limit)
def get_clan_matches(session, subdomain, clan_id, from_timestamp=None, limit=None)
Get recent matches by clan.
9.2901
9.066385
1.024675
return get_recent_matches(session, '{}{}/{}/Matches/games/matches/user/{}/0'.format( session.auth.base_url, PROFILE_URL, user_id, user_id), from_timestamp, limit)
def get_user_matches(session, user_id, from_timestamp=None, limit=None)
Get recent matches by user.
10.241799
9.231492
1.109441
if not from_timestamp: from_timestamp = datetime.datetime.now() - datetime.timedelta(days=1) matches = [] page_id = 0 done = False while not done and page_id < MAX_MATCH_PAGE_ID: url = '{}/{}'.format(init_url, page_id) parsed = make_scrape_request(session, url) f...
def get_recent_matches(session, init_url, from_timestamp, limit)
Get recently played user matches.
2.454657
2.434483
1.008287
if not from_timestamp: from_timestamp = datetime.datetime.now() - datetime.timedelta(days=1) matches = [] page_id = 0 done = False i = 0 while not done and page_id < MAX_LADDER_PAGE_ID: url = '{}{}/{}/{}'.format(session.auth.base_url, LADDER_MATCHES_URL, lookup_ladder_id(lad...
def get_ladder_matches(session, ladder_id, from_timestamp=None, limit=LADDER_MATCH_LIMIT)
Get recently played ladder matches.
2.596197
2.556905
1.015367
url = '{}{}/{}'.format(session.auth.base_url, MATCH_URL, match_id) parsed = make_scrape_request(session, url) game = parsed.find('h3').text if game != GAME_AOC: raise ValueError('not an aoc match') date_played = parsed.find(text=MATCH_DATE_PLAYED).find_next('td').text players = [] ...
def get_match(session, match_id)
Get match metadata.
2.983876
2.979259
1.00155
try: resp = session.get(session.auth.base_url + rec_url) except RequestException: raise VooblyError('failed to connect for download') try: downloaded = zipfile.ZipFile(io.BytesIO(resp.content)) downloaded.extractall(target_path) except zipfile.BadZipFile: rai...
def download_rec(session, rec_url, target_path)
Download and extract a recorded game.
3.583711
3.592072
0.997672
if not session.auth.username or not session.auth.password: raise VooblyError('must supply username and password') _LOGGER.info("logging in (no valid cookie found)") session.cookies.clear() try: session.get(session.auth.base_url + LOGIN_PAGE) resp = session.post(session.auth....
def login(session)
Login to Voobly.
3.225079
2.838268
1.136284
class VooblyAuth(AuthBase): # pylint: disable=too-few-public-methods def __init__(self, key, username, password, cookie_path, version): self.key = key self.username = username self.password = password self.cookie_path = cookie_path...
def get_session(key=None, username=None, password=None, cache=True, cache_expiry=datetime.timedelta(days=7), cookie_path=COOKIE_PATH, backend='memory', version=VERSION_GLOBAL)
Get Voobly API session.
2.697715
2.404716
1.121844
neutron_config.register_agent_state_opts_helper(CONF) common_config.init(sys.argv[1:]) neutron_config.setup_logging() hyperv_agent = HyperVNeutronAgent() # Start everything. LOG.info("Agent initialized successfully, now running... ") hyperv_agent.daemon_loop()
def main()
The entry point for the Hyper-V Neutron Agent.
5.08356
3.498836
1.452929
super(HyperVNeutronAgent, self)._setup() self._sg_plugin_rpc = sg_rpc.SecurityGroupServerRpcApi(topics.PLUGIN) self._sec_groups_agent = HyperVSecurityAgent(self._context, self._sg_plugin_rpc) self._vlan_driver = trunk_driver....
def _setup(self)
Setup the layer two agent.
5.925374
5.54031
1.069502
if not CONF.AGENT.enable_qos_extension: return self._qos_ext = qos_extension.QosAgentExtension() self._qos_ext.consume_api(self) self._qos_ext.initialize(self._connection, 'hyperv')
def _setup_qos_extension(self)
Setup the QOS extension if it is required.
4.271727
3.755359
1.137501
LOG.info("Provisioning network %s", net_uuid) vswitch_name = self._get_vswitch_name(network_type, physical_network) if network_type == h_constant.TYPE_VLAN: # Nothing to do pass elif network_type == h_constant.TYPE_FLAT: # Nothing to do ...
def _provision_network(self, port_id, net_uuid, network_type, physical_network, segmentation_id)
Provision the network with the received information.
2.816916
2.82335
0.997721
super(HyperVNeutronAgent, self)._port_bound( port_id, network_id, network_type, physical_network, segmentation_id, port_security_enabled, set_port_sriov ) vswitch_map = self._network_vswitch_map[network_id] if network_type == h_constant.TYPE_VLAN: ...
def _port_bound(self, port_id, network_id, network_type, physical_network, segmentation_id, port_security_enabled, set_port_sriov)
Bind the port to the recived network.
3.036713
3.052802
0.99473
super(HyperVNeutronAgent, self)._work() if self._nvgre_enabled: self._nvgre_ops.refresh_nvgre_records() self._port_enable_control_metrics()
def _work(self)
Process the information regarding the available ports.
11.808751
10.533284
1.121089
if magic_name == 'bash': self.shebang("bash", cell) elif magic_name == 'metatab': self.mm.metatab(line, cell)
def run_cell_magic(self, magic_name, line, cell)
Run a limited number of magics from scripts, without IPython
7.906916
8.355385
0.946326
if cmd.rstrip().endswith('&'): # this is *far* from a rigorous test # We do not support backgrounding processes because we either use # pexpect or pipes to read from. Users can always just call # os.system() or use ip.system=ip.system_raw # i...
def system_piped(self, cmd)
Call the given cmd in a subprocess, piping stdout/err Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. Should not be a command that expects input other than simple text.
14.713912
13.303632
1.106007
ns = self.user_ns.copy() try: frame = sys._getframe(depth + 1) except ValueError: # This is thrown if there aren't that many frames on the stack, # e.g. if a script called run_line_magic() directly. pass else: ns.update...
def var_expand(self, cmd, depth=0, formatter=DollarFormatter())
Expand python variables in a string. The depth argument indicates how many frames above the caller should be walked to look for the local namespace where to expand variables. The global namespace for expansion is always the user's interactive namespace.
6.683825
6.623328
1.009134
argv = arg_split(line, posix=not sys.platform.startswith('win')) args, cmd = self.shebang.parser.parse_known_args(argv) try: p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE) except OSError as e: if e.errno == errno.ENOENT: print("Coul...
def shebang(self, line, cell)
Run a cell via a shell command The `%%script` line is like the #! line of script, specifying a program (bash, perl, ruby, etc.) with which to run. The rest of the cell is run by that program. Examples -------- :: In [1]: %%script bash ...: f...
2.31061
2.368209
0.975678
zero_fn = (lambda: 0) vertices_neighbours = defaultdict(lambda: defaultdict(zero_fn)) for net in nets: if net.weight != 0: for sink in net.sinks: vertices_neighbours[net.source][sink] += net.weight vertices_neighbours[sink][net.source] += net.weight ...
def _get_vertices_neighbours(nets)
Generate a listing of each vertex's immedate neighbours in an undirected interpretation of a graph. Returns ------- {vertex: {vertex: weight, ...}), ...}
2.809004
2.903524
0.967446
visited = set() to_visit = deque([vertex]) while to_visit: vertex = to_visit.pop() if vertex not in visited: yield vertex visited.add(vertex) to_visit.extend(vertices_neighbours[vertex])
def _dfs(vertex, vertices_neighbours)
Generate all the vertices connected to the supplied vertex in depth-first-search order.
1.858212
1.79851
1.033195
remaining_vertices = set(vertices) subgraphs = [] while remaining_vertices: subgraph = set(_dfs(remaining_vertices.pop(), vertices_neighbours)) remaining_vertices.difference_update(subgraph) subgraphs.append(subgraph) return subgraphs
def _get_connected_subgraphs(vertices, vertices_neighbours)
Break a graph containing unconnected subgraphs into a list of connected subgraphs. Returns ------- [set([vertex, ...]), ...]
2.606837
3.037762
0.858144
vertices_degrees = {v: sum(itervalues(vertices_neighbours[v])) for v in vertices} peripheral_vertex = min(vertices, key=(lambda v: vertices_degrees[v])) visited = set([peripheral_vertex]) cm_order = [peripheral_vertex] previous_layer = set([peripheral_vertex]) whil...
def _cuthill_mckee(vertices, vertices_neighbours)
Yield the Cuthill-McKee order for a connected, undirected graph. `Wikipedia <https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_ provides a good introduction to the Cuthill-McKee algorithm. The RCM algorithm attempts to order vertices in a graph such that their adjacency matrix's bandw...
2.67599
2.803425
0.954543
vertices_neighbours = _get_vertices_neighbours(nets) for subgraph_vertices in _get_connected_subgraphs(vertices_resources, vertices_neighbours): cm_order = _cuthill_mckee(subgraph_vertices, vertices_neighbours) for vertex in reversed(cm_...
def rcm_vertex_order(vertices_resources, nets)
A generator which iterates over the vertices in Reverse-Cuthill-McKee order. For use as a vertex ordering for the sequential placer.
4.368251
3.908691
1.117574
# Convert the Machine description into a placement-problem-style-graph # where the vertices are chip coordinate tuples (x, y) and each net # represents the links leaving each chip. This allows us to re-use the # rcm_vertex_order function above to generate an RCM ordering of chips in # the machi...
def rcm_chip_order(machine)
A generator which iterates over a set of chips in a machine in Reverse-Cuthill-McKee order. For use as a chip ordering for the sequential placer.
7.184869
7.040672
1.020481
return sequential_place(vertices_resources, nets, machine, constraints, rcm_vertex_order(vertices_resources, nets), rcm_chip_order(machine))
def place(vertices_resources, nets, machine, constraints)
Assigns vertices to chips in Reverse-Cuthill-McKee (RCM) order. The `RCM <https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_ algorithm (in graph-centric terms) is a simple breadth-first-search-like heuristic which attempts to yield an ordering of vertices which would yield a 1D placement ...
7.698292
7.944179
0.969048
if tracer is None: from ddtrace import tracer @signals.job_started.connect_via(namespace) def job_started(namespace, job, **kwargs): tracer.trace( 'spinach.task', service=service, span_type='worker', resource=job.task_name ) @signals.job_finished.co...
def register_datadog(tracer=None, namespace: Optional[str]=None, service: str='spinach')
Register the Datadog integration. Exceptions making jobs fail are sent to Sentry. :param tracer: optionally use a custom ddtrace Tracer instead of the global one. :param namespace: optionally only register the Datadog integration for a particular Spinach :class:`Engine` :param se...
2.206145
2.204366
1.000807
yield from doc.reference(resource.name)
def copy_reference(resource, doc, env, *args, **kwargs)
A row-generating function that yields from a reference. This permits an upstream package to be copied and modified by this package, while being formally referenced as a dependency The function will generate rows from a reference that has the same name as the resource term
33.418648
25.888615
1.290863
all_headers = [] # Combine all of the headers into a list of tuples by position for ref in doc.references(): if ref.get_value('Group') == resource.get_value('Group'): for row in ref.iterrowproxy(): all_headers.append(list(row.keys())) break # F...
def copy_reference_group(resource, doc, env, *args, **kwargs)
A Row generating function that copies all of the references that have the same 'Group' argument as this reference The 'RefArgs' argument is a comma seperated list of arguments from the references that will be prepended to each row. :param resource: :param doc: :param env: :param args: :par...
4.498264
3.932358
1.14391
try: path = self.doc_file.path except AttributeError: path = self.doc_file source_ref = self._doc.ref.path try: age_diff = getmtime(source_ref) - getmtime(path) return age_diff > 0 except (FileNotFoundError, OSError): ...
def is_older_than_metadata(self)
Return True if the package save file is older than the metadata. If it is, it should be rebuilt. Returns False if the time of either can't be determined :param path: Optional extra save path, used in save_path()
5.685132
5.462749
1.040709
from itertools import islice from metapack.exc import MetapackError from os.path import splitext # Refetch the resource ... IIRC b/c the source_r resource may actually be from # a different package. So r is the resource we want to possibly modify in this package, ...
def _load_resource(self, source_r, abs_path=False)
The CSV package has no resources, 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.
7.630189
7.513504
1.01553
try: title = term['title'].value except KeyError: self.warn("Documentation has no title, skipping: '{}' ".format(term.value)) return if term.term_is('Root.Readme'): # This term type has inline content, not a url package_sub_dir = 'docs' ...
def _load_documentation(self, term, contents, file_name)
Load a single documentation entry
5.87676
5.744211
1.023075
if isinstance(obj, datetime.datetime): serial = obj.isoformat(sep='T') return serial if isinstance(obj, uuid.UUID): serial = str(obj) return serial try: return obj.__dict__ except AttributeError: return str(obj) except Exception as e: st...
def serialize(obj)
JSON serializer for objects not serializable by default json code
3.296391
3.185216
1.034903
try: # top level payload items d = record.__dict__ pid = d.pop('process', 'nopid') tid = d.pop('thread', 'notid') payload = { k: v for (k, v) in d.items() if k in TOP_KEYS } # logging ...
def _getPayload(self, record)
The data that will be sent to the RESTful API
3.28447
3.373707
0.973549
payload = self._getPayload(record) json_data = json.dumps(payload, default=serialize) return { 'json': (json_data, 'application/json') }.get(self.content_type, (json_data, 'text/plain'))
def _prepPayload(self, record)
record: generated from logger module This preps the payload to be formatted in whatever content-type is expected from the RESTful API. returns: a tuple of the data and the http content-type
3.849159
3.655659
1.052932
# avoid infinite recursion if record.name.startswith('requests'): return data, header = self._prepPayload(record) try: self.session.post(self._getEndpoint(), data=data, headers={'content-type':...
def emit(self, record)
Override emit() method in handler parent for sending log to RESTful API
5.10575
4.550022
1.122137
return 'https://logs-01.loggly.com/bulk/{0}/tag/{1}/'.format( self.custom_token, self._implodeTags(add_tags=add_tags) )
def _getEndpoint(self, add_tags=None)
Override Build Loggly's RESTful API endpoint
8.004826
5.289724
1.513278
payload = super(LogglyHandler, self)._getPayload(record) payload['tags'] = self._implodeTags() return payload
def _getPayload(self, record)
The data that will be sent to loggly.
6.657087
5.022665
1.325409
pid = os.getpid() if pid != self.pid: self.pid = pid self.logs = [] self.timer = self._flushAndRepeatTimer() atexit.register(self._stopFlushTimer) # avoid infinite recursion if record.name.startswith('requests'): retu...
def emit(self, record)
Override emit() method in handler parent for sending log to RESTful API
5.552752
5.65381
0.982126
nv = self.as_version(None) if not nv: import re nv = re.sub(r'-[^-]+$', '', self.name) return nv
def nonver_name(self)
Return the non versioned name
7.341432
6.060271
1.211403
return ' '.join(e.value.strip() for e in self['Root'].find(term) if e and e.value)
def wrappable_term(self, term)
Return the Root.Description, possibly combining multiple terms. :return:
15.830333
12.503917
1.26603
import textwrap for t in self['Root'].find(term): self.remove_term(t) for l in textwrap.wrap(v, 80): self['Root'].new_term(term, l)
def set_wrappable_term(self, v, term)
Set the Root.Description, possibly splitting long descriptions across multiple terms.
6.983888
5.305042
1.316462
from importlib import import_module if not self.ref: return {} u = parse_app_url(self.ref) if u.scheme == 'file': if not self.set_sys_path(): return {} for module_name in self.lib_dir_names: try: ...
def get_lib_module_dict(self)
Load the 'lib' directory as a python module, so it can be used to provide functions for rowpipe transforms. This only works filesystem packages
5.701871
5.347962
1.066176
from jinja2 import Template from markdown import markdown as convert_markdown extensions = [ 'markdown.extensions.extra', 'markdown.extensions.admonition' ] return convert_markdown(self.markdown, extensions)
def _repr_html_(self, **kwargs)
Produce HTML for Jupyter Notebook
4.766233
4.39952
1.083353
# Sort the Sections self.sort_sections(['Root', 'Contacts', 'Documentation', 'References', 'Resources', 'Citations', 'Schema']) # Sort Terms in the root section # Re-wrap the description and abstract if self.description: self.description = self.descriptio...
def write_csv(self, path=None)
Write CSV file. Sorts the sections before calling the superclass write_csv
9.684631
8.716174
1.11111
option = yield MultipleChoice( "What type of SpiNNaker system to you have?", ["A single four-chip 'SpiNN-3' board", "A single forty-eight-chip 'SpiNN-5' board", "Multiple forty-eight-chip 'SpiNN-5' boards", "Other"], None) assert 0 <= option < 4 if op...
def dimensions_wizard()
A wizard which attempts to determine the dimensions of a SpiNNaker system. .. warning:: Since SC&MP v2.0.0 it is not necessary to know the dimensions of a SpiNNaker machine in order to boot it. As a result, most applications will no longer require this wizard step. Returns ``{"dim...
3.831644
3.578563
1.070721
option = yield MultipleChoice( "Would you like to auto-detect the SpiNNaker system's IP address?", ["Auto-detect", "Manually Enter IP address or hostname"], 0) assert 0 <= option < 2 if option == 0: yield Prompt( "Make sure the SpiNNaker system is s...
def ip_address_wizard()
A wizard which attempts to determine the IP of a SpiNNaker system. Returns ``{"ip_address": "..."}`` via the :py:exc:`~rig.wizard.Success` exception.
5.100265
4.524779
1.127185
data = {} for wizard in wizards: try: response = None while True: response = yield wizard.send(response) except Success as s: data.update(s.data) raise Success(data)
def cat(*wizards)
A higher-order wizard which is the concatenation of a number of other wizards. The resulting data is the union of all wizard outputs.
4.338398
4.62376
0.938284
first = True response = None while True: # Insert blank lines between prompts if not first: print() first = False try: message = generator.send(response) if isinstance(message, MultipleChoice): print(message.question)...
def cli_wrapper(generator)
Given a wizard, implements an interactive command-line human-friendly interface for it. Parameters ---------- generator A generator such as one created by calling :py:func:`rig.wizard.wizard_generator`. Returns ------- dict or None Returns a dictionary containing th...
2.765025
2.888818
0.957148
# This function is by far the hottest code in the entire algorithm, as a # result, small performance improvements in here can have significant # impact on the runtime of the overall algorithm. As an unfortunate side # effect, this code is rather ugly since many higher-level constructs (e.g. # m...
def _net_cost(net, placements, has_wrap_around_links, machine)
Get the cost of a given net. This function, in principle at least, should estimate the total network resources consumed by the given net. In practice this estimate is based on the size of the bounding-box of the net (i.e. HPWL). This should be improved at some later time to better account for the effec...
3.38066
3.254412
1.038793
total_cost = 0.0 for net in v2n[vertex]: total_cost += _net_cost(net, placements, has_wrap_around_links, machine) return total_cost
def _vertex_net_cost(vertex, v2n, placements, has_wrap_around_links, machine)
Get the total cost of the nets connected to the given vertex. Parameters ---------- vertex The vertex whose nets we're interested in. v2n : {vertex: [:py:class:`rig.netlist.Net`, ...], ...} placements : {vertex: (x, y), ...} has_wrap_around_links : bool machine : :py:class:`rig.plac...
2.58257
2.896386
0.891652
# The resources already available at the given location chip_resources = machine[location] # The set of vertices at that location vertices = l2v[location] # The set of vertices to be moved from the location to free up the # specified amount of resources to_move = [] # While there...
def _get_candidate_swap(resources, location, l2v, vertices_resources, fixed_vertices, machine)
Given a chip location, select a set of vertices which would have to be moved elsewhere to accommodate the arrival of the specified set of resources. Parameters ---------- resources : {resource: value, ...} The amount of resources which are required at the specified location. location : ...
5.918216
5.263332
1.124424
# Get the lists of vertices at either location vas_location2v = l2v[vas_location] vbs_location2v = l2v[vbs_location] # Get the resource availability at either location vas_resources = machine[vas_location] vbs_resources = machine[vbs_location] # Move all the vertices in vas into vbs. ...
def _swap(vas, vas_location, vbs, vbs_location, l2v, vertices_resources, placements, machine)
Swap the positions of two sets of vertices. Parameters ---------- vas : [vertex, ...] A set of vertices currently at vas_location. vas_location : (x, y) vbs : [vertex, ...] A set of vertices currently at vbs_location. vbs_location : (x, y) l2v : {(x, y): [vertex, ...], ...} ...
1.986359
1.942039
1.022822
self._subscriber_thread = None self._must_stop = threading.Event() self._number_periodic_tasks = 0
def _reset(self)
Initialization that must happen before the broker is (re)started.
11.725724
8.684803
1.350143
with open(path.join(here, 'redis_scripts', filename), mode='rb') as f: script_data = f.read() rv = self._r.register_script(script_data) if script_data.startswith(b'-- idempotency protected script'): self._idempotency_protected_scripts.append(rv) return rv
def _load_script(self, filename: str) -> Script
Load a Lua script. Read the Lua script file to generate its Script object. If the script starts with a magic string, add it to the list of scripts requiring an idempotency token to execute.
5.361912
4.618956
1.160849