content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def to_real(x):
""" Use to print VHDL variables as float: example print(to_real(x))"""
return x | 07bb6b570d415d1523ce89fa4091ab63e5f6fb50 | 684,183 |
import os
def get_model_path(modelname):
"""
Config your pretrained model path here!
"""
# raise NotImplementedError("Please config your pretrained modelpath!")
pretrained_dir = '/config/to/your/pretrained/model/dir/if/needed'
PTDICT = {
'CvT_w24': 'CvT-w24-384x384-IN-22k.pth',
... | 4c18c14bcf5f6327ab0dd898c8f05b01ee3d2905 | 684,184 |
def normalize_id(entity_type, entity_id):
"""return node type and node id for a given entity type and id"""
if entity_type == 'Chemical':
if entity_id == '':
return None
if entity_id[:5] == 'CHEBI':
return 'ChEBI', entity_id[6:]
elif entity_id[0] == 'D' or entity_... | 4ae621e72eb4dab7688543a96fb055bb3866069f | 684,185 |
def make_grid(x, y, fill: int = 0):
"""Make a 2x2 list of lists filled with "fill"."""
return [[fill for y in range(y)] for _ in range(x)] | e854943ee62138a9f68cb91fc0887765ff491948 | 684,186 |
def notas(*n, sit=False):
"""
->Recebe várias notas de alunos, e retorna o número
de notas (aceita várias), a maior e menor nota,
a média e a situação (opcional)
:param n: uma ou mais notas
:param sit: (opcional) indica a situação do aluno
:return: dicionário com as informações
"""
... | c9d932064383423ed4c6359ce2479ff6ea75fcc4 | 684,187 |
import os
def parse_timestamp(filename):
"""
File name parser when the name without extension is a Unix Epoch
"""
basename = os.path.basename(filename)
strtime = basename[:basename.index('.')]
return int(strtime) | 119c9cecfe8b7d8d694ab80f09e9810dacd00760 | 684,188 |
def is_disconnected(ret: int):
"""
check whether connection is lost by return value of OesApi/MdsApi
106 : ECONNABORTED
107 : ECONNREFUSED
108 : ECONNRESET
maybe there is more than there error codes indicating a disconnected state
"""
return ret == -106 or ret == -107 or ret == -108 | 8b675a501105188383ad1f47ae1d38568769a4fb | 684,189 |
def i8(x):
"""truncates x to a 8-bit integer"""
return x & 0xFF | 564cd8ffbe89dcfa32dd0d7f82d066449df50b58 | 684,190 |
def get_las_version(las):
"""
Get the LAS file format version from an in-memory lasio.LAFile object.
There are 3 possible versions (https://www.cwls.org/products/):
- LAS 1.2
- LAS 2.0
- LAS 3.0
Args:
las (lasio.LASFile): An in-memory lasio.LASFile object
Returns:... | dc06eebdc0a710d1d8d46f2bb6bfa135f9296a91 | 684,192 |
from typing import Any
def _remove_dummy_service_message(
service_messages: list[list[tuple[str, str, Any]]]
) -> list[list[tuple[str, str, Any]]]:
"""Remove dummy SM, that hmip server always sends."""
new_service_messages: list[list[tuple[str, str, Any]]] = []
for client_messages in service_messages:... | a125184fd0701245e003ed8a01ddf40f6f4061a3 | 684,193 |
import pathlib
import os
def newpathdir(filename, olddir, newdir, n=1):
"""Return /a/b/n/d/e.ext for filename=/a/b/c/d/e.ext, olddir=c, newdir=n"""
p = pathlib.PurePath(filename)
assert sum([d == olddir for d in p.parts]) == n, "Path must have exactly %s directory matches" % n
return os.path.join(*[d.... | 6392016841d164dd7870f8032c44ec623501e9a7 | 684,194 |
import os
def get_dir_files(dir):
"""
Get files in directory
Args:
dir: directory
Returns:
filenames:
files in directory
"""
filenames = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f))]
return filenames | 1c6835813ddfa5013e7d9d17db302522fd8a9336 | 684,196 |
from typing import Sequence
from typing import Dict
from typing import Any
def bind_function_args(argument_names: Sequence[str], *args,
**kwargs) -> Dict[str, Any]:
"""Returns a dict with function arguments."""
outputs = {}
for k, val in zip(argument_names, args):
outputs[k] = val
o... | 39853df7944cc219c601dc2f58a8844832b81911 | 684,197 |
def DropExpectation(_check, _step_odict):
"""Using this post-process hook will drop the expectations for this test
completely.
Usage:
yield TEST + api.post_process(DropExpectation)
"""
return {} | becfee63dd09e54545c504e8f2ed7596e9718568 | 684,198 |
from datetime import datetime
def get_date_string(date: datetime, format_: str = "%Y-%m-%d"):
"""Generic function to get a string from a datetime object
Args:
date: The value to be validated.
format_: A regex pattern to return the string with
Returns:
A string formatted
Rais... | 40d6fab206fcc8a311491c26eda989a40cbceb2d | 684,200 |
import os
def split_chunk_filepath(path):
""" Split chunk path into (basedir, basename, index, extension)
NOTE: extension contains the leading dot
"""
basedir, name = os.path.split(path)
name, ext = os.path.splitext(name)
basename, index = name.rsplit('_', 1)
index = int(index)
return... | 1d9f0dc3d8c9a8c8353583564622debf935fc1cc | 684,201 |
import importlib
def load_class(namespace):
""" Python package namespace with class, e.g. module.Class
:param namespace:
:return:
"""
module_name, class_name = namespace.rsplit(".", 1)
module = importlib.import_module(module_name)
return getattr(module, class_name) | 6ff38dbedc63059b037ee9323422a33455d233b3 | 684,202 |
from typing import Dict
def make_character_dict() -> Dict[str, str]:
"""Create dict of {character: label, ->} to label smiles characters
"""
character_dict = {}
atoms = ["C", "O", "N", "S", "B", "P", "F", "I", "c", "n", "o", '*',
'Cl', 'Br', 'p', 'b', 'p', 's']
cyclic = list(range(1,1... | 2df05f45fc1bceeccff3e33672db8761ea031da6 | 684,203 |
def calculate_fitness_value(
fitness,
normalize_rawfitness: int,
kii: int
) -> float:
""" Calculates and returns final fitness values of each individuals"""
if normalize_rawfitness != 0:
fit = fitness.rawfitness / normalize_rawfitness \
+ fitness.total_error * (20 +... | cb61a15db13574778742efbe3d886becf2bb3581 | 684,204 |
def list_contains_only_xs(lst):
"""Check whether the given list contains only x's"""
for elem in lst:
if elem != "X":
return False
return True | b2aefed95cbb93bc43aec80a17d2712bee49a11b | 684,205 |
import json
def decode_json(json_string: str) -> dict:
"""
Takes a message as a JSON string and unpacks it to get a dictionary.
:param str json_string: A message, as a JSON string.
:return dict: An unverified dictionary. Do not trust this data.
"""
return json.JSONDecoder().decode(json_string... | 31ecca471008ba13d2b767a41027fd5b1bf99486 | 684,206 |
def set_length_units(client, units, file_=None, convert=None):
"""Set the current length units for a model.
This will search the model's available Unit Systems for the first one
which contains the given length unit.
Args:
client (obj):
creopyson Client.
units (str):
... | d77a92be3cb107d59cbb5f5eb25b666a3880b283 | 684,207 |
import torch
import math
def log_sum_exp(a: torch.Tensor, b: torch.Tensor):
"""
Logsumexp with safety checks for infs.
"""
if torch.isinf(a):
return b
if torch.isinf(b):
return a
if a > b:
return math.log1p(math.exp(b - a)) + a
else:
return math.log1p(math... | e0e24a15a5ec1dd89376d09e8a558d2997b9356f | 684,208 |
from typing import List
from typing import Any
from typing import Union
from typing import Tuple
def isinstances(__obj: List[Any], __class_or_tuple: Union[Any, Tuple[Any]]) -> bool:
"""Return whether an every element of the list is an instance of a class or of a subclass thereof.
A tuple, as in `isinstance(x,... | 301beead20aabafeb6532a21fc5ad44fbc05fb4f | 684,209 |
def delta_seconds(delta):
"""Find the total number of seconds in a timedelta object.
Flatten out the days and microseconds to get a simple number of seconds.
"""
day_seconds = 24 * 3600 * delta.days
ms_seconds = delta.microseconds / 1000000.0
total = day_seconds + delta.seconds + ms_seconds
... | 3141888b18f257a1a66294b720f7503b9cf34314 | 684,210 |
def polynomial_power_combinations(degree):
"""
Combinations of powers for a 2D polynomial of a given degree.
Produces the (i, j) pairs to evaluate the polynomial with ``x**i*y**j``.
Parameters
----------
degree : int
The degree of the 2D polynomial. Must be >= 1.
Returns
-----... | 8cdbea13354f92182792e07de60f1457b759f4e6 | 684,211 |
def records_desc(table: bool) -> str:
"""description records"""
return 'Rows' if table else 'Features' | 763d1d4285b6c151ef77fa12fc5a8c2d1ebfdd87 | 684,212 |
def from_cpp(str_msg, cls):
"""Return a ROS message from a serialized string
Parameters
----------
- str_msg: str, serialized message
- cls: ROS message class, e.g. sensor_msgs.msg.LaserScan.
"""
msg = cls()
result = msg.deserialize(str_msg)
return result | 49ddbb290ff8a0bada431e87f86f31dbb0899889 | 684,214 |
def proj_masking(feat, projector, mask=None):
"""Universal projector and masking"""
proj_feat = projector(feat.view(-1, feat.size(2)))
proj_feat = proj_feat.view(feat.size(0), feat.size(1), -1)
if mask is not None:
return proj_feat * mask.unsqueeze(2).expand_as(proj_feat)
else:
retur... | a6c480f8c15aa1de7d398b169dad4d9d7ad6055d | 684,216 |
from typing import Optional
import os
import tempfile
import logging
def get_cache_dir(cache_dir: Optional[str] = None) -> str:
"""
Modified from https://github.com/facebookresearch/iopath/blob/main/iopath/common/file_io.py
Returns a default directory to cache static files
(usually downloaded from Int... | 4c278e9552a19a0222cf5809847d9570ba0d806f | 684,217 |
def team_map(fpl_data):
"""
team mapping
"""
return {team["id"]: team["name"] for team in fpl_data["teams"]} | 206b495051e7d50477480234e93bb1e452acd5e4 | 684,218 |
def failed(response):
"""DreamHost does not use HTTP status codes to indicate success or failure,
relying instead on a 'result' key in the response."""
try:
if response['result'] == u'success':
return False
except:
pass
return True | b3bc75a1d53af6cc0321ca57d67a9a6c919e5551 | 684,219 |
import os
import json
import six
def load_profile(file_path):
""" Load a check profile config file.
``file_path`` must be a valid json configuration file, this function
include a basic check for correctness (required keys and type).
Args:
file_path (str): Config file (json) a... | 0a9a1433632bacb5b7a258eac26c20efec8b9035 | 684,221 |
import torch
def layer_regularizer_L2(G, zd, z, y, lay):
"""L2 regularizer on G activations.
Args:
G: GAN generator (from pretorched).
zd: modified z vector.
z: noise vector.
y: class vector.
lay: GAN layer.
"""
zd_activations = G.forward(zd, y, embed=True, la... | 6cf37e57cfdb14d28a7fe1e279f5cdaa150bd7e3 | 684,222 |
def XXX(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root:
if root.left and root.right:
return 1+min(self.XXX(root.left),self.XXX(root.right))
elif root.left:
return 1+self.XXX(root.left)
elif root.ri... | 13664efe3e7dc99f6d64b6a44afd55aae26b9aac | 684,224 |
import os
import logging
def exist_file(file_adress: str) -> bool:
"""
Check if a given file exist at the given adress
args: file_adress is the address of the file
return: return if the file exists
"""
if os.path.isfile(file_adress):
logging.info(f'found file at {file_adress}')
... | 0889b8b931a3c06623edec42e41278b2135b3c3d | 684,225 |
from typing import Dict
from typing import List
def response_value() -> Dict[str, List[str]]:
"""Fixture for response value."""
return {"key": ["value1", "value2"]} | ffcff740efcb7fb56d57ee3e82a897e34441e4dd | 684,227 |
def ipv4_lstrip_zeros(address):
"""
The function to strip leading zeros in each octet of an IPv4 address.
Args:
address: An IPv4 address in string format.
Returns:
String: The modified IPv4 address string.
"""
# Split the octets.
obj = address.strip().split('.')
for ... | 154fc62abe71e108587cf18c23f81dfecc2ed916 | 684,228 |
def expand_word_graph(word_graph):
"""Expands word graph dictionary to include all words as keys."""
expanded_word_graph = word_graph.copy()
for word1 in word_graph:
for word2 in list(word_graph[word1]):
expanded_word_graph[word2] = (expanded_word_graph.get(word2, set())
... | 8f1b309eed6950eabd2f24772edb4d9330293638 | 684,229 |
def get_available_eval_metrics():
"""Output the available eval metrics in the cytominer_eval library"""
return [
"replicate_reproducibility",
"precision_recall",
"grit",
"mp_value",
"enrichment",
"hitk",
] | d51e5ca022849bc0a949d6157fb15c8e6b1d84b2 | 684,230 |
import os
def top_dir():
"""
returns project top most directory
:return: (str) Project directory
"""
return os.sep.join(
os.path.dirname(
os.path.realpath(__file__)).split(
os.sep)[
:-2]) | 3fb18ecedd71b335385e188a933641b8022f3e96 | 684,231 |
import re
def join_lines(src, before, after, sep=" "):
"""
Remove the newline and indent between a pair of lines where the first
ends with ``before`` and the second starts with ``after``, replacing
it by the ``sep``.
"""
before_re = "][".join(before).join("[]")
after_re = "][".join(after).... | c11ace588e83edf4ea9447a2b1f043f01a07ffeb | 684,232 |
def parse_cell(cell, rules):
""" Applies the rules to the bunch of text describing a cell.
@param string cell
A network / cell from iwlist scan.
@param dictionary rules
A dictionary of parse rules.
@return dictionary
parsed networks. """
parsed_cell = {}
for key in rule... | a3cdaed28c82a5f278a5deeff65ecaf08f58de0a | 684,233 |
def flatten_stmts(stmts):
"""Return the full set of unique stms in a pre-assembled stmt graph.
The flattened list of of statements returned by this function can be
compared to the original set of unique statements to make sure no
statements have been lost during the preassembly process.
Parameters... | a527b40950042f530971cdb5f37559788c1d7b98 | 684,234 |
import numpy
def raw(signal):
"""
compute the raw audio signal with limited range
Args:
signal: the audio signal from which to compute features. Should be an
N*1 array
Returns:
A numpy array of size (N by 1) containing the raw audio limited to a
range between -1 a... | 3e041e1b7e40085aff76c88e288fd81e9c94bee4 | 684,235 |
def value_check(arg_name, pos, allowed_values):
"""
allows value checking at runtime for args or kwargs
"""
def decorator(fn):
# brevity compromised in favour of readability
def logic(*args, **kwargs):
arg_count = len(args)
if arg_count:
if pos <... | d65efa24d2ad3766353092c76ccdb7e7aa7395e7 | 684,236 |
import math
def round_sig(number, precision=4):
""" Round number with given number of significant numbers - precision
Args:
number (number): number to round
precision (int): number of significant numbers
"""
if number == 0.0:
return number
return round(number, precision - ... | 0f10f35dd0cc08e097853125f13968f8fffad7d3 | 684,237 |
def pairs(k, arr):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/pairs/problem
You will be given an array of integers and a target value. Determine the number of pairs of array elements that
have a difference equal to a target value.
Args:
k (int): The target difference
... | ddf8236b4e87599ea4a969a6171e2c94b9bda732 | 684,238 |
import numpy as np
def quatmul ( a, b ):
"""Returns quaternion product of two supplied quaternions."""
assert a.size==4, 'Error in a dimension'
assert b.size==4, 'Error in b dimension'
return np.array ( [ a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3],
a[1]*b[0] + a[0]*b[1] -... | 49cf2dbcc76167fb9508e264e77517e5c855f577 | 684,239 |
import hashlib
def hash_apitoken(accessToken, appSecret): # pragma: no cover
"""
**Deprecated**
The issued access token and app secret key are combined and hashed for use in API.
:param accessToken: Token Specify the access token issued at the time of authentication.
:param appSecret: Specify the... | c7a2dc5253d8a2338e7a879edff9b3caecfd6cca | 684,240 |
import os
def create_report_dir(dir_base_name):
"""
Creates a new directory in current working directory
Parameters:
dir_base_name (str): name of the directory
Returns:
str:Full path of the new directory
"""
current_dir = os.getcwd()
report_dir = os.path.join(current_dir,'Reports')
if not os.pa... | c67518cac5b1743d4e05ec0869cf4e0f0a10d10b | 684,241 |
def find(sexp, *names):
"""Return the first node in `sexp` whose name is in `names`"""
for child in sexp:
if child[0] in names:
return child | 35e581faa028447fcea1106da5877a4955147760 | 684,243 |
import json
def get_workflow_metadata(metadata_json):
"""Load workflow metadata from a JSON file.
Args:
metadata_json (str): Path to file containing metadata json for the workflow.
Returns:
metadata (dict): A dict consisting of Cromwell workflow metadata information.
"""
with ope... | ed838f72a3bb9df45d2d507a538aab5128cb3c8e | 684,245 |
def find_max_min(list_numbers):
"""
takes a list_numbers and returns min and max values
as list i.e [min, max]
"""
if not isinstance(list_numbers, list):
raise TypeError("expected list_numbers to be a list")
list_length = len(list_numbers)
# remove duplicates values and sor... | c083de3756b61b2d1bd46f8ce5ed3050b11ad374 | 684,246 |
def print_help_info():
"""
Print a list of help related flags
:return: 1 for exit code purposes
:rtype: int
"""
print("""
Help Flags:
--help-info This printout
--help More detailed description of this utility
--usage Arguments, parameters, flags, options, etc.... | e516d0245a956cff6018b20109778d8f864ea433 | 684,248 |
def create_unbroadcast_axis(shape, broadcast_shape):
"""Creates the reduction axis for unbroadcasting.
Args:
shape: A list. The shape after the broadcast operation.
broadcast_shape: A list. The original shape the array being unbroadcast
had.
Returns:
A list. The axes along which the array needs... | 2758f1f1b993dfa7bdba10343cc9afde4cfcf38e | 684,249 |
def check_zeros(counts):
"""
helper function to check if vector is all zero
:param counts:
:return: bool
"""
if sum(counts) == 0:
return True
else:
return False | cfaeb34b6ad94fc21c795720f3c8754f3d1823be | 684,250 |
def get_nat_orb_occ(lines):
"""
Find the natural orbital occupations
"""
nat_occ = []
start = False
for line in lines:
if start:
if line.strip():
nat_occ.append(abs(float(line.split('=')[-1].strip())))
else:
break
elif line ... | c1fe1b5f25578d2884925b7e2b786ee26a83dde9 | 684,251 |
def are_words_in_word_list(
words, word_list, case_sensitive=False, get_score=False, all_must_match=True
):
"""Checks if word(s) are contained in another word list.
The search can be performed with or without case sensitivity.
The check words can contain wildcards, e.g. "abc*" to allow
a wider range... | f1fa12e313fb65cf8606c7f81cc16b99b9e35c58 | 684,252 |
def percentiles_from_counts(counts_dt, percentiles_range=None):
"""Returns [(percentile, value)] with nearest rank percentiles.
Percentile 0: <min_value>, 100: <max_value>.
counts_dt: { <value>: <count> }
percentiles_range: iterable for percentiles to calculate; 0 <= ~ <= 100
Source: https://stackov... | 4a0ac65e8e35cee866d0aad2cbdcf066d06135f5 | 684,253 |
def epsi_vapor_bot(Fr_bot):
"""
Calculates the vapor content of bubble layer at the bottom of column
Parameters
----------
Fr_bot : float
The Frudo criterion at the bottom of column, [dimensionless]
Returns
-------
epsi_vapor_bot : float
The vapor content of bubble layer ... | 8828831e85ea2afcd645fb87f61961f8b32ca49c | 684,254 |
import subprocess
def execute_cmd(full_cmd, cwd=None):
"""Execute a git command"""
process = subprocess.Popen(
full_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd=cwd)
(stdoutdata, stderrdata) = process.communicate(None)
if 0 != process.wait():
raise ... | 41c6783ad5bc9fd8b908d4c5f6a88b157ef0cdcf | 684,256 |
def check_stat_proc(l_df):
"""
Check nr of processes done/running or not running
:param l_df:
:return:
"""
nrunning = l_df['status'][l_df['status'] == 'running'].count()
ndone = l_df['status'][l_df['status'] == 'done'].count()
nnrunning = l_df['status'][l_df['status'] == 'not running'].c... | 481eecd25be4edcc72ca4016bd4c2ca2a34f2493 | 684,258 |
def lscmp(a, b):
""" Compares two strings in a cryptographically safe way:
Runtime is not affected by length of common prefix, so this
is helpful against timing attacks.
..
from vital.security import lscmp
lscmp("ringo", "starr")
# -> False
ls... | 78713e2ff1da330eb7ad20ae5260cfdd0e6dae5b | 684,259 |
def flatten_double_list(double_list):
"""
flatten a double list into a single list.
"""
return [obj for single_list in double_list for obj in single_list] | 6ddfda54fe265947d8b6d6b9f05f926cc825b048 | 684,260 |
import sys
def get_abbr_impl():
"""Return abbreviated implementation name."""
if hasattr(sys, 'pypy_version_info'):
pyimpl = 'pp'
elif sys.platform.startswith('java'):
pyimpl = 'jy'
elif sys.platform == 'cli':
pyimpl = 'ip'
else:
pyimpl = 'cp'
return pyimpl | 8af7dc2127e14c573e7c61b3810d3d3bfb783c43 | 684,261 |
def slice_list_to_chunks(lst, n):
"""
Slice a list into chunks of size n.
Args:
list
int
Returns:
[list]
"""
chunks = [lst[x:x+n] for x in range(0, len(lst), n)]
return chunks | 0082ae78492b3927c63740b1606108b6e29f82a7 | 684,263 |
def get_age_bracket(school_type):
"""Return the age structure for different school types."""
age_brackets = {
'primary':[6, 7, 8, 9],
'primary_dc':[6, 7, 8, 9],
'lower_secondary':[10, 11, 12, 13],
'lower_secondary_dc':[10, 11, 12, 13],
'upper_secondary':[14, 15, 16, 17],
'secondary':[10, 11, 12, 13, 14, 1... | 099128fd30f332789ea457b6411d64148dec1ce3 | 684,264 |
def seq_to_arch(seq, num_nodes):
"""
Translates given sequential representation of an architecture sampled by
the controller to an architecture
Arguments:
seq: sequential representation of architecture
num_nodes: number of nodes in cell including the two input nodes
Returns:
... | 835ec0b656cf2ef310b7b4b43fb52280611c1820 | 684,265 |
def http_client_error(exc, request):
""" specific json renderer for HTTPClientError """
request.response.status_int = 400
return {'title': exc.title,
'explanation': exc.explanation,
'detail': exc.detail} | 4ae262fa6fe0f3d32f52ce75d96c2f5e0cf4f8c1 | 684,266 |
def get_project_files_results(resp):
"""
get the project files API results
"""
files_found = {}
for obj in resp.data['files']:
if obj['type'] == 'server_js':
ext = 'js'
elif obj['type'] == 'html':
ext = 'html'
else:
continue
key = '... | 250531c5e4c276238d1a4c5d89fd230fad7daeee | 684,267 |
def force_tuple(x):
"""Make tuple out of `x` if not already a tuple or `x` is None"""
if x is not None and not isinstance(x, tuple):
return (x,)
else:
return x | 3f2b16e4cfd95e9cd1d86c54a772aca18e4c1ca7 | 684,268 |
from typing import List
from typing import Dict
def _build_record_dict(record_strings: List[str]) -> Dict:
"""
Parse the pbn line by line. When a block section like "Auction" or "Play" is encountered, collect all the content of
the block into a single entry
:param record_strings: List of string lines... | 173a95d485dae9d6bfcc77f5d73c9ee3305e735a | 684,269 |
import resource
import platform
import math
async def get_max_rss_mb():
"""Get the max resident set size of this process in megabytes"""
max_rss_bytes = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
# rlimit in Linux returns kilobytes; other systems return bytes
# mebibytes (as per IEC standard)
... | 76d57ad2f195f718bfd9f25f99f13be2c2e978bb | 684,270 |
def gomc_control_file_written(job, control_filename_str):
"""General check that the gomc control files are written."""
file_written_bool = False
control_file = f"{control_filename_str}.conf"
if job.isfile(control_file):
with open(f"{control_file}", "r") as fp:
out_gomc = fp.readline... | 8ddb6620644aadf4afaae11f9d89004ac64cadbe | 684,271 |
def or_(source, added):
"""Combine two queries with 'or'"""
if source is None:
source = added
else:
source |= added
return source | 4f817d796ae8213165c6fea4ec0f7b5b5a7c03c9 | 684,272 |
import re
def escape(text):
"""Like re.escape(), but does not escape spaces"""
return re.escape(text).replace("\\ ", " ") | 9a0803c86496dbaff002a1d372c8707767252a08 | 684,273 |
def add_plotting_column(df):
"""
This function will create a new column ("plot_value") in the dataframe
and will set either a 0 if BisBis_BisBis % > BosTau_BisBis %, and 1 if
BisBis_BisBis % < BosTau_BisBis %
Args:
df: input file DataFrame
Returns: new dataframe with added "plot_value" ... | aa84ebf5d8d385b9fee6ed8a68dd009bf53b8673 | 684,274 |
def ts_to_vtt(timestamp):
"""
ts_to_vtt converts timestamp into webvtt times
"""
hours, seconds = divmod(timestamp, 3600)
mins, seconds = divmod(seconds, 60)
seconds = round(seconds, 3)
return f" {int(hours):02}:{int(mins):02}:{seconds:02}" | fe2b89aa45db2fe9de296623219770793584c705 | 684,275 |
def _node_label(node):
"""Generate a node label in the format of "support:name" if both exist,
or "support" or "name" if either exists.
Parameters
----------
skbio.TreeNode
node containing support value or name
Returns
-------
str
Generated node label
"""
lblst ... | fee8956d87dbb086a4723012822f93b45d4aac6c | 684,276 |
def fetch_tensor(name, ws):
"""Return the value of a tensor."""
return ws.get_tensor(name).ToNumpy() | 9f735a55e14f6c548a3e5c543ef9d7e9dc1bf54b | 684,277 |
import subprocess
def get_user_pool_id(stage):
"""
Retrieve the ID of this stage's Cognito User Pool.
"""
return subprocess.run(
f"./services/output.sh services/ui-auth UserPoolId {stage}",
check=True,
capture_output=True,
shell=True,
).stdout.strip() | 88fb5775f5e2702b0463c8cbcffb004a28c1ed7d | 684,278 |
def is_compatible_dict(base, delta):
"""
returns False if any key common to base/delta has a different type,
except for None values, dicts are evaluated recursively
"""
common_keys = [k for k in base if k in delta]
for k in common_keys:
if base[k] is None or delta[k] is None:
... | c3f17d01f2fd150afde5489f3d0f9dcbcd73430d | 684,279 |
def torch2numpy(img):
"""
Converts a torch image to numpy format
"""
if img.dim() == 4:
img = img.permute(0, 2, 3, 1).contiguous()
elif img.dim() == 3:
img = img.permute(1, 2, 0).contiguous()
return img.cpu().numpy() | 25fee887319d6014bc480498550c6b95fb0f6ea8 | 684,281 |
from typing import Dict
import re
def str_replace(s: str, replacements: Dict[str, str]) -> str:
"""Replaces keys in replacements dict with their values."""
for word, replacement in replacements.items():
if word in s:
s = re.sub(re.escape(word), replacement, s, flags=re.IGNORECASE)
retu... | dc805fc0c0774e2de0448d3860231743e909eaba | 684,282 |
def get_bits(num, gen):
""" Get "num" bits from gen """
out = 0
for i in range(num):
out <<= 1
val = gen.next()
if val != []:
out += val & 0x01
else:
return []
return out | cf6e6d34998f86f75861f39674c67551bf8c64df | 684,283 |
def GetMangledParam(datatype):
"""Returns a mangled identifier for the datatype."""
if len(datatype) <= 2:
return datatype.replace('[', 'A')
ret = ''
for i in range(1, len(datatype)):
c = datatype[i]
if c == '[':
ret += 'A'
elif c.isupper() or datatype[i - 1] in ['/', 'L']:
ret += c.... | 30a6e1af027de612b9217bf68fc77b65ff59cb32 | 684,285 |
def _this_group_length(sf, param):
"""Tells the parser that this parameter contains the length of the current
repeating group.
The length of some repeating groups are defined by a parameter placed before
the repeating group, while others are defined by a parameter in the repeating
group itself.
... | 4e67815f6cda1a91e36f6ba89ab375ef0a65cdf0 | 684,286 |
import re
def unflatten(json_dict):
"""
Convert the JSON Flat dictionary into nested one.
>>> unflatten({'draw': '3', 'columns[0][data]': '0', 'columns[0][name]': '', 'columns[0][searchable]': 'true', 'columns[0][orderable]': 'false', 'columns[0][search][value]': '', 'columns[0][search][regex]': 'fal... | 18d235ca6967704d36a3e9b74aa100e948d089f3 | 684,287 |
def sparse_image(img,cropx,cropy):
"""
Crop the imge and make it sparse.
Parameters
----------
img : numpy array
image to make sparse.
cropx : int
number pixels in the y direction.
cropy : int
numnber of pixels in the x direction.
Returns
-------
TYP... | dd256f84bbe0777f9a1272acb34311fc34c24129 | 684,288 |
def get_feature_class(base_name, workspace):
"""
Creates a valid ESRI reference to a shapefile or geodatabase feature class
base_name: the name of the feature class, without any extension
workspace: the name of the folder (for shapefiles) or geodatabase (for gdb feature classes)
return: a text strin... | 3e7e267ebf1cb53e93e4a4426e0846c72a234a3a | 684,289 |
def anchor_to_resource(resource, post_create_func=None, title=None):
""" Converts an LXML 'A' element into a resource dict """
href = resource.get('href')
resource = {
"description": title or resource.text_content().encode('utf8'),
"name": href.split('/')[-1],
"url": href,
"... | aed33483b78588fd7faebacbee28dc99ef25ed60 | 684,290 |
import signal
def signal_to_human(value):
"""signal_to_human() -- provide signal name based on subprocess return code
Args:
value (int) - Popen.returncode
Returns:
Signal name if it exists, otherwise the original value provided
"""
signals = {getattr(signal, name) * -1 : name for... | 2c8d3f098cb4a952bafda71cf3d20b3b834ef424 | 684,291 |
def clean_string(string):
"""Returns a string with all newline and other whitespace garbage removed.
Mostly this method is used to print out objectMasks that have a lot of extra whitespace
in them because making compact masks in python means they don't look nice in the IDE.
:param string: The string t... | b2bbd14705d8bd3480a74b7cb9bc7919f32c2495 | 684,292 |
def interpret_bintime(bintime):
"""If bin time is negative, interpret as power of two.
Examples
--------
>>> interpret_bintime(2)
2
>>> interpret_bintime(-2) == 0.25
True
>>> interpret_bintime(0)
Traceback (most recent call last):
...
ValueError: Bin time cannot be = 0
... | d5d90415c9725a3f7bc12e28bb1b5f216d2aee2c | 684,293 |
def SPRING_CONTRIBUTION(N_DOFSNODE, SPRINGS, N_DOFSPRINGS):
"""
This function creates the contribution of the spring elements in the global stiffness matrix.
Input:
N_DOFSNODE | Number of degress of freedom per node | Integer
SPRINGS | Nodal DOF spring properties ... | b2cb7b5399cebbbb367cbe158e1c414a3557bdfa | 684,294 |
import site
from distutils.sysconfig import get_python_lib
def get_site_packages():
""" Gets all site_packages paths """
try:
if hasattr(site, 'getsitepackages'):
site_packages = site.getsitepackages()
else:
site_packages = [get_python_lib()]
if hasattr(site, 'g... | 7fe6a7ad79b45f244d7b75adbdae3ece8b66f27c | 684,295 |
import gc
def _get_in_memory_objects():
"""Returns all objects in memory."""
gc.collect()
return gc.get_objects() | db3b57178267d0351c88b98571308362ea517415 | 684,296 |
def get_kernel(x, kernel):
"""
Calculates the kernel size given the input. Kernel size is changed only if the input dimentions are smaller
than kernel
Args:
x: The input vector.
kernel: The height and width of the convolution kernel filter
Returns:
The height and width of new co... | 5e07970f0a9ec7f0802371b9ef6c416d2f4e21d2 | 684,297 |
def isDead(nova, wolf, window):
"""Checks if Nova is dead and sets the output message to reflect her death"""
global msg
if wolf.dist >= nova.dist: msg = "Nova died! The wolves caught her, but she was a tasty snack!"
elif nova.health <= 0: msg = "Nova died! She ran out of health!"
elif nova.hunger... | 9c6ffe9424f0b4607ab13d126533e3e71452ec86 | 684,298 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.