code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def GetChildrenByPriority(self, allow_external=True): """Generator that yields active filestore children in priority order.""" for child in sorted(self.OpenChildren(), key=lambda x: x.PRIORITY): if not allow_external and child.EXTERNAL: continue if child.Get(child.Schema.ACTIVE): yie...
Generator that yields active filestore children in priority order.
def freeze_parameter(self, name): """ Freeze a parameter by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = False
Freeze a parameter by name Args: name: The name of the parameter
def add_row(self, id_): """Add a new row to the pattern. :param id_: the id of the row """ row = self._parser.new_row(id_) self._rows.append(row) return row
Add a new row to the pattern. :param id_: the id of the row
def boundary_maximum_linear(graph, xxx_todo_changeme1): r""" Boundary term processing adjacent voxels maximum value using a linear relationship. An implementation of a boundary term, suitable to be used with the `~medpy.graphcut.generate.graph_from_voxels` function. The same as `boundary_...
r""" Boundary term processing adjacent voxels maximum value using a linear relationship. An implementation of a boundary term, suitable to be used with the `~medpy.graphcut.generate.graph_from_voxels` function. The same as `boundary_difference_linear`, but working on the gradient image instea...
def namedb_get_name_from_name_hash128( cur, name_hash128, block_number ): """ Given the hexlified 128-bit hash of a name, get the name. """ unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number ) select_query = "SELECT name FROM name_records JOIN namespaces ON name_re...
Given the hexlified 128-bit hash of a name, get the name.
def append_value_continuation(self, linenum, indent, continuation): """ :param linenum: The line number of the frame. :type linenum: int :param indent: The indentation level of the frame. :type indent: int :param continuation: :type continuation: str """ ...
:param linenum: The line number of the frame. :type linenum: int :param indent: The indentation level of the frame. :type indent: int :param continuation: :type continuation: str
def _distance(self): """Compute the distance function d(f,g,\pi), Eq. (3)""" return np.average(self.min_kl, weights=self.f.weights)
Compute the distance function d(f,g,\pi), Eq. (3)
def match(self, node, results=None): """Override match() to insist on a leaf node.""" if not isinstance(node, Leaf): return False return BasePattern.match(self, node, results)
Override match() to insist on a leaf node.
def get_download_url(self, instance, default=None): """Calculate the download url """ download = default # calculate the download url download = "{url}/@@download/{fieldname}/{filename}".format( url=api.get_url(instance), fieldname=self.get_field_name(), ...
Calculate the download url
def fromMimeData(self, data): """ Paste the clipboard data at the current cursor position. This method also adds another undo-object to the undo-stack. ..note: This method forcefully interrupts the ``QsciInternal`` pasting mechnism by returning an empty MIME data elemen...
Paste the clipboard data at the current cursor position. This method also adds another undo-object to the undo-stack. ..note: This method forcefully interrupts the ``QsciInternal`` pasting mechnism by returning an empty MIME data element. This is not an elegant implemen...
def heartbeat(self): """Heartbeat request to keep session alive. """ unique_id = self.new_unique_id() message = { 'op': 'heartbeat', 'id': unique_id, } self._send(message) return unique_id
Heartbeat request to keep session alive.
def space_acl(args): ''' Retrieve access control list for a workspace''' r = fapi.get_workspace_acl(args.project, args.workspace) fapi._check_response_code(r, 200) result = dict() for user, info in sorted(r.json()['acl'].items()): result[user] = info['accessLevel'] return result
Retrieve access control list for a workspace
def ruamelindex(self, strictindex): """ Get the ruamel equivalent of a strict parsed index. E.g. 0 -> 0, 1 -> 2, parsed-via-slugify -> Parsed via slugify """ return ( self.key_association.get(strictindex, strictindex) if self.is_mapping() else...
Get the ruamel equivalent of a strict parsed index. E.g. 0 -> 0, 1 -> 2, parsed-via-slugify -> Parsed via slugify
def send_packet(self, pk, expected_reply=(), resend=False, timeout=0.2): """ Send a packet through the link interface. pk -- Packet to send expect_answer -- True if a packet from the Crazyflie is expected to be sent back, otherwise false """ sel...
Send a packet through the link interface. pk -- Packet to send expect_answer -- True if a packet from the Crazyflie is expected to be sent back, otherwise false
def _maybeCleanSessions(self): """ Clean expired sessions if it's been long enough since the last clean. """ sinceLast = self._clock.seconds() - self._lastClean if sinceLast > self.sessionCleanFrequency: self._cleanSessions()
Clean expired sessions if it's been long enough since the last clean.
def _get_best_effort_ndims(x, expect_ndims=None, expect_ndims_at_least=None, expect_ndims_no_more_than=None): """Get static ndims if possible. Fallback on `tf.rank(x)`.""" ndims_static = _get_static_ndims( x, expect_ndims=...
Get static ndims if possible. Fallback on `tf.rank(x)`.
def total_members_in_score_range_in( self, leaderboard_name, min_score, max_score): ''' Retrieve the total members in a given score range from the named leaderboard. @param leaderboard_name Name of the leaderboard. @param min_score [float] Minimum score. @param max_s...
Retrieve the total members in a given score range from the named leaderboard. @param leaderboard_name Name of the leaderboard. @param min_score [float] Minimum score. @param max_score [float] Maximum score. @return the total members in a given score range from the named leaderboard.
def delayed_redraw(self): """Handle delayed redrawing of the canvas.""" # This is the optimized redraw method with self._defer_lock: # pick up the lowest necessary level of redrawing whence = self._defer_whence self._defer_whence = self._defer_whence_reset ...
Handle delayed redrawing of the canvas.
def apply_transform(self, matrix): """ Transform mesh by a homogenous transformation matrix. Does the bookkeeping to avoid recomputing things so this function should be used rather than directly modifying self.vertices if possible. Parameters ---------- ...
Transform mesh by a homogenous transformation matrix. Does the bookkeeping to avoid recomputing things so this function should be used rather than directly modifying self.vertices if possible. Parameters ---------- matrix : (4, 4) float Homogenous transformati...
def update_browsers(self, *args, **kwargs): """Update the shot and the assetbrowsers :returns: None :rtype: None :raises: None """ sel = self.prjbrws.selected_indexes(0) if not sel: return prjindex = sel[0] if not prjindex.isValid(): ...
Update the shot and the assetbrowsers :returns: None :rtype: None :raises: None
def train(self): """Runs one logical iteration of training. Subclasses should override ``_train()`` instead to return results. This class automatically fills the following fields in the result: `done` (bool): training is terminated. Filled only if not provided. `time_t...
Runs one logical iteration of training. Subclasses should override ``_train()`` instead to return results. This class automatically fills the following fields in the result: `done` (bool): training is terminated. Filled only if not provided. `time_this_iter_s` (float): Time in...
def get_language(query: str) -> str: """Tries to work out the highlight.js language of a given file name or shebang. Returns an empty string if none match. """ query = query.lower() for language in LANGUAGES: if query.endswith(language): return language return ''
Tries to work out the highlight.js language of a given file name or shebang. Returns an empty string if none match.
def setCheckedRecords(self, records, column=0, parent=None): """ Sets the checked items based on the inputed list of records. :param records | [<orb.Table>, ..] parent | <QTreeWidgetItem> || None """ if parent is None: for i ...
Sets the checked items based on the inputed list of records. :param records | [<orb.Table>, ..] parent | <QTreeWidgetItem> || None
def save(self, request): """ Saves a new comment and sends any notification emails. """ comment = self.get_comment_object() obj = comment.content_object if request.user.is_authenticated(): comment.user = request.user comment.by_author = request.user ==...
Saves a new comment and sends any notification emails.
def publish(self, message): """ Publishes the message to all subscribers of this topic :param message: (object), the message to be published. """ message_data = self._to_data(message) self._encode_invoke(topic_publish_codec, message=message_data)
Publishes the message to all subscribers of this topic :param message: (object), the message to be published.
def _set_alert(self, v, load=False): """ Setter method for alert, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert (container) If this variable is read-only (config: false) in the source YANG file, then _set_alert is considered as a private method. Backends looking...
Setter method for alert, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert (container) If this variable is read-only (config: false) in the source YANG file, then _set_alert is considered as a private method. Backends looking to populate this variable should do so via c...
def is_pure_name(path): """ Return True if path is a name and not a file path. Parameters ---------- path : str Path (can be absolute, relative, etc.) Returns ------- bool True if path is a name of config in config dir, not file path. """ return ( not os...
Return True if path is a name and not a file path. Parameters ---------- path : str Path (can be absolute, relative, etc.) Returns ------- bool True if path is a name of config in config dir, not file path.
def _flatten_lane_details(runinfo): """Provide flattened lane information with multiplexed barcodes separated. """ out = [] for ldetail in runinfo["details"]: # handle controls if "project_name" not in ldetail and ldetail["description"] == "control": ldetail["project_name"] =...
Provide flattened lane information with multiplexed barcodes separated.
def dbg(*objects, file=sys.stderr, flush=True, **kwargs): "Helper function to print to stderr and flush" print(*objects, file=file, flush=flush, **kwargs)
Helper function to print to stderr and flush
def GetOrderKey(self): """Return a tuple that can be used to sort problems into a consistent order. Returns: A list of values. """ context_attributes = ['_type'] context_attributes.extend(ExceptionWithContext.CONTEXT_PARTS) context_attributes.extend(self._GetExtraOrderAttributes()) t...
Return a tuple that can be used to sort problems into a consistent order. Returns: A list of values.
def get_option(self, option): """ Get a configuration option, trying the options attribute first and falling back to a Django project setting. """ value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIE...
Get a configuration option, trying the options attribute first and falling back to a Django project setting.
def swd_write(self, output, value, nbits): """Writes bytes over SWD (Serial Wire Debug). Args: self (JLink): the ``JLink`` instance output (int): the output buffer offset to write to value (int): the value to write to the output buffer nbits (int): the number of ...
Writes bytes over SWD (Serial Wire Debug). Args: self (JLink): the ``JLink`` instance output (int): the output buffer offset to write to value (int): the value to write to the output buffer nbits (int): the number of bits needed to represent the ``output`` and ...
def operations(self, op_types=None): """Process operation stream.""" if not op_types: op_types = ['message', 'action', 'sync', 'viewlock', 'savedchapter'] while self._handle.tell() < self._eof: current_time = mgz.util.convert_to_timestamp(self._time / 1000) tr...
Process operation stream.
def top(num_processes=5, interval=3): ''' Return a list of top CPU consuming processes during the interval. num_processes = return the top N CPU consuming processes interval = the number of seconds to sample CPU usage over CLI Examples: .. code-block:: bash salt '*' ps.top sa...
Return a list of top CPU consuming processes during the interval. num_processes = return the top N CPU consuming processes interval = the number of seconds to sample CPU usage over CLI Examples: .. code-block:: bash salt '*' ps.top salt '*' ps.top 5 10
def check_columns(self, check_views=True): """Check if the columns in all tables are equals. Parameters ---------- check_views: bool if True, check the columns of all the tables and views, if False check only the columns of the tables ...
Check if the columns in all tables are equals. Parameters ---------- check_views: bool if True, check the columns of all the tables and views, if False check only the columns of the tables Returns ------- bool ...
def _parse_bands(self, band_input): """ Parses class input and verifies band names. :param band_input: input parameter `bands` :type band_input: str or list(str) or None :return: verified list of bands :rtype: list(str) """ all_bands = AwsConstants.S2_L1C...
Parses class input and verifies band names. :param band_input: input parameter `bands` :type band_input: str or list(str) or None :return: verified list of bands :rtype: list(str)
def tril(array, k=0): '''Lower triangle of an array. Return a copy of an array with elements above the k-th diagonal zeroed. Need a multi-dimensional version here because numpy.tril does not broadcast for numpy verison < 1.9.''' try: tril_array = np.tril(array, k=k) except: # hav...
Lower triangle of an array. Return a copy of an array with elements above the k-th diagonal zeroed. Need a multi-dimensional version here because numpy.tril does not broadcast for numpy verison < 1.9.
def encrypt(self, wif): """ Encrypt the content according to BIP38 :param str wif: Unencrypted key """ if not self.unlocked(): raise WalletLocked return format(bip38.encrypt(str(wif), self.masterkey), "encwif")
Encrypt the content according to BIP38 :param str wif: Unencrypted key
def find_requirement(self, req, upgrade, ignore_compatibility=False): # type: (InstallRequirement, bool, bool) -> Optional[Link] """Try to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a Link if found, Raises DistributionNotFound or B...
Try to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a Link if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
def select_edges_by(docgraph, layer=None, edge_type=None, data=False): """ get all edges with the given edge type and layer. Parameters ---------- docgraph : DiscourseDocumentGraph document graph from which the nodes will be extracted layer : str name of the layer edge_type ...
get all edges with the given edge type and layer. Parameters ---------- docgraph : DiscourseDocumentGraph document graph from which the nodes will be extracted layer : str name of the layer edge_type : str Type of the edges to be extracted (Edge types are defined in the ...
def create_nginx_config(self): """ Creates the Nginx configuration for the project """ cfg = '# nginx config for {0}\n'.format(self._project_name) if not self._shared_hosting: # user if self._user: cfg += 'user {0};\n'.format(self._user) ...
Creates the Nginx configuration for the project
def __update_offset_table(self, fileobj, fmt, atom, delta, offset): """Update offset table in the specified atom.""" if atom.offset > offset: atom.offset += delta fileobj.seek(atom.offset + 12) data = fileobj.read(atom.length - 12) fmt = fmt % cdata.uint_be(data[:4]) ...
Update offset table in the specified atom.
def on_left_click(self, event, grid, choices): """ creates popup menu when user clicks on the column if that column is in the list of choices that get a drop-down menu. allows user to edit the column, but only from available values """ row, col = event.GetRow(), event.Get...
creates popup menu when user clicks on the column if that column is in the list of choices that get a drop-down menu. allows user to edit the column, but only from available values
def set_insn(self, insn): """ Set a new raw buffer to disassemble :param insn: the buffer :type insn: string """ self.insn = insn self.size = len(self.insn)
Set a new raw buffer to disassemble :param insn: the buffer :type insn: string
def get_referenced_object(self): """ :rtype: core.BunqModel :raise: BunqException """ if self._BunqMeTab is not None: return self._BunqMeTab if self._BunqMeTabResultResponse is not None: return self._BunqMeTabResultResponse if self._Bunq...
:rtype: core.BunqModel :raise: BunqException
def _docstring_parse(self, blocks): """Parses the XML from the specified blocks of docstrings.""" result = {} for block, docline, doclength, key in blocks: doctext = "<doc>{}</doc>".format(" ".join(block)) try: docs = ET.XML(doctext) docsta...
Parses the XML from the specified blocks of docstrings.
def calls(self): """ Provides access to call overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls :return: :class:`WebhookWebhooksCallProxy <contentful_management.webhook_webhooks_call_prox...
Provides access to call overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls :return: :class:`WebhookWebhooksCallProxy <contentful_management.webhook_webhooks_call_proxy.WebhookWebhooksCallProxy>` object. ...
def write(self, data): """ write data on the OUT endpoint associated to the HID interface """ report_size = self.packet_size if self.ep_out: report_size = self.ep_out.wMaxPacketSize for _ in range(report_size - len(data)): data.append(0) ...
write data on the OUT endpoint associated to the HID interface
def parse(file_or_string): """Parse a file-like object or string. Args: file_or_string (file, str): File-like object or string. Returns: ParseResults: instance of pyparsing parse results. """ from mysqlparse.grammar.sql_file import sql_file_syntax if hasattr(file_or_string, 'r...
Parse a file-like object or string. Args: file_or_string (file, str): File-like object or string. Returns: ParseResults: instance of pyparsing parse results.
def get_clean_url(self): """Retrieve the clean, full URL - including username/password.""" if self.needs_auth: self.prompt_auth() url = RepositoryURL(self.url.full_url) url.username = self.username url.password = self.password return url
Retrieve the clean, full URL - including username/password.
def make_action_list(self, item_list, **kwargs): ''' Generates a list of actions for sending to Elasticsearch ''' action_list = [] es_index = get2(kwargs, "es_index", self.es_index) action_type = kwargs.get("action_type","index") action_settings = {'_op_type': action_type,...
Generates a list of actions for sending to Elasticsearch
def predict_subsequences(self, sequence_dict, peptide_lengths=None): """Given a dictionary mapping unique keys to amino acid sequences, run MHC binding predictions on all candidate epitopes extracted from sequences and return a EpitopeCollection. Parameters ---------- fa...
Given a dictionary mapping unique keys to amino acid sequences, run MHC binding predictions on all candidate epitopes extracted from sequences and return a EpitopeCollection. Parameters ---------- fasta_dictionary : dict or string Mapping of protein identifiers to pr...
def _glslify(r): """Transform a string or a n-tuple to a valid GLSL expression.""" if isinstance(r, string_types): return r else: assert 2 <= len(r) <= 4 return 'vec{}({})'.format(len(r), ', '.join(map(str, r)))
Transform a string or a n-tuple to a valid GLSL expression.
def getFilenameSet(self): """ Returns a set of profiled file names. Note: "file name" is used loosely here. See python documentation for co_filename, linecache module and PEP302. It may not be a valid filesystem path. """ result = set(self.file_dict) # Ig...
Returns a set of profiled file names. Note: "file name" is used loosely here. See python documentation for co_filename, linecache module and PEP302. It may not be a valid filesystem path.
def print_list(extracted_list, file=None): """Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file.""" if file is None: file = sys.stderr for filename, lineno, name, line in extracted_list: _print(file, ' Fil...
Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file.
def flows(args): """ todo : add some example :param args: :return: """ def flow_if_not(fun): # t = type(fun) if isinstance(fun, iterator): return fun elif isinstance(fun, type) and 'itertools' in str(fun.__class__): return fun else: ...
todo : add some example :param args: :return:
def find_copies(input_dir, exclude_list): """ find files that are not templates and not in the exclude_list for copying from template to image """ copies = [] def copy_finder(copies, dirname): for obj in os.listdir(dirname): pathname = os.path.join(dirname, obj) ...
find files that are not templates and not in the exclude_list for copying from template to image
def user_topic_ids(user): """Retrieve the list of topics IDs a user has access to.""" if user.is_super_admin() or user.is_read_only_user(): query = sql.select([models.TOPICS]) else: query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic_id]) .select_from( ...
Retrieve the list of topics IDs a user has access to.
def solve_discrete_lyapunov(A, B, max_it=50, method="doubling"): r""" Computes the solution to the discrete lyapunov equation .. math:: AXA' - X + B = 0 :math:`X` is computed by using a doubling algorithm. In particular, we iterate to convergence on :math:`X_j` with the following recursio...
r""" Computes the solution to the discrete lyapunov equation .. math:: AXA' - X + B = 0 :math:`X` is computed by using a doubling algorithm. In particular, we iterate to convergence on :math:`X_j` with the following recursions for :math:`j = 1, 2, \dots` starting from :math:`X_0 = B`, :ma...
def get_widget(self, request): """ Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for filtering. """ return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget)
Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for filtering.
async def jsk_vc_join(self, ctx: commands.Context, *, destination: typing.Union[discord.VoiceChannel, discord.Member] = None): """ Joins a voice channel, or moves to it if already connected. Passing a voice channel uses that voice channel. Passing a member will...
Joins a voice channel, or moves to it if already connected. Passing a voice channel uses that voice channel. Passing a member will use that member's current voice channel. Passing nothing will use the author's voice channel.
def add_edge(self, fr, to): """ Add an edge to the graph. Multiple edges between the same vertices will quietly be ignored. N-partite graphs can be used to permit multiple edges by partitioning the graph into vertices and edges. :param fr: The name of the origin vertex. :param to: The n...
Add an edge to the graph. Multiple edges between the same vertices will quietly be ignored. N-partite graphs can be used to permit multiple edges by partitioning the graph into vertices and edges. :param fr: The name of the origin vertex. :param to: The name of the destination vertex. :...
def build_idx_set(branch_id, start_date): """ Builds a dictionary of keys based on the branch code """ code_set = branch_id.split("/") code_set.insert(3, "Rates") idx_set = { "sec": "/".join([code_set[0], code_set[1], "Sections"]), "mag": "/".join([code_set[0], code_set[1], code_...
Builds a dictionary of keys based on the branch code
def parse(self, valstr): # type: (bytes) -> None ''' Parse an El Torito section header from a string. Parameters: valstr - The string to parse. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('...
Parse an El Torito section header from a string. Parameters: valstr - The string to parse. Returns: Nothing.
def close_files(self): """Close all files with an activated disk flag.""" for name in self: if getattr(self, '_%s_diskflag' % name): file_ = getattr(self, '_%s_file' % name) file_.close()
Close all files with an activated disk flag.
def _update_counters(self, ti_status): """ Updates the counters per state of the tasks that were running. Can re-add to tasks to run in case required. :param ti_status: the internal status of the backfill job tasks :type ti_status: BackfillJob._DagRunTaskStatus """ ...
Updates the counters per state of the tasks that were running. Can re-add to tasks to run in case required. :param ti_status: the internal status of the backfill job tasks :type ti_status: BackfillJob._DagRunTaskStatus
def to_bson_voronoi_list2(self): """ Transforms the voronoi_list into a vlist + bson_nb_voro_list, that are BSON-encodable. :return: [vlist, bson_nb_voro_list], to be used in the as_dict method """ bson_nb_voro_list2 = [None] * len(self.voronoi_list2) for ivoro, voro in e...
Transforms the voronoi_list into a vlist + bson_nb_voro_list, that are BSON-encodable. :return: [vlist, bson_nb_voro_list], to be used in the as_dict method
def sync(self): """ synchronize self from Ariane server according its id (prioritary) or name :return: """ LOGGER.debug("Company.sync") params = None if self.id is not None: params = {'id': self.id} elif self.name is not None: param...
synchronize self from Ariane server according its id (prioritary) or name :return:
def to_language(locale): """ Turns a locale name (en_US) into a language name (en-us). Taken `from Django <http://bit.ly/1vWACbE>`_. """ p = locale.find('_') if p >= 0: return locale[:p].lower() + '-' + locale[p + 1:].lower() else: return locale.lower()
Turns a locale name (en_US) into a language name (en-us). Taken `from Django <http://bit.ly/1vWACbE>`_.
async def issueClaim(self, schemaId: ID, claimRequest: ClaimRequest, iA=None, i=None) -> (Claims, Dict[str, ClaimAttributeValues]): """ Issue a claim for the given user and schema. :param schemaId: The schema ID (reference to claim defin...
Issue a claim for the given user and schema. :param schemaId: The schema ID (reference to claim definition schema) :param claimRequest: A claim request containing prover ID and prover-generated values :param iA: accumulator ID :param i: claim's sequence number within acc...
def swallow_stdout(stream=None): """Divert stdout into the given stream >>> string = StringIO() >>> with swallow_stdout(string): ... print('hello') >>> assert string.getvalue().rstrip() == 'hello' """ saved = sys.stdout if stream is None: stream = StringIO() sys.stdout =...
Divert stdout into the given stream >>> string = StringIO() >>> with swallow_stdout(string): ... print('hello') >>> assert string.getvalue().rstrip() == 'hello'
def call_inputhook(self, input_is_ready_func): """ Call the inputhook. (Called by a prompt-toolkit eventloop.) """ self._input_is_ready = input_is_ready_func # Start thread that activates this pipe when there is input to process. def thread(): input_is_ready_...
Call the inputhook. (Called by a prompt-toolkit eventloop.)
def get_long_short_pos(positions): """ Determines the long and short allocations in a portfolio. Parameters ---------- positions : pd.DataFrame The positions that the strategy takes over time. Returns ------- df_long_short : pd.DataFrame Long and short allocations as a ...
Determines the long and short allocations in a portfolio. Parameters ---------- positions : pd.DataFrame The positions that the strategy takes over time. Returns ------- df_long_short : pd.DataFrame Long and short allocations as a decimal percentage of the total net liq...
def _decorate_urlconf(urlpatterns, decorator=require_auth, *args, **kwargs): '''Decorate all urlpatterns by specified decorator''' if isinstance(urlpatterns, (list, tuple)): for pattern in urlpatterns: if getattr(pattern, 'callback', None): pattern._callback = decorator( ...
Decorate all urlpatterns by specified decorator
def parse_allele_name(name, species_prefix=None): """Takes an allele name and splits it into four parts: 1) species prefix 2) gene name 3) allele family 4) allele code If species_prefix is provided, that is used instead of getting the species prefix from the name. (And in th...
Takes an allele name and splits it into four parts: 1) species prefix 2) gene name 3) allele family 4) allele code If species_prefix is provided, that is used instead of getting the species prefix from the name. (And in that case, a species prefix in the name will result in an e...
def create_replication_instance(ReplicationInstanceIdentifier=None, AllocatedStorage=None, ReplicationInstanceClass=None, VpcSecurityGroupIds=None, AvailabilityZone=None, ReplicationSubnetGroupIdentifier=None, PreferredMaintenanceWindow=None, MultiAZ=None, EngineVersion=None, AutoMinorVersionUpgrade=None, Tags=None, Km...
Creates the replication instance using the specified parameters. See also: AWS API Documentation :example: response = client.create_replication_instance( ReplicationInstanceIdentifier='string', AllocatedStorage=123, ReplicationInstanceClass='string', VpcSecurityGroupIds...
def main_loop(self, steps_per_epoch, starting_epoch, max_epoch): """ Run the main training loop. Args: steps_per_epoch, starting_epoch, max_epoch (int): """ with self.sess.as_default(): self.loop.config(steps_per_epoch, starting_epoch, max_epoch) ...
Run the main training loop. Args: steps_per_epoch, starting_epoch, max_epoch (int):
def list_nodes(conn=None, call=None): ''' Return a list of the VMs that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) if not conn: conn = get_conn() # pylint: disable=E0...
Return a list of the VMs that are on the provider
def solution_violations(solution, events, slots): """Take a solution and return a list of violated constraints Parameters ---------- solution: list or tuple a schedule in solution form events : list or tuple of resources.Event instances slots : list or tuple ...
Take a solution and return a list of violated constraints Parameters ---------- solution: list or tuple a schedule in solution form events : list or tuple of resources.Event instances slots : list or tuple of resources.Slot instances Returns ...
def get_args(): ''' Parse CLI args ''' parser = argparse.ArgumentParser(description='Process args') parser.Add_argument( '-H', '--host', required=True, action='store', help='Remote host to connect to' ) parser.add_argument( '-P', '--port', type...
Parse CLI args
def _mirror_groups(self): """ Mirrors the user's LDAP groups in the Django database and updates the user's membership. """ target_group_names = frozenset(self._get_groups().get_group_names()) current_group_names = frozenset( self._user.groups.values_list("name...
Mirrors the user's LDAP groups in the Django database and updates the user's membership.
def query_item(self, key, abis): """Query items based on system call number or name.""" try: key = int(key) field = 'number' except ValueError: try: key = int(key, 16) field = 'number' except ValueError: ...
Query items based on system call number or name.
def _set_extensions(self): """ Sets common named extensions to private attributes and creates a list of critical extensions """ self._critical_extensions = set() for extension in self['single_extensions']: name = extension['extn_id'].native attri...
Sets common named extensions to private attributes and creates a list of critical extensions
def touch_member(config, dcs): ''' Rip-off of the ha.touch_member without inter-class dependencies ''' p = Postgresql(config['postgresql']) p.set_state('running') p.set_role('master') def restapi_connection_string(config): protocol = 'https' if config.get('certfile') else 'http' con...
Rip-off of the ha.touch_member without inter-class dependencies
def _get_event_source_obj(awsclient, evt_source): """ Given awsclient, event_source dictionary item create an event_source object of the appropriate event type to schedule this event, and return the object. """ event_source_map = { 'dynamodb': event_source.dynamodb_stream.DynamoDBStreamE...
Given awsclient, event_source dictionary item create an event_source object of the appropriate event type to schedule this event, and return the object.
def run_analysis(self, argv): """Run this analysis""" args = self._parser.parse_args(argv) obs = BinnedAnalysis.BinnedObs(irfs=args.irfs, expCube=args.expcube, srcMaps=args.srcmaps, ...
Run this analysis
def naturalsortkey(s): """Natural sort order""" return [int(part) if part.isdigit() else part for part in re.split('([0-9]+)', s)]
Natural sort order
def view_surface_app_activity(self) -> str: '''Get package with activity of applications that are running in the foreground.''' output, error = self._execute( '-s', self.device_sn, 'shell', 'dumpsys', 'window', 'w') return re.findall(r"name=([a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)", output)
Get package with activity of applications that are running in the foreground.
def get(self, path): # pylint: disable=W0221 """Renders a GET request, by showing this nodes stats and children.""" path = path or '' path = path.lstrip('/') parts = path.split('/') if not parts[0]: parts = parts[1:] statDict = util.lookup(scales.getStats(), parts) if statDict is None...
Renders a GET request, by showing this nodes stats and children.
def ip_allocate(self, public=False): """ Allocates a new :any:`IPAddress` for this Instance. Additional public IPs require justification, and you may need to open a :any:`SupportTicket` before you can add one. You may only have, at most, one private IP per Instance. :p...
Allocates a new :any:`IPAddress` for this Instance. Additional public IPs require justification, and you may need to open a :any:`SupportTicket` before you can add one. You may only have, at most, one private IP per Instance. :param public: If the new IP should be public or private. ...
def iterator_chain(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: """This successively appends each element of an array to a single list of values. This takes a list of values and puts all the values generated for each element in the list into a single list of values. It uses the :func:`it...
This successively appends each element of an array to a single list of values. This takes a list of values and puts all the values generated for each element in the list into a single list of values. It uses the :func:`itertools.chain` function to achieve this. This function is particularly useful for spec...
def get_exe_path(cls): """ Return the full path to the executable. """ return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + ".exe"))
Return the full path to the executable.
def update_vm(vm_ref, vm_config_spec): ''' Updates the virtual machine configuration with the given object vm_ref Virtual machine managed object reference vm_config_spec Virtual machine config spec object to update ''' vm_name = get_managed_object_name(vm_ref) log.trace('Up...
Updates the virtual machine configuration with the given object vm_ref Virtual machine managed object reference vm_config_spec Virtual machine config spec object to update
def get_subhash(hash): """Get a second hash based on napiprojekt's hash. :param str hash: napiprojekt's hash. :return: the subhash. :rtype: str """ idx = [0xe, 0x3, 0x6, 0x8, 0x2] mul = [2, 2, 5, 4, 3] add = [0, 0xd, 0x10, 0xb, 0x5] b = [] for i in range(len(idx)): a =...
Get a second hash based on napiprojekt's hash. :param str hash: napiprojekt's hash. :return: the subhash. :rtype: str
def _apply_policy_config(policy_spec, policy_dict): '''Applies a policy dictionary to a policy spec''' log.trace('policy_dict = %s', policy_dict) if policy_dict.get('name'): policy_spec.name = policy_dict['name'] if policy_dict.get('description'): policy_spec.description = policy_dict['d...
Applies a policy dictionary to a policy spec
def best_model(self): """Rebuilds the top scoring model from an optimisation. Returns ------- model: AMPAL Returns an AMPAL model of the top scoring parameters. Raises ------ NameError: Raises a name error if the optimiser has not been ru...
Rebuilds the top scoring model from an optimisation. Returns ------- model: AMPAL Returns an AMPAL model of the top scoring parameters. Raises ------ NameError: Raises a name error if the optimiser has not been run.
def _calculate_values(self, tree, bar_d): """Calculate values for drawing bars of non-leafs in ``tree`` Recurses through ``tree``, replaces ``dict``s with ``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use the ``BarDescriptor``s to draw the tree """ if a...
Calculate values for drawing bars of non-leafs in ``tree`` Recurses through ``tree``, replaces ``dict``s with ``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use the ``BarDescriptor``s to draw the tree
def can_handle(self, data): r""" >>> e = Entry('http://www.github.com/?bar=foo&foobar', Entry.GET, (Response(b'<html/>'),)) >>> e.can_handle(b'GET /?bar=foo HTTP/1.1\r\nHost: github.com\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUser-Agent: python-requests/2.7.0 CPython/3.4.3...
r""" >>> e = Entry('http://www.github.com/?bar=foo&foobar', Entry.GET, (Response(b'<html/>'),)) >>> e.can_handle(b'GET /?bar=foo HTTP/1.1\r\nHost: github.com\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUser-Agent: python-requests/2.7.0 CPython/3.4.3 Linux/3.19.0-16-generic\r\nAccept: ...
def fade(self, fade_in_len=0.0, fade_out_len=0.0, fade_shape='q'): '''Add a fade in and/or fade out to an audio file. Default fade shape is 1/4 sine wave. Parameters ---------- fade_in_len : float, default=0.0 Length of fade-in (seconds). If fade_in_len = 0, ...
Add a fade in and/or fade out to an audio file. Default fade shape is 1/4 sine wave. Parameters ---------- fade_in_len : float, default=0.0 Length of fade-in (seconds). If fade_in_len = 0, no fade in is applied. fade_out_len : float, defaut=0.0 ...
def get_align(text): "Return (halign, valign, angle) of the <text>." (x1, x2, h, v, a) = unaligned_get_dimension(text) return (h, v, a)
Return (halign, valign, angle) of the <text>.