content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def notebook(request, id=0):
"""
:param request:
:param id:
:return:
"""
get_notebook = JupyterNotebooks.objects.get(id=id)
return render(request, "customdashboard/notebook.html",
{'get_notebook': get_notebook}) | 12,100 |
def encrypt_decrypt(data_string, password, mode='encrypt'):
"""Encrypts OR Decrypts data_string w.r.t password based on mode specified
Parameters:
data_string: Text that needs to be encoded. passed in string format
password: a string to encrypt data before encoding into an image.
mo... | 12,101 |
def test_atanh():
"""Test atanh function behavior."""
dep_vector = np.array([0.1, 0.98, 0.5])
strict_compare_waves(dep_vector, peng.atanh, "atanh", "", np.arctanh) | 12,102 |
def compute_alphabet(sequences):
"""
Returns the alphabet used in a set of sequences.
"""
alphabet = set()
for s in sequences:
alphabet = alphabet.union(set(s))
return alphabet | 12,103 |
def numpy_dtype_arg_type(string: str) -> np.dtype:
"""argument type for string reps of numpy dtypes"""
try:
ret = np.dtype(string)
except TypeError as error:
raise argparse.ArgumentTypeError(error.message)
return ret | 12,104 |
def Diff(a, b):
"""Returns the number of different elements between 2 interables.
Args:
a(iterable): first iterable.
b(iterable): second iterable.
Returns:
int: the number of different elements.
"""
return sum(map(lambda x, y: bool(x-y), a, b)) | 12,105 |
def create_piechart(AttrJson, FnameImage, Title=None, Yunit="perc", LabelsMap=None, Silent=False):
"""
todo: add cycle-free subset to plot using pairs of similar colours
todo: add unit tests
Creates a pie chart of the basins of attraction specified in *AttrJson*.
Requires that *AttrJson* has been e... | 12,106 |
def load_description(model):
"""Load description of the <model>."""
desc = get_available_pkgyaml(model)
entry = read_mlhubyaml(desc)
return entry | 12,107 |
def timolo():
"""
Main motion and or motion tracking
initialization and logic loop
"""
# Counter for showDots() display if not motion found
# shows system is working
dotCount = 0
checkMediaPaths()
timelapseNumCount = 0
motionNumCount = 0
tlstr = "" # Used to display if timel... | 12,108 |
def test_server_cow_sends_400_response():
"""test cow route sends 400"""
response = requests.get('http://127.0.0.1:3000/cow?msg=hello')
assert response.status_code == 400
assert response.text == 'Incorrect format' | 12,109 |
def show_statistics(simulation_type, results, client_results, client_counters):
"""
Show statistics from queue.
"""
title = '\n\n\n{} Avg Delays for {} simulation {}'.format(
10 * '*', simulation_type, 10 * '*')
print(title)
if simulation_type == SimType.COM_SIM:
avg_delays, p0_x... | 12,110 |
def generate_star(rect: RectType, line_count: int = 20) -> vp.LineCollection:
"""Generate a set of line from a random point."""
orig_x = np.random.uniform(rect[0], rect[0] + rect[2])
orig_y = np.random.uniform(rect[1], rect[1] + rect[3])
r = math.hypot(rect[2], rect[3])
angles = np.linspace(0, 2 * ... | 12,111 |
def failure(request):
"""Display failure message"""
return HttpResponse(f"Failure! {request.session['failure message'] if request.session['failure message'] is not None else ''}") | 12,112 |
def visualize_image(cam, rgb_img, target_category):
"""
Visualize output for given image
"""
input_tensor = preprocess_image(rgb_img)
grayscale_cam = cam(input_tensor=input_tensor, target_category=target_category)
grayscale_cam = grayscale_cam[0, :]
output = cam.activations_and_grads(inpu... | 12,113 |
def read_csr_matrix(f):
"""Read A in compressed sparse row format from file f. Return dense ndarray.
Text file format:
- one number per line
- First number is m = number of rows
- Second number is n = number of columns
- Next m+1 numbers are the row pointers (int, zero-based)
- Next nnz num... | 12,114 |
def test_analysis():
"""Test the full analysis of a portfolio."""
asset1_close = [22.9, 24.8, 40.3]
asset2_close = [101.3, 129.9, 104.5]
analysis = Analysis.PortfolioAnalysis(Analysis.Portfolio([Datasource.DataSource(asset1_close, "Asset 1"),
... | 12,115 |
def _get_random_hangul(count=(0xd7a4 - 0xac00)):
"""Generate a sequence of random, unique, valid Hangul characters.
Returns all possible modern Hangul characters by default.
"""
valid_hangul = [chr(_) for _ in range(0xac00, 0xd7a4)]
return random.sample(valid_hangul, count) | 12,116 |
def test_prepare_for_install_on_installed(install_mockery, monkeypatch):
"""Test of _prepare_for_install's early return for installed task path."""
const_arg = installer_args(['dependent-install'], {})
installer = create_installer(const_arg)
request = installer.build_requests[0]
install_args = {'ke... | 12,117 |
def test_execute(fake: Faker, Context: MagicMock = None, **kwargs) -> None:
"""Test the Execution of a Chain.
Ensures that we can execute a chain given a specific context.
"""
# Given
context = Context()
prev_args, prev_kwargs = (tuple(), dict())
function = MagicMock(return_value=None)
... | 12,118 |
def build(dir, **kwargs):
"""run cmake to generate a project buildsystem
Parameters:
----------
dir str: Location of the CMake build directory
Keyword Args:
----------
parallel int: The maximum number of concurrent processes to use when building. Default: 1 less than
... | 12,119 |
def is_builtin_model(target: type) -> bool:
"""returns ``True`` if the given type is a model subclass"""
return is_builtin_class_except(target, ["MetaModel", "Model", "DataBag"]) | 12,120 |
def runQ(qparsed, params=dict(), nbcircuits=1, nbqubits = None):
"""
qparsed: qlang circuit (already parsed)
params:{x:np.array, t:np.array}
"""
#*** verify if parameters are ok for qparsed circuit ****
_ , vector_parameters = parseqlang.parameters_from_gates(qparsed)
for pname, dimension i... | 12,121 |
def add_CNNB_loss_v2(true_labels,
hidden,
embed_model,
bsz=512,
dataset='imagenet2012',
hidden_norm=True,
temperature=1.0,
strategy=None,
loss... | 12,122 |
def create_container_group_multi(aci_client, resource_group,
container_group_name,
container_image_1, container_image_2):
"""Creates a container group with two containers in the specified
resource group.
Arguments:
aci_client {azu... | 12,123 |
def simulation_wells(self):
"""Get a list of all simulation wells for a case
Returns:
:class:`rips.generated.generated_classes.SimulationWell`
"""
wells = self.descendants(SimulationWell)
return wells | 12,124 |
def getSmartMeter() -> Optional[str]:
"""Return smartmeter name used in recording."""
mapping = getDeviceMapping()
# Identifier for smartmeter is meter with phase 0
try: return next(key for key in mapping if mapping[key]["phase"] == 0)
except StopIteration: return None | 12,125 |
def olbp(array, point):
"""Perform simple local binary pattern calculation with a fixed
3x3 neighbourhood. Thanks to:
http://www.bytefish.de/blog/local_binary_patterns/
for a really nice explanation of LBP.
Won't return correct results around the image boundaries.
Because it's on... | 12,126 |
def handle_ref(p):
"""
参考文献
"""
if p.text:
if is_bold(p): # 标题
reference + PRef(R16(p.text))
else:
reference + PRef(p.text)
else:
pass | 12,127 |
def view_index(
request: http.HttpRequest,
workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
"""Render the list of views attached to a workflow.
:param request: Http request received.
:param workflow: Workflow being processed
:return: HTTP response with the table
"""
#... | 12,128 |
def inverseLPSB(data, mu, g):
"""Compute regularized L-PSB step."""
mUpd = data.mUpd
gamma = data.gamma
gammah = data.gamma + mu
Q22 = np.tril(data.STY[:mUpd, :mUpd], -1) + np.tril(data.STY[:mUpd, :mUpd], -1).T + \
np.diag(np.diag(data.STY[:mUpd, :mUpd])) + \
gamma * np.diag(np.diag... | 12,129 |
def canPlay(request):
"""
Endpoint qui retourne la liste des cartes qui peuvent être jouées ( pour le Player )
rq : {
"cards_played" : [
{
"card_name": "As",
"value_non_atout": 0,
"value_atout": 0,
"id" : "A"... | 12,130 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Genie Aladdin component."""
return True | 12,131 |
def _module_available(module_path: str) -> bool:
"""Testing if given module is avalaible in your env
>>> _module_available('os')
True
>>> _module_available('bla.bla')
False
"""
mods = module_path.split('.')
assert mods, 'nothing given to test'
# it has to be tested as per partets
... | 12,132 |
def delete_file_with_object(instance, **kwargs):
"""
Deletes files from system when UploadedFile object is deleted from database
:param instance: UploadedFile object (file that is being deleted)
:param kwargs:
:return:
"""
instance.file.delete() | 12,133 |
def stale_token():
"""
Handler function for a no more fresh token
"""
message = 'The JWT Token is not fresh. Please request a new Token directly with the /auth resource.'
log_unauthorized(message)
abort(403, message) | 12,134 |
def _GetPathBeforeFinalDir(uri):
"""
Returns the part of the path before the final directory component for the
given URI, handling cases for file system directories, bucket, and bucket
subdirectories. Example: for gs://bucket/dir/ we'll return 'gs://bucket',
and for file://dir we'll return file://
Args:
... | 12,135 |
def extend_requests(request_id=None, workload_id=None, lifetime=30, session=None):
"""
extend an request's lifetime.
:param request_id: The id of the request.
:param workload_id: The workload_id of the request.
:param lifetime: The life time as umber of days.
:param session: The database sessio... | 12,136 |
def iter_key_path_items(d, key_path_prefix=None, path_sep='.'):
"""
iterate through items of dict recursively, yielding (key_path, val) pairs for all nested values that are not dicts.
That is, if a value is a dict, it won't generate a yield, but rather, will be iterated through recursively.
:param d: in... | 12,137 |
def fulfil_defaults_for_data_model_identifiers(
data_model_identifiers,
context
):
"""
Intelligently set default entries for partially specified data model identifiers.
:param data_model_identifiers:
An list (or iterable) of dictionaries, where each dictionary contains keyw... | 12,138 |
def _add_default_arguments(parser: argparse.ArgumentParser):
"""Add the default arguments username, password, region to the parser."""
parser.add_argument("username", help="Connected Drive username")
parser.add_argument("password", help="Connected Drive password")
parser.add_argument("region", choices=v... | 12,139 |
def load_page_details(data, filename=None):
"""
# Raises
ValueError of (filename, error)
"""
try:
options = toml.loads(data)
except toml.TomlDecodeError as exc:
raise ValueError(filename, exc)
if not isinstance(options, dict):
raise ValueError(filename, 'page details could not be parsed into ... | 12,140 |
def nested_render(cfg, fully_rendered_cfgs, replacements):
"""
Template render the provided cfg by recurisevly replacing {{var}}'s which values
from the current "namespace".
The nested config is treated like nested namespaces where the inner variables
are only available in current block and further... | 12,141 |
def element_by_atomic_number(atomic_number):
"""Search for an element by its atomic number
Look up an element from a list of known elements by atomic number.
Return None if no match found.
Parameters
----------
atomic_number : int
Element atomic number that need to look for
if ... | 12,142 |
def get_data_from_db(cursor):
"""
Get data from the database given a query-instantiated cursor
:param cursor: query-instantiated database cursor
:return: tuple of labels and training data
"""
training_data, labels = [], []
cols = [desc[0] for desc in cursor.description]
for record in tq... | 12,143 |
def parse(input_str, file_path=True):
"""
Parse a GLM into an omf.feeder tree. This is so we can walk the tree,
change things in bulk, etc.
Input can be a file path or GLM string.
"""
tokens = _tokenize_glm(input_str, file_path)
return _parse_token_list(tokens) | 12,144 |
def pred(model, x_pred_scaled, scaler_y):
"""
Predict
:param model: model for prediction
:param x_pred_scaled: scaled x values we need to predict for
:param scaler_y: scaler for y values
:return:
"""
MAX_PREDICT_SIZE = 10000
g_mean_full = g_std_full = None
start = 0
while s... | 12,145 |
def metadataAbstractElementEmptyValuesTest3():
"""
Empty value for unknown attribute.
>>> doctestMetadataAbstractElementFunction(
... testMetadataAbstractElementEmptyValue,
... metadataAbstractElementEmptyValuesTest3(),
... requiredAttributes=["required1"],
... optionalAttri... | 12,146 |
def orthonormal_initializer(input_size, output_size):
"""from https://github.com/patverga/bran/blob/32378da8ac339393d9faa2ff2d50ccb3b379e9a2/src/tf_utils.py#L154"""
I = np.eye(output_size)
lr = .1
eps = .05/(output_size + input_size)
success = False
tries = 0
while not success and tries < 10... | 12,147 |
def stick_figure (ax, type, num, start, end, prev_end, scale, linewidth, opts):
""" General function for drawing stick based parts (e.g., ribozyme and protease sites).
"""
# Default options
color = (0,0,0)
start_pad = 2.0
end_pad = 2.0
x_extent = 5.0
y_extent = 10.0
linestyle = '-'
linetype = ""... | 12,148 |
def display_datetime(datetime_str, time_zone=None, verbose=True):
"""Returns a formatted datetime with TZ (if provided) or 'Error (Missing)"""
"""
>>> print(datetime.datetime.utcnow().strftime("%Y/%m/%d %a %I:%M %p"))
2019/05/19 Sun 01:10 AM
"""
if datetime_str: # and type(datetime_str) =... | 12,149 |
def test1():
"""The test runs a loop to check the consistency of the random init file
generating process and the following simulation.
"""
for _ in range(1000):
random_init()
simulate("test.boupy.yml") | 12,150 |
def mask_channels(mask_type, in_channels, out_channels, data_channels=3):
"""
Creates an autoregressive channel mask.
Input:
mask_type: str
Either 'A' or 'B'. 'A' for first layer of network, 'B' for all others.
in_channels: int
Number of input channels to layer.
... | 12,151 |
def patchCombinedLogFormatter() -> None:
"""
Patch the twisted.web.http.combinedLogFormatter to include USER.
"""
twisted.web.http.combinedLogFormatter = combinedLogFormatter | 12,152 |
def dedent(text):
"""
Remove all common indentation from every line but the 0th.
This will avoid getting <code> blocks when rendering text via markdown.
Ignoring the 0th line will also allow the 0th line not to be aligned.
Args:
text: A string of text to dedent.
Returns:
String dedented by above r... | 12,153 |
def MockConnRecord(conn_record):
"""Mock ConnRecord fixture."""
with mock.patch("didcomm_resolver.resolver.ConnRecord") as patched:
patched.retrieve_by_id = mock.CoroutineMock(return_value=conn_record)
yield patched | 12,154 |
def open_text_file_for_write(output_directory:str, file_name:str, verbose=False) -> TextIOWrapper:
"""Open a text file for writing"""
if verbose:
print(f"opening text file for write: {output_directory}/{file_name}", file=stderr)
return open(f"{output_directory}/{file_name}", 'w', encoding='utf-8') | 12,155 |
def dpsplit(n,k, sig):
""" Perform the dynamic programming optimal segmentation, using the sig function
to determine the cost of a segment sig(i,j) is the cost of the i,j segment. These
are then added together
"""
# Set up the tracking tables
K = k + 1
N = n
segtable = np.zeros((n,K)) ... | 12,156 |
def get_wind_tiles() -> List[Tile]:
"""return a list of four wind tiles
"""
return [Tile(Suit.JIHAI.value, Jihai.TON.value),
Tile(Suit.JIHAI.value, Jihai.NAN.value),
Tile(Suit.JIHAI.value, Jihai.SHAA.value),
Tile(Suit.JIHAI.value, Jihai.PEI.value)] | 12,157 |
def test_custom_envvars(caplog):
"""Test using environment variables for configuration. """
root = Path(__file__).with_suffix('') / 'gh_pages_envvars'
env = {
'DOCTR_VERSIONS_MENU_LATEST': 'master',
'DOCTR_VERSIONS_MENU_DEBUG': "true",
'DOCTR_VERSIONS_MENU_VERSIONS': "<branches>, <re... | 12,158 |
def train_mnist_classifier(lr=0.001, epochs=50, model_dir='.'):
"""train mnist classifier for inception score"""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device {0!s}".format(device))
train_loader = load_mnist(batchSize=100, train=True)
test_loader = load_m... | 12,159 |
def datetime_now_filename_string():
"""create a string representation for now() for use as part of the MHL filename"""
return datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d_%H%M%S") | 12,160 |
def test_remote_backup(host):
"""Check if the remote backup runs successfully"""
cmd = host.run("/usr/local/bin/remote-backup.sh")
assert cmd.succeeded | 12,161 |
def generate_simulation_dataset(path, runs, **kawrgs):
"""Generate and save a simulation dataset.
Parameters
----------
path : str
Root path where simulation data will be stored.
runs : int, array
If int then number of runs to use. If array then
array must be of one dim more... | 12,162 |
def num_sites(sequence, rule, **kwargs):
"""Count the number of sites where `sequence` can be cleaved using
the given `rule` (e.g. number of miscleavages for a peptide).
Parameters
----------
sequence : str
The sequence of a polypeptide.
rule : str or compiled regex
A regular ex... | 12,163 |
def get_packages(code: str) -> defaultdict:
"""Extracts the packages that were included in the file being inspected.
Source for this code: https://stackoverflow.com/questions/2572582/
Example:
input:
'from collections import Counter\n
import kivy\n
from stats import median as stats_median... | 12,164 |
def beam_name():
"""Session level fixture for beam path."""
return str(beam_path) | 12,165 |
def get_mv_sandwich(a_blade_indices, b_blade_indices, signature, prod="gp"):
"""a b ~a"""
out_indices = []
out_blade_indices = []
out_signs = []
out_indices = []
indices_a = []
indices_b = []
indices_a_r = []
blade_to_index = {}
for (i_a, index_a), (i_b, index_b), (... | 12,166 |
def clear():
"""Clear the buffer."""
global _pixel_map
_pixel_map = deepcopy(_empty_map) | 12,167 |
def ldns_dnssec_create_nsec3(*args):
"""LDNS buffer."""
return _ldns.ldns_dnssec_create_nsec3(*args) | 12,168 |
def S_difference_values(_data_lista, _data_listb):
"""
Returns new data samples where values are transformed by transformer values.
"""
d_data = []
dsa = len(_data_lista)
dsb = len(_data_listb)
if dsa != dsb:
return []
for i in range(dsa):
d_data.append(_data_lista[i] ... | 12,169 |
def parseFixedZone(s):
"""Convert a +hhmm or -hhmm zone suffix.
[ s is a string ->
if s is a time zone suffix of the form "+hhmm" or "-hhmm" ->
return that zone information as an instance of a class
that inherits from datetime.tzinfo
else -> raise SyntaxError ]
... | 12,170 |
def tica_eigenvalues_plot(tica, num=12, plot_file=None):
"""
Plots the highest eigenvalues over the number of the time-lagged independent components.
Parameters
----------
tica : TICA obj
Time-lagged independent components information.
num : int, default = 12
... | 12,171 |
def latex2svg(code, params=default_params, working_directory=None):
"""Convert LaTeX to SVG using dvisvgm and scour (or svgo).
Parameters
----------
code : str
LaTeX code to render.
params : dict
Conversion parameters.
working_directory : str or None
Working directory fo... | 12,172 |
def _split_train_test(features, labels, train_set, random_seed):
"""Split the dataset into training and test sets.
Parameters
----------
features : pandas.DataFrame
Features of the dataset events.
labels : pandas.DataFrame
Labels of the dataset events.
train_set : {float, list-l... | 12,173 |
def parse_config(requesting_file_path, is_plugin=True):
"""
Parse the config files for a given sideboard plugin, or sideboard itself.
It's expected that this function is called from one of the files in the
top-level of your module (typically the __init__.py file)
Args:
requesting_file_path... | 12,174 |
def generate_enc_keypair():
"""
Generate Curve25519 keypair
:returns tuple: A byte pair containing the encryption key and decryption
key.
"""
private_key = PrivateKey.generate()
return private_key.public_key.encode(), private_key.encode() | 12,175 |
def filter_molecular_components(
components: List[Component],
) -> Tuple[List[Component], List[Component]]:
"""Separate list of components into molecular and non-molecular components.
Args:
components: A list of structure components, generated using
:obj:`pymatgen.analysis.dimensionalit... | 12,176 |
async def test_client_proto_packet_received_log(caplog: Any) -> None:
"""
Ensure we properly process received packets
"""
proto = tpt.SNMPClientProtocol(b"SNMP-packet")
with caplog.at_level(logging.DEBUG):
proto.datagram_received(b"fake-packet", ("192.0.2.1", 42))
assert "66 61 6b" in ca... | 12,177 |
def enter_card_details(driver, ccn, exp, cvc):
"""set credit card number, valid till. cvc"""
driver.find_element_by_xpath("//input[@placeholder='Card number']").send_keys(ccn)
driver.find_element_by_xpath("//input[@placeholder='MM / YY']").send_keys(exp)
driver.find_element_by_xpath("//input[@placeh... | 12,178 |
def argument(name, type):
"""
Set the type of a command argument at runtime. This is useful for more
specific types such as mitmproxy.types.Choice, which we cannot annotate
directly as mypy does not like that.
"""
def decorator(f: types.FunctionType) -> types.FunctionType:
a... | 12,179 |
def add_menu_item(method, label, **kwargs):
# type: (callable, Union[str, int], Any) -> None
"""wrapper for xbmcplugin.addDirectoryItem"""
args = kwargs.get("args", {})
label = ku.localize(label) if isinstance(label, int) else label
list_item = ListItem(label)
list_item.setArt(kwargs.get("art"))... | 12,180 |
def init_logging(human_log_level: str = "info") -> None:
"""Init the `logging.Logger`.
It should be called only once in the app (e.g. in `main`). It sets
the log_level to one of `HUMAN_LOG_LEVELS`. And sets up a handler
for stderr. The logging level is propagated to all subprocesses.
"""
_new_l... | 12,181 |
async def async_google_actions_request_sync(cloud):
"""Request a Google Actions sync request."""
return await cloud.websession.post(
f"{cloud.google_actions_report_state_url}/request_sync",
headers={AUTHORIZATION: f"Bearer {cloud.id_token}"},
) | 12,182 |
def convert_time_string_to_secs(string: str) -> int:
"""
Takes a string in the format '1h30m25s' and converts it to an integer
in seconds. This functions uses the regular expression RE_CONVERT_TIME
above for matching the string.
"""
match = regexp_time.match(string)
if not match:
rai... | 12,183 |
def polar_cube(c, index, n=512, interp='cubic'):
"""VIMS cube polar projected.
Parameters
----------
c: pyvims.VIMS
Cube to interpolate.
index: int, float, str, list, tuple
VIMS band or wavelength to plot.
n: int, optional
Number of pixel for the grid interpolation.
... | 12,184 |
def _load_surf_files_gifti_gzip(surf_file):
"""Load surface data Gifti files which are gzipped. This
function is used by load_surf_mesh and load_surf_data for
extracting gzipped files.
Part of the code can be removed while bumping nibabel 2.0.2
"""
with gzip.open(surf_file) as f:
as_by... | 12,185 |
def WriteTo(linelist, outfile):
"""writes the matches to a CSV file with name outfile"""
file = open(str(outfile),'w')
i=0
for line in linelist:
file.write(linelist[i].borough+ ',')
file.write(linelist[i].block+ ',')
file.write(linelist[i].lot+ ',')
file.write(li... | 12,186 |
def get_platform_system():
"""return platform.system
platform module has many regexp, so importing it is slow...
import only if required
"""
import platform
return platform.system() | 12,187 |
def populate_sql(
sql: sqlparse.sql.Statement, example: NLToSQLExample, anonymize_values: bool
) -> bool:
"""
Creates a sequence of output / decoder actions from a raw SQL query.
Args:
sql: The SQL query to convert.
example: The NLToSQLExample object to add output actions.
anony... | 12,188 |
def factorial(n):
"""Stop sympy blindly calculating factorials no matter how large.
If 'n' is a number of some description, ensure that it is smaller than
a cutoff, otherwise sympy will simply evaluate it, no matter how long that
may take to complete!
- 'n' should be a sympy object, tha... | 12,189 |
def getSupplier(num):
"""" get the supplier for a card number
Attributes:
@num: card number
"""
supplier = str()
for key, value in suppliers.items():
if bool(re.match(value, num)):
supplier = key
break
if supplier == "":
supplier = "Ukwno... | 12,190 |
def load_torch_hub_model(repo: str, model: str, *args, **kwargs):
"""Tries to load a torch hub model and handles different exceptions that could be raised.
Args:
repo: The GitHub repository containing the models.
model: The model name to download.
max_retries: The maximum number of trie... | 12,191 |
def report_unmerged(unmerged):
"""
Stores a list of deletable unmerged files in the orphan table
:param list unmerged: A list of tuples,
where each tuple is a name, info dict pair
"""
_report_files('unmerged', unmerged) | 12,192 |
def compute_medoid(data):
"""
Get medoid of data
Parameters
----------
data: ndarray
Data points
Returns
------
medoid: ndarray
Medoid
"""
dist_mat = pairwise_distances(data)
return data[np.argmin(dist_mat.sum(axis=0))] | 12,193 |
def int_sphere(fx, xgrid):
"""
Computes integrals over the sphere defined by the logarithmic
grid provided as input
Parameters
----------
fx : array_like
The function (array) to be integrated
xgrid : ndarray
The logarithmic radial grid
Returns
-------
I_sph : fl... | 12,194 |
def run(
func,
args=[],
kwargs={},
service="lambda",
capture_response=False,
remote_aws_lambda_function_name=None,
remote_aws_region=None,
**task_kwargs
):
"""
Instead of decorating a function with @task, you can just run it directly.
If you were going to do func(*args, **kwa... | 12,195 |
def run_webserver(destination_root_dir):
""" Run a local """
destination_root_dir = destination_root_dir
if destination_root_dir.startswith('/'):
destination_root_dir = destination_root_dir[1:]
if destination_root_dir.endswith('/'):
destination_root_dir = destination_root_dir[:-1]
... | 12,196 |
def sym_to_elm(symbols: Union[str, List, np.ndarray],
order: Union[np.ndarray, List[str]]):
"""Transform symbols to elements."""
if not isinstance(order, list):
order = order.tolist()
if not isinstance(symbols, (str, list)):
symbols = symbols.tolist()
if isinstance(symbols... | 12,197 |
def set_custom_field(
custom_field_id: str = None,
person_id: str = None,
owner_id: str = None,
term_id: str = None,
value: str = None,
option_index: str = None):
"""
Sets a custom field value for a particular person, organization, or donation.
:param custom_... | 12,198 |
def ixn_is_increases_activity(ixn: ChemGeneIxn):
"""Checks if the interaction results in the decrease of the activity of the protein of the gene
:param pyctd.manager.models.ChemGeneIxn ixn: A chemical-gene interaction
:rtype: bool
"""
return _ixn_is_changes_protein(ixn, 'increases^activity') | 12,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.