content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import random
def CrossoverWith(first_flag, second_flag):
"""Get a crossed over gene.
At present, this just picks either/or of these values. However, it could be
implemented as an integer maskover effort, if required.
Args:
first_flag: The first gene (Flag) to cross over with.
second_flag: The seco... | 91ac8842681da4dfcecdc0f3ce0b84d76e293e44 | 682,036 |
def isPalindrome(self, s): # ! 常规思路
"""
:type s: str
:rtype: bool
"""
clean_s = [item.lower() for item in s if item.isalnum()]
while len(clean_s) > 1:
if clean_s.pop(0) == clean_s.pop():
continue
else:
return False
return True | 8be3f590c7a7d329fe699fd85935af6ba63a4391 | 682,037 |
import logging
def get_logger(name):
"""
Proxy to the logging.getLogger method.
"""
return logging.getLogger(name) | 615e8c281f3c30f69339eba4c4ac6b28a7b89b09 | 682,038 |
def change_password(reset_code):
"""Show password change form"""
return dict(reset_code=reset_code) | 6df84c95436cd7f6e07d3b7ad72036303dee1780 | 682,039 |
def chroma_correlate(Lstar_P, S):
"""
Returns the correlate of *chroma* :math:`C`.
Parameters
----------
Lstar_P : numeric
*Achromatic Lightness* correlate :math:`L_p^\star`.
S : numeric
Correlate of *saturation* :math:`S`.
Returns
-------
numeric
Correlate ... | cc583c39c0b64e4075d8f4711163d9cd09875f77 | 682,040 |
def find_median(quantiles):
"""Find median from the quantile boundaries.
Args:
quantiles: A numpy array containing the quantile boundaries.
Returns:
The median.
"""
num_quantiles = len(quantiles)
# We assume that we have at least one quantile boundary.
assert num_quantiles > 0
median_index = ... | 7d65a2fc1f1a6ec5836b841fe5c7e280b0e4c056 | 682,041 |
from pathlib import Path
import string
def guess_pdb_type(pdb_file: str) -> str:
"""Guess PDB file type from file name.
Examples
--------
>>> _guess_pdb_type('4dkl.pdb')
'pdb'
>>> _guess_pdb_type('/tmp/4dkl.cif.gz')
'cif'
"""
for suffix in reversed(Path(pdb_file).suffixes):
... | a156ac86c02d05b6f6783bf62f8e3ad06c717744 | 682,042 |
import re
def replace_text(input_str, find_str, replace_str,
ignore_case=False, regex=True, quiet=True):
"""Find and replace text in a string.
Return the new text as a string.
Arguments:
input_str (str) -- the input text to modify
find_str (str) -- the text to find in the input text
replace_str (str) -- ... | 1979e5a52c2135500d42e00b67d207eddbf248c2 | 682,043 |
def generateLinkLocal(mac):
"""
This works in two steps:
---Make a EUI-64 ID
---Turn that into a link-local address
RFC 2373 defines how to create a EUI-64 ID for a 48-bit mac
"""
#mac = "3c:a9:f4:b8:26:c0"
UL_bitflip_mask = 0b00000010
new_UL_bit = hex(bytes.fromhex(mac[0:2])[0] ^ U... | c3dbce06cb048af9c05415907a018536474e88ac | 682,044 |
def integerize(value):
"""Convert value to integer.
Args:
value: Value to convert
Returns:
result: Value converted to iteger
"""
# Try edge case
if value is True:
return None
if value is False:
return None
# Try conversion
try:
result = int... | 088c4b212d96c2205fa51cf1ddc20bd558efbdfb | 682,045 |
async def _verify_provision_request(request, params):
"""Verifies a received 'provision' REST command.
Args:
request (aiohttp.Web.Request): The request from the client.
params (dict-like): A dictionary like object containing the REST command request parameters.
Returns:
(boolean, s... | fb8db3b3cc8aa12232997e71d5c130402cb45525 | 682,046 |
def verify_filename(filename: str) -> str:
""" Check file name is accurate
Args:
filename (str): String for file name with extension
Raises:
ValueError: Provide filename with extensions
ValueError: Specify a length > 0
Returns:
str: Verified file name
"""
if le... | fe989269d4861d209efddf1b13e84e24ba3cfb0c | 682,048 |
def _batchwise_fn(x, y, f):
"""For each value of `x` and `y`, compute `f(x, y)` batch-wise.
Args:
x (th.Tensor): [B1, B2, ... , BN, X] The first tensor.
y (th.Tensor): [B1, B2, ... , BN, Y] The second tensor.
f (function): The function to apply.
Returns:
(th.Tensor): [B1, B... | bd9b291c00d5905281fb1ac14d3fd2f57c0141ca | 682,049 |
def _pairs(items):
"""Return a list with all the pairs formed by two different elements of a list "items"
Note : This function is a useful tool for the building of the MNN graph.
Parameters
----------
items : list
Returns
-------
list
list of pairs formed by two dif... | 0dad2a9a77bbcb20359c28db2845cb6e46118761 | 682,050 |
import os
def dmg_name(fullversion, pyver, osxver=None):
"""Return name for dmg installer.
Notes
-----
Python 2.7 has two binaries, one for 10.3 (ppc, i386) and one for 10.6
(i386, x86_64). All other Python versions at python.org at the moment
have binaries for 10.3 only. The "macosx%s" part ... | 8738ecb79212fe4ec28f7d3fd56fa66a0aac0ba0 | 682,051 |
def bot_to_slack(message, bot):
"""
A simple routine that posts to a slack channel as 'Onolab_bot'
"""
print("Sending:", message)
data = '{"text":"%s"}' % message
resp = bot.send_message_to_channel("研究室開閉", data)
print("Response:", "ok" if resp else "NG")
return resp | e46a42062f59ad32fefb4fce0e9cce3682a67b08 | 682,052 |
def dt_minutes(dt):
"""Format a datetime with precision to minutes."""
return dt.strftime('%Y-%m-%d %H:%M') | 8f510b9207e89500458324bee86bc1428e1e12c9 | 682,054 |
def baryocentric_coords(pts,pt):
"""See e.g.: http://en.wikipedia.org/wiki/Barycentric_coordinate_system_%28mathematics%29"""
xs,ys=list(zip(*pts))
x,y=pt
det=(ys[1]-ys[2])*(xs[0]-xs[2])+(xs[2]-xs[1])*(ys[0]-ys[2])
l1=((ys[1]-ys[2])*(x-xs[2])+(xs[2]-xs[1])*(y-ys[2]))/float(det)
l2=((ys... | 370bf1a101fb5cae02f4e0703bcf62c29ab4ddd6 | 682,055 |
def pagination_limit():
"""max page return"""
return 50 | c2910ee5e6a819daf36ed2cf62c30180d602e07f | 682,056 |
import logging
import sys
def get_logger(name: str, level) -> logging.Logger:
"""Return logger for calling module
Args:
name (str): [description]
level ([type]): [description]
Returns:
logging.Logger: [description]
"""
logger = logging.getLogger(name)
logger.setLevel(le... | 1b0679d7b4c5a1b199853518fb30ce4742f89b5f | 682,057 |
from sys import modules
def testing():
""" Returns the `testing` module. """
return modules[__name__] # `testing.py` has already been imported | 56835528ff0ddbaf332ff2589098cba14cdcb1bc | 682,058 |
def read_file(filename):
"""Returns the contents of a file as a string."""
return open(filename).read() | bb6906cbc580e57dc9de917f962362305694e393 | 682,059 |
def get_public_scoreboard():
"""Gets the archived public scoreboard.
Kind of a hack, tells the front end to look for a static page scoreboard rather than sending a 2000+ length
array that the front end must parse.
"""
return {'path': '/staticscoreboard.html', 'group': 'Public'} | 98dbee1066d78d7b0b1ac4e68aecc0de1fb9b90d | 682,060 |
def create_dict_keyed_by_field_from_items(items, keyfield):
""" given a field and iterable of items with that field
return a dict keyed by that field with item as values
"""
return {i.get(keyfield): i for i in items if i and keyfield in i} | a7478c5dc04d7e23801eecb5aaf85b7530d6bf79 | 682,062 |
def get_item(value: dict, key: str):
"""Returns a value from a dictionary"""
return value.get(key, None) | 2b27510c1ece30970b263c5b127d2911e8b117ca | 682,063 |
import os
def read_reqs_file(reqs_name):
""" Read requirements file for given requirements group. """
path_reqs_file = os.path.join(
"requirements", "reqs-{}.txt".format(reqs_name))
with open(path_reqs_file, 'r') as reqs_file:
return [pkg.rstrip() for pkg in reqs_file.readlines()
... | 7067999fa974ec0d34d1f15cd1ccae291ab6b12d | 682,064 |
import re
def camelcase(string, uppercase=True):
"""Converts a string to camelCase.
Args:
uppercase (bool): Whether or not to capitalize the first character
"""
if uppercase:
return re.sub(r'(?:^|_)(.)', lambda s: s.group(1).upper(), string)
else:
return string[0].lower() ... | fc480133abcb012124a4557dcc9474eac5bb86cc | 682,065 |
def subcall(rpc_output):
"""
If you want to call another rpc_method from within an rpc_method, and do
something with it's result, but also forward errors, you can wrap it with
this.
Args:
rpc_output (tuple): a tuple of the kind we get from an rpc_method
Returns:
the result half ... | 5cb7769612a13c2620b7aa1077e33a7f506696e0 | 682,066 |
def healthz() -> str:
"""Cosmetic GET route to health-check the service. Used by Kubernetes' pod controller to
check pod health
:returns: ok
:rtype: str
"""
return "ok" | e4c8b2b673e54f42eefa941bc12f137c3372a4f0 | 682,067 |
import os
def relative_path(filename, start=os.path.curdir):
"""Cross platform relative path of a filename.
If no relative path can be calculated (i.e different
drives on Windows), then instead of raising a ValueError,
the absolute path is returned.
"""
try:
dirname, basename = os.pa... | 87e9bef141f54113b09e5083093e1a86fa3497da | 682,068 |
def read_file(file_path):
"""Loads raw file content in memory.
Args:
file_path (str): path to the target file.
Returns:
bytes: Raw file's content until EOF.
Raises:
OSError: If `file_path` does not exist or is not readable.
"""
with open(file_path, 'rb') as byte_file:
... | 5d3d361c3823eeca561895c9b28ca2b2c379f86c | 682,069 |
import random
def rand_unicode(length=8):
"""
:type length: int
:rtype: str
"""
return "".join(chr(random.randint(0, 50000)) for _ in range(length)) | 8758c594030f5c4c75c5de577cde13c05764477d | 682,070 |
def selection_sort(x):
"""
Sorts an array x in non-decreasing order using the selection sort
algorithm.
@type x: array
@param x: the array to sort
@rtype: array
@return: the sorted array
"""
n = len(x)
for i in range(n):
min_idx = i;
for j in range(i + 1, n):
... | 45824b8eaffa8d64b4ed6b7617707229884a87f7 | 682,071 |
def get_most_freq_cui(cui_list, cui_freq):
"""
from a list of strings get the cui string that appears the most frequently.
Note: if there is no frequency stored then this will crash.
"""
cui_highest_freq = None
for cui in cui_list:
if cui in cui_freq:
# sets an initial c... | cb08a41a3b9a7447edf95f3b39b0b2ec7f76e02b | 682,072 |
def delete_all_elements_in_str(string_delete: str, string: str):
"""
delete same string in given list
"""
for i in string:
if i == string_delete:
string = string.replace(i,"")
return string | 730db69de29058fb21204c71f2b568beb7d53602 | 682,073 |
import random
def create_pretrain_delete(tokens, mask_cnt):
"""
Deleted 생성
:param tokens: tokens
:param mask_cnt: mask 개수 (전체 tokens의 15%)
:return deleted: deleted된 tokens
"""
# 단어 단위로 mask 하기 위해서 index 분할
cand_idx = [] # word 단위의 index array
for (i, token) in enumerate(tokens):
... | e92e67e53614ca568fce0d94b22d28059fa1a26f | 682,074 |
def limited(x, z, limit):
"""Logic that is common to invert and change."""
if x != 0:
return min(z, limit)
else:
return limit | 38adca1ab165bd391a3ab856b12a2038d2aa47e8 | 682,075 |
def Annotation(factories, index_annotations):
"""Create and index an annotation.
Looks like factories.Annotation() but automatically uses the build()
strategy and automatically indexes the annotation into the test
Elasticsearch index.
"""
def _Annotation(**kwargs):
annotation = factori... | 315dfd1a4180e4686dd69441efc5c97389c85b69 | 682,077 |
def check_hermes() -> bool:
""" Check if hermes-parser is available on the system."""
try:
return True
except ImportError:
return False | 3bf1d0ceed005e5c85fdd03494cef32fa6a31291 | 682,078 |
from typing import Optional
def _is_in_range(a_list: list,
min: Optional[float] = None,
max: Optional[float] = None) -> bool:
"""
Return True if `a_list` ontains values between `min` and `max`, False
otherwise
"""
for el in a_list:
if min is not None:
... | af50579279e98459dd4ed759c7fe36efd1caeff7 | 682,079 |
def svpwat(t):
"""e = svpwat(t)
Calculates the water vapor mixing ratio
Inputs: (all vectors of same length)
t = dry bulb temperature(s) (K)
Outputs:
e = saturation vapor pressure with respect to a plane surface of ice (mb)
RLT, 010710
"""
A0 = 0.999996876e0
A1 = -0.9082695004e-2
A2 = 0.7873616869e... | bc09eeb55bb17589a7f9879c2e6e577acc590262 | 682,080 |
def calculateAvgMass(problemFile,windno):
"""
Calculate the average mass of a winds flow
Inputs:
- dict problemFile: problem file, containing mass fractions
- int windno: wind number, counting from 1
Outputs:
- avgMass: average mass of particles in wind (g)
"""
protonmass = 1.6726219e-24
... | a4522d98fbe91aa45ebb25f0a64f9ebdb0abbe3e | 682,081 |
def get_reorg_matrix(m, m_size, transition_state_nb):
"""
Reorder the matrix to only keep the rows with the transition states
By storing the new order in an array, we can have a mapping between new pos (idx) and old pos (value)
For example reorg_states = [2,3,1,0] means the first new row/col was in posi... | 35cf06daa0225e53fbdc21f2fe34a3337c1b1901 | 682,082 |
import time
def _get_time_diff_to_now(ts):
"""Calculate time difference from `ts` to now in human readable format"""
secs = abs(int(time.time() - ts))
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
time_ago = ""
if hours:
time_ago += "%dh" % hours
if mins:
tim... | 091f420971f23432c3ebaa1bef93b60ff2953c88 | 682,083 |
def _read_file(name, encoding='utf-8'):
"""
Read the contents of a file.
:param name: The name of the file in the current directory.
:param encoding: The encoding of the file; defaults to utf-8.
:return: The contents of the file.
"""
with open(name, encoding=encoding) as f:
return f... | c0a03bee2d4ef48dd13c72cc3b05f7e10d724e5c | 682,084 |
def binary_array_search(A, target):
"""
Use Binary Array Search to search for target in ordered list A.
If target is found, a non-negative value is returned marking the
location in A; if a negative number, x, is found then -x-1 is the
location where target would need to be inserted.
"""
lo =... | a1f4908032910ea6a7c14e9509953450c9a0a44e | 682,085 |
def _convert_float(value):
"""Convert an "exact" value to a ``float``.
Also works recursively if ``value`` is a list.
Assumes a value is one of the following:
* :data:`None`
* an integer
* a string in C "%a" hex format for an IEEE-754 double precision number
* a string fraction of the for... | 7896c97dafd577b6eefec452f5983c8c06c5f831 | 682,086 |
def PaddingLayerParams(op, insym, symtab):
"""Hacking for padding layer params."""
if op.WhichOneof('PaddingType') == 'constant':
constant = op.constant
if constant.value != 0:
raise NotImplementedError("Padding value {} not supported.".format(constant.value))
padding = [b.st... | e3c970d99fa14a82db7d5a283f09b76a0f1bfb1b | 682,087 |
async def read_file(file_path: str):
"""
You could need the parameter to contain /home/johndoe/myfile.txt, with a leading slash (/).
In that case, the URL would be: /files//home/johndoe/myfile.txt, with a double slash (//) between files and home.
"""
return {"file_path": file_path} | 6e36555aaca09fc06b50f399f2300fb274755419 | 682,088 |
def merge(args_array, cfg, log):
"""Function: merge_repo
Description: This is a function stub for merge_repo.merge_repo.
Arguments:
args_array -> Stub argument holder.
cfg -> Stub argument holder.
log -> Stub argument holder.
"""
status = True
if args_array and cf... | 0de179b48306e18e53778d0d50722352786b695c | 682,089 |
def origin2center_of_mass(inertia, center_of_mass, mass):
"""
convert the moment of the inertia about the world coordinate into
that about center of mass coordinate
Parameters
----------
moment of inertia about the world coordinate: [xx, yy, zz, xy, yz, xz]
center_of_mass: [x, y, z]
... | 9d083c767956b0dddf3a7fea10c17c42fe9354d3 | 682,091 |
import re
def get_valid_user_input():
"""Prompt user to define device or partition to wipe.
"""
while True:
try:
device = input(
"Enter letter [number] of device/partition to wipe,"
"\ne.g. to wipe '/dev/sdb1' enter 'b1': ")
if not re.match... | 92a695e03e651ca82c4da7c2003b7fc742ec83be | 682,094 |
def serialize_titular_bien(titulares):
"""
# $ref: '#/components/schemas/titularBien'
"""
# TBD
if titulares:
return [{
"clave": titulares.codigo if titulares.codigo else "DEC",
"valor": titulares.tipo_titular if titulares.tipo_titular else "DECLARANT... | 90c428f747c74548ceff478259e844305549cdcd | 682,095 |
import logging
def make_logger():
"""Return a logger instance."""
return logging.getLogger('django.request') | 871ad402896e07d31cb97938299f91e34a466329 | 682,096 |
def _versionTuple(versionString):
"""
Return a version string in 'x.x.x' format as a tuple of integers.
Version numbers in this format can be compared using if statements.
"""
if not isinstance(versionString, str):
raise ValueError("version must be a string")
if not versionString.count("... | cc64832a8b7c1c46d639a8628ca7afd8701d7135 | 682,097 |
import re
def SplitBehavior(behavior):
"""Splits the behavior to compose a message or i18n-content value.
Examples:
'Activate last tab' => ['Activate', 'last', 'tab']
'Close tab' => ['Close', 'tab']
"""
return [x for x in re.split('[ ()"-.,]', behavior) if len(x) > 0] | c388e0a2b57e1826176d7032775622abd0ca5f7c | 682,099 |
from sys import version_info
def is_sphinx_version_lower_than(version):
"""Return true if current Sphinx version is less than specified version
"""
major, minor, patch, _, _ = version_info
return (major, minor, patch) < version | bca513119c0972a0f71bc23bf77bfc68baee2052 | 682,100 |
def reformat(keyword, fields):
"""
Reformat field name to url format using specific keyword.
Example:
reformat('comment', ['a','b']) returns
['comment(A)', 'comment(B)']
"""
return ['{}({})'.format(keyword, f.upper()) for f in fields] | b277eb2efdb78d49035c319e1ca31c1c7ff3e333 | 682,101 |
def diff_msg_formatter(
ref,
comp,
reason=None,
diff_args=None,
diff_kwargs=None,
load_kwargs=None,
format_data_kwargs=None,
filter_kwargs=None,
format_diff_kwargs=None,
sort_kwargs=None,
concat_kwargs=None,
report_kwargs=None,
): # pylint: disable=too-many-arguments
... | 8586c9364e1aef2777cf33a91efa4ffd8aa48708 | 682,102 |
def corn() -> str:
"""Return the string corn."""
return "corn" | e8cbbc3804a24006f2eeef72f9a03cb5a737283d | 682,103 |
import os
import shutil
def _CopyResultsDir(src, dest):
"""Copies a results dir to a new directory for archiving.
Args:
src: String source path.
dest: String destination path (presumably under
generic_stages.ArchivingStageMixin.archive_path). Must not exist
already.
Raises:
OSE... | b37e5d41fd473913416fae2b213bffdd5560080e | 682,104 |
def get_atom_groups(atom):
"""
returns a dictionary of functional groups attached to the
specified atom `atom` for molecule `molecule`, which contains
atom ID numbers. Ignores neighbors with labels.
Does not get cyclic values.
"""
functional_groups = {}
for nn, bond in atom.bonds.it... | a870f5e4d5c54fe286faf3974b8553d2f513ccd5 | 682,105 |
def celsius_to_rankine(temp: float) -> float:
"""
Converts temperature in celsius to temperature in rankine
Args:
temp (float): supplied temperature, in celsius
Returns:
float: temperature in rankine
"""
return (9 / 5) * temp + 491.67 | aac1daf7b9681c7ece129b2a1f5ca7e7b9388ad9 | 682,106 |
def configs_check(difflist):
"""
Generate a list of files which exist in the bundle image but not the base
image
'- ' - line unique to lhs
'+ ' - line unique to rhs
' ' - line common
'? ' - line not present in either
returns a list containing the items which are unique in the rhs
... | 897c0b9c05e26619f4d10f693173642f2ffabc8a | 682,107 |
def pytest_report_header(config):
"""Test report header."""
rh = "Testing server base url: " + config.getoption("--baseurl")
if config.getoption("--remote-server"):
rh += '\n WARNING: Not cleaning tables on remote server.'
rh += '\n On remote server run : `app_setup.py --only-tables` \n'
... | 53469fb5ef898541be77aa92b6838b804ecaa89a | 682,108 |
def binarize_syllable(syllable):
"""Return 1 or 0 depending on Guru or Laghu syllable.
Input
syllable : string of characters denoting a syllable
Ouptut
0 for Laghu, 1 for Guru
"""
guruMarkers = [u'\N{DEVANAGARI LETTER AA}', u'\N{DEVANAGARI LETTER II}',
u'\N{DEVANAGARI LETTER UU}', u'... | b8ea3fecefd9f005e101538222e9b121b2c7a31a | 682,109 |
import os
def get_path_to_recording(local_download_dir, surah_num, ayah_num, filename):
"""
Returns the path of a single recording, given the local_download_dir, the surah and ayah numbers, and the filename.
"""
local_path = os.path.join(local_download_dir, "s" + str(surah_num), "a" + str(ayah_num), f... | ed4d6747163f554b428bda1dc37a90cecdac9c36 | 682,110 |
def _broadcast_bmm(a, b):
"""
Batch multiply two matrices and broadcast if necessary.
Args:
a: torch tensor of shape (P, K) or (M, P, K)
b: torch tensor of shape (N, K, K)
Returns:
a and b broadcast multipled. The output batch dimension is max(N, M).
To broadcast transforms a... | 152769b8509eb709d7b762cc718543006dbf29f2 | 682,111 |
def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
results = []
results.extend(
input_api.canned_checks.CheckChangedLUCIConfigs(input_api, output_api))
return results | 5ffed5770f6f776851ebe08db0c1bbdf66b89694 | 682,112 |
import re
def _htmlPingbackURI(fileObj):
"""Given an interable object returning text, search it for a pingback URI
based upon the search parameters given by the pingback specification.
Namely, it should match the regex:
<link rel="pingback" href="([^"]+)" ?/?>
(source: http://www.hixie.ch/specs... | 342f401cb955af511040be30cb56c80d05dfeeda | 682,113 |
def add_train_args(parser):
"""Add training-related arguments.
Args:
* parser: argument parser
Returns:
* parser: argument parser with training-related arguments inserted
"""
train_arg = parser.add_argument_group('Train')
train_arg.add_argument('--train_prep',
... | de97966105e08c03f0de180f0385e2ccd6a455ea | 682,115 |
import uuid
import time
def generate_random_string():
"""
Generate a random string
"""
random = str(uuid.uuid4())
random = random.replace("-","")
tstr = str(int(time.time() * 1000))
random = random + tstr
return random | a8d4ec05541a9e5a73cd11e881d681f10b1b15c3 | 682,116 |
def _convert_graph(G):
"""Convert a graph to the numbered adjacency list structure expected by
METIS.
"""
index = dict(zip(G, list(range(len(G)))))
xadj = [0]
adjncy = []
for u in G:
adjncy.extend(index[v] for v in G[u])
xadj.append(len(adjncy))
return xadj, adjncy | ba3fc856896c5e6ac1a76668cff519871ee7805d | 682,117 |
import struct
import socket
def d2ip(d):
"""Decimal to IP"""
packed = struct.pack("!L", d)
return socket.inet_ntoa(packed) | e54252c85e7403531342e3fc71a0ebf5f6b5fe16 | 682,118 |
import zlib
def crc32_hex(data):
"""Return unsigned CRC32 of binary data as hex-encoded string.
>>> crc32_hex(b'spam')
'43daff3d'
"""
value = zlib.crc32(data) & 0xffffffff
return f'{value:x}' | 0535421da8671f7d3d329c0c8e0a4cf51a29d1cf | 682,119 |
import re
def fix_punct_spaces(string: str):
"""
fix_punct_spaces - replace spaces around punctuation with punctuation. For example, "hello , there" -> "hello, there"
Parameters
----------
string : str, required, input string to be corrected
Returns
-------
str, corrected string
... | ba6e532b2ba702e6a4f4d76484f184a406c5a629 | 682,120 |
from datetime import datetime
def find_time_since(previous_time):
"""Just finds the time between now and previous_time."""
return datetime.now() - previous_time | 6cdeff0005cf58aa5bd0fc174658e8524a40c83c | 682,121 |
def escape_reserved_keyword(word):
"""
# Escape reserved language keywords like openapi generator does it
:param word: Word to escape
:return: The escaped word if it was a reserved keyword, the word unchanged otherwise
"""
reserved_keywords = ["from"]
if word in reserved_keywords:
re... | cd6d628c4369cff012437a4b4dae2b51ebacca41 | 682,123 |
def _update_shape_dtype(shape, dtype, params):
"""Update shape dtype given params information"""
if not params:
return shape, dtype
shape = shape.copy()
shape.update({k : v.shape for k, v in params.items()})
if isinstance(dtype, str):
for k, v in params.items():
if v.dtyp... | 332f7bad1e82e768185d0c43494eeb0e9ffa384c | 682,124 |
import argparse
def get_args() -> dict: # pragma: no cover
"""Command line argument parser."""
parser = argparse.ArgumentParser()
parser.add_argument(
"path",
type=str,
)
args = parser.parse_args()
return {
"path": args.path,
} | 6b2004f373965bfe70daee72da2dc68e02d61319 | 682,125 |
def _evalPrefix(cad):
"""
Internal function
"""
pot={'k':1e3,'M':1e6,'G':1e9,'T':1e12,'P':1e15,'E':1e18
,'m':1e-3,'u':1e-6,'n':1e-9,'p':1e-12,'f':1e-15,'a':1e-18}
if cad in pot:
return pot[cad]
return None | 90b2f817a85e0bffea9d0af0165dbe3303183a82 | 682,126 |
import subprocess
def run_shell(command):
"""Run a command in the shell, returning stdout and stderr combined."""
if isinstance(command,list):
command = ' '.join(map(str,command))
print(command)
output = subprocess.run(command, stdout=subprocess.PIPE,
st... | 55836fa7d9d753aa04cf0a3643eb1f569ec85564 | 682,128 |
def dansCercle(x,y, cx,cy, r):
"""
Teste l'appartenance à un cercle.
Paramètres:
(x,y) --> point à tester,
(cx,cy) --> centre du cercle,
r --> rayon du cercle.
Retourne ``Vrai`` si le point est dans le cercle, ``Faux`` sinon.
"""
return (x-cx)**2 + (y-cy)**2 <= ... | a429bc6a40d0c49bbc331d9cf0f4011137188900 | 682,129 |
from typing import Collection
def split_identifier(all_modules: Collection[str], fullname: str) -> tuple[str, str]:
"""
Split an identifier into a `(modulename, qualname)` tuple. For example, `pdoc.render_helpers.split_identifier`
would be split into `("pdoc.render_helpers","split_identifier")`. This is n... | aa9e6ace179634167d8820ccf4d48053ce64ca59 | 682,130 |
def read_txt(filename='filename.txt'):
"""Read a text file into a list of line strings."""
f = open(filename, 'r')
data = f.readlines()
f.close()
return data | ee74a55af75cbbf5f5065f97becf663cc7d01344 | 682,131 |
def add_limit(limit):
"""plus 1 to limit
To know if there is next or preview page, we need to find an extra document which will not be returned to user.
"""
return abs(limit) + 1 | c4304a88b677e0f4e4c358d03592dfad077e6de1 | 682,132 |
import re
def _str_time_to_sec(s):
"""
Converts epanet time format to seconds.
Parameters
----------
s : string
EPANET time string. Options are 'HH:MM:SS', 'HH:MM', 'HH'
Returns
-------
Integer value of time in seconds.
"""
pattern1 = re.compile(r'^(\d+):(\d+):(\d+... | 5bb000920ff3295607317f4d8d001a4b7b859549 | 682,133 |
def apisecret(request):
"""Return API key."""
return request.config.getoption("--apisecret") | 152694affb473bc1f44678cda3b89d6aa95804ad | 682,134 |
import re
def phone_valid(number):
"""
Check if the phone number is valid
:param number: phone number in a string type
:return: True or False
"""
model = '[0-9]{2} [0-9]{5}-[0-9]{4}'
return re.findall(model, number) | 823b3ad20612552c7bc5b32b50304d92a796c74d | 682,135 |
def pretty_hex_str(byte_seq, separator=","):
"""Converts a squence of bytes to a string of hexadecimal numbers.
For instance, with the input tuple ``(255, 0, 10)``
this function will return the string ``"ff,00,0a"``.
:param bytes byte_seq: a sequence of bytes to process. It must be
compatible ... | 2f3f43bffff140320b12dce5d423d7e3f64b88e5 | 682,136 |
import re
def sanitize_sql(s):
"""Sanitize the sql by removing all new lines and surrounding whitespace."""
s = re.sub('[ \\s\n\r]*\n[ \\s\n\r]*', ' ', s, flags=re.MULTILINE)
s = re.sub('\\([ \t]+', '(', s)
s = re.sub('[ \t]+\\)', ')', s)
return s.strip() | 801c5856bc5ad69a2b3252b481526ba168d79b26 | 682,137 |
def score2durations(score):
""" Generates a sequence of note durations (in quarterLengths) from a score.
Args:
score (music21.Score): the input score
Returns:
list[float]: a list of durations corresponding to each note in the score
"""
return [n.duration.quarterLength for n in scor... | 2b7060bd5101a10ae4816816a8fbdc812c311cf2 | 682,138 |
import os
async def __link_notification_hub(clients, args):
"""
Link a Notification Hub to the Communication Service
"""
print("\nLink Notification Hub...")
# Resource ID of the Notification Hub you want to link; `<your-tenant-id>`
notification_hub_resource_id = os.environ.get("AZURE_NOTIFIC... | 6069d36d7f23f8e5a36d8ae94944460c4dbddaf4 | 682,139 |
import re
def download_dependent_rpms_rhel7(log, host, target_cpu, packages_dir,
dependent_rpms, extra_package_fnames):
"""
Download dependent RPMs for RHEL7
"""
# pylint: disable=too-many-locals
command = "repotrack -a %s -p %s" % (target_cpu, packages_dir)
f... | 8635b645cb230cf7f4ac13a45d0bd22a7be67f4c | 682,140 |
from typing import Any
def startswith(query: str, field_name: str, object: Any) -> bool:
"""
Check if a string is Starts With the query (Case Sensitive)
"""
return str(getattr(object, field_name)).startswith(str(query)) | cc3e0a28d922c298d5b4d4e36c3c5bd05ef90870 | 682,142 |
import torch
def complex_abs_sq(data: torch.Tensor) -> torch.Tensor:
"""
Compute the squared absolute value of a complex tensor.
Args:
data: A complex valued tensor, where the size of the final dimension
should be 2.
Returns:
Squared absolute value of data.
"""
if... | 42a2cc3daec9ee8cc381985622d89f7ca0665a5d | 682,143 |
import yaml
def convertYMLtoJSON(yFile):
"""
Just convert a YML file to JSON an returns it.
"""
with open(yFile, "r", encoding="utf8") as y_file:
yDic = yaml.load(y_file, Loader=yaml.FullLoader)
return yDic | 7469b1ade25eabc73e463523930c540ad16c16d9 | 682,144 |
def has_attribute(object, name):
"""Check if the given object has an attribute (variable or method) with the given name"""
return hasattr(object, name) | 44f0cd1cc54fe61b755d94629e623afe234fe99d | 682,145 |
def filtro_ternario(cantidad_autos: int, numero_auto: int) -> int:
""" Filtro ternario
Parámetros:
cantidad_autos (int): La cantidad de carros que recibe el operario en su parqueadero
numero_auto (int): El número único del carro a ubicar en alguno de los tres lotes de parqueo. Se
... | 5607c83bc7e3e3cc28dd33e72bc86c943884bf3f | 682,146 |
def text_alignment(x: float, y: float):
"""
Align text labels based on the x- and y-axis coordinate values.
This function is used for computing the appropriate alignment of the text
label.
For example, if the text is on the "right" side of the plot, we want it to
be left-aligned. If the text i... | 477ab0dffa22de16af3d1811b39fbfc5289c4327 | 682,147 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.