content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def clean_texmath(txt):
"""
clean tex math string, preserving control sequences
(incluing \n, so also '\nu') inside $ $, while allowing
\n and \t to be meaningful in the text string
"""
s = "%s " % txt
out = []
i = 0
while i < len(s)-1:
if s[i] == '\\' and s[i+1] in ('n', 't'... | 95741f1f3cc84a7c7ae6479cc49ace350a6ba40d | 646,526 |
import math
def days_frac_to_dhms(days_frac):
"""Convert a day float to integer days, hours, minutes and seconds.
Returns a tuple (days, hours, minutes, seconds).
>>> days_frac_to_dhms(2.5305)
(2, 12, 43, 55)
"""
days = math.floor(days_frac)
hms_frac = days_frac - days
hours = ma... | 82a8b85dcadef3e279637fb514d6a926231df18f | 646,527 |
def yes_or_no(question):
""" a utility tool to ask the user yes/no question
Parameters
----------
question : str
the text for the question
Returns
-------
value : bool
True or False
"""
while True:
answer = input(question + ' (y/n): ').lower().strip()
... | 6bbc7da97e3af17ae1689a2bd88665b6e1ff1356 | 646,528 |
import os
def resource_path(path: str) -> str:
"""
return the absolute path for a file
"""
return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) | e908863ec7d53af0ae1a541ed7381cc4f71aabe0 | 646,529 |
def keyboard_data_signals_an_interrupt(
keyboard_data, stop_signal_chars=frozenset(['\x03', '\x04', '\x1b'])
):
"""The function returns a positive stop signal (1) if the character is in the
`stop_signal_chars` set.
By default, the `stop_signal_chars` contains:
* \x03: (ascii 3 - End of Text)
* \... | ac395bd2ccc690e6f1b40565db297087d3a1738b | 646,530 |
def vep_csq():
"""Returns the CSQ entry of a VEP-annotated variant - Has the same fields as vep_csq_header"""
# Note that this has both MANE_SELECT and MANE_PLUS_CLINCAL set for testing purposes, but that
# will never happen in real CSQ entries
csq_entry = """C|synonymous_variant|LOW|SCN5A|6331|Transcri... | b8102dd350c31c0c120d30cdd67a0b0ae3ed08a4 | 646,531 |
import os
def scan_project_names(projects_dir):
"""Scan and return project list from directory."""
projects = []
for root, dirs, files in os.walk(projects_dir):
for file in files:
if file == 'Dockerfile':
projects.append(os.path.basename(root))
return sorted(projects) | 2ca36edbe158e69a00a6f29da71563def79f72ff | 646,532 |
def clean_prior_names(df, **kwargs):
"""
:param df: a pandas data frame containing experimental results
:return: a pandas data frame containing the same results but with cleaner prior names
"""
df = df.replace('mle', 'MLE')
df = df.replace('standard', 'Standard')
df = df.replace('vamp', 'VAM... | 17645e1837cb910ae181971f5b72d18398b8487f | 646,533 |
def get_metric(mod, obs, fun, dim='time', verbose=False):
"""Calculate a metric along a dimension.
Metrics implemented: name
* correlation > corr
* mse > mse
* rmse > rmse
* mean percentage error > mpe
* stan... | f70caba77a464f8ed55da0daa2c4b4eb5a45a4e6 | 646,536 |
import json
import requests
def get_public_ip():
"""Fetch public IP of hosting server with the help of httpbin API"""
return json.loads(requests.get('http://httpbin.org/ip').text)['origin'] | 78c4a90a9853acab4c86b19c58128ee7e005ded5 | 646,537 |
def remove_spaces(st):
""" Removes spaces from a string
:param st: (str) input string with spaces
:return: (str) string without any spaces
"""
return st.replace(' ', '') | 3419571854077e2365c94d96394be0edfbe8912d | 646,539 |
def usage():
"""Returns usage string. May be different on what's installed in this Sakai
Instances"""
return '''
turnitin runtests
- runs tests
turnitin runtest testname
- run a single named test
turnitin showtests
- show all available tests
turnitin viewasnn siteid taskid
- view the info... | 86ea084a6681dc8e10ec1fd3d02db81467256863 | 646,540 |
import itertools
def Powerset(iterable):
"""powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)."""
s = list(iterable)
return itertools.chain.from_iterable(itertools.combinations(s, r)
for r in range(len(s)+1)) | a904a9cf7c4a62238f114dc877080e20bcf78d92 | 646,541 |
def update_leases(transform, persistence_service):
"""
Update the leases configuration in the persistence service.
:param transform: A function to execute on the currently configured
leases to manipulate their state.
:param persistence_service: The persistence service to which the
updat... | bd99ef43d452a520061305e0ac8bb6e21326b2a6 | 646,542 |
def fib(n: int) -> int:
"""Fibonacci numbers with naive recursion
>>> fib(20)
6765
>>> fib(1)
1
"""
if n == 0: return 0
if n == 1: return 1
return fib(n-1) + fib(n-2) | 656223d8bd39fc184ad191d45c25fb450e489648 | 646,543 |
import subprocess
def get_hostname() -> str:
"""Get the hostname from the command line utility `hostname`
:return: (str) of the hostname
"""
p = subprocess.Popen(["hostname"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
return p.communicate()[0].rstrip().decode("utf-... | 2f4d9c684d933cc6966cf7cdccc3e2d0ef08fa16 | 646,544 |
def pkg_key(pkg, type_):
"""
generate a package key for a given type string
Generates a compatible "package key" for a unsanitized package name ``pkg``
of a specific key ``type``. The package string is "cleaned" to replaces
select characters (such as dashes) with underscores and becomes uppercase.
... | c61ff00db34d0d838bd95ff011679a1ec523a3af | 646,545 |
import re
def generate_node_id(node, data):
"""Generate a node ID from the node label, extracts data from: [$ID].
Return the extracted node ID and the label, without the ID part, so
it can be the expression if one isn't specified in the description."""
pat = r"\[(?P<node_id>\w+)\]"
m = re.search(... | 65826d73028d3f5fc7107b7f540e698d5f8739f5 | 646,546 |
import argparse
def parse_args():
""" Parses the command-line arguments.
"""
parser = argparse.ArgumentParser(description='Submits data to the real-time streaming endpoint.')
parser.add_argument('-k', '--key', required=True, help='YOUR_DEEPGRAM_API_KEY (authorization)')
parser.add_argument('input'... | 71befb4351abfc771f56b2e813493e2484c0079a | 646,547 |
from typing import Counter
def most_repeated_values(query_list):
"""[Get most repeated values for each key in list of objects]
Args:
query_list ([list]): [List of dictionaries containing
query results from three different APIs. Dict Keys are
'deductible', 'stop_loss', 'oop_max']
... | ebf31b2881f49701d0817bb8c715002c8244a6e1 | 646,548 |
def get_translation_suggestions(vocabulary_article, translation_suggestions):
"""Returns XML with translate suggestions"""
res = []
if len(vocabulary_article['def']) != 0:
for article in vocabulary_article['def']:
for translation in article['tr']:
if 'ts' in article.keys(... | ba5ff2db5222d6428872fc1d2769a06faa8d0fb9 | 646,549 |
def normalize(msg):
"""
Normalizes the plain text removing all invalid characters and spaces
:param msg: Plain text to be normalized
:return: the normalized message without invalid chars
"""
return "".join([let.lower() for let in msg if let.isalpha() or let.isdigit()]) | d0bea7e7a813196d49cda8873d756849ec61b36d | 646,550 |
import json
def load_json(filename):
"""Load dictionary from JSON file."""
with open(filename, 'r') as f:
mybooks = json.load(f)
return(mybooks) | 3edd21661886ea783e1e9d9c4f4c65561e35f060 | 646,551 |
def update_nested_dictionary(old, new):
"""
Update dictionary with the values from other dictionary. Recursively update
any nested dictionaries if both old and new values are dictionaries.
:param old: Old dictionary that will be updated
:type old: dict
:param new: New dictionary that contains t... | 9960cab305508a38b7b245c2db468db263c413d5 | 646,552 |
def fisbHexErrsToStr(hexErrs):
"""
Given an list containing error entries for each FIS-B block, return a
string representing the errors. This will appear as a comment in either
the result string, or the failed error message.
Args:
hexErrs (list): List of 6 items, one for each FIS-B block. Each entry
... | 7f81dc250b6e780f384720d98bb53574b1da86f9 | 646,553 |
def wing(Sw,bw,cw,Nwr,t_cw,Nwer,nult,GW):
""" Compute weight of human-powered aircraft wing
Assumptions:
All of this is from AIAA 89-2048, units are in kg. These weight estimates
are from the MIT Daedalus and are valid for very lightweight
carbon fiber composite structures. This may n... | be00ec0cc3580fb2446b5bbb9fca391845da6855 | 646,554 |
def _spline_to_path_list(spline, height, replace_with_prev=False):
"""Converts SplineSet to a list of tokenized commands in svg path."""
path = []
prev_xy = []
for line in spline.splitlines():
if not line:
continue
tokens = line.split(' ')
cmd = tokens[-2]
if ... | 7622974bd0426e45e3c86ea9303ef800ff47da7f | 646,555 |
import argparse
import os
def parse_args(argv):
"""Parse input arguments"""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('exp_name', type=str,
help='id of experiment. Ex: exp0')
... | 0d410335b7fcfd9de0d97b2c687ba920129fa693 | 646,557 |
import codecs
def get_nationality(nation):
"""Test id a word is a nationality adjective"""
with codecs.open("nationalities.txt", "r", "utf-8") as f:
nationalities = {}
for x in f.readlines():
nationalities[x.strip().lower().split(',')[1]] = x.strip().lower().split(',')[0]
res... | 483c05fcee24d0712153d6e132456f0cc0af46a3 | 646,558 |
import numpy as np
from typing import Collection
from typing import Dict
def symbol_counts_dist(texts: Collection[str],
symbols: str = "`~!@#$%^&*)(-_+=|\\}{][:;><,.?"
) -> Dict[str, Dict[int, int]]:
"""Count distribution of symbols in strings."""
return {
... | 1aa01daf9cff5b1b37646595112a4f62b88e311c | 646,559 |
import os
def is_elf_binary(bin_path):
"""Return true if the binary is valid ELF."""
if not os.access(bin_path, os.X_OK):
return False
if os.path.islink(bin_path) or os.path.isdir(bin_path):
return False
with open(bin_path, 'rb') as f:
if f.read(4)[1:].decode('ascii') != 'ELF':
return False
... | 3ec1c804c7f31621d2d9c9b97299a3910cb5c5a0 | 646,560 |
def read_lines(file_name):
""" Read lines from given file and return as list """
with open(file_name, 'r') as fobj:
lines = fobj.readlines()
return lines | d5fbf26b61029a6cfd1738b8d3f44b71bbf6e0a2 | 646,561 |
def defaults_add(dictionary, defaults):
"""if a value has not been defined in the dictionary add it from defaults"""
if dictionary:
for key in defaults.keys():
if not key in dictionary.keys():
dictionary[key] = defaults[key]
return dictionary
else:
return ... | 54e79251ce50f0f73830612d3fa4b63b50d6be5d | 646,563 |
def count_frequency(my_list):
"""
count the frequency of elements in a list using a dictionary
Args:
my_list (list): List
Returns:
dict: Dictionary containing unique item and frequency
Example::
>> my_list = ["happy", "neutral", "happy"]
>> count_frequency... | 8db1b58f429fe596e73094e0ae100a38251acf86 | 646,564 |
def _ensure_list(item):
"""
Ensures that the given item is a list.
:param item:
:return:
"""
if item is None:
return []
if isinstance(item, list):
return item
if isinstance(item, tuple):
return list(item)
return [item] | 35f5fffdf8cdcac5d2ecd1f2291395a633ceddc7 | 646,565 |
import ast
async def literal_eval(str_to_eval: str):
"""
Evaluate the input using ast.literal_eval()
Parameters
----------
str_to_eval : str
A string to be evaluated.
Returns
-------
dict
A dict containing python literal.
Examples
--------
The following ... | b2dd7870ec94bf0f3e87e423169a34366c9c5296 | 646,566 |
import glob
import os
def iterate_dictionary(path):
"""iterates through all kinds of files in a directory by using the
glob package and leaves directories alone"""
if path[-1] != "/":
path += "/"
files_only = list(filter(lambda obj: os.path.isfile(obj), glob.glob(path + "*")))
retu... | b1d7681f1e15c3d918cda0a9217a8322f5e56f4d | 646,567 |
from typing import Dict
import subprocess
def get_pip_requirements() -> Dict[str, str]:
"""This assumes it was generated with pip freeze, i.e, all lines are =="""
output = subprocess.check_output("pip freeze", shell=True, text=True)
cleaned_packages: Dict[str, str] = {}
for row in output.split("\n"):
... | 3d7b3fa623200c9805f28bbde7e17293efae5f10 | 646,568 |
from typing import Tuple
def asn1_get_value(der: bytes, indices: Tuple[int, int, int]) -> bytes:
"""get value"""
ixs, ixf, ixl = indices
return der[ixf : ixl + 1] | c6479812c070b3d331749bbd885c90df6c46cd04 | 646,569 |
def add_neighbours(cluster_index, Adj, check, factor=0.5):
"""
Creates a list of nodes which are densely connected between each other.
Parameters
----------
cluster_index : Node index of nodes belonging to a densely connected cluster
Adj : Adjacency matrix of the graph
check : Temp arra... | f597582bfd8b107022ce5325658fa52684db3a65 | 646,570 |
from pathlib import Path
def guess_array_type(raw_data: Path) -> str:
"""
Guess array type, just like its name suggested
"""
raw_data = Path(raw_data)
if not raw_data.exists():
raise FileNotFoundError(f"Could not find: {str(raw_data)}")
array_type = None
for file in raw_data.iterd... | 59953d01c035bbf742f4b0bcfc7185b328c54d2b | 646,572 |
import torch
def sequence_loss(flow_preds, flow_gt, valid_flow_mask, gamma=0.8, max_flow=400):
"""Loss function defined over sequence of flow predictions"""
if gamma > 1:
raise ValueError(f"Gamma should be < 1, got {gamma}.")
# exlude invalid pixels and extremely large diplacements
flow_norm... | fdf5bdeb3830871fd851e49c3e6f317471fe9d2a | 646,573 |
def floodFill(pos, data, dataArray):
"""
checks how much room there is if snake does a move
used so snake doesn't run into a corner
returns free space
"""
count = 0
try:
if dataArray[pos["y"]][pos["x"]] == 1 or pos["x"] not in range (0, data["board"]["width"]) or pos["y"] not in range(0, data["board"]["height"... | 67439d8fe05ebc18d2de6a2dfd0ec1575eef39d9 | 646,574 |
def header_exists(header_name, headers):
"""Check that a header is present."""
return header_name.lower() in (k.lower() for (k, _) in headers) | bf0dd31a9febbed20efb7e8078bc085b5fe4f792 | 646,576 |
def pre_process_expressions(expressions, variable_templates):
"""
This one is pretty simple - pass in a list of expressions which contain
references to templates and pass a dictionary of the templates themselves.
Strings will only be evaluated which are prepended with $.
Parameters
----------
... | ae9a418215380d5804de9ad339af12601f29abc1 | 646,577 |
import torch
def neigh_square(position_diff: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
"""
Square-shaped neighborhood scaling function based on center-wise diff `position_diff` and radius `sigma`.
Parameters
----------
position_diff : torch.Tensor
The positional difference aroun... | abebe4bbcbb348d45b396867b833fcb0714cb0ca | 646,578 |
def join_strings(strings, glue=" AND "):
"""
Returns the non-empty strings joined together with the specified glue.
@param glue separator used as glue between strings
@return (joined string, number of strings actually used)
"""
strings = list(filter(None, strings))
return glue.joi... | 18a786d7f74cc07a3645036dfbd012c3268c0d07 | 646,580 |
import argparse
def get_parser():
"""
Get parser.
:return: parser
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser('Evaluate predicted occupancy grids and LTSDFs.')
parser.add_argument('--predictions', type=str, help='Predictions HDF5 file.')
parser.add_argument('... | 68128e90f5a93c0c89f13578470d8fe4b76d6303 | 646,581 |
import bz2
def task_compress_bz2():
"""bz2 compression (C)"""
with open(__file__, "rb") as f:
arg = f.read(3000) * 2
def compress(s):
bz2.compress(s)
return compress, (arg, ) | 1644ad2155061e35a25e176bd5bea82be33e79db | 646,582 |
def custom(datacells, ncells, value):
"""Calculate percent of total"""
x = float(datacells.GetUnformattedValueAt(ncells-1,2)) # total
return float(value) / x | f65190bd2680f5a2adc8065d1e5d75630ccd2136 | 646,583 |
def shape(x):
"""Change str to List[int]
>>> shape('3,5')
[3, 5]
>>> shape(' [3, 5] ')
[3, 5]
"""
# x: ' [3, 5] ' -> '3, 5'
x = x.strip()
if x[0] == '[':
x = x[1:]
if x[-1] == ']':
x = x[:-1]
return list(map(int, x.split(','))) | 554d2c3f7572b10a897d03c679420a8afed56a0a | 646,584 |
def Node(k: int, v: str, l: dict, r: dict) -> dict:
""" Crée un arbre binaire avec un noeud de clé k, de valeur v, de fils gauche l et de fils droit r."""
return {"Node": (k, v, l, r)} | 17de88202b327655899a7daf4675276302dac177 | 646,585 |
def determineWhatIsDeleted(ref, alt):
"""Must take the deletion from the ends.
"""
altIdx = ref.find(alt)
if altIdx == 0:
# the tail is deleted
# AGGTCTG to A
# TCCTACACCTACT to TCCTACA so TCCTACA(CCTACT) (want)
endDelIdx = altIdx + len(alt)
return ref[endDelIdx:]... | 0b58e91b8e52f4c2e445612fc16af47bb4d6fff5 | 646,586 |
import glob
import os
def get_files(directory, pattern = "*.gz", full_path = True):
"""
Returns the files in the specified directory.
:param directory: the directory to scan
:param pattern: the file extension, default '*.gz'.
:param full_path: if True the full path to the files is retured, otherw... | 92de9924e58e260504fdda988dc93b0445d0f485 | 646,587 |
def max_value(tab):
"""
Brief: computes the max with positiv value
Args:
tab: a liste of numeric value exepcts at least one positive valus, raise expection
Return: the max value
Raises :
ValueError if no positive value is found
"""
if not(isinstance(tab, list)):
rai... | 82a6e83df070a8e32ecce6f12a7e0a03307b81ce | 646,588 |
def calc(x, y, serial):
"""
Find the fuel cell's rack ID, which is its X coordinate plus 10.
Begin with a power level of the rack ID times the Y coordinate.
Increase the power level by the value of the grid serial number (your puzzle
input).
Set the power level to itself multiplied by the rack I... | f3aac2bbb2e3180716773c7751678dbb4335890c | 646,589 |
def swap_chunk(chunk_orig):
"""Swap byte endianness of the given chunk.
Returns:
swapped chunk
"""
chunk = bytearray(chunk_orig)
# align to 4 bytes and pad with 0x0
chunk_len = len(chunk)
pad_len = chunk_len % 4
if pad_len > 0:
chunk += b'\x00' * (4 - pad_len)
chun... | 0548dc9fa5ade75668cdabe7e817dcbbaf214ec3 | 646,590 |
def _cut_title(fixed_front, variable, fixed_rear, MAX_LENGTH=240):
"""Return the given title smartly cut"""
fixed_length = len(fixed_front) + len(fixed_rear)
available_length = MAX_LENGTH - fixed_length
chunked = variable.split()
part = 1
while len(variable) > available_length:
variable ... | 332d897d7fdfa957e571ddbeaa8ca204cdfa33b3 | 646,591 |
def sdfGetTitle(mol):
"""
sdfGetTitle() returns the title of molecule mol
"""
molblock = mol["molblock"]
if not molblock:
return None
first_eol_pos = molblock.find('\n')
return molblock[0:first_eol_pos] | dd10996c8760561ba48536524f11a213df34535f | 646,592 |
def make_snapshots(frame, ignore):
"""Extract a subset of atoms from a given frame."""
snapshot = {
'header': 'Removed.',
'box': frame['box'],
'residunr': [],
'residuname': [],
'atomname': [],
'atomnr': [],
'x': [],
'y': [],
'z': [],
}
... | e2356bdad3c8fe7633d598ea6e49825e90daf671 | 646,593 |
def getFluctuationFrame(
dataFrame,
valueKeys,
collectByKeys,
averageOverKeys=None,
):
"""Routine for computing the collective average and standard deviation
information for specified keys in a data frame.
Computes the mean and standard deviations for the 'valueKeys' over all keys
no collected ... | 6640ef2ad1595e05fbd857cae3b1edbd9b290828 | 646,594 |
def comp_sym(self):
"""Compute the symmetry factor of the lamination
Parameters
----------
self : LamHole
A LamHole object
Returns
-------
sym : int
Number of symmetries of the Lamination
is_antisym : bool
True if an anti-symmetry is possible after the symmetrie... | 578675969592f3d646ba7a662f62d185c0c7ecca | 646,595 |
def measure(function, xs, ys, popt, weights):
"""
measure the quality of a fit
"""
m = 0
n = 0
for x in xs:
try:
if len(popt) == 2:
m += (ys[n] - function(x, popt[0], popt[1]))**2 * weights[n]
elif len(popt) == 3:
m += (ys[n] - func... | e473236980cd6ecffb0c180ef66e8b63002893e6 | 646,596 |
def find_schema_links(resource_type, schemas):
"""
returns a dict with schema and paths pointing to resource_type
e.g.
find_schema_links("person", schemas) should return:
{
"software": [
[
"contributors",
"foreignKey"
]
]
},... | b4be346b5b9f8749fffff6f549b334bfe567a8c5 | 646,597 |
def cg(A, b, x, imax=50, eps=1e-6):
"""
A, b, x : matrix, rhs, solution
imax : maximum allowed iterations
eps : tolerance for convergence
"""
# allocate work vectors
r = b.duplicate()
d = b.duplicate()
q = b.duplicate()
# initialization
i = 0
A.mult(x, r)
r.... | 0dd452bf7082b26467c9300d8f3396b618c8040a | 646,598 |
import os
def get_times(file):
"""
Return a tuple of (atime, mtime) for the given file.
"""
stat_info = os.stat(file)
return (stat_info[7], stat_info[8]) | f6b22058b03ee8b2f15885748b9b580450fd12f1 | 646,599 |
import sys
import shlex
def invocation():
"""reconstructs the invocation for this python program"""
cmdargs = [sys.executable] + sys.argv[:]
invocation = " ".join(shlex.quote(s) for s in cmdargs)
return invocation | bd72c1b92e81386319ee88ce1e89a82fabf93974 | 646,600 |
import json
def compare(df):
"""
If the category of UEID is present in the segment file, it is considered as normal(0)
otherwise, the sample is considered as anomaly.
"""
with open("ad/ue_seg.json", "r") as json_data:
segment = json.loads(json_data.read())
anomaly = []
for i in d... | 4a3c42975a5b86db076e3a26a83b8f607df16f62 | 646,601 |
def mean_gare(data):
"""
Affiche le barycentre des données.
:param DataFrame data: Tableau de données numériques.
:return: * **b** (*pd.core.Series.Series*) - Le vecteur aux coordonnées moyennes.
:example: .. code:: python
>>> import asltam as atm
>>> # aff... | d39a638c904ca7cc0d4c4045df64cf4cce511270 | 646,602 |
from typing import Optional
import os
def auto_detect_content_type(filename: Optional[str]) -> Optional[str]:
"""Auto detects the content type based on the filename.
Args:
filename : A filename to use to auto detect the content type.
Returns:
The content type of the file. None if the con... | 3a0daa4419f33fb5e7aba556eca16324cda67c5d | 646,603 |
def clone_aiida_structure (s):
"""
A cloned structure is not quite ready to store more atoms.
This function fixes it
"""
t=s.clone()
t._internal_kind_tags={}
return t | ebee925dd651fbc9faffb58ab168633b493b4ed8 | 646,604 |
import sys
def isatty():
"""
Wrapper for isatty
I use this for monkeypatching input detection
in the add method. Its not nice. It works. Its mine <3
"""
return sys.stdin.isatty() | 19b3b1daa514131d78fde85be66246fb7ddf86c7 | 646,605 |
def calculate_difference(dsm_array, dtm):
"""Calculate the difference between the dsm and dtm"""
dtm_array = dtm.read(1, masked = True)
difference = dsm_array - dtm_array
difference.data[difference < 0] = 0 # We set to 0 anything that might have been negative
return difference | 962078fe055b27189472fceb4008665aa946b038 | 646,606 |
def norm_colname(colname):
"""Given an arbitrary column name, translate to a SQL-normalized column
name a la CARTO's Import API will translate to
Examples
* 'Field: 2' -> 'field_2'
* '2 Items' -> '_2_items'
Args:
colname (str): Column name that will be SQL normalized
Return... | 623eef718a6f74d374250a32f291b499fae0d9fa | 646,607 |
def destination_mac(source_list):
"""Returns the destination MAC address, byte 0 - byte 5"""
output = ""
for i in range(6):
output += source_list[i] + " "
return output[:-1] | b6a5d7f65451600dffc2fc755efec5f186937f2b | 646,608 |
def build_vo_from_dn(user_dn):
"""
Generate an 'anonymous' VO from the user_dn
"""
components = filter(lambda c: len(c) == 2, map(lambda c: tuple(c.split('=')), user_dn.split('/')))
domain = []
uname = ''
for key, value in components:
if key.upper() == 'CN' and not uname:
... | 4671fa86db805acc7415c34bf6c8e3b9cddf98fd | 646,609 |
from typing import Iterable
from typing import Any
def composed_to_string(seq: Iterable[Any]) -> str:
"""Test helper to convert a sql query to a string for comparison.
Works for queries built with postgres.sql.Composable objects.
From https://github.com/psycopg/psycopg2/issues/747#issuecomment-662857306
... | c2a0263c4adc68fe8a60923425b421b3239812e9 | 646,610 |
def makesafe(s):
"""Makes the given string "safe" by replacing spaces and lower-casing (less aggressive)"""
def rep(c):
if c.isalnum():
return c.lower()
else:
return '_'
ret = ''.join([rep(c) for c in s])
return ret | 13d8b683c348c991007ee2463e976ac1da394d29 | 646,611 |
from glob import glob
import os
import stat
def get_searched_ids(root_directories):
"""Export the inode numbers of the selected directories."""
inode_to_path = {}
inodes = "{"
total_dirs = 0
for root_directory in root_directories.split(','):
searched_dirs = glob(root_directory, recursive=T... | b7c3e53fbaa8805638ba31305cffc4602d9d90c4 | 646,612 |
def _get_empty_lines(text):
"""Get number of empty lines before and after code."""
before = len(text) - len(text.lstrip('\n'))
after = len(text) - len(text.strip('\n')) - before
return before, after | e9125dc8039ebe4208c8358fb11dd33e58ee8506 | 646,614 |
import re
def unescape(in_s):
"""
:param in_s: Input string
"""
return re.sub(r"\\(.)", r"\1", in_s) | b266a00e6c29fd155d0793354fd2159dcd7b5a33 | 646,616 |
def _get_db_table_for_model(model):
"""
Return table name in database server for passed model.
"""
return model._meta.db_table | 14607fd11ae308b371af45232467bbe13fe907ac | 646,617 |
def INT_ICART(a, b, c):
"""Given a, b, and c, return a cartesian offset.
#define INT_ICART(a, b, c) (((((((a)+(b)+(c)+1)<<1)-(a))*((a)+1))>>1)-(b)-1)
"""
return ((((((a + b + c + 1) << 1) - a) * (a + 1)) >> 1) - b - 1) | 9547d9a9de2bfde2a19144c1be314d23cdef173e | 646,618 |
async def root() -> dict:
"""Get root."""
return {"message": "Welcome:)"} | 0d33e7ea218fef200f8a855ebe80953a01733ef2 | 646,619 |
def run_process(cls_instance, message):
"""
运行一个子进程
:param MultiProcessExecutor cls_instance: 运行实例
:param Message message: 消息
:return: 执行结果
:rtype: dict
"""
return cls_instance.message_handler(message) | 53a7ce37428503ce30f7940fbc79179525252dbe | 646,620 |
def pixels_voisins(y, x):
"""
Calcul les 4 voisins du point aux coordonnees (y,x)
Retourne les voisins a droite gauche bas haut
"""
vecteur = [(0, 1), (0, -1), (1, 0), (-1, 0)]
voisins = []
for v in vecteur:
voisins.append((v[0] + y, v[1] + x))
return voisins | 7a02dde525cb1ef8e5e2d4fde9e72b5cf48a3254 | 646,621 |
def walk(path, container):
"""
Recurse over the ActBlue JSON object, and get the values that we need,
based on the settings file.
Returns a single value for each path.
"""
if not container or isinstance(container, str):
return None
key = path[0]
if len(path) == 1:
if key... | 5fe569bc6b15d29fe8761900383a6cd46b17f9b8 | 646,622 |
def feature_diff(features_a, features_b):
"""Compute features_a - features_b
:param features_a:
:param features_b:
:return:
"""
keys = set(features_a.keys() + features_b.keys())
diff = dict()
for k in keys:
v_a = features_a.get(k, 0.0)
v_b = features_b.get(k, 0.0)
... | a2b413afd8e91fc4dbd072a4463a9cc7d1815bf3 | 646,624 |
def sparse_mimmax(A, B, type="mim"):
"""Return the element-wise mimimum/maximum of sparse matrices `A` and `B`.
Parameters
----------
A:
The first sparse matrix
B:
The second sparse matrix
type:
The type of calculation, either mimimum or maximum.... | 922bd5a7a3d3651347b59e7c2f05b6e8983410bb | 646,625 |
import argparse
def parse_command_line():
"""Parse the utility's command-line arguments."""
parser = argparse.ArgumentParser(description='Read an AFP file or files and output an ASCII representation')
parser.add_argument(
'afp_files',
metavar='afp-file',
nargs='+',
help='an... | a6db6511093ec086ad4f0532a8d482b97a4051eb | 646,627 |
from typing import List
def find_missing_element(numbers: List[int]) -> int:
"""
Finds the missing element in a list of numbers
:param numbers of numbers
:return missing element
:rtype: int
"""
missing_element = len(numbers) + 1
for index, number in enumerate(numbers):
missi... | 4c6397104eeb580a3208c53fb889cd925a4d4abb | 646,628 |
import os
def rebase(path_to_rebase, base):
""" Rebase the parameter (a list or a single string)
"""
if base is None or base == "" or base == ".":
return path_to_rebase
path_list = path_to_rebase if isinstance(path_to_rebase, list) else [path_to_rebase]
rebased_paths = []
for path in p... | 943ed2c72e00c7e1e5edf17ed18497ca4bcece88 | 646,629 |
import os
def _is_astropy_source(path=None):
"""
Returns whether the source for this module is directly in an astropy
source distribution or checkout.
"""
# If this __init__.py file is in ./astropy/ then import is within a source
# dir .astropy-root is a file distributed with the source, but ... | fd20084fa95aa86d174ab364266d814cec1f927e | 646,630 |
def format_literal(raw):
"""Format a literal into a safe format. This is used to format the
flont:Literal IRI.
"""
return "_" + raw.replace(" ", "_") | 87a6d4b0eb0d162f178ebba4d628d09133c6ed84 | 646,631 |
def make_PEM_filename(cert_id: str) -> str:
"""Create a filename for PEM certificate"""
return cert_id + '.pem' | 48fe918f64822b74f580303ac022dbfda07468fd | 646,632 |
def is_in_list(num, lst):
"""
>>> is_in_list(4, [1, 2, 3, 4, 5])
True
>>> is_in_list(6, [1, 2, 3, 4, 5])
False
>>> is_in_list(5, [5, 4, 3, 2, 1])
True
"""
if not lst:
return False
else:
return lst[0] == num or is_in_list(num, lst[1:]) | 891e6727ffe88f682f55bea5553df1ddc1558d90 | 646,634 |
def get_investigation_data(investigation_response):
"""Get investigation raw response and returns the investigation info for context and human readable.
Args:
investigation_response: The investigation raw response
Returns:
dict. Investigation's info
"""
investigation_data = {
... | 0caedeb4581a6fc5493b0c2fa7953b670a9c3008 | 646,635 |
def wraps(wrapped, fun, namestr="{fun}", docstr="{doc}", **kwargs):
"""
Like functools.wraps, but with finer-grained control over the name and docstring
of the resulting function.
"""
try:
name = getattr(wrapped, "__name__", "<unnamed function>")
doc = getattr(wrapped, "__doc__", "") or ""
fun.__d... | b3fa0464bdde8518eeed626dab5fcfaf38beac5a | 646,636 |
import re
def keyvault_name(name: str) -> bool:
"""Validate the name of the keyvault.
Args:
name (str): Name of the keyvault.
Returns:
bool: True or False depending on the name validity.
"""
regex = "^[a-zA-Z0-9-]{3,24}$"
pattern = re.compile(regex)
return pattern.match(... | db648c1d1c507f652ebd4e589c1b37ea9459e746 | 646,637 |
def misses_cost(a: set, b: set):
"""
Misses cost measures the proportion of non-sensitive itemsets hidden by the sanitisation process;
this indicates the number of itemsets which are consistent across the original and sanitised database.
Given a transactional database D and an associated sanitised data... | 78c0a452ac14469313ecddc31390f882195e6736 | 646,638 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.