content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def isPostCSP(t, switch=961986575.):
"""
Given a GALEX time stamp, return TRUE if it corresponds to a "post-CSP"
eclipse. The actual CSP was on eclipse 37423, but the clock change
(which matters more for calibration purposes) occured on 38268
(t~=961986575.)
:param t: The time stamp... | 2b731ec0bb06ce08d2a36137e3d48563e5cb0c11 | 7,803 |
import uuid
def get_a_uuid() -> str:
"""Gets a base 64 uuid
Returns:
The id that was generated
"""
r_uuid = str(uuid.uuid4())
return r_uuid | 20e87638c3718b4b75ffc48cf980216120edaea8 | 7,806 |
from pathlib import Path
def cookiecutter_cache_path(template):
"""
Determine the cookiecutter template cache directory given a template URL.
This will return a valid path, regardless of whether `template`
:param template: The template to use. This can be a filesystem path or
a URL.
:ret... | cbdc72195bf47fb1bb91368ac2bbca3890775a60 | 7,807 |
def generate_comic_html(comic={}):
"""Generates part HTML for the qotd supplied"""
return """
<h3>Dilbert by Scott Adams -</h3>
<a href="{0}"><img alt="{1} - Dilbert by Scott Adams" src="{2}"></a>
""".format(comic['url'], comic['title'], comic['image']) | 6003abddbe7b8f3ca281787b09d92b42907669fb | 7,808 |
def get_cloudify_endpoint(_ctx):
"""
ctx.endpoint collapses the functionality for local and manager
rest clients.
:param _ctx: the NodeInstanceContext
:return: endpoint object
"""
if hasattr(_ctx._endpoint, 'storage'):
return _ctx._endpoint.storage
return _ctx._endpoint | 37ac79f564626399bd940d4c9d9fd9fb8417c424 | 7,809 |
def get_vendors(ven):
"""
Input arguments for function = tuple
Coverts tuple into a list. I know, it is silly.
Input example:
get_vendors(("Neste", "Circle K"))
Output example:
['Neste', 'Circle K']
"""
vendors_list = list(ven)
return vendors_list | 7703a1efc2f6cb329f8c15dc4df19a966d3c4197 | 7,810 |
from typing import Any
from datetime import datetime
def stringify_mongovalues(v: Any):
"""
Mostly the values are fine, but at least datetime needs handled.
Also need to handle datetimes embedded in dicts, so use recursion to get them.
"""
if type(v) == datetime:
return v.isoformat()
e... | 27349086a58681f0d06ce795b3792cc4e25e97fc | 7,812 |
def get_log_info(prefix='', rconn=None):
"""Return info log as a list of log strings, newest first. On failure, returns empty list"""
if rconn is None:
return []
# get data from redis
try:
logset = rconn.lrange(prefix+"log_info", 0, -1)
except:
return []
if logset:
... | d333fbeaff754e352a0b84c10f4d28e148badfa0 | 7,816 |
def text_to_html(string):
"""Take text as input and return html that renders nicely.
For example replace newlines with '<br/>'
This was built for use in reminder emails, please check for
effects there if you are updating it."""
string = "<html><body>" + string + "</body></html>"
string = string... | 86cbbc0d35bc994450bb16e989264f96c992aaa3 | 7,818 |
def spacecraft_vel(deltaw, deltan, deltar, dij, vmap):
"""
function to calculate pixel-wise spacecraft velocities for Sunpy map
Based on Haywood et al. (2016) and described in Ervin et al. (2021) - In Prep.
Parameters
----------
deltaw: float, array
relative westward position of pixel
... | 78c2acffc4f14c3f707cc50e1594ad7012bc1b08 | 7,819 |
import time
def convert_time(t):
"""Takes epoch time and translates it to a human readable version"""
return time.strftime('%Y-%m-%d', time.localtime(t)) | e591e32e30a8ceb81c9934f4e67556896a56b79a | 7,822 |
from typing import List
from functools import reduce
def singleNumber(nums: List[int]) -> int:
"""
思路:排序,哈希,位运算(异或) 0^1 = 1, 1^1 = 0
"""
# n = 0
# for val in nums:
# n ^= val
# return n
return reduce(lambda x, y: x ^ y, nums) | 444b2e2685d42bcc717d95058a6c86dc4da31609 | 7,823 |
def valid_box(box, host_extent):
"""Returns True if the entire box is within a grid of size host_extent.
input arguments (unmodified):
box: numpy int array of shape (2, 3)
lower & upper indices in 3 dimensions defining a logical cuboid subset of a 3D cartesian grid
in python protocol... | c6b1bc144e23b35002a1fbf17d4e02d9ba904655 | 7,824 |
import yaml
def yaml_dump_result(obj, stream):
"""Redefinition of yaml.safe_dump with added float representer
The float representer uses float precision of four decimal digits
"""
def float_representer(dumper, value):
text = '{0:.4f}'.format(value)
return dumper.represent_scalar(u'tag... | 55a8a06e918276060505224a680e1cb136d4a541 | 7,825 |
def rho_NFW(r, rs, rhos):
"""
The density profile [GeV/cm**3] of an NFW halo.
Parameters
----------
r : the distance from the center [kpc]
rs : the NFW r_s parameter [kpc]
rhos : the NFW rho_s parameter [GeV/cm**3]
"""
res = rhos/(r/rs)/(1.+r/rs)**2
return res | 3b8f97713610c1622815e15f13a75d39ad7e64ba | 7,827 |
def breakup_names(df):
"""Breakup full name into surname, title, first name"""
df[['surname','given_name']] = df['Name'].str.split(",", expand= True)
df[['title', 'first_name']] = df['given_name'].str.split(n=1, expand= True)
df = df.drop(columns=['Name', 'given_name'])
return df | ee76975b88702daf47fa9638c4d1217ca22e1e6e | 7,830 |
import os
def cat(dir, file_name=None, input=None):
""" act like unix 'cat' - put string into file (or echo data out """
ret_val = None
# step 1: figure out the file path
if dir:
if file_name:
file_path = os.path.join(dir, file_name)
else:
file_path = dir
... | 5ef0ae24d1ea3bd23c98d43ab2ddca80233a75b9 | 7,831 |
from pathlib import Path
def image_content_type(outfile: Path) -> str:
""" Derives a content type from an image file's suffix """
return f"image/{outfile.suffix[1:]}" | 4c1545dbdcaa31826fd8567cabe2935ed7237961 | 7,832 |
def play_again() -> str:
"""Ask the user if he wants to play another turn"""
yes_or_no = input('Play again? [y/n]: ')
while yes_or_no not in ['y', 'n']:
yes_or_no = input('Please insert "y" or "n": ')
return yes_or_no | 8b3d74456b7ce13a0ffffab8dc9e946cbb5e594c | 7,833 |
def UserTypingFilter(cli):
"""Determine if the input field is empty."""
return (cli.current_buffer.document.text and
cli.current_buffer.document.text != cli.config.context) | 420b24cdeb17cb97294a937e49096c5462d4061e | 7,834 |
def scale_image(image, new_width=600):
"""
scales the image to new_width while maintaining aspect ratio
"""
new_w = new_width
(old_w, old_h) = image.size
aspect_ratio = float(old_h)/float(old_w)
new_h = int(aspect_ratio * new_w)
new_dim = (new_w, new_h)
image = image.resize(new_dim)
... | e9bfdf6309cf97b1a7f44dff96b655aa09d64fd5 | 7,835 |
def get_container_metadata(item):
"""Extract desired metadata from Docker container object."""
if type(item) is str:
return item
tags = getattr(item, 'tags', None)
if tags is not None:
return tags[0]
else:
return str(item) | bf805e33f17dc664a62989f36ae164ee3c348b3e | 7,836 |
def percentage(sub, all):
"""Calculate percent relation between "sub" and "all".
Args:
sub (int): Some value.
all (int): Maximum value.
Returns:
int: (sum * 100) / all
"""
return int((sub * 100) / all) | 21b398c81f76de0ec81be9d26b2f79d8b0d08edc | 7,837 |
def value(colors: list):
"""
Each resistor has a resistance value.
Manufacturers print color-coded bands onto
the resistors to denote their resistance values.
Each band acts as a digit of a number.
The program will take two colors as input,
and output the correct number.
:param colors:
... | 14a52f12bfcfccd921ade8fa7708d3563c9c2508 | 7,838 |
import torch
def nan_mode(input):
"""Mode value for tensor (ignoring NaNs)."""
return torch.mode(input[~torch.isnan(input)])[0] | cf2ef4fb23a0dfbc251dd385a38ed8e01142ac08 | 7,840 |
def activation(func_a):
"""Activation function wrapper
"""
return eval(func_a) | ad7f668aec546de452ef4968b22c338c2ca873b6 | 7,841 |
def quote_columns_data(data: str) -> str:
"""When projecting Queries using dot notation (f.e. inventory [ facts.osfamily ])
we need to quote the dot in such column name for the DataTables library or it will
interpret the dot a way to get into a nested results object.
See https://datatables.net/referenc... | db5e82e5d3641bebcac069ac4d5a7bb42baafcbb | 7,843 |
def sort_kv_pairs_by_value(d):
"""Turn a dict into a list of key-value pairs, sorted by value."""
return [
(k, v) for v, k in sorted([(v, k) for k, v in d.items()], reverse=True)
] | 58f3e40c4993a64f71212157fdd73ad82712fa44 | 7,844 |
import os
def newcd(path):
"""DEPRICATE"""
cwd = os.getcwd()
os.chdir(path)
return cwd | 5def36e28a4125fafcfdab697be842841ed767b1 | 7,845 |
import string
def is_string_formatted(s, return_parsed_list=False):
""" check if a string has formatted characters (with curly braces) """
l = list(string.Formatter().parse(s))
if len(l) == 1 and l[0][0] == s:
is_formatted = False
else:
is_formatted = True
if return_parsed_list:
... | a47a698d1c53bbf4bfb88ec7aca9e1ed3b0958d5 | 7,846 |
from datetime import datetime
def _get_creation_date():
"""作成時刻を返す"""
return datetime.utcnow().strftime('%Y-%m-%d-T%H:%M:%SZ') | a6725716361b0b37c35c62fe1f9600224d8d04f2 | 7,848 |
def check_length(min_length: int,
max_length: int,
mode: str = 'and',
*args) -> bool:
"""
check items length is between min_length and max_length
:param min_length: minimum length
:param max_length: maximum length
:param mode: check mode, 'and': all... | f959619a466f62bf6ecfaf10e0fbb316652891e7 | 7,850 |
def check_processed_data(df,col_list,na_action):
""" Checks if provided dataframe consists of required columns and no missing values
"""
check_passed = True
# Check columns
df_cols = df.columns
if set(df_cols) != set(col_list):
check_passed = False
print('Column names mismatched... | fd26d00eabd9eb1dfd1f8bce01a3fb86582a740f | 7,851 |
import subprocess
def execute_command(command):
"""Executes a command, capturing the output"""
output = subprocess.run(command, capture_output=True, encoding='utf-8')
if len(output.stderr) > 0:
print(output.stderr)
output.check_returncode()
return output | 7b768251d0ad52091e79b55aadeebc2481e07b26 | 7,852 |
def feed_conversation(samples, limit=5, threshold=.85):
"""helper function to feed result of classifier to Conversation module."""
try:
iter(samples)
assert not any(not isinstance(sub, tuple) for sub in samples)
except (AssertionError, TypeError) as e:
raise TypeError('samples must b... | 4c3d9b7c63e71790bb1a8445662754d48e31524f | 7,853 |
def point_inside_volume(p, ab1, ab2, eps = 0.01):
"""
Check if point p is inside the aabb volume
"""
ab1 = ab1.copy() - eps
ab2 = ab2.copy() + eps
if ab1[0] <= p[0] <= ab2[0] and \
ab1[1] <= p[1] <= ab2[1] and \
ab1[2] <= p[2] <= ab2[2]:
return True
else:
retu... | 9cdb6323343fdc23dae4b2c899927450c92cb7a2 | 7,854 |
def _determine_levels(index):
"""Determine the correct levels argument to groupby."""
if isinstance(index, (tuple, list)) and len(index) > 1:
return list(range(len(index)))
else:
return 0 | 2eaed820eb45ff17eb4911fe48670d2e3412fb41 | 7,855 |
def format_val(v):
"""Takes in float and formats as str with 1 decimal place
:v: float
:returns: str
"""
return '{:.1f}%'.format(v) | 932ca312a573a7e69aa12e032d7b062ac22f3709 | 7,858 |
import re
def you_to_yall(text: str) -> str:
"""Convert all you's to y'all."""
pattern = r'\b(y)(ou)\b'
return re.sub(pattern, r"\1'all", text, flags=re.IGNORECASE) | 1a3ee7ebf2394f84ad296e18da789dff8ca50a12 | 7,860 |
def to_aws_tags(tags):
"""
When you assign tags to an AWS resource, you have to use the form
[{"key": "KEY1", "value": "VALUE1"},
{"key": "KEY2", "value": "VALUE2"},
...]
This function converts a Python-style dict() into these tags.
"""
return [
{"key": key, "valu... | d1e18ea1e4de08fcae59febbe97ab3eb5bc2a2f1 | 7,863 |
def check_for_winner(players) -> bool:
"""Checks all players for a single winner. Returns True if there is a winner.
Keyword arguments:
players -- list of player objects
"""
return sum(map(lambda x: not x.is_bankrupt(), players)) == 1 | 17d39e92a38a9474f080ddebfac1d4813f464a1e | 7,864 |
def get_game_player(game_state):
"""Get the game player whose turn it is to play."""
num_players = len(game_state.game_players)
for game_player in game_state.game_players:
if game_state.turn_number % num_players == game_player.turn_order:
return game_player
return None | a75a0b1b7f1ce4da8c944ad40208fba6f9a50f5a | 7,865 |
import re
def get_headers_pairs_list(filename, verbose=False):
"""
Read data for clustering from a given file.
Data format: <email_number> <header>.
Clusters are separated with a blank line.
:param filename: file with input data for clustering.
:param verbose: Whether to be verbose. Default ... | d6b457652e1025475075fb601ba81b6a7fe346fc | 7,867 |
from pathlib import Path
def _run_jlab_string(talktorials_dst_dir):
"""
Print command for starting JupyterLab from workspace folder.
Parameters
----------
talktorials_dst_dir : str or pathlib.Path
Path to directory containing the talktorial folders.
"""
talktorials_dst_dir = Path... | 76c45f77f419b6a302d63d92e51cd0ea1bb92ebb | 7,869 |
def get_full_names(pdb_dict):
"""Creates a mapping of het names to full English names.
:param pdb_dict: the .pdb dict to read.
:rtype: ``dict``"""
full_names = {}
for line in pdb_dict.get("HETNAM", []):
try:
full_names[line[11:14].strip()] += line[15:].strip()
except: f... | be31bb2c8e59e7b2ef4b51aba45f3cbafcb23a63 | 7,871 |
def refsoot_imag(wavelengths, enhancement_param=1):
"""imaginary part ot the refractive index for soot
:param wavelengths: wavelength(s) in meter.
:param enhancement_param: This parameter enhances the mass absoprtion efficiency of BC.
It makes it possible to scale BC absorption. Values of this param... | bbd7a9ad7f14088739c8eeaef926dbc63f5a2385 | 7,873 |
import os
def _file_path_check(filepath=None, format="png", interactive=False, is_plotly=False):
"""Helper function to check the filepath being passed.
Args:
filepath (str or Path, optional): Location to save file.
format (str): Extension for figure to be saved as. Defaults to 'png'.
... | 27d47df198331ee3dd3f6d4d0d1490520f09fd4b | 7,874 |
def get_table_type(filename):
""" Accepted filenames:
device-<device_id>.csv,
user.csv,
session-<time_iso>.csv,
trials-<time_iso>-Block_<n>.csv
:param filename: name of uploaded file.
:type filename: str
:return: Name of table type.
:rtype: str|None
"""
basename, ext = f... | bc4f39e4c9138168cec44c492b5d1965de711a7e | 7,876 |
def length_of_longest_substring(s: str) -> int:
"""
The most obvious way to do this would be to go through all possible substrings of the string which would result in
an algorithm with an overall O(n^2) complexity.
But we can solve this problem using a more subtle method that does it with one linear tr... | 3844c6fd1c62025b704284e76da25f7c63aa0fc9 | 7,877 |
def make_download_filename(genome, args, response_format):
"""
Make filename that will explain to the user what the predictions are for
:param genome: str: which version of the genome we are pulling data from
:param args: SearchArgs: argument used for search
:param response_format: str file extensio... | 4645e3175de0db81e940d0e64740e937bce7afc3 | 7,878 |
def window_to_bounds(window, affine):
"""Convert pixels to coordinates in a window"""
minx = ((window[1][0], window[1][1]) * affine)[0]
maxx = ((window[1][1], window[0][0]) * affine)[0]
miny = ((window[1][1], window[0][1]) * affine)[1]
maxy = ((window[1][1], window[0][0]) * affine)[1]
return min... | 6377d792271a86175349daa277b8eb937dd740f5 | 7,879 |
import os
import uuid
def docker_compose_package_project_name():
"""Generate a project name using the current process PID and a random uid.
Override this fixture in your tests if you need a particular project name.
This is a package scoped fixture. The project name will contain the scope"""
return "p... | 7e7960a5e34e93618338765b95f5a4c8eb874a3f | 7,882 |
import numpy
import random
def time_mask(spec, T=40, n_mask=2, replace_with_zero=True, inplace=False):
"""freq mask for spec agument
:param numpy.ndarray spec: (time, freq)
:param int n_mask: the number of masks
:param bool inplace: overwrite
:param bool replace_with_zero: pad zero on mask if tru... | f69364510c78f2fc3e96fb4f028737c6c415d5df | 7,883 |
def change(csq):
"""
>>> change("missense|TMEM240|ENST00000378733|protein_coding|-|170P>170L|1470752G>A")
('170P', '170L', True)
>>> change('synonymous|AGRN|ENST00000379370|protein_coding|+|268A|976629C>T')
('268A', '268A', False)
"""
parts = csq.split("|")
if len(parts) < 7:
ret... | da43c6bd45e641b885469d07c2e6befff334d8a3 | 7,884 |
def with_coordinates(pw_in_path, positions_type, atom_symbols, atom_positions):
"""Return a string giving a new input file, which is the same as the one at
`pw_in_path` except that the ATOMIC_POSITIONS block is replaced by the one
specified by the other parameters of this function.
`positions_type`, `a... | 11dc207a4f17a6521a1aa6299d455f0548c50566 | 7,885 |
def calculate_factor_initial_size(n, key):
"""
Calculate different initial embedding sizes by a chosen factor.
:param n: Number of nodes in the graph
:param key: The factor- for example if key==10, the sizes will be n/10, n/100, n/100, .... the minimum is 100 nodes
in the initial embedding
:retu... | 35fdef82e55647b20f9d86ec926e77c1d5244e2e | 7,887 |
def is_iterable(value):
""" Verifies the value is an is_iterable
:param value: value to identify if iterable or not.
"""
try:
iterable_obj = iter(value)
return True
except TypeError as te:
return False | 13728b7c28506086a3eb9b8faefcdc6276eba00e | 7,888 |
def rw_normalize(A):
"""
Random walk normalization: computes D^⁼1 * A.
Parameters
----------
A: torch.Tensor
The matrix to normalize.
Returns
-------
A_norm: torch.FloatTensor
The normalized adjacency matrix.
"""
degs = A.sum(dim=1)
degs[degs == 0] = 1
r... | 2a9f90d1f2bf02545e9719b0f373e6eb215fa0cd | 7,889 |
import logging
def _get_areas(params, feature_names):
"""Returns mapping between areas and constituent feature types."""
areas = {}
for feature_id in range(len(params)):
feature_info = params[feature_id]
feature = feature_info["ID"]
area = feature_info["Area"]
if area not in areas:
areas[a... | 937797d7634ac6cd73af941c783f26d5a8028b4d | 7,891 |
import numpy
def calc_m_sq_cos_sq_para(tensor_sigma, flag_tensor_sigma: bool = False):
"""Calculate the term P2 for paramagnetic sublattice.
For details see documentation "Integrated intensity from powder diffraction".
"""
sigma_13 = tensor_sigma[2]
sigma_23 = tensor_sigma[5]
p_2 = numpy.... | 910087c34ffc5ec43376fbdbc6368761fb4580ee | 7,892 |
def transform_seed_objects(objects):
"""Map seed objects to state format."""
return {obj['instance_id']: {
'initial_player_number': obj['player_number'],
'initial_object_id': obj['object_id'],
'initial_class_id': obj['class_id'],
'created': 0,
'created_x': obj['x'],
... | 685c0c5b22fdff108311338354bb42fb53fd07f6 | 7,894 |
def remove_digits(text):
"""
Remove all digits from the text document
take string input and return a clean text without numbers.
Use regex to discard the numbers.
"""
result = ''.join(i for i in text if not i.isdigit()).lower()
return ' '.join(result.split()) | d9604c31391e48ab826089d39201577bdf83c2fa | 7,896 |
def _ipaddr(*args, **kwargs):
"""Fake ipaddr filter"""
return "ipaddr" | 8550ebc305442620e57d9b164d6751c1a16b4ef6 | 7,897 |
def QueryEncode(q: dict):
"""
:param q:
:return:
"""
return "?" + "&".join(["=".join(entry) for entry in q.items()]) | b92aaf02b3322b3c35b8fe8d528e2e4bc6f91813 | 7,899 |
import re
def _fast_suggest(term):
"""Return [] of suggestions derived from term.
This list is generated by removing punctuation and some stopwords.
"""
suggest = [term]
def valid(subterm):
"""Ensure subterm is valid."""
# poor man stopwords collection
stopwords = ['and',... | f4790e22abae7b33ee5585ea4a21189d7954cf40 | 7,900 |
def fixture_perform_migrations_at_unlock():
"""Perform data migrations as normal during user unlock"""
return False | a8a8ae9118b2de4f0cdbb7ba3e39fdd7a552f77b | 7,903 |
from pathlib import Path
def getFileAbsolutePath(rel_path):
"""
Retorna o caminho absoluto de um arquivo a partir de seu caminho relativo no projeto
:param rel_path:
:return: absolute_path
"""
data_folder = Path("PythoWebScraper/src")
file_to_open = data_folder / rel_path
return file_... | b39baaa26e3c8a7c7a8c41dbb4fafceb7ca78c70 | 7,904 |
import requests
def generate_text(query, genre):
"""
Функция отправляет POST-запрос к Балабобе,
и получает ответ в виде словаря.
Параметры POST-запроса:
query: ключевая фраза
genre: id жанра, в котором Балабоба должен сгенерировать текст
"""
text_url = 'https://zeapi.yandex.net/lab/api... | 467c40145db532f912ba2d17ad3ba588273fa682 | 7,905 |
def directive_exists(name, line):
"""
Checks if directive exists in the line, but it is not
commented out.
:param str name: name of directive
:param str line: line of file
"""
return line.lstrip().startswith(name) | eb69044de8860b1779ce58ef107859028b8c98cf | 7,906 |
import timeit
def search_set(n):
"""Search for an element in a set.
"""
my_set = set(range(n))
start = timeit.default_timer()
n in my_set # pylint: disable=pointless-statement
return timeit.default_timer() - start | f0d8ba45df45130cc81d70e2d391825ed46dc93e | 7,907 |
import os
def sweepnumber_fromfile(fname):
"""Returns the sweep number of a polar file based on its name"""
return int(os.path.basename(fname).split('.')[1]) | 4648bfcf10ea0645266109a5c0ab1a7e41ffe46d | 7,908 |
import os
import subprocess
def add(printer_name, uri, ppd, location, description):
"""
Add a new printer to the system with the given parameters.
"""
try:
if ppd[:4] == 'drv:':
type = '-m'
else:
type = '-P'
with open(os.devnull, "w") as fnull:
... | 8066f5ba76fc039efd5dc4a3f53fa84c28b825c7 | 7,910 |
def unitSpacing2MM(unit):
""" Converts KLE unit spacing into wxPoint spacing. Used in placing KiCAD components """
unitSpacing = 19.050000
wxConversionFactor = 1000000
return unit*unitSpacing | 2cc137b7db7a8b1871a7329fa482351fd52ed544 | 7,911 |
def entrypoint(label):
"""
If a class if going to be registered with setuptools as an entrypoint it
must have the label it will be registered under associated with it via this
decorator.
This decorator sets the ENTRY_POINT_ORIG_LABEL and ENTRY_POINT_LABEL class
proprieties to the same value, la... | 68cb3f2d2a982fefd34f412888ae50fcea6a743f | 7,913 |
def hide_empty(value, prefix=', '):
"""Return a string with optional prefix if value is non-empty"""
value = str(value)
return prefix + value if value else '' | d2943dbce763bd054dc26839b2d24232867b3312 | 7,915 |
import logging
import os
import csv
def check_table_and_warn_if_dmg_freq_is_low(folder):
"""Returns true if the damage frequencies are too low to allow
Bayesian estimation of DNA damages, i.e < 1% at first position.
"""
logger = logging.getLogger(__name__)
filename = "misincorporation.txt"
mis... | d776bf11d311ae1fac9f259e8f7a78f9caf8d1b8 | 7,916 |
def preauction_filters(participants, task, indivisible_tasks=False):
"""Apply some preauction filters to the participants list in order to remove any invalid candidates.
Args:
participants (list): A list of participating nodes and their info.
indivisible_tasks (bool): Only allow nodes that offe... | 7eadb0f8e95942ae0b3033cbca90ea44fba4d199 | 7,917 |
def isSymmetric(root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
leftPart=[root.left]
rightPart=[root.right]
while leftPart and rightPart:
leftNode=leftPart.pop()
rightNode=rightPart.pop()
if leftNode and rightNode:
if ... | 7026794a5e94df15439da1e776b485927fcf6078 | 7,918 |
import time
from datetime import datetime
def check_date(birth_date):
"""If false it has a validation message with it"""
if birth_date != None:
birth_date = birth_date.strip()
if birth_date == '':
return (False, "Please Enter Your Birth Date")
try:
time.strptim... | 06c7a10413d1509201ae672cca5985769d12871e | 7,919 |
import heapq
def min_window(k):
"""
Algorithm to find minimum window length between k lists. Uses
a heap.
"""
heap = []
p=[0 for i in range(len(k))]
min_r = 99999999
ma=0
for i in range(len(k)):
if k[i][0]>ma:
ma=k[i][0]
heapq.heappush(heap,(k[i... | 4ad706eac321a43924a32e2883c3ffae24a7f989 | 7,920 |
def as_dict_with_keys(obj, keys):
"""
Convert SQLAlchemy model to list of dictionary with provided keys.
"""
return [dict((a, b) for (a, b) in zip(keys, item)) for item in obj] | 1fcab95f9f94696c1af652b0b181e6e3e69f7f53 | 7,922 |
def get_required_fields():
""" Get required fields for the deployment from UI.
Fields required for update only:
eventId, rd, deploymentNumber, versionNumber,
[lastModifiedTimestamp, deployCruiseInfo, recoverCruiseInfo, ingestInfo]
At a minimum, deploymentNumber, versionNumber and (instr... | fe2439b7e5adcd7b9d98f828c3315253e0786bc8 | 7,923 |
def maximo_libreria(a: float, b: float) -> float:
"""Re-escribir utilizando el built-in max.
Referencia: https://docs.python.org/3/library/functions.html#max
"""
return max(a, b) | 41f4c37c2dcb0a64c11c1517f93c119722002e3d | 7,924 |
from typing import List
import os
import fnmatch
def glob(glob_pattern: str, directoryname: str) -> List[str]:
"""
Walks through a directory and its subdirectories looking for files matching
the glob_pattern and returns a list=[].
:param directoryname: Any accessible folder name on the filesystem.
... | 3155ce1037c39339439805024f1d6abac6b24460 | 7,926 |
def test_store_decorator(sirang_instance):
"""Test dstore"""
db = 'dstore'
collection = 'test'
def test_func(arg1, arg2, arg3, arg4):
return arg2
# Test inversions
no_invert = sirang_instance.dstore(
db, collection, keep=['arg1', 'arg2'], inversion=False,
doc_id_templat... | 868d26de1db3af3ea22e129c757400d8d013c9b1 | 7,927 |
def sdate_from_datetime(datetime_object, format='%y-%m-%d'):
"""
Converts a datetime object to SDATE string.
"""
return datetime_object.strftime(format) | 3f7ee70c47e1971e1c690f564fc8d4df519db5b6 | 7,929 |
def get_version(release):
""" Given x.y.z-something, return x.y
On ill-formed return verbatim.
"""
if '.' in release:
sl = release.split(".")
return '%s.%s' % (sl[0], sl[1])
else:
return release | 520438d5ca260caf27df31c4742d9da8c31f3218 | 7,931 |
def arrays_shape(*arrays):
"""Returns the shape of the first array that is not None.
Parameters
----------
arrays : ndarray
Arrays.
Returns
-------
tuple of int
Shape.
"""
for array in arrays:
if array is not None:
shape = array.shape
... | e9e6a4876b938934c843386dffc58f0eccfb20a3 | 7,932 |
import os
def check_is_board(riotdir, board):
"""Verify if board is a RIOT board.
:raises ValueError: on invalid board
:returns: board name
"""
if board == 'common':
raise ValueError("'%s' is not a board" % board)
board_dir = os.path.join(riotdir, 'boards', board)
if not os.path.i... | 94ecf0ca5762e66e667f7021af83038d982a0ff0 | 7,933 |
def max_profit(prices):
"""
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock),
design an algorithm to find the maximum profit.
Note that you cannot s... | 056dff9d2ad4af9d38f2ce0f1ad27c1c0df69121 | 7,934 |
def model_as_json(bot_entries):
""" Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB
@param
bot_entries (list) list of sub-lists
@returns
json_list (list) list of modeled dictionaries
"""
... | e18d4c29cdeda950bd0b32db5354f197e38f27ff | 7,935 |
def cone(toplexes, subcomplex, coneVertex="*"):
"""Construct the cone over a subcomplex. The cone vertex can be renamed if desired. The resulting complex is homotopy equivalent to the quotient by the subcomplex."""
return toplexes + [spx + [coneVertex] for spx in subcomplex] | 6b1328a2f7c32988666b0c7039efd0ce6ecdffef | 7,937 |
def replace(correct, guess, correct2):
"""
Find out if your guess is in the correct answer or not, if yes, put it into your answer
"""
ans = ''
i = 0
for ch in correct:
if guess == ch:
ans += correct[i]
else:
ans += correct2[i]
i += 1
# for i i... | aacd9142599cc815a5526350c96b4db09b74777d | 7,938 |
def broadcastable(shape_1, shape_2):
"""Returns whether the two shapes are broadcastable."""
return (not shape_1 or not shape_2 or
all(x == y or x == 1 or y == 1
for x, y in zip(shape_1[::-1], shape_2[::-1]))) | 9a968fdee4a401b5f9cee42286de7553afa02183 | 7,939 |
def bipartite_sets(bg):
"""Return two nodes sets of a bipartite graph.
Parameters:
-----------
bg: nx.Graph
Bipartite graph to operate on.
"""
top = set(n for n, d in bg.nodes(data=True) if d['bipartite']==0)
bottom = set(bg) - top
return (top, bottom) | 618756dbfa87dc0b5d878545fa5395c4a122c84c | 7,940 |
def htmlize(widget):
"""
Jinja filter to render a widget to a html string
"""
html = widget.render(widget)
try:
html = html.decode('utf-8')
except Exception:
pass
return html | a6c4aeac2bc27aeaaccbe78b893ca33181234169 | 7,943 |
def _merge_block(internal_transactions, transactions, whitelist):
"""
Merge responses with trace and chain transactions. Remove non-whitelisted fields
Parameters
----------
internal_transactions : list
List of trace transactions
transactions : list
List of chain transactions
... | b60c9cde133d97ac84b2899956a15a72c720bbaa | 7,945 |
def remove_virtual_slot_cmd(lpar_id, slot_num):
"""
Generate HMC command to remove virtual slot.
:param lpar_id: LPAR id
:param slot_num: virtual adapter slot number
:returns: A HMC command to remove the virtual slot.
"""
return ("chhwres -r virtualio --rsubtype eth -o r -s %(slot)s "
... | 2c6f14949910865f3a60c0016b4587088441572e | 7,948 |
import json
def dict_to_bytestring(dictionary):
"""Converts a python dict to json formatted bytestring"""
return json.dumps(dictionary).encode("utf8") | 31e201d87e92075d6078450ad019cc51f474f9d4 | 7,949 |
def _merge_candidate_name(src, dest):
"""Returns the formatted name of a merge candidate branch."""
return f"xxx-merge-candidate--{src}--{dest}" | a08b6d4b57385bc390e649448ce264cffd5a1ffa | 7,950 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.