content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import logging
def split_dataframe_by_column(df, column):
"""
Purpose:
Split dataframe into multipel dataframes based on uniqueness
of columns passed in. The dataframe is then split into smaller
dataframes, one for each value of the variable.
Args:
d... | 3983c7270032f6a6bc8f6963f0da1ffada139216 | 288,334 |
def standard_codec_name(name: str) -> str:
"""
Map a codec name to the preferred standardized version.
The preferred names were taken from this list published by IANA:
U{http://www.iana.org/assignments/character-sets/character-sets.xhtml}
@param name:
Text encoding name, in lower case.
... | e9f30c9cb9da065f300900923e9b9ce5bac255e9 | 70,801 |
def normalize_disp(dataset_name):
"""Function that specifies if disparity should be normalized"""
return dataset_name in ["forward_facing"] | b97141606ad7efa32501d6ad6dd2e97fde791a91 | 410,008 |
def has_same_pattern(ruler_intervals1, ruler_intervals2):
"""
Check whether the give two ruler interval lists have the same pattern
Args:
ruler_intervals1: a list of ruler-intervals
ruler_intervals2: a list of ruler-intervals
Returns:
True or False
"""
if len(ruler_inter... | 8cc9aba474347b4e4493a3c44dc204d9af0354b4 | 199,294 |
def tlv_file_xml(tlv_data_xml, tmp_path):
"""Return the path to an XML file containing the test tree."""
path = tmp_path / "expected.xml"
path.write_bytes(tlv_data_xml)
return path | ef01ff58cf3afe7cd08eec98689c69b24c308b20 | 173,382 |
import random
import string
def random_alphanumeric(length=5, upper_case=False):
"""Generate a random alphanumeric string of given length
:param length: the size of the string
:param upper_case: whether to return the upper case string
"""
if upper_case:
return ''.join(random.choice(
... | d9072421639d629516911b72b451905d08063cc9 | 625,247 |
def csc_cumsum_i(p, c, n):
"""
p [0..n] = cumulative sum of c [0..n-1], and then copy p [0..n-1] into c
@param p: size n+1, cumulative sum of c
@param c: size n, overwritten with p [0..n-1] on output
@param n: length of c
@return: sum (c), null on error
"""
nz = 0
nz2 = 0.0
for... | ab567b6b357fc7e5e1b0a961b9b66d88487a0e7f | 697,125 |
def sent_length(sentence):
""" Returns sentence length without spaces. """
return sum(1 for c in sentence if c != ' ') | cde1e2e93e99a9c97d68a514b0fd31841de46d04 | 518,256 |
def bounding_boxes_xyxy2xywh(bbox_list):
"""
Transform bounding boxes coordinates.
:param bbox_list: list of coordinates as: [[xmin, ymin, xmax, ymax], [xmin, ymin, xmax, ymax]]
:return: list of coordinates as: [[xmin, ymin, width, height], [xmin, ymin, width, height]]
"""
new_coordinates = []
... | da55bf46bc65bffb999ab7de9ddaedb333718f53 | 100,532 |
def filter_polygons(state, header):
"""
Removes any non-polygon sources from the state file.
We are only interested in parsing parcel data, which is
marked as Polygon in the state file.
"""
filtered_state = []
for source in state:
if 'Polygon' in source[header.index('geometry type'... | d100e6a4e87dccdc42c7217dc1e793e4353237e2 | 7,081 |
def _get_zone(gcdns, zone_name):
"""Gets the zone object for a given domain name."""
# To create a zone, we need to supply a zone name. However, to delete a
# zone, we need to supply a zone ID. Zone ID's are often based on zone
# names, but that's not guaranteed, so we'll iterate through the list of
... | 20d746cbf8caa3f55e39856862868ed0c0d7aa31 | 533,809 |
from typing import List
from typing import Any
def getListDifference(listOne: List[Any], listTwo: List[Any]) -> List[Any]:
""" Return difference (items that are unique just to a one of given lists)
of a given lists.
Note:
Operation does not necessary maintain items order!
Args:
listO... | 5839988761a8f242828c8526d75e2b7ea8aea2f3 | 37,114 |
import click
def routes_file_option(help_text=None):
"""Option for providing a routes file instead of pulling from content."""
if help_text is None:
help_text = 'Use routes file to load routes instead of loading from files.'
def _decorator(func):
return click.option(
'--routes... | 8aaf1e916e5101f6427a2dbb35c9d9077ac50138 | 366,277 |
def _convert_float(value):
"""Convert an "exact" value to a ``float``.
Also works recursively if ``value`` is a list.
Assumes a value is one of the following:
* :data:`None`
* an integer
* a string in C "%a" hex format for an IEEE-754 double precision number
* a string fraction of the for... | 7896c97dafd577b6eefec452f5983c8c06c5f831 | 682,086 |
import time
def annotate_heatmap(im, # the AxesImage to be labeled
# a 2D numpy array of shape (N, M) containing the standard deviations to be used to annotate
# the heatmap
std,
# a 2D python array containing Boolean values indicati... | dc85f08ecdecb49c4f8b170ce331117f677f5075 | 98,932 |
def add_terminating_slash_to_url(url):
"""
adds terminating slash if necessary to main input URL
"""
if url[-1] != '/':
url += '/'
return url | 3f4e871891ddc3930e6b40238616038fee086bef | 349,954 |
def streamPrint(token: str = '', saveToken: str = '', printToken: bool = True):
"""
Helper function to take a token candidate, save destination, and print if requested.
Args:
token: New string to append.
saveToken: Save token string stream.
printToken:
Returns: appended string w... | b30d57e458f407cd6642f443a97774acbada3d92 | 542,744 |
def is_start_main_block(inputstring):
"""Check if line is the first line of the main block of data"""
return inputstring.startswith("Location: ") or inputstring.startswith('Site Number: ') | 480cf3cab6b0a3c569960d85f1cef92df300875c | 157,347 |
def fillout(template, adict):
"""returns copy of template filled out per adict
applies str.replace for every entry in adict
"""
rval = template[:]
for key in adict:
rval = rval.replace(key, adict[key])
return rval | b06551896f2cd3eafbe75fbfa6ab7885fbd34813 | 468,862 |
def booleanize_list(vals, null_vals=['no', 'none', 'na', 'n/a', '']):
"""Return a list of true/false from values."""
out = []
for val in vals:
val = val.strip().lower()
out.append(val and val not in null_vals)
return out | 296026dd59731a593a1a47704de73237d35af835 | 217,438 |
def is_die_attr_ref(attr):
"""
Returns True if the DIE attribute is a reference.
"""
return bool(attr.form in ('DW_FORM_ref1', 'DW_FORM_ref2',
'DW_FORM_ref4', 'DW_FORM_ref8',
'DW_FORM_ref')) | f00ee94396e66f2a3d81648698e29d6d3fe2885a | 212,867 |
def calc_subrange(range_max, sub_amount, weight):
"""
return the start and stop points that are sub_amount distance apart and
contain weight, without going outside the provided range
"""
if weight > range_max or sub_amount > range_max:
raise ValueError("sub_amount and weight must be less tha... | e0c020b32a0b73f109e843df1a9eccbe805cc252 | 535,574 |
from typing import Tuple
from typing import List
def _resolve_dim(slicer_index: Tuple, slicer_dim: List) -> List:
""" Extracts new dim after applying slicing index and maps it back to the original index list. """
new_slicer_dim = []
reduced_mask = []
for _, curr_idx in enumerate(slicer_index):
... | 5535fadbf29fabf8343af44e5daf16d1cfec36e2 | 495,481 |
import re
def curlify(content: str) -> str:
"""
Adds a pair of curly braces to the content. If the content already contains curly brackets, nothing will happen.
Example:
- curlify("Hello") returns "{Hello}".
- curlify("{Hello}") returns "{Hello}".
"""
curlify_pattern = re.compile(r'^{.*}$... | a45b6805eb3250f74fea913478d93f49e09b12cf | 116,029 |
import re
def text_reformat(text):
"""lowercase without punctuation"""
return re.sub(r'[^\w\s]', '', text.lower()) | 60f87486f65ddaf17919cf3ddbc72923597ddb08 | 96,812 |
import asyncio
import random
async def task_coro(pid):
"""Coroutine non-deterministic task"""
await asyncio.sleep(random.randint(0, 2) * 0.1)
print('Task %s done' % pid)
return random.choice([True, False, False, False, False, False, False, False, False, False, False, False]) | f88861797c5d36608b7d2ff7a4ccf79e64132062 | 620,779 |
def items_in_this_page(ls_resp, mode=None):
"""
Returns a dictionary of data record and/or collections from the given
listing response from DataFed
Parameters
----------
ls_resp : protobuf message
Message containing the listing reply
mode : str, optional
Set to "d" to only g... | 24241b2acf1bf20a47c0c69263209df6424dcfa9 | 125,363 |
def wrap_to_180(lon):
"""Wrapps longitude to -180 to 180 degrees."""
lon[lon>180] -= 360.
return lon | f1b8e9ac40e35a39b88afffb51de79a12df11c50 | 372,930 |
def get_command_help_messsage(command: str) -> str:
"""
Get the help message for a command.
Parameters
----------
command : str
Name of the command.
Returns
-------
str
Command's help message.
"""
return f'Show {command} command help message.' | 246e645d28569c346d08d1e2470d5db5c7ea40cc | 501,771 |
def find_attribute(rcv, xpath, attribute_name):
"""Find an attribute in the RCV record which can have either zero or one occurrence. Return a textual representation
of the attribute, including special representations for the case of zero or multiple, constructed using the
attribute_name parameter."""
a... | bb1dc226b1489fb8f5534770fa3dda2748c65d6f | 243,418 |
from typing import Optional
def prepare_error_message(message: str, error_context: Optional[str] = None) -> str:
"""
If `error_context` is not None prepend that to error message.
"""
if error_context is not None:
return error_context + ": " + message
else:
return message | ea95d40797fcc431412990706d5c098a07986156 | 5,521 |
def is_matrix(A):
"""Checks if an array is a matrix
Args:
A (jax.numpy.ndarray): A JAX array
Returns:
bool: True if the array is a matrix, False otherwise.
"""
return A.ndim == 2 | 114cd7a8c08b842e5bd85495e1c764f229f421e8 | 375,677 |
def group(text, size):
"""Group ``text`` into blocks of ``size``.
Example:
>>> group("test", 2)
['te', 'st']
Args:
text (str): text to separate
size (int): size of groups to split the text into
Returns:
List of n-sized groups of text
Raises:
ValueE... | 55e8cc79de23651b764648a655d41220253f90b8 | 574,364 |
from typing import List
import glob
def get_l10n_files() -> List[str]:
"""取得所有翻譯相關檔案列表,包括.pot .po .mo。
Returns:
List[str]: 翻譯相關檔案列表,包括.pot .po .mo。
"""
po_parser = 'asaloader/locale/*/LC_MESSAGES/asaloader.po'
pot_file = 'asaloader/locale/asaloader.pot'
po_files = glob.glob(po_parser)... | a783679261e7c9bd617728946d01a440b51cfb6a | 703,302 |
from typing import List
def close_gap_to_1(prev_vals: List[float], fraction: float) -> float:
"""
Reduce the difference between the last value and one (full mobility) according to the "fraction" request.
"""
prev_val = prev_vals[-1]
return (1.0 - prev_val) * fraction + prev_val | ba597fe3df369d3a4072e8765d12ae22d0cd9557 | 419,252 |
import time
import re
def get_time(string):
""" Convert GitHub timestamp to epoch """
return time.mktime(
time.strptime(re.sub(r"Z", "", str(string)), "%Y-%m-%dT%H:%M:%S")
) | 007790eb7429ef534e06ef4de6753878107c565f | 209,505 |
import re
def _check_for_run_information(sample_name):
"""
Helper function to try and find run ID information of the form RunXX_YY
"""
m = re.match('^Run\d+_\d+$', sample_name)
if m is not None:
return True
else:
return False | 1ddf51cc723b7831912952c1aacf4095dbcb9d9a | 94,025 |
def create_url(hostname, port=None, isSecure=False):
"""
Create a RawSocket URL from components.
:param hostname: RawSocket server hostname (for TCP/IP sockets) or
filesystem path (for Unix domain sockets).
:type hostname: str
:param port: For TCP/IP sockets, RawSocket service port or ``No... | 66db7e468649ab89f3795a1ed71dc5f05ce9365b | 380,588 |
def _lag_observations(observations, lag, stride=1):
""" Create new trajectories that are subsampled at lag but shifted
Given a trajectory (s0, s1, s2, s3, s4, ...) and lag 3, this function will generate 3 trajectories
(s0, s3, s6, ...), (s1, s4, s7, ...) and (s2, s5, s8, ...). Use this function in order to... | 65537ed7e19eaa28750cfaea1649d9de73e69678 | 169,265 |
def get_play_mode(instruction_set):
"""
Get the play_mode, type of execution arrangement.
:param instruction_set: json object
:return: play_mode value
"""
result = instruction_set.get("play_mode")
if result is None:
raise ValueError("Play mode not found in instruction_set data.")
... | 6393c035716f436158f952143b362ac220c216ee | 324,290 |
def expand_id_map(id_map, all_ids):
""" Ensures all ids within all_ids are included as keys in the mapping """
unmapped_ids = list(set(all_ids).difference(id_map.keys()))
for i in unmapped_ids:
id_map[i] = i
return id_map | 10e80cc2d3a84de745bc03f09f56c197b5bab13a | 615,931 |
def css_rgb(color, a=False):
"""Get a CSS `rgb` or `rgba` string from a `QtGui.QColor`."""
return ("rgba({}, {}, {}, {})" if a else "rgb({}, {}, {})").format(*color.getRgb()) | f3f15c2c5fdb7317f679cc080b4f0c6fb343f45a | 665,509 |
from typing import Any
def create_property(attr: str, default: Any, type_annotation: type) -> property:
"""Return a property descriptor given config attribute."""
def fget(self) -> Any:
if attr in self._env_overrides:
return self._env_overrides[attr]
if attr in self._config:
... | d7359b49a666e8826797d297e6642bd0736a0191 | 654,030 |
def is_thm_included(thm, splits, library_tags):
"""Decides whether the theorem is included in the selection.
This function can be used for filtering for theorems belonging to
the allowed splits and library tags.
Args:
thm: Theorem object to be decided for inclusion.
splits: Of type List[proof_assistan... | 621e789ae2a254f727f591ec75a0b78a1130aaa0 | 309,638 |
def interface_r_cos(polarization, n_i, n_f, cosTh_i, cosTh_f):
"""
reflection amplitude (from Fresnel equations)
polarization is either "s" or "p" for polarization
n_i, n_f are (complex) refractive index for incident and final
th_i, th_f are (complex) propegation angle for incident and final
... | fd7da775fbba9c411ff2a461aa8d41c673fe8584 | 668,587 |
def term_frequency(text, word):
"""Takes in a text (list of strings) and calculates
TF(t) = (number of times term appears in text) / (total number of terms in a text)"""
total_words = len(text)
word_in_text = text.count(word)
try:
return float(word_in_text) / float(total_words)
except Ze... | 4d773a13e5b3698bdbb8ea280a8997c6d2eab530 | 281,391 |
import time
def gen_test_packet(sender="server", size=3000):
"""
Generates a simple test packet, containing a decent amount of data,
as well as the timestamp of generation and the sender.
"""
# Packet containing 'size' floats
data = [0.0 if i % 2 == 0 else 1.0 for i in range(size)]
timesta... | f51651e755f8579158a485f0a2a56ba3791eaec1 | 284,482 |
import csv
def write_colocated_gates(coloc_gates, fname):
"""
Writes the position of gates colocated with two radars
Parameters
----------
coloc_gates : dict
dictionary containing the colocated gates parameters
fname : str
file name where to store the data
Returns
---... | aaf7421036f39c898a3ee9e7c166ce24cdda6b4e | 670,851 |
def aslist(item):
"""
aslist wraps a single value in a list, or just returns the list
"""
return item if type(item) == list else [item] | e9b3a9f189f74243d713e896dfbbd002e78abada | 27,536 |
def add_user_tag(func):
""" Add the attribute __user_tag__ to func.
:params func: a non-builtin function to decorate
:type func: function
:rtype: function
"""
func.__user_tag__ = "YiranChe"
return func | da940697113afd7cba2b5ef7de822546be6bf925 | 471,176 |
import re
def remove_tag(string):
"""
Most of web scrapped data contains html tags.
It can be removed from below re script
Parameters
----------
text: str
Text selected to apply transformation.
Examples:
---------
```python
sentence="Markdown sentences can use... | 284f07aed99a403d1a99efce6e37b5564e9f8401 | 108,997 |
def detailed_event_metrics_to_list(detailed_event_results):
""" Converting detailed event metric results to a list (position of each item is fixed)
Argument:
detailed_event_results (dictionary): as provided by the 3rd item in the results of eval_events function
Returns:
list: Item order: 0... | b6baeb8548d035982a2bd5bab88deb915d9f99cc | 368,502 |
def inRange(v1, minVal = 0, maxVal = 1):
"""
Check if every value in v1 is in the range (minVal, maxVal)
"""
for v in v1:
if v < minVal or v > maxVal:
return False
return True | c166f7d9aaa94988eb4e245cb41c34b44ace86cf | 572,902 |
import random
def generate_mac_address(type="XEN"):
"""
<comment-ja>
ランダムなMACアドレスを生成する
(XENなら、00:16:3e:00:00:00 から 00:16:3e:7f:ff:ff の範囲)
(KVMなら、52:54:00:00:00:00 から 52:54:00:ff:ff:ff の範囲)
@param type: ハイパーバイザのタイプ (XEN or KVM)
@return: MACアドレス
</comment-ja>
<comment-en>
Genera... | 573a1568c2705eb0e108104f3b9e0e2f484770d2 | 330,727 |
def explore_or_choose_direction(current_village_number):
"""Ask the user whether he/she would like to explore the current village or move to a different village."""
while True:
print("")
print("Would you like to explore village {} or move to a different village? Enter explore or move.".format(current_v... | ee0f75b3b245be4245427981da249f13554353cd | 289,533 |
def getNumBlocksToMine(chanBlocks):
"""
get number blocks to mine to fund the channels including extra 100 to spend the blocks
:param chanBlocks: the outputs of coinbase txs put in blocks
:return: int
"""
cbs = 0
for block in chanBlocks:
cbs += len(block)
blocksToMine = cbs + 100... | 21d4c3d5f5d1c497b21e135a3bd5cf53144efe58 | 248,581 |
from datetime import datetime
def timestamp2isoformat(timestamp):
"""
This function converts a timestamp (float) to a string in the
ISO 8061 date format
"""
date = datetime.fromtimestamp(timestamp)
return date.isoformat() | e1c6d68821c0986b658328dc32ea70d7f9c58919 | 453,615 |
def maybe(f, default):
"""Evaluate f and return the value; return default on error."""
try:
return f()
except: # noqa: E722
return default | 0d23ed11df5ded9e2f7f122c64f4bc4c7fab3d74 | 533,539 |
import importlib
def construct_instance(fq_name, kwargs):
"""
Constructs an instance of the class from the fully qualified name expanding
the kwargs during construction. e.g. fq_name(**kwargs)
:param fq_name: The fully qualified class name.
:param kwargs: Keyword args (a dict) to be expanded.
... | 2007446ea66e321b35824153b6b304dad53dac6f | 460,646 |
def alpha_numeric_filter(string):
"""Takes a string and returns a filtered string with only alpha-numeric characters"""
filtered = ""
for char in string:
if char.isalnum() or char == ' ':
filtered += char
if char == '\n':
continue
return filtered | e9bd4337489203024fb1052cd3f30e7657d709e1 | 203,365 |
def get_readme_description(head_string: str) -> str:
"""
Parse the head of README and get description.
:param head_string: A string containing title, description and images.
:return: Stripped description string.
"""
# Split title section and rule out empty lines.
parts = list(filter(bool, h... | a37d01565461b028874ca725f0473f87470b8816 | 590,617 |
def linear_annuity_mapping_fprime(underlying, alpha0, alpha1):
"""linear_annuity_mapping_fprime
first derivative of linear annuity mapping function.
See :py:func:`linear_annuity_mapping_func`.
The function calculates following formula:
.. math::
\\alpha^{\prime}(S) := \\alpha_{0.}
wher... | ff57723cad7ade65644744dc30abb6db5c1e6b95 | 697,518 |
import hashlib
def generage_sha1(text: str) -> str:
"""Generate a sha1 hash string
Args:
text (str): Text to generate hash
Returns:
str: sha1 hash
"""
hash_object = hashlib.sha1(text.encode('utf-8'))
hash_str = hash_object.hexdigest()
return hash_str | 3df62f7607db571b45e82d18e756861c84699513 | 689,973 |
def validate_port(confvar):
"""
Validate that the value of confvar is between [0, 65535].
Returns [(confvar, error_msg)] or []
"""
port_val = confvar.get()
error_res = [(confvar, 'Port should be an integer between 0 and 65535 (inclusive).')]
try:
port = int(port_val)
if port < 0 or port > 65535:
... | a200fd85f417c7e9a958a97f02c6aa8b6ed381bf | 517,881 |
import json
def to_json_string(my_obj):
"""
Function that returns the JSON representation of an object.
Args:
my_obj (str): Surce object
Returns:
JSON representation.
"""
return json.dumps(my_obj) | 18e51b0ae242ef99ec3831a915b9a1693e25281a | 621,817 |
def event_blocknumbers(events):
"""given a list of events returns the block numbers containing events"""
return {ev.blocknumber for ev in events} | 442432b1c2b795d3373a17925b79a14a44469480 | 254,999 |
def perimeter_square(length):
"""
.. math::
perimeter = 4 * length
Parameters
----------
length: float
length of one side of a square
Returns
-------
perimeter: float
perimeter of the square
"""
return length * 4 | 07b8eefed384636a254c1ca84d861bebf80782ec | 651,751 |
import torch
def demean(tensor, dim=-1):
"""
Demeans the input tensor along the specified dimension(s)
Parameters
----------
tensor : Tensor
the input tensor
dim : int or list or tuple (optional)
the dimension(s) along the operation is performed (default is -1)
Returns
... | dcf9a40ca9895f76966970fd970ace68750e90a9 | 184,233 |
import six
def bytes_increment(b):
"""Increment and truncate a byte string (for sorting purposes)
This functions returns the shortest string that sorts after the given
string when compared using regular string comparison semantics.
This function increments the last byte that is smaller than ``0xFF``, ... | 197031de601f9754bb44648ed5bc2198096d827e | 219,876 |
def goal_error(name):
"""Adds a string which occurs in the
output of coq if a goal is admitted.
Arguments:
- `name`: a goal name
"""
return "*** [ {0!s}".format(name) | 85d2fc3ece04e4f43a60736acc388437d65a5d68 | 583,011 |
def label2yolobox(labels, info_img, maxsize, lrflip):
"""
Transform coco labels to yolo box labels
Args:
labels (numpy.ndarray): label data whose shape is :math:`(N, 5)`.
Each label consists of [class, x, y, w, h] where \
class (float): class index.
x, y, ... | 1eb05502c22e7ad28fbac05a8131a6f16b0efa5f | 566,361 |
def parse_extension(extension):
"""Parse a single extension in to an extension token and a dict
of options.
"""
# Naive http header parser, works for current extensions
tokens = [token.strip() for token in extension.split(';')]
extension_token = tokens[0]
options = {}
for token in token... | 11b205ce3e304cfd697c53a06e554a07a615d3c0 | 320,130 |
def _ToWebSafeString(per_result, internal_cursor):
"""Returns the web safe string combining per_result with internal cursor."""
return str(per_result) + ':' + internal_cursor | 61f8465d9e6e0634c4d99a402cbfc011a9bac717 | 286,364 |
def get_binary(community):
"""Binary variables for community."""
return [f"y_{org_id}" for org_id in community.organisms.keys()] | 4f92ac9c80dcf3125f9825aacbf304e6fb689605 | 608,952 |
def initialize_bins(start, end, width):
"""
Generate a list of interval borders.
@param start: The left border of the first interval.
@param end: The left border of the last interval.
@param width: The width of each interval.
@return: The list of interval borders.
"""
return list(range(s... | 6118ce31574dec47755462a2ac190e51e15a4bcf | 207,126 |
from pathlib import Path
def get_label(f):
"""
f = '../celeba_man/fake/9992_split.jpg'
get_label(f) -> 'fake'
"""
return Path(f).parts[-2] | a2f70e1a25022c8a6975f2f48f811ae34b51314c | 157,297 |
def _mdtraj_summary(wizard, context, result):
"""Standard summary of MDTraj CVs: function, atom, topology"""
cv = result
func = cv.func
topology = cv.topology
indices = list(cv.kwargs.values())[0]
atoms_str = " ".join([str(topology.mdtraj.atom(i)) for i in indices[0]])
summary = (f" Functio... | b5bfdfc39dd8f62e6046397438a05e2ed069bffb | 149,387 |
def ovs_version_str(host):
""" Retrieve OVS version and return it as a string """
mask_cmd = None
ovs_ver_cmd = "ovs-vsctl get Open_vSwitch . ovs_version"
with host.sudo():
if not host.exists("ovs-vsctl"):
raise Exception("Unable to find ovs-vsctl in PATH")
mask_cmd = host.r... | 607ffbb2ab1099e86254a90d7ce36d4a9ae260ed | 13,822 |
def variant_display_name(variant):
"""Construct a display name for a variant."""
display_name = "{}: {}: {}".format(
variant["Product SKU"],
variant["Product Name"],
variant["Question|Answer"]
)
return display_name.strip() | 8ef91205873f87769e3a1169208fd7174a4e5346 | 107,828 |
def hello(friend_name):
""" Returns a greeting for a friend name
:param friend_name: Name of friend to greet
:type friend_name: str
:return: Greeting to friend
"""
return 'Hello, {}!'.format(friend_name) | 56c77f6e29f751bbc01b1e24addb517b673f0b75 | 251,558 |
def serialize_none(x):
"""Substitute None with its string representation."""
return str(x) if x is None else x | 4f983c98d4f669a07ae4f8b71c0eeb9abd1fec06 | 272,166 |
import pprint
def pretty_str(obj):
"""Wrapper for the pprint.pformat function that generates a formatted
string representation of the input object.
"""
return pprint.pformat(obj, indent=4, width=79) | a4efc6cdb55a776e29598ca227e187459c66d688 | 348,123 |
def ascii_symbol_to_integer(character):
"""Convert ascii symbol to integer."""
if(character == ' '):
return 0
elif(character == '+'):
return 1
elif(character == '#'):
return 2 | ec50241bd6c7ae8bfc9f0ebcdfd194e597f5e8a4 | 151,435 |
def min_npix(npix):
"""
Minimum npix criteria
Parameters
----------
npix : int
The minimum number of pixels in a leaf
"""
def result(structure, index=None, value=None):
return len(structure.values()) >= npix
return result | fc078cc37ecd10638bcb0d8c3abaaa2de63f5dd8 | 429,582 |
def nopat(operating_income, tax_rate):
"""
nopat = Net Operating Profit After Tax
"""
return operating_income * (1-(tax_rate/100)) | de002f10b5deebf22e6a53428bbef663df649783 | 647,760 |
def mergesort_reversed(list):
"""
A mergesort implementation. The only difference is that it sorts the input list in a REVERSED ORDER.
I.e. the elements are sorted in a DESCENDING order.
:param list:
:type list: list
:return: list sorted in descending order
:rtype: list
"""
def _me... | 3d6ba0cff8132f1e2b6deb9bced8ad35e3efeee9 | 447,340 |
def predict_cluster(x, centroids):
"""
Given a vector of dimension D and a matrix of centroids of dimension VxD,
return the id of the closest cluster
:params np.array x:
the data to assign
:params np.array centroids:
a matrix of cluster centroids
:returns int:
cluster as... | 3cbd582bd3a947e3d0a11ad05db1ca98547372e5 | 96,175 |
def get_id_pairs(track_list):
"""Create a list of (sid, eid) tuples from a list of tracks. Tracks without an eid will have an eid of None."""
return [(t["id"], t.get("playlistEntryId")) for t in track_list] | 8711a96d9c1367c2d5c151d6dc3d9be69b3aced6 | 136,604 |
def _is_audio_link(link):
"""Checks if a given link is an audio file"""
if "type" in link and link["type"][:5] == "audio":
return True
if link["href"].endswith(".mp3"):
return True
return False | 4551771b6e0b568c24d0c8e1234c4ffd086460e6 | 252,007 |
def weighted_average(items, weights):
"""
Returns the weighted average of a list of items.
Arguments:
items is a list of numbers.
weights is a list of numbers, whose sum is nonzero.
Each weight in weights corresponds to the item in items at the same index.
items and weights must be... | bd535be8d39bafb2598add9f858878c8f0726c3f | 265,616 |
import socket
def current_fqdn() -> str:
"""Returns fully-qualified domain main (FQDN) of current machine"""
return socket.getfqdn() | e74005b306db756907bf34ddf0ee0bb1e2bbd8e0 | 433,250 |
from typing import Any
def logging_filter_log_records_for_chat(record: Any) -> bool:
"""Filters log records suitable for interactive chat."""
return (
record.msg.startswith("decoded")
or record.msg.startswith(" ->")
or record.msg.startswith("Restoring parameters from")
) | fae587aa8a6985667a24429db618da0b93743882 | 614,044 |
def MultiplyList(myList):
"""
multiplying the numbers in list
input: list
output: returns the multiplication
of numbers in given list
"""
# Multiply elements one by one
result = 1
for x in myList:
result = result * x
return result | c852428ea3d34e780c50b7b58bb22083d4743ea4 | 338,879 |
def rename_entity_id(old_name):
"""
Given an entity_id, rename it to something else. Helpful if ids changed
during the course of history and you want to quickly merge the data. Beware
that no further adjustment is done, also no checks whether the referred
sensors are even compatible.
"""
ren... | c2461fda461392404694f7ac084a9f86a2b40c9f | 120,517 |
def getColName(col):
""" The column name is the concatination of the table's "abbr" and the column name.
If abbr doesn't exist, it's just the column name
"""
strAbbr = col.parentNode.parentNode.getAttribute('abbr')
if len(strAbbr) > 0:
return strAbbr + '_' + col.getAttribute('name')
... | d05b205665cff9e6859769edfd338fe97fdfa157 | 409,706 |
def get_method_name(name):
# type: (str) -> str
"""Get a method name from a fully qualified method name."""
pos = name.rfind('::')
if pos == -1:
return name
return name[pos + 2:] | d2e9c0865cac417f88fe8b4812ac629b3f0303e3 | 314,735 |
def _stringify(major: int, minor: int, micro: int = 0, releaselevel: str = 'final', serial: int = 0, **kwargs) -> str:
"""Stringifies a version number based on version info given. Follows :pep:`440`.
Releaselevel is the status of the given version, NOT the project itself.
All versions of an alpha or beta s... | e55d6a68260dcf153608ffc4db2eef7fab288cef | 210,251 |
from typing import Tuple
def egcd(a: int, b: int)->Tuple[int, int, int]:
"""Extended Euclidean algorithm to compute the gcd
Taken from https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
Returns:
A tuple (g, x, y) where a*x + b*y = gcd(x, y)"""
if a ... | 8fcc2bdd0e8de089cff912536cff273d8cec842a | 271,737 |
def is_iterable(obj) -> bool:
"""Whether the given object is iterable or not.
This is tested simply by invoking ``iter(obj)`` and returning ``False`` if
this operation raises a TypeError.
Args:
obj: The object to test
Returns:
bool: True if iterable, False else
"""
try:
... | 0be1d1e6c372465093bc4f12800a9727793542ee | 216,366 |
def compact_counts_to_100_shots(counts):
"""Compact counts to 100 shots
This helps to reduce animation generation time, and file size
Args:
counts (dict): job result counts, e.g. For 1024 shots: {'000': 510, '111': 514}
Returns:
dict: the compacted-counts, e.g. {'000': 51,... | dd5fdad65d67bb82c2c2bc3f1e084b5731d5b7c6 | 467,836 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.