code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
path = os.path.join(self.directory, filename) # spec = spec_from_file_location("migration", path) # module = module_from_spec(spec) # spec.loader.exec_module(module) module = imp.load_source("migration", path) return module
def load_migration_file(self, filename)
Load migration file as module.
2.319972
2.161204
1.073463
if migration_id is not None: migration_id = MigrationFile.validate_id(migration_id) if not migration_id: return [] migrations = self.get_unregistered_migrations() if not migrations: logger.info(self.NO_MIGRATIONS_MSG) retu...
def get_migrations_to_up(self, migration_id=None)
Find migrations to execute.
3.008275
2.938336
1.023802
if not self.check_directory(): return for migration in self.get_migrations_to_up(migration_id): logger.info('Executing migration: %s' % migration.filename) migration_module = self.load_migration_file(migration.filename) if not fake: ...
def up(self, migration_id=None, fake=False)
Executes migrations.
3.163131
3.092043
1.02299
migration_id = MigrationFile.validate_id(migration_id) if not migration_id: return [] migrations = self.get_migration_files() last_migration_id = self.get_last_migrated_id() if migration_id in (m.id for m in self.get_unregistered_migrations()): ...
def get_migrations_to_down(self, migration_id)
Find migrations to rollback.
2.987079
2.909011
1.026837
if not self.check_directory(): return for migration in self.get_migrations_to_down(migration_id): logger.info('Rollback migration %s' % migration.filename) migration_module = self.load_migration_file(migration.filename) if hasattr(migration_modu...
def down(self, migration_id)
Rollback to migration.
3.129081
3.041144
1.028916
profile = kwargs.pop('profile', None) if profile is not None and not isinstance(profile, UserProfile): profile = UserProfile(**profile) if kwargs.get('id'): profile.user_id = kwargs['id'] kwargs['profile'] = profile
def on_user_init(target, args, kwargs)
Provide hook on :class:`~invenio_accounts.models.User` initialization. Automatically convert a dict to a :class:`~.UserProfile` instance. This is needed during e.g. user registration where Flask-Security will initialize a user model with all the form data (which when Invenio-UserProfiles is enabled...
3.164454
2.767222
1.143549
validate_username(username) self._username = username.lower() self._displayname = username
def username(self, username)
Set username. .. note:: The username will be converted to lowercase. The display name will contain the original version.
6.339005
6.558725
0.9665
return cls.query.filter( UserProfile._username == username.lower() ).one()
def get_by_username(cls, username)
Get profile by username. :param username: A username to query for (case insensitive).
8.980258
8.843247
1.015493
if settings.DEBUG and not ON_DEBUG: return sitemetricsDummyNode() tokens = token.split_contents() tokens_num = len(tokens) if tokens_num == 1: # Notation Type 1 current_site = Site.objects.get_current() cached = cache.get('sitemetrics') if not cached or cu...
def sitemetrics(parser, token)
Renders sitemetrics counter. Two notation types are possible: 1. No arguments: {% sitemetrics %} Used to render all metrics counters registered and active for the current site. This requires 'Admin site' and 'Sites' Django contribs. 2. Four argume...
3.553808
3.130192
1.135332
if inspect.isclass(obj): cls_name = obj.__name__ else: cls_name = obj.__class__.__name__ mod = inspect.getmodule(obj) if mod: name = mod.__name__ # jython if name.startswith('org.python.core.'): name = name[len('org.python.core.'):] return...
def nice_classname(obj)
Returns a nice name for class object or class instance. >>> nice_classname(Exception()) # doctest: +ELLIPSIS '...Exception' >>> nice_classname(Exception) # doctest: +ELLIPSIS '...Exception'
2.185377
2.544014
0.859027
exc = exc_info[1] if exc is None: # str exception result = exc_info[0] else: try: result = str(exc) except UnicodeEncodeError: try: result = unicode(exc) # flake8: noqa except UnicodeError: # Fallback t...
def exc_message(exc_info)
Return the exception's message.
4.725709
4.599318
1.02748
Plugin.options(self, parser, env) parser.add_option( '--html-file', action='store', dest='html_file', metavar="FILE", default=env.get('NOSE_HTML_FILE', 'nosetests.html'), help="Path to html file to store the report in. " "Default ...
def options(self, parser, env)
Sets additional command line options.
2.960838
2.902812
1.01999
Plugin.configure(self, options, config) self.config = config if self.enabled: self.jinja = Environment( loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')), trim_blocks=True, lstrip_blocks=True ...
def configure(self, options, config)
Configures the xunit plugin.
3.185986
2.917301
1.092101
from collections import OrderedDict self.stats['total'] = sum(self.stats.values()) for group in self.report_data.values(): group.stats['total'] = sum(group.stats.values()) self.report_file.write(self.jinja.get_template('report.html').render( report=Ordere...
def report(self, stream)
Writes an Xunit-formatted XML file The file includes a report of test errors and failures.
2.957828
2.913143
1.015339
exc_type, exc_val, tb = err tb = ''.join(traceback.format_exception( exc_type, exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val), tb )) name = id_split(test.id()) group = self.report_data[name[0]] if issubclass(er...
def addError(self, test, err, capt=None)
Add error output to Xunit report.
3.17914
3.087425
1.029706
all_messages = [] for storage in self.storages: messages, all_retrieved = storage._get() # If the backend hasn't been used, no more retrieval is necessary. if messages is None: break if messages: self._used_storages...
def _get(self, *args, **kwargs)
Gets a single list of messages from all storage backends.
5.423314
4.411092
1.229472
for storage in self.storages: if messages: messages = storage._store(messages, response, remove_oldest=False) # Even if there are no more messages, continue iterating to ensure # storages which contained messages are flushed. ...
def _store(self, messages, response, *args, **kwargs)
Stores the messages, returning any unstored messages after trying all backends. For each storage backend, any messages not stored are passed on to the next backend.
6.461905
6.09204
1.060713
expire = timezone.now() qs = PersistentMessage.objects.\ filter(user=self.get_user()).\ filter(Q(expires=None) | Q(expires__gt=expire)) if not include_read: qs = qs.exclude(read=True) return qs
def _message_queryset(self, include_read=False)
Return a queryset of messages for the request user
4.329877
3.942303
1.098311
is_authenticated = self.get_user().is_authenticated if callable(is_authenticated): is_authenticated = is_authenticated() if is_authenticated is not True: return [], False return self._message_queryset(), False
def _get(self, *args, **kwargs)
Retrieves a list of stored messages. Returns a tuple of the messages and a flag indicating whether or not all the messages originally intended to be stored in this storage were, in fact, stored and retrieved; e.g., ``(messages, all_retrieved)``.
5.056171
4.271476
1.183706
if not message.level in PERSISTENT_MESSAGE_LEVELS: return message user = kwargs.get("user") or self.get_user() try: anonymous = user.is_anonymous() except TypeError: anonymous = user.is_anonymous if anonymous: raise NotIm...
def process_message(self, message, *args, **kwargs)
If its level is into persist levels, convert the message to models and save it
3.76722
3.446454
1.093072
if not message: return # Check that the message level is not less than the recording level. level = int(level) if level < self.level: return # Add the message. self.added_new = True message = Message(level, message, extra_t...
def add(self, level, message, extra_tags='', *args, **kwargs)
Queues a message to be stored. The message is only queued if it contained something and its level is not less than the recording level (``self.level``).
4.107969
3.724944
1.102827
return [message for message in messages if not message.level in STICKY_MESSAGE_LEVELS]
def _store(self, messages, response, *args, **kwargs)
Delete all messages that are sticky and return the other messages This storage never save objects
11.212847
6.716881
1.669353
if current_user.is_anonymous: return AnonymousUserProfile() profile = g.get( 'userprofile', UserProfile.get_by_userid(current_user.get_id())) if profile is None: profile = UserProfile(user_id=int(current_user.get_id())) g.userprofile = profile return profil...
def _get_current_userprofile()
Get current user profile. .. note:: If the user is anonymous, then a :class:`invenio_userprofiles.models.AnonymousUserProfile` instance is returned. :returns: The :class:`invenio_userprofiles.models.UserProfile` instance.
2.886701
2.988467
0.965947
levels = levels or ["DEBUG", "INFO"] for level in levels: if level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"): raise ValueError("unknown log level: {0}".format(level)) for _, module_name, _ in pkgutil.iter_modules(ibapi.__path__): module = __import__("ibapi.{...
def silence_ibapi_logging(levels=["DEBUG", "INFO"])
Silences the excessive ibapi logging to the root logger.
2.330611
2.245864
1.037735
if hasattr(request, '_messages'): return request._messages.add(level, message, extra_tags, *args, **kwargs) if not fail_silently: raise MessageFailure('You cannot add messages without installing ' 'django.contrib.messages.middleware.MessageMiddleware')
def add_message(request, level, message, extra_tags='', fail_silently=False, *args, **kwargs)
Attempts to add a message to the request using the 'messages' app.
3.315926
3.261894
1.016564
add_message(request, DEBUG_PERSISTENT, message, extra_tags=extra_tags, fail_silently=fail_silently, *args, **kwargs)
def persistant_debug(request, message, extra_tags='', fail_silently=False, *args, **kwargs)
Adds a persistant message with the ``DEBUG`` level.
2.749147
2.708318
1.015075
add_message(request, INFO_PERSISTENT, message, extra_tags=extra_tags, fail_silently=fail_silently, *args, **kwargs)
def persistant_info(request, message, extra_tags='', fail_silently=False, *args, **kwargs)
Adds a persistant message with the ``INFO`` level.
3.146793
2.87034
1.096314
add_message(request, SUCCESS_PERSISTENT, message, extra_tags=extra_tags, fail_silently=fail_silently, *args, **kwargs)
def persistant_success(request, message, extra_tags='', fail_silently=False, *args, **kwargs)
Adds a persistant message with the ``SUCCESS`` level.
3.145281
2.857205
1.100824
add_message(request, WARNING_PERSISTENT, message, extra_tags=extra_tags, fail_silently=fail_silently, *args, **kwargs)
def persistant_warning(request, message, extra_tags='', fail_silently=False, *args, **kwargs)
Adds a persistant message with the ``WARNING`` level.
3.364716
3.055143
1.101328
add_message(request, ERROR_PERSISTENT, message, extra_tags=extra_tags, fail_silently=fail_silently, *args, **kwargs)
def persistant_error(request, message, extra_tags='', fail_silently=False, *args, **kwargs)
Adds a persistant message with the ``ERROR`` level.
3.216265
2.88448
1.115024
for i in range(0, len(items), limit): yield items[i:i + limit]
def _chunks(self, items, limit)
Yield successive chunks from list \a items with a minimum size \a limit
2.35191
2.133205
1.102524
if not isinstance(data, dict): data = {'msg': data} registration_ids = registration_ids or [] if len(registration_ids) > conf.GCM_MAX_RECIPIENTS: ret = [] for chunk in self._chunks( registration_ids, conf.GCM_MAX_RECIPIENTS): ...
def send(self, data, registration_ids=None, **kwargs)
Send a GCM message for one or more devices, using json data registration_ids: A list with the devices which will be receiving a message data: The dict data which will be send Optional params e.g.: collapse_key: A string to group messages For more info see the following docume...
2.639445
2.689029
0.981561
if ordinal < 1: raise ValueError("ordinal must be >= 1") return super(Week, cls).__new__(cls, *(date.fromordinal((ordinal-1) * 7 + 1).isocalendar()[:2]))
def fromordinal(cls, ordinal)
Return the week corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 starts the week with ordinal 1.
3.548212
3.162986
1.121792
if isinstance(isostring, basestring) and len(isostring) == 7 and isostring[4] == 'W': return cls(int(isostring[0:4]), int(isostring[5:7])) elif isinstance(isostring, basestring) and len(isostring) == 8 and isostring[4:6] == '-W': return cls(int(isostring[0:4]), int(isostri...
def fromstring(cls, isostring)
Return a week initialized from an ISO formatted string like "2011W08" or "2011-W08".
2.733054
2.251018
1.214141
w = cls(year, 1) while w.year == year: yield w w += 1
def weeks_of_year(cls, year)
Return an iterator over the weeks of the given year. Years have either 52 or 53 weeks.
4.375281
3.633319
1.204211
if year == cls.max.year: return cls.max return cls(year+1, 0)
def last_week_of_year(cls, year)
Return the last week of the given year. This week with either have week-number 52 or 53. This will be the same as Week(year+1, 0), but will even work for year 9999 where this expression would overflow. The first week of a given year is simply Week(year, 1), so there is no dedic...
6.40273
5.30244
1.207506
d = date(self.year, 1, 4) # The Jan 4th must be in week 1 according to ISO return d + timedelta(weeks=self.week-1, days=-d.weekday() + num)
def day(self, num)
Return the given day of week as a date object. Day 0 is the Monday.
6.534186
4.935442
1.323931
monday = self.day(0) return [monday + timedelta(days=i) for i in range(7)]
def days(self)
Return the 7 days of the week as a list (of datetime.date objects)
5.201421
3.425627
1.518385
return self.__class__(self.year if year is None else year, self.week if week is None else week)
def replace(self, year=None, week=None)
Return a Week with either the year or week attribute value replaced
3.262153
2.642762
1.234372
dt = datetime.strptime(ts[:19],"%Y-%m-%dT%H:%M:%S") if ts[19] == '+': dt -= timedelta(hours=int(ts[20:22]),minutes=int(ts[23:])) elif ts[19] == '-': dt += timedelta(hours=int(ts[20:22]),minutes=int(ts[23:])) return dt.replace(tzinfo=pytz.UTC)
def _ts_parse(ts)
Parse alert timestamp, return UTC datetime object to maintain Python 2 compatibility.
1.739349
1.672074
1.040235
return {'title': self.title, 'summary': self.summary, 'areadesc': self.areadesc, 'event': self.event, 'samecodes': self.samecodes, 'zonecodes': self.zonecodes, 'expiration': self.expiration, ...
def _serialized(self)
Provides a sanitized & serializeable dict of the alert mainly for forward & backwards compatibility
3.472281
3.050649
1.138211
kind = "{prefix}buf".format(prefix=prefix) private_name = "_" + kind buf = getattr(self, private_name) if buf: return buf try: buf_string = self.raw_data["result"][kind] except KeyError: buf_string = self.ensure(kind, str) ...
def _get_buf(self, prefix)
Lazy read-only accessor for the (a|q)buf. The qbuf Message object is cached for subsequent requests.
4.082076
3.885754
1.050523
responses = [] part_of_set = True # Account for single results if "result" in self.raw_data: if "qbuf" in self.raw_data: if "qbuf" not in self.raw_data["result"]: self.raw_data["result"]["qbuf"] = self.raw_data.pop("qbuf") ...
def build_responses(self)
DNS measurement results are a little wacky. Sometimes you get a single response, other times you get a set of responses (result set). In order to establish a unified interface, we conform all results to the same format: a list of response objects. Additionally, the qbuf property is we...
4.367594
3.570324
1.223305
if protocol is not None: try: return self.PROTOCOL_MAP[protocol] except KeyError: self._handle_malformation( '"{protocol}" is not a recognised protocol'.format( protocol=protocol ) ...
def clean_protocol(self, protocol)
A lot of measurement types make use of a protocol value, so we handle that here.
4.847366
4.354706
1.113133
raw_data = data if isinstance(data, string): raw_data = Json.loads(data) try: kind = raw_data["type"].lower() except KeyError: raise ResultParseError("No type value was found in the JSON input") if kind == "ping": from ....
def get(cls, data, **kwargs)
Call this when you have a JSON result and just want to turn it into the appropriate Result subclass. This is less performant than calling PingResult(json_string) directly however, as the JSON has to be parsed first to find the type.
2.127162
1.901542
1.118651
median = None if not given_list: return median given_list = sorted(given_list) list_length = len(given_list) if list_length % 2: median = given_list[int(list_length / 2)] else: median = (given_list[int(list_length / 2)] + gi...
def calculate_median(given_list)
Returns the median of values in the given list.
1.661497
1.581609
1.050511
path = filter(None, env['PATH_INFO'].split('/')) handler = getattr(self, 'handle_%s' % path[0], None) if not handler: return '404 Not Found', '%(PATH_INFO)s not found' % env return handler(env)
def dispatch(self, env)
very simple URL dispatch, a la Cake: /zelink maps to handle_zelink
3.84873
3.383614
1.137461
return "".join( "/{}={}".format( self._get_oid_name(attr.oid), attr.value, ) for attr in name )
def _name_attribute_to_string(self, name)
Build a /-separated string from an x509.Name.
6.76309
3.611222
1.872798
values = [] for san in ext.value: if isinstance(san.value, string): # Pass on simple string SAN values values.append(san.value) elif isinstance(san.value, x509.Name): # In theory there there could be >1 RDN here... ...
def _get_subject_alternative_names(self, ext)
Return a list of Subject Alternative Name values for the given x509 extension object.
6.456894
5.740691
1.124759
checksums = [] for certificate in self.certificates: checksums.append(certificate.checksum) return "::".join(checksums)
def checksum_chain(self)
Returns a list of checksums joined with "::".
5.66522
3.017117
1.877693
# Convert standard SPI sheme to USBISS scheme lookup_table = [0, 2, 1, 3] mode = lookup_table[self._mode] # Add signal for SPI switch iss_mode = self._usbiss.SPI_MODE + mode # Configure USB-ISS self._usbiss.mode = [iss_mode, self.sck_divisor]
def configure(self)
Configure SPI controller with the SPI mode and operating frequency
14.651505
12.144949
1.206387
_divisor = (6000000 / sck) - 1 divisor = int(_divisor) if divisor != _divisor: raise ValueError('Non-integer SCK divisor.') if not 1 <= divisor < 256: error = ( "The value of sck_divisor, {}, " "is not between 0 and 255"....
def iss_spi_divisor(self, sck)
Calculate a USBISS SPI divisor value from the input SPI clock speed :param sck: SPI clock frequency :type sck: int :returns: ISS SCK divisor :rtype: int
4.52863
4.472999
1.012437
self._usbiss.write_data([self._usbiss.SPI_CMD] + data) response = self._usbiss.read_data(1 + len(data)) if len(response) != 0: response = self._usbiss.decode(response) status = response.pop(0) if status == 0: raise USBISSError('SPI Tra...
def exchange(self, data)
Perform SPI transaction. The first received byte is either ACK or NACK. :TODO: enforce rule that up to 63 bytes of data can be sent. :TODO: enforce rule that there is no gaps in data bytes (what define a gap?) :param data: List of bytes :returns: List of bytes :rtype: ...
4.547418
4.124715
1.10248
feed_cache = None if os.path.exists(self._feed_cache_file): maxage = datetime.now() - timedelta(minutes=self._cachetime) file_ts = datetime.fromtimestamp(os.stat(self._feed_cache_file).st_mtime) if file_ts > maxage: try: wi...
def _get_feed_cache(self)
If a recent cache exists, return it, else return None
2.464787
2.19272
1.124078
if refresh is True: self._raw = self.refresh() if self._raw is None: self._raw = self._get_feed_cache() if self._raw is None: self._raw = self.refresh() return self._raw
def raw_cap(self, refresh=False)
Raw xml(cap) of the the feed. If a valid cache is available it is used, else a new copy of the feed is grabbed Note: you can force refresh here, if you do, don't also manually call refresh
3.33618
2.624036
1.271393
self._raw = self._get_nws_feed() self._save_feed_cache(self._raw) return self._raw
def refresh(self)
NOTE: You probably don't want to call this... This does not update the alerts loaded in the WeatherAlerts object, only the underlying feed. This is only used internally now and as such, will likely be deprecated soon. Please call `WeatherAlerts.refresh()` instead.
9.83212
6.008116
1.636473
url = '''http://alerts.weather.gov/cap/%s.php?x=0''' % (str(self._state).lower()) # pylint: disable=E1103 xml = requests.get(url).content return xml
def _get_nws_feed(self)
get nws alert feed, and cache it
6.427199
5.530839
1.162066
rtts = sorted([p.rtt for p in self.packets if p.rtt is not None]) if rtts: self.rtt_min = rtts[0] self.rtt_max = rtts[-1] self.rtt_median = self.calculate_median(rtts) offsets = sorted( [p.offset for p in self.packets if p.offset is not ...
def _set_medians_and_extremes(self)
Sets median values for rtt and the offset of result packets.
2.10481
1.726788
1.218917
self._feed = AlertsFeed(state=self.scope, maxage=self.cachetime) parser = CapParser(self._feed.raw_cap(), geo=self.geo) self._alerts = parser.get_alerts()
def load_alerts(self)
NOTE: use refresh() instead of this, if you are just needing to refresh the alerts list Gets raw xml (cap) from the Alerts feed, throws it into the parser and ends up with a list of alerts object, which it stores to self._alerts
14.725592
8.995989
1.636906
if force is True: self._feed.refresh() self._alerts = CapParser(self._feed.raw_cap(), geo=self.geo).get_alerts()
def refresh(self, force=False)
Refresh the alerts list. set `force` to True to force pulling a new list from the NWS, otherwise it'll only pull a new list if the cached copy is expired. (see cachetime)
15.833204
10.428533
1.518258
if self.samecodes is not None: temp = [] for alert in self._alerts: for code in alert.samecodes: if code in self.samecodes: temp.append(alert) return temp else: return self._alerts
def alerts(self)
returns the alerts list. If samecode(s) are specified when the WeatherAlerts object is created, this will only return alerts for those samecodes. If no samecodes were given, it'll return all alerts for the state if one was specified otherwise for the entire U.S.
4.080359
2.487684
1.640224
return [x for x in self._alerts if samecode in x.samecodes]
def samecode_alerts(self, samecode)
Returns alerts for a ()single) SAME geocode. Only useful if you didn't specify samecodes when the WeatherAlerts object was created.
6.753906
5.406833
1.249143
samecode = self.geo.lookup_samecode(county, state) return self.samecode_alerts(samecode)
def county_state_alerts(self, county, state)
Given a county and state, return alerts
9.431782
8.078429
1.167527
# FIXME: most of this logic should be moved to the alert instance and refactored counties = '' state = '' for alert in self._alerts: locations = [] states = [] for samecode in alert.samecodes: county, state = self.geo.lookup_co...
def event_state_counties(self)
DEPRECATED: this will be moved elsewhere or dropped in the near future, stop using it. Return an event type and it's state(s) and counties (consolidated)
4.863349
4.536092
1.072145
if collect: collector = get_context().socket(zmq.PUSH) collector.connect(collector_addr) collector.send_multipart([prefix, '']) collector.close() requests[hash(req)] = time()
def start_request(req, collect=False, collector_addr='tcp://127.0.0.2:2345', prefix='my_app')
register a request registers a request in the internal request table, optionally also sends it to the collector :param req: request, can be mostly any hash-able object :param collect: whether to send the request started event to the collector (bool) :param collector_addr: collector address, in zeromq ...
5.21702
5.895156
0.884967
req_end = time() hreq = hash(req) if hreq in requests: req_time = req_end - requests[hreq] req_time *= 1000 del requests[hreq] collector = get_context().socket(zmq.PUSH) collector.connect(collector_addr) collector.send_multipart([prefix, str(req_time...
def end_request(req, collector_addr='tcp://127.0.0.2:2345', prefix='my_app')
registers the end of a request registers the end of a request, computes elapsed time, sends it to the collector :param req: request, can be mostly any hash-able object :param collector_addr: collector address, in zeromq format (string, default tcp://127.0.0.2:2345) :param prefix: label under which to ...
3.863992
3.483062
1.109367
target_areas = [] areas = str(entry['cap:areaDesc']).split(';') for area in areas: target_areas.append(area.strip()) return target_areas
def build_target_areas(entry)
Cleanup the raw target areas description string
4.312946
3.565049
1.209786
emptyfeed = "There are no active watches, warnings or advisories" alerts = [] if emptyfeed in str(self._raw_cap): pass else: main_dom = minidom.parseString(self._raw_cap) xml_entries = main_dom.getElementsByTagName('entry') # title...
def get_alerts(self)
Public method that parses
8.393657
8.343453
1.006017
entry = {} for tag in self._cap_tags: # we need to handle the geocodes a bit differently if tag == 'cap:geocode': try: geotypes = [] # FIXME: this will parse VTEC and add it to the feed as well, that's both a featur...
def _parse_entry(self, dom)
Sigh....
5.28199
5.175356
1.020604
name = fullname.rsplit('.', 1)[-1] if not path: path = [''] for d in path: nb_path = os.path.join(d, name + ".ipynb") if os.path.isfile(nb_path): return nb_path # let import Notebook_Name find "Notebook Name.ipynb" nb_path = nb_path.replace("_", " ") ...
def find_notebook(fullname, path=None)
find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist.
2.779231
2.843409
0.977429
path = find_notebook(fullname, self.path) print ("importing Jupyter notebook from %s" % path) # load the notebook object with io.open(path, 'r', encoding='utf-8') as f: nb = read(f, 4) # create the module and add it to sys.modules if name in sys.modules: ...
def load_module(self, fullname)
import a notebook as a module
3.171063
3.048721
1.040129
location = False try: location = self.samecodes[req_location['code']] except Exception: pass try: location = self.lookup_samecode(req_location['local'], req_location['state']) except Exception: pass return location
def location_lookup(self, req_location)
returns full location given samecode or county and state. Returns False if not valid. *currently locations are a dictionary, once other geo data is added, they will move to a location class/obj*
5.546139
4.26892
1.29919
for location in self.samecodes: if state.lower() == self.samecodes[location]['state'].lower(): if local.lower() == self.samecodes[location]['local'].lower(): return self.samecodes[location] return False
def lookup_samecode(self, local, state)
Given County, State return the SAME code for specified location. Return False if not found
3.045374
2.393969
1.272103
states = self._get_states_from_samecodes(geocodes) if len(states) >= 2: return 'US' else: return states[0]
def getfeedscope(self, geocodes)
Given multiple SAME codes, determine if they are all in one state. If so, it returns that state. Otherwise return 'US'. This is used to determine which NWS feed needs to be parsed to get all alerts for the requested SAME codes
5.845543
3.622597
1.613633
states = [] for code in geocodes: if not isinstance(geocodes, list): raise Exception("specified geocodes must be list") try: state = self.samecodes[code]['state'] except KeyError: raise Exception("Samecode Not F...
def _get_states_from_samecodes(self, geocodes)
Returns all states for a given list of SAME codes *Shouldn't be used to determine feed scope, please use getfeedscope()*
3.887743
3.509782
1.107688
if refresh is True: self._get_same_codes() else: self._cached_same_codes()
def _load_same_codes(self, refresh=False)
Loads the Same Codes into this object
5.130988
3.834026
1.338277
same = {} url = '''http://www.nws.noaa.gov/nwr/data/SameCode.txt''' # pylint: disable=E1103 raw = requests.get(url).content.decode('utf-8') # py3 compatibility for row in raw.split('\n'): try: code, local, state = str(row).strip().split(',') ...
def _get_same_codes(self)
get SAME codes, load into a dict and cache
5.59016
5.06358
1.103994
cache_file = self._same_cache_file if os.path.exists(cache_file): maxage = datetime.now() - timedelta(minutes=4320) file_ts = datetime.fromtimestamp(os.stat(cache_file).st_mtime) if file_ts > maxage: try: cache = open(cache...
def _cached_same_codes(self)
If a cached copy is available, return it
3.148886
3.01414
1.044705
for i in xrange(self.nreq): req = '%s_%s' % (self.ident, i) pre_request(None, req) sleep(random() / 2) post_request(None, req)
def run(self)
generate <nreq> requests taking a random amount of time between 0 and 0.5 seconds
6.414386
4.915454
1.304943
if not self.destination_address: return for packet in last_hop.packets: if packet.origin and \ self.destination_address == packet.origin: self.destination_ip_responded = True break
def set_destination_ip_responded(self, last_hop)
Sets the flag if destination IP responded.
4.178439
3.992978
1.046447
for packet in last_hop.packets: if packet.rtt: self.last_hop_responded = True break
def set_last_hop_responded(self, last_hop)
Sets the flag if last hop responded.
6.399168
5.027708
1.27278
for packet in last_hop.packets: if packet.rtt and not packet.is_error: self.is_success = True break else: self.set_last_hop_errors(last_hop)
def set_is_success(self, last_hop)
Sets the flag if traceroute result is successful or not.
4.810783
3.95076
1.217685
if last_hop.is_error: self.last_hop_errors.append(last_hop.error_message) return for packet in last_hop.packets: if packet.is_error: self.last_hop_errors.append(packet.error_message)
def set_last_hop_errors(self, last_hop)
Sets the last hop's errors.
2.432229
2.402237
1.012485
r = [] for hop in self.hops: r.append([packet.origin for packet in hop.packets]) return r
def ip_path(self)
Returns just the IPs from the traceroute.
9.337389
6.526614
1.430664
error = [] do_header = True do_question = True do_answer = True do_authority = True do_additional = True do_options = True if options and isinstance(options, dict): if 'DO_Header' in options and not options['DO_Header']: ...
def parse(cls, buf, options=None)
According to Philip, an abuf is like a TARDIS: it's bigger on the inside
1.869441
1.873218
0.997984
nodes = [] for shiny_app in ShinyApp.objects.all(): node = NavigationNode( shiny_app.name, reverse('cms_shiny:shiny_detail', args=(shiny_app.slug,)), shiny_app.slug ) nodes.append(node) return nodes
def get_nodes(self, request)
This method is used to build the menu tree.
3.553035
3.376059
1.052421
self.write_data([self.ISS_CMD, self.ISS_VERSION]) response = self.read_data(3) if len(response) == 3: response = self.decode(response) self.module = response[0] self.firmware = response[1] self._mode = response[2] else: ...
def get_iss_info(self)
Get information about the USB-ISS Querying will return three bytes; - the module ID (7), - firmware version (currently 2), - the current operating mode.
4.770389
3.492769
1.36579
self.write_data([self.ISS_CMD, self.ISS_SER_NUM]) # Return 8 bytes serial number self.iss_sn = self.read_data(8)
def get_iss_serial_no(self)
Get serial number of USB-ISS module
8.015252
6.410199
1.250391
self._mode = set_bytes data = [self.ISS_CMD, self.ISS_SET_MODE] + set_bytes self.write_data(data) response = self.read_data(2) if response[0] == 0: error_dict = { 0x05: 'Unknown Command', 0x06: 'Internal Error 1', ...
def mode(self, set_bytes)
Set the operating protocol of the USB-ISS with additional parameters for the protocol
4.125783
3.650386
1.130232
if not keys: return obj for k in keys: if k not in obj: continue v = obj[k] if not isinstance(v, string_types): continue obj[k] = parse_datetime(v) return obj
def keys_to_datetime(obj, *keys)
Converts all the keys in an object to DateTime instances. Args: obj (dict): the JSON-like ``dict`` object to modify inplace. keys (str): keys of the object being converted into DateTime instances. Returns: dict: ``obj`` inplace. >>> keys_to_...
2.359298
2.728989
0.864532
if not s: return None try: ret = dateutil_parser(s, **kwargs) except (OverflowError, TypeError, ValueError) as e: logger.exception(e, exc_info=True) reraise('datetime parsing error from %s' % s, e) return ret
def parse_datetime(s, **kwargs)
Converts a time-string into a valid :py:class:`~datetime.datetime.DateTime` object. Args: s (str): string to be formatted. ``**kwargs`` is passed directly to :func:`.dateutil_parser`. Returns: :py:class:`~datetime.datetime.DateTime`
4.076807
4.345547
0.938157
params = None if path: assert isinstance(path, string_types) params = {'current': path} return self.get('browse', params=params)
def browse(self, path=None)
Returns a list of directories matching the path given. Args: path (str): glob pattern. Returns: List[str]
5.127087
8.216138
0.624026
assert isinstance(config, dict) self.post('config', data=config) if and_restart: self.restart()
def set_config(self, config, and_restart=False)
Post the full contents of the configuration, in the same format as returned by :func:`.config`. The configuration will be saved to disk and the ``configInSync`` flag set to ``False``. Restart Syncthing to activate.
4.240315
4.034294
1.051068
status = self.get('config/insync').get('configInSync', False) if status is None: status = False return status
def config_insync(self)
Returns whether the config is in sync, i.e. whether the running configuration is the same as that on disk. Returns: bool
6.615593
9.224854
0.717149
ret_errs = list() errors = self.get('error').get('errors', None) or list() assert isinstance(errors, list) for err in errors: when = parse_datetime(err.get('when', None)) msg = err.get('message', '') e = ErrorEvent(when, msg) ret_e...
def errors(self)
Returns the list of recent errors. Returns: list: of :obj:`.ErrorEvent` tuples.
3.803863
3.576121
1.063684
assert isinstance(message, string_types) self.post('error', data=message)
def show_error(self, message)
Send an error message to the active client. The new error will be displayed on any active GUI clients. Args: message (str): Plain-text message to display. Returns: None >>> s = _syncthing() >>> s.system.show_error('my error m...
9.365879
15.568698
0.601584
resp = self.post('pause', params={'device': device}, return_response=True) error = resp.text if not error: error = None return {'success': resp.status_code == requests.codes.ok, 'error': error}
def pause(self, device)
Pause the given device. Args: device (str): Device ID. Returns: dict: with keys ``success`` and ``error``.
4.221267
3.78873
1.114164
warnings.warn('This is a destructive action that cannot be undone.') self.post('reset', data={}, params={'folder': folder})
def reset_folder(self, folder)
Erase the database index from a given folder and restart Syncthing. Args: folder (str): Folder ID. Returns: None
10.786225
11.854994
0.909847
assert isinstance(levels, int) or levels is None assert isinstance(prefix, string_types) or prefix is None return self.get('browse', params={'folder': folder, 'levels': levels, 'prefix': prefix})
def browse(self, folder, levels=None, prefix=None)
Returns the directory tree of the global model. Directories are always JSON objects (map/dictionary), and files are always arrays of modification time and size. The first integer is the files modification time, and the second integer is the file size. Args: ...
2.956642
3.695732
0.800015
return self.get( 'completion', params={'folder': folder, 'device': device} ).get('completion', None)
def completion(self, device, folder)
Returns the completion percentage (0 to 100) for a given device and folder. Args: device (str): The Syncthing device the folder is syncing to. folder (str): The folder that is being synced. Returs: int
5.35285
7.156403
0.747981