content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def GetNewIssueStarrers(cnxn, services, issue_id, merge_into_iid):
"""Get starrers of current issue who have not starred the target issue."""
source_starrers = services.issue_star.LookupItemStarrers(cnxn, issue_id)
target_starrers = services.issue_star.LookupItemStarrers(
cnxn, merge_into_iid)
return set(... | 403fdf91bc8dd1df347217efa10467b8829bac54 | 629,506 |
def computeF(V_max, rho_max, rho):
"""Computes flux F=V*rho
Parameters
----------
V_max : float
Maximum allowed velocity
rho : array of floats
Array with density of cars at every point x
rho_max: float
Maximum allowed car density
Returns
-------
... | a18869e3c13a7c6dca556a1b861bf655101327f7 | 629,508 |
def get_atomic_number(molecule, atom_index):
"""Get the atomic number of an atom for a specified index.
Returns the atomic number of the atom present at index atom_index.
Parameters
----------
molecule : Molecule
The molecule to which the atom belongs.
atom_index : int
Index of... | 00b232fff40237203a77ae15f5c2e422304a581b | 629,510 |
def uri_sort_key(uri):
"""return a sort key for the given URI, based on whether it represents the primary work in the record"""
if uri.startswith('http://urn.fi/URN:NBN:fi:bib:me:'):
priority = int(uri[-2:]) # last two digits are 00 for the primary work, 01+ for other works mentioned
else:
p... | 2223ca084af9b81cb5ce24fdb6c671038973be85 | 629,514 |
def _from_stdin(prompt, default=None):
"""
Read from stdin, if default is not set to None, some input is expected.
Parameters
----------
prompt: str
The stdin prompt.
default:
Default value.
Returns
-------
value read
"""
while True:
return_val =... | 4aa6ebe6a346b0f712c0631d2c41906b300106d6 | 629,516 |
def get_ticket_detail(tickets):
"""
Iterate over ticket details from response.
:param tickets: ticket details from the response.
:return: List of ticket details which include required fields from resp.
"""
return [{
'TicketNumber': ticket.get('ticketNumber', ''),
'TicketStatus':... | 6c908863086b4f51d913fa6cee76c22ba9fb3a01 | 629,517 |
def _get_local_cache_repo_path(repo_ctx):
""" Return a default local path to clone the repository into else return the cache_directory attribute if supplied
(default location: $HOME/.git-cache/<repo-name>)
Args:
repo_ctx: Repository context of the calling rule
Returns:
... | fa01762f48dc97959ba3ccd696182167dcbacd22 | 629,519 |
def _get_col_that_is_primary(common_cols, featuregroups):
"""
Helper method that returns the column among a shared column between featuregroups that is most often marked as
'primary' in the hive schema.
Args:
:common_cols: the list of columns shared between all featuregroups
:featuregro... | f9bdab097c73bc1a447e02d1929f5e9b4804c717 | 629,522 |
def ordinal_suffix(n):
"""The ordinal suffix of integer *n* as a string."""
if n % 100 in [11, 12, 13]:
return 'th'
else:
return {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th') | eb96c4c4497831f9480c4e03b00b0786eb826526 | 629,526 |
def get_dims(slices):
"""Given a set of slices, gets number of pixels along x,y,z of reconstructed
volumetric image."""
ds = next(iter(slices)) #Takes an arbitrary element of slices
x_count = ds.Rows
y_count = ds.Columns
z_count = len(slices)
return (x_count,y_count,z_count) | b57742195aaa43249bc689e70f6dbd33b5cb5793 | 629,529 |
from typing import List
def pessimistic_aggregation(alternative_assessment: List[int]) -> int:
"""
Aggregates the assessments of an alternative, using the minimum as aggregation function.
Args:
alternative_assessment: A list of integers, representing the assessments made of an alternative by a gr... | 29cf146e87e9d35fbb3e87ab82b0e0ea510e7234 | 629,531 |
import math
def complexLog(value, base = math.e):
"""Computes the log of a complex number."""
mag = (value*value.conjugate()).real**.5
tan_theta = value.imag/value.real
theta = math.atan(tan_theta)/math.log(base, math.e)
return complex(math.log(mag, base), theta) | 6af6e965b82e5755dd3a76da06ac30c584fa75f1 | 629,537 |
def team_sign(team: int) -> int:
"""Gives the sign for a calculation based on team.
Arguments:
team {int} -- 0 if Blue, 1 if Orange.
Returns:
int -- 1 if Blue, -1 if Orange
"""
return 1 if team == 0 else -1 | 41b5e9983212fc866fe596b9df9ef8ba6de1630d | 629,538 |
def _get_pt_to_obj(cvt_archive):
"""Creates a dict from centroid index to objective value in a CVTArchive."""
data = cvt_archive.as_pandas(include_solutions=False)
pt_to_obj = {}
for row in data.itertuples():
# row.index is the centroid index. The dataframe index is row.Index.
pt_to_obj[... | 1b975388f5d0d08735f3618ed2d8b6cd3da10f5e | 629,539 |
def apply(func, args, kwargs):
"""
a helper method that applies args and kwargs to given function and gets the result.
:param function func: function to be used.
:param tuple args: function positional arguments.
:param dict kwargs: function keyword arguments.
:returns: function result
"""
... | 37b2f1ee85c195398c608cc1ae6946e0940cfe77 | 629,545 |
def _get_translated_node(target_node, target_dom_to_doc_dom):
"""Convenience function to get node corresponding to 'target_node'
and to assign the tail text of 'target_node' to this node."""
dom_node = target_dom_to_doc_dom[target_node]
dom_node.tail = target_node.tail
return dom_node | 8b356c8acddbad1279b066ebc36a8799994558c3 | 629,547 |
def tree_child(tree, cname):
"""Locate a descendant subtree named cname using breadth-first search and
return it. If no such subtree exists, return None."""
for st in tree.iter_subtrees_topdown():
if (st.data == cname):
return st
return None | 43979bdc05a14cfa3f854cc798bdbfb6e59963e9 | 629,552 |
def explicit_transform(tarinfo):
""" Reject files with 'bar' anywhere in their path """
if 'bar' in tarinfo.name:
return False
else:
return tarinfo | e0d58c825ea3ea9ceb862789bc0799d5e5e964b3 | 629,553 |
def _Append(text):
"""Inserts a space to text if it is not empty and returns it."""
if not text:
return ''
if text[-1].isspace():
return text
return ' ' + text | a8e879cdda734387bf0f8dbbb7b80bf93ab01bcd | 629,557 |
def dict_recursive_update(existing_dict: dict, new_dict: dict):
"""
Recursively add values from new_dict to existing_dict.
:param existing_dict: existing dict to be updated
:param new_dict: new values to enter if an existing value does not already exist.
:return: udpated dict
"""
for key, va... | a4406d5e6212450dde98fb98ad5b37227c3cd435 | 629,560 |
def sort_list_by_keys(values, sort_keys):
""" Sorts list values by a second list sort_keys
e.g. given ["a","c","b"], [1, 3, 2], returns ["a", "b", "c"]
Args:
values: a list of values to be sorted
sort_keys: a list of keys to sort values by
Returns:
list of values, sorte... | 59dfd2399d11c36f200f6b9b1186991f460f7004 | 629,562 |
import torch
def get_traversals(
vec: torch.Tensor,
dim_i: int,
min_value: float,
max_value: float,
n_samples: int
) -> torch.Tensor:
"""Given a single 1dim vector, get a batch of 1dim vectors by traversing
`dim_i`th dimension of `vec` linearly, from `min_value` to `max... | b17d316a913cea4e8c06039363e2becdfd9f88e4 | 629,564 |
def leftshift(x, c):
""" Left shift the number x by c bytes."""
return x << c | dfb620c42c978b1737ebc2a2039e1285054727be | 629,566 |
import torch
def generate_softmax_labels(rois, keyps, label_h, label_w):
"""
Arguments:
rois (FloatTensor): [R, 4]
keyps (FloatTensor): [R, K, 3], (x, y, v)
label_w, label_h (int): label size
Returns:
labels (LongTensor): [R, K]
"""
assert (rois.shape[0] == keyps.s... | d0885eda07a4452ca12b687aaa79f0940e86f884 | 629,569 |
from typing import Optional
import binascii
def crc32(path) -> Optional[int]:
"""
Compute the CRC-32 checksum of the given *path*, consistent with
checksums stored in a ZIP file.
Returns None if *path* does not exist.
"""
if path.exists():
crc = 0
# Directories always return ... | 6abe3c9677df06c65bd9fec491fcb457dc073d0f | 629,570 |
def ar_to_vaf(ar):
"""
Convert AR to VAF.
VAF (variant allele frequency) = V-AF
AR (allele ratio) = V-AF / WT-AF
V-AF + WT-AF = 100 (%)
Args:
ar (float): AR to convert.
Returns:
VAF (float)
"""
return ar/(ar + 1) * 100 | 681919548d827fcf551970e68545f37c89512e85 | 629,575 |
import torch
from typing import Tuple
def pack_right_padded_seq(seqs: torch.Tensor, lengths: torch.Tensor, device: str) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Function for packing a right-padded sequence, inspired by the functionality of
torch.nn.utils.rnn.pack_padded_sequence.
Instead of relying o... | 52f151174cc81a23ddbdbeddfd57d8e1d2ba11a2 | 629,577 |
def reward_lives_left(lives_left):
"""Returns rewards for number of lives left after beating the game."""
return lives_left + 1 | edc421f1388b44e97d00f8c382533a5d3756c547 | 629,578 |
def clean_attrib(value):
"""Cleans up value string.
Removes any trailing '_0' that randomly show up
Args:
value (str): attrib value to clean
Returns:
str: cleaned attribute value
"""
clean_value = value
if value.endswith("_0"):
clean_value = clean_value.strip('_0')... | b97bacf819260b9dce08fb0edcf68e0166838be2 | 629,579 |
def _remove_nones(**kwargs):
"""
Removes any kwargs whose values are `None`.
"""
final = kwargs.copy()
for k in kwargs:
if kwargs[k] is None:
final.pop(k)
return final | 787a3aba60a3651aa5b8fafcff359c9011f741b9 | 629,580 |
import re
def get_xml_attrib(el, key):
"""Gets an Element attribute value without regard to namespace.
Returns:
Value of given key or None.
"""
for k in el.attrib.keys():
if key == re.sub("^{.*}", "", k):
return el.attrib[k] | 1e1bcf0325b8312cd19fb1a4f48781e8da964ea4 | 629,582 |
def _merge_dicts(*dicts):
"""Merge any number of dictionaries, some of which may be None."""
final = {}
for dict in dicts:
if dict is not None:
final.update(dict)
return final | 1d8a4831bc9ccd2e8ff1b98c7db004312b21d32c | 629,586 |
from typing import Optional
import re
import click
def validate_version_string(ctx, param, value: Optional[str]) -> Optional[str]:
"""
Callback for click commands that checks that version string is valid
"""
if value is None:
return None
version_pattern = re.compile(r"\d+(?:\.\d+)+")
... | 22e084403cfa2ff72c003de53fe6b17c5dc03319 | 629,587 |
def list_policies(iot_client, old_certificate_arn):
"""
Creates a list of all the policies attached to the old certificate
:param iot_client: the boto client to connect and execute
IoT APIs
:param old_certificate_arn: the old certificate arn
:return: list of policies
"""
policy_list = []... | 0d8ac00434bf57c1eca5d47c7decac0e594d51cd | 629,590 |
from datetime import datetime
def execution_time(func):
"""Decorator to print in console the execution time of the 'func' function passed."""
def wrapper(*args, **kwargs):
t0 = datetime.now()
res = func(*args, **kwargs)
t1 = datetime.now()
print(f"\nExecution time of '{func.__n... | bd0d1b60ceddcdba7fa8562f3fdb691e23c946cf | 629,596 |
def args_from_constants(constants):
"""
>>> c = {
... "proof_of_work_nonce_size": 8,
... "nonce_length": 32,
... "max_anon_ops_per_block": 132,
... "max_operation_data_length": 32768,
... "max_proposals_per_delegate": 20,
... "max_micheline_node_count": 50000,
... | 2d460c57abae5e508c554bc9b36cddc603d71b3b | 629,598 |
def get_description_value(obj):
"""
Returns object description from LLDB value.
:param lldb.SBValue obj: LLDB value object.
:return: Object description from LLDB value.
:rtype: str | None
"""
desc = None if obj is None else obj.GetObjectDescription()
if desc == "<nil>":
desc = N... | d37541b82514a9beb06a393b6ee2743c2f495822 | 629,599 |
import pathlib
import json
def get_archiver_index(config, archiver):
"""
Get the contents of the archiver index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
... | e6cf45201a3858effd25b3e2b83a0ab8e17af033 | 629,604 |
def clean_get_table(df):
"""Default table cleaner for get_table()"""
return df | ad3899f3481fba8b74392623b9772e68f18dfb57 | 629,605 |
def is_natural_number(number, include_zero: bool = False) -> bool:
"""
Returns True if `number` is the natural number.
Args:
number : an integer number to be checked.
include_zero (bool, optional): A flag to swith to include 0
in the natural numbers.
Defaults to Fals... | a137a074543a5b5e12ea7b6bc54f3842015d2a9b | 629,613 |
def exclude_keys(d, keys):
"""Return a new dictionary excluding all `keys`."""
return {k: v for k, v in d.items() if k not in keys} | d97c362f419403e0c413678a399b25b1e0208f34 | 629,614 |
from typing import Dict
from typing import Any
from typing import Tuple
def global_average_precision_score(
y_true: Dict[Any, Any], y_pred: Dict[Any, Tuple[Any, float]]
) -> float:
"""
Compute Global Average Precision score (GAP)
Parameters
----------
y_true : Dict[Any, Any]
Dictionary... | 3cb7b97fa19ec63053b7b10668dd3d7a992b9fb9 | 629,620 |
def get_tag(commands):
"""Generates a preprocessor tag from a set of grid commands."""
# Extra line break prevents unclosed paragraphs in markdown HTML output
return "\n<!--grid:%s-->" % ';'.join([str(cmd) for cmd in commands]) | 2e5d3c099a10dd6175e94c609b88fa211b3cbe0d | 629,621 |
def flatten_dictionary(nested_dict, separator):
"""Flattens a nested dictionary.
New keys are concatenations of nested keys with the `separator` in between.
"""
flat_dict = {}
for key, val in nested_dict.items():
if isinstance(val, dict):
new_flat_dict = flatten_dictionary(val,... | f9975b2ec1cf523e1acaab57881e174b216ecac3 | 629,622 |
def _gnurl(clientID):
"""
Helper function to form URL to Gracenote service
"""
clientIDprefix = clientID.split('-')[0]
return 'https://c' + clientIDprefix + '.web.cddbp.net/webapi/xml/1.0/' | 2f6ba2a261da1920fda26c99e25c49f157e60576 | 629,623 |
def hasManyOccurencies(elt, listx):
"""Find if a point has many similar occurences in a list.
This function is based on a threshold by default it is 80%.
Args:
elt: One element of the list.
listx: The list of elements
Returns:
True if it is a very frequent element, False other... | 617ee22d4dda70c8d82e82483677f768529155b3 | 629,628 |
def run_test(cfg, init_state):
"""
Run an execution given initial values for variables.
Arguments:
cfg -- control flow graph of the input program
init_state -- a test
Returns:
path -- path of the execution
state -- state after execution
"""
state = init... | 5534c5c29dae64faea62e540529c96ad87066f79 | 629,630 |
def get_platform_folder_to_keyword_map(ctx):
"""
Get the cached map of platforms to their PAL platform folder and keyword, so we can
attempt to search for platform-specific 3rd party fragments to combine with the input config file
:param ctx: Context
:return: Map of platform names to their keyword
... | 1f1fa691a51e1184238d9b949aaeb9179c0227df | 629,631 |
def tree_search(states, goal_reached, get_successors, combine_states):
"""
Given some initial states, explore a state space until reaching the goal.
`states` should be a list of initial states (which can be anything).
`goal_reached` should be a predicate, where `goal_reached(state)` returns
`True` ... | 5636b43df2da45c13569f4a9157f7df7a99aa10e | 629,632 |
def add_args_to_parser(arg_list, parser):
"""
Adds arguments from one of the argument lists above to a passed-in
arparse.ArgumentParser object. Formats helpstrings according to the
defaults, but does NOT set the actual argparse defaults (*important*).
Args:
arg_list (list) : A list of the s... | 7aad7ca5db343da6d6a6aa970b191ce8e508cfc3 | 629,633 |
def updateTracker(idx,newChar,tracker,force=False):
"""Set final sequence value by column index if 'None'.
Optionally force overwrite of previously updated base."""
if tracker[idx].base and force:
# Note: Add alert when overwriting a previously set base
tracker[idx] = tracker[idx]._replace(base=newChar)
elif n... | 0b72e40af6d575ead2f585f020b6aca301076c7d | 629,635 |
def strSQLite(string):
"""
Sanitizes input for SQLite TEXT fields by converting to string and replacing
each single quote (') with two single quotes ('')
"""
return str(string).replace(r"'", "''") | 51ef66c05c55a2f3e07b8c090d763795a1175445 | 629,636 |
def inherit_docs(original):
"""A decorator that copies the docstring from a function to the decorated one"""
def wrapper(target):
target.__doc__ = original.__doc__
return target
return wrapper | 21501e506cbd211f61fbd17f7bcfd1242eb46523 | 629,642 |
def forecast_error(y, y_predicted):
"""Calculate the forecast error in a regression model.
Parameters
----------
y : array-like of shape = number_of_outputs
Represent the target values.
y_predicted : array-like of shape = number_of_outputs
Target values predicted by the model.
... | 4aede163ae2b1affbc533c9ef054ba789c8c53f0 | 629,643 |
import yaml
def read_yaml(fname):
"""Read a YAML file and return a list of Python dictionaries, one for each
document in the YAML file."""
stream = open(fname, 'r')
docs = [doc for doc in yaml.safe_load_all(stream)]
return docs | e09cb4b4236f46ab345a535f1d8a1682f30b3a1b | 629,645 |
def win_check(hidden_word, guessed_letters):
"""
hidden_word: string, the hidden word to guess
guessed_letters: list, with all letters user have used
return: boolean, True if all letters of hidden_word exist in guessed_letters otherwise False
"""
for letter in hidden_word:
if letter not ... | 6ea1c57897268c2ced84ad674fb1c8f078bce98a | 629,653 |
import torch
def macro_double_soft_f1(y, y_hat):
"""Compute the macro soft F1-score as a cost (average 1 - soft-F1 across all labels).
Use probability values instead of binary predictions.
This version uses the computation of soft-F1 for both positive and negative class for each label.
Args:
... | 567197cb76bec393d18604221b5a06a270cee8e4 | 629,656 |
def sumAvailable(value):
"""Sum available_in_bytes over all partitions."""
result = [x['available_in_bytes'] for x in value]
return sum(result) | d2f1ef9d7660005726d548f827d32e3b52101985 | 629,658 |
def is_palindrome(n, base=10):
"""
Is the given number n a palindrome in the given base?
"""
if base == 10:
n_str = str(n)
elif base == 2:
n_str = "{0:b}".format(n)
else:
raise RuntimeError("Only 2 and 10 bases supported")
for i in range(len(n_str) // 2):
... | 7e90c2122888d853850a84229ca3ca65074a8993 | 629,659 |
def find_place(lines, size_x):
"""
Finds the highest place at the left for a panel with size_x
:param lines:
:param size_x:
:return: line with row, col, len
"""
for line in lines:
if line['len'] >= size_x:
return line | 995ec1cd42526864ba80a8d8fb1991b7980b5c6e | 629,661 |
import re
def normalize(s):
""" Normalize a string """
return re.sub('[^a-z0-9_]', '_', re.sub('[()]', '', s.lower())) | dc64bb41deaf5534fdc214e806c3d04194de0ac4 | 629,662 |
import warnings
def _log_warnings_postprocess(response):
"""Logs warnings contained within the x-wf-warnings response header."""
# NOTE: .initial_metadata() will block.
for key, value in response.initial_metadata():
if key == "x-wf-warnings":
warnings.warn(value)
return response | 0207b4d37902a4a13f7cc914c64a90d3f0a0cfc2 | 629,663 |
import re
def process_token(token: str):
"""Makes sure a given token is valid for usage within the Discord API.
Args:
token (:class:`str`): The token to be processed.
Returns:
:class:`str`: The modified, adapted token.
Examples:
.. testsetup::
from serpcord.util... | c42b58cb89e37d71f11beefd8654e3a9cf845054 | 629,668 |
def if_exception_type(*exception_types):
"""Creates a predicate to check if the exception is of a given type.
Args:
exception_types (Sequence[:func:`type`]): The exception types to check
for.
Returns:
Callable[Exception]: A predicate that returns True if the provided
... | 2384c3fc4f6f369c92c23f49f9dec40d365e2483 | 629,669 |
def remove_extra_space(
text: str,
) -> str:
"""To remove extra space in a given text.
Parameters
----------
text : str
The text to clean.
Returns
-------
str
returns text after removing all redundant spaces.
Examples
--------
>>> from SkillNer.cleaner impo... | 1743c8cae32b0b23631a7f7dc3ed25526826fa69 | 629,674 |
from typing import List
def count_failed_students(student_scores: List[int]) -> int:
"""
:param student_scores: list of integer student scores.
:return: integer count of student scores at or below 40.
"""
return len(list(filter(lambda x: x <= 40, student_scores))) | c3fb0cc4fecb946a1850465f342e3530012826c1 | 629,675 |
def add_bda(base_config):
"""Add BDA to config file with hard-coded parameter values."""
bda_config = """
bda:
max_decorr: 0
pre_fs_int_time: !dimensionful
value: 0.1
units: s
corr_FoV_angle: !dimensionful
value: 20
units: deg
max_time: !dimensionful
value... | ba28edbff23a08f844cb87d32ea7856cb269fa36 | 629,676 |
def getbitlen(bint):
"""
Returns the number of bits encoding an integer
"""
if bint == 0:
# Zero is encoded on one bit
return 1
else:
return int(bint).bit_length() | 99cfb57c0248aed21747c85dbb270703b184fd48 | 629,681 |
from typing import Dict
import torch
def dictionary_to_device(dictionary: Dict, device: torch.device):
"""Move dictionary values to a torch device, if they support it.
:param dictionary: Dictionary, whose values are to be moved to the torch device.
:param device: torch device
:return: Dictionary, wit... | ba240355c1ae49fc449b82c652663aa4de021492 | 629,686 |
import math
def determine_num_particles(pack_frac, num_vertices):
"""Return the number of model particles to be created
based on the packing fraction"""
num_particles = num_vertices * pack_frac
num_particles = int(math.ceil(num_particles))
return num_particles | 58f49659cc011278786b91938ac4d31630308080 | 629,688 |
def functions_in(module):
"""
Create a dictionary of the functions in a module
Parameters
----------
module : Module
module to run on.
Returns
-------
dict
"""
return {name: f for name, f in module.__dict__.items() if callable(f)} | 26d8b64034eb5cdb236b877c254eaffee57d1093 | 629,691 |
def reverse_2nd(vec):
"""Do time-reversal on numpy array of form `B x T`
:param vec: vector to time-reverse
:return: Time-reversed vector
"""
return vec[:, ::-1] | cf069e59e680333698582de81b0e9c2e13eec78b | 629,693 |
def GetPatchMetadata(patch_dict):
"""Gets the patch's metadata.
Args:
patch_dict: A dictionary that has the patch metadata.
Returns:
A tuple that contains the metadata values.
"""
# Get the metadata values of a patch if possible.
start_version = patch_dict.get('start_version', 0)
end_version = ... | 4fa58c5cbcdd457ef7ad92b6b9ad3600264542c4 | 629,694 |
def get_suite_name(nodeid):
"""Return suitename from nodeid string.
Args:
nodeid(str): pytest.Item nodeid string
Returns:
str: test suite name
"""
names = nodeid.split("::")
names[0] = names[0].replace("/", '.')
names = [x.replace(".py", "") for x in names if x != "()"]
... | c08133bf7d70a288abaac7f6c15e0c06eb6888dc | 629,696 |
def min_sec(secs):
"""
Takes an epoch timestamp and returns string of minutes:seconds.
:param secs:
Timestamp (in seconds)
>>> import time
>>> start = time.time() # Wait a few seconds
>>> finish = time.time()
>>> min_sec(finish - start)
'0:11'
"""
secs = int(secs)
... | 6c06866c0c44d7662b7b655798fd2f92357af14a | 629,704 |
def get_number_of_images(body_response):
"""
Returns the number of images in the list.
:param body_response: Parsed response (Python dic). List of images
:return: Length of list
"""
return len(body_response['images']) | c7034154b379c647739b3f7d52c4a5ba631eafb6 | 629,706 |
def char_to_bin(char: str) -> str:
"""This creates a string representing the binary value of the character.
Parameters:
-----------
char:
string: A single character.
Returns:
--------
binary:
string: The 8-bit binary representation of the character.
"""
binary = bi... | 8a07c944733cf9543e236eb61dadf47571fa6b9b | 629,707 |
def is_indicator(item_type):
"""Return whether or not the given item_type is an indicator."""
indicator_types = [
'address',
'emailaddress',
'file',
'host',
'url',
'asn',
'cidr',
'mutex',
'registry key',
'user agent'
]
retur... | 9f471290f62e3f583cc9b2c1e45604312f9f48bb | 629,708 |
from typing import Tuple
def parse(args: Tuple[str, str, str, str, str]) -> Tuple[str, str, str]:
"""Parser for rd rs rt format instructions."""
return (args[2], args[3], args[4]) | 9a74a7a98f108d350ca22ae62e0d6ea3769ca720 | 629,709 |
def list_daily_cases(list_of_cumulative_cases):
"""
Given a list of cumulative cases, this function makes and returns a list of
daily cases.
"""
daily_list = [0]
for i in range(1, len(list_of_cumulative_cases)):
N_daily_case = list_of_cumulative_cases[i] - list_of_cumulative_cases[i - 1... | 287d01b2c7a2a8764289c1f5f2e65372fedc35b5 | 629,710 |
def is_user_inputs_populated(user_prefs):
"""
Takes a dictionary of user preferences and returns a Boolean whether all inputs are filled.
"""
return all(value != '' or value != 'No preference' for value in user_prefs.values()) | 316769bb352b8f67f6080a4e021ef800f243fcaf | 629,711 |
from typing import Mapping
def get_keys_for_dict(d):
"""
Get all (possibly nested) keys in a dictionary
"""
out = []
for k, v in d.items():
out.append(k)
if isinstance(v, Mapping):
out += get_keys_for_dict(v)
return out | 4ad5a9df77f5fe153c75cc820b3899542990f98b | 629,712 |
def average(values):
"""calculates average from a list"""
try:
return float(sum(values) / len(values))
except ZeroDivisionError:
return 0 | 103923cba72bb7a1c84577518731ad56e1f4bc4c | 629,716 |
def _parse_action_removals(actions):
""" Separates the combined list of keys to remove into webhooks and emails. """
flattened = list({x for sublist in actions for x in sublist})
emails = []
webhooks = []
for item in flattened:
if item.startswith('http://') or item.startswith('https://'):
... | 7ac597c039c64d22e3dc82b965e4b28b1ddbd8e7 | 629,717 |
import requests
from bs4 import BeautifulSoup
def get_soup(link):
"""Gets soup from a given website."""
res = requests.get(link)
soup = BeautifulSoup(res.text, "html.parser")
return soup | e4212b3e95642fc238407b803e5c65ac44d3aeca | 629,718 |
def get_package_name_and_type(package, known_extensions):
"""Return package name and type.
Package type must exists in known_extensions list. Otherwise None is
returned.
>>> extensions = ['tar.gz', 'zip']
>>> get_package_name_and_type('underscored_name.zip', extensions)
('underscored_name', 'z... | eb7732a16a4f1ca84b25c38c7aec2e4572f1afd3 | 629,720 |
def merge(d1, d2, merge_fn):
"""
Merges two dictionaries, non-destructively, combining
values on duplicate keys as defined by the optional merge
function. The default behavior replaces the values in d1
with corresponding values in d2.
Examples:
>>> d1
{'a': 1, 'c': 3, 'b': 2}
>>> ... | d1d4b48d5d4048bb7fa99312236a5df1a4e409d0 | 629,722 |
def _perp(t: tuple) -> tuple:
"""
Obtain the point whose corresponding vector is perpendicular to t.
Parameters
----------
t : tuple
Point (x, y)
Returns
-------
tuple:
(-y, x)
"""
return -t[1], t[0] | ed49a4f326f8ef065e72d964bce3b3ce444c25f5 | 629,725 |
def solve_me_first(num1: int, num2: int):
"""Calculate the sum of two numbers."""
return num1 + num2 | 09c44886cd43d2e0ab7b54bbbcaa058a9e9382ed | 629,726 |
import math
def cint(num):
"""
Returns ceiling of number as type integer
:param num: input number
:returns: integer ceil number
"""
return int(math.ceil(num)) | 46dccd12e93053b4e54f43a498d97a97e202693c | 629,727 |
import hashlib
def create_key(notification):
"""Create the key for status_keys from notification
in: notification
return: the key
"""
key = notification.host
key += '/'
key += notification.plugin
if notification.plugin_instance:
key += '-'
key += notification.plug... | 2397430e9198bfbbbe66f83ce0e9eddfc172ec4c | 629,728 |
def zero_cross_down(values, start=0, end=-1):
"""
Returns the indexes of the values so that values[i] > 0 and values[i+1] < 0
params:
- values: list of values to consider
- start: index of the first value to consider
- end: index of the last value to consider (can be < 0)
"""
... | ee86118c23dcb6278d9c86bd50a1915661a2eaf5 | 629,729 |
def get_set_intersection(list_i, list_j):
""" Get the intersection set
Parameters
----------
list_i, list_j: list
two generic lists
Returns
-------
intersection_set: set
the intersection of list_i and list_j
"""
set_i = set(list_i)
set_j = set(list_j)
interse... | bfba58d6f8b33591208de76c20fee60ac9e56fd8 | 629,732 |
def delete_user_defined_app_address_map(
self,
ip_start: int,
ip_end: int,
) -> bool:
"""Delete specific user defined application group based on
address map
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - applicationDefini... | d783812a6faad1c12bc5e7afc765e44ca23f78e6 | 629,734 |
def getMutationIDs(data):
"""
Function to get uniques mutation IDs from COSMIC data
Arguments:
data = dataframe containing COSMIC data
Returns:
list of unique mutation IDs
"""
return list(set(data["Mutation ID"])) | 906f4d4a240373d2476e8a420b9e8df542db70b5 | 629,735 |
def AmOppCreditParts(exact, e87521, num, c00100, CR_AmOppRefundable_hc,
CR_AmOppNonRefundable_hc, c10960, c87668):
"""
Applies a phaseout to the Form 8863, line 1, American Opportunity Credit
amount, e87521, and then applies the 0.4 refundable rate.
Logic corresponds to Form 8863, P... | 36be57cf25ea18d422a522e2a7a1aef36aee7ef6 | 629,738 |
def is_string_integer(string: str):
"""
This function takes in a character value and checks if it is a valid integer.
All entries must be strings of length 1
:param string: the string to be analyzed
:type string: str
:return: true or false, depending on if the character is a valid integer
... | 854c86f9eeda717b8a76339d22642e6503069222 | 629,740 |
import torch
import math
def attention(query, key, value, atten_mask=None):
"""
Compute Scaled Dot Product Atten
should: d_q == d_k, len_v == len_q, atten_mask.shape equal to scores or can be broadcast
:param query: (batch_size, n_heads, len_q, d_q)
:param key: (batch_size, n_heads, len_k, d_q)
... | 95e4dd0a35d1a82b523e2764e23a5eba5231fb9c | 629,742 |
def compute_pad(image_shape, kernel_size, enforce_odd=True):
"""Computes a padding length for a given image shape and kernel.
Args:
image_shape: A tuple or list of 2 integers.
kernel_size: A positive integer.
enforce_odd: A boolean indicating whether the padding should result in an
image with odd... | a6ca56c99d90942ea55dc6c3b039fb62e4aada22 | 629,745 |
def valid_field_in_tree(arch):
"""A `tree` must have `string` attribute and an immediate node of `tree` view must be `field` or `button`."""
if arch.xpath('//tree[not (@string)]'):
return False
for child in arch.xpath('/tree/child::*'):
if child.tag not in ('field', 'button'):
re... | 84b8f67b01929d4a9c6dd89954ea3397a489e9f4 | 629,749 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.