content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import re
def str_find_all(str_input, match_val):
"""
Function returns indexes of all occurrences of matchVal inside of str_input
"""
return [m.start() for m in re.finditer(match_val, str_input)] | 7a41f874806b4bcdcbd8791cdcf6f4f8292d5dc0 | 223,215 |
def is_midday(this_t):
"""
Return true if this_t is "mid-day" in North America. "Mid-day" is
defined as between 15:00 and 23:00 UTC, which is 10:00 EST to
15:00 PST.
INPUTS
this_t: a datetime.datetime object
OUTPUTS
True or False
"""
return ((this_t.hour >= 15) and (this_t.hou... | 4fbe87ec65c3943d18d4b0ad7eb3b106f0b14ced | 306,210 |
def string_like(value, name, optional=False, options=None, lower=True):
"""
Check if object is string-like and raise if not
Parameters
----------
value : object
Value to verify.
name : str
Variable name for exceptions.
optional : bool
Flag indicating whether None is a... | 17c95e147684e0d0fc473f66c7e1e0597bec9111 | 465,856 |
from typing import Iterator
from typing import Sequence
def head_reader(
rows: Iterator[Sequence[str]]
) -> Iterator[Sequence[str]]:
"""Consumes three header rows and returns the iterator."""
r0 = next(rows)
r1 = next(rows)
r2 = next(rows)
assert set(r2) == {"x", "y"}, set(r2)
retu... | bfbc453cf57cae3d3b3f39e22db70a3eb5ddaeed | 247,071 |
def grouper(list_, n):
"""
Collect data into fixed-length chunks or blocks
Adapt from https://docs.python.org/3/library/itertools.html#itertools-recipes
>>> list(grouper('ABCDEF', 3))
[("A", "B", "C"), ("D", "E")]
"""
assert len(list_) % n == 0
args = [iter(list_)] * n
return zi... | f438a247b60597775bdaa4859de55d2cafb925d9 | 240,278 |
def set_active_editor(oDesign, editorname="3D Modeler"):
"""
Set the active editor.
Parameters
----------
oDesign : pywin32 COMObject
The HFSS design upon which to operate.
editorname : str
Name of the editor to set as active. As of this writing "3D Modeler"
is the... | 906cc753c5b6acb9e8e26dfa71986c4c41a4d6f6 | 135,807 |
from typing import List
from typing import Dict
def str_to_sql_dict(tables: List[str]) -> List[Dict]:
"""
Transforms a list of tables/procedures names into a list of dictionaries with keys schema and name
:param tables: list ot table names
:return: list of table dictionaries
"""
return [dic... | 03249755df54b86b288116b62fe3775ff044f303 | 231,005 |
import functools
def _register_style(style_list, cls=None, *, name=None):
"""Class decorator that stashes a class in a (style) dictionary."""
if cls is None:
return functools.partial(_register_style, style_list, name=name)
style_list[name or cls.__name__.lower()] = cls
return cls | e186f3e9cd54fbf9a8f3191b6ec7bc930fa8b4f8 | 519,431 |
from typing import Optional
from typing import List
def compact(array: Optional[List]) -> Optional[List]:
"""Compact an list by removing `None` elements. If the result is an empty list, return `None`
:param array: Inital list to compact
:type array: List
:return: Final compacted list or None
... | 20271464dd9b1c312be6bd12f7df40dfc10076d5 | 574,731 |
def split_str_to_list(input_str, split_char=","):
"""Split a string into a list of elements.
Args:
input_str (str): The string to split
split_char (str, optional): The character to split the string by. Defaults
to ",".
Returns:
(list): The string split into a list
"... | 2b13868aed1869310a1398886f6777ddceb6c777 | 708,964 |
def returnListWithoutOutliers(data, outlierRange):
"""
An outlier is defiend as a datapoint not in [Q1 - 1.5*IQR*outlierRange, Q3 + 1.5*IQR*outlierRange],
where IQR is the interquartile range: Q3 - Q1
"""
data.sort()
dataPointsBefore = len(data)
Q1 = data[dataPointsBefore//4]
Q3... | 1c8dc965af7057dddeec7e44cd95f21702e5fd99 | 112,529 |
def validate(img):
""" validate correct numpy.ndarray shape for get_prediction function
- Input one arguments: image read as numpy.ndarray
- Output True/False if the array has shape (x, y, 3) """
if img.shape[2] == 3:
return True
else:
return False | 634ee537694bf045688d2dc91cc27bb00ad68cf0 | 383,377 |
import six
import base64
def nice64(src):
"""
Returns src base64-encoded and formatted nicely for our XML,
as Unicode.
"""
# If src is a Unicode string, we encode it as UTF8.
if isinstance(src, six.text_type):
src = src.encode('utf8')
return base64.b64encode(src).decode('utf8').rep... | 0e9c9861ef05e612c564bd535d6278a6410c5c2f | 435,190 |
def p_count(value):
"""
Jinja2 custom filter to use for Peewee query count
"""
return value.count() | 8958f3ab6b3bf9b2359ae4ef7628c4bd14c5c858 | 299,279 |
import re
def _collapse_impacted_interfaces(text):
"""Removes impacted interfaces details, leaving just the summary count."""
return re.sub(
r"^( *)([^ ]* impacted interfaces?):\n(?:^\1 .*\n)*",
r"\1\2\n",
text,
flags=re.MULTILINE) | 504bf7170ea4624d1703ff7ed25106a5bb671834 | 115,774 |
def area_triangle(base: float, height: float) -> float:
"""
Calculate the area of a triangle given the base and height.
>>> area_triangle(10, 10)
50.0
>>> area_triangle(-1, -2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
>>... | 33520e4457a027157886ab14f1822b1675b2fa92 | 22,726 |
def lpad(s, l):
""" add spaces to the beginning of s until it is length l """
s = str(s)
return " "*max(0, (l - len(s))) + s | f903e9beea4cbc43bd2453f9f768923b3e088a07 | 655,365 |
import string
def lstrip(s):
"""strip whitespace from the left hand side of a string, returning a tuple (string, number_of_chars_stripped) for S"""
num_stripped = 0
for i in s:
# for bytes
char = chr(i) if type(i) == int else i
if char in string.whitespace:
s = s[1:]
num_stripped += 1
else:
break
... | 5330e27709bbf5078396662c0978310bf2946e02 | 336,388 |
import re
def check_for_masked_bases(seq, max_masked=20):
"""Check sequence has runs of masked bases."""
return bool(re.search(r"[acgtnN]{" + str(max_masked) + "}", seq)) | 86a09d5e53068716b6a9e700f4e6829daa26c169 | 392,867 |
def node_access(G, node, degree=1, direction="backward"):
"""
Return the set of nodes which lead to "node" (direction = backaward)
or the set o nodes which can be accessed from "node" (direction = forward)
Parameters:
G - Networkx muldigraph
node - Node whose accessibility ... | e0fd2c6693480684b46dbad188efc36dd7a27fe7 | 266,528 |
def chunk(value, size=2):
""" size=2: 'abcdefg' -> ['ab', 'cd', 'ef', 'gh'] """
return [value[0 + i:size + i] for i in range(0, len(value), size)] | b4c32503074cf6d85f80a3ca046f348065bcbe0d | 129,241 |
import requests
def getHTML(url, needPretty=False):
""" 获取网页 HTML 返回字符串
Args:
url: str, 网页网址
needPretty: bool, 是否需要美化(开发或测试时可用)
Returns:
HTML 字符串
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
... | 49c2f5066bf52f97ed88c204e2ed3703f47df960 | 281,621 |
def tell_me_about(s):
"""Return a tuple containing the type of the input string and the input
string itself.
"""
return (type(s), s) | 5f3e30966a130d587f23fbb89b8db91e1b942bee | 179,864 |
def get_datastore_for_server(server):
"""
Given a server, return its datastore based on its first disk.
"""
root_disk = server.disks.first()
if root_disk:
return root_disk.cast().datastore
return None | d235dcf6e0f5e87133da378d6aef5288b139ce4b | 465,275 |
def build_pathnet_graph(p_inputs, p_labels, p_task_id, pathnet, training):
"""Builds a PathNet graph, returns input placeholders and output tensors.
Args:
p_inputs: (tf.placeholder) placeholder for the input image.
p_labels: (tf.placeholder) placeholder for the target labels.
p_task_id: (tf.placeholder... | c283ac433ea8ec8864b61c7943af8735c9da6045 | 657,905 |
def convert_value(value):
"""
None and boolean values are not accepted by the Transip API.
This method converts
- None and False to an empty string,
- True to 1
"""
if isinstance(value, bool):
return 1 if value else ''
if not value:
return ''
return value | 6c6a05df64c59185c610399dbe1d9dc9888e2086 | 274,770 |
import logging
import pickle
def _load_data_pickle(fname, kind="data"):
"""Load generic data in pickle format."""
logging.info('Loading %s and info from %s' % (kind, fname))
try:
with open(fname, 'rb') as fobj:
result = pickle.load(fobj)
return result
except Exception as e:... | 48da9c4abf9d84056e754c0fce84114ccf8368f5 | 434,625 |
def get_field_value_for_record(record_cls, record_pid, field_name):
"""Return the given field value for a given record PID."""
record = record_cls.get_record_by_pid(record_pid)
if not record or field_name not in record:
message = "{0} not found in record {1}".format(field_name, record_pid)
... | ff32fdd481a4c191f48ac95ac4c7a505e7ed61c8 | 214,743 |
def instance_group(group_type, instance_type, instance_count, name=None):
"""
Construct instance group
:param group_type: instance group type
:type group_type: ENUM {'Master', 'Core', 'Task'}
:param instance_type
:type instance_type: ENUM {'g.small', 'c.large', 'm.medium', 's.medium', 'c.2xlar... | b8f42f49a7cc5455cf57ce5c14d523fb85189b8f | 667,691 |
def delimit(delimiters, content):
"""
Surround `content` with the first and last characters of `delimiters`.
>>> delimit('[]', "foo")
[foo]
>>> delimit('""', "foo")
'"foo"'
"""
if len(delimiters) != 2:
raise ValueError(
"`delimiters` must be of length 2. Got %r" % de... | a393e2a8330c05d29855505fe679bfda4665500f | 651,266 |
import torch
def smooth_l1_loss_augmix(pred, target, beta=1.0):
"""Smooth L1 loss.
Args:
pred (torch.Tensor): The prediction.
target (torch.Tensor): The learning target of the prediction.
beta (float, optional): The threshold in the piecewise function.
Defaults to 1.0.
... | 1dd60e6199160567eb3c9520186898eaae057c72 | 516,470 |
def check_multi_single(filenames):
"""
Check if multiple or single file is chosen.
Args:
filenames (list): A list of all the filepaths or string of
filepath
Returns:
single (bool): Return whether it is a single file (True)
or multi... | b5019bc8c644c60ad862f5868a1cd1b807006ed7 | 380,033 |
import re
def StripComments(line):
"""Strips comments from a line and return None if the line is empty
or else the contents of line with leading and trailing spaces removed
and all other whitespace collapsed"""
commentIndex = line.find('//')
if commentIndex is -1:
commentIndex = len(line)
line... | bc0094efd57e44c56080ec6471f1f34c9d5eae60 | 303,914 |
def largest_number(seq_seq):
"""
Returns the largest number in the subsequences of the given
sequence of sequences. Returns None if there are NO numbers
in the subsequences.
For example, if the given argument is:
[(3, 1, 4),
(13, 10, 11, 7, 10),
[1, 2, 3, 4]]
then thi... | 5a2418e1f8ee0413e8306a04d3ee17a909b7b0c3 | 702,295 |
def error_message(e, message=None, cause=None):
"""
Formats exception message + cause
:param e:
:param message:
:param cause:
:return: formatted message, includes cause if any is set
"""
if message is None and cause is None:
return None
elif message is None:
return '%... | 8017f426f8d6b94bbed729e91b48aad8f36e9fad | 72,569 |
from typing import Iterable
from typing import Callable
from typing import Tuple
from typing import List
import itertools
def partition(items: Iterable, predicate: Callable) -> Tuple[List, List]:
"""
:param items: iterable of items to split
:param predicate: predicate to split by
:return: a tuple of l... | a00e28149254e9ccede3392397fae9c5ad87cede | 215,672 |
import copy
def badmatch(match, badfn):
"""Make a copy of the given matcher, replacing its bad method with the given
one.
"""
m = copy.copy(match)
m.bad = badfn
return m | f9937a4076ede88b25735a0b095e63d7082da620 | 75,889 |
def escape_attribute(value, encoding):
"""Escape an attribute value using the given encoding."""
if "&" in value:
value = value.replace("&", "&")
if "<" in value:
value = value.replace("<", "<")
if '"' in value:
value = value.replace('"', """)
return value.encode(... | 2a3ff495a5082e130b8a59af1bff82a4a4ca6430 | 628,768 |
from typing import List
import shlex
def _clean_command_arguments(*, args: str) -> List[str]:
"""Clean args from input for execution."""
return [shlex.quote(i) for i in shlex.split(args)] | 61f8cff69e2d7a6df0de6538cec48160f53f7576 | 422,439 |
import torch
def recoLossGaussian(predicted_x, x, gaussian_noise_std, data_std):
"""
Compute reconstruction loss for a Gaussian noise model.
This is essentially the MSE loss with a factor depending on the standard deviation.
Parameters
----------
predicted_x: Tensor
Predicted signal by... | 0ce87fb200ccd601356944199e9df41a857d30ed | 147,663 |
def prod(lst):
"""Computes the product of a list of numbers."""
p = 1.0
for i in lst:
p *= i
return p | 58e89b14dde96e52d9b8e445fd8cf912edc7c440 | 362,477 |
def _threat_intel_handler(options, config):
"""Configure Threat Intel from command line
Args:
options (argparse.Namespace): The parsed args passed from the CLI
config (CLIConfig): Loaded StreamAlert config
Returns:
bool: False if errors occurred, True otherwise
"""
config.a... | 2e2bec4a87271bd7f79c9d1fdc5488d39334a2f0 | 512,623 |
def square(var_x): # 在文档字符串中添加doctest测试的内容:此函数在命令行下成功运行的过程
"""
Squares a number and returns the results.
>>> square(2)
4
>>> square(3)
9
"""
return var_x * var_x | badd41ba524aafdcd602c7596696f804753a95c4 | 141,225 |
import pickle
def dumps_content(content):
"""
pickle 序列化响应对象
:param content: 响应对象
:return: 序列化内容
"""
return pickle.dumps(content) | f88159b9d016a6e39744e7af09a76705c9f4e76f | 10,125 |
def prompt_choice(length, select_action, per_page):
"""
Prompt the user for a choice of entry, to continue or to quit.
An invalid choice will repeat the prompt.
@param length: the largest choosable value
@param select_action: description of what choosing an entry will result in.
@param per_pag... | 4b957479d96e5b8c642db4e888faf92c8c9cf945 | 10,570 |
def train_step(model, features, targets, optimizer, loss_function):
"""Computes an optimizer step and updates NN weights.
Parameters
----------
model : NeuralNetwork instance
features : torch.Tensor
Input features.
targets : torch.Tensor
Targets to compare with in loss function.
... | e15f1cba2212d52d41e32e464d7af62695e59a4f | 229,526 |
from typing import Tuple
from typing import List
def get_mpcs(model, mpc_id: int, consider_mpcadd: bool=True,
stop_on_failure: bool=True) -> Tuple[List[int], List[str]]:
"""
Gets the MPCs in a semi-usable form.
Parameters
----------
mpc_id : int
the desired MPC ID
stop_on... | 0e9ba03352c6f48a8cdfc37e12e270d3890401f3 | 152,721 |
import re
def _get_custom_metric_name(name):
"""Make a metric suitable for sending to Cloud Monitoring's API.
Metric names must not exceed 100 characters.
For now we limit to alphanumeric plus dot and underscore. Invalid
characters are converted to underscores.
"""
# Don't guess at automatic... | abf927893c5393a735eb6d90a2cc87fcbcfa8e36 | 402,127 |
from datetime import datetime
def calc_delta_days(d1, d2):
"""Calculate the day difference between datetime objects."""
if isinstance(d1, datetime) and isinstance(d2, datetime):
return (d2 - d1).days
else:
raise TypeError("d1 and d2 must be datetime.datetime objects") | b4ca090eaa500ecd8237903de4bf57a1bdf89b66 | 482,698 |
def extract_sample_name_from_sam_reader(sam_reader):
"""Returns the sample name as derived from the BAM file of reads.
Args:
sam_reader: Already opened sam_reader to use to extract the sample names
from. This sam_reader will not be closed after this function returns.
Returns:
The sample ID annotat... | f0be6306f8a107e874baec36b94b74ae9a5e0a1c | 79,863 |
def column_spec(name, func, width, padding_right=5, padding_left=5, align='right', vertical_align='middle'):
"""
Returns a function html_table_cell(item, header=False) that generates HTML for table cells
<td> for header == False and <th> for header == True according to the specification defined
by the i... | 6c1e7d73158e9c073e8bdd1866baf03cc80f6acf | 429,089 |
def clean_query(this_object):
"""clean_query: remove `_version_` key"""
this_object.pop('_version_', None)
return this_object | db7129343a602c02e6e39b46c8cf04aee2be16dd | 229,057 |
import requests
def get_file_size(url, params, timeout=10):
"""Get file size from a given URL in bytes.
Args:
url: str.
URL string.
timeout: int, optional.
Timeout in seconds.
Returns:
int. File size in bytes.
#### Examples
```python
get_file_size(url)
## 178904
```
"""
... | 642e733a1385423f0f8a894e8e3bfb96ea15dda4 | 90,630 |
def clean_o365_license_list(df):
"""
This function takes in an Office 365 license list (as a DataFrame) and cleans various aspects and then returns the cleaned list.
Parameters
----------
df : pandas DataFrame
Returns
-------
df : pandas DataFrame
"""
df['User principal nam... | 9774eb8a4055e30f63322619d3efe96d1d8095e1 | 559,071 |
import math
def vector_of_angle(angle):
""" Unit vector of an angle in degrees. """
return [[0.0, 0.0], [math.sin(math.radians(angle)), math.cos(math.radians(angle))]] | 3ac8b4b4a04dc40cf533588a9bf17cb2b0220588 | 583,672 |
def _has_repeated_entity(tokens, token_strings, vocab_size, comma_id):
"""
Returns whether the same entity token is repeated back to back or separated by a comma.
E.g. 'Obama Obama' or 'India, India'.
"""
for i in range(len(tokens) - 2):
if tokens[i] < vocab_size:
continue
... | bb6f95cc9b68c50fb129cb0478b2733d702ea113 | 326,488 |
def _valid_source_node(node: str) -> bool:
"""Check if it is valid source node in BEL.
:param node: string representing the node
:return: boolean checking whether the node is a valid target in BEL
"""
# Check that it is an abundance
if not node.startswith('a'):
return False
# check ... | d8f0e341c0f1ea4fffeea5193054cb9e9eec4b28 | 586,605 |
def roundodd(num):
"""
Round the given number to the nearest odd number.
"""
rounded = round(num)
if rounded % 2 != 0:
return rounded
else:
if rounded > num:
return rounded - 1
else:
return rounded + 1 | b2c6a1205069fd4e7323a5e62814bd31ae0b4123 | 587,581 |
import json
def get_json(json_path):
"""
Gets the JSON data.
:param json_path: Path to JSON file.
:return: JSON.
"""
with open(json_path, 'r') as json_file:
data = json.load(json_file)
return data | 97ac2ec1010755c2222acb002409256af0e88980 | 526,101 |
def capitalize(text):
"""Capitalises the specified text: first letter upper case,
all subsequent letters lower case."""
if not text:
return ''
return text[0].upper() + text[1:].lower() | 25d1a0e1ad7211cefa6938ed3bf5a9e0386b704b | 202,689 |
from bs4 import BeautifulSoup
def scrape_links(domain_name, html):
"""Scrape all links from the html document
Positional Arguments:
domain_name (str): the domain name of the website you're scraping
html (str): standard html document
Return:
list: all scraped links
"""
soup... | 8795430de17d7f02123a302af1c43ceee35b18a0 | 263,943 |
from typing import Dict
from typing import Any
from typing import List
def handle_ruling_rows(
card_data: Dict[str, Any], card_uuid: str
) -> List[Dict[str, Any]]:
"""
This method will take the card data and convert it, preparing
for SQLite insertion
:param card_data: Data to process
:param ca... | d8d020caa223bb6f9be9f72f4711f72752601bb7 | 614,778 |
def create_firewall(context):
"""Creates a VPC firewall config.
The VPC firewall config depends on the VPC network having been completely
instantiated, so it includes a dependsOn reference to the list of resources
generated by the network sub-template.
Args:
context: the DM context object.
Returns:... | b4d55379437c9de0dfbf3c3dd0c65c1b3aabedfb | 611,638 |
def plot_number_of_structures_per_kinase(structures, top_n_kinases=30):
"""
Plot the number of structures per kinase (for the top N kinases with the most structures).
Parameters
----------
structures : pandas.DataFrame
Structures DataFrame from opencadd.databases.klifs module.
top_n_kin... | 0d674ce68ae1bf0e7690faa22a1907fac3c925d1 | 235,547 |
def string_dict(d, offset=30, desc='DICTIONARY'):
""" transform dictionary to a formatted string
:param dict d:
:param int offset: length between name and value
:param str desc: dictionary title
:return str:
>>> string_dict({'abc': 123}) #doctest: +NORMALIZE_WHITESPACE
\'DICTIONARY: \\n"a... | 9a60de18325c17082e0c0e985854442f13c83759 | 274,412 |
def strong(text: str) -> str:
"""
Return the *text* surrounded by strong HTML tags.
>>> strong("foo")
'<b>foo</b>'
"""
return f"<b>{text}</b>" | fa63f2b38cbb8841cd495e47a0085115ad3a75b9 | 87,704 |
def augmentToBeUnique(listOfItems):
"""Returns a list of [(x,index)] for each 'x' in listOfItems, where index is the number of times
we've seen 'x' before.
"""
counts = {}
output = []
for x in listOfItems:
counts[x] = counts.setdefault(x, 0) + 1
output.append((x, counts[x]-1))
... | eb5208bd89444f0b0c618bef1fb6ae7a584f467c | 559,145 |
def smiles_to_folder_name(smiles):
"""
Encodes the SMILES containing special characters as URL encoding.
Parameters
----------
smiles : str
SMILES string describing a compound.
Returns
-------
str :
The standard URL encoding of the SMILES if it contains special characte... | ae2c45cf7388094dfaa63f62ff33dcfa12da6f43 | 473,679 |
def determine_adjusted(adjusted):
"""Determines weather split adjusted closing price should be used."""
if adjusted == False:
return 'close'
elif adjusted == True:
return 'adjClose' | c8c0ccc0284045d504595901506eb659f93b1cfb | 169,643 |
def markdown_table(body, header=None):
""" Generate a MultiMarkdown text table.
:param body: The body as a list-of-lists
:param header: The header to print
"""
s = ""
def cellstr(cell):
if type(cell) == float:
return ("%.2f" % cell)
if type(cell) in (list,... | 53139c42a994ccc70c445e89e287a9f2a589b9a8 | 369,054 |
def get_lr(optimizer):
"""get learning rate from optimizer
Args:
optimizer (torch.optim.Optimizer): the optimizer
Returns:
float: the learning rate
"""
for param_group in optimizer.param_groups:
return param_group['lr'] | fc8293cc29c2aff01ca98e568515b6943e93ea50 | 11,358 |
def tower(n):
"""computes 2^(2^(2^...)) with n twos, using recursion"""
if(n==0):
return 1
return 2**tower(n-1) | 30554f29eee5498d06910d580afaaa606894a83a | 624,671 |
def start_target_to_space(start, target, length, width):
"""
Create a state space for RRT* search given a start, target and
length / width buffer.
Args:
start: tuple of form (x, y)
target: tuple of form (x, y), (range_x, range_y)
length: float specifying length to buffer
... | e197c998ca8d401ae49cad9e96b8d074a8f28774 | 508,104 |
def predcedence(operator):
"""Return the predcedence of an operator."""
if operator in '+-':
return 0
elif operator in '*/':
return 1 | 6e67d4fd3a36e6c3fdd207d31edc80ebbe905fd3 | 429,764 |
def get_by_name(yaml, ifname):
"""Returns the interface or sub-interface by a given name, or None,None if it does not exist"""
if "." in ifname:
try:
phy_ifname, subid = ifname.split(".")
subid = int(subid)
iface = yaml["interfaces"][phy_ifname]["sub-interfaces"][subi... | 1437d233ebdad7ee949b16e31df8497364f213e1 | 401,336 |
def sum_of_squared_digits(number):
"""
Returns the sum of squares of the digits of a number
"""
sum = 0
while number > 0:
digit = number%10
number = number//10
sum += digit**2
return sum | 014f336fd8f83f3e3bba0a92b8106771f31d9365 | 133,462 |
import random
def flip_coin(p):
"""Flip biased coint p(True) = p."""
r = random.random()
return r < p | 21a1c1e186c9aad030fcb1706853dae6af1668e4 | 219,882 |
def r(b, p, alpha):
"""
Function to calculate the r coeficient of the Massman frequency correction.
"""
r = ((b ** alpha) / (b ** alpha + 1)) * \
((b ** alpha) / (b ** alpha + p ** alpha)) * \
(1 / (p ** alpha + 1))
return r | ddffac7b5af40147d6653501a72fd7c5c501a2fa | 692,435 |
def create_rules(lines):
"""
Given the list of line rules, create the rules dictionary.
"""
rules = dict()
for line in lines:
sline = line.split()
rules[sline[0]] = sline[-1]
return rules | 3ae3555f08fa4aa2cb147172ad4d584025c35133 | 100,215 |
def get_int_icode(res_seq):
"""
Return tuple (int, icode) with integer residue sequence number and
single char icode from PDB residue sequence string such as '60A' or '61'
etc.
Parameters:
res_seq - PDB resisue sequence number string, with or without icode
Return value:
tuple (int... | ec7380c85dcced668b2e359ec9a11b24246a9dcc | 359,795 |
def _have_common_proto(origin_meta, destination_meta):
"""
Takes two VersionMeta objects, in order of test from start version to next version.
Returns a boolean indicating if the given VersionMetas have a common protocol version.
"""
return origin_meta.max_proto_v >= destination_meta.min_proto_v | 6bf9f3fe0752319bb65cebc7e9eb5a8888de1819 | 320,002 |
import itertools
def interleave_lists(a, b):
"""
Interleaves the values of two lists. The length is equal to the shorter of the two lists x 2
:param a: first list e.g., ['a', 'b', 'c', 'd', 'e']
:param b: second list e.g., [1, 2, 3]
:return: interleaved list ['a', 1, 'b', 2, 'c', 3]
"""
r... | 45a96c07ce748d7e0caef62ab87e6ead6dd830c5 | 236,502 |
def _generate_overlaps(sequence, order):
"""
This function takes an input sequence & generates overlapping subsequences
of length order + 1, returned as a tuple. Has no dependencies & is called
by the wrapper compute()
Parameters
----------
sequence : string
String containing nucleo... | 134c130c6ff5173cc914b556899a2f04d1afd2e2 | 559,518 |
def _add_indent(string, indent):
"""Add indent of ``indent`` spaces to ``string.split("\n")[1:]``
Useful for formatting in strings to already indented blocks
"""
lines = string.split("\n")
first, lines = lines[0], lines[1:]
lines = ["{indent}{s}".format(indent=" " * indent, s=s)
fo... | cf7c90702a2664cc2088740758675911ed60a37c | 322,552 |
def all_taxa_have_attribute(phylogeny, attribute):
"""Do all taxa in the given phylogeny have the given attribute?
Args:
phylogeny (networkx.DiGraph): graph object that describes a phylogeny
attribute (str): a possible attribute/descriptor for a taxa (node) in
phylogeny
Returns:
... | 14ebbe774caa580911ef811228b26d7af5cdf9b7 | 335,986 |
def FivePointsDiff(fx, x, h=0.001):
"""
FivePointsDiff(@fx, x, h);
Use five points difference to approximatee the derivative of function fx
in points x, and with step length h
The function fx must be defined as a function handle with input
parameter x and the derivative as output parameter
... | 3b2ff6eca789e5cdf8c1ac2eba556b4994ca8e54 | 442,871 |
def _get_num_ve_sve_and_max_num_cells(cell_fracs):
"""
Calculate the num_ve, num_sve and max_num_cells
Parameters
----------
cell_fracs : structured array, optional
A sorted, one dimensional array,
each entry containing the following fields:
:idx: int
Th... | c0d154898bbfeafd66d89a2741dda8c2aa885a9a | 706,040 |
def getlenDict(data, keys=None):
"""Get len of a dict of lists"""
l = 0
if keys == None:
keys = data.keys()
for i in keys:
l += len(data[i])
return l | 369b8a32b59cbbfc60df512279c8758224a08fab | 612,073 |
def get_target_ns(xml_tree):
"""Extract the target namespace for the XML doc.
Returns:
str: Extracted from the `targetNamespace` attribute of the root element.
If the root element does not have a `targetNamespace` attribute, return an empty
string, "".
Examples:
<xs:sch... | f6bc1899f9e2590528bb0fc58c91b1938d4cb63d | 478,074 |
def zone_bc_type_english(raw_table, base_index):
""" Convert zone b/c type to English """
value = raw_table[base_index]
if value == 0:
return "NA"
if value == 1:
return "Direct"
if value == 2:
return "3WV"
if value == 3:
return "NA"
if value == 4:
ret... | d6fef02dd92ec1604b2bb892e6ad6dc00d5f889f | 659,290 |
def edit_header(my_vcf):
"""
Add INFO for new fields to vcf
"""
header = my_vcf.header.copy()
header.add_line(('##INFO=<ID=TruScore,Number=1,Type=Integer,'
'Description="Truvari score for similarity of match">'))
header.add_line(('##INFO=<ID=PctSeqSimilarity,Number=1,Type=Fl... | bde0247125c2bc20f25ec21ae8117d5c4887c358 | 499,639 |
import re
def make_role_node_dict(target_dict, nodes):
"""Given the target dict containing targets grouped by nodes and the list of
nodes, this function returns a dictionary containing the list of nodes
grouped by target and by role:
{
'role1':
{
... | fb25b55192670391d3f1a120fe49b815e8cfbee6 | 172,947 |
def elementtree_to_dict(element):
"""Convert an xml ElementTree to a dictionary."""
d = {}
if hasattr(element, "text") and element.text is not None:
d["text"] = element.text
d.update(list(element.items())) # element's attributes
for c in list(element): # element's children
if c.t... | ba89b27ae5f3b86e21a33f33a4eb239f0b24ac57 | 527,117 |
def get_cycles(motif):
"""
Generates cyclical variations of a motif
Parameters
----------
motif : str, nucleotide motif
Returns
-------
LIST, List of cyclical variations of the motif sorted in alphabetical order.
"""
cycles = set()
for i in range(len(motif)):
cy... | d34fcb1e9f2608fcf519755f2105bb5926393aeb | 480,049 |
import requests
def get_sha_url_and_ref_from_prid(repo, prid):
"""
given a GIT repo and a pull request ID, return the SHA, clone_url, and ref for that pull request
"""
response = requests.get(
"https://api.github.com/repos/{}/pulls/{}".format(repo, prid)
)
if response.status_code == 20... | aba031aa86c1d8bbf1d75ba27813811dd4ac3cef | 504,700 |
def query_transform(request, **kwargs):
"""Taken from http://stackoverflow.com/a/24658162/2844093
return a querystring with updated parameter. Useful, for example
in pagination to change page number without replacing the whole
query parameters.
Usage:
.. code-block:: html+django
<a hr... | 9ec06a5c2414a26019d51e9b4229d9fddc1b6b5f | 302,475 |
def get_csr_position(index, shape, crow_indices, col_indices):
"""Return the position of index in CSR indices representation. If
index is not in indices, return None.
"""
# binary search
row, col = index
left = crow_indices[row]
right = crow_indices[row+1] - 1
while left <= right:
... | baf115707a23963a253470ebc7a63cd49cd87278 | 76,805 |
def get_lna_num(name):
"""Return the number of an LNA, in the range 0…5
Valid values for the parameter `name` can be:
- The official name, e.g., HA1
- The UniMIB convention, e.g., H0
- The JPL convention, e.g., Q1
- An integer number, which will be returned identically
"""
if type(name... | ea5b29f25efbee2720d1ac62052e73f01924381d | 383,456 |
def match_error_event(event, *_args):
"""
Matches error events.
Returns True or False.
"""
return event['tag'] == 'error' | e3df2cbcbf3a8321a27fafad7a49881ec20502da | 212,581 |
def _isoformat(date):
"""Format a date or return None if no date exists"""
return date.isoformat() if date else None | 566e26fed7818874322f820e684c68940c726376 | 63,693 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.