content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Optional
import re
def extract_with_pattern(text: str, pattern: str) -> Optional[str]:
"""
Return the first found result of a given pattern in the string or None if not found
E.g: ('Test _t Test _t', '_t') -> '_t'
Args:
text: string to find the match
pattern: patter... | 33df16be02f4e1ece4fe3ea9e0f122cbb5f0a2f2 | 640,453 |
import six
def _annotator_error_msg(ex):
"""
Formats a human readable error message.
:param ex:
:return:
"""
if isinstance(ex, six.string_types):
return ex
return '\n' + ex.__class__.__name__ + ': ' + str(ex) + '\n\n' | 890e6105a2b932e7f7b0280befdb6bb4cf3dd454 | 640,454 |
def FirstValidDatum(data, default=None):
"""Gets the first valid datum or default.
Args:
data (list[event_data.EventDatum]): list of event data.
default (object): returned in case no no valid datum was found.
Returns:
event_data.EventDatum|object: first valid datum or default value.
"""
for datu... | 60a65696d62fffd205750efcda52a2df8cf8301c | 640,461 |
def _getoffsets(lineno, lineindex, data):
"""Return the (start, end) byte offsets for a given 1-based line number."""
offset = 0
if 1 <= lineno < len(lineindex):
offset = lineindex.select(lineno - 1)
else:
raise IndexError
nextoffset = lineindex.select(lineno)
# there is at least one newline, but there may be... | f03408ec2ed7432a38e0f21c217b72b04cdfaa85 | 640,464 |
from typing import Sequence
from typing import Any
from typing import Optional
from typing import Type
def has_types_sequence(item: Sequence[Any]) -> Optional[tuple[Type[Any], ...]]:
"""Returns types contained in 'item'.
Args:
item (Sequence[Any]): item to examine.
Returns:
Optional[... | 0cd65e1d4f10fd4a1aa83ed83d71d7e09f8e8eae | 640,465 |
def get_okta_group_name(prefix, account_id, role_name):
"""
Return an Okta group name specific to an account.
The format of the group name is '<prefix>_<account_id>_role'.
"""
group_name = prefix + "_" + account_id + "_" + role_name
print(f"get_okta_group_name() result is {group_name}")
retu... | 8723bab3addceaf905f889c3239156289314a46d | 640,469 |
def is_ufshost_error(conn, cloud_type):
"""
Returns true if ufshost setting is not resolvable externally
:type conn: boto.connection.AWSAuthConnection
:param conn: a connection object which we get host from
:type cloud_type: string
:param cloud_type: usually 'aws' or 'euca'
"""
ufshost... | 6f48a3792a9860635406f1310d7c4a5ef158d175 | 640,474 |
def get_separator(handle):
""" get the column separator (assumes same on all lines)
"""
current = handle.tell()
line = handle.readline()
handle.seek(current)
if line.count('\t') > line.count(' '):
return '\t'
else:
return ' ' | 57033e4a14a0189666dcb484119c2e6a3566a658 | 640,477 |
def cycle_checker(head):
"""Check if the Singly Linked List is cyclic.
Returns boolean value based on the result
"""
marker_1 = head
marker_2 = head
flag = False
while marker_2 != None and marker_2.next_node != None:
marker_1 = marker_1.next_node
marker_2 = marker_2.next_no... | 6367a9651074a423295cabfef5942a1d14291719 | 640,478 |
import time
def write_generator_lines(conctimes, concaz, concel, concva, concve, az_flags, el_flags):
"""
Produces a list of lines in the format necessary to upload to the ACU to complete a
generated scan. Params are the outputs of generate.
Params:
conctimes (list): List of times starting a... | 2fb671e5111a9b8ee7ca7f64f107e69a69a4dc2c | 640,485 |
from typing import Dict
from typing import Any
from typing import Optional
def to_dot(
config: Dict[str, Any],
prefix: Optional[str] = None,
separator: str = '.',
function_to_name: bool = True,
) -> Dict[str, Any]:
"""Convert nested dictionary to flat dictionary.
:param config:
The po... | 5d08d669c7e9758177b3bcc178581dfef33a9eab | 640,489 |
def is_valid_walk(walk):
"""
You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early
to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens
with a Walk Generating App on their phones -- e... | b556810ddfbaaec8e2b2462606c8da58f978e9cf | 640,491 |
def get_department_average_salary_service(department):
"""
Returns department average salary from db
:param department: department
:return: department average salary
"""
average_salary = 0
if department.employees:
for employee in department.employees:
average_salary += em... | 8149ff4cbb2d0c9e00a1fb6e7bd36db7ce7bee79 | 640,492 |
def get_filter_string(filter_dict):
"""
return a string like _F0_B50 for a dict like {'F': 0, 'B': 50}
"""
return "".join(
"_{}{}".format(k, filter_dict[k]) for k in sorted(filter_dict.keys())
) | 9e6274c7aae56589ec5a3fe1c40aed8068d42747 | 640,493 |
def get_aic(lnL, Nf):
"""
Provides the Akaike Information Criterion (Akaike, 1973), i.e. AIC.
Parameters
----------
lnL : float
Minus the log-likelihood.
Nf : int
Number of free parameters.
Returns
-------
AIC : float
AIC indicator.
"""
AIC = 2 * (... | 4d995f1d41f78238b15ec00c3ee7b66f5a9dafb8 | 640,496 |
def mk_level(ptype):
"""Convert a Pylint warning "type" to a Sarif level"""
ldict = {'error': 'error',
'warning': 'warning',
'refactor': 'note',
'convention': 'note',
'usage': 'note'}
return ldict.get(ptype, 'note') | 1a48a4839d024ae82653c322916884244db84c5f | 640,497 |
def request_json_data(scraper, uri):
"""
A simple helper to return a dict when given the url of a json endpoint
"""
r = scraper.session.get(uri)
if r.status_code != 200:
raise ValueError("Failed to get url '{}' with status code {}.".format(uri, r.status_code))
return r.json() | c4c89dd638a31222b994d11ab6ea9e3b39c2c5dc | 640,501 |
def unzip(ls, nout):
"""Unzip a list of lists into ``nout`` outputs."""
out = list(zip(*ls))
if not out:
out = [()] * nout
return out | 4d8e3b2b6ba875b8d072364caf1bdd8605482f0a | 640,503 |
from typing import Union
def has_output_type(cell, output_type: Union[set, str]):
"""
Select cells that have a given output_type
:param cell: Cell object to select
:param output_type: Output Type(MIME type) to select: text/plain, text/html, image/png, ...
:type output_type: str
:return: a boo... | a51214e0b34783c4a51fff82185c191b8c910486 | 640,504 |
def ns(v):
"""Return empty str if bool false"""
return str(v) if bool(v) else '' | 47b4e9fd2857c42aefaaf92aa2590ad8db33abfd | 640,509 |
def utf8len(s):
"""Returns the UTF-8 encoded byte size of a string. `s` is a string parameter."""
return len(s.encode("utf-8")) | 826e179c2fbd6d6e55ef28b92b86a75e51082c4f | 640,511 |
import base64
def convert_bytes_to_base64(data: bytes) -> str:
"""Convert bytes data to base64 for serialization."""
return base64.b64encode(data).decode("ascii") | a810937ffaf0c40d318d02b3838accb294a5c226 | 640,512 |
def hasHandlers(logger):
"""
See if a logger has any handlers.
"""
rv = False
while logger:
if logger.handlers:
rv = True
break
elif not logger.propagate:
break
else:
logger = logger.parent
return rv | 1715836b43a323cdd92cb33dd80981f1cecc172a | 640,515 |
def values_in_acceptable_entries(sequence, allowed_values) -> bool:
"""Each value in the sequence must be an allowed values. Otherwise, False."""
if len(sequence) == 0:
return True
for item in sequence:
if item not in allowed_values:
return False
return True | c8e1c1aa39cd1d88ed13f48151991d2b0230feb9 | 640,518 |
def int_or_none(value):
"""
Try to make `value` an int. If the string is not a number,
or empty, return None.
"""
try:
return int(value)
except ValueError:
return None | dde9fce68dc9abdb51a5d21416fd7faca26a63a1 | 640,520 |
def get_tensor_parents_placeholders(tensor):
""" Get all placeholders that is depending the given tensor. """
placeholders_list = []
if tensor.op.type == 'Placeholder':
placeholders_list.append(tensor)
if tensor.op:
for t in tensor.op.inputs:
if not 'read:0' in t.name:
... | fe32db36ca4c299006e82fcef836e88a8ce7b8d0 | 640,523 |
def bedtxt2dict(pybed, strand_col=5):
"""
convert bed object to a dict with keys in bed file
From
chr123 123 123 +
To
('chr123', 123, '+') -> 1
:param pybed: bed object
:return:
"""
ret_dict = {}
for t in pybed:
ret = str(t).strip().split('\t')
key = (ret[... | 1e52add179a7c3011d0901c5dc7474765d7b4d89 | 640,525 |
def word_count(data):
"""
输入一个列表,统计列表中各个元素出现的次数
参数
----
data : list, 需要统计的列表
返回
----
re : dict, 结果hash表,key为原列表中的元素,value为对应的出现次数
"""
re = {}
for item in data:
re[item] = re.get(item, 0) + 1
return re | 57c90aaac8252cb0085bb946c6e66572e2c534bb | 640,527 |
def getRunFilename(sessionId, runId):
"""Return run filename given session and run"""
filename = "patternsData_run-{0:02d}_id-{1}_py.mat".format(runId, sessionId)
return filename | 623ad10430f3a165ab277c069ef75b86c9bf7e66 | 640,532 |
def lambda_handler(event, context):
"""Sample pure Lambda function
"""
return "Hello from a Lambda Image!" | ecf003ce92c2b41055f30fbe26a7bf5392039098 | 640,533 |
def _is_datetime_dtype(obj):
"""Returns True if the obj.dtype is datetime64 or timedelta64
"""
dtype = getattr(obj, 'dtype', None)
return dtype is not None and dtype.char in 'Mm' | b45eb6749ef2703358f9c9fe65d47d5c92543342 | 640,535 |
def get_selected_scenarios_in_cache(request, proj_id):
"""Given a request and the project id returns the list of selected scenarios"""
if isinstance(proj_id, int):
proj_id = str(proj_id)
selected_scenarios_per_project = request.session.get("selected_scenarios", {})
selected_scenario = selected_s... | 8629cc73a76cc797da335925e9f40f5ac77e8b85 | 640,537 |
def find_ids(df, id_column: str):
"""
Reads a dataframe and returns a list of unique data from the id_column.
"""
return list(set(df[id_column])) | 9ff197808ac1f1167f0ac22af59aa1ccb7271920 | 640,546 |
def text_in_text(entity, attribute, value):
"""
Return ``True`` if the provided entity has the string provided in
``value`` within its text attribute.
"""
try:
return value.lower() in entity.text.lower()
except (UnicodeDecodeError, TypeError):
# Binary tiddler
return Fals... | 12be5d3cbdb884735e17929c9f365bd8cde391fa | 640,552 |
import re
def unstring(obj):
"""
Attempt to parse string to native integer formats.
One can't simply call int/float in a try/catch because there is a
semantic difference between (for example) 15.0 and 15.
"""
floatreg = "^\\d+.\\d+$"
match = re.findall(floatreg, obj)
if match != []:
... | 79c8f660ca4318c6575688e864ba5bb9284f1629 | 640,554 |
from typing import List
from typing import Optional
from typing import cast
def _mask_positional_args(name: str) -> List[Optional[str]]:
"""Create a section name representation that masks names
of positional arguments to retain their order in sorts."""
stable_name = cast(List[Optional[str]], name.split("... | 0590040ea6d5ba1a24886b9ce653322b7a258350 | 640,560 |
def level_list(root):
"""Get full level order traversal of binary tree nodes.
Example:
>>> from leetcode_trees import binarytree
>>> tree = binarytree.tree_from_list([5,1,4,None,None,3,6])
>>> binarytree.print_tree(tree)
___5___
1 _4_
3 6
>>> print(binarytree.level_representation(tree))
[[... | f53c14c5b195a6d0b5364c5258bd2576f1fabe66 | 640,564 |
from typing import List
def get_requirements() -> List[str]:
"""Read requirements.txt and return the requirements.
Returns:
List[str]: List of requirements.
"""
requirements = []
with open("requirements.txt", "r", encoding="utf8") as file:
for line in file.readlines():
... | aa2c2a7d8053c304d1faebdd47a48794b5f6fada | 640,566 |
def is_nan(x):
"""
Returns `True` if x is a NaN value.
"""
if isinstance(x, float):
return x != x
return False | 342d64791986da9a1c0c0ee706bbc793539d6367 | 640,567 |
def check_edge(e,q,fsm):
"""
checks whether the current state q has an out-edge e. If so returns the state it goes to and the probability; otherwise returns None
Arguments
e : we're checking to see if there's an edge with this label
q : the current state
fsm : the fsm
Returns
... | d55ac87e904c17bbbd4e6a191e6468ce6fed6ac5 | 640,568 |
def total_rows(cursor, table_name, print_out=False):
""" Returns the total number of rows in the database """
cursor.execute('SELECT COUNT(*) FROM {}'.format(table_name))
count = cursor.fetchall()
if print_out:
print('\n[+] Total rows in database: {}'.format(count[0][0]))
return count[0][0] | cbd6d97e241d3f9b7043d26d2cd224a68dc90cef | 640,571 |
import time
def format_date( unixTime ):
""" format epoch time stamp as string """
return time.strftime("%Y/%m/%d %H:%M", time.gmtime(unixTime)) | 5f2d1f167a0a4245dca471d590490069a73df84e | 640,572 |
def sort_fragments_by_elf10wbo(frags):
"""
Sort fragments by ELF10 WBO. This helps with plotting all distributions so the distributions of the different
clusters are together
Parameters
----------
frags : dict
{'smiles': {'ensamble': , 'individual_confs': []}
Returns
-------
... | 1b2ad490f47421a5ca2695b0713b0ead59f6f58f | 640,573 |
import re
def get_exclude_patterns_as_regex_list(exclude_patterns=None):
"""
Takes a list of strings are returns a list of compiled regexes.
Strips enclosing quotes if present.
:type exclude_patterns: list[str]
:return:
:rtype: list[re.__Regex]
"""
exclude_regexes = []
if exclude_... | 4de3c0e34540e326e5d95e00fc5dc738b7fe3f17 | 640,578 |
def decorated_test_task_with_decorator_args(**kwargs):
"""
Test task, echos back all arguments that it receives.
This one is registered using a decorator
"""
print(f"The decorated (with args) test task is being run with kwargs {kwargs} and will echo them back")
return kwargs | bc6cd92a7df6634834756ca391536fc86818e72c | 640,579 |
def separator(simbol, count):
"""
Функция создает разделитель из любых символов любого количества
:param simbol: символ разделителя
:param count: количество повторений
:return: строка разделитель примеры использования ниже
"""
s = simbol * count
return s | bdf9b7ac533eaec26552a3ed6238f239caac9d21 | 640,582 |
def eq_by(f, value_1, value_2):
"""Check if two values are equal when applying f on both of them."""
return f(value_1) == f(value_2) | 2ea1d66fdadf8cc8d9b31ec358b90e8e579263b6 | 640,583 |
from pathlib import Path
def read_markdown(fpath: Path) -> str:
"""Read Markdown file as a string."""
with open(fpath, "r+") as f:
md = f.read()
return md | 1723a43eacefd780c7a38caa5591e48bad8fdf85 | 640,584 |
def parse_contig_assignments(assignment_file_path, contig_name_col=0, unassigned_col=9):
"""
Finds contig_names that are unassigned twice.
Inputs:
- assignment_file_path: Path to tab-delimited file
- contig_name_col: Index of the col which will have the contig name
- unassigned_col: Index of th... | 49cca60afaadcf0e665b65e7fab08f1e186c3785 | 640,589 |
def create_name(words):
""" Concatenate words to create the title name. """
return ' '.join(words).title() | ace7c8c4ea3015f0f6ad346408ffff60b588cd99 | 640,591 |
def covstr(strings):
""" convert string to int or float. """
try:
result = int(strings)
except ValueError:
result = float(strings)
return result | c4784b6f7529d124ea4f8d8725985a9662e10ba6 | 640,593 |
def create_dataset_url(base_url, identifier, is_pid):
"""Creates URL of Dataset.
Example: https://data.aussda.at/dataset.xhtml?persistentId=doi:10.11587/CCESLK
Parameters
----------
base_url : str
Base URL of Dataverse instance
identifier : str
Identifier of the dataset. Can be... | 47116663bd851d380e7de807b3a5e544302936d1 | 640,597 |
import base64
def from_url_safe_stream_id(stream_id: str) -> str:
"""Convert the URLSafe encoded stream id to the corresponding original stream id
:param stream_id: streamId of the stream to be parsed
:return: stream id after conversion
"""
decoded_url_bytes = base64.urlsafe_b64decode(stream_id +... | 3cbeabb40431f999fa4ed9ebf9698ec670a45f9f | 640,598 |
def remove(seq1, seq2):
""" remove the elements in `seq2` from `seq1`
"""
return tuple(elem for elem in seq1 if elem not in seq2) | 49ab05fec0304aca078f419dfee0cb5fab38d5f5 | 640,602 |
def empty_prep_nb(context, *args):
"""Preparation function that forwards received arguments down the stack."""
return args | 8f7c11f24aef5ab039bf3d2f870844d0203dd066 | 640,607 |
def outline(text: str, outline_clr=[10,10,10], text_clr=[250,250,250]) -> str:
""" Creates a colored outline around the given text.
Requires the "contour" package in the preamble, preferably with the [outline] option. That is:
\usepackage[outline]{contour}
Currently, this package is not included by de... | cd6851d842a589228a7a41e3f3f771b2239a3d31 | 640,612 |
def fetch_licenses(fw_conn):
"""Fetch Licenses
Args:
fw_conn (PanDevice): A panos object for device
"""
try:
fw_conn.fetch_licenses_from_license_server()
print('Licenses retrieved from Palo Alto Networks')
return True
except:
print('WARNING: Not able to retri... | 52b62f45895f3a3a211d034dca491e2d8efab230 | 640,613 |
import re
def squashed(s):
"""Remove all of the whitespace from s."""
return re.sub(r"\s", "", s) | a6172c1cb1cfe796d23515e42ec6545fadbfbe14 | 640,616 |
def add_two(num):
"""Add two to num"""
return num + 2 | fb1bd640c0e4787c74ebdd2f503cf0170629fd8c | 640,618 |
from pathlib import Path
import pkg_resources
def get_path_of_data_dir() -> Path:
"""
get the path of the package data directory
:returns:
"""
file_path: str = pkg_resources.resource_filename(
"{{ cookiecutter.project_slug }}", "data")
return Path(file_path) | 4f4bc73003d1545ffdd9bce85bb3862ea39aa538 | 640,619 |
def _DictToString(dictionary):
"""Convert a dictionary to a space separated 'key=value' string.
Args:
dictionary: the key-value dictionary to be convert
Returns:
a string representing the dictionary
"""
dict_str = ' '.join(' {key}={value}'.format(key=key, value=value)
for key, ... | 43579b56919fba318654d4d8bce25e093a67c687 | 640,625 |
def create_edges(dc):
"""
Create edges (lines) connecting each pair of stars
Arguments
---------
dc : dictionary of constellations
Returns
-------
edges : list of all edges
"""
edges = []
for k,v in dc.items():
for i in v:
edges.append(i)
... | 7cb856f08abbf7c412d94449bfef17cf453e274c | 640,633 |
from typing import Union
from typing import List
def get_verbalization_ids(word: str, tokenizer, force_single_token: bool) -> Union[int, List[int]]:
"""
Get the token ids corresponding to a verbalization
:param word: the verbalization
:param tokenizer: the tokenizer to use
:param force_single_tok... | 9989d3489b1ba5d528303d0dc64179526749e086 | 640,634 |
import re
def normalize_reference(s):
"""
Normalize reference label: collapse internal whitespace
to single space, remove leading/trailing whitespace, case fold.
"""
return re.sub(r'\s+', ' ', s.strip()).upper() | 15ff7e40ba318c2ac6de8cd3548f5c1980bd7be6 | 640,636 |
import json
import re
def generate_suppression(filepath: str) -> str:
"""Generate an example suppression document for the given file."""
return json.dumps(
{
"include": [],
"ignore": [
{
"pattern": f"{re.escape(filepath)}$",
... | 8ed58de36eba53e33f3029850fc67072f711b1d8 | 640,637 |
def update_bathrooms_slider(area):
"""
Update bathrooms slider to sensible values.
"""
return [1, min(int(area / 40) + 1, 5)] | ffb63e4ec0ff00d6bb6ab4105c816d688cf403ab | 640,639 |
from pathlib import Path
def extend_path(path: Path, extension: str) -> Path:
"""Extends a path by adding an extension to the stem.
Args:
path (Path): Full path.
extension (str): Extension to add. This will replace the current extension.
Returns:
Path: New path with extension.
... | 65df8265b7a5b5896cbab9b13ef6b598b6132227 | 640,642 |
def get_html(html: str):
"""Convert HTML so it can be rendered."""
WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>"""
# Newlines seem to mess with the rendering
html = html.replace("\n", " ")
return WRAPPER.... | be2a2f7fa1d6e3c2643673442028521c796b70d2 | 640,644 |
def _insert_idxs(feature_centre, feature_size, dimensions):
"""Returns the indices of where to put the signal into the signal volume
Parameters
----------
feature_centre : list, int
List of coordinates for the centre location of the signal
feature_size : list, int
How big is the s... | a1e514cfb9625cb2d42055b4284f602e625ee15e | 640,645 |
def get_user_nick(user):
"""Returns the nickname of the passed user, the name otherwise"""
if user.nick is None:
return user.name
return user.nick | 504a233b372644144ece22696140aeb1660e13b1 | 640,646 |
def xdist_molar(xdist_mass, Massl, Massh):
"""
Calculates the molar concetration distilliat of liquid.
Parameters
----------
xdist_mass : float
The mass concetration distilliat of liquid, [kg/kg]
Massl : float
The molar mass of low-boilling component, [kg/kmol]
Massh : float
... | 8737a837f193a44e0028abe144c5f675464f897e | 640,648 |
def calc_pct_reliability(df_pct):
"""
Calculates percent reliability of interstate and non-interstate network.
Args: df_pct, a pandas dataframe.
Returns: int_rel_pct, % interstate reliability.
non_int_rel_pct, % non interstate reliability.
"""
# Auto, Bus interstate
df_int = d... | e5c0806f21a42cfde5a9fe5d5af3906adfa775b3 | 640,652 |
def get_corr(d):
"""
Calculate correlation between SibSp and Parch
:param d: data frame
:return: rounded correlation
"""
return round(d.filter(items=['SibSp', 'Parch']).corr(method='pearson'), 2) | 2277a6d2d8965bab75b03d6c14fe24bcb112f626 | 640,653 |
def _remove_invalid_char(s):
"""Remove invalid and dangerous characters from a string."""
s = ''.join([i if ord(i) >= 32 and ord(i) < 127 else '' for i in s])
s = s.translate(dict.fromkeys(map(ord, "_%~#\\{}\":$")))
return s | 614fcc1aaf59c3be796ce3b0cbd69d9df6d9350c | 640,655 |
def _doMatchExcept1(inv, atoms):
""" Helper function to check if two atoms in the list are the same,
and one not
Note: Works only for three atoms
Arguments:
- inv: atom invariants (used to define equivalence of atoms)
- atoms: list of atoms to check
Return: atom that i... | 639774acbc86981ca6a241987ef7a95855793c35 | 640,663 |
import typing
def unpack_key_value_pair(entry) -> typing.Tuple[object, object]:
"""ensure the given entry can be unpacked into a key/value pair
:param entry: an iterable element with exactly two elements
:return: a tuple containing the key value pair
:raises: ValueError when the entry can't be unpack... | 8094e4d58439c6ea91fafd12b06b3c0104af003c | 640,665 |
def value_if_found_else_key(some_dict, key):
"""Lookup a value in some_dict and use the key itself as fallback"""
return some_dict.get(key, key) | c02f50851908df0aa03c1c850f1e52f710bce3ce | 640,669 |
def unitstep(t):
"""Returns the unit step function: ``u(t) = 1.0 if t>=0 else 0``"""
return 1.0 if t >= 0 else 0.0 | 5f9d39cccdc673cff8f1c691499cc5b3689689f5 | 640,670 |
def getRowMarker(f, year):
""" Get the row marker for given year
(where the most recent update left off) and return.
Returns 0 if doesn't exist. """
dset = f['data']
marker = 0
if "_row_marker" in dset.attrs:
row_marker = dset.attrs["_row_marker"]
# returns [year, row]
... | ccd1857f23d5cb70ab869719b7bc106f182b778e | 640,671 |
def strokes_to_lines(strokes):
"""Convert stroke-3 format to polyline format."""
x = 0
y = 0
lines = []
line = []
for i in range(len(strokes)):
if strokes[i, 2] == 1:
x += float(strokes[i, 0])
y += float(strokes[i, 1])
line.append([x, y])
l... | 61eafa7fdc9e010220251fdf3ced0a0bf6286afc | 640,673 |
def uncomposekey(prefix, key):
"""Remove a prefix from a composite key.
Example: uncomposekey("attr1.attr2", "attr1.attr2.attr3.attr4") == "attr3.attr4"
"""
if " " in prefix or " " in key:
raise NotImplementedError()
prefix, key = prefix.split("."), key.split(".")
while prefix:
a, b = prefix.pop(0)... | 748b1f03dcdb46483d54b3aac44523911b450da0 | 640,682 |
def fw_action(raw):
"""Normalize firewall action
Gives back a value between allow, deny, reject and other
"""
lower = raw.lower()
if lower in ['allow', 'deny', 'reject']:
return lower
return 'other' | 3cc1d93712dba75e501d915a4c6319b038073aec | 640,683 |
import torch
def split_tensor_pos(tensor):
""" Splits tensor into positive and negative terms """
zeros_like = torch.zeros_like(tensor)
pos_tensor = torch.max(tensor, zeros_like)
neg_tensor = torch.min(tensor, zeros_like)
return pos_tensor, neg_tensor | e3f1b013949b38a88185aeaaec45cb60891753a2 | 640,685 |
import random
def randomly_true(probability: float) -> float:
"""
Return True with a given probability, False otherwise.
"""
return random.uniform(0,1) < probability | 835fc2367b8fca9d524aaec110d523d4f55f397f | 640,686 |
def numeric_filter(operation, value, column, df):
"""Filters a data column numerically.
Arguments:
operation: Operator used to filter data (e.g. ">", "<", "==", ">=", "<=", "!=")
value: Operand
column: String for column name
df: DataFrame
Returns: Boolean column that indicates whether each... | 868907d2fed5947c0974896af73a9277fcef0ae8 | 640,693 |
def webpage_attribute_setter(attr):
""" Helper function for defining setters for web_page attributes, e.g.
``set_foo_enabled = webpage_attribute_setter("foo")`` sets
a value of ``webpage.foo`` attribute.
"""
def _setter(self, value):
setattr(self.web_page, attr, value)
return _setter | 9c5d0f7ec8d7cec531c414071088a4f848628027 | 640,695 |
def meanOffNadirViewAngle(xmlroot):
"""Get the mean off nadir view angle from the xml."""
return float(xmlroot.find('IMD/IMAGE/MEANOFFNADIRVIEWANGLE').text) | 3df2a26dceabb36d944040fd31541339e1ead183 | 640,696 |
def truesi(xs):
""" indices for which x[i] is True """
return [i for i, x in enumerate(xs) if x] | a037f61eddb7a77e536a20843b587ccb62bd7d4e | 640,698 |
def create_event(event_type, data):
"""Return a dictionary containing the properties required when defining an
event.
Keyword arguments:
event_type -- the type of event, used to distinguish multiple events apart.
data -- a dictionary of key/value pairs containing custom data.
"""
return {
... | 5bff5b0b860a56c00ab83928939369a7e339ad73 | 640,699 |
def resize_bbox(bbox, in_size, out_size):
"""
Resize bounding boxes according to image resize.
:param bbox (numpy.ndarray): An array that has a shape (R, 4),
'R' is the number of the bounding boxes.
'4' indicates the position of the box, which represents
(y_min, x_min, y_max, x_max)
... | e6d1f97e2625f8dee78fe78fe608087a52701fbe | 640,701 |
def strip_spaces_list(list_in, strip_method="all"):
"""
Remove spaces from all items in a list
:param list_in:
:param strip_method: Default: 'all' for leading and trailing spaces.
Can also be 'leading' or 'trailing'
:return: List with items stripped of spaces
"""
if strip_method == "all... | f6d60e8a847f7f339784066e39807caaa63c426c | 640,709 |
def LinearReconstruct( u_stencil ):
"""Linear reconstruction with linear weights. This reconstructs u_{i+1/2}
given cell averages \\bar{u}_i at each neighboring location.
See (2.14) in `High Order Weighted Essentially Nonoscillatory Schemes for
Convection Dominated Problems'.
"""
uim2, u... | 9564cedf70dbf59a5997960f4db1153f7a90d21e | 640,711 |
def compute_avg_wmd_distance(contexts1, contexts2, gensim_obj):
"""
Compute an average word metric distance
:param contexts1: List of ContextAndEntities objects extracted from Document 1
:param contexts2: List of ContextAndEntities objects extracted from Document 2
:param gensim_obj: a Gensim object... | 4cf65eab5ff15cb96560d01a5e4268874a9f3c01 | 640,712 |
from typing import Dict
import torch
def default_fn(x, models, **kwargs) -> Dict[str, torch.Tensor]:
"""
The default inference function for [BaseAdapter][pytorch_adapt.adapters.BaseAdapter].
"""
features = models["G"](x)
logits = models["C"](features)
return {"features": features, "logits": lo... | b020a629385abf410c30a1850fce4b04c8e181e2 | 640,715 |
def merge_dico_in_first(d1, d2):
"""
Merge dictionary d2 in d1.
"""
for k, v in d2.items():
if k in d1:
raise ValueError(f"Key {k} should not be in d1")
else:
d1[k] = v
return d1 | 1de21618882eccf2e6482271cc98497060e43669 | 640,718 |
def json_config(json_sample_path):
"""Return a list containing the key and the sample path for a json config."""
return ["--config", json_sample_path] | e609ad7aae09fc0ea3acd19d8b22e08a0f362789 | 640,720 |
from typing import Iterable
from typing import List
from typing import Any
def flatten(iterable: Iterable, drop_null: bool = False) -> List[Any]:
"""Flatten out a nested iterable.
Flatten a nested iterable, even with multiple nesting levels and
different data types. It is also possible to drop null value... | e33dafe1e6db2a020d4eb143da2c17110c1e2733 | 640,722 |
def get_routes(feed, date=None, time=None):
"""
Return a subset of ``feed.routes``
Parameters
-----------
feed : Feed
date : string
YYYYMMDD date string restricting routes to only those active on
the date
time : string
HH:MM:SS time string, possibly with HH > 23, res... | 6a14d78775d0fc84d3bf6cea0d5590e9d5505a9c | 640,723 |
def forecasted_occlusion_position(occlusion_bool_list):
""" Given a boolean list of occlusion events, return the index position of the forecasts
that indicate that an occlusion event has been predicted. """
positional_list = []
for i in range(len(occlusion_bool_list)):
if occlusion... | 94cbdc6812ce2da1eba873e9860800800f35e741 | 640,729 |
import re
def _get_name(name):
"""Internal Method to Change camelcase to
underscores. CamelCase -> camel_case
"""
return re.sub('(?!^)([A-Z]+)', r'_\1', name).lower() | 341cfa2611393a23dde80d66fac1598e2b1c4dd3 | 640,732 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.