content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
import re
def __unzip_labels(label):
"""unzips a string with more than one word
Parameters
----------
label : tuple
tuple or list of the text labels from the folder name
Returns
-------
list
splited labels as list of strings
"""
labels = re.split('(?=[A-Z])', label)
label = [label.lower() for label in labels]
return label | c442eaadf18c51fdb7d9519bc00658b97657a225 | 20,754 |
def check_user(user, event):
"""
Checks whether the ``ReactionAddEvent``, ``ReactionDeleteEvent``'s user is same as the given one.
Parameters
----------
user : ``ClientUserBase``
The user who should be matched.
event : ``ReactionAddEvent``, ``ReactionDeleteEvent``
The reaction addition or deletion event.
"""
return (event.user is user) | 37c5e280ced5a3470ac9691e6cb0dcadf3e3c550 | 20,756 |
def is_theme(labels, zen_issue):
"""Check If Issue Is a Release Theme.
Use the input Github Issue object and Zenhub Issue object to check:
* if issue is an Epic (Zenhub)
* if issue contains a `theme` label
"""
if zen_issue['is_epic']:
if 'theme' in labels:
return True | 380dbe8d4c9105a49a8ae211f55dcbfd35c38d3c | 20,775 |
from typing import Dict
from typing import Any
import pprint
def describe_item(data: Dict[str, Any], name: str) -> str:
"""
Function that takes in a data set (e.g. CREATURES, EQUIPMENT, etc.) and
the name of an item in that data set and returns detailed information about
that item in the form of a string that is ready to be sent to Discord
"""
item = data.get(name)
if item is None:
return "I'm sorry. I don't know about that thing"
s = pprint.pformat(item, indent=2, sort_dicts=True)
return s | 4df9e99f713effc00714342f54e2bd135b580675 | 20,777 |
def mini(a,b):
""" Minimal value
>>> mini(3,4)
3
"""
if a < b:
return a
return b | 2d49ce51bd239dd5ceb57396d7ed107f1309c203 | 20,778 |
def prod(iterable):
"""Computes the product of all items in iterable."""
prod = 1
for item in iterable:
prod *= item
return prod | f5ddea44c14a6d1dc77a3049723609358c1e8525 | 20,781 |
def areinstance(tokens, classes):
"""
>>> tokens = (TimeToken(15), TimeToken(16))
>>> areinstance(tokens, TimeToken)
True
>>> tokens = (TimeToken(15), DayToken(7, 5, 2018))
>>> areinstance(tokens, TimeToken)
False
>>> areinstance(tokens, (TimeToken, DayToken))
True
"""
assert isinstance(classes, type) or isinstance(classes, tuple), \
"Classes must either be a tuple or a type."
if isinstance(classes, type):
classes = (classes,)
return all([
any([isinstance(token, cls) for cls in classes]) for token in tokens]) | 27cf41a668dfcd52975becd0ae96c81d2c9ab385 | 20,782 |
def do_decomposition(gene_trail, selection):
"""Given a list of lists gene_trail and indexes for every item to be
selected in every list in gene_trail, returns a list representing the
corresponding decomposition.
For example, if gene_trail is [['a', 'b'], ['c'], ['d','e']] and the index
for the first list (['a', 'b']) is 0, the index for the second list (['c'])
is 0, and the index for the third list (['d', 'e']) is 1, then the
corresponding decomposition of gene_trail is ['a', 'c', 'e'].
:param gene_trail: list of lists where list items are identifiers of genes
involved in reactions of a CoMetGeNe trail
:param selection: dict storing the currently selected item for every list in
gene_trail
:return: list representing the decomposition of gene_trail given by indexes
stored in 'selection'
"""
for i in range(len(gene_trail)):
assert i in selection.keys()
for list_index in selection:
assert 0 <= selection[list_index] < len(gene_trail[list_index])
decomposition = list()
for i in range(len(gene_trail)):
decomposition.append(gene_trail[i][selection[i]])
return decomposition | cbe3a942db5fb447f9e7ffe8f0866419b04f81f1 | 20,784 |
def processEnum(enum, tableExists=True, join=True):
"""
Take an Enum object generated by the PyDBML library and use it to generate SQLite DDL for creating an enum table for "full" enum emulation mode only.
Parameters:
enum (Enum): Enum object generated by PyDBML library representing an SQL enum.
tableExists (bool): Default is True. If True, all generated `CREATE TABLE` SQLite statements will have `IF NOT EXISTS` language included.
join (bool): Default is True. If True, function will `join` the result list of string segments with an empty string and return the resulting string to you. Otherwise, the one-dimensional list of string segments will be returned to you directly.
Returns:
str or list of str: SQLite DDL for creating a table to emulate SQL enum functionality.
"""
segments = []
segments.append(f'CREATE TABLE {"IF NOT EXISTS" if tableExists else ""} {enum.name} (\n id INTEGER PRIMARY KEY,\n type TEXT NOT NULL UNIQUE,\n seq INTEGER NOT NULL UNIQUE\n);\n')
for i, v in enumerate(enum.items):
segments.append(f'INSERT INTO {enum.name}(type, seq) VALUES (\'{v.name}\', {i + 1});\n')
if join:
segments = "".join(segments)
return segments | 832ca77c1287790ea33b26baacdeee5b3f611785 | 20,785 |
from typing import OrderedDict
def _get_file_metadata(help_topic_dict):
"""
Parse a dictionary of help topics from the help index and return back an
ordered dictionary associating help file names with their titles.
Assumes the help dictionary has already been validated.
"""
retVal = OrderedDict()
for file in sorted(help_topic_dict.keys()):
retVal[file] = help_topic_dict[file][0]
return retVal | 6e03564f28ebc9ab8dc8ce12d314d18c35cf3518 | 20,786 |
def is_no_overlap(*set_list):
"""
Test if there's no common item in several set.
"""
return sum([len(s) for s in set_list]) == len(set.union(*[set(s) for s in set_list])) | 300253d499c22bb398837c9766a9f5d8f7b5c720 | 20,790 |
from warnings import warn
def _format_1(raw):
"""
Format data with protocol 1.
:param raw: returned by _load_raw
:return: formatted data
"""
data, metadata = raw[0]['data'], raw[0]['metadata']
# Check for more content
if len(raw) > 1:
base_key = 'extra'
key = base_key
count = 0
while key in metadata:
key = base_key + f'_{count}'
count += 1
metadata[key] = raw[1:]
warn('File contains extra information which will be returned in '
f'metadata[{key}].')
return data, metadata | 0939ffb4242828a7857f0f145e4adeb90ec6cff1 | 20,791 |
def first(iterable):
"""
Gets the first element from an iterable. If there are no items or there
are not enough items, then None will be returned.
:param iterable: Iterable
:return: First element from the iterable
"""
if iterable is None or len(iterable) == 0:
return None
return iterable[0] | 246ca69493a601343e1b1da201c68e2d8a3adc55 | 20,794 |
import re
def allsplitext(path):
"""Split all the pathname extensions, so that "a/b.c.d" -> "a/b", ".c.d" """
match = re.search(r'((.*/)*[^.]*)([^/]*)',path)
if not match:
return path,""
else:
return match.group(1),match.group(3) | 06baf4d1a58c9f550bd2351171db57a8fc7620d2 | 20,796 |
def is_prepositional_tag(nltk_pos_tag):
"""
Returns True iff the given nltk tag
is a preposition
"""
return nltk_pos_tag == "IN" | 746a1439613a2203e6247924fe480792e171eb7b | 20,798 |
import re
def clean_data(d):
"""Replace newline, tab, and whitespace with single space."""
return re.sub("\s{2}", " ", re.sub(r"(\t|\n|\s)+", " ", d.strip())) | 3c6b9032588d0cb2ca359ff27d727ade7011048a | 20,801 |
def calc_alpha_init(alpha, decay):
"""
Calculate the numerator such that at t=0, a/(decay+t)=alpha
"""
if not decay or decay <= 0:
return alpha
else:
return float(alpha * decay) | 41725753868a01b89f0a1ba0bc0b37b0ac2499c2 | 20,807 |
def tuple_to_list(t):
""" Convert a markup tuple:
(text,[(color,pos),...])
To a markup list:
[(color,textpart),...]
This is the opposite to urwid.util.decompose_tagmarkup
"""
(text,attrs) = t
pc = 0
l = []
for (attr,pos) in attrs:
if attr == None:
l.append(text[pc:pc+pos])
else:
l.append((attr, text[pc:pc+pos]))
pc += pos
return l | 466767cd7d1d43665141908661ca75b291b4db50 | 20,811 |
from typing import Iterable
from typing import Tuple
import networkx
def build_graph(data: Iterable[Tuple[dict, str, dict]]):
"""
Builds a NetworkX DiGraph object from (Child, Edge, Parent) triples.
Each triple is represented as a directed edge from Child to Parent
in the DiGraph.
Child and Parent must be dictionaries containing all hashable values
and a 'name' key (this is the name of the node in the DiGraph).
Edge must be a string representing an edge label from Child to Parent.
:param data: Iterable of (Child, Edge, Parent) triples.
:rtype: networkx.DiGraph
"""
g = networkx.DiGraph()
for child_attrs, edge, parent_attrs in data:
if 'name' not in child_attrs or 'name' not in parent_attrs:
raise ValueError(
"Both child and parent dicts must contain a 'name' key.\n"
"Provided Child data: {}\n"
"Provided Parent data: {}\n".format(child_attrs, parent_attrs)
)
# Copy dicts so popping 'name' doesn't affect the underlying data
child_attrs, parent_attrs = child_attrs.copy(), parent_attrs.copy()
child_name, parent_name = child_attrs.pop('name'), parent_attrs.pop('name')
# Update node attributes only if the updated version has strictly more data
# than the previous version
if child_name not in g or set(child_attrs).issuperset(g.nodes[child_name]):
g.add_node(child_name, **child_attrs)
if parent_name not in g or set(parent_attrs).issuperset(g.nodes[parent_name]):
g.add_node(parent_name, **parent_attrs)
g.add_edge(child_name, parent_name, label=edge)
return g | 6d43f3d2b9698eaac54cfcee38fd005e6762eaf6 | 20,813 |
def find_first_feature(tree):
"""Finds the first feature in a tree, we then use this in the split condition
It doesn't matter which feature we use, as both of the leaves will add the same value
Parameters
----------
tree : dict
parsed model
"""
if 'split' in tree.keys():
return tree['split']
elif 'children' in tree.keys():
return find_first_feature(tree['children'][0])
else:
raise Exception("Unable to find any features") | d57d29c3aadb0269d39fa73d27cd56416cc3e456 | 20,819 |
def sum_product(array: list) -> dict:
"""
BIG-O Notation: This will take O(N) time. The fact that we iterate through the array twice doesn't matter.
:param array: list of numbers
:return:
"""
total_sum = 0
total_product = 1
for i in array:
total_sum += i
for i in array:
total_product *= i
return {"sum": total_sum, "product": total_product} | 53a8ac6000f9c6f722ef7159e31d1dc5f069fa9b | 20,821 |
from pathlib import Path
def get_file_extension(filepath: str) -> str:
"""
Returns the extension for a given filepath
Examples:
get_file_extension("myfile.txt") == "txt"
get_file_extension("myfile.tar.gz") == "tar.gz"
get_file_extension("myfile") == ""
"""
extension_with_dot = "".join(Path(filepath).suffixes).lower()
if extension_with_dot:
return extension_with_dot[1:]
return "" | d90dd071298c1ee429d913abd831030a60086b1b | 20,826 |
def unescape(s):
"""The inverse of cgi.escape()."""
s = s.replace('"', '"').replace('>', '>').replace('<', '<')
return s.replace('&', '&') | 3bad6bc3679405dd0d223ea8ab6362a996067ea5 | 20,827 |
import random
def seq_permutation(seq: str, k: int = 1) -> str:
"""Shuffle a genomic sequence
Args:
seq (str): Sequence to be shuffled.
k (int): For `k==1`, we shuffle individual characters. For `k>1`, we shuffle k-mers.
Returns:
Shuffled sequence.
"""
if k == 1:
return ''.join(random.sample(seq, len(seq)))
else:
kmers = [seq[i:(i + k)] for i in range(0, len(seq), k)]
return ''.join(random.sample(kmers, len(kmers))) | a789c2a5cb00e2e5fd140ba889510e6b7fd556d3 | 20,832 |
import math
def get_normalized_meter_value(t):
"""
Expects a value between 0 and 1 (0 -> 00:00:00 || 1 -> 24:00:00) and returns the normalized
simulated household consumption at that time, according to this
Graph: http://blog.abodit.com/images/uploads/2010/05/HomeEnergyConsumption.png
The formula can be examinated on https://www.desmos.com/calculator
The formula used is this one:
\frac{\left(\sin\left(x\right)\ +\ \frac{x}{2.5}\ \cdot\left(-e^{\frac{x}{12}}+2.85\right)+1\right)}{5}
It tries to mimic the Graph as normalized values.
f(0) = power consumption at 00:00:00
f(PI*4) = power consumption at 24:00:00
"""
x = t * math.pi * 4
meter_value = math.sin(x) + (x/2.5) * (-math.pow(math.e, x / 12.0) + 2.85) + 1
normalized_meter_value = meter_value / 5.0
return normalized_meter_value | 03f40967f05de4d23d7600286bfc2927fea544d6 | 20,835 |
def squared_dist(x1, x2):
"""Computes squared Euclidean distance between coordinate x1 and coordinate x2"""
return sum([(i1 - i2)**2 for i1, i2 in zip(x1, x2)]) | c4ae86e54eb1630c20546a5f0563d9db24eebd3a | 20,838 |
def itensity_rescaling_one_volume(volume):
"""
Rescaling the itensity of an nd volume based on max and min value
inputs:
volume: the input nd volume
outputs:
out: the normalized nd volume
"""
out = (volume + 100) / 340
return out | 58ee7f00c54b063fac23eeb166df5f6d6adb2941 | 20,840 |
def default_func(entity, attribute, value):
"""
Look in the entity for an attribute with the
provided value. First proper attributes are
checked, then extended fields. If neither of
these are present, return False.
"""
try:
return getattr(entity, attribute) == value
except AttributeError:
try:
return entity.fields[attribute] == value
except (AttributeError, KeyError):
return False | 0ec6636c20d3f5eedb7a7c1f2457f72ecddb7545 | 20,852 |
def get_last_file(paths):
"""Returns last modified file from list of paths"""
if paths:
return sorted(paths, key=lambda f: f.stat().st_mtime)[-1]
return "" | 51978ae6dbb3686de40eebda156825904895a854 | 20,853 |
from inspect import signature
def check_callable(input_func, min_num_args=2):
"""Ensures the input func 1) is callable, and 2) can accept a min # of args"""
if not callable(input_func):
raise TypeError('Input function must be callable!')
# would not work for C/builtin functions such as numpy.dot
func_signature = signature(input_func)
if len(func_signature.parameters) < min_num_args:
raise TypeError('Input func must accept atleast {} inputs'.format(min_num_args))
return input_func | 7358d0685fd6f04f6a2ecf75aee66288a25a5e08 | 20,854 |
def evaluate_svm(test_data, train_data, classifier, logfile=None):
"""
Evaluates svm, writes output to logfile in tsv format with columns:
- svm description
- accuracy on test set
- accuracy on train set
"""
train_x, train_y = train_data
classifier.fit(train_x, train_y)
test_x, test_y = test_data
train_accuracy = classifier.score(train_x, train_y)
test_accuracy = classifier.score(test_x, test_y)
out_msg = '\t'.join((str(classifier.C), str(classifier.kernel), str(test_accuracy), str(train_accuracy)))
print(out_msg)
if logfile is not None:
with open(logfile, 'a+') as lf:
lf.writelines([out_msg])
return test_accuracy, train_accuracy | 21550a91227eca49a05db2f3216bc72c50a74d1e | 20,861 |
def flatten_results(results: dict, derivation_config: dict) -> dict:
"""Flatten and simplify the results dict into <metric>:<result> format.
Args:
results (dict): The benchmark results dict, containing all info duch as
reduction types too
derivation_config (dict): The configuration defining how metrics are
derived from logs
Returns:
flat_results (dict): The flattened dict of all results in
<metric>:<result> format
"""
flat_results = {}
for metric, results_dict in results.items():
key = derivation_config.get(metric, {}).get("reduction_type", "mean")
flat_results[metric] = results_dict[key]
return flat_results | 045c1e1d856c20b37d2d78d8dd6c3fd76cb91777 | 20,862 |
def path_string(obj, **kwargs):
"""return physical path as a string"""
return "/".join(obj.getPhysicalPath()) | bae683d392b519f8c43f5e9d1415abb8cf8de636 | 20,865 |
def adjust_returns_for_slippage(returns, turnover, slippage_bps):
"""Apply a slippage penalty for every dollar traded.
Parameters
----------
returns : pd.Series
Time series of daily returns.
turnover: pd.Series
Time series of daily total of buys and sells
divided by portfolio value.
- See txn.get_turnover.
slippage_bps: int/float
Basis points of slippage to apply.
Returns
-------
pd.Series
Time series of daily returns, adjusted for slippage.
"""
slippage = 0.0001 * slippage_bps
# Only include returns in the period where the algo traded.
trim_returns = returns.loc[turnover.index]
return trim_returns - turnover * slippage | d445bf566f5c228ffda793089d7bfe23f3897df2 | 20,869 |
import requests
def get_json(url):
"""Fetches URL and returns JSON. """
res = requests.get(url)
res.raise_for_status()
return res.json() | 280f3c298cb5a471abe180b29c9d465d52b7b9b8 | 20,870 |
def find_matching_resource(preview_resource, delivery_entry, search_field):
"""Returns matching resource for a specific field.
:param preview_resource: Entry from the Preview API to match.
:param delivery_entry: Entry to search from, from the Delivery API.
:param search_field: Field in which to search in the delivery entry.
:return: Entry from the Delivery API or None.
"""
if not delivery_entry:
return None
for delivery_resource in delivery_entry.fields().get(search_field, []):
if preview_resource.id == delivery_resource.id and (
delivery_resource.type == 'Entry'
or delivery_resource.type == 'Asset'
):
return delivery_resource | 518297f18a2dcd37bb226f96bd51370d7ed3c7e3 | 20,872 |
import re
def extract_date(text):
"""
Given the HTML text for one day, get the date
:param text: HTML text for one day
:return: Date as string
"""
report_date = re.findall("Arrow Build Report for Job nightly-.*", text)[0]
report_date = report_date.strip("Arrow Build Report for Job nightly-")
report_date = report_date.strip("-0$")
return report_date | e73952c4efc421f9227dad16346e923590933bdf | 20,875 |
def __validate_scikit_params(parameters):
"""validate scikit-learn DBSCAN parameters
Args:
parameters: (dict)
Returns:
eps, min_samples, metric, n_jobs
"""
eps, min_samples, metric, n_jobs = None, None, None, None
if parameters is not None:
eps = parameters.get('eps')
min_samples = parameters.get('min_samples')
metric = parameters.get('metric')
n_jobs = parameters.get('n_jobs')
else:
pass
# set default values if the dictionary didn't contain correct keys
eps = 0.005 if eps is None else eps
min_samples = 100 if min_samples is None else min_samples
metric = 'euclidean' if metric is None else metric
n_jobs = -1 if n_jobs is None else n_jobs
return eps, min_samples, metric, n_jobs | 9b1f9bf89f6526bb0b67d658dd1bfc6d69a8ad83 | 20,880 |
import json
def load_json_key(obj, key):
"""Given a dict, parse JSON in `key`. Blank dict on failure."""
if not obj[key]:
return {}
ret = {}
try:
ret = json.loads(obj[key])
except Exception:
return {}
return ret | d695d8eb1d08933a3bacba4de77161a6587a863d | 20,886 |
def float_to_fixed_point(x: float, precision: int) -> int:
"""
Converts the given floating point value to fixed point representation
with the given number of fractional bits.
"""
multiplier = 1 << precision
width = 16 if precision >= 8 else 8
max_val = (1 << (width - 1)) - 1
min_val = -max_val
fp_val = int(round(x * multiplier))
if fp_val > max_val:
print('WARNING: Observed positive overflow')
return max_val
elif fp_val < min_val:
print('WARNING: Observed negative overflow')
return min_val
return fp_val | 8b80f701b610da06ac8a09e8811ce00967a1a413 | 20,887 |
def encode(s):
""" Encodes a string into base64 replacing the newline
at the end.
Args:
s (str): The string.
"""
return s.strip().encode('base64').replace('\n', '') | 02c805b7888560596cede9c763d0cf42334d4185 | 20,889 |
def format_file_date(edition_date):
"""Return a string DDMMYY for use in the filename"""
return edition_date.strftime('%d%m%y') | 3cab0a2de4c91ae66826f4ba49d9e4fdc1b7c1d0 | 20,890 |
def parse_repo_url(repo_url: str) -> str:
"""
Parses repo url and returns it in the form 'https://domain.com/user/repo'
Args:
repo_url (str): unformatted repo url
Returns:
str: parsed repo url
"""
repo = repo_url.lstrip("git+") if repo_url.startswith("git+") else repo_url
repo = repo.rstrip(".git") if repo.endswith(".git") else repo
if repo.startswith("http"):
if "gitlab.com" in repo:
return f"{repo}/-/blob/master/"
return f"{repo}/blob/master/"
else:
repo_data = repo.split(":", 1)
domain = repo_data[0].split("@")[-1]
return f"https://{domain}/{repo_data[1]}/blob/master/" | 5f9b5d2a0bc3dc30e48006fd43baa73d996268ca | 20,896 |
def organism_matches(organism, patterns):
"""Tests organism filter RegEx patterns against a given organism name."""
for pattern in patterns:
if pattern.match(organism):
return True
return False | 135b6ad0472a2b0904ececc8b8f226c77b2294e6 | 20,897 |
from typing import Optional
from typing import Dict
def type_filter(type_: Optional[str], b: Dict) -> bool:
"""
Check Mistune code block is of a certain type.
If the field "info" is None, return False.
If type_ is None, this function always return true.
:param type_: the expected type of block (optional)
:param b: the block dicionary.
:return: True if the block should be accepted, false otherwise.
"""
if type_ is None:
return True
return b["info"].strip() == type_ if b["info"] is not None else False | 083c89f9563c9282edf1babf9fdf249f694a0117 | 20,906 |
from typing import List
def elements_identical(li: List) -> bool:
"""Return true iff all elements of li are identical."""
if len(li) == 0:
return True
return li.count(li[0]) == len(li) | 2cccfaf588994080033e4ddfd17c351f5c462546 | 20,908 |
def read_file(filepath):
"""Open and read file contents.
Parameters
----------
filepath : str
path to a file
Returns
-------
str
contents of file
Raises
------
IOError
if file does not exist
"""
file_data = None
with open(filepath, "r") as f:
file_data = f.read()
return file_data | 5b4e65893c94c45bb697a41222dbe524d60d2b04 | 20,910 |
def format_date(date:str) -> str:
"""return YYYYmmdd as YYYY-mm-dd"""
return f"{date[:4]}-{date[4:6]}-{date[6:]}" | dfcc434006df8a7f6bd89003f592792faa891f30 | 20,911 |
def _get_bootstrap_samples_from_indices(data, bootstrap_indices):
"""convert bootstrap indices into actual bootstrap samples.
Args:
data (pandas.DataFrame): original dataset.
bootstrap_indices (list): List with numpy arrays containing positional indices
of observations in data.
Returns:
list: list of DataFrames
"""
out = [data.iloc[idx] for idx in bootstrap_indices]
return out | 15dac498120db5590bc3c8c2542c0d78be999dd4 | 20,914 |
def get_module_name_parts(module_str):
"""Gets the name parts of a module string
`module_str` in the form of module.submodule.method or module.submodule.class
"""
if module_str:
parts = module_str.split('.')
module_name = '.'.join(parts[:-1])
attr_name = parts[-1]
values = (module_name, attr_name,)
else:
values = (None, None,)
return values | f167fe3a1224b5d3a1909e66bb9fa5288fd23eae | 20,915 |
from typing import List
def blocks_to_squares(blocks: List[List[int]]) -> List[List[List[int]]]:
"""Returns a list of list of blocks of four squares at a time. E.g.
.. code-block:: python
blocks = [
[A, B, 1, 1],
[C, D, 0, 1],
]
# would return the list below containing a list of rows, with each
# row being a list of squares
[ [ [A, B, C, D], [1, 1, 0, 1] ] ]
In the returned squares, the square coords go:
* top-left
* top-right
* bottom-left
* bottom-right
:param blocks: List of blocks to transform into squares
"""
max_row = len(blocks)
max_col = len(blocks[0])
def get_pos(row, col):
if row >= len(blocks):
return None
if col >= len(blocks[0]):
return None
val = blocks[row][col]
if val == 1:
return None
return val
square_rows = []
for row in range(0, len(blocks), 2):
curr_square_row = []
for col in range(0, len(blocks[0]), 2):
tl = get_pos(row, col)
tr = get_pos(row, col+1)
bl = get_pos(row+1, col)
br = get_pos(row+1, col+1)
curr_square_row.append([tl, tr, bl, br])
square_rows.append(curr_square_row)
return square_rows | 5bdde168ef9309ff93d478c6e6776d250c832c37 | 20,916 |
def server(app):
"""Return a test client to `app`."""
client = app.test_client()
return client | aeef67904f95d28356989ddbde49a43378fa096f | 20,920 |
def middle(a):
"""Returns a (list) without the first and last element"""
return a[1:-1] | 112854e009afaf6080363f3f1b3df944b4739ede | 20,922 |
import unicodedata
import re
def ascii_uppercase_alphanum(s, decoding='utf-8'):
"""Convert a string to alphanumeric ASCII uppercase characters."""
if type(s) is float:
return s
nfkd = unicodedata.normalize('NFKD', s)
only_ascii = nfkd.encode('ASCII', 'ignore')
upper = only_ascii.upper()
decoded = upper.decode(decoding)
alphanum = ' '.join(m.group(0) for m in re.finditer('[A-Z0-9]+', decoded))
return alphanum | 3694581fae9935a332e2929364e96eb054b3e749 | 20,926 |
def _add_tags(tags, additions):
""" In all tags list, add tags in additions if not already present. """
for tag in additions:
if tag not in tags:
tags.append(tag)
return tags | 234e6cabd478bcfc95bb3d8f6118e0f0307fabc4 | 20,929 |
def get_cmdb_detail(cmdb_details):
"""
Iterate over CMDB details from response and convert them into RiskSense context.
:param cmdb_details: CMDB details from response
:return: List of CMDB elements which includes required fields from resp.
"""
return [{
'Order': cmdb_detail.get('order', ''),
'Key': cmdb_detail.get('key', ''),
'Value': cmdb_detail.get('value', ''),
'Label': cmdb_detail.get('label', '')
} for cmdb_detail in cmdb_details] | aa2750b3754d2a776d847cfa22ff2b84f53bb351 | 20,932 |
def sqr(num):
"""
Computes the square of its argument.
:param num: number
:return: number
"""
return num*num | cb16d5638afeff0061415e45467b5fd4e644951f | 20,935 |
def cidr_to_common(cidr_mask):
"""Function that returns a common mask (Ex: 255.255.255.0)
for a given input CIDR mask (Ex: 24)"""
cidrtocommon = {
1: "128.0.0.0",
2: "192.0.0.0",
3: "224.0.0.0",
4: "240.0.0.0",
5: "248.0.0.0",
6: "252.0.0.0",
7: "254.0.0.0",
8: "255.0.0.0",
9: "255.128.0.0",
10: "255.192.0.0",
11: "255.224.0.0",
12: "255.240.0.0",
13: "255.248.0.0",
14: "255.252.0.0",
15: "255.254.0.0",
16: "255.255.0.0",
17: "255.255.128.0",
18: "255.255.192.0",
19: "255.255.224.0",
20: "255.255.240.0",
21: "255.255.248.0",
22: "255.255.252.0",
23: "255.255.254.0",
24: "255.255.255.0",
25: "255.255.255.128",
26: "255.255.255.192",
27: "255.255.255.224",
28: "255.255.255.240",
29: "255.255.255.248",
30: "255.255.255.252",
31: "255.255.255.254",
32: "255.255.255.255",
}
if int(cidr_mask) >= 0 and int(cidr_mask) <= 32:
return cidrtocommon[int(cidr_mask)]
else:
raise ValueError("Incorrect CIDR mask entered") | 9357592b86c812d632edcbe376d55994c58174b6 | 20,936 |
def pluralize(n, s, ss=None):
"""Make a word plural (in English)"""
if ss is None:
ss = s + "s"
if n == 1:
return s
else:
return ss | 1b24a513f1529666f8535a17482f1ce1b140d1ef | 20,939 |
def serialize_profile(user_profile):
"""
Serializes an user profile object.
:param user_profile: user profile object
:return: dictionary with the user profile info
"""
return {
'bio': user_profile.bio,
'description': user_profile.description,
'resume': user_profile.resume,
'full_name': user_profile.full_name,
'mail': user_profile.mail,
'birth_date': user_profile.birth_date.strftime("%d-%m-%Y"),
'avatar': user_profile.avatar,
} | 4eb1f88c197117c9dd31ab3090d541c0ae7b65bb | 20,941 |
def ensure_list(thing):
"""
Wrap ``thing`` in a list if it's a single str.
Otherwise, return it unchanged.
"""
if isinstance(thing, str):
return [thing]
return thing | 45ac322794627661c814b7905d6531aedd2a61b5 | 20,948 |
def create_acc_ui_command(packer, main_on: bool, enabled: bool, stock_values):
"""
Creates a CAN message for the Ford IPC adaptive cruise, forward collision
warning and traffic jam assist status.
Stock functionality is maintained by passing through unmodified signals.
Frequency is 20Hz.
"""
values = {
"HaDsply_No_Cs": stock_values["HaDsply_No_Cs"], # [0|255]
"HaDsply_No_Cnt": stock_values["HaDsply_No_Cnt"], # [0|15]
"AccStopStat_D_Dsply": stock_values["AccStopStat_D_Dsply"], # ACC stopped status message: 0=NoDisplay, 1=ResumeReady, 2=Stopped, 3=PressResume [0|3]
"AccTrgDist2_D_Dsply": stock_values["AccTrgDist2_D_Dsply"], # ACC target distance [0|15]
"AccStopRes_B_Dsply": stock_values["AccStopRes_B_Dsply"], # [0|1]
"TjaWarn_D_Rq": stock_values["TjaWarn_D_Rq"], # TJA warning: 0=NoWarning, 1=Cancel, 2=HardTakeOverLevel1, 3=HardTakeOverLevel2 [0|7]
"Tja_D_Stat": 2 if enabled else (1 if main_on else 0), # TJA status: 0=Off, 1=Standby, 2=Active, 3=InterventionLeft, 4=InterventionRight, 5=WarningLeft, 6=WarningRight, 7=NotUsed [0|7]
"TjaMsgTxt_D_Dsply": stock_values["TjaMsgTxt_D_Dsply"], # TJA text [0|7]
"IaccLamp_D_Rq": stock_values["IaccLamp_D_Rq"], # iACC status icon [0|3]
"AccMsgTxt_D2_Rq": stock_values["AccMsgTxt_D2_Rq"], # ACC text [0|15]
"FcwDeny_B_Dsply": stock_values["FcwDeny_B_Dsply"], # FCW disabled [0|1]
"FcwMemStat_B_Actl": stock_values["FcwMemStat_B_Actl"], # FCW enabled setting [0|1]
"AccTGap_B_Dsply": stock_values["AccTGap_B_Dsply"], # ACC time gap display setting [0|1]
"CadsAlignIncplt_B_Actl": stock_values["CadsAlignIncplt_B_Actl"], # Radar alignment? [0|1]
"AccFllwMde_B_Dsply": stock_values["AccFllwMde_B_Dsply"], # ACC follow mode display setting [0|1]
"CadsRadrBlck_B_Actl": stock_values["CadsRadrBlck_B_Actl"], # Radar blocked? [0|1]
"CmbbPostEvnt_B_Dsply": stock_values["CmbbPostEvnt_B_Dsply"], # AEB event status [0|1]
"AccStopMde_B_Dsply": stock_values["AccStopMde_B_Dsply"], # ACC stop mode display setting [0|1]
"FcwMemSens_D_Actl": stock_values["FcwMemSens_D_Actl"], # FCW sensitivity setting [0|3]
"FcwMsgTxt_D_Rq": stock_values["FcwMsgTxt_D_Rq"], # FCW text [0|7]
"AccWarn_D_Dsply": stock_values["AccWarn_D_Dsply"], # ACC warning [0|3]
"FcwVisblWarn_B_Rq": stock_values["FcwVisblWarn_B_Rq"], # FCW alert: 0=Off, 1=On [0|1]
"FcwAudioWarn_B_Rq": stock_values["FcwAudioWarn_B_Rq"], # FCW audio: 0=Off, 1=On [0|1]
"AccTGap_D_Dsply": stock_values["AccTGap_D_Dsply"], # ACC time gap: 1=Time_Gap_1, 2=Time_Gap_2, ..., 5=Time_Gap_5 [0|7]
"AccMemEnbl_B_RqDrv": stock_values["AccMemEnbl_B_RqDrv"], # ACC setting: 0=NormalCruise, 1=AdaptiveCruise [0|1]
"FdaMem_B_Stat": stock_values["FdaMem_B_Stat"], # FDA enabled setting [0|1]
}
return packer.make_can_msg("ACCDATA_3", 0, values) | 2a0ab397b54d328e6af38701caec002ca7fa99ac | 20,951 |
import re
def cleanup_tex_line(text):
"""Format line of tex e.g. replace multiple spaces with one"""
# replace multiple spaces with 1 space (simplifies matching)
if text == r"\n":
return ""
text = re.sub(r" {2,}", " ", text)
text = text.rstrip()
return text | 0304477aafa447a3aad58da116cac2590437351d | 20,952 |
import json
def humanreadable_from_report_contents(contents):
"""Make the selected contents pulled from a report suitable for war room output
Parameters
----------
contents : dict
Contents selected from an ANYRUN report for Demisto output.
Returns
-------
dict
Contents formatted so that nested dicts/lists appear nicely in a war room
entry.
"""
def dict_to_string(nested_dict):
return json.dumps(nested_dict).lstrip('{').rstrip('}').replace('\'', '').replace('\"', '')
humanreadable_contents = {}
for key, val in contents.items():
if isinstance(val, dict):
humanreadable_contents[key] = dict_to_string(val)
elif isinstance(val, list):
humanreadable_vals = []
for item in val:
if isinstance(item, dict):
humanreadable_vals.append(dict_to_string(item))
else:
humanreadable_vals.append(item)
humanreadable_contents[key] = humanreadable_vals
else:
humanreadable_contents[key] = val
return humanreadable_contents | 852be1990fff7832ff73f1853b756ddf1b34ec33 | 20,953 |
def get_id(mention):
"""
Get the ID out of a mention as a string
:param mention: String of just the mention
:return: Snowflake ID as an int
"""
return int(mention.strip("<@#&!>")) | eb7dcfd8ae5752318e646218219c8faaf6348d19 | 20,956 |
import math
def to_deg_min_sec(DecDegrees):
"""
Converts from decimal (binary float) degrees to:
Degrees, Minutes, Seconds
"""
degrees, remainder = divmod(round(abs(DecDegrees), 9), 1)
minutes, remainder = divmod(round(remainder * 60, 9), 1)
# float to preserve -0.0
return math.copysign(degrees, DecDegrees), minutes, remainder * 60 | 52ac22a4d504c264260a812d43b7bf850c7f1595 | 20,962 |
import re
def cleanId(input_id) :
"""
filter id so that it's safe to use as a pyflow indentifier
"""
return re.sub(r'([^a-zA-Z0-9_\-])', "_", input_id) | a53b93945754dec2c79039e9fe2720f3472248cc | 20,963 |
import torch
def predict(model, dataloader, labeldict):
"""
Predict the labels of an unlabelled test set with a pretrained model.
Args:
model: The torch module which must be used to make predictions.
dataloader: A DataLoader object to iterate over some dataset.
labeldict: A dictionary associating labels to integer values.
Returns:
A dictionary associating pair ids to predicted labels.
"""
# Switch the model to eval mode.
model.eval()
device = model.device
# Revert the labeldict to associate integers to labels.
labels = {index: label for label, index in labeldict.items()}
predictions = {}
# Deactivate autograd for evaluation.
with torch.no_grad():
for batch in dataloader:
# Move input and output data to the GPU if one is used.
ids = batch["id"]
premises = batch['premise'].to(device)
premises_lengths = batch['premise_length'].to(device)
hypotheses = batch['hypothesis'].to(device)
hypotheses_lengths = batch['hypothesis_length'].to(device)
_, probs = model(premises,
premises_lengths,
hypotheses,
hypotheses_lengths)
_, preds = probs.max(dim=1)
for i, pair_id in enumerate(ids):
predictions[pair_id] = labels[int(preds[i])]
return predictions | c2e28c9dacca715720186c2ce01735cb4a7c2e38 | 20,964 |
def target_fasta(tmp_path):
"""A simple target FASTA"""
out_file = tmp_path / "target.fasta"
with open(out_file, "w+") as fasta_ref:
fasta_ref.write(
">wf|target1\n"
"MABCDEFGHIJKLMNOPQRSTUVWXYZKAAAAABRAAABKAAB\n"
">wf|target2\n"
"MZYXWVUTSRQPONMLKJIHGFEDCBAKAAAAABRABABKAAB\n"
">wf|target3\n"
"A" + "".join(["AB"] * 24) + "AK\n"
">wf|target4\n"
"MABCDEFGHIJK"
)
return out_file | a0aead0b8aab69d3d9b2805b26fcad94ea9e5b8d | 20,967 |
def simple_mutation(image, base_image, sequence, calculate_error, palette, draw):
"""Computes the effects of a simple mutation.
:param image: The image to draw the gene on.
:param base_image: The original image to compare to.
:param sequence: The gene sequence.
:param calculate_error: The error metric method.
:param palette: The color palette to use.
:param draw: The method to draw the shape according to the gene.
:type image: ndarray
:type base_image: ndarray
:type sequence: List[Gene]
:type calculate_error: Callable
:type palette: List[Tuple[int, int, int]]
:type draw: Callable
:return: The error, the mutated gene, and the new image.
:rtype: Tuple[float, Gene, ndarray]
"""
mutated_gene = sequence[0].clone()
mutated_gene.mutate()
new_image = image.copy()
draw(new_image, mutated_gene, palette)
error = calculate_error(new_image, base_image)
return error, mutated_gene, new_image | 7f39cfcf877f55b4f3072ac1762470d7d38d33e7 | 20,969 |
import time
def should_refresh_time(event_time, last_refresh_time, refresh_after_mins=60):
"""
The clock on the PyPortal drifts, and should be refreshed
from the internet periodically for accuracy.
We want to refresh the local time when:
- The local time isn't set
- After refresh_after_mins have passed
- If the event time hasn't passed
Args:
event_time (time.struct_time): Time of the event.
last_refresh_time (time.monotonic): Time local time
was last refreshed from the internet.
refresh_after_mins (int, optional): How many minutes to wait
between refreshing from the internet. Defaults to 60.
Returns:
bool: If the local device time should be refreshed from
the internet.
"""
just_turned_on = not last_refresh_time
if just_turned_on:
print("Refreshing time: PyPortal just turned on.")
return True
time_since_refresh = time.monotonic() - last_refresh_time
refresh_time_period_expired = time_since_refresh > refresh_after_mins * 60
if refresh_time_period_expired:
print(
"Refreshing time: last refreshed over {} mins ago.".format(
refresh_after_mins
)
)
return True
remaining_time = time.mktime(event_time) - time.mktime(time.localtime())
is_event_over = remaining_time and remaining_time < 0
if is_event_over:
print("Won't refresh time: event over.")
return False | a785714b5efeafe8250f4fe841d2d0e085ba197f | 20,973 |
def map_skip_none(fn, it):
"""
emulate list(map(fn, it)) but leave None as it is.
"""
ret = []
for x in it:
if x is None:
ret.append(None)
else:
ret.append(fn(x))
return ret | 296110c3d416d1653411da7c3fbce02b280078b1 | 20,974 |
def shoot_error(x_target, x):
"""
calculates the error of a shoot on the target at x_target.
:param x_target: position of the target
:param x: state array holding the complete history of the shoot
:return: error. A positive sign of the error indicates that the shoot has been to far, a negative sign that it has
been to short.
"""
# ==============================================================================
#
# ==============================================================================
x_hit = x[0, -1] # access last element from the state array and get x position
error = x_hit - x_target
return error | d03e07cb4779cedbf485e4ebd55869c5f9471d29 | 20,981 |
def parse_mapholder_div(tree):
"""Parses the HTML for a 'mapholder' class.
Parameter
---------
tree: lxml.html.HtmlElement
The section in the HTML page for each map. This is normally
<div class="mapholder"> ... </div>
Return
------
Dictionary object with the specified fields
"""
# Name of current map
map_name = tree.find_class("mapname")[0].text_content()
# ID of the map statistics
map_stats_uri = tree.find_class("results-stats")[0].get("href")
map_stats_id = map_stats_uri.rsplit("/")[-2]
# Scores for CT and T sides for each half
ct_scores = [score.text_content() for score in tree.find_class("ct")]
t_scores = [score.text_content() for score in tree.find_class("t")]
# Team 1 starts on CT or T side
team_1_starting = tree.find_class("results-center-half-score")[0].xpath(".//span")[1].get("class")
# 1 iff team_1 starts on CT, 2 otherwise (team_2 starts on CT)
if team_1_starting == "ct":
starting_ct = 1
team_1_ct = ct_scores[0]
team_1_t = t_scores[1]
team_2_ct = ct_scores[1]
team_2_t = t_scores[0]
else:
starting_ct = 2
team_1_ct = ct_scores[1]
team_1_t = t_scores[0]
team_2_ct = ct_scores[0]
team_2_t = t_scores[1]
return {
"map": map_name.lower(),
"map_stats_id": int(map_stats_id),
"team_1_t": int(team_1_t),
"team_1_ct": int(team_1_ct),
"team_2_t": int(team_2_t),
"team_2_ct": int(team_2_ct),
"starting_ct": starting_ct
} | 6f211eb5341de1d59e9043d2cc9c4b0340a8bd50 | 20,982 |
from typing import Iterable
def last_survivor(letters: str, coords: Iterable[int]) -> str:
"""
Removes from letters the chars at coords index.
Returns the first survivor letter.
"""
arr = list(letters)
for idx in coords:
del arr[idx]
return arr[0] | 21d2ddb7bfb43a8df5eca390b1154a1a863ed373 | 20,987 |
def pred_sql(col, val):
""" Generates SQL for equality predicate.
Args:
col: predicate restricts this column
val: filter column using this value
Returns:
predicate as SQL string (escaped)
"""
esc_val = str(val).replace("'", r"''")
return f"{col}='{esc_val}'" | 16dd042820fc0cef3139320e204646c3c678bd0e | 20,988 |
import random
def block(n_subjects, n_groups, block_length, seed=None):
""" Create a randomization list using block randomization.
Block randomization takes blocks of group labels of length `block_length`,
shuffles them and adds them to the randomization list. This is done to
prevent long runs of a single group. Usually `block_length` is equal
to 4 or 6.
Args:
n_subjects: The number of subjects to randomize.
n_groups: The number of groups to randomize subjects to.
block_length: The length of the blocks. `block` should be equal to
:math:`k * n_{groups}, k > 1`.
seed: (optional) The seed to provide to the RNG.
Returns:
list: a list of length `n_subjects` of integers representing the
groups each subject is assigned to.
Notes:
The value of `block_length` should be a multiple of `n_groups` to
ensure proper balance.
"""
random.seed(seed)
block_form = []
for i in range(0, block_length):
# If n_groups is not a factor of block_length, there will be unbalance.
block_form.append(i % n_groups + 1)
count = 0
groups = []
while count < n_subjects:
random.shuffle(block_form)
groups.extend(block_form)
count += block_length
# If `n_subjects` is not a multiple of `block_length`, only return the
# first `n_subjects` elements of `groups`
return groups[:n_subjects] | d42601d3861f86f7eac4c7525d78e1b4dd4ef81a | 20,990 |
def get_number_features(dict_features):
"""Count the total number of features based on input parameters of each feature
Parameters
----------
dict_features : dict
Dictionary with features settings
Returns
-------
int
Feature vector size
"""
number_features = 0
for domain in dict_features:
for feat in dict_features[domain]:
if dict_features[domain][feat]["use"] == "no":
continue
n_feat = dict_features[domain][feat]["n_features"]
if isinstance(n_feat, int):
number_features += n_feat
else:
n_feat_param = dict_features[domain][feat]["parameters"][n_feat]
if isinstance(n_feat_param, int):
number_features += n_feat_param
else:
number_features += eval("len(" + n_feat_param + ")")
return number_features | 6f81c359cfee77896cb8e4334aa23cf977aaca5a | 20,991 |
def save_gpf(df, output_file):
"""
Write a socet gpf file from a gpf-defined pandas dataframe
Parameters
----------
df : pd.DataFrame
Pandas DataFrame
output_file : str
path to the output data file
Returns
-------
int : success value
0 = success, 1 = errors
"""
# Check that file can be opened
try:
outGPF = open(output_file, 'w', newline='\r\n')
except:
print('Unable to open output gpf file: {0}'.format(output_file))
return 1
#grab number of rows in pandas dataframe
numpts = len(df)
#Output gpf header
outGPF.write('GROUND POINT FILE\n')
outGPF.write('{0}\n'.format(numpts))
outGPF.write('point_id,stat,known,lat_Y_North,long_X_East,ht,sig(3),res(3)\n')
for index,row in df.iterrows():
#Output coordinates to gpf file
outGPF.write('{0} {1} {2}\n'.format(row['point_id'], row['stat'], row['known']))
outGPF.write('{0} {1} {2}\n'.format(row['lat_Y_North'], row['long_X_East'], row['ht']))
outGPF.write('{0} {1} {2}\n'.format(row['sig0'], row['sig1'], row['sig2']))
outGPF.write('{0} {1} {2}\n\n'.format(row['res0'], row['res1'], row['res2']))
outGPF.close()
return | fb551a8e5a3861939bd40cbfcb5a82bd6cc88161 | 20,993 |
def next_node_of_edge(node, edge):
"""
Return the node of the edge that is not the input node.
:param node: current node
:type node: Node object
:param edge: current edge
:type edge: Edge object
:return: next node of the edge
:rtype: Node object
"""
# If the input node is the start node of the edge, return the end node
if edge.node_start.id_node == node.id_node:
return edge.node_end
# If the input node is the end node of the edge, return the start node
if edge.node_end.id_node == node.id_node:
return edge.node_start | 2fd226802ba504bfa7f950d0c69defc79a45e049 | 20,994 |
from typing import List
def consec_badpixels(bad_pixels: List[List[int]]) -> bool:
"""Check for consecutive bad pixels in the same nod.
Consecutive in in axis=1 for the same axis=0 value.
parameters
----------
bad_pixels: list of list of ints
List of index locations of bad pixels [nod, pixel].
returns
-------
is_consec: bool
True if a consecutive bad pixel found."""
for pixel in bad_pixels:
left_pix = [pixel[0], pixel[1] - 1]
right_pix = [pixel[0], pixel[1] + 1]
if (left_pix in bad_pixels) or (right_pix in bad_pixels):
return True
return False | a14e994151c12fa04dca4ce5f6e143d652264dc7 | 21,004 |
def format_pfrule(pfrule):
"""Render port forwarding option."""
format_str = '-{0.pf_type} {binding}'.format
return format_str(pfrule, binding=pfrule.binding) if pfrule else '' | a8e7bec5818586aac945c48ff5553f38f5c444d6 | 21,008 |
def _is_ref(schema):
"""
Given a JSON Schema compatible dict, returns True when the schema implements `$ref`
NOTE: `$ref` OVERRIDES all other keys present in a schema
:param schema:
:return: Boolean
"""
return '$ref' in schema | 1f805929a6b28cf4fbe16714d300f3beffeb6e73 | 21,015 |
def add_one(number):
"""
Example of a simple function.
Parameters
----------
number: int, float, str
Returns
-------
out: int, float, str
The input value plus one. Raises TypeError if the input is not
the expected type
"""
if isinstance(number, (float, int)):
return number + 1
elif isinstance(number, (str)):
return number + '1'
else:
raise TypeError('Expecting an int, float or string.') | d24a5d9e1a02098d1a6638bdc8b5493bc4d732e2 | 21,016 |
import json
def load_settings(settings_fname='settings.json'):
"""
Загрузить настройки из файла
Parameters
----------
settings_fname : str
Имя файла с настройками, по умолчанию имя файла: settings.json
Returns
-------
username : str
Имя пользователя
passw : str
пароль пользователя
root_url : str
URL к API
client_id : str
Идентификатор клиента для доступа к API
client_secret : str
Секрет для доступа к API
auth_server : str
URL к серверу авторизации
"""
if settings_fname is None:
settings_fname = 'settings.json'
with open(settings_fname) as datafile:
jd = json.load(datafile)
return jd['username'], \
jd['passw'], \
jd['root_url'], \
jd['client_id'], \
jd['client_secret'], \
jd['auth_server'] | 63067d6d351bbe799f5e9a839c9e7fba92fe54ef | 21,017 |
def eval_cluster(labels, cluster_id, is_clean):
""" Evaluate true positives in provided cluster.
:param labels: (np.ndarray) array of labels
:param cluster_id: (int) identifier of the cluster to evaluate
:param is_clean: (array) bitmap where 1 means the point is not attacked
:return: (int) number of identified backdoored points
"""
cluster = labels == cluster_id
identified = 0
for i in range(len(is_clean)):
if cluster[i] and is_clean[i] == 0:
identified += 1
return identified | 1499d705bf6a250e214b5f6cac9f1daa3a22d30f | 21,019 |
def iter_dicts_table(iter_dicts, classes=None, check=False):
"""Convert an iterable sequence of dictionaries (all of which with
identical keys) to an HTML table.
Args:
iter_dicts (iter): an iterable sequence (list, tuple) of
dictionaries, dictionaries having identical keys.
classes (str): Is the substitute for <table class="%s">.
check (bool): check for key consistency!
Returns:
str|None: HTML tabular representation of a Python iterable sequence of
dictionaries which share identical keys. Returns None if table
is not consistent (dictionary keys).
"""
# check key consistency
if check:
first_keys = iter_dicts[0].keys()
for d in iter_dicts:
if d.keys() != first_keys:
return None
table_parts = {}
table_parts['classes'] = ' class="%s"' % classes if classes else ''
table_parts['thead'] = ''.join(['<th>%s</th>' % k for k in iter_dicts[0]])
# tbody
keys = ['<td>%(' + key + ')s</td>' for key in iter_dicts[0]]
row = '<tr>' + ''.join(keys) + '</tr>'
table_parts['tbody'] = '\n'.join([row % d for d in iter_dicts])
return '''
<table{classes}>
<thead>
<tr>{thead}</tr>
</thead>
<tbody>
{tbody}
</tbody>
</table>
'''.format(**table_parts) | e1be3d05180eef1a9a039011007413d4fec65301 | 21,020 |
def filter_post_edits(dict_elem):
"""
Filter post history events that modified the body of the posts.
:param dict_elem: dict with parsed XML attributes
:return: boolean indicating whether element modified the body of the corresponding post
"""
return int(dict_elem['PostHistoryTypeId']) in [2, 5, 8] | b8f567d6dceb0dd1deb6cffac631bfc44f0fb282 | 21,023 |
def split_str(string: str, maxsplit: int = 1) -> list:
"""
Splits characters of a String into List of Strings
:param string: String to split
:param maxsplit: It is the number of skips in character before splitting, DEFAULT = 1
:return: Returns the Array containing elements of characters splitted from the String
Example:
>>> split_str("HELLO WORLD", 2)
>>> ['He', 'll', 'o ', 'Wo', 'rl']
"""
txt = ""
str_list = []
for i in string:
txt += i
if len(txt) == maxsplit:
str_list.append(txt)
txt = ''
return str_list | 0d0e2a43c03009c85b2e2fcfa0df8ac4bd241787 | 21,026 |
import collections
def items_to_dict(l, attrs='name', ordered=False):
"""Given a list of attr instances, return a dict using specified attrs as keys
Parameters
----------
attrs : str or list of str
Which attributes of the items to use to group
ordered : bool, optional
Either to return an ordered dictionary following the original order of items in the list
Raises
------
ValueError
If there is a conflict - multiple items with the same attrs used for key
Returns
-------
dict or collections.OrderedDict
"""
many = isinstance(attrs, (list, tuple))
out = (collections.OrderedDict if ordered else dict)()
for i in l:
k = tuple(getattr(i, a) for a in attrs) if many else getattr(i, attrs)
if k in out:
raise ValueError(
"We already saw entry for %s: %s. Not adding %s",
k, out[k], i
)
out[k] = i
return out | 0948ab89944319887661804c78c995adcf306695 | 21,028 |
def median(seq):
"""Returns the median of a sequence.
Note that if the list is even-length, then just returns the item to the left
of the median, not the average of the median elements, as is strictly correct.
"""
seq = sorted(seq)
return seq[len(seq)//2] | c463fa83908606472ead5ef7d56d8b72c7c34edd | 21,033 |
def AddFieldToUpdateMask(field, patch_request):
"""Adds name of field to update mask."""
update_mask = patch_request.updateMask
if not update_mask:
patch_request.updateMask = field
elif field not in update_mask:
patch_request.updateMask = update_mask + "," + field
return patch_request | f8533b38e3ecf7658aa06850869727ab3f34e7de | 21,038 |
def sub_from_color(color, value):
"""Subtract value from a color."""
sub = lambda v: (v - value) % 256
if isinstance(color, int):
return sub(color)
return tuple(map(sub, color)) | 71be1ef8f956ec2c9fdee0516a01833922934aa7 | 21,050 |
import re
def replace_with_null_body(udf_path):
"""
For a given path to a UDF DDL file, parse the SQL and return
the UDF with the body entirely replaced with NULL.
:param udf_path: Path to the UDF DDL .sql file
:return: Input UDF DDL with a NULL body
"""
with open(udf_path) as udf_file:
udf_sql = udf_file.read()
udf_sql = udf_sql.replace('\n', ' ')
pattern = re.compile(r'FUNCTION\s+(`?.+?`?.*?\).*?\s+)AS')
match = pattern.search(udf_sql)
if match:
udf_signature = match[1].replace('LANGUAGE js', '')
udf_null_body = (f'CREATE FUNCTION IF NOT EXISTS {udf_signature}'
f' AS (NULL)')
return udf_null_body
else:
return None | 7a014192b4623ed90f04b50fe52dceb696355c9c | 21,052 |
def create_login_url(path):
"""Returns the URL of a login page that redirects to 'path' on success."""
return "/auth/hello?redirect=%s" % path | 0ba50d443d8cddbbc77ada8a0828cf5a0e534ef1 | 21,053 |
def option_name_to_variable_name(option: str):
"""
Convert an option name like `--ec2-user` to the Python name it gets mapped to,
like `ec2_user`.
"""
return option.replace('--', '', 1).replace('-', '_') | abaf2bb749eed54372233db677f9668c2d486f29 | 21,062 |
def file_unload(file: str):
"""
Open text file, read it's contents and write unpack them into list.
:param file: str -- name of the config file
:return: list -- list of lines read from the file
"""
unpacked_file = []
with open(file, "r") as f:
for line in f:
if line.startswith("#") or line == "\n":
continue
else:
unpacked_file.append(line.strip("\n"))
return unpacked_file | 7bdc61b662796ec2fd7324d4d6934755dc9a2ab7 | 21,075 |
def ez_user(client, django_user_model):
"""A Django test client that has been logged in as a regular user named "ezuser",
with password "password".
"""
username, password = "ezuser", "password"
django_user_model.objects.create_user(username=username, password=password)
client.login(username=username, password=password)
return client | 20e54603e8154cbf9f6c7e0cbd06a78627beecd0 | 21,077 |
def _split_left(val, sep):
"""Split a string by a delimiter which can be escaped by \\"""
result = []
temp = u""
escaped = False
index = 0
left = True
for c in val:
left = False
temp += c
if c == sep[index] and not escaped:
index += 1
else:
index = 0
if c == u"\\":
escaped ^= True
else:
escaped = False
if index >= len(sep):
left = True
index = 0
result.append(temp[:-len(sep)])
temp = u""
if temp or left:
result.append(temp)
return result | c85d8e0e07b9a99ad3f299f44d722c514a11935a | 21,079 |
def parent_directory(path):
"""
Get parent directory. If root, return None
"" => None
"foo/" => "/"
"foo/bar/" => "foo/"
"""
if path == '':
return None
prefix = '/'.join(path.split('/')[:-2])
if prefix != '':
prefix += '/'
return prefix | 261943945531fc348c46c49f5d3081cbd815bfdb | 21,083 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.