code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def ltake(n: int, xs: Iterable[T]) -> List[T]: return list(take(n, xs))
A non-lazy version of take.
def guess_currency_from_address(address): if is_py2: fixer = lambda x: int(x.encode('hex'), 16) else: fixer = lambda x: x first_byte = fixer(b58decode_check(address)[0]) double_first_byte = fixer(b58decode_check(address)[:2]) hits = [] for currency, data in crypto_data.items(): ...
Given a crypto address, find which currency it likely belongs to. Raises an exception if it can't find a match. Raises exception if address is invalid.
def get_sections(self): try: obj_list = self.__dict__['sections'] return [Section(i) for i in obj_list] except KeyError: self._lazy_load() obj_list = self.__dict__['sections'] return [Section(i) for i in obj_list]
Fetch the sections field if it does not exist.
def rstyle(self, name): try: del self.chart_style[name] except KeyError: self.warning("Style " + name + " is not set") except: self.err("Can not remove style " + name)
Remove one style
def get_base_url(html: str) -> str: forms = BeautifulSoup(html, 'html.parser').find_all('form') if not forms: raise VVKBaseUrlException('Form for login not found') elif len(forms) > 1: raise VVKBaseUrlException('More than one login form found') login_url = forms[0].get('action') if n...
Search for login url from VK login page
def from_path(cls, path): urlparts = urlparse.urlsplit(path) site = 'nonlocal' if (urlparts.scheme == '' or urlparts.scheme == 'file'): if os.path.isfile(urlparts.path): path = os.path.abspath(urlparts.path) path = urlparse.urljoin('file:', ...
Takes a path and returns a File object with the path as the PFN.
def get_rlz(self, rlzstr): r mo = re.match(r'rlz-(\d+)', rlzstr) if not mo: return return self.realizations[int(mo.group(1))]
r""" Get a Realization instance for a string of the form 'rlz-\d+'
def plot_roc_curve(self, on, bootstrap_samples=100, ax=None, **kwargs): plot_col, df = self.as_dataframe(on, return_cols=True, **kwargs) df = filter_not_null(df, "benefit") df = filter_not_null(df, plot_col) df.benefit = df.benefit.astype(bool) return roc_curve_plot(df, plot_col,...
Plot an ROC curve for benefit and a given variable Parameters ---------- on : str or function or list or dict See `cohort.load.as_dataframe` bootstrap_samples : int, optional Number of boostrap samples to use to compute the AUC ax : Axes, default None ...
def delete(self, *keys): key_counter = 0 for key in map(self._encode, keys): if key in self.redis: del self.redis[key] key_counter += 1 if key in self.timeouts: del self.timeouts[key] return key_counter
Emulate delete.
def write(self, request): if FLAGS.sc2_verbose_protocol: self._log(" Writing request ".center(60, "-") + "\n") self._log_packet(request) self._write(request)
Write a Request.
def add(self, lineitem): if lineitem['ProductName']: self._lineitems.append(lineitem) if lineitem['BlendedCost']: self._blended_cost += lineitem['BlendedCost'] if lineitem['UnBlendedCost']: self._unblended_cost += lineitem['UnBlendedCost']
Add a line item record to this Costs object.
def map_query(self, variables=None, evidence=None, elimination_order=None): final_distribution = self._variable_elimination(variables, 'marginalize', evidence=evidence, elimination_order=elimination_o...
Computes the MAP Query over the variables given the evidence. Note: When multiple variables are passed, it returns the map_query for each of them individually. Parameters ---------- variables: list list of variables over which we want to compute the max-marginal. ...
def _get_permission_description(permission_name): parts = permission_name.split('_') parts.pop(0) method = parts.pop() resource = ('_'.join(parts)).lower() return 'Can %s %s' % (method.upper(), resource)
Generate a descriptive string based on the permission name. For example: 'resource_Order_get' -> 'Can GET order' todo: add support for the resource name to have underscores
def is_mainline(self) -> bool: node = self while node.parent: parent = node.parent if not parent.variations or parent.variations[0] != node: return False node = parent return True
Checks if the node is in the mainline of the game.
def build_on_start(self, runnable, regime, on_start): on_start_code = [] for action in on_start.actions: code = self.build_action(runnable, regime, action) for line in code: on_start_code += [line] return on_start_code
Build OnStart start handler code. @param on_start: OnStart start handler object @type on_start: lems.model.dynamics.OnStart @return: Generated OnStart code @rtype: list(string)
def mark_dead(self, proxy, _time=None): if proxy not in self.proxies: logger.warn("Proxy <%s> was not found in proxies list" % proxy) return if proxy in self.good: logger.debug("GOOD proxy became DEAD: <%s>" % proxy) else: logger.debug("Proxy <%s> ...
Mark a proxy as dead
def calcLorenzDistance(self): LorenzSim = np.mean(np.array(self.Lorenz_hist)[self.ignore_periods:,:],axis=0) dist = np.sqrt(np.sum((100*(LorenzSim - self.LorenzTarget))**2)) self.LorenzDistance = dist return dist
Returns the sum of squared differences between simulated and target Lorenz points. Parameters ---------- None Returns ------- dist : float Sum of squared distances between simulated and target Lorenz points (sqrt)
def update_release(id, **kwargs): data = update_release_raw(id, **kwargs) if data: return utils.format_json(data)
Update an existing ProductRelease with new information
def loop_input(self, on_quit=None): self._run_script( self.__session, self._context.get_property(PROP_INIT_FILE) ) script_file = self._context.get_property(PROP_RUN_FILE) if script_file: self._run_script(self.__session, script_file) else: self....
Reads the standard input until the shell session is stopped :param on_quit: A call back method, called without argument when the shell session has ended
def _init_metadata(self): self._mdata.update(default_mdata.get_osid_form_mdata()) update_display_text_defaults(self._mdata['journal_comment'], self._locale_map) for element_name in self._mdata: self._mdata[element_name].update( {'element_id': Id(self._authority, ...
Initialize OsidObjectForm metadata.
def highlight_source_at_location(source: "Source", location: "SourceLocation") -> str: first_line_column_offset = source.location_offset.column - 1 body = " " * first_line_column_offset + source.body line_index = location.line - 1 line_offset = source.location_offset.line - 1 line_num = location.lin...
Highlight source at given location. This renders a helpful description of the location of the error in the GraphQL Source document.
def _ServerActions(action,alias,servers): if alias is None: alias = clc.v1.Account.GetAlias() results = [] for server in servers: r = clc.v1.API.Call('post','Server/%sServer' % (action), {'AccountAlias': alias, 'Name': server }) if int(r['StatusCode']) == 0: results.append(r) return(results)
Archives the specified servers. :param action: the server action url to exec against :param alias: short code for a particular account. If none will use account's default alias :param servers: list of server names
def query_most(num=8, kind='1'): return TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( TabPost.view_count.desc() ).limit(num)
Query most viewed.
def create_osd_keyring(conn, cluster, key): logger = conn.logger path = '/var/lib/ceph/bootstrap-osd/{cluster}.keyring'.format( cluster=cluster, ) if not conn.remote_module.path_exists(path): logger.warning('osd keyring does not exist yet, creating one') conn.remote_module.write_...
Run on osd node, writes the bootstrap key if not there yet.
def remove_file(config_map, file_key): if file_key[0] == '/': file_key = file_key[1::] client = boto3.client( 's3', aws_access_key_id=config_map['put_public_key'], aws_secret_access_key=config_map['put_private_key'] ) client.delete_object( Bucket=config_map['s3_bu...
Convenience function for removing objects from AWS S3 Added by cjshaw@mit.edu, Apr 28, 2015 May 25, 2017: Switch to boto3
def new_floating_ip(self, **kwargs): droplet_id = kwargs.get('droplet_id') region = kwargs.get('region') if self.api_version == 2: if droplet_id is not None and region is not None: raise DoError('Only one of droplet_id and region is required to create a Floating IP. '...
Creates a Floating IP and assigns it to a Droplet or reserves it to a region.
def email(self, value): email = self.wait.until(expected.visibility_of_element_located( self._email_input_locator)) email.clear() email.send_keys(value)
Set the value of the email field.
def _indent(stream, indent, *msgs): for x in range(0, indent): stream.write(" ") for x in msgs: stream.write(x.encode("ascii", "backslashreplace").decode("ascii")) stream.write("\n")
write a message to a text stream, with indentation. Also ensures that the output encoding of the messages is safe for writing.
def clean(self, *args, **kwargs): if self.status != LINK_STATUS.get('planned'): if self.interface_a is None or self.interface_b is None: raise ValidationError(_('fields "from interface" and "to interface" are mandatory in this case')) if (self.interface_a_id == self.inter...
Custom validation 1. interface_a and interface_b mandatory except for planned links 2. planned links should have at least node_a and node_b filled in 3. dbm and noise fields can be filled only for radio links 4. interface_a and interface_b must differ 5. inter...
def image_data(verbose=False): global _IMAGE_DATA if _IMAGE_DATA is None: if verbose: logger.info("--- Downloading image.") with contextlib.closing(urllib.request.urlopen(IMAGE_URL)) as infile: _IMAGE_DATA = infile.read() return _IMAGE_DATA
Get the raw encoded image data, downloading it if necessary.
def create_client_for_kernel(self): connect_output = KernelConnectionDialog.get_connection_parameters(self) (connection_file, hostname, sshkey, password, ok) = connect_output if not ok: return else: self._create_client_for_kernel(connection_file, hostname, s...
Create a client connected to an existing kernel
def save(self, *args, **kwargs): if self.descriptor_schema: try: validate_schema(self.descriptor, self.descriptor_schema.schema) self.descriptor_dirty = False except DirtyError: self.descriptor_dirty = True elif self.descriptor and ...
Perform descriptor validation and save object.
def generate_new_address(coin_symbol='btc', api_key=None): assert api_key, 'api_key required' assert is_valid_coin_symbol(coin_symbol) if coin_symbol not in ('btc-testnet', 'bcy'): WARNING_MSG = [ 'Generating private key details server-side.', 'You really should do th...
Takes a coin_symbol and returns a new address with it's public and private keys. This method will create the address server side, which is inherently insecure and should only be used for testing. If you want to create a secure address client-side using python, please check out bitmerchant: from bitme...
def H11(self): "Difference entropy." return -(self.p_xminusy * np.log(self.p_xminusy + self.eps)).sum(1)
Difference entropy.
def commit(message, add=False, quiet=False): if add: run('add .') try: stdout = run('commit -m %r' % str(message), quiet=quiet) except GitError as e: s = str(e) if 'nothing to commit' in s or 'no changes added to commit' in s: raise EmptyCommit(*e.inits()) ...
Commit with that message and return the SHA1 of the commit If add is truish then "$ git add ." first
def __set_frame_shift_status(self): if 'fs' in self.hgvs_original: self.is_frame_shift = True self.is_non_silent = True elif re.search('[A-Z]\d+[A-Z]+\*', self.hgvs_original): self.is_frame_shift = True self.is_non_silent = True else: s...
Check for frame shift and set the self.is_frame_shift flag.
def parse(self, text): if isinstance(text, bytes): text = text.decode("ascii") text = re.sub("\s+", " ", unidecode(text)) return self.communicate(text + "\n")
Call the server and return the raw results.
def brighten(color, brightness): h, s, v = rgb_to_hsv(*map(down_scale, color)) return tuple(map(up_scale, hsv_to_rgb(h, s, v + down_scale(brightness))))
Adds or subtracts value to a color.
def _CamelCaseToSnakeCase(path_name): result = [] for c in path_name: if c == '_': raise ParseError('Fail to parse FieldMask: Path name ' '{0} must not contain "_"s.'.format(path_name)) if c.isupper(): result += '_' result += c.lower() else: result += c r...
Converts a field name from camelCase to snake_case.
def add_ref(self, ref, attr=None): self.session.add_ref(self, ref, attr) return self.fetch()
Add reference to resource :param ref: reference to add :type ref: Resource :rtype: Resource
def _setup(self): if isinstance(self.module, torch.nn.RNNBase): self.module.flatten_parameters = noop for name_w in self.weights: w = getattr(self.module, name_w) del self.module._parameters[name_w] self.module.register_parameter(name_w + '_raw', nn.Parameter(w.data))
for each string defined in self.weights, the corresponding attribute in the wrapped module is referenced, then deleted, and subsequently registered as a new parameter with a slightly modified name. Args: None Returns: None
def _parse_datetime_string(val): dt = None lenval = len(val) fmt = {19: "%Y-%m-%d %H:%M:%S", 10: "%Y-%m-%d"}.get(lenval) if fmt is None: raise exc.InvalidDateTimeString("The supplied value '%s' does not " "match either of the formats 'YYYY-MM-DD HH:MM:SS' or " "'YYYY-...
Attempts to parse a string representation of a date or datetime value, and returns a datetime if successful. If not, a InvalidDateTimeString exception will be raised.
def createWidgets(self): from gooey.gui.components import widgets return [getattr(widgets, item['type'])(self, item) for item in getin(self.widgetInfo, ['data', 'widgets'], [])]
Instantiate the Gooey Widgets that are used within the RadioGroup
def GetHandlers(self): handlers = [] if self.ssl_context: handlers.append(urllib2.HTTPSHandler(context=self.ssl_context)) if self.proxies: handlers.append(urllib2.ProxyHandler(self.proxies)) return handlers
Retrieve the appropriate urllib2 handlers for the given configuration. Returns: A list of urllib2.BaseHandler subclasses to be used when making calls with proxy.
def find_stacks(node, strict=False): fso = FindStackOps() fso.visit(node) AnnotateStacks(fso.push_pop_pairs, strict).visit(node) return node
Find pushes and pops to the stack and annotate them as such. Args: node: An AST node that might contain stack pushes and pops. strict: A boolean indicating whether to stringently test whether each push and pop are matched. This is not always possible when taking higher-order derivatives of co...
def requires(self): value = self._schema.get("requires", {}) if not isinstance(value, (basestring, dict)): raise SchemaError( "requires value {0!r} is neither a string nor an" " object".format(value)) return value
Additional object or objects required by this object.
def pre_request(self, response, exc=None): if response.request.method == 'CONNECT': self.start_response( '200 Connection established', [('content-length', '0')] ) self.future.set_result([b'']) upstream = response.connection ...
Start the tunnel. This is a callback fired once a connection with upstream server is established.
def get_config(path): if configparser is None: return None if os.path.exists(os.path.join(ROOT, 'config', NAME, path)): path = os.path.join(ROOT, 'config', NAME, path) else: path = os.path.join(ROOT, 'config', path) if not os.path.isfile(path): return None conf = open...
Load a config from disk :param path: target config :type path: unicode :return: :rtype: configparser.Config
def insert_all(db, schema_name, table_name, columns, items): table = '{0}.{1}'.format(schema_name, table_name) if schema_name else table_name columns_list = ', '.join(columns) values_list = ', '.join(['?'] * len(columns)) query = 'INSERT INTO {table} ({columns}) VALUES ({values})'.format( table=...
Insert all item in given items list into the specified table, schema_name.table_name.
def is_participle_clause_fragment(sentence): if not _begins_with_one_of(sentence, ['VBG', 'VBN', 'JJ']): return 0.0 if _begins_with_one_of(sentence, ['JJ']): doc = nlp(sentence) fw = [w for w in doc][0] if fw.dep_ == 'amod': return 0.0 if _begins_with_one_of(sente...
Supply a sentence or fragment and recieve a confidence interval
def sprand(m, n, density, format='csr'): m, n = int(m), int(n) A = _rand_sparse(m, n, density, format='csr') A.data = sp.rand(A.nnz) return A.asformat(format)
Return a random sparse matrix. Parameters ---------- m, n : int shape of the result density : float target a matrix with nnz(A) = m*n*density, 0<=density<=1 format : string sparse matrix format to return, e.g. 'csr', 'coo', etc. Return ------ A : sparse matrix ...
def get_app_config(app_id): try: req = requests.get( ("https://clients3.google.com/" "cast/chromecast/device/app?a={}").format(app_id)) return json.loads(req.text[4:]) if req.status_code == 200 else {} except ValueError: return {}
Get specific configuration for 'app_id'.
def get_cgi_parameter_float(form: cgi.FieldStorage, key: str) -> Optional[float]: return get_float_or_none(get_cgi_parameter_str(form, key))
Extracts a float parameter from a CGI form, or None if the key is absent or the string value is not convertible to ``float``.
def read_float(self): self.bitcount = self.bits = 0 return unpack('>d', self.input.read(8))[0]
Read float value.
def is_valid_boundaries(self, boundaries): if boundaries is not None: min_ = boundaries[0] for value in boundaries: if value < min_: return False else: min_ = value return True return False
checks if the boundaries are in ascending order
def deserialize_header_auth(stream, algorithm, verifier=None): _LOGGER.debug("Starting header auth deserialization") format_string = ">{iv_len}s{tag_len}s".format(iv_len=algorithm.iv_len, tag_len=algorithm.tag_len) return MessageHeaderAuthentication(*unpack_values(format_string, stream, verifier))
Deserializes a MessageHeaderAuthentication object from a source stream. :param stream: Source data stream :type stream: io.BytesIO :param algorithm: The AlgorithmSuite object type contained in the header :type algorith: aws_encryption_sdk.identifiers.AlgorithmSuite :param verifier: Signature verifi...
def query(self, *args): if not args or len(args) > 2: raise TypeError('query() takes 2 or 3 arguments (a query or a key ' 'and a query) (%d given)' % (len(args) + 1)) elif len(args) == 1: query, = args return self.get('text').query(text_typ...
Query a fulltext index by key and query or just a plain Lucene query, i1 = gdb.nodes.indexes.get('people',type='fulltext', provider='lucene') i1.query('name','do*') i1.query('name:do*') In this example, the last two line are equivalent.
def validate_work_spec(cls, work_spec): if 'name' not in work_spec: raise ProgrammerError('work_spec lacks "name"') if 'min_gb' not in work_spec or \ not isinstance(work_spec['min_gb'], (float, int, long)): raise ProgrammerError('work_spec["min_gb"] must be a numb...
Check that `work_spec` is valid. It must at the very minimum contain a ``name`` and ``min_gb``. :raise rejester.exceptions.ProgrammerError: if it isn't valid
def after_third_friday(day=None): day = day if day is not None else datetime.datetime.now() now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0) now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR) return day > now
check if day is after month's 3rd friday
def listen_now_items(self): response = self._call( mc_calls.ListenNowGetListenNowItems ) listen_now_item_list = response.body.get('listennow_items', []) listen_now_items = defaultdict(list) for item in listen_now_item_list: type_ = f"{ListenNowItemType(item['type']).name}s" listen_now_items[type_].ap...
Get a listing of Listen Now items. Note: This does not include situations; use the :meth:`situations` method instead. Returns: dict: With ``albums`` and ``stations`` keys of listen now items.
def _create_sync_map(self, sync_root): sync_map = SyncMap(tree=sync_root, rconf=self.rconf, logger=self.logger) if self.rconf.safety_checks: self.log(u"Running sanity check on computed sync map...") if not sync_map.leaves_are_consistent: self._step_failure(ValueEr...
If requested, check that the computed sync map is consistent. Then, add it to the Task.
def update_ticket(self, ticket_id=None, body=None): return self.ticket.addUpdate({'entry': body}, id=ticket_id)
Update a ticket. :param integer ticket_id: the id of the ticket to update :param string body: entry to update in the ticket
def hasReaders(self, ulBuffer): fn = self.function_table.hasReaders result = fn(ulBuffer) return result
inexpensively checks for readers to allow writers to fast-fail potentially expensive copies and writes.
def get_instance(cls, encoded_key): login_str = base64.b64decode(encoded_key).decode('utf-8') usertoken, password = login_str.strip().split(':', 1) instance = cls(usertoken, password) return instance
Return an ApiAuth instance from an encoded key
def stop(self, nowait=False): self._stop.set() if nowait: self._stop_nowait.set() self.queue.put_nowait(self._sentinel_item) if (self._thread.isAlive() and self._thread is not threading.currentThread()): self._thread.join() self._thread = N...
Stop the listener. This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there may be some records still left on the queue, which won't be processed. If nowait is False then thread will handle remaining items i...
def populate_audit_fields(self, event): event.updated = self._data event.original = self.get_original()._data
Populates the the audit JSON fields with raw data from the model, so all changes can be tracked and diffed. Args: event (Event): The Event instance to attach the data to instance (fleaker.db.Model): The newly created/updated model
def schemaValidCtxtGetParserCtxt(self): ret = libxml2mod.xmlSchemaValidCtxtGetParserCtxt(self._o) if ret is None:raise parserError('xmlSchemaValidCtxtGetParserCtxt() failed') __tmp = parserCtxt(_obj=ret) return __tmp
allow access to the parser context of the schema validation context
def iterate_similarity_datasets(args): for dataset_name in args.similarity_datasets: parameters = nlp.data.list_datasets(dataset_name) for key_values in itertools.product(*parameters.values()): kwargs = dict(zip(parameters.keys(), key_values)) yield dataset_name, kwargs, nlp....
Generator over all similarity evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset.
def bind(cls, origin, handler, *, name=None): name = cls.__name__ if name is None else name attrs = { "_origin": origin, "_handler": handler, "__module__": "origin", } return type(name, (cls,), attrs)
Bind this object to the given origin and handler. :param origin: An instance of `Origin`. :param handler: An instance of `bones.HandlerAPI`. :return: A subclass of this class.
def get_time_position(self, time): if time < self._start or time > self._finish: raise ValueError("time argument out of bounds") return (time - self._start) / (self._resolution / self._zoom_factor)
Get x-coordinate for given time :param time: Time to determine x-coordinate on Canvas for :type time: float :return: X-coordinate for the given time :rtype: int :raises: ValueError
def open(self, mode): if mode == 'w': return self.format.pipe_writer(AtomicFtpFile(self._fs, self.path)) elif mode == 'r': temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-contrib-ftp') self.__tmp_path = temp_dir + '/' + self.path.lstrip('/') + '-luigi-tmp-%09d' ...
Open the FileSystem target. This method returns a file-like object which can either be read from or written to depending on the specified mode. :param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will open the FileSystemTarget in write mode....
def eol_distance_last(self, offset=0): distance = 0 for char in reversed(self.string[:self.pos + offset]): if char == '\n': break else: distance += 1 return distance
Return the ammount of characters until the last newline.
def order_target_percent(self, asset, target, limit_price=None, stop_price=None, style=None): if not self._can_order_asset(asset): return None amount = self._calculate_order_target_percent_amount(asset, target) return self.order(asset, amount, ...
Place an order to adjust a position to a target percent of the current portfolio value. If the position doesn't already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target percent and t...
def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type...
Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_ty...
def count(a, axis=None): axes = _normalise_axis(axis, a) if axes is None or len(axes) != 1: msg = "This operation is currently limited to a single axis" raise AxisSupportError(msg) return _Aggregation(a, axes[0], _CountStreamsHandler, _CountMaskedStreamsHandler, ...
Count the non-masked elements of the array along the given axis. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the inp...
def lines(self): if self._lines is None: with io.open(self.path, 'r', encoding='utf-8') as fh: self._lines = fh.read().split('\n') return self._lines
List of file lines.
def get_version(): if not INSTALLED: try: with open('version.txt', 'r') as v_fh: return v_fh.read() except Exception: warnings.warn( 'Unable to resolve package version until installed', UserWarning ) retu...
find current version information Returns: (str): version information
def stringify(data): def serialize(k, v): if k == "candidates": return int(v) if isinstance(v, numbers.Number): if k == "zipcode": return str(v).zfill(5) return str(v) return v return [{k: serialize(k, v) for k, v in json_dict.items()} ...
Ensure all values in the dictionary are strings, except for the value for `candidate` which should just be an integer. :param data: a list of addresses in dictionary format :return: the same list with all values except for `candidate` count as a string
def rm(venv_name): inenv = InenvManager() venv = inenv.get_venv(venv_name) click.confirm("Delete dir {}".format(venv.path)) shutil.rmtree(venv.path)
Removes the venv by name
def build_table(self, table, force=False): sources = self._resolve_sources(None, [table]) for source in sources: self.build_source(None, source, force=force) self.unify_partitions()
Build all of the sources for a table
def format_sms_payload(self, message, to, sender='elkme', options=[]): self.validate_number(to) if not isinstance(message, str): message = " ".join(message) message = message.rstrip() sms = { 'from': sender, 'to': to, 'message': message ...
Helper function to create a SMS payload with little effort
def create_server(loop, host, port=CONTROL_PORT, reconnect=False): server = Snapserver(loop, host, port, reconnect) yield from server.start() return server
Server factory.
def check_production_parameters_exist(self): for k, v in self.modelInstance.parameter_sets.items(): for p_id in self.modelInstance.production_params.keys(): if v.get(p_id): pass else: v[p_id] = 1.0 for p_id in self.m...
old versions of models won't have produciton parameters, leading to ZeroDivision errors and breaking things
def close_db(self, exception): if self.is_connected: if exception is None and not transaction.isDoomed(): transaction.commit() else: transaction.abort() self.connection.close()
Added as a `~flask.Flask.teardown_request` to applications to commit the transaction and disconnect ZODB if it was used during the request.
def show(self, uuid=None, term=None): try: if uuid: uidentities = api.unique_identities(self.db, uuid) elif term: uidentities = api.search_unique_identities(self.db, term) else: uidentities = api.unique_identities(self.db) ...
Show the information related to unique identities. This method prints information related to unique identities such as identities or enrollments. When <uuid> is given, it will only show information about the unique identity related to <uuid>. When <term> is set, it will only s...
def get_similar_commands(name): from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
Command name auto-correct.
def readString(self): length, is_reference = self._readLength() if is_reference: result = self.context.getString(length) return self.context.getStringForBytes(result) if length == 0: return '' result = self.stream.read(length) self.context.addS...
Reads and returns a string from the stream.
def _dataframe_to_edge_list(df): cols = df.columns if len(cols): assert _SRC_VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _SRC_VID_COLUMN assert _DST_VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _DST_VID_COLUMN df = df[cols].T ret = [Edge(Non...
Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN respectively.
def after(f, chain=False): def decorator(g): @wraps(g) def h(*args, **kargs): if chain: return f(g(*args, **kargs)) else: r = g(*args, **kargs) f(*args, **kargs) return r return h return decorator
Runs f with the result of the decorated function.
def _from_dict(cls, _dict): args = {} if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) ] if 'entities...
Initialize a DialogSuggestionValue object from a json dictionary.
def getExtensionArgs(self): aliases = NamespaceMap() required = [] if_available = [] ax_args = self._newArgs() for type_uri, attribute in self.requested_attributes.items(): if attribute.alias is None: alias = aliases.add(type_uri) else: ...
Get the serialized form of this attribute fetch request. @returns: The fetch request message parameters @rtype: {unicode:unicode}
def determine_end_point(http_request, url): if url.endswith('aggregates') or url.endswith('aggregates/'): return 'aggregates' else: return 'detail' if is_detail_url(http_request, url) else 'list'
returns detail, list or aggregates
def types(self): out = [] if self._transform_bytes: out.append(bytes) if self._transform_str: out.append(str) return tuple(out)
Tuple containing types transformed by this transformer.
def entity_types(args): r = fapi.list_entity_types(args.project, args.workspace) fapi._check_response_code(r, 200) return r.json().keys()
List entity types in a workspace
def shutdown(self): self._must_shutdown = True self._is_shutdown.wait() self._meta_runner.stop()
Shutdown the accept loop and stop running payloads
def insert(self, space, t, *, replace=False, timeout=-1) -> _MethodRet: return self._db.insert(space, t, replace=replace, timeout=timeout)
Insert request coroutine. Examples: .. code-block:: pycon # Basic usage >>> await conn.insert('tester', [0, 'hello']) <Response sync=3 rowcount=1 data=[ <TarantoolTuple id=0 name='hello'> ]> #...
def serialize_to_string(self, name, datas): value = datas.get('value', None) if value is None: msg = ("String reference '{}' lacks of required 'value' variable " "or is empty") raise SerializerError(msg.format(name)) return value
Serialize given datas to a string. Simply return the value from required variable``value``. Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Returns: string: Value.
def SensorShare(self, sensor_id, parameters): if not parameters['user']['id']: parameters['user'].pop('id') if not parameters['user']['username']: parameters['user'].pop('username') if self.__SenseApiCall__("/sensors/{0}/users".format(sensor_id), "POST", parameters =...
Share a sensor with a user @param sensor_id (int) - Id of sensor to be shared @param parameters (dictionary) - Additional parameters for the call @return (bool) - Boolean indicating whether the ShareSensor call was successful
def get_queryset(self, request): if request.GET.get(ShowHistoryFilter.parameter_name) == '1': queryset = self.model.objects.with_active_flag() else: queryset = self.model.objects.current_set() ordering = self.get_ordering(request) if ordering: return q...
Annote the queryset with an 'is_active' property that's true iff that row is the most recently added row for that particular set of KEY_FIELDS values. Filter the queryset to show only is_active rows by default.
def salt_syndic(): import salt.utils.process salt.utils.process.notify_systemd() import salt.cli.daemons pid = os.getpid() try: syndic = salt.cli.daemons.Syndic() syndic.start() except KeyboardInterrupt: os.kill(pid, 15)
Start the salt syndic.