content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def add(x, y):
"""Adds x to y"""
# Some comment
return x + y | 5bf9e5b43e69438fdc76f511f088f5a28ca4fa21 | 591,240 |
def match_cases(original, replacement):
""" Returns a copy of the replacement word with the cases
altered to match the original word's case
Only supports upper case, capitalised (title) and lower case -
everything else gets lower cased by default"""
if original.isupper():
return ... | a3886a936aee8ae36a8200aacebd08b5f6ca7545 | 591,241 |
import torch
def calc_psnr(img1, img2):
""" PSNR calculator
:param img1: true/estimated image
:param img2: estimated/true image
:return: PSNR value
"""
return 10. * torch.log10(1. / torch.mean((img1 - img2) ** 2)) | efe6ac64ec22ad8ed57421d14b2179970b1184b6 | 591,244 |
def SplitFieldName(qualified_field_name):
"""Splits the field name on '/' and returns the parts separately.
Args:
qualified_field_name: the possibly fully qualified field name
Returns:
tuple with namespace and raw field name. Defaults to global for no
namespace.
"""
field_only = qualified_fiel... | 4bf4f5778cc519e6c29f17a92eceb1bc0db99720 | 591,245 |
import re
def get_simple_version(version_string):
"""Extract the version number without the ><= requirements.
This simply extracts the version number without the ><= requirement so
it will not be accurate for version requirements that are not >=, <= or
= to a version.
>>> get_simple_version('>=3... | 7b964248200ab8559a0411ac633253c0941c9cfd | 591,249 |
def find_next_non_blank_token(tokens, i):
"""
Find next non-blank token after index i (including i).
Args:
tokens (list[str]): a string token list.
i (int): the position to search.
Returns:
If any token is found, return the found token.
Otherwise, return None.
"""
... | a2cf2f33ea0e03625b34577d240d3b77e7947a47 | 591,250 |
def _parse_directories(dir_list):
"""Helper function for parsing and cleaning a list of directories for analysis.
:param list[str] dir_list: A list of directories to parse.
:rtype: list[str]
:return: The cleaned up list of directories.
"""
return [line for line in dir_list if line is not None] | eb66681f2f98c8189fb08a497641d0d0240f054f | 591,251 |
def bytes2str(val):
"""
Converts a bytes into a hex string.
"""
return f'0x{val.hex()}' | 5be3312c34691d3142c26d96f474dbd8d081cc6b | 591,256 |
def __get_type_JMA(code):
"""
Get the type (grade) of the JMA TC records.
Reference:
https://www.jma.go.jp/jma/jma-eng/jma-center/rsmc-hp-pub-eg/Besttracks/e_format_bst.html
1 - not used
2 - tropical depression (TD)
3 - tropical storm (TS)
4 - severe tropical storm (STS)
5 - typ... | a224470f874f42fb0047ca1b28f0308199f1c079 | 591,257 |
from typing import Iterable
from functools import reduce
from operator import ixor
def calculate_checksum(message: Iterable[int]) -> int:
"""
Calculates the checksum, which is the XOR of all bytes in the message
"""
return reduce(ixor, message) | fc8b5183575fb102ad7fe182a0e29fc0320a02bb | 591,260 |
def mask(collection, collection_ty, booleans):
"""
Returns a masking operation that filters values from 'collection' using
the bitvector 'booleans'.
Examples
--------
>>> mask("v", "i64", "mask").code
'map(filter(zip(v, mask), |e: {i64,bool}| e.$1), |e: {i64,bool}| e.$0)'
"""
struc... | 3cc46a3aa8c0fb56be7e714217aae1f2207f2c6f | 591,261 |
import math
def _expected_m0(ref_mean, t1, t2, pc, gain=1.0, alpha=1.0, te=0, tr=3.2, t2b=150):
"""
Expected M0 value from reference region mean
"""
#print("ref mean: ", ref_mean)
m0 = ref_mean / (1 - math.exp(- tr / t1))
#print("T1 correction: ", m0)
m0 = m0 / math.exp(-te/t2)
m0 = m... | 2dc2d617968fc7d3555e3354b4dd84af40203f06 | 591,264 |
def LabelIDsInvolvedInConfig(config):
"""Return a set of all label IDs referenced in the config."""
result = set()
for cd in config.component_defs:
result.update(cd.label_ids)
return result | e559313c903a9f61d89ca7f88772c05496156189 | 591,265 |
def rsa_crt_dmp1(private_exponent: int, p: int) -> int:
"""
Compute the CRT private_exponent % (p - 1) value from the RSA
private_exponent (d) and p.
"""
return private_exponent % (p - 1) | f61158211b67fff84c2573f71419a9714dcdfea3 | 591,268 |
import pickle
def from_pickle(fname):
"""Load from pickle file
Load from pickle file
Args:
fname(str): Filename to read
Note:
Watch out for pickle objects, as they can be hacked.
Example: https://realpython.com/python-pickle-module/
"""
return... | 54400f3b7b1feea6700a4462d26d9d76131ad593 | 591,272 |
def final_path_colors(initial_node_colors, problem, solution):
"""Return a node_colors dict of the final path provided the problem and solution."""
# get initial node colors
final_colors = dict(initial_node_colors)
# color all the nodes in solution and starting node to green
final_colors[problem.in... | 9657400ada26332762304807945a034391de461b | 591,274 |
def jsonify(dataset, variable):
"""
Extract a time series from a THREDDS dataset at the given location.
Args:
dataset(xarray.Dataset): an xarray dataset.
variable(str): Name of the variable to query.
Returns:
dict: JSON-compatible Python Dict.
"""
str_time_da = dataset.... | 43205368dc364198fbe0bd7d888c47d6627906cd | 591,275 |
import re
def replace_track_tags(content):
"""Replaces tags like {4} to formatting compatible tags like {tracks[4]}."""
return re.sub(r"{(\d+)}", '<i>{tracks[\\1]}</i>', content) | 199cc45ae5028c64075ef3fd4cf13debf5ec480b | 591,278 |
def does_include(text, chars):
"""Check if text contains any character from chars."""
return any(char in text for char in chars) | 83ed980f37ecde4003da40737d554e7e1a5a1470 | 591,279 |
def get_consolidated_topics_list(
fallback_topics,
snapshot_type,
default_topic_list_full,
default_topic_list_incremental,
topics_overrides=None,
):
"""Works out the topics needed for snapshot sender based on the passed in overrides.
Keyword arguments:
fallback_topics -- the topics for ... | a96c80411feb1e7589a398db8fa3e93f94596bab | 591,280 |
def clip(x, minimum=None, maximum=None):
"""Clip (limit) input value.
Parameters
----------
x : float
Value to be clipped.
minimum : float
Lower limit.
maximum : float
Upper limit.
Returns
-------
float
Clipped value.
"""
if minimum is not N... | e1b823ddeaad17b24e8dd168695b548b62953f89 | 591,281 |
def char(cA, cB):
"""Returns the appropriate single qubit pauli character when merging."""
if cA == "I":
return cB
return cA | 977f9acb4d476aee70c20301b952f1118b3d5349 | 591,283 |
def get_inserts(block):
"""Identify the inserts in sequence in a block.
Inserts are relative to the consensus (theoretically), and identified by
lowercase letters in the sequence. The returned integer pairs represent the
insert start and end positions in the full-length sequence, using one-based
nu... | 3b287db2d3c7e8dc55a2d4523706cf614311a05f | 591,286 |
import re
def _redact_volatile(output: str) -> str:
"""
Replace some volatile values, like temp paths & memory locations.
>>> _redact_volatile("<__main__.A at 0x10b80ce50>")
'<__main__.A at 0x...>'
>>> _redact_volatile("/tmp/abcd234/pytest-accept-test-temp-file-0.py")
'/tmp/.../pytest-accept... | 6a53bf858618c255134c54707550afa4b3934d3b | 591,293 |
from typing import Dict
def role_has_managed_policy(role: Dict, managed_policy_name: str) -> bool:
"""
Checks a role dictionary to determine if a managed policy is attached
:param role: An AWS role dictionary (from a boto3 get_role or get_account_authorization_details call)
:param managed_policy_name:... | 2cd6e2f237c224673b455cd92990072e164197ad | 591,296 |
from typing import Dict
from typing import Any
def can_enclose(objectA: Dict[str, Any], objectB: Dict[str, Any]) -> bool:
"""Return True iff each 'dimensions' of objectA is >= the corresponding dimension of objectB."""
return objectA['dimensions']['x'] >= objectB['dimensions']['x'] and \
objectA['dime... | 5438403f68746f4f083639dfe1488a9370e52810 | 591,298 |
def confirm(prompt: str, sep: str = ': '):
""" Prompts the user with a yes/no prompt
Args:
prompt: Prompt user sees on the command-line
sep (Optional): Separator symbol between prompt and input
Outputs:
selection (bool): True if user indicates "yes"
"""
final_prompt = f"{pr... | 74ce122ba2078561bb480dcb754996c8e1d8b170 | 591,299 |
from typing import Optional
import re
def _can_disambiguate_from_context(
line: str, old_string: str, type_: str
) -> Optional[bool]:
"""
Check whether we can disambiguate the public id given contextual information.
For example:
- whether the public id appears in a line of the form 'aea fetch ...... | d8102fad673344f47dbae5514be6c82f8c27ff8b | 591,301 |
def line_with_check_passed(line, prefix):
"""Check if the processed line contains dead code measurement summary that passed."""
return line.startswith(prefix) | f31b57c2ee4ed94daab756bb3a6026ced6135e16 | 591,303 |
def correct_folder_path(folder: str) -> str:
""" checks if given folder ends with "/" cuts that off """
return folder.rstrip('/') | f720d18382382eb6f5b554af990d962a96a78956 | 591,306 |
def state_attributes(self):
"""Return the attributes of the entity."""
return self._attributes | c81fa9b8e411c37ea0d0e2764f4e1d1a023b8649 | 591,309 |
def transform_headers(headers):
"""
Boto url-encodes values unless we convert the value to `str`, so doing
this prevents 'max-age=100000' from being converted to "max-age%3D100000".
:param headers: Headers to convert
:type headers: dict
:rtype: dict
"""
for key, value in headers.item... | a9033ff06fdd126c5525b3904f4daeb159d724cc | 591,310 |
def recvall(client_socket, packet_size):
"""
Keep receiving up to `packet_size` bytes, returning partial result
if connection closed normally by remote.
Params:
client_socket (socket.socket() object) : client socket connection to webserver
packet_size (int) : packet size of message
... | 4b0c2e7a5c0acc0fc6cdd3b9909dd176a618734e | 591,313 |
import random
def create_random_proteins_from_distribution(length_lst,
amino_acid_lst,
amino_acid_distribution=None):
"""Create random protein from distribution.
https://docs.python.org/3/library/random.html#random.ch... | 9a0f65d06fa70d48c050db7d6ce04814b8ef784c | 591,314 |
def q(a: float, e: float) -> float:
"""
q = a * (1 - e)
:param a: semi-major axis
:type a: float
:param e: eccentricity
:type e: float
:return: pericentric distance
:rtype: float
"""
return a * (1 - e) | 733c10a4886e1d98e25c2dd2890a787f040ff8f2 | 591,316 |
import torch
def pow(input, exponent, *args, **kwargs):
"""
Takes the power of each element in ``input`` with ``exponent`` and
returns a tensor with the result.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.pow(
... ttorch.tensor([4,... | 8fe53d36f4bf0cbd6e50c60813c019ed81e43eb1 | 591,317 |
def max_value_1_highest_weight_value_ratio(weight_value_tuples, max_capacity):
"""
Solution: Compute the max value by finding the item with the highest
weight to value ratio and use it as many times as possible until we need
to find a smaller one that fits into the knapsack but still has the
greatest weight to val... | 00ef3d3c0b155fc47b189ac52660eaf8aba4cf0a | 591,322 |
def to_string(board):
"""Make an ascii-art representation of a board."""
rows = []
for r in range(board.board_size):
row = ''
for c in range(board.board_size):
row += board.board.get((r, c), '.')
rows.append(row)
rows.reverse()
return '\n'.join(rows) | e2a48cc830e4445d32a646c74f7e1907cada75a2 | 591,323 |
def init_obj(module_name, module_args, module, *args, **kwargs):
"""
Finds a function handle with the name given as 'type' in config, and returns the
instance initialized with corresponding arguments given.
`object = config.init_obj('name', module, a, b=1)`
is equivalent to
`object = module.name... | eb15b447881a5f8b681e06064a8d57140281800b | 591,328 |
from typing import List
from typing import Dict
from typing import Any
def filter_executables(items: List[Dict[str, Any]], executables: List[str]) -> List[Dict[str, Any]]:
"""Returns only payloads for given list of executables."""
if not executables:
return items
filtered = []
for item in ite... | 1dee151bea6163536c62f4d0524f24f69700815b | 591,332 |
def bool_(input_):
""" Convert boolean or string to boolean, also 'False' and 'F' to False """
return bool(input_) if input_.upper() not in ["FALSE", "F"] else False | 5388df32ab10464cd603c0cc2358a12928f8045b | 591,333 |
import ast
def _node_returns_bool_const(node: ast.stmt) -> bool:
"""Checks if a Return node would return a boolean constant."""
return (
isinstance(node, ast.Return) and
isinstance(node.value, ast.NameConstant) and
isinstance(node.value.value, bool)
) | e0d4758ba3a9d8f32f86779f64477fca7409244f | 591,336 |
import requests
import json
def getWbDistrictID(st_id, lookout_district):
"""
Function to get district id from state id and district name
Parameters
----------
st_id : String
ID associated with a state.
lookout_district : String
District name for which we need the district id.... | bca911fb3003d03cc7303c5dbf5352c90b4dc022 | 591,337 |
def _process_config(config):
"""
Make sure config object has required values
"""
required_fields = [
"account_sid",
"auth_token",
"from_phone",
"to_phone",
]
for field in required_fields:
if field not in config:
raise ValueError("required... | 975dfb9bfd9400c478abb5a7103c1f4591080b2a | 591,342 |
def translate(parsed):
"""
translate a tuple (mod, args) to a string
"""
if isinstance(parsed, tuple):
return '%s(%s)' % (parsed[0], ', '.join(map(translate, parsed[1])))
else:
return parsed | aa67dee8433103cd5273374c2a46db8000d9ea8c | 591,343 |
def map_collection(collection, map_fn):
"""Applies ``map_fn`` on each element in ``collection``.
* If ``collection`` is a tuple or list of elements, ``map_fn`` is applied on each element,
and a tuple or list, respectively, containing mapped values is returned.
* If ``collection`` is a dictionary, ``m... | 015c8acfc57fcb88c870c500b2e7483cd9980c36 | 591,345 |
def code() -> str:
"""
Example G-code module, a fancy drawing of two squares, one fully milled, one sides-only.
Please simulate first, before milling.
"""
return """
G91 G17
G0 X7 Y0
G0 X0 Y18
G0 X-18 Y0
G0 X0 Y-18
G0 X10 Y0
G0 X0 Y-5
... | be260ad91d2baf42d93a4a6667d51b70444c5b0d | 591,347 |
def get_metabolite_name(compound):
"""Get metabolite id from compound name."""
return f"M_{compound}_c" | 6823aa52dff7964288c02a1d484f331d13b465a4 | 591,348 |
import itertools
from typing import List
def itertools_combinations(string: str, n: int) -> List[str]:
"""
>>> itertools_combinations('HACK', 2)
['A', 'C', 'H', 'K', 'AC', 'AH', 'AK', 'CH', 'CK', 'HK']
>>> itertools_combinations('ABCD', 3) #doctest: +NORMALIZE_WHITESPACE
['A', 'B', 'C', 'D', 'AB',... | 142735ef1760d7eaaf114d7f74db28189dc21921 | 591,350 |
def split_by_key_presense(l, key):
"""Split list of dictionaries into two lists based on key presense
Parameters
----------
l : List[Dict[str, Any]]
List to split
key : str
Key to find in list's dictionaries
Returns
-------
Tuple[List[Any], List[Any]]
First list... | 72ed8c37df62b356b86ad39e3e3ff87b4dd818b4 | 591,351 |
import re
def noqa_reformat(source: str) -> str:
"""
Pull ``# noqa: ...`` comments that immediately follow docstrings back up to the end of the correct line.
:param source: The source to reformat.
:return: The reformatted source.
"""
return re.sub(r'"""[\n\s]+#\s+noqa', '""" # noqa', source) | f907ae78cb0d9c454821f7cf354cb0a18f5c3314 | 591,358 |
import math
def _ln_binomial(n, k):
"""log of binomial coefficient function (n k), i.e., n choose k"""
if k > n:
raise ValueError
if k == n or k == 0:
return 0
if k * 2 > n:
k = n - k
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1) | e4573a3223f2bcadb290b3378b70be1ef8af683b | 591,359 |
def get_motif(sequences):
"""
Computes the motif for a given collection of sequences.
A motif is a representative sequence for all sequences in a collection, with blank values (0) being those which are variable within the collection, and fixed values which are not.
Motifs are related to the measure of synchrony in ... | d308e8bddb48c28fbf5612b6d856b020196b4c80 | 591,361 |
def read_file(path):
"""Read file at path, return list of stripped strings.
:param path: path to file
:return: list with stripped strings
"""
with open(path) as stream:
return [x.strip() for x in stream.readlines()] | f20fb7d9615ff9c5fe135edf24047837bd8a5a12 | 591,362 |
import math
def i4_bit_lo0(n):
"""
I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer.
Example:
+------+------------+----
| N | Binary | BIT
+------+------------+----
| 0 | 0 | 1
| 1 | 1 | 2
| 2 | 10 | ... | f8766d351183ecb9fe74b836a4bbf226e8db1501 | 591,364 |
def update_mean(value, mean, count):
"""
Update value of a streaming mean.
:param value: New value.
:param mean: Mean value.
:param count: Number of values averaged.
:return:
"""
return (value - mean) / (count + 1) | bf0b5d767731fbea444ae14bc82ff849d70cffb6 | 591,367 |
import torch
def onehot(image, width: int, height: int, col: dict):
"""
This function takes the target pictures and onehot encode them. The amount
of classes are defined by the amount of different classes in the col
dictionary.
Args:
image (tensor): target image meant to be onehot encoded... | d6a40952603c4e547d91bdd1fcce0781e18aaedf | 591,368 |
import torch
def _ref_embedding_separation_term(reference_embeds, sigma=1):
"""
This function implements the second sub-expression from the grouping loss
in the associative embedding paper. This sub-expression incentivizes
separation between reference embedding values
"""
instance_count = re... | d5377d1e6eba591beec005df4cbe87e0176ae18c | 591,370 |
import re
def pre_process(column):
"""
Do a little bit of data cleaning. Things like casing, extra spaces,
quotes and new lines are ignored.
"""
column = re.sub(' +', ' ', column)
column = re.sub('\n', ' ', column)
column = column.strip().strip('"').strip("'").lower().strip()
if col... | 103e8bd3c5f022f2da0f2605e5c1f73b8188fa95 | 591,371 |
def get_posixtime(uuid1):
"""Convert the uuid1 timestamp to a standard posix timestamp
"""
assert uuid1.version == 1, ValueError('only applies to type 1')
t = uuid1.time
t = t - 0x01b21dd213814000
t = t / 1e7
return t | a20899a995ffd549362f4495d9da030efbb4a470 | 591,372 |
import time
def neg(value):
"""Return a negative copy of the value """
time.sleep(2.0)
return -value | 717635b890262657b9c95dfa298d0824bc0ba6ea | 591,375 |
import pathlib
from typing import List
def _get_all_directories(root: pathlib.Path) -> List[pathlib.Path]:
"""Walk the directory tree and return all the folders."""
all_files_and_folders = root.glob("**/*")
return [path for path in all_files_and_folders if path.is_dir()] | 911dc7b14629e6b929f8aa9b96b9ba72406f36ee | 591,377 |
def _almost_equal(test_value, reference_value, tolerance=1.0e-9):
"""
Numerical equality with a tolerance
"""
return abs(test_value - reference_value) < tolerance | 066d50167f3faad17ddc78bdb5d6aaa01f8972ba | 591,378 |
def get_weight_kids(tree, node, weights):
"""
Computes the weight (i.e the number of direct and indirect dependents) for each node.
Recursive function called inside optimal_linearization.
Parameters
----------
tree : Tree
a dependency Tree in dict format
node : dict
the dict corresponding to the current r... | 22e636fe3685c9462fe8d31768b0bb23c8c3052e | 591,384 |
def weight_function(self, t):
"""
Weight function proposed in the original paper to subsample
"""
if t < self.a:
return 0
elif t >= self.a and t < self.b:
return (t - self.a)/(self.b - self.a)
else:
return 1 | d3281bad1b538c94549035df33e9f827f543f184 | 591,387 |
def HSW_offset(r, rs, alpha, Rv, beta, deltac, offset):
"""
HSW (Hamaus-Sutter-Wendelt) function for the universal void density profile
See: Hamaus et al. (2014)
"""
numerator = 1-(r/rs)**alpha
denominator = 1+(r/Rv)**beta
return deltac*numerator/denominator +offset | b4f69df4ced303d34f92d390763fc545f83e0437 | 591,391 |
def prepend_with_fs(fs, path):
"""Prepend 'path' with 'fs' if it's not already the prefix."""
return path if path.startswith(fs) else "%s%s" % (fs, path) | 4c62591b8b72331ea25d5cf85c263c9254a40bef | 591,393 |
def safe_numeric(string, default=0):
"""Converts string to int or float or returns default.
Args:
string: string to be converted to numeric
default: number to return in case of failure
Returns:
integer value, if possible, otherwise float or default
"""
try:
n = flo... | c4b13950d6f860bf1909e7d2be12339243ac90c4 | 591,395 |
import importlib
def get_world_module(world_path):
"""
Import the module specified by the world_path.
"""
run_module = None
try:
run_module = importlib.import_module(world_path)
except Exception as e:
print("Could not import world file {}".format(world_path))
raise e
... | ef179c59b17b782be3db882ce7da70d2a9ce74be | 591,397 |
def pull_partition_status(partition):
"""
Retrieve the partition operational status as fast as possible and return
it.
"""
parts = partition.manager.cpc.partitions.list(
filter_args={'name': partition.name})
if len(parts) != 1:
raise AssertionError()
this_part = parts[0]
... | 074d2c436c5e7b6cb2d7579305a4ffc678b53d77 | 591,398 |
def _float(v):
"""Try to convert to a float
:param v: value
:rtype: float
"""
try:
return float(v)
except Exception:
return 0.0 | 7eec8ff108352429cf6e94b06b548768be592107 | 591,401 |
def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float:
"""
Convert a given value from Celsius to Rankine and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
>>> celsius_to_rankine(2... | 0d2d95ae1d709b32a44213044915f7bd7b47334d | 591,405 |
def GetTweetContent(Tweet, Location = False) :
"""
A Function that takes a Tweet rerurned from a listener and
makes a dictionary for this tweet, with the usefull info we need
and not all tweet's info.
"""
# The dictionary which represents the tweet.
Fields = {}
# { "Screen_nam... | 89d210108abd20797444d5c1c10e943115236258 | 591,406 |
def determine_archive_version_generic(name, leading_terms, trailing_terms):
"""
Given an archive file name, tries to get version information. Generic version that can cut off leading and trailing
terms and converts to lower case. Give the most special terms first in the list. As many cut offs as possible ar... | bb76a96a20938059cb6be22dc047c54dad5a9e58 | 591,407 |
def crop(image, contour):
"""Crops the image by the provided contour."""
tl_x, tl_y = contour.tl_point
br_x, br_y = contour.br_point
return image[int(tl_y) : int(br_y), int(tl_x) : int(br_x)] | 0cc78397aaefdef6fe4c0fa283ab919cdb4f4026 | 591,410 |
def checked_in_freshers(freshers):
"""Get checked in Freshers from a list."""
return [fresher for fresher in freshers if fresher.is_checked_in] | c737f1893170f34d852e0d71e0ac7caf08baa2be | 591,413 |
def get_maturity_rst(maturity):
"""rst markup for the maturity tags"""
if maturity:
return '|' + maturity.upper() + '|'
else:
return '' | ac25d6ac60b3aa84217873fa8059c9b7f332c16e | 591,415 |
from pathlib import Path
def get_logfile() -> str:
"""
查找原神客户端日志文件。
:return: 日志文件地址。找不到则返回空字符串。
"""
base = Path('~/AppData/LocalLow/miHoYo')
for folder in ('原神', 'Genshin Impact', 'YuanShen'):
logfile = base / folder / 'output_log.txt'
if logfile.is_file():
return ... | 747412b2634ca10e8341c49a5157deda9e18684f | 591,416 |
def add_underscore(s):
"""
Makes sure S begins with an underscore.
"""
return s if s.startswith('_') else u'_%s' % s | 2f45942098fef5caab10a3ea5325324b32f493e2 | 591,417 |
def strip(text):
""":strip: Any text. Strips all leading and trailing whitespace."""
return text.strip() | 975b2e2b0345298478ec2d7f60af871ebeaed3d9 | 591,418 |
def fill_embarked(df):
"""Fill missing embarked"""
df['Embarked'] = df['Embarked'].fillna('S')
return df | 28be66c3657adfa0b01c7e6227e81205d60a627b | 591,420 |
def compute_ga_days_for_charttime(charttime, intime, ga_days_birth):
"""Compute the gestational age in days at a specific charttime
Args:
charttime (datetime.datetime): The charttime
intime (datetime.datetime): The admission time of the ICU stay
ga_days_birth: The gestational age in day... | 4896d9abf62143295fdb5efc5a34bc45b34e0063 | 591,426 |
import re
def _parse_query_postgres(search_term):
"""Takes a plain unicode string from the user and converts it into a form
that can be passed to database.
We use this so that we can add prefix matching, which isn't something
that is supported by default.
"""
# Pull out the individual words, ... | 7b326bc68fc1312ce7b287ada69cd1ff9fc12099 | 591,429 |
def error_from_response(message, http_response, error_class,
response_body=None):
"""Creates a new exception and sets the HTTP information in the error.
Args:
message: str human readable message to be displayed if the exception is
not caught.
http_response: The response f... | 91ff52330245d64389e2b3fa157c08376ef92e9d | 591,430 |
def rule(request):
"""Parametrized fixture of each convention rule."""
return request.param | b8d8106ebc053d8135d27ff52bd0dcb9f565e362 | 591,431 |
def create_points_for_rectangle(x, y, width, height):
"""Simple helper function to create points for a rectangle
Arguments:
x {int} -- [description]
y {int} -- [description]
width {int} -- [description]
height {int} -- [description]
Returns:
[int] -- [descri... | 633112d0a68c8edff4efc5ef404033c8fdbac773 | 591,437 |
def bxor(x, y):
"""Bitwise XOR"""
return x ^ y | af359e6a81090b6cf73b6befeccc0a661f9128d9 | 591,439 |
def get_2pttype_for_dictkey(dictkey):
"""
Convert key in blinding factor dictionary to sets of strings used
in the fits file to designate which kind of 2pt function is being analyzed.
"""
if dictkey == 'gal_gal_cl':
return 'GPF','GPF'
elif dictkey == 'gal_shear_cl':
return 'GPF',... | 5d61c11fa576e058173c03a602c0c5527770b399 | 591,443 |
import ast
def builtin_folding(value):
""" Convert builtin function to ast expression. """
if value.__name__ in ("bool", "float", "int", "long"):
name = value.__name__ + "_"
else:
name = value.__name__
return ast.Attribute(ast.Name('__builtin__', ast.Load()),
n... | 650276289ba436885ddf8b82ffa10a274fac20f7 | 591,445 |
import socket
def lookup_host_addr(hostname):
"""Looks up a single host IP address.
Returns None if it cannot find one."""
try:
return socket.gethostbyname(hostname)
except socket.gaierror:
return None | 008190f538aaa852dddd21fa49091cb6b2b13032 | 591,447 |
def _apply_wrappers(wrappers, multi_env):
"""Helper method to apply wrappers if they are present. Returns wrapped multi_env"""
if wrappers is None:
wrappers = []
for wrap in wrappers:
multi_env = wrap(multi_env)
return multi_env | 81a914690d7a4840b202cf14e98c9ca04a5b8001 | 591,448 |
def is_palindrome(word: str) -> str:
"""Check if a word is a palindrome or not
Args:
word (str): String to be evaluated
Returns:
str: Return a string which specify id the word a palindrome or not
"""
word = word.strip().replace(" ", "").lower()
result = "It's not a Palindrome"... | d7e1f5734c0150d8d6e38b43968826ea988b8645 | 591,449 |
def SumVal(inputList):
"""
Return the sum of the supplied list
"""
return sum(inputList) | 4ad063e72a21f702c8d4f32f0ff6f28fc147f7ee | 591,455 |
import math
def degrees_to_sin(x):
"""Takes the sine of an angle given in degrees."""
return math.sin(math.radians(x)) | b9846b58ce66fe327a77bb5f12aae1d57431f476 | 591,457 |
from typing import Callable
import click
def max_num_results_option(
command: Callable[..., None],
) -> Callable[..., None]:
"""
An option decorator for choosing the maximum number of query results.
"""
maximum = 50
click_option_function = click.option(
'--max-num-results',
typ... | 38a1b0ec220fd57e67903d36928afab6811022ca | 591,461 |
def kvadrat_vsote(n):
""" Vrne kvadrat vsote naravnih števil do n. """
vsota = 0
for i in range(n+1):
vsota += i
return vsota ** 2 | 298421fe7cdead1ddfeb41c08f6d5889820b2120 | 591,463 |
from typing import Tuple
from typing import List
def parse_inventory_groups(args_groups: str) -> Tuple[List[str], List[str]]:
"""Parse list of inventory groups passed via CLI
Groups with indices like: 3, [3:], [:3] should be parsed into slices
that later can be utilizes as list indices on inventory parsin... | 00b8095112afad1913b8e2e8b1ed42ad8e9a8f9c | 591,465 |
def convert_timeseries_to_subdocuments(timeseries):
"""
Converts a timeseries to a list of dicts. Every dict represents one timestep
and contains the keys 'timestamp' and 'value' as well as the according values.
Parameters
----------
timeseries : pandas.Series
A timeseries with the time... | 63ab64c0acb81153a8302a17f010045640f69f2c | 591,467 |
import string
def is_printable(s):
"""
Return True if 's' is printable string
"""
try:
return all(c in string.printable.encode() for c in s)
except TypeError:
return False | 34d7de4a453b89028e6a61e678fb7684368c4095 | 591,477 |
import textwrap
def indent(text: str, indent: int = 2) -> str:
"""Add indentation to text"""
return textwrap.indent(text, ' ' * indent) | 9471ac380b43543a786c21fbe05a620d43c14169 | 591,478 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.