content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Mapping
def UpdateDict( target, override ):
"""Apply the updates in |override| to the dict |target|. This is like
dict.update, but recursive. i.e. if the existing element is a dict, then
override elements of the sub-dict rather than wholesale replacing.
e.g.
UpdateDict(
{
'outer... | a07a3d7989e227ff1759271248777e167b7e5467 | 699,096 |
def dss_target(request):
"""
This is a parameterized fixture. Its value will be set with the different DSS target (DSS7, DSS8 ...) that are specified in the configuration file.
It returns the value of the considered DSS target for the test. Here it is only used by other fixtures, but one could use it
a... | 0aa9f85160280032dfdea872b7c9a147a5717523 | 699,098 |
def gym_size(gym):
"""Returns the size of the gym."""
return len(gym) | b31a46a7b56e973da8dfa0cac9950fad14b48622 | 699,101 |
def is_call_id_in_video_state(log, ad, call_id, video_state):
"""Return is the call_id is in expected video_state
Args:
log: logger object
ad: android_device object
call_id: call id
video_state: valid VIDEO_STATE
Returns:
True is call_id in expected video_state; Fal... | d0da323a21a23d461fc2aec06ac5d0bebac7cbef | 699,103 |
def _extract_spots_outside_foci(cell_cyt_mask, spots_out_foci):
"""
Extract spots detected outside foci, in a specific cell.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell with shape (y, x).
spots_out_foci : np.ndarray, np.int64
Coordinate of the ... | d4e06d9ad14ced3b8984b71c32d9d3b1e0cebaae | 699,104 |
def extract_image_number(filename: str, from_file: bool) -> int:
"""
finds the number of the image from the original images of LITIV 2014 dataset.
:param filename: name of the image file.
:param from_file: filename is read from a ground-truth file or not.
:return: number.
"""
number = filena... | e55431beffb02959907106a01596310812ba7363 | 699,107 |
def calculateNetIncome(gross, state):
"""
Calculate the net income after federal and state tax
:param gross: Gross Income
:param state: State Name
:return: Net Income
"""
state_tax = {'LA': 10, 'SA': 0, 'NY': 9}
# Calculate net income after federal tax
net = gross - (gross * .10)
... | 915528d8bfd15c18003eaeb8f6b3f1e8ad5565a0 | 699,110 |
def field_size(field_label):
"""
Helper function to determine the size of a binary
table field
Parameters
----------
field_label : PVLModule
The field label
Returns
-------
int :
The size of the one entry in bytes
"""
data_sizes = {
'Intege... | afaff70bc18d4d9d023fb7c89d45560f1a691bcf | 699,111 |
def leading_by(agents, player):
"""Determine difference between player's score and closest opponent."""
scores = [a.score() for a in agents]
player_score = scores[player]
scores.sort()
if player_score == scores[-1]:
return player_score - scores[-2]
else:
return player_score - sco... | e97aa0a1109bb2ba5f276f34030ea1f93022046f | 699,113 |
def mk_seealso(
function_name: str,
role: str = "func",
prefix: str = "\n\n",
module_location: str = ".",
) -> str:
"""
Returns a sphinx `seealso` pointing to a function.
Intended to be used for building custom fitting model docstrings.
.. admonition:: Usage example for a custom fittin... | 0165599829e8edd3f75adcda9402069066a0381a | 699,115 |
def mock_xibo_api(mocker):
"""Return a mock XiboApi."""
return mocker.MagicMock() | 8c2ad1566ad716d9fb4dd680a624e59f89950a0a | 699,117 |
def get_corpus_archive_name(cycle: int) -> str:
"""Returns a corpus archive name given a cycle."""
return 'corpus-archive-%04d.tar.gz' % cycle | 3068ce88bd85f2c21819da697a2b1147f547c509 | 699,118 |
import re
def extract_airlines_from_flight_text(flight_text):
"""
:param flight_text: Raw flight text string, e.g.,
"3:45 PM – 8:15 PM+1\nUnited\n13h 30m\nSFO–PVG\nNonstop\n$4,823",
"12:51 PM – 4:50 PM+1\nDelta\nChina Southern\n12h 59m\nSEA–PVG\nNonstop\n$4,197",
"2:10 AM – 1:25 PM+1\... | 188f040c15e62f4eace72cb90ef74825c4b803fc | 699,120 |
def get_inputs(inputs, mask=None):
"""Extract and normalize the arrays from inputs"""
gmax = inputs[0][:,:,1].max()
o = inputs[0][:,:,0]/gmax
n = inputs[1][:,:,0]/gmax
return o,n | 329dfce70d65dec8d5f177239b7f88c977519867 | 699,121 |
def formatTime(t):
"""Check if hour, minute, second variable has format hh, mm or ss if not change format.
:param t: string time hh, mm or ss
:return: string time in correct format eg. hh=02 instead of hh=2
"""
if len(t) < 2:
t = "0" + t
return t | 8011fc25a001964af1f1e0b0cb4e54f7d7aec721 | 699,123 |
def remove_signature(message):
"""Remove the 3 Letter signature and the '/' found at the beginning of a valid message"""
return message[1:] | a802dc5abfea09e05fad51936dd76e17719900e7 | 699,126 |
import textwrap
def get_comment_from_location(location):
"""Return comment text from location.
Args:
location: descriptor_pb2.SourceCodeInfo.Location instance to get
comment from.
Returns:
Comment as string.
"""
return textwrap.dedent(location.leading_comments or
... | d86213ddee50128c8363d2a31a740c5677244612 | 699,128 |
def get_name(test):
"""Gets the name of a test.
PARAMETERS:
test -- dict; test cases for a question. Expected to contain a key
'name', which either maps to a string or a iterable of
strings (in which case the first string will be used)
RETURNS:
str; the name of the test
... | e9d5a5013b062077c499e0351786819c9bd6bd90 | 699,131 |
def check_if_points_escape_box(u, box_boundaries):
"""
Determine if points u in 2D plane have escaped from box_boundaries limits.
Parameters
----------
u : ndarray, shape(n, 2),
Points in plane.
box_boundaries : list of 2 tuples of floats,
Values are interpreted as [[x_... | 41b04b72821bc39f387c7557be1b11f14e65c71d | 699,132 |
from typing import Any
import random
def assign_new_ids(items: dict[str, Any]) -> list[str]:
"""
Assigns new IDs to any item ID that starts with "NEW:" or is an empty
string. Will modify the dict in place. Will return a list of new item IDs
assigned.
"""
new_items = []
for item_id in items... | 4fb3466566f0fd9981e1c99cb429da629c843dab | 699,133 |
def isatty(stream):
"""Check if a stream is attached to a console.
Args:
stream (:obj:`io.IOBase`):
Stream to check.
Returns:
:obj:`bool`
"""
return stream.isatty() if hasattr(stream, "isatty") else False | 4ec38e35413f0f8af76da5e2681f5502acf3d61e | 699,134 |
def egcd(a, b):
"""
Calculate the extended Euclidean algorithm. ax + by = gcd(a,b)
Args:
a (int): An integer.
b (int): Another integer.
Returns:
int: Greatest common denominator.
int: x coefficient of Bezout's identity.
int: y coefficient of Bezout's identity.
... | 87b35ff4e28529d1de2a6fb0063b69cee5dfec74 | 699,137 |
def old(sym):
""" Return the "old" version of symbol "sym", that is, the one
representing "sym" in the pre_state.
"""
return sym.prefix('old_') | 4cc24bd0448195ee1c373106679177ce428e5937 | 699,139 |
def _remove_stopwords(line, nlp):
""" Helper function for removing stopwords from the given text line. """
line_nlp = nlp(line)
line_tokens = [tok.text for tok in line_nlp]
filtered_line = list()
# Filter
for tok in line_tokens:
lexeme = nlp.vocab[tok]
if not lexeme.is_stop:
... | 58932dc254874ea7a9e93e7e8d7fbf9f306f740b | 699,144 |
from typing import Dict
def dict_from_text_file(fpath: str) -> Dict[str, float]:
"""Parse a two-column CSV file into a dictionary of string keys and float values.
Will fail an assertion if the second column contains values which are not valid floats.
Args:
fpath (str): Path to file to parse.
... | 5baf29832e0a44c8131a97168cde796757c05bfa | 699,146 |
import posixpath
def get_fuzzer_benchmark_covered_regions_filestore_path(
fuzzer: str, benchmark: str, exp_filestore_path: str) -> str:
"""Returns the path to the covered regions json file in the |filestore| for
|fuzzer| and |benchmark|."""
return posixpath.join(exp_filestore_path, 'coverage', 'da... | f999a81c53d961a2ed38a7941d7dd6912dae9621 | 699,148 |
def breakdown(data):
"""Break down each row into context-utterance pairs.
Each pair is labeled to indicate truth (1.0) vs distraction (0.0).
Output is a native array with format : [context, utterance, label]"""
output = []
for row in data:
context = row[0]
ground_truth_utterance = ro... | 613cc8ca3d65d8eb22631114a88a934f67f37867 | 699,149 |
def string_escape(text: str) -> str:
"""Escape values special to javascript in strings.
With this we should be able to use something like:
elem.evaluateJavaScript("this.value='{}'".format(string_escape(...)))
And all values should work.
"""
# This is a list of tuples because order matters, an... | f85d02527f3a9fdb9373f2359c2fce86b86a5a89 | 699,150 |
def check_permutation(str1, str2):
""" 1.2 Check Permutation: Given two strings, write a method to decide if
one is a permutation of the other.
Complexity: O(n) time, O(n) space
"""
h = {}
for c in str1:
if c not in h:
h[c] = 0
h[c] += 1
for c in str2:
if ... | 4da48752e963c05115b3255b03749e8579a9f8ff | 699,151 |
def climb_stairs(n: int) -> int:
"""
Args:
n: number of steps of staircase
Returns:
Distinct ways to climb a n step staircase
Raises:
AssertionError: n not positive integer
"""
fmt = "n needs to be positive integer, your input {}"
assert isinstance(n, int) and n > 0, ... | 71ac88a1f475e8fe2da8e525f7924e289dbf28e4 | 699,152 |
import codecs
def raw_buffered_line_counter(path, encoding="utf-8", buffer_size=1024 * 1024):
"""
Fast way to count the number of lines in a file.
:param Path path: Path to file.
:param str encoding: Encoding used in file.
:param int buffer_size: Size of buffer for loading.
:return: int
""... | 700135dc1a5b5bf4a807469e34f56213d7b1265a | 699,155 |
def consider_trip_number(trip_strategy, total_trips, trip_num):
"""Determines if the vehicle should charge given trip strategy and current trip
:param int trip_strategy: a toggle that determines if should charge on any trip or only after last trip (1-anytrip number, 2-last trip)
:param int total_trips:... | b2fe3a43b95fead4ebf65981cfba39857d1bee3c | 699,157 |
import pathlib
def as_pathlib(path):
"""
Converts the supplied path to an pathlib.Path object
:param path: The path to convert
:return: The path converted to pathlib.Path
"""
return pathlib.Path(path) | 88129771be8c3277320c813502efbcfee6abdc84 | 699,158 |
import re
def remove_non_alpha_numeric(input_string):
"""
return string by removing non alpha numric characters from it
"""
return re.sub(r'\W+', '', input_string) | fc7b203e4937a7a5a80f0d3dc9a2d7bca5de6b45 | 699,159 |
def extract_text(tweet):
"""Gets the full text from a tweet if it's short or long (extended)."""
def get_available_text(t):
if t['truncated'] and 'extended_tweet' in t:
# if a tweet is retreived in 'compatible' mode, it may be
# truncated _without_ the associated extended_tweet
... | 41660b71e3b020bc25309821b46471e88d79aa49 | 699,163 |
def search_linearf(a, x):
"""
Returns the index of x in a if present, None elsewhere.
"""
for i in range(len(a)):
if a[i] == x:
return i
return None | 949cb93218381a1a45002be03c6b8ca4d00092bf | 699,164 |
def gamma_corr(clip, gamma):
""" Gamma-correction of a video clip """
def fl(im):
corrected = 255 * (1.0 * im / 255) ** gamma
return corrected.astype("uint8")
return clip.fl_image(fl) | d98d411c63d932b068d80bef63d42289cb0d8468 | 699,166 |
def connected_components(graph):
"""
Given an undirected graph (a 2d array of indices), return a set of
connected components, each connected component being an (arbitrarily
ordered) array of indices which are connected either directly or indirectly.
"""
def add_neighbors(el, seen=[]):
''... | e8299cc024dd27414a287ee0afa302ea64c18b68 | 699,167 |
import math
import torch
def loglinspace(a, b, n=100, **kwargs):
"""Like :meth:`torch.linspace`, but spread the values out in log space,
instead of linear space. Different from :meth:`torch.logspace`"""
return math.e**torch.linspace(math.log(a), math.log(b), n, **kwargs) | ea456462a0d029f1ada1c4a9e40c9377b86e815d | 699,170 |
def _query_pkey(query, args):
"""Append 'query' and 'args' into a string for use as a primary key
to represent the query. No risk of SQL injection as memo_dict will
simply store memo_dict['malicious_query'] = None.
"""
return query + '.' + str(args) | d524697af247879f6aca5fa3918d80199b6148d5 | 699,177 |
from typing import Dict
def alias(alias: str) -> Dict[str, str]:
"""Select a single alias."""
return {"alias": alias} | 9321f00118658dc74fbc9704f1ea0e4a33e1f7aa | 699,181 |
def max_digits(x):
"""
Return the maximum integer that has at most ``x`` digits:
>>> max_digits(4)
9999
>>> max_digits(0)
0
"""
return (10 ** x) - 1 | 3f0ffdfbbb3fdaec8e77889b3bfa14c9b9829b2e | 699,184 |
def to_numpy(t):
"""
If t is a Tensor, convert it to a NumPy array; otherwise do nothing
"""
try:
return t.numpy()
except:
return t | 3ac3ef0efd9851959f602d42e7f38bdd7e5da21a | 699,185 |
import json
def _jsonToDict(json_file):
"""Reads in a JSON file and converts it into a dictionary.
Args:
json_file (str): path to the input file.
Returns:
(dict) a dictionary containing the data from the input JSON file.
"""
with open(json_file, 'r') as fid:
dout = json.loa... | 6e4b5996d6aaf2982012c6c2f135d7876ee5b3ca | 699,195 |
def _matches_app_id(app_id, pkg_info):
"""
:param app_id: the application id
:type app_id: str
:param pkg_info: the package description
:type pkg_info: dict
:returns: True if the app id is not defined or the package matches that app
id; False otherwise
:rtype: bool
"""
... | 4d6cd0d652a2751b7a378fd17d5ef7403cfdc075 | 699,196 |
def quad_pvinfo(tao, ele):
"""
Returns dict of PV information for use in a DataMap
"""
head = tao.ele_head(ele)
attrs = tao.ele_gen_attribs(ele)
device = head['alias']
d = {}
d['bmad_name'] = ele
d['pvname_rbv'] = device+':BACT'
d['pvname'] = device+':BDES'
d['bmad_f... | b35e04d78d419673afbc0711f9d454e01bc1dd5d | 699,198 |
from typing import Callable
from typing import Set
from typing import Type
def is_quorum(is_slice_contained: Callable[[Set[Type], Type], bool], nodes_subset: set):
"""
Check whether nodes_subset is a quorum in FBAS F (implicitly is_slice_contained method).
"""
return all([
is_slice_contained(n... | 4a4af3af8ca5a3f969570ef3537ae75c17a8015c | 699,202 |
from re import match
def extrakey(key):
"""Return True if key is not a boring standard FITS keyword.
To make the data model more human readable, we don't overwhelm the output
with required keywords which are required by the FITS standard anyway, or
cases where the number of headers might change over ... | d4c36c3a5408d7056e55d5e67ebebe0b960e5b72 | 699,206 |
def P(N_c, N_cb, e_t, t, A, N_bb):
"""
Returns the points :math:`P_1`, :math:`P_2` and :math:`P_3`.
Parameters
----------
N_c : numeric
Surround chromatic induction factor :math:`N_{c}`.
N_cb : numeric
Chromatic induction factor :math:`N_{cb}`.
e_t : numeric
Eccentri... | 82e444ca0e7563f061b69daedd82ff3fc771f190 | 699,208 |
import re
def trim_http(url :str) -> str:
"""
Discard the "http://" or "https://" prefix from an url.
Args:
url: A str containing an URL.
Returns:
The str corresponding to the trimmed URL.
"""
return re.sub("https?://", "", url, flags = re.IGNORECASE) | 472e71a646de94a1ad9b84f46fc576ed5eb5a889 | 699,214 |
def remove_recorders(osi):
"""Removes all recorders"""
return osi.to_process('remove', ['recorders']) | c63f23a031a5c957fd8667fc5be87fbd96b26a1e | 699,221 |
from typing import Match
def gen_ruby_html(match: Match) -> str:
"""Convert matched ruby tex code into plain text for bbs usage
\ruby{A}{B} -> <ruby><rb>A</rb><rp>(</rp><rt>B</rt><rp>)</rp></ruby>
Also support | split ruby
\ruby{椎名|真昼}{しいな|まひる} ->
<ruby><rb>椎名</rb><rp>(</rp><rt>しいな</rt><rp>)</rp>... | bd603b67a61812152f7714f3a13f48cac41db277 | 699,224 |
import random
import string
def randomstring(size=20):
"""Create a random string.
Args:
None
Returns:
result
"""
# Return
result = ''.join(
random.SystemRandom().choice(
string.ascii_uppercase + string.digits) for _ in range(size))
return result | 64ecd935130f6308367d02a5d699ea05c906cbb2 | 699,228 |
def has_seven(k):
"""Returns True if at least one of the digits of k is a 7, False otherwise.
>>> has_seven(3)
False
>>> has_seven(7)
True
>>> has_seven(2734)
True
>>> has_seven(2634)
False
>>> has_seven(734)
True
>>> has_seven(7777)
True
"""
if k % 10 == 7:
... | 8c0b7b02e36247b3685a6a0142ebd81dd63e220c | 699,229 |
def get_grid_size(grid):
"""Return grid edge size."""
if not grid:
return 0
pos = grid.find('\n')
if pos < 0:
return 1
return pos | 9ff60184bb0eed7e197d015d8b330dcf615b4008 | 699,233 |
def index() -> str:
"""
Static string home page
"""
return "Hello, Python!!!" | 7bf6b684e8404d0b2d52bb7578e1f44e37bdf565 | 699,236 |
def get_unique_coords(df, lat_field, lon_field):
"""
Takes in a dataframe and extract unique fields for plotting.
Uses dataframe group by to reduce the number of rows that need to
be plotted, returns the lat and lon fields
"""
unique = df.groupby([lat_field, lon_field]).size().reset_index()
... | 3914e59a9263e07a18833135b0d30a3e5b1d4ce6 | 699,237 |
def unhex(value):
"""Converts a string representation of a hexadecimal number to its equivalent integer value."""
return int(value, 16) | 0a8c297a93f484c8a1143511ef8511521c887a78 | 699,239 |
def filter_errors(seq, errors):
"""Helper for filter_keys.
Return singleton list of error term if only errors are in sequence; else
return all non-error items in sequence.
Args
seq: list of strings
errors: dict representing error values
Returns
List of filtered items.
"""... | 93f44cd933e48974c393da253b7f37057ea7de19 | 699,244 |
def _offset(x, y, xoffset=0, yoffset=0):
"""Return x + xoffset, y + yoffset."""
return x + xoffset, y + yoffset | a6c88b2ee3172e52f7a538d42247c0fdc16352f8 | 699,245 |
def filter_to_be_staged(position):
"""Position filter for Experiment.filter() to include only worms that still need to be
stage-annotated fully."""
stages = [timepoint.annotations.get('stage') for timepoint in position]
# NB: all(stages) below is True iff there is a non-None, non-empty-string
# anno... | df771b0856c91c8663ad06cacf86bf3389df04c5 | 699,246 |
def leja_growth_rule(level):
"""
The number of samples in the 1D Leja quadrature rule of a given
level. Most leja rules produce two point quadrature rules which
have zero weight assigned to one point. Avoid this by skipping from
one point rule to 3 point rule and then increment by 1.
Parameters... | b93fe05a3bf9b8c016b92a00078dce8ef156a8c4 | 699,248 |
def nastran_replace_inline(big_string, old_string, new_string):
"""Find a string and replace it with another in one big string.
In ``big_string`` (probably a line), find ``old_string`` and replace
it with ``new_string``. Because a lot of Nastran
is based on 8-character blocks, this will find the 8-char... | f9955d40a74fc57674e79dd6aeea3872ffc2c87d | 699,249 |
import re
def does_support_ssl(ip):
"""Check if IP supports SSL.
Has aba sequence outside of the bracketed sections and corresponding
bab sequence inside bracketed section.
Examples:
- aba[bab]xyz supports SSL (aba outside square brackets with
corresponding bab within square brackets).
... | f46dda13d53717352fe27446d9fa3d0292d75c26 | 699,250 |
import six
import json
def meta_serialize(metadata):
"""
Serialize non-string metadata values before sending them to
Nova.
"""
return dict((key, (value if isinstance(value,
six.string_types)
else json.dumps(value))
... | a2ef8762c9d1b3d78dc401996392df0985c1c226 | 699,251 |
def keep_merge(walkers, keep_idx):
"""Merge a set of walkers using the state of one of them.
Parameters
----------
walkers : list of objects implementing the Walker interface
The walkers that will be merged together
keep_idx : int
The index of the walker in the walkers list that wil... | b029bd14cab4aec2cdf8edf27a9d63c2ffbbe61e | 699,253 |
def is_nan(var) -> bool:
"""
Simple check if a variable is a numpy NaN
based on the simple check where (nan is nan) gives True but (nan == nan) gives False
"""
return not var == var | 0f91829f9b5ee3dfb22944d956066069b4a3f606 | 699,259 |
def load_instances(model, primary_keys):
"""Load model instances preserving order of keys in the list."""
instance_by_pk = model.objects.in_bulk(primary_keys)
return [instance_by_pk[pk] for pk in primary_keys] | 21f26f66047fc2b2871f77447035ba15fbf78fa7 | 699,260 |
def GetHotlistRoleName(effective_ids, hotlist):
"""Determines the name of the role a member has for a given hotlist."""
if not effective_ids.isdisjoint(hotlist.owner_ids):
return 'Owner'
if not effective_ids.isdisjoint(hotlist.editor_ids):
return 'Editor'
if not effective_ids.isdisjoint(hotlist.follower... | 0c03460d3e4190d4964a60a2753d31e1732b6e44 | 699,263 |
from unittest.mock import Mock
from unittest.mock import patch
def mock_gateway_fixture(gateway_id):
"""Mock a Tradfri gateway."""
def get_devices():
"""Return mock devices."""
return gateway.mock_devices
def get_groups():
"""Return mock groups."""
return gateway.mock_gro... | 6404cb18ce9dd0e97b33958958d7851ee5739bed | 699,264 |
from typing import Any
def function_sig_key(
name: str,
arguments_matter: bool,
skip_ignore_cache: bool,
*args: Any,
**kwargs: Any,
) -> int:
"""Return a unique int identifying a function's call signature
If arguments_matter is True then the function signature depends ... | bfec647db5d819fb87cf3a227927acd5cd6dda10 | 699,267 |
import time
def date_file_name(name):
"""Generate file name with date suffix."""
time_str = time.strftime("%Y%m%d-%H%M%S")
return name + "_" + time_str | 40e37e2a5dbc0208421f797bc2ae349414b05e4e | 699,271 |
def compute_efficiency_gap(partition):
"""
Input is a gerrychain.Partition object
with voteshare and population data.
It is assumed that `add_population_data` and
`add_voteshare_data` have been called on
the given partition's GeoDataFrame.
Returns the efficiency gap of
the distri... | 2982fe1b2f570c8eca27fade8915e9b117397cd1 | 699,272 |
import requests
import json
def updateData(url):
"""
Returns the symbol and the price of an asset.
Parameters
-----------
url: url used for information retrieval
Returns
-----------
tuple
(symbol name, symbol price)
"""
res = requests.get(url);
text = res... | b458dee9da7700f5c4f82a182724bba007c7a05f | 699,273 |
def has_phrase(message: str, phrases: list):
""" returns true if the message contains one of the phrases
e.g. phrase = [["hey", "world"], ["hello", "world"]]
"""
result = False
for i in phrases:
# if message contains it
i = " ".join(i)
if i in message:
result = True
return result | f56fcc261e21c538f1f23b811e14ae29d92f3038 | 699,276 |
def check_output(solution: str, output: str) -> bool:
"""Check if program's output is correct.
Parameters
----------
solution
Sample output taken from BOJ.
output
Output from program run.
Returns
-------
bool
True if correct, False if wrong.
"""
solution... | 66d35952d892842bd1b47329bfa7b77e0a878a51 | 699,278 |
from typing import Sequence
def bit_array_to_int(bit_array: Sequence[int]) -> int:
"""
Converts a bit array into an integer where the right-most bit is least significant.
:param bit_array: an array of bits with right-most bit considered least significant.
:return: the integer corresponding to the bit... | d902a8e3db7b65ad348ef86cbfac371361aedd58 | 699,279 |
import math
def euclidean_distance(p1, p2):
"""Calculate the euclidean distance of two 2D points.
>>> euclidean_distance({'x': 0, 'y': 0}, {'x': 0, 'y': 3})
3.0
>>> euclidean_distance({'x': 0, 'y': 0}, {'x': 0, 'y': -3})
3.0
>>> euclidean_distance({'x': 0, 'y': 0}, {'x': 3, 'y': 4})
5.0
... | 8cdc0e0534b2ed9272832fc0f977b9aa0e594c65 | 699,281 |
import zlib
def zlib_handler(method):
"""
Prepare hash method and seed depending on CRC32/Adler32.
:param method: "crc32" or "adler32".
:type method: str
"""
hashfunc = zlib.crc32 if method == "crc32" else zlib.adler32
seed = 0 if method == "crc32" else 1
return hashfunc, seed | 46e9d91e5ebe92f3b5b24f138ae693368128ce09 | 699,283 |
def delete_container(client, resource_group_name, name, **kwargs):
"""Delete a container group. """
return client.delete(resource_group_name, name) | d69c3fbd89ce684942af4980ca9931908b12db6a | 699,289 |
def unmatched_places(w, open, close):
"""
Given a word ``w`` and two letters ``open`` and
``close`` to be treated as opening and closing
parentheses (respectively), return a pair ``(xs, ys)``
that encodes the positions of the unmatched
parentheses after the standard parenthesis matching
proc... | cfd2a50c50cecc6fcc08d4fd95df56ad503fa4d2 | 699,290 |
def _clip(n: float) -> float:
"""
Helper function to emulate numpy.clip for the specific
use case of preventing math domain errors on the
acos function by "clipping" values that are > abs(1).
e.g. _clip(1.001) == 1
_clip(-1.5) == -1
_clip(0.80) == 0.80
"""
sign = n / abs(n... | 78308e70a405b3b3d94827c00705e8842b242cde | 699,291 |
import math
def line_intersect(pt1, pt2, ptA, ptB):
"""
Taken from https://www.cs.hmc.edu/ACM/lectures/intersections.html
this returns the intersection of Line(pt1,pt2) and Line(ptA,ptB)
returns a tuple: (xi, yi, valid, r, s), where
(xi, yi) is the intersection
r is the scalar multiple such ... | 73ffd9674302f3be7b0edd9cdddd95df198919cb | 699,295 |
def render_icon(icon):
"""
Render a Bootstrap glyphicon icon
"""
return '<span class="glyphicon glyphicon-{icon}"></span>'.format(icon=icon) | 4fcc501cbea07d3dbe99f35f63dc39c8f629c4c4 | 699,296 |
import binascii
def hex_to_bytes(hex_repn: str) -> bytes:
"""
Convert a hexidecimal string representation of
a block of bytes into a Pyton bytes object.
This function is the inverse of bytes_to_hex.
hex_to_bytes('F803') -> b'\xf8\x03'
"""
return binascii.unhexlify(hex_repn) | 2c456a353e1cce75998d1b2dd9b077af962ee41d | 699,297 |
import re
def get_text_url_base(content):
"""Return base URL to full text based on the content of the landing page.
Parameters
----------
content : str
The content of the landing page for an rxiv paper.
Returns
-------
str or None
The base URL if available, otherwise None... | c679e9e1e8b074f7fea3aaf9eb256542e20a4d7d | 699,298 |
def calculateMatchValue(incompleteObject, knownObject):
"""Calculate an integer match value, scoring +1 for each match"""
matchvalue = 0
for catkey, catval in incompleteObject.items():
if knownObject[catkey] == catval:
matchvalue += 1
return matchvalue | bd0efa089fa9edc2e290a46ca7e18b3d22bd1594 | 699,299 |
def get_contents_dir(node):
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
for n in sorted(node.children(), key=lambda t: t.name):
contents.append('%s %s\n' % (n.get_csig(), n.name))
return ''.join(content... | 147d26ae5fca9540a081feef495dfa4bb0fca8eb | 699,302 |
def two_way_merge(array1, array2):
"""
Given two sorted arrays, merge them into a single sorted array.
This is a very simple operation but is a precursor to k-way merge.
We compare each element at the beginning of each array and remove smaller one and add it to the merged array.
If one of the array... | 6d1a4779634809b7ff63159928af668596f5c00e | 699,304 |
def wavelength_to_energy(wavelength: float):
"""Conversion from photon wavelength (angstroms) to photon energy (eV)"""
return 1.2398 / wavelength * 1e4 | fc067b9fd9cae68103742e8998b6aa0117d906d0 | 699,306 |
import threading
def concurrent_map(func, data):
"""
Similar to the bultin function map(). But spawn a thread for each argument
and apply `func` concurrently.
Note: unlike map(), we cannot take an iterable argument. `data` should be an
indexable sequence.
"""
N = len(data)
result = [... | 5fb482055699087ca7f7b3b95b7d8c425894882f | 699,308 |
def van_vleck_weisskopf(νeval, ν, γ, δ):
"""Complex Van Vleck-Weisskopf line shape function.
νeval GHz frequency at which line shape is evaluated
ν GHz center frequency of line
γ GHz width parameter of line
δ - overlap parameter of line
Returned value is u... | f2f221196fbe911d4582cfc74bf260bb87ce7db0 | 699,310 |
import re
def is_valid_username(field):
"""
Checks if it's an alphanumeric + underscore, lowercase string, at least
two characters long, and starts with a letter, ends with alphanumeric
"""
return re.match(r"[a-z][0-9a-z_]*[a-z0-9]$", field) is not None | b4c870951715e103d58d1187703276dbb21e84cf | 699,313 |
def select_number(list_of_numbers):
"""The player select *one* number of a list of numbers"""
answer = ""
while ((not answer.isdecimal()) or int(answer) not in list_of_numbers):
answer = input("Please type selected number and press ENTER: ")
return int(answer) | af91b18508ff361b0524a551949aac7d93f9afc6 | 699,324 |
def cast(s):
""" Function which clarifies the implicit type of
strings, a priori coming from csv-like files.
Example
-------
>>> cast('1')
1
>>> cast('1.')
1.0
>>> cast('1E+0')
1.0
>>> cast('1E+1')
10.0
>>> cast('one')
'one'
>>> cast('One')
'one'
"""
... | 5e2c9b3b913a733608cab614ae0f08421e489196 | 699,326 |
def is_macosx_sdk_path(path):
"""
Returns True if 'path' can be located in an OSX SDK
"""
return (path.startswith('/usr/') and not path.startswith('/usr/local')) or path.startswith('/System/') | 59b60fa00bf6dd10cf207e6421ea3e4828de5b9c | 699,327 |
import math
def _mean_standard(dist):
"""Find the mean and standard deviation."""
# In the dist dictionary, the key is the value of the metric and
# the value is the number of times it appears. So, the sample
# value is the key and the number of samples for the value is the
# value in dist for th... | 3d90807a619b6fe090571a3f07db807e60c3849c | 699,328 |
def shift2d(x,w,a,b):
"""Shift a 2d quadrature rule to the box defined by the tuples a and b"""
xs=[[a[0]],[a[1]]]+x*[[b[0]-a[0]],[b[1]-a[1]]]
ws=w*(b[0]-a[0])*(b[1]-a[1])
return xs,ws | 84c2090cc0e1689a79aa2c7fa40fb399bc03f535 | 699,329 |
def effective_kernel(kernel_shape, dilations):
"""
Args:
kernel_shape: tuple[int] representing the kernel shape in each
given dimension.
dilations: tuple[int] representing the dilation of the kernel
in each given dimension. Must be the same length as
kernel_... | a955d185c924514bf981c2512a8e78646d523144 | 699,333 |
def int_from_32bit_array(val):
"""Converts an integer from a 32 bit bytearray
:param val: the value to convert to an int
:type val: int
:rtype: int
"""
rval = 0
for fragment in bytearray(val):
rval <<= 8
rval |= fragment
return rval | ca2f32c7eac6f42aeed688510fa57e717edfacdf | 699,334 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.