code
stringlengths
1
18.2k
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`. """ return types.List(name, self.api, initial=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`. """ return types.Set(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`. """ return types.SortedSet(name, self.api, initial)
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). See ...
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`. """ return types.Queue(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`. """ return types.LifoQueue(name, self.api, initial=initial, maxsize=maxsize)
def update(self, mapping): """Update database with the key/values from a :class:`dict`.""" return self.api.mset(dict((key, self.prepare_value(value)) for key, value in mapping.items()))
def rename(self, old_name, new_name): """Rename key to a new name.""" 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 iteritems(self, pattern="*"): """An iterator over all the ``(key, value)`` items in the database, or where the keys matches ``pattern``.""" for key in self.keys(pattern): yield (key, self[key])
def pop(self, name): """Get and remove key from database (atomic).""" name = mkey(name) temp = mkey((name, "__poptmp__")) self.rename(name, temp) value = self[temp] del(self[temp]) return value
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)) ''' with file.open('w', newline='') as f: yield DictWriter(f, *args, **kwargs)
def todict(self): """Returns a dictionary fully representing the state of this object """ 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 fromdict(dict): """Takes a dictionary as an argument and returns a new State object from the dictionary. :param dict: the dictionary to convert """ 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 get_hmac(self, key): """Returns the keyed HMAC for authentication of this state data. :param key: the key for the keyed hash function """ 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 ...
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 """ if (self.encrypted): return # encrypt self.iv = Random.new().read(AES.block_size) aes = AES.ne...
def decrypt(self, key): """This method checks the signature on the state and decrypts it. :param key: the key to decrypt and sign with """ # 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...
def fromdict(dict): """Takes a dictionary as an argument and returns a new Proof object from the dictionary. :param dict: the dictionary to convert """ self = Proof() self.mu = dict["mu"] self.sigma = dict["sigma"] return self
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 """ tag = Tag() tag.sigma = list() state = State(Random.new().read(32), Random.new().read(32)) f = KeyedPRF(state.f_key, self.prime) alp...
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...
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 """ chunk_size = self.sectors...
proof.sigma %= self.prime return proof
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 """ state.decrypt(self.key) index = KeyedPRF(ch...
def put(self, event_dict, namespace=None): """ Sends a dictionary of `event_dict` of the form {stream_name: [event, ...], ...} to the server. """ # 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_tim...
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 t...
namespace = namespace or self.namespace if namespace is not None: request_dict['namespace'] = namespace errors = [] last_id = None while True: try: response = self._make_request(self._get_url, data=request_dict, stream=True, timeout=timeout) for line in response.iter_lines(chunk_size=self._chunk_size): if line: # Pytho...
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. "...
def get_streams(self, namespace=None): """ Queries the Kronos server and fetches a list of streams available to be read. """ 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, strea...
def infer_schema(self, stream, namespace=None): """ Queries the Kronos server and fetches the inferred schema for the requested stream. """ return self._make_request(self._infer_schema_url, data={'stream': stream, 'namespace': namespace or self.namespace})
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...
(sys.last_traceback if log_exception_stack_trace else None)) raise exception finally: event['duration'] = time.time() - start_time for key, value_getter in properties.iteritems(): event[key] = value_getter(*args, **kwargs) self.put({stream_name: [event]}, namespace=namespace) return wrapper return decorator
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 functio...
def _nodemap_changed(self, data, stat): """Called when the nodemap changes.""" 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( self.zk, conf...
def _config_changed(self, data, stat): """Called when config changes.""" self.config = json.loads(data) if self.cb: self.cb(self.config)
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 `s...
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 objec...
and not data['message'].get('from_email', None): raise ValueError( 'No from email was specified and no default was configured') response = requests.post(endpoint, data=json.dumps(data), headers={'Content-Type': 'application/json'}) response.raise_for_status() return response
def put_a_hit_out(name): """Download a feed's most recent enclosure that we don't have""" 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: pr...
def selective_download(name, oldest, newest): """Note: RSS feeds are counted backwards, default newest is 0, the most recent.""" 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: pr...
def resolve_name(name): """Takes a given input from a user and finds the url for it""" 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 fee...
def hitsquad(ctx): """'put a hit out' on all known rss feeds [Default action without arguements]""" 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....
def growl(text): """send native notifications where supported. Growl is gone.""" 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") n = pynotif...
platform.system() == 'Windows': try: from win10toast import ToastNotifier toaster = ToastNotifier() toaster.show_toast(text, "Hitman") # gntplib.publish("Hitman", "Status Update", "Hitman", text=text) except Exception: logger.exception()
def add_feed(url): """add to db""" with Database("feeds") as db: title = feedparser.parse(url).feed.title name = str(title) db[name] = url return name
def del_feed(name): """remove from database (and delete aliases)""" 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 aliases del feeds[proper_...
def del_alias(alias): """sometimes you goof up.""" 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 alias_feed(name, alias): """write aliases to db""" 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 list_feeds(): """List all feeds in plain text and give their aliases""" 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: aliases.append(k) if aliases: p...
def export_opml(): """Export an OPML feed list""" with Database("feeds") as feeds: # Thanks to the canto project- used under the GPL print("""<opml version="1.0">""") print("""<body>""") # Accurate but slow. for name in list(feeds.keys()): kind = feedparser.parse(feeds[name]).version if kind[:4] == 'atom': t = 'pie' el...
def import_opml(url): """Import an OPML file locally or from a URL. Uses your text attributes as aliases.""" # 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 = re...
def directory(): """Construct hitman_dir from os name""" 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() == 'Windows': hitman_...
def add(url, force=False): """Add a atom or RSS feed by url. If it doesn't end in .atom or .rss we'll do some guessing.""" if url[-3:] == 'xml' or url[1][-4:] == 'atom': print("Added your feed as %s" % str(add_feed(url))) elif is_feed(url): print("Added your feed as %s" % str(add_feed(url))) elif force: print("Added yo...
def set_settings(key, value): """Set Hitman internal settings.""" with Database("settings") as settings: if value in ['0', 'false', 'no', 'off', 'False']: del settings[key] print("Disabled setting") else: print(value) settings[key] = value print("Setting saved")
def get_settings(all,key): """View Hitman internal settings. Use 'all' for all keys""" with Database("settings") as s: if all: for k, v in zip(list(s.keys()), list(s.values())): print("{} = {}".format(k, v)) elif key: print("{} = {}".format(key, s[key])) else: print("Don't know what you want? Try --all")
def fromdict(dict): """Takes a dictionary as an argument and returns a new Challenge object from the dictionary. :param dict: the dictionary to convert """ seed = hb_decode(dict['seed']) index = dict['index'] return Challenge(seed, index)
def fromdict(dict): """Takes a dictionary as an argument and returns a new Tag object from the dictionary. :param dict: the dictionary to convert """ tree = MerkleTree.fromdict(dict['tree']) chunksz = dict['chunksz'] filesz = dict['filesz'] return Tag(tree, chunksz, filesz)
def todict(self): """Returns a dictionary fully representing the state of this object """ return {'index': self.index, 'seed': hb_encode(self.seed), 'n': self.n, 'root': hb_encode(self.root), 'hmac': hb_encode(self.hmac), 'timestamp': self.timestamp}
def fromdict(dict): """Takes a dictionary as an argument and returns a new State object from the dictionary. :param dict: the dictionary to convert """ index = dict['index'] seed = hb_decode(dict['seed']) n = dict['n'] root = hb_decode(dict['root']) hmac = hb_decode(dict['hmac']) timestamp = dict['timestamp'] self = St...
def get_hmac(self, key): """Returns the keyed HMAC for authentication of this state data. :param key: the key for the keyed hash function """ h = HMAC.new(key, None, SHA256) h.update(str(self.index).encode()) h.update(self.seed) h.update(str(self.n).encode()) h.update(self.root) h.update(str(self.timestamp).encode()) r...
def fromdict(dict): """Takes a dictionary as an argument and returns a new Proof object from the dictionary. :param dict: the dictionary to convert """ key = hb_decode(dict['key']) check_fraction = dict['check_fraction'] return Merkle(check_fraction, key)
def encode(self, file, n=DEFAULT_CHALLENGE_COUNT, seed=None, chunksz=None, filesz=None): """This function generates a merkle tree with the leaves as seed file hashes, the seed for each leaf being a deterministic seed generated from a key. :param file: a file like object that supports the `read()`, `seek()` and `tell()`...
""" if (seed is None): seed = os.urandom(DEFAULT_KEY_SIZE) if (filesz is None): file.seek(0, 2) filesz = file.tell() if (chunksz is None): if (self.check_fraction is not None): chunksz = int(self.check_fraction * filesz) else: chunksz = DEFAULT_CHUNK_SIZE mt = MerkleTree() state = State(0, seed, n) seed = MerkleHelper....
def gen_challenge(self, state): """returns the next challenge and increments the seed and index in the state. :param state: the state to use for generating the challenge. will verify the integrity of the state object before using it to generate a challenge. it will then modify the state by incrementing the seed and ind...
def prove(self, file, challenge, tag): """Returns a proof of ownership of the given file based on the challenge. The proof consists of a hash of the specified file chunk and the complete merkle branch. :param file: a file that supports `read()`, `seek()` and `tell()` :param challenge: the challenge to use for generatin...
def verify(self, proof, challenge, state): """returns true if the proof matches the challenge. verifies that the server possesses the encoded file. :param proof: the proof that was returned from the server :param challenge: the challenge provided to the server :param state: the state of the file, which includes the mer...
def get_next_seed(key, seed): """This takes a seed and generates the next seed in the sequence. it simply calculates the hmac of the seed with the key. It returns the next seed :param key: the key to use for the HMAC :param seed: the seed to permutate """ return hmac.new(key, seed, hashlib.sha256).digest()
def get_file_hash(file, seed, bufsz=DEFAULT_BUFFER_SIZE): """This method generates a secure hash of the given file. Returns the hash :param file: a file like object to get a hash of. should support `read()` :param seed: the seed to use for key of the HMAC function :param bufsz: an optional buffer size to use for readin...
def get_chunk_hash(file, seed, filesz=None, chunksz=DEFAULT_CHUNK_SIZE, bufsz=DEFAULT_BUFFER_SIZE): """returns a hash of a chunk of the file provided. the position of the chunk is determined by the seed. additionally, the hmac of the chunk is calculated from the seed. :param file: a file like object to get the chunk ha...
< bufsz): bufsz = chunksz buffer = file.read(bufsz) h.update(buffer) chunksz -= len(buffer) assert(chunksz >= 0) if (chunksz == 0): break return h.digest()
def from_tuple(cls, queries): """Create a ``Domain`` given a set of complex query tuples. Args: queries (iter): An iterator of complex queries. Each iteration should contain either: * A data-set compatible with :func:`~domain.Domain.add_query` * A string to switch the join type Example:: [('subject', 'Test1'), 'OR', ('...
def add_query(self, query, join_with=AND): """Join a new query to existing queries on the stack. Args: query (tuple or list or DomainCondition): The condition for the query. If a ``DomainCondition`` object is not provided, the input should conform to the interface defined in :func:`~.domain.DomainCondition.from_tuple`....
def from_tuple(cls, query): """Create a condition from a query tuple. Args: query (tuple or list): Tuple or list that contains a query domain in the format of ``(field_name, field_value, field_value_to)``. ``field_value_to`` is only applicable in the case of a date search. Returns: DomainCondition: An instance of a dom...
def load_backends(self): """ Loads all the backends setup in settings.py. """ for name, backend_settings in settings.storage.iteritems(): backend_path = backend_settings['backend'] backend_module, backend_cls = backend_path.rsplit('.', 1) backend_module = import_module(backend_module) # Create an instance of the config...
def get_matching_prefix(self, namespace, stream): """ We look at the stream prefixs configured in stream.yaml and match stream to the longest prefix. """ validate_stream(stream) default_prefix = '' longest_prefix = default_prefix for prefix in self.prefix_confs[namespace]: if prefix == default_prefix: continue if not s...
def backends_to_mutate(self, namespace, stream): """ Return all the backends enabled for writing for `stream`. """ if namespace not in self.namespaces: raise NamespaceMissing('`{}` namespace is not configured' .format(namespace)) return self.prefix_confs[namespace][self.get_matching_prefix(namespace, stream)]
def backend_to_retrieve(self, namespace, stream): """ Return backend enabled for reading for `stream`. """ if namespace not in self.namespaces: raise NamespaceMissing('`{}` namespace is not configured' .format(namespace)) stream_prefix = self.get_matching_prefix(namespace, stream) read_backend = self.prefix_read_backen...
def create(cls, session, web_hook): """Create a web hook. Note that creating a new web hook will overwrite the web hook that is already configured for this company. There is also no way to programmatically determine if a web hook already exists for the company. This is a limitation of the HelpScout API and cannot be ci...
def raw_data(self, value): """Set the base64 encoded data using a raw value or file object.""" if value: try: value = value.read() except AttributeError: pass b64 = base64.b64encode(value.encode('utf-8')) self.data = b64.decode('utf-8')
def schedule(): """HTTP endpoint for scheduling tasks If a task with the same code already exists, the one with the shorter interval will be made active. """ code = request.form['code'] interval = int(request.form['interval']) task_id = binascii.b2a_hex(os.urandom(5)) new_task = Task(id=task_id) new_task.active = True ...
def cancel(): """HTTP endpoint for canceling tasks If an active task is cancelled, an inactive task with the same code and the smallest interval will be activated if it exists. """ task_id = request.form['id'] task = Task.query.get(task_id) if not task: return json.dumps({ 'status': 'success', 'id': None, }) task.delet...
def insert(self, ns, docid, raw, **kw): """ Perform a single insert operation. {'docid': ObjectId('4e95ae77a20e6164850761cd'), 'ns': u'mydb.tweets', 'raw': {u'h': -1469300750073380169L, u'ns': u'mydb.tweets', u'o': {u'_id': ObjectId('4e95ae77a20e6164850761cd'), u'content': u'Lorem ipsum', u'nr': 16}, u'op': u'i', u'ts'...
def update(self, ns, docid, raw, **kw): """ Perform a single update operation. {'docid': ObjectId('4e95ae3616692111bb000001'), 'ns': u'mydb.tweets', 'raw': {u'h': -5295451122737468990L, u'ns': u'mydb.tweets', u'o': {u'$set': {u'content': u'Lorem ipsum'}}, u'o2': {u'_id': ObjectId('4e95ae3616692111bb000001')}, u'op': u'...
def delete(self, ns, docid, raw, **kw): """ Perform a single delete operation. {'docid': ObjectId('4e959ea11669210edc002902'), 'ns': u'mydb.tweets', 'raw': {u'b': True, u'h': -8347418295715732480L, u'ns': u'mydb.tweets', u'o': {u'_id': ObjectId('4e959ea11669210edc002902')}, u'op': u'd', u'ts': Timestamp(1318432261, 104...
def drop_index(self, raw): """ Executes a drop index command. { "op" : "c", "ns" : "testdb.$cmd", "o" : { "dropIndexes" : "testcoll", "index" : "nuie_1" } } """ dbname = raw['ns'].split('.', 1)[0] collname = raw['o']['dropIndexes'] self.dest[dbname][collname].drop_index(raw['o']['index'])
def command(self, ns, raw, **kw): """ Executes command. { "op" : "c", "ns" : "testdb.$cmd", "o" : { "drop" : "fs.files"} } """ try: dbname = raw['ns'].split('.', 1)[0] self.dest[dbname].command(raw['o'], check=True) except OperationFailure, e: logging.warning(e)
def get_folders(cls, session, mailbox_or_id): """List the folders for the mailbox. Args: mailbox_or_id (helpscout.models.Mailbox or int): Mailbox or the ID of the mailbox to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.Folder): Folders iterator. """ if isinstance(mailbox_or_id, Mailbox): ...
def _slice(start, stop, step): """ Generate pairs so that you can slice from start to stop, step elements at a time :param start: The start of the generated series :param stop: The last of the generated series :param step: The difference between the first element of the returned pair and the second :return: A pair that...
def leagues_by_summoner_ids(summoner_ids, queue=Queue.RANKED_SOLO_5x5): """ Takes in a list of players ids and divide them by league tiers. :param summoner_ids: a list containing the ids of players :param queue: the queue to consider :return: a dictionary tier -> set of ids """ summoners_league = defaultdict(set) for s...
def get_tier_from_participants(participantsIdentities, minimum_tier=Tier.bronze, queue=Queue.RANKED_SOLO_5x5): """ Returns the tier of the lowest tier and the participantsIDs divided by tier player in the match :param participantsIdentities: the match participants :param minimum_tier: the minimum tier that a participan...
def summoner_names_to_id(summoners): """ Gets a list of summoners names and return a dictionary mapping the player name to his/her summoner id :param summoners: a list of player names :return: a dictionary name -> id """ ids = {} for start, end in _slice(0, len(summoners), 40): result = get_summoners_by_name(summoners[...
def json(self): """A JSON-encoded description of this board. Format: {'id': board_id, 'title': 'The title of the board', 'panels': [{ 'title': 'The title of the panel' 'data_source': { 'source_type': PanelSource.TYPE, 'refresh_seconds': 600, ...source_specific_details... }, 'display': { 'display_type': PanelDisplay.TYP...
def get(dataset = None, include_metadata = False, mnemonics = None, **dim_values): """Use this function to get data from Knoema dataset.""" if not dataset and not mnemonics: raise ValueError('Dataset id is not specified') if mnemonics and dim_values: raise ValueError('The function does not support specifying mnemonics ...
def upload(file_path, dataset=None, public=False): """Use this function to upload data to Knoema dataset.""" config = ApiConfig() client = ApiClient(config.host, config.app_id, config.app_secret) return client.upload(file_path, dataset, public)
def delete(dataset): """Use this function to delete dataset by it's id.""" config = ApiConfig() client = ApiClient(config.host, config.app_id, config.app_secret) client.check_correct_host() client.delete(dataset) return ('Dataset {} has been deleted successfully'.format(dataset))
def verify(dataset, publication_date, source, refernce_url): """Use this function to verify a dataset.""" config = ApiConfig() client = ApiClient(config.host, config.app_id, config.app_secret) client.check_correct_host() client.verify(dataset, publication_date, source, refernce_url)
def start(self): """ Starts the OplogWatcher. """ oplog = self.connection.local['oplog.rs'] if self.ts is None: cursor = oplog.find().sort('$natural', -1) obj = cursor[0] if obj: self.ts = obj['ts'] else: # In case no oplogs are present. self.ts = None if self.ts: logging.info('Watching oplogs with timestamp > %s' % se...
def process_op(self, ns, raw): """ Processes a single operation from the oplog. Performs a switch by raw['op']: "i" insert "u" update "d" delete "c" db cmd "db" declares presence of a database "n" no op """ # Compute the document id of the document that will be altered # (in case of insert, update or delete). docid = s...
def multi_way_partitioning(items, bin_count): #TODO rename bin_count -> bins ''' Greedily divide weighted items equally across bins. This approximately solves a multi-way partition problem, minimising the difference between the largest and smallest sum of weights in a bin. Parameters ---------- items : ~typing.Iterable...
def toset_from_tosets(*tosets): # Note: a setlist is perfect representation of a toset as it's totally ordered and it's a set, i.e. a toset ''' Create totally ordered set (toset) from tosets. These tosets, when merged, form a partially ordered set. The linear extension of this poset, a toset, is returned. .. warning:: ...
rely on NetworkXUnfeasible https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.dag.topological_sort.html raise ValueError('Given tosets contradict each other') # each cycle is a contradiction, e.g. a > b > c > a # Topological sort return setlist(nx.topological_sort(graph, rever...
def _sortValueIntoGroup(groupKeys, groupLimits, value): """ returns the Key of the group a value belongs to :param groupKeys: a list/tuple of keys ie ['1-3', '3-5', '5-8', '8-10', '10+'] :param groupLimits: a list of the limits for the group [1,3,5,8,10,float('inf')] note the first value is an absolute minimum and the ...