code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if num < 0: raise HeartbeatError('%s is not greater than 0' % num) blocks = [] random.seed(root_seed) for i in range(num): blocks.append(random.randint(0, self.file_size - 1)) return blocks
def pick_blocks(self, num, root_seed)
Pick a set of positions to start reading blocks from the file that challenges are created for. This is a deterministic operation. Positions are guaranteed to be within the bounds of the file. :param num: Number of blocks to pick :param root_seed: Seed with which begin picking bl...
3.665194
3.695888
0.991695
for challenge in self.challenges: if challenge.response == hash_answer: # If we don't discard a used challenge then a node # could fake having the file because it already # knows the proper response self.delete_challenge(hash_a...
def check_answer(self, hash_answer)
Check if the returned hash is in our challenges list. :param hash_answer: Hash that we compare to our list of challenges :return: boolean indicating if answer is correct, True, or not, False
13.18486
13.476223
0.978379
helpscout = __import__('helpscout.apis') for class_name in helpscout.apis.__all__: if not class_name.startswith('_'): cls = getattr(helpscout.apis, class_name) api = AuthProxy(self.session, cls) setattr(self, class_name, api) ...
def _load_apis(self)
Find available APIs and set instances property auth proxies.
3.737862
3.053643
1.224066
duration_ms = int(duration.total_seconds() * 1000) previous = int(unix_time(begin) * 1000) next = previous + duration_ms now_ms = unix_time(datetime.datetime.now())*1000 end_slice = now_ms if not end else min(now_ms, int(unix_time(end) * 1000)) while next < end_slice: yield TimeSli...
def slice_time(begin, end=None, duration=datetime.timedelta(days=2))
:param begin: datetime :param end: datetime :param duration: timedelta :return: a generator for a set of timeslices of the given duration
2.116117
2.126358
0.995183
if isinstance(response, unicode) or \ isinstance(response, str): response = (response, 'text/html') return response
def make_response(response)
Make response tuple Potential features to be added - Parameters validation
5.040787
7.216379
0.69852
status = webkitView.get_load_status() if status == status.FINISHED: if self.debug is True: print 'Load finished'
def on_notify_load_status(self, webkitView, *args, **kwargs)
Callback function when the page was loaded completely FYI, this function will be called after $(document).ready() in jQuery
4.940967
6.176572
0.799953
(content, mimetype) = make_response(self._url_map_to_function('/')) try: beautifulsoup = BeautifulSoup(content) self.window.set_title(beautifulsoup.find('title').string) except: pass if self.debug is True: print self.app_dir ...
def _init_ui(self)
Initial the first UI page. - load html from '/' endpoint - if <title> is defined, use as windows title
8.249671
7.090968
1.163406
t_step = ts.index[1] - ts.index[0] oc = np.abs(np.fft.fftshift(np.fft.fft(ts.values))) / len(ts.values) t = np.fft.fftshift(np.fft.fftfreq(len(oc), d=t_step)) return Trace(oc, t)
def fft(ts)
Perform a fast-fourier transform on a Trace
2.847916
2.836513
1.00402
m = np.ones(int(window)) / int(window) return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')
def movingaverage(arr, window)
Calculates the moving average ("rolling mean") of an array of a certain window size.
3.207541
3.467515
0.925026
data = zlib.decompress(ast_str) li = struct.unpack('<L', data[0:4])[0] lt = struct.unpack('<L', data[4:8])[0] n = data[8:8 + li].decode('utf-8') t = np.fromstring(data[8 + li:8 + li + lt]) d = np.fromstring(data[8 + li + lt:]) return Trace(d, t, name=n)
def loads(ast_str)
Create a Trace from a suitably compressed string.
3.086926
2.566994
1.202545
d = asts.values.tostring() t = asts.index.values.astype(float).tostring() lt = struct.pack('<L', len(t)) i = asts.name.encode('utf-8') li = struct.pack('<L', len(i)) try: # python 2 return buffer(zlib.compress(li + lt + i + t + d)) except NameError: # python 3 return z...
def dumps(asts)
Create a compressed string from an Trace.
3.84903
3.63662
1.058409
def wrap_func(df, *args): # TODO: should vectorize to apply over all columns? return Chromatogram(f(df.values, *args), df.index, df.columns) return wrap_func
def ts_func(f)
This wraps a function that would normally only accept an array and allows it to operate on a DataFrame. Useful for applying numpy functions to DataFrames.
6.474676
6.460244
1.002234
from matplotlib.colors import ColorConverter c = ColorConverter().to_rgb(c) intensity = 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] return [intensity * k + i * (1 - k) for i in c]
def desaturate(c, k=0)
Utility function to desaturate a color c by an amount k.
2.272368
2.20314
1.031422
# filter out any points with abundance below 1 % # spec[spec / np.sum(spec) < 0.01] = 0 # normalize everything to sum to 1 spec = spec / np.max(spec) if method == 'dot': d1 = (spec_lib * lil_matrix(spec).T).sum(axis=1).A ** 2 d2 = np.sum(spec ** 2) * spec_lib.multiply(spec_lib)...
def find_spectrum_match(spec, spec_lib, method='euclidian')
Find spectrum in spec_lib most similar to spec.
3.762704
3.79012
0.992766
if name not in self.daemon_class.list_actions(): return None # The context object is a Daemon object daemon = ctx.obj def subcommand(debug=False): if daemon.detach and debug: daemon.detach = False daemon.do_acti...
def get_command(self, ctx, name)
Get a callable command object.
4.702616
4.721675
0.995964
''' Load configuration (from configuration files). Parameters ---------- path : ~pathlib.Path or None Path to configuration file, which must exist; or path to directory containing a configuration file; or None. Returns ------- ~ty...
def load(self, path=None)
Load configuration (from configuration files). Parameters ---------- path : ~pathlib.Path or None Path to configuration file, which must exist; or path to directory containing a configuration file; or None. Returns ------- ~typing.Dict[str, ~typi...
4.039763
2.454311
1.645987
''' Get a user friendly help message that can be dropped in a `click.Command`\ 's epilog. Parameters ---------- description : str Description of the configuration file to include in the message. Returns ------- str A help ...
def cli_help_message(self, description)
Get a user friendly help message that can be dropped in a `click.Command`\ 's epilog. Parameters ---------- description : str Description of the configuration file to include in the message. Returns ------- str A help message that uses :p...
5.388135
3.005354
1.792845
current_pedalboard = self.controller(CurrentController).pedalboard if current_pedalboard is None: self.log('Not exists any current pedalboard.') self.log('Use CurrentController to set the current pedalboard') else: self.log('Load current pedalboard - ...
def start(self)
Start the application, initializing your components.
5.740166
5.318472
1.079289
for component in self.components: component.close() self.log('Stopping component - {}', component.__class__.__name__) for controller in self.controllers.values(): controller.close() self.log('Stopping controller - {}', controller.__class__.__name...
def stop(self)
Stop the application, closing your components.
3.642071
3.300968
1.103334
scales = { 'seconds': lambda x: x, 'minutes': lambda x: x * 60, 'hours': lambda x: x * 60 * 60, 'days': lambda x: x * 60 * 60 * 24, 'weeks': lambda x: x * 60 * 60 * 24 * 7, 'months': lambda x: x * 60 * 60 * 24 * 30, 'years': lambda x: x * 60 * 60 * 24 * 365, } return scales[scale](v...
def get_seconds(value, scale)
Convert time scale dict to seconds Given a dictionary with keys for scale and value, convert value into seconds based on scale.
1.34414
1.322734
1.016183
col = class_mapper(mapped_class).get_property(geom_attr).columns[0] return col.type.srid
def _get_col_epsg(mapped_class, geom_attr)
Get the EPSG code associated with a geometry attribute. Arguments: geom_attr the key of the geometry property as defined in the SQLAlchemy mapper. If you use ``declarative_base`` this is the name of the geometry attribute as defined in the mapped class.
3.246932
4.744454
0.684364
tolerance = float(request.params.get('tolerance', 0.0)) epsg = None if 'epsg' in request.params: epsg = int(request.params['epsg']) box = request.params.get('bbox') shape = None if box is not None: box = [float(x) for x in box.split(',')] shape = Polygon(((box[0], bo...
def create_geom_filter(request, mapped_class, geom_attr)
Create MapFish geometry filter based on the request params. Either a box or within or geometry filter, depending on the request params. Additional named arguments are passed to the spatial filter. Arguments: request the request. mapped_class the SQLAlchemy mapped class. geom_...
2.067811
2.210112
0.935614
mapping = { 'eq': '__eq__', 'ne': '__ne__', 'lt': '__lt__', 'lte': '__le__', 'gt': '__gt__', 'gte': '__ge__', 'like': 'like', 'ilike': 'ilike' } filters = [] if 'queryable' in request.params: queryable = request.params['querya...
def create_attr_filter(request, mapped_class)
Create an ``and_`` SQLAlchemy filter (a ClauseList object) based on the request params (``queryable``, ``eq``, ``ne``, ...). Arguments: request the request. mapped_class the SQLAlchemy mapped class.
2.260311
2.073286
1.090207
attr_filter = create_attr_filter(request, mapped_class) geom_filter = create_geom_filter(request, mapped_class, geom_attr, **kwargs) if geom_filter is None and attr_filter is None: return None if geom_filter is None: return attr_filter if att...
def create_filter(request, mapped_class, geom_attr, **kwargs)
Create MapFish default filter based on the request params. Arguments: request the request. mapped_class the SQLAlchemy mapped class. geom_attr the key of the geometry property as defined in the SQLAlchemy mapper. If you use ``declarative_base`` this is the name of ...
1.897744
2.109496
0.89962
if 'attrs' in request.params: attrs = request.params['attrs'].split(',') props = feature.properties new_props = {} for name in attrs: if name in props: new_props[name] = props[name] feature.properties = new_...
def _filter_attrs(self, feature, request)
Remove some attributes from the feature and set the geometry to None in the feature based ``attrs`` and the ``no_geom`` parameters.
2.608279
2.305007
1.131571
attr = request.params.get('sort', request.params.get('order_by')) if attr is None or not hasattr(self.mapped_class, attr): return None if request.params.get('dir', '').upper() == 'DESC': return desc(getattr(self.mapped_class, attr)) else: retu...
def _get_order_by(self, request)
Return an SA order_by
2.72928
2.488157
1.096909
limit = None offset = None if 'maxfeatures' in request.params: limit = int(request.params['maxfeatures']) if 'limit' in request.params: limit = int(request.params['limit']) if 'offset' in request.params: offset = int(request.params['of...
def _query(self, request, filter=None)
Build a query based on the filter and the request params, and send the query to the database.
2.164612
2.162038
1.001191
if filter is None: filter = create_filter(request, self.mapped_class, self.geom_attr) query = self.Session().query(self.mapped_class) if filter is not None: query = query.filter(filter) return query.count()
def count(self, request, filter=None)
Return the number of records matching the given filter.
3.946551
3.647897
1.08187
ret = None if id is not None: o = self.Session().query(self.mapped_class).get(id) if o is None: return HTTPNotFound() # FIXME: we return a Feature here, not a mapped object, do # we really want that? ret = self._filter_...
def read(self, request, filter=None, id=None)
Build a query based on the filter or the idenfier, send the query to the database, and return a Feature or a FeatureCollection.
4.362422
4.211984
1.035717
if self.readonly: return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'}) collection = loads(request.body, object_hook=GeoJSON.to_instance) if not isinstance(collection, FeatureCollection): return HTTPBadRequest() session = self.Session() obje...
def create(self, request)
Read the GeoJSON feature collection from the request body and create new objects in the database.
2.820956
2.551352
1.105671
if self.readonly: return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'}) session = self.Session() obj = session.query(self.mapped_class).get(id) if obj is None: return HTTPNotFound() feature = loads(request.body, object_hook=GeoJSON.to_instan...
def update(self, request, id)
Read the GeoJSON feature from the request body and update the corresponding object in the database.
3.422748
2.926281
1.169658
if self.readonly: return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'}) session = self.Session() obj = session.query(self.mapped_class).get(id) if obj is None: return HTTPNotFound() if self.before_delete is not None: self.before_...
def delete(self, request, id)
Remove the targeted feature from the database
3.042897
3.134305
0.970836
store = self._stores.get(tier, None) if not store: store = AutoSplittingFile(self._dir, self._lines_per_store, self._file_name, tier) self._stores[tier] = store store.write(text)
def store(self, text, tier)
Writes text to the underlying Store mapped at tier. If the store doesn't exists, yet, it creates it :param text: the text to write :param tier: the tier used to identify the store :return:
4.868464
4.68517
1.039122
return timeuuid_from_time(int(time) + UUID_TIME_OFFSET, type=_type)
def uuid_from_kronos_time(time, _type=UUIDType.RANDOM)
Generate a UUID with the specified time. If `lowest` is true, return the lexicographically first UUID for the specified time.
11.395448
11.889358
0.958458
if technology == PluginTechnology.LV2 \ or str(technology).upper() == PluginTechnology.LV2.value.upper(): return self.lv2_builder.all else: return []
def by(self, technology)
Get the plugins registered in PedalPi by technology :param PluginTechnology technology: PluginTechnology identifier
8.650483
8.592272
1.006775
plugins_data = self.lv2_builder.lv2_plugins_data() self._dao.save(plugins_data)
def reload_lv2_plugins_data(self)
Search for LV2 audio plugins in the system and extract the metadata needed by pluginsmanager to generate audio plugins.
7.816449
7.791981
1.00314
''' Invert by swapping each value with its key. Returns ------- MultiDict Inverted multi-dict. Examples -------- >>> MultiDict({1: {1}, 2: {1,2,3}}, 4: {}).invert() MultiDict({1: {1,2}, 2: {2}, 3: {2}}) ''' result = de...
def invert(self)
Invert by swapping each value with its key. Returns ------- MultiDict Inverted multi-dict. Examples -------- >>> MultiDict({1: {1}, 2: {1,2,3}}, 4: {}).invert() MultiDict({1: {1,2}, 2: {2}, 3: {2}})
4.66522
1.716472
2.717912
data = urllib.urlencode(values) # Simulate a Flask request because that is what will be unpacked when the # request is received on the other side request = Request.from_values( content_length=len(data), input_stream=StringIO(data), content_type='application/x-www-form-urlencoded', method='P...
def _send_with_auth(values, secret_key, url)
Send dictionary of JSON serializable `values` as a POST body to `url` along with `auth_token` that's generated from `secret_key` and `values` scheduler.auth.create_token expects a JSON serializable payload, so we send a dictionary. On the receiving end of the POST request, the Flask view will have access to...
3.788427
3.30014
1.147959
if not secret_key: secret_key = default_key() if not url: url = default_url() url = '%s/schedule' % url values = { 'interval': interval, 'code': code, } return _send_with_auth(values, secret_key, url)
def schedule(code, interval, secret_key=None, url=None)
Schedule a string of `code` to be executed every `interval` Specificying an `interval` of 0 indicates the event should only be run one time and will not be rescheduled.
3.183304
3.2994
0.964813
if not secret_key: secret_key = default_key() if not url: url = default_url() url = '%s/cancel' % url values = { 'id': task_id, } return _send_with_auth(values, secret_key, url)
def cancel(task_id, secret_key=None, url=None)
Cancel scheduled task with `task_id`
3.132442
2.996954
1.045209
f.seek(0x26) nparts = struct.unpack('<H', f.read(2))[0] foff = 0x2D if title is None: data = [] for _ in range(nparts): d = read_reg_file(f, foff) data.append(d) foff = f.tell() + 1 else: for _ in range(nparts): d = read_re...
def read_multireg_file(f, title=None)
Some REG files have multiple "sections" with different data. This parses each chunk out of such a file (e.g. LCDIAG.REG)
2.330278
2.374952
0.98119
return cls( '/teams/%d.json' % team_id, singleton=True, session=session, )
def get(cls, session, team_id)
Return a specific team. Args: session (requests.sessions.Session): Authenticated session. team_id (int): The ID of the team to get. Returns: helpscout.models.Person: A person singleton representing the team, if existing. Otherwise ``None``.
6.559705
8.993435
0.729388
if isinstance(team_or_id, Person): team_or_id = team_or_id.id return cls( '/teams/%d/members.json' % team_or_id, session=session, out_type=User, )
def get_members(cls, session, team_or_id)
List the members for the team. Args: team_or_id (helpscout.models.Person or int): Team or the ID of the team to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.Users): Users iterator.
3.835039
3.805389
1.007792
g = re.match('PT(?:(.*)H)?(?:(.*)M)?(?:(.*)S)?', x).groups() return sum(0 if g[i] is None else float(g[i]) * 60. ** (1 - i) for i in range(3))
def t_to_min(x)
Convert XML 'xs: duration type' to decimal minutes, e.g.: t_to_min('PT1H2M30S') == 62.5
4.510318
3.765468
1.197811
for r in df.values: df.columns pass
def write_mzxml(filename, df, info=None, precision='f')
Precision is either f or d.
44.681541
35.571617
1.256101
if ba is None: return [] pgr = ba.find('m:referenceableParamGroupRef', namespaces=self.ns) if pgr is not None and param_groups is not None: q = 'm:referenceableParamGroup[@id="' + pgr.get('ref') + '"]' pg = param_groups.find(q, namespaces=self.ns) ...
def read_binary(self, ba, param_groups=None)
ba - binaryDataArray XML node
2.438877
2.331544
1.046035
''' Pretty format memory info. Returns ------- str Memory info. Examples -------- >>> pretty_memory_info() '5MB memory usage' ''' process = psutil.Process(os.getpid()) return '{}MB memory usage'.format(int(process.memory_info().rss / 2**20))
def pretty_memory_info()
Pretty format memory info. Returns ------- str Memory info. Examples -------- >>> pretty_memory_info() '5MB memory usage'
3.38401
1.993493
1.697528
if not hasattr(func, '__dynamic__'): func.__dynamic__ = {name: expression} else: func.__dynamic__[name] = expression return func return decorator
def dynamic(name: str, expression: Union[type, Callable[[Type[Any]], type]]) \ -> Callable[[Callable[..., Any]], Callable[..., Any]]: # TODO type annotations for pass-through decorator def decorator(func)
:param name: :param expression: a subclass of ``type`` or a callable in the format ``(owner: Type[Any]) -> type``. :return:
3.297892
3.138047
1.050938
''' Swap index with values of series. Parameters ---------- series : ~pandas.Series Series to swap on, must have a name. Returns ------- ~pandas.Series Series after swap. See also -------- pandas.Series.map Joins series ``a -> b`` and ``b -> c`` int...
def invert(series)
Swap index with values of series. Parameters ---------- series : ~pandas.Series Series to swap on, must have a name. Returns ------- ~pandas.Series Series after swap. See also -------- pandas.Series.map Joins series ``a -> b`` and ``b -> c`` into ``a -> c``...
8.019741
3.294676
2.434152
''' Split values. The index is dropped, but this may change in the future. Parameters ---------- series : ~pandas.Series[~pytil.numpy.ArrayLike] Series with array-like values. Returns ------- ~pandas.Series Series with values split across rows. Examples --...
def split(series)
Split values. The index is dropped, but this may change in the future. Parameters ---------- series : ~pandas.Series[~pytil.numpy.ArrayLike] Series with array-like values. Returns ------- ~pandas.Series Series with values split across rows. Examples -------- >...
3.877616
1.718987
2.255757
''' Get whether 2 series are equal. ``NaN`` is considered equal to ``NaN`` and `None`. Parameters ---------- series1 : pandas.Series Series to compare. series2 : pandas.Series Series to compare. ignore_order : bool Ignore order of values (and index). ignore_...
def equals(series1, series2, ignore_order=False, ignore_index=False, all_close=False, _return_reason=False)
Get whether 2 series are equal. ``NaN`` is considered equal to ``NaN`` and `None`. Parameters ---------- series1 : pandas.Series Series to compare. series2 : pandas.Series Series to compare. ignore_order : bool Ignore order of values (and index). ignore_index : bool...
6.087098
1.180168
5.157822
''' Assert 2 series are equal. Like ``assert equals(series1, series2, ...)``, but with better hints at where the series differ. See `equals` for detailed parameter doc. Parameters ---------- actual : ~pandas.Series expected : ~pandas.Series ignore_order : bool ignore_index ...
def assert_equals(actual, expected, ignore_order=False, ignore_index=False, all_close=False)
Assert 2 series are equal. Like ``assert equals(series1, series2, ...)``, but with better hints at where the series differ. See `equals` for detailed parameter doc. Parameters ---------- actual : ~pandas.Series expected : ~pandas.Series ignore_order : bool ignore_index : bool a...
4.958328
2.260771
2.193203
Gtk.Application.do_startup(self) gtk_window = Gtk.ApplicationWindow(application=self) gtk_window.set_title('AppKit') webkit_web_view = WebKit.WebView() webkit_web_view.load_uri('http://localhost:' + str(self.port)) screen = Gdk.Screen.get_default() moni...
def do_startup(self)
Gtk.Application.run() will call this function()
2.2224
2.121625
1.047499
mention_text = '' mention_length = 0 if mentions: formatted_mentions = ['@{0}'.format(mention) for mention in mentions] mention_text = " ".join(formatted_mentions) message = '{0} {1}'.format(mention_text, message) mention_length = len(ment...
def tokenize(self, message, max_length, mentions=None)
Tokenize a message into a list of messages of no more than max_length, including mentions in each message :param message: Message to be sent :param max_length: Maximum allowed length for each resulting message :param mentions: List of usernames to mention in each message :return:
2.583325
2.55785
1.00996
messages = self.tokenize(message, self.MESSAGE_LENGTH, mentions) code = 0 for message in messages: if self.dry_run: mention_message = '' if mention_id: mention_message = " to mention_id '{0}'".format(mention_id) ...
def send_message(self, message, mention_id=None, mentions=[])
Send the specified message to twitter, with appropriate mentions, tokenized as necessary :param message: Message to be sent :param mention_id: In-reply-to mention_id (to link messages to a previous message) :param mentions: List of usernames to mention in reply :return:
3.15278
3.138305
1.004612
mention_list = [user['screen_name'] for user in mention['entities']['user_mentions']] mention_list.append(mention['user']['screen_name']) reply_to_names = set(mention_list) # Do not include bot's own name reply_to_names.discard(self.screen_name) return sorted(lis...
def get_reply_to_names(self, mention)
Get a sorted list of unique usernames mentioned in the message, excluding the bot's own name :param mention: JSON mention object from twitter :return: list of usernames
2.772313
2.396499
1.156818
since_id = self.since_id.get() kwargs = {'count': 200} if since_id: kwargs['since_id'] = since_id mentions_list = [] try: mentions_list = self.twitter.statuses.mentions_timeline(**kwargs) except TwitterHTTPError as e: logging...
def reply_to_mentions(self)
For every mention since since_id, create a message with the provider and use it to reply to the mention :return: Number of mentions processed
3.185778
3.174171
1.003657
bot = TwitterBot(settings) result = 1 if command == 'post_message': result = bot.post_message() elif command == 'reply_to_mentions': result = bot.reply_to_mentions() else: print("Command must be either 'post_message' or 'reply_to_ment...
def go(self, settings, command)
Run the specified command using a TwitterBot created with the provided settings :param settings: Settings class :param command: Command to run, either 'post_message' or 'reply_to_mentions' :return: Result of running the command
3.489229
2.229905
1.564743
data = zlib.decompress(zdata) lc = struct.unpack('<L', data[0:4])[0] li = struct.unpack('<L', data[4:8])[0] c = json.loads(data[8:8 + lc].decode('utf-8')) i = np.fromstring(data[8 + lc:8 + lc + li], dtype=np.float32) v = np.fromstring(data[8 + lc + li:], dtype=np.float64) if len(c) == ...
def decompress(zdata)
Unserializes an AstonFrame. Parameters ---------- zdata : bytes Returns ------- Trace or Chromatogram
2.537675
2.424847
1.04653
if twin is None: return 0, df.shape[0] tme = df.index if twin[0] is None: st_idx = 0 else: st_idx = (np.abs(tme - twin[0])).argmin() if twin[1] is None: en_idx = df.shape[0] else: en_idx = (np.abs(tme - twin[1])).argmin() + 1 return st_idx, en_i...
def _slice_idxs(df, twin=None)
Returns a slice of the incoming array filtered between the two times specified. Assumes the array is the same length as self.data. Acts in the time() and trace() functions.
1.894316
1.912949
0.99026
# TODO: needs to catch np numeric types? if isinstance(ts, (int, float)): d = ts * np.ones(self.shape[0]) elif ts is None: d = None elif np.array_equal(ts.index, self.index): d = ts.values else: d = ts._retime(self.index) ...
def _apply_data(self, f, ts, reverse=False)
Convenience function for all of the math stuff.
3.057574
2.961579
1.032413
traces = [] for v, c in zip(self.values.T, self.columns): traces.append(Trace(v, self.index, name=c)) return traces
def traces(self)
Decomposes the Chromatogram into a collection of Traces. Returns ------- list
4.616677
5.899247
0.782588
# styles: 2d, colors, otherwise interpret as trace? if ax is None: import matplotlib.pyplot as plt ax = plt.gca() if style == 'heatmap': ions = self.columns ext = (self.index[0], self.index[-1], min(ions), max(ions)) grid = se...
def plot(self, style='heatmap', legend=False, cmap=None, ax=None)
Presents the AstonFrame using matplotlib. Parameters ---------- style : {'heatmap', 'colors', ''} legend : bool, optional cmap: matplotlib.colors.Colormap, optional ax : matplotlib.axes.Axes, optional
3.104085
3.105199
0.999641
# make a 1d array for the sound def to_t(t): return (t - self.index[0]) / speed wav_len = int(to_t(self.index[-1]) * 60 * 44100) wav = np.zeros(wav_len) # create an artificial array to interpolate times out of tmask = np.linspace(0, 1, self.shape[0]...
def as_sound(self, filename, speed=60, cutoff=50)
Convert AstonFrame into a WAV file. Parameters ---------- filename : str Name of wavfile to create. speed : float, optional How much to speed up for sound recording, e.g. a value of 60 will turn an hour-long AstonFrame into a minute-long sound clip. ...
3.988203
3.932962
1.014046
idx = (np.abs(self.index - t)).argmin() if dt is None: # only take the spectra at the nearest time mz_abn = self.values[idx, :].copy() else: # sum up all the spectra over a range en_idx = (np.abs(self.index - t - dt)).argmin() ...
def scan(self, t, dt=None, aggfunc=None)
Returns the spectrum from a specific time. Parameters ---------- t : float dt : float
2.949999
3.089403
0.954877
connections_to_shutdown = [] self.cluster = Cluster(self.hosts) for namespace_name in namespaces: keyspace = '%s_%s' % (self.keyspace_prefix, namespace_name) namespace = Namespace(self.cluster, keyspace, self.replication_factor, self.read_size) connections...
def setup_cassandra(self, namespaces)
Set up a connection to the specified Cassandra cluster and create the specified keyspaces if they dont exist.
3.849991
3.945908
0.975692
stream = self.get_stream(namespace, stream, configuration) return stream.delete(start_id, uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST))
def _delete(self, namespace, stream, start_id, end_time, configuration)
Delete events for `stream` between `start_id` and `end_time`. `stream` : The stream to delete events for. `start_id` : Delete events with id > `start_id`. `end_time` : Delete events ending <= `end_time`. `configuration` : A dictionary of settings to override any default settings, s...
9.291174
10.739416
0.865147
stream = self.get_stream(namespace, stream, configuration) events = stream.iterator(start_id, uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST), order == ResultOrder.DESCENDING, limit) eve...
def _retrieve(self, namespace, stream, start_id, end_time, order, limit, configuration)
Retrieve events for `stream` between `start_id` and `end_time`. `stream` : The stream to return events for. `start_id` : Return events with id > `start_id`. `end_time` : Return events ending <= `end_time`. `order` : Whether to return the results in ResultOrder.ASCENDING or ResultOrder.DESC...
6.713545
6.25687
1.072988
response = {'service': 'kronosd', 'version': kronos.__version__, 'id': settings.node['id'], 'storage': {}, SUCCESS_FIELD: True} # Check if each backend is alive for name, backend in router.get_backends(): response['storage'][name] = {'alive': backend...
def index(environment, start_response, headers)
Return the status of this Kronos instance + its backends> Doesn't expect any URL parameters.
6.349547
5.283917
1.201674
errors = [] events_to_insert = defaultdict(list) request_json = environment['json'] namespace = request_json.get('namespace', settings.default_namespace) # Validate streams and events for stream, events in request_json.get('events', {}).iteritems(): try: validate_stream(stream) except Exce...
def put_events(environment, start_response, headers)
Store events in backends POST body should contain a JSON encoded version of: { namespace: namespace_name (optional), events: { stream_name1 : [event1, event2, ...], stream_name2 : [event1, event2, ...], ... } } Where each event is a dictionary of keys and values.
2.994248
2.94622
1.016302
request_json = environment['json'] try: stream = request_json['stream'] validate_stream(stream) except Exception, e: log.exception('get_events: stream validation failed for `%s`', request_json.get('stream')) start_response('400 Bad Request', headers) yield marshal.dumps({E...
def get_events(environment, start_response, headers)
Retrieve events POST body should contain a JSON encoded version of: { namespace: namespace_name (optional), stream : stream_name, start_time : starting_time_as_kronos_time, end_time : ending_time_as_kronos_time, start_id : only_return_events_with_id_greater_than_me, limit: optional_m...
3.764946
3.363557
1.119335
request_json = environment['json'] try: stream = request_json['stream'] validate_stream(stream) except Exception, e: log.exception('delete_events: stream validation failed for `%s`.', request_json.get('stream')) start_response('400 Bad Request', headers) return {ERRORS_FIE...
def delete_events(environment, start_response, headers)
Delete events POST body should contain a JSON encoded version of: { namespace: namespace_name (optional), stream : stream_name, start_time : starting_time_as_kronos_time, end_time : ending_time_as_kronos_time, start_id : only_delete_events_with_id_gte_me, } Either start_time or start...
3.18228
2.976439
1.069157
start_response('200 OK', headers) streams_seen_so_far = set() namespace = environment['json'].get('namespace', settings.default_namespace) for prefix, backend in router.get_read_backends(namespace): for stream in backend.streams(namespace): if stream.startswith(prefix) and stream not in streams_see...
def get_streams(environment, start_response, headers)
List all streams that can be read from Kronos right now. POST body should contain a JSON encoded version of: { namespace: namespace_name (optional) }
4.182215
4.085474
1.023679
stream = environment['json']['stream'] namespace = environment['json'].get('namespace') or settings.default_namespace start_response('200 OK', headers) schema = _infer_schema(namespace, stream) response = { 'stream': stream, 'namespace': namespace, 'schema': schema, SUCCESS_FIELD: True }...
def infer_schema(environment, start_response, headers)
Return the inferred schema of the requested stream. POST body should contain a JSON encoded version of: { stream: stream_name, namespace: namespace_name (optional) }
4.595624
3.76486
1.220663
devices = None with self.socket.Connect(): devices = self._command("host:devices") return parse_device_list(devices)
def devices(self)
Return a list of connected devices in the form (*serial*, *status*) where status can be any of the following: 1. device 2. offline 3. unauthorized :returns: A list of tuples representing connected devices
14.634924
20.96035
0.698219
self.leaves.append(MerkleLeaf(len(self.leaves), leaf_blob))
def add_leaf(self, leaf_blob)
Adds a leaf to the list of leaves. Does not build the tree so call `build()` to construct the rest of the tree from the added leaves. :param leaf_blob: the leaf payload to add. should be a hashable object
7.050122
10.824152
0.651332
self.order = MerkleTree.get_order(len(self.leaves)) n = 2 ** self.order self.nodes = [b''] * 2 * n # populate lowest nodes with leaf hashes for j in range(0, n): if (j < len(self.leaves)): self.nodes[j + n - 1] = self.leaves[j].get_hash() ...
def build(self)
Builds the tree from the leaves that have been added. This function populates the tree from the leaves down non-recursively
2.746621
2.673463
1.027365
branch = MerkleBranch(self.order) j = i + 2 ** self.order - 1 for k in range(0, self.order): if (self.is_left(j)): branch.set_row(k, (self.nodes[j], self.nodes[j + 1])) else: branch.set_row(k, (self.nodes[j - 1], self.nodes[j])) ...
def get_branch(self, i)
Gets a branch associated with leaf i. This will trace the tree from the leaves down to the root, constructing a list of tuples that represent the pairs of nodes all the way from leaf i to the root. :param i: the leaf identifying the branch to retrieve
3.471769
3.588302
0.967524
# just check the hashes are correct try: lh = leaf.get_hash() except: return False for i in range(0, branch.get_order()): if (branch.get_left(i) != lh and branch.get_right(i) != lh): return False h = hashlib.sha256(...
def verify_branch(leaf, branch, root)
This will verify that the given branch fits the given leaf and root It calculates the hash of the leaf, and then verifies that one of the bottom level nodes in the branch matches the leaf hash. Then it calculates the hash of the two nodes on the next level and checks that one of the nod...
2.509503
2.731469
0.918738
id = self.id or self.objects.id(self.name) self.objects[id] = self.prepare_save(dict(self)) self.id = id self.post_save() return id
def save(self)
Save this entry. If the entry does not have an :attr:`id`, a new id will be assigned, and the :attr:`id` attribute set accordingly. Pre-save processing of the fields saved can be done by overriding the :meth:`prepare_save` method. Additional actions to be done after the save o...
6.377137
5.690572
1.120649
return [self.instance(id, **fields) for id, fields in zip(ids, self.api.mget(ids))]
def get_many(self, ids)
Get several entries at once.
7.47023
6.577011
1.135809
entry = self.instance(**fields) entry.save() return entry
def create(self, **fields)
Create new entry.
6.615556
4.684619
1.412186
parse_result = urlparse(uri) if parse_result.scheme == '': abspath = os.path.abspath(parse_result.path) if IS_WINDOWS: abspath = windows_to_unix_path(abspath) fixed_uri = "file://{}".format(abspath) parse_result = urlparse(fixed_uri) return parse_result
def generous_parse_uri(uri)
Return a urlparse.ParseResult object with the results of parsing the given URI. This has the same properties as the result of parse_uri. When passed a relative path, it determines the absolute path, sets the scheme to file, the netloc to localhost and returns a parse of the result.
3.042199
3.300808
0.921653
is_windows = platform.system() == "Windows" no_username_in_env = os.environ.get("USERNAME") is None return cross_platform_getuser(is_windows, no_username_in_env)
def getuser()
Return the username.
4.40245
4.475218
0.98374
if config_path is None: config_path = DEFAULT_CONFIG_PATH # Default (empty) content will be used if config file does not exist. config_content = {} # If the config file exists we use that content. if os.path.isfile(config_path): with open(config_path) as fh: config...
def _get_config_dict_from_file(config_path=None)
Return value if key exists in file. Return empty string ("") if key or file does not exist.
2.855604
2.807954
1.01697
if config_path is None: config_path = DEFAULT_CONFIG_PATH # Get existing config. config = _get_config_dict_from_file(config_path) # Add/update the key/value pair. config[key] = value # Create parent directories if they are missing. mkdir_parents(os.path.dirname(config_path)) ...
def write_config_value_to_file(key, value, config_path=None)
Write key/value pair to config file.
2.668572
2.59205
1.029522
config = _get_config_dict_from_file(config_path) if key not in config: return default return config[key]
def get_config_value_from_file(key, config_path=None, default=None)
Return value if key exists in file. Return default if key not in config.
2.825945
3.152664
0.896367
if config_path is None: config_path = DEFAULT_CONFIG_PATH # Start by setting default value value = default # Update from config file value = get_config_value_from_file( key=key, config_path=config_path, default=value ) # Update from environment variabl...
def get_config_value(key, config_path=None, default=None)
Get a configuration value. Preference: 1. From environment 2. From JSON configuration file supplied in ``config_path`` argument 3. The default supplied to the function :param key: name of lookup value :param config_path: path to JSON configuration file :param default: default fall back val...
2.760149
3.770908
0.731959
try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise
def mkdir_parents(path)
Create the given directory path. This includes all necessary parent directories. Does not raise an error if the directory already exists. :param path: path to create
1.927921
2.327635
0.828275
start_of_time = datetime.datetime(1970, 1, 1) diff = datetime_obj - start_of_time return diff.total_seconds()
def timestamp(datetime_obj)
Return Unix timestamp as float. The number of seconds that have elapsed since January 1, 1970.
2.610947
2.483852
1.051169
# The name can only be 80 characters long. if len(name) > MAX_NAME_LENGTH: return False return bool(NAME_VALID_CHARS_REGEX.match(name))
def name_is_valid(name)
Return True if the dataset name is valid. The name can only be 80 characters long. Valid characters: Alpha numeric characters [0-9a-zA-Z] Valid special characters: - _ .
4.437788
4.841425
0.916628
logger.debug("Getting admin metdata") text = self.get_text(self.get_admin_metadata_key()) return json.loads(text)
def get_admin_metadata(self)
Return the admin metadata as a dictionary.
6.052197
5.015022
1.206813
logger.debug("Getting manifest") text = self.get_text(self.get_manifest_key()) return json.loads(text)
def get_manifest(self)
Return the manifest as a dictionary.
5.829597
4.939569
1.180183
logger.debug("Getting overlay: {}".format(overlay_name)) overlay_key = self.get_overlay_key(overlay_name) text = self.get_text(overlay_key) return json.loads(text)
def get_overlay(self, overlay_name)
Return overlay as a dictionary.
3.279325
2.956796
1.109081
logger.debug("Putting admin metdata") text = json.dumps(admin_metadata) key = self.get_admin_metadata_key() self.put_text(key, text)
def put_admin_metadata(self, admin_metadata)
Store the admin metadata.
3.971135
3.563796
1.114299
logger.debug("Putting manifest") text = json.dumps(manifest, indent=2, sort_keys=True) key = self.get_manifest_key() self.put_text(key, text)
def put_manifest(self, manifest)
Store the manifest.
3.338016
2.980917
1.119795
logger.debug("Putting readme") key = self.get_readme_key() self.put_text(key, content)
def put_readme(self, content)
Store the readme descriptive metadata.
5.27772
4.564326
1.156298
logger.debug("Updating readme") key = self.get_readme_key() # Back up old README content. backup_content = self.get_readme_content() backup_key = key + "-{}".format( timestamp(datetime.datetime.now()) ) logger.debug("README.yml backup key: {}...
def update_readme(self, content)
Update the readme descriptive metadata.
4.454697
4.388773
1.015021
logger.debug("Putting overlay: {}".format(overlay_name)) key = self.get_overlay_key(overlay_name) text = json.dumps(overlay, indent=2) self.put_text(key, text)
def put_overlay(self, overlay_name, overlay)
Store the overlay.
3.310048
2.980485
1.110574
logger.debug("Getting properties for handle: {}".format(handle)) properties = { 'size_in_bytes': self.get_size_in_bytes(handle), 'utc_timestamp': self.get_utc_timestamp(handle), 'hash': self.get_hash(handle), 'relpath': self.get_relpath(handle) ...
def item_properties(self, handle)
Return properties of the item with the given handle.
2.72852
2.69165
1.013698