code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You must be in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickException('You must be in a Recipe folder') recipe = DKRecipeDi...
def file_update_all(backend, message, dryrun)
Update all of the changed files for this Recipe
3.920871
3.720895
1.053744
recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder.') click.secho("%s - Resolving conflicts" % get_datetime()) for file_to_resolve in filepath: if not os.path.exists(file_to_resolve): raise click.Click...
def file_resolve(backend, filepath)
Mark a conflicted file as resolved, so that a merge can be completed
6.704573
6.233333
1.0756
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho('%s - Watching Active OrderRun Changes in Kitchen %s' % (get_datetime(), use_kitchen), fg='green') DKCloudCommandRunner.watch_active_servings(backend.dki, us...
def active_serving_watcher(backend, kitchen, period)
Watches all cooking Recipes in a Kitchen Provide the kitchen name as an argument or be in a Kitchen folder.
6.598488
6.157935
1.071542
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder, or pro...
def order_run(backend, kitchen, recipe, variation, node)
Run an order: cook a recipe variation
4.337585
4.20876
1.030609
use_kitchen = Backend.get_kitchen_name_soft(kitchen) print use_kitchen if use_kitchen is None and order_id is None: raise click.ClickException('You must specify either a kitchen or an order_id or be in a kitchen directory') if order_id is not None: click.secho('%s - Delete an Order...
def order_delete(backend, kitchen, order_id)
Delete one order or all orders in a kitchen
4.010082
3.845459
1.04281
if order_id is None: raise click.ClickException('invalid order id %s' % order_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_id), fg='green') check_and_print(DKCloudCommandRunner.stop_order(backend.dki, order_id))
def order_stop(backend, order_id)
Stop an order - Turn off the serving generation ability of an order. Stop any running jobs. Keep all state around.
7.083753
6.616034
1.070695
if order_run_id is None: raise click.ClickException('invalid order id %s' % order_run_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_run_id), fg='green') check_and_print(DKCloudCommandRunner.stop_orderrun(backend.dki, order_run_id.strip()))
def order_stop(backend, order_run_id)
Stop the run of an order - Stop the running order and keep all state around.
6.755483
6.463282
1.045209
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) # if recipe is None: # recipe = DKRecipeDisk.find_reciper_name() # if recipe is None: # raise click.ClickException('You must be in a recipe folde...
def orderrun_detail(backend, kitchen, summary, nodestatus, runstatus, log, timing, test, all_things, order_id, order_run_id, disp_order_id, disp_order_run_id)
Display information about an Order-Run
3.07766
2.996018
1.02725
click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green') check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip()))
def delete_orderrun(backend, orderrun_id)
Delete the orderrun specified by the argument.
8.717552
8.733284
0.998199
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho('%s - Get Order information for Kitchen %s' % (get_datetime(), use_kitchen), fg='green') check_and_print( DKCloudCommandRunner.list_order(back...
def order_list(backend, kitchen)
Apply variables to a Recipe
8.706341
8.898147
0.978444
click.echo(click.style('%s - Getting the list of secrets' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_list(backend.dki,path))
def secret_list(backend,path)
List all Secrets
15.128778
15.353998
0.985332
path,value=entry.split('=') if value.startswith('@'): with open(value[1:]) as vfile: value = vfile.read() click.echo(click.style('%s - Writing secret' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_write(backend.dki,path,value))
def secret_write(backend,entry)
Write a secret
8.214544
8.449045
0.972245
stream.write(str(text) + end) if flush: stream.flush()
def puts(text, end="\n", flush=True, stream=sys.stdout)
Print ``text`` to ``stream`` (default: ``sys.stdout``) and auto-flush. This is useful for fast loops where Python's default IO buffering would prevent "realtime" updating. Newlines may be disabled by setting ``end`` to the empty string (``''``). (This intentionally mirrors Python 3's ``print`` syntax....
3.314605
8.462144
0.391698
if not hasattr(self, '_stream'): if self.file is not None: self._stream = self.file elif self.filename is not None: self._stream = open(self.filename, 'rb') elif self.text is not None: self._stream = StringIO(self.text...
def stream(self)
Returns a stream object (:func:`file`, :class:`~io.BytesIO` or :class:`~StringIO.StringIO`) on the data.
2.706818
2.346822
1.153397
return list(iter(partial(self.readline, *args, **kwargs), u''))
def readlines(self, *args, **kwargs)
Return list of all lines. Always returns list of unicode.
6.690749
4.426575
1.511496
dest = file if hasattr(dest, 'write'): # writing to a file-like # only works when no unicode conversion is done if self.file is not None and\ getattr(self.file, 'encoding', None) is None: copyfileobj(self.file, dest) ...
def save_to(self, file)
Save data to file. Will copy by either writing out the data or using :func:`shutil.copyfileobj`. :param file: A file-like object (with a ``write`` method) or a filename.
5.190519
5.409767
0.959472
tmp = tempfile.NamedTemporaryFile( suffix=suffix, prefix=prefix, dir=dir, delete=False, ) try: self.save_to(tmp) tmp.flush() tmp.seek(0) yield tmp finally: try: ...
def temp_saved(self, suffix='', prefix='tmp', dir=None)
Saves data to temporary file and returns the relevant instance of :func:`~tempfile.NamedTemporaryFile`. The resulting file is not deleted upon closing, but when the context manager exits. Other arguments are passed on to :func:`~tempfile.NamedTemporaryFile`.
2.298115
2.692206
0.853618
outside_pos = f.tell() doff = find_offset(f, 4 * b'\xff' + 'HapsSearch'.encode('ascii')) # actual end of prev section is 34 bytes before, but assume 1 rec f.seek(doff - 62) # seek backwards to find the FFFFFFFF header while True: f.seek(f.tell() - 8) ...
def _ions(self, f)
This is a generator that returns the mzs being measured during each time segment, one segment at a time.
4.861047
4.8023
1.012233
sys.stdout.write(message) sys.stdout.flush()
def _emit_message(cls, message)
Print a message to STDOUT.
4.267552
3.527406
1.209827
sys.stderr.write('ERROR: {message}\n'.format(message=message)) sys.stderr.flush()
def _emit_error(cls, message)
Print an error message to STDERR.
3.393992
3.100613
1.09462
sys.stderr.write('WARNING: {message}\n'.format(message=message)) sys.stderr.flush()
def _emit_warning(cls, message)
Print an warning message to STDERR.
3.528297
3.320351
1.062628
if self.pidfile is None: return piddir = os.path.dirname(self.pidfile) if not os.path.isdir(piddir): # Create the directory with sensible mode and ownership os.makedirs(piddir, 0o777 & ~self.umask) os.chown(piddir, self.uid, self.gid)
def _setup_piddir(self)
Create the directory for the PID file if necessary.
2.744186
2.482913
1.105228
if self.pidfile is None: return None if not os.path.isfile(self.pidfile): return None # Read the PID file with open(self.pidfile, 'r') as fp: try: pid = int(fp.read()) except ValueError: self._emit...
def _read_pidfile(self)
Read the PID file and check to make sure it's not stale.
2.554557
2.393059
1.067486
flags = os.O_CREAT | os.O_RDWR try: # Some systems don't have os.O_EXLOCK flags = flags | os.O_EXLOCK except AttributeError: pass self._pid_fd = os.open(self.pidfile, flags, 0o666 & ~self.umask) os.write(self._pid_fd, str(os.getpid())....
def _write_pidfile(self)
Create, write to, and lock the PID file.
2.777775
2.599153
1.068723
if self._pid_fd is not None: os.close(self._pid_fd) try: os.remove(self.pidfile) except OSError as ex: if ex.errno != errno.ENOENT: raise
def _close_pidfile(self)
Closes and removes the PID file.
2.339468
2.200628
1.063091
try: # Try to get the current limit resource.getrlimit(resource.RLIMIT_CORE) except ValueError: # System doesn't support the RLIMIT_CORE resource limit return else: # Set the soft and hard limits for core dump size to zero ...
def _prevent_core_dump(cls)
Prevent the process from generating a core dump.
4.052788
3.842048
1.054851
# Save the original working directory so that reload can launch # the new process with the same arguments as the original self._orig_workdir = os.getcwd() if self.chrootdir is not None: try: # Change the root directory os.chdir(self.c...
def _setup_environment(self)
Setup the environment for the daemon.
2.815236
2.686716
1.047835
if self.close_open_files: # Attempt to determine the max number of open files max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if max_fds == resource.RLIM_INFINITY: # If the limit is infinity, use a more reasonable limit max_fds...
def _reset_file_descriptors(self)
Close open file descriptors and redirect standard streams.
2.416177
2.284955
1.057429
try: fd = stream.fileno() except ValueError: # If it has no file descriptor, it's not a socket return False sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW) try: # This will raise a socket.error if it's not a socket ...
def _is_socket(cls, stream)
Check if the given stream is a socket.
2.602588
2.506165
1.038474
try: proc = psutil.Process(pid) except psutil.NoSuchProcess: return False try: proc.wait(timeout=timeout) except psutil.TimeoutExpired: return True return False
def _pid_is_alive(cls, pid, timeout)
Check if a PID is alive with a timeout.
2.177614
1.997572
1.090131
if os.getppid() == 1: # Process was started by init return False if cls._is_socket(sys.stdin): # If STDIN is a socket, the daemon was started by a super-server return False return True
def _is_detach_necessary(cls)
Check if detaching the process is even necessary.
9.665819
7.501311
1.288551
# First fork to return control to the shell pid = os.fork() if pid > 0: # Wait for the first child, because it's going to wait and # check to make sure the second child is actually running # before exiting os.waitpid(pid, 0) sy...
def _detach_process(self)
Detach the process via the standard double-fork method with some extra magic.
4.905231
4.822795
1.017093
# The current PID will be the PPID of the forked child ppid = os.getpid() pid = os.fork() if pid > 0: # Exit parent sys.exit(0) if wait_for_parent and cls._pid_is_alive(ppid, timeout=1): raise DaemonError( 'Parent did...
def _orphan_this_process(cls, wait_for_parent=False)
Orphan the current process by forking and then waiting for the parent to exit.
5.138489
4.70515
1.092099
pid = os.fork() if pid == 0: # Fork again but orphan the child this time so we'll have # the original parent and the second child which is orphaned # so we don't have to worry about it becoming a zombie cls._orphan_this_process() retur...
def _fork_and_supervise_child(cls)
Fork a child and then watch the process group until there are no processes in it.
3.823286
3.680733
1.038729
if self._shutdown_complete: # Make sure we don't accidentally re-run the all cleanup sys.exit(code) if self.shutdown_callback is not None: # Call the shutdown callback with a message suitable for # logging and the exit code self.shutd...
def _shutdown(self, message=None, code=0)
Shutdown and cleanup everything.
4.434719
4.270104
1.038551
signal_names = { signal.SIGINT: 'SIGINT', signal.SIGQUIT: 'SIGQUIT', signal.SIGTERM: 'SIGTERM', } message = 'Terminated by {name} ({number})'.format( name=signal_names[signal_number], number=signal_number) self._shutdown(message, c...
def _handle_terminate(self, signal_number, _)
Handle a signal to terminate.
2.404639
2.345286
1.025307
try: # Run the worker self.worker() except SystemExit as ex: # sys.exit() was called if isinstance(ex.code, int): if ex.code is not None and ex.code != 0: # A custom exit code was specified s...
def _run(self)
Run the worker function with some custom exception handling.
3.505904
3.283179
1.067838
if self.worker is None: raise DaemonError('No worker is defined for daemon') if os.environ.get('DAEMONOCLE_RELOAD'): # If this is actually a reload, we need to wait for the # existing daemon to exit first self._emit_message('Reloading {prog} ... ...
def start(self)
Start the daemon.
4.253706
4.186622
1.016023
if self.pidfile is None: raise DaemonError('Cannot stop daemon without PID file') pid = self._read_pidfile() if pid is None: # I don't think this should be a fatal error self._emit_warning('{prog} is not running'.format(prog=self.prog)) r...
def stop(self)
Stop the daemon.
3.0084
2.870671
1.047978
if self.pidfile is None: raise DaemonError('Cannot get status of daemon without PID file') pid = self._read_pidfile() if pid is None: self._emit_message( '{prog} -- not running\n'.format(prog=self.prog)) sys.exit(1) proc = ps...
def status(self)
Get the status of the daemon.
2.41319
2.351352
1.026299
# Make sure these are always at the beginning of the list actions = ['start', 'stop', 'restart', 'status'] # Iterate over the instance attributes checking for actions that # have been exposed for func_name in dir(cls): func = getattr(cls, func_name) ...
def list_actions(cls)
Get a list of exposed actions that are callable via the ``do_action()`` method.
4.16828
3.871418
1.07668
func_name = action.replace('-', '_') if not hasattr(self, func_name): # Function doesn't exist raise DaemonError( 'Invalid action "{action}"'.format(action=action)) func = getattr(self, func_name) if (not hasattr(func, '__call__') or ...
def get_action(self, action)
Get a callable action.
3.505737
3.189863
1.099024
pid = self._read_pidfile() if pid is None or pid != os.getpid(): raise DaemonError( 'Daemon.reload() should only be called by the daemon process ' 'itself') # Copy the current environment new_environ = os.environ.copy() new_en...
def reload(self)
Make the daemon reload itself.
5.171971
4.757604
1.087096
win_list = [] for t0, t1, hints in peak_list: p_w = (t0, t1) for w in win_list: if p_w[0] <= w[0][1] and p_w[1] >= w[0][0]: w[0] = (min(p_w[0], w[0][0]), max(p_w[1], w[0][1])) w[1].append((t0, t1, hints)) break else: ...
def _get_windows(peak_list)
Given a list of peaks, bin them into windows.
2.087052
1.994369
1.046473
rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None or isinstance(recipe, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe parame...
def add_file(self, kitchen, recipe, message, api_file_key, file_contents)
returns True for success or False for failure '/v2/recipe/create/<string:kitchenname>/<string:recipename>', methods=['PUT'] :param self: DKCloudAPI :param kitchen: basestring :param recipe: basestring -- kitchen name, basestring :param message: basestring message -- commit messa...
2.54653
2.313305
1.100819
rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen') return rc if recipe_name is None or isinstance(recipe_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe_name')...
def get_compiled_serving(self, kitchen, recipe_name, variation_name)
get the compiled version of arecipe with variables applied for a specific variation in a kitchen returns a dictionary '/v2/servings/compiled/get/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['GET'] :param self: DKCloudAPI :param kitchen: basestring :p...
2.921845
2.54316
1.148903
rc = DKReturnCode() if from_kitchen is None or isinstance(from_kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with from kitchen') return rc if to_kitchen is None or isinstance(to_kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with ...
def merge_kitchens_improved(self, from_kitchen, to_kitchen, resolved_conflicts=None)
merges kitchens '/v2/kitchen/merge/<string:kitchenname>/<string:kitchenname>', methods=['POST'] :param resolved_conflicts: :param self: DKCloudAPI :param from_kitchen: string :param to_kitchen: string :rtype: dict
2.82151
2.57021
1.097774
rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False or \ recipe is None or isinstance(recipe, basestring) is False or \ file_path is None or isinstance(file_path, basestring) is False or \ orig_head is None or isinst...
def merge_file(self, kitchen, recipe, file_path, file_contents, orig_head, last_file_sha)
Returns the result of merging a local file with the latest version on the remote. This does not cause any side-effects on the server, and no actual merge is performed in the remote repo. /v2/file/merge/<string:kitchenname>/<string:recipename>/<path:filepath>, methods=['POST'] :param kitchen: nam...
2.745211
2.63044
1.043632
rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None or isinstance(recipe, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe parame...
def recipe_status(self, kitchen, recipe, local_dir=None)
gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :param local_dir: string -- :rtype: dict
3.558649
3.326672
1.069732
rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None or isinstance(recipe, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe parame...
def recipe_tree(self, kitchen, recipe)
gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :rtype: dict
3.836643
3.486706
1.100363
rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen') return rc if recipe_name is None or isinstance(recipe_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe_name')...
def create_order(self, kitchen, recipe_name, variation_name, node_name=None)
Full graph '/v2/order/create/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['PUT'] Single node '/v2/order/create/onenode/<string:kitchenname>/<string:recipename>/<string:variationname>/<string:nodename', methods=['PUT']
2.781556
2.576705
1.079501
rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen') return rc url = '%s/v2/order/details/%s' % (self.get_url_for_direct_rest_call(), kitchen) ...
def orderrun_detail(self, kitchen, pdict, return_all_data=False)
api.add_resource(OrderDetailsV2, '/v2/order/details/<string:kitchenname>', methods=['POST']) :param self: DKCloudAPI :param kitchen: string :param pdict: dict :param return_all_data: boolean :rtype: DKReturnCode
3.873006
3.333938
1.161691
rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc url = '%s/v2/order/status/%s' % (self.get_url_for_direct_rest_call(), kitchen) try: response = re...
def list_order(self, kitchen, save_to_file=None)
List the orders for a kitchen or recipe
4.194957
4.144112
1.012269
if isinstance(value, types.StringTypes): value = parse(value) return_as_str = True else: value = kronos_time_to_datetime(value) return_as_str = False timeframes = { DateTrunc.Unit.SECOND: (lambda dt: dt - timedelta(microseconds=dt.microsecond)), DateTrunc.Uni...
def _date_trunc(value, timeframe)
A date flooring function. Returns the closest datetime to the current one that aligns to timeframe. For example, _date_trunc('2014-08-13 05:00:00', DateTrunc.Unit.MONTH) will return a Kronos time representing 2014-08-01 00:00:00.
1.945156
1.794756
1.0838
if isinstance(value, types.StringTypes): value = parse(value) else: value = kronos_time_to_datetime(value) parts = { DatePart.Unit.SECOND: lambda dt: dt.second, DatePart.Unit.MINUTE: lambda dt: dt.minute, DatePart.Unit.HOUR: lambda dt: dt.hour, DatePart.Unit.DAY: lambda dt: dt.day, ...
def _date_part(value, part)
Returns a portion of a datetime. Returns the portion of a datetime represented by timeframe. For example, _date_part('2014-08-13 05:00:00', DatePart.Unit.WEEK_DAY) will return 2, for Wednesday.
2.067502
1.784724
1.158444
return types.List(name, self.api, initial=initial)
def List(self, name, initial=None)
The list datatype. :param name: The name of the list. :keyword initial: Initial contents of the list. See :class:`redish.types.List`.
11.715154
19.603527
0.597604
return types.Set(name, self.api, initial)
def Set(self, name, initial=None)
The set datatype. :param name: The name of the set. :keyword initial: Initial members of the set. See :class:`redish.types.Set`.
17.464474
32.645782
0.534969
return types.SortedSet(name, self.api, initial)
def SortedSet(self, name, initial=None)
The sorted set datatype. :param name: The name of the sorted set. :param initial: Initial members of the set as an iterable of ``(element, score)`` tuples. See :class:`redish.types.SortedSet`.
11.287192
22.717377
0.496853
return types.Dict(name, self.api, initial=initial, **extra)
def Dict(self, name, initial=None, **extra)
The dictionary datatype (Hash). :param name: The name of the dictionary. :keyword initial: Initial contents. :keyword \*\*extra: Initial contents as keyword arguments. The ``initial``, and ``**extra`` keyword arguments will be merged (keyword arguments has priority). S...
7.229424
12.76982
0.566134
return types.Queue(name, self.api, initial=initial, maxsize=maxsize)
def Queue(self, name, initial=None, maxsize=None)
The queue datatype. :param name: The name of the queue. :keyword initial: Initial items in the queue. See :class:`redish.types.Queue`.
5.784464
10.677211
0.541758
return types.LifoQueue(name, self.api, initial=initial, maxsize=maxsize)
def LifoQueue(self, name, initial=None, maxsize=None)
The LIFO queue datatype. :param name: The name of the queue. :keyword initial: Initial items in the queue. See :class:`redish.types.LifoQueue`.
6.715517
11.315289
0.593491
return self.api.mset(dict((key, self.prepare_value(value)) for key, value in mapping.items()))
def update(self, mapping)
Update database with the key/values from a :class:`dict`.
7.562548
6.771801
1.116771
try: self.api.rename(mkey(old_name), mkey(new_name)) except ResponseError, exc: if "no such key" in exc.args: raise KeyError(old_name) raise
def rename(self, old_name, new_name)
Rename key to a new name.
4.452018
4.160697
1.070018
for key in self.keys(pattern): yield (key, self[key])
def iteritems(self, pattern="*")
An iterator over all the ``(key, value)`` items in the database, or where the keys matches ``pattern``.
3.974477
4.353507
0.912937
name = mkey(name) temp = mkey((name, "__poptmp__")) self.rename(name, temp) value = self[temp] del(self[temp]) return value
def pop(self, name)
Get and remove key from database (atomic).
7.32116
6.643327
1.102032
''' Write CSV file. Parameters ---------- file : Path *args csv.DictWriter args (except the f arg) **kwargs csv.DictWriter args Examples -------- with write.csv(file) as writer: writer.writerow((1,2,3)) ''' with file.open('w', newline='') as f: ...
def csv(file, *args, **kwargs)
Write CSV file. Parameters ---------- file : Path *args csv.DictWriter args (except the f arg) **kwargs csv.DictWriter args Examples -------- with write.csv(file) as writer: writer.writerow((1,2,3))
4.710421
1.792072
2.628477
return {"f_key": hb_encode(self.f_key), "alpha_key": hb_encode(self.alpha_key), "chunks": self.chunks, "encrypted": self.encrypted, "iv": hb_encode(self.iv), "hmac": hb_encode(self.hmac)}
def todict(self)
Returns a dictionary fully representing the state of this object
4.009941
3.962979
1.01185
return State(hb_decode(dict["f_key"]), hb_decode(dict["alpha_key"]), dict["chunks"], dict["encrypted"], hb_decode(dict["iv"]), hb_decode(dict["hmac"]))
def fromdict(dict)
Takes a dictionary as an argument and returns a new State object from the dictionary. :param dict: the dictionary to convert
9.244097
10.242195
0.90255
h = HMAC.new(key, None, SHA256) h.update(self.iv) h.update(str(self.chunks).encode()) h.update(self.f_key) h.update(self.alpha_key) h.update(str(self.encrypted).encode()) return h.digest()
def get_hmac(self, key)
Returns the keyed HMAC for authentication of this state data. :param key: the key for the keyed hash function
3.344142
3.693482
0.905417
if (self.encrypted): return # encrypt self.iv = Random.new().read(AES.block_size) aes = AES.new(key, AES.MODE_CFB, self.iv) self.f_key = aes.encrypt(self.f_key) self.alpha_key = aes.encrypt(self.alpha_key) self.encrypted = True # sign ...
def encrypt(self, key)
This method encrypts and signs the state to make it unreadable by the server, since it contains information that would allow faking proof of storage. :param key: the key to encrypt and sign with
2.917807
3.013959
0.968098
# check signature if (self.get_hmac(key) != self.hmac): raise HeartbeatError("Signature invalid on state.") if (not self.encrypted): return # decrypt aes = AES.new(key, AES.MODE_CFB, self.iv) self.f_key = aes.decrypt(self.f_key) se...
def decrypt(self, key)
This method checks the signature on the state and decrypts it. :param key: the key to decrypt and sign with
4.080085
3.951256
1.032604
self = Proof() self.mu = dict["mu"] self.sigma = dict["sigma"] return self
def fromdict(dict)
Takes a dictionary as an argument and returns a new Proof object from the dictionary. :param dict: the dictionary to convert
6.41134
5.613231
1.142184
tag = Tag() tag.sigma = list() state = State(Random.new().read(32), Random.new().read(32)) f = KeyedPRF(state.f_key, self.prime) alpha = KeyedPRF(state.alpha_key, self.prime) done = False chunk_id = 0 while (not done): sigma = f.ev...
def encode(self, file)
This function returns a (tag,state) tuple that is calculated for the given file. the state will be encrypted with `self.key` :param file: the file to encode
4.568637
4.367402
1.046077
state.decrypt(self.key) chal = Challenge(state.chunks, self.prime, Random.new().read(32)) return chal
def gen_challenge(self, state)
This function generates a challenge for given state. It selects a random number and sets that as the challenge key. By default, v_max is set to the prime, and the number of chunks to challenge is the number of chunks in the file. (this doesn't guarantee that the whole file will be che...
11.208222
11.269954
0.994522
chunk_size = self.sectors * self.sectorsize index = KeyedPRF(chal.key, len(tag.sigma)) v = KeyedPRF(chal.key, chal.v_max) proof = Proof() proof.mu = [0] * self.sectors proof.sigma = 0 for i in range(0, chal.chunks): for j in range(0, self.s...
def prove(self, file, chal, tag)
This function returns a proof calculated from the file, the challenge, and the file tag :param file: this is a file like object that supports `read()`, `tell()` and `seek()` methods. :param chal: the challenge to use for proving :param tag: the file tag
3.302121
3.455219
0.955691
state.decrypt(self.key) index = KeyedPRF(chal.key, state.chunks) v = KeyedPRF(chal.key, chal.v_max) f = KeyedPRF(state.f_key, self.prime) alpha = KeyedPRF(state.alpha_key, self.prime) rhs = 0 for i in range(0, chal.chunks): rhs += v.eval(i)...
def verify(self, proof, chal, state)
This returns True if the proof matches the challenge and file state :param proof: the proof that was returned from the server :param chal: the challenge sent to the server :param state: the state of the file, which can be encrypted
4.755806
4.93558
0.963576
# Copy the input, in case we need to modify it by adding a timestamp. event_dict = copy.deepcopy(event_dict) # Ensure that all events have a timestamp. timestamp = kronos_time_now() for events in event_dict.itervalues(): for event in events: if TIMESTAMP_FIELD not in event: ...
def put(self, event_dict, namespace=None)
Sends a dictionary of `event_dict` of the form {stream_name: [event, ...], ...} to the server.
3.184402
3.038016
1.048185
if isinstance(start_time, types.StringTypes): start_time = parse(start_time) if isinstance(end_time, types.StringTypes): end_time = parse(end_time) if isinstance(start_time, datetime): start_time = datetime_to_kronos_time(start_time) if isinstance(end_time, datetime): end_ti...
def get(self, stream, start_time, end_time, start_id=None, limit=None, order=ResultOrder.ASCENDING, namespace=None, timeout=None)
Queries a stream with name `stream` for all events between `start_time` and `end_time` (both inclusive). An optional `start_id` allows the client to restart from a failure, specifying the last ID they read; all events that happened after that ID will be returned. An optional `limit` limits the maximum ...
2.459018
2.466445
0.996989
if isinstance(start_time, types.StringTypes): start_time = parse(start_time) if isinstance(end_time, types.StringTypes): end_time = parse(end_time) if isinstance(start_time, datetime): start_time = datetime_to_kronos_time(start_time) if isinstance(end_time, datetime): end_ti...
def delete(self, stream, start_time, end_time, start_id=None, namespace=None)
Delete events in the stream with name `stream` that occurred between `start_time` and `end_time` (both inclusive). An optional `start_id` allows the client to delete events starting from after an ID rather than starting at a timestamp.
1.864853
1.891694
0.985811
request_dict = {} namespace = namespace or self.namespace if namespace is not None: request_dict['namespace'] = namespace response = self._make_request(self._streams_url, data=request_dict, stream=True) for line in respon...
def get_streams(self, namespace=None)
Queries the Kronos server and fetches a list of streams available to be read.
3.330247
3.121537
1.066861
return self._make_request(self._infer_schema_url, data={'stream': stream, 'namespace': namespace or self.namespace})
def infer_schema(self, stream, namespace=None)
Queries the Kronos server and fetches the inferred schema for the requested stream.
5.138511
5.186804
0.990689
namespace = namespace or self.namespace def decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): event = {} start_time = time.time() if log_function_stack_trace: event['stack_trace'] = traceback.extract_stack() try: r...
def log_function(self, stream_name, properties={}, log_function_stack_trace=False, log_exception_stack_trace=False, namespace=None)
Logs each call to the function as an event in the stream with name `stream_name`. If `log_stack_trace` is set, it will log the stack trace under the `stack_trace` key. `properties` is an optional mapping fron key name to some function which expects the same arguments as the function `function` being dec...
2.470013
2.531791
0.975599
start_time = time.time() namespace = namespace or self.namespace event = properties.copy() if log_scope_stack_trace: event['stack_trace'] = traceback.extract_stack() try: yield event except Exception, exception: self._log_exception(event, exception, ...
def log_scope(self, stream_name, properties={}, log_scope_stack_trace=False, log_exception_stack_trace=False, namespace=None)
Identical to `log_function` except that `log_scope` is used to log blocks of code. The API is identical except that keys in `properties` are mapped to real values rather than getter functions. Usage: with kronos_client.log_scope('mystreamname', properties={ 'lol':'cat' }, ...
3.222627
3.438221
0.937295
if not stat: raise EnvironmentNotFoundException(self.nodemap_path) try: conf_path = self._deserialize_nodemap(data)[self.hostname] except KeyError: conf_path = '/services/%s/conf' % self.service self.config_watcher = DataWatch( ...
def _nodemap_changed(self, data, stat)
Called when the nodemap changes.
7.275863
7.251128
1.003411
self.config = json.loads(data) if self.cb: self.cb(self.config)
def _config_changed(self, data, stat)
Called when config changes.
5.355963
4.763351
1.124411
if not start_id: start_id = uuid_from_kronos_time(start_time, _type=UUIDType.LOWEST) else: start_id = TimeUUID(start_id) if uuid_to_kronos_time(start_id) > end_time: return [] return self._retrieve(namespace, stream, start_id, end_time, order, limit, conf...
def retrieve(self, namespace, stream, start_time, end_time, start_id, configuration, order=ResultOrder.ASCENDING, limit=sys.maxint)
Retrieves all the events for `stream` from `start_time` (inclusive) till `end_time` (inclusive). Alternatively to `start_time`, `start_id` can be provided, and then all events from `start_id` (exclusive) till `end_time` (inclusive) are returned. `start_id` should be used in cases when the client got dis...
4.052643
4.628973
0.875495
endpoint = self.messages_endpoint data = { 'async': kwargs.pop('async', False), 'ip_pool': kwargs.pop('ip_pool', ''), 'key': kwargs.pop('key', self.api_key), } if not data.get('key', None): raise ValueError('No Mandrill API key h...
def send_email(self, **kwargs)
Sends an email using Mandrill's API. Returns a Requests :class:`Response` object. At a minimum kwargs must contain the keys to, from_email, and text. Everything passed as kwargs except for the keywords 'key', 'async', and 'ip_pool' will be sent as key-value pairs in the message object. ...
2.97091
2.706389
1.09774
feed = resolve_name(name) if six.PY3: feed = feed.decode() d = feedparser.parse(feed) # logger.info(d) # logger.info(feed) print(d['feed']['title']) if d.entries[0].enclosures: with Database("settings") as s: if 'verbose' in s: print(d.entrie...
def put_a_hit_out(name)
Download a feed's most recent enclosure that we don't have
3.844476
3.671288
1.047174
if six.PY3: name = name.encode("utf-8") feed = resolve_name(name) if six.PY3: feed = feed.decode() d = feedparser.parse(feed) logger.debug(d) try: d.entries[int(oldest)] except IndexError: print("Error feed does not contain this many items.") prin...
def selective_download(name, oldest, newest)
Note: RSS feeds are counted backwards, default newest is 0, the most recent.
4.467312
4.401936
1.014852
logger.debug("resolve_name: %s", name) with Database("feeds") as feeds, Database("aliases") as aliases: if name in aliases.keys(): return feeds[aliases[name]] elif name in feeds.keys(): return feeds[name] else: print("Cannot find feed named: %s" %...
def resolve_name(name)
Takes a given input from a user and finds the url for it
3.873545
3.821068
1.013734
with Database("feeds") as feeds: for name, feed in zip(list(feeds.keys()), list(feeds.values())): logger.debug("calling put_a_hit_out: %s", name) ctx.invoke(put_a_hit_out, name=name) if len(list(feeds.keys())) == 0: ctx.get_help()
def hitsquad(ctx)
put a hit out' on all known rss feeds [Default action without arguements]
5.80353
4.087923
1.419677
if platform.system() == 'Darwin': import pync pync.Notifier.notify(text, title="Hitman") elif platform.system() == 'Linux': notified = False try: logger.debug("Trying to import pynotify") import pynotify pynotify.init("Hitman") ...
def growl(text)
send native notifications where supported. Growl is gone.
4.213398
4.171374
1.010074
with Database("feeds") as db: title = feedparser.parse(url).feed.title name = str(title) db[name] = url return name
def add_feed(url)
add to db
5.391975
5.305283
1.016341
with Database("aliases") as aliases, Database("feeds") as feeds: if aliases[name]: proper_name = aliases[name] elif feeds[name]: proper_name = feeds[name] for k, v in aliases: if v == proper_name: del aliases[k] # deleted from ...
def del_feed(name)
remove from database (and delete aliases)
4.593065
3.974447
1.155649
with Database("aliases") as mydb: try: print("removing alias of %s to %s" % (alias, mydb.pop(alias))) except KeyError: print("No such alias key") print("Check alias db:") print(zip(list(mydb.keys()), list(mydb.values())))
def del_alias(alias)
sometimes you goof up.
6.724342
6.52098
1.031186
with Database("aliases") as db: if alias in db: print("Something has gone horribly wrong with your aliases! Try deleting the %s entry." % name) return else: db[alias] = name
def alias_feed(name, alias)
write aliases to db
6.393927
6.204427
1.030543
with Database("feeds") as feeds, Database("aliases") as aliases_db: for feed in feeds: name = feed url = feeds[feed] aliases = [] for k, v in zip(list(aliases_db.keys()), list(aliases_db.values())): if v == name: aliase...
def list_feeds()
List all feeds in plain text and give their aliases
3.221334
3.026533
1.064364
with Database("feeds") as feeds: # Thanks to the canto project- used under the GPL print() print() # Accurate but slow. for name in list(feeds.keys()): kind = feedparser.parse(feeds[name]).version if kind[:4] == 'atom': t = 'pie' ...
def export_opml()
Export an OPML feed list
12.014624
11.855503
1.013422
# Test if URL given is local, then open, parse out feed urls, # add feeds, set text= to aliases and report success, list feeds added from bs4 import BeautifulSoup try: f = file(url).read() except IOError: f = requests.get(url).text soup = BeautifulSoup(f, "xml") links = ...
def import_opml(url)
Import an OPML file locally or from a URL. Uses your text attributes as aliases.
11.213486
10.410335
1.077149
home = os.path.expanduser('~') if platform.system() == 'Linux': hitman_dir = os.path.join(home, '.hitman') elif platform.system() == 'Darwin': hitman_dir = os.path.join(home, 'Library', 'Application Support', 'hitman') elif platform.system() == 'Win...
def directory()
Construct hitman_dir from os name
1.632909
1.402855
1.16399