content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def read_magnum_cluster_template(client, cluster):
"""Get the actual template associated with the one specified in the given Magnum
cluster resource.
Args:
client (MagnumV1Client): the Magnum client to use to connect to the Magnum
service.
cluster (krake.data.openstack.MagnumClu... | 6c61c927cee7d5448d4156fa0c2c2f1e02007a1c | 637,998 |
def read_data_from(file_: str) -> list:
"""Read math homework from file."""
return open(file_, "r").read().splitlines() | e0168c78cb7046a035ce90eee209f5976ca2bff1 | 637,999 |
from typing import List
def risk_level(cave: List[List[int]], tx: int, ty: int) -> int:
"""
Computes risk level for the smallest rectangle which contains both the
mouth of the cave and the target.
"""
risk_level = 0
for y in range(ty + 1):
for x in range(tx + 1):
risk_level... | 8e5b4da00f0e3a354e0972c267623043a2136d55 | 638,000 |
def gen_property_of_type(name, _type, doc=""):
""" Generates a type-forced property associated with a name. Provides type
checking on the setter (coherence between value to be set and the type
specified).
@param name: property name
@param _type: force type
@param doc: documentation for the prop... | e90d83379d01013674d5f21f9ab3cfc036ab080a | 638,001 |
def expected_file(expected_files):
"""Get existing remote file name."""
return expected_files[0] | cba59870ba8f0ef7e8221fd98d94a4283edead5e | 638,002 |
def replace_quotes(match):
"""Replace match with « xxxxxxx »."""
length = len(match.group(0)) - 4
return "« " + length * "x" + " »" | 5c872515db0a0e76d913ff80338bc35bf49ec920 | 638,003 |
import secrets
def branch() -> str:
"""Return a branch name that is unique for every test case."""
random = secrets.token_hex(nbytes=3)
return f"branch-{random}" | 71c1bf62074737cfc41a2caca202f2e9b5dc69c4 | 638,004 |
import re
import argparse
def validate_hd(input):
"""
checks that the input
/dev/name:SIZE[:type[:value]] is correct./
"""
a = re.compile("^[/a-zA-Z1-9]+:[0-9]+(:[a-zA-Z0-9]+(:[a-zA-Z0-9]+)?)?$", re.IGNORECASE)
match = a.match(input)
if not match:
msg = "'%s' hard-disk is i... | d8c6e09140c199009e16bca58da7d98427078703 | 638,005 |
def legendre_polynomial(x: float, n: int) -> float:
"""Evaluate n-order Legendre polynomial.
Args:
x: Abscissa to evaluate.
n: Polynomial order.
Returns:
Value of polynomial.
"""
if n == 0:
return 1
elif n == 1:
return x
else:
polynomials = [... | 9c1890f54ae0a91b8d4cd8771f7a944fd3f7e7ab | 638,006 |
from typing import List
def jaccard_similarity(correct_duplicates: List, retrieved_duplicates: List) -> float:
"""
Get jaccard similarity for a single query given correct and retrieved file names.
Args:
correct_duplicates: List of correct duplicates i.e., ground truth)
retrieved_duplicate... | 1a1d9adf32b43624b29336f8dc8fef025004a659 | 638,008 |
import os
def deck_menu_constructor(paths):
"""
Takes a list of file paths and returns a three part tuple with a label number,
the truncated filename, and the file path.
:param list paths: a list of file file paths, must be json files containing dictionaries
:return: a list of three part tuples (numb... | 14e306c54abfc09f41db2ee10a80ca4444dc64ff | 638,009 |
def make_cygpath_function(mounts):
"""Creates a make function that can be used in place of cygpath.
Args:
mounts: A list of tuples decribing filesystem mounts.
Returns:
The body of a function implementing cygpath in make as a string.
"""
# We're building a bunch of nested patsubst ... | 68990df9a1fb9df78c13a4456c3882896cc70acc | 638,010 |
def get_item_type(code):
"""Get item type from code."""
item_type = {0: "Zabbix agent",
1: "SNMPv1 agent",
2: "Zabbix trapper",
3: "simple check",
4: "SNMPv2 agent",
5: "Zabbix internal",
6: "SNMPv3 agent",
... | a4f425bfc29a0512d29d7d3e4b024410c1a481fb | 638,011 |
def getReplacementMap():
"""
Returns a dict, mapping which packages need to be mapped to which
replacement package, e.g.:
{ 'Libraries/Foo/1.0': 'Libraries/Bar/2.0',
'Libraries/Foo/1.1': 'Libraries/Bar/2.0' }
"""
replacementMap = {}
# replacementMap.update( ... | 01f1353a9b0231191bc745bb81ff0256f4f06dd9 | 638,012 |
def sensorsDifferenceSum(sensor_1, sensor_2):
"""
given two lists contains the reading of two sensors for the same place, give the total difference between
there elements
"""
if len(sensor_1) == 0 or len(sensor_2) == 0:
return 0
return abs(sensor_1[0] - sensor_2[0]) + sensorsDifferenceSu... | 9ad0da3182528760edb22cf694c94b2d25e66c06 | 638,013 |
def update_radius(intersection, new_rad):
"""
Updates the radius of the intersection
:param intersection: intersection
:param new_rad: new radius value
:type intersection: Intersection
:type new_rad: float
:return: updated intersection
"""
return intersection.update_radius(new_rad) | 6490f42e2853865e3825d6f89bb10b0deaa7d9f6 | 638,014 |
from typing import List
def message_empty(sysex_data: List[int]) -> bool:
"""Return whether the sysex data is an empty message packet."""
return len(sysex_data) == 2 | f17043a8ac49656253837f90d1e78501dbd9ce05 | 638,015 |
def get_uniprotentries_of_user_entity_ids(cursor, unification_table, user_entity_ids):
"""
Get Uniprot Entries of targets using their BIANA user entity ids
"""
query_uniprotentry = ("""SELECT UA.value, UA.type
FROM externalEntityUniprotEntry UA, {} U
... | 01202fd172c6e6061d6c82ecf2928eeb0a18b852 | 638,016 |
import torch
def construct_optimizer(model,cfg):
"""
construct optimizer in
stochastic gradient descent or ADAM
set w in decay
:return:
"""
# weight_p, bias_p = [], []
# for name, p in model.named_parameters():
# if 'bias' in name:
# bias_p += [p]
# else:
... | 22510da10f76624ab911f54cdbdc6d94249e1fa5 | 638,017 |
def mask_string(raw_str, right_padding=4) -> str:
"""Mask a string with a default value of 4."""
return raw_str[-right_padding:].rjust(len(raw_str), '*') | 1a8d130c723f893e2bbaa3392841ce80dd659d30 | 638,018 |
import os
import json
def parse_json(args):
"""add or modify bam files to json"""
json_in = os.path.join(args.jbrowse_dir, 'data', args.name, 'trackList.json')
json_out = json.load(open(json_in, 'r'))
return json_out | 5ccb774642df2be4009c1b72ecca263bc69386c4 | 638,019 |
def _field_set_recursively(resource, field_name, value):
"""Set a field for a given resource and all of its children.
Args:
resource (ResourceData): the resource to change.
field_name (str): the field to set.
value (str): the value of the field to set to.
Returns:
list. all... | eb8e489fe47a6cf99d673cbd3f7f7d65260098d6 | 638,020 |
def to_list(x):
"""
Return x if it is already a list, or return a list containing x if x is a scalar.
"""
if isinstance(x, (list, tuple)):
return x # Already a list, so just return it.
return [x] | 4b1d303dfba85adec9bdee9b3cba6c93b7937543 | 638,021 |
def scan_for_change(oldBoard: tuple, gameBoard: tuple) -> bool:
""" Look for changes in life """
for rows in zip(oldBoard, gameBoard):
for values in zip(rows[0], rows[1]):
if values[0] != values[1]:
return True
return False | 5e2f4a1891033ce19db04a9995abbe0e87cf64b4 | 638,022 |
def search_for_ISM(edge_IDs, transcript_dict):
""" Given a list of edges in a query transcript, determine whether it is an
incomplete splice match (ISM) of any transcript in the dict. Will also
return FSM matches if they're there"""
edges = frozenset(edge_IDs)
ISM_matches = ... | 87b40a7e97fd39a8833cbae33eaa392fb666ffec | 638,023 |
def normalize(list):
"""
this is assuming that there is a min with 0
:param list:
:return:
"""
# find max
a_max = max(list)
# set errors to max
list_error_free = [x if x >= 0 else a_max for x in list]
# normalize
result = []
for entry in list_error_free:
result.ap... | 04d3377afe61351360a50233682e65495a633265 | 638,024 |
def format_timeout(timeout):
"""Render server alive interval option."""
format_str = '-o ServerAliveInterval={}'.format
return format_str(timeout) if timeout else '' | 750c923cd08bad5d4e71d5c5d9a610f44f81213f | 638,025 |
def transposed(matrix):
"""Returns the transpose of the given matrix."""
return [list(r) for r in zip(*matrix)] | 30835a1583f365b558c39e8fd1b459e79e85448e | 638,027 |
def word_len(word):
"""Returns the length of word not counting spaces
>>> word_len("a la carte")
8
>>> word_len("hello")
5
>>> word_len('')
0
>>> word_len("coup d'etat")
10
"""
num = len(word)
for i in range(len(word)):
if word[i] == " ":
num = num-1
... | c51a98e173b92a4efcd18d640de00d8015036c73 | 638,028 |
def from_iban(alist:list) -> dict:
""" Returns the following dictionary -->
"""
ba_dict = {
"by-nib-ref": {},
"by-agent": {},
}
for item in alist:
agent, name, nib_ref = item["agent"], item["name"], item["nib-ref"]
assert agent not in ba_dict["by-agent"], f"Duplicate ... | 94aab47b8f2c12ff3723adf5cbf4dce8e41aaf7b | 638,029 |
def td_to_str(td_obj):
"""
Convert a timedelta object to allow a "string" usage. In reality, it return a `dict`.
:param td_obj:
:return: {years: x, months: x, days: x, hours: x, minutes: x, seconds: x}
"""
td_obj = int(td_obj.total_seconds())
# 1 year = 31,540,000s
# 1 month = 2,628,000... | fa22c213760f787a80c01b3608c4a6cff1fc6e7d | 638,030 |
def pick_n_equispaced(l, n):
"""Picks out n points out of list, at roughly equal intervals."""
assert len(l) >= n
r = (len(l) - n)/float(n)
result = []
pos = r
while pos < len(l):
result.append(l[int(pos)])
pos += 1+r
return result | 2866786a994817d529e8a255d06614bd92f3e839 | 638,031 |
def test_Qs(function, all_function, max_profundity, num_atomics, arity, verbose=False):
"""
Tests the Q functions with the all_functions
:param function: the numeric function to test
:param all_function: the generator function of all formulae to test it with
:param max_profundity: ze... | e15dc4822c12a3ac1df72877727256e156254d3e | 638,032 |
async def get_chains(self, symbol, info='expiration_dates'):
"""Returns the chain information of an option.
:param symbol: The ticker of the stock.
:type symbol: str
:param info: Will data_filter the results to get a specific value.
:type info: Optional[str]
:returns: Returns a dictionary of ke... | 2756d4c9f36d81968305c15c77cb613f68440dd8 | 638,033 |
def syncgateway_admin_url():
"""
Returns:
str: URL to reach admin port of SG.
"""
return "http://localhost:4985/" | c3256f21aed9af5a615050a2aceec0bbb37c20bf | 638,034 |
def message_warning(msg, *a, **kwargs):
"""Ignore everything except the message."""
return str(msg) + '\n' | a39440007b6e07c4810e73a9c16edd06316962e4 | 638,035 |
def save_as_vec(dset, nrow, data):
"""Save 'data' columns as chunks in 1d arrays."""
# Iterate over columns
for name, d in zip(list(dset.keys()), data.T):
# Resize the datasets to accommodate next chunk of rows
dset[name].resize(nrow + data.shape[0], axis=0)
# Write next chunk
... | 3ad1f04a2354d77ca32a76c715dcf37786b5ede8 | 638,036 |
def R_update(state, reward, critic, lr):
"""Really simple TD learning"""
update = lr * (reward - critic(state))
critic.update(state, update)
return critic | ce60ba8e7c98840499bfa960f5b7f8972c181820 | 638,038 |
def regrid_get_operator_method(operator, method):
"""Return the regridding method of a regridding operator.
:Parameters:
operator: `RegridOperator`
The regridding operator.
method: `str` or `None`
A regridding method. If `None` then ignored. If a `str`
then... | 59b728fc74d89cf3daee34dff668d62a6d1fe5b0 | 638,039 |
def is_affiliation(item: str) -> bool:
"""Return true if a string contains an affiliation."""
return item.startswith('(') | 64823607277c632c8b2f08c1865ebade42ec6832 | 638,040 |
import numpy as np
def mercator_transform(data, lat_bounds, origin='upper', height_out=None):
"""
Transforms an image computed in (longitude,latitude) coordinates into
the a Mercator projection image.
Parameters
----------
data: numpy array or equivalent list-like object.
Must be NxM... | ed5c1913871832c63c271a989b9c63a7988d492a | 638,042 |
def faker_seed():
"""Default `faker` seed."""
return 12345 | 6c7fbec7718d212b814254b3027e8c3d7d47ab50 | 638,043 |
def RelationshipLengthProperty(relationship_name):
"""Return a property representing number of objects in relationship."""
def getter(self):
relationship = getattr(self._object, relationship_name)
try:
return relationship.countObjects()
except Exception:
return le... | 8550a6374d5d7bc405352bbee11bb3b40684711c | 638,044 |
def consistent_det(A, E):
"""Checks if the attributes(A) is consistent with the examples(E)"""
H = {}
for e in E:
attr_values = tuple(e[attr] for attr in A)
if attr_values in H and H[attr_values] != e['GOAL']:
return False
H[attr_values] = e['GOAL']
return True | 33ef32091c5cb1230d4b749b465cd007e32fafe3 | 638,045 |
def pad_to(x, k=8):
"""Pad int value up to divisor of k.
Examples:
>>> pad_to(31, 8)
32
"""
return x + (x % k > 0) * (k - x % k) | d31bc75de96f941ef77afd5e8e909c4174709b77 | 638,047 |
import types
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.FunctionT... | 9c80425bf08336d064a44564b7b16aecfe06f109 | 638,048 |
from typing import List
import bisect
def get_bin(pred_prob: float, bins: List[float]) -> int:
"""Get the index of the bin that pred_prob belongs in."""
assert 0.0 <= pred_prob <= 1.0
assert bins[-1] == 1.0
return bisect.bisect_left(bins, pred_prob) | 9924212bd9d6ae364d1c432cfd5a7927a4645719 | 638,049 |
import sympy
def det(x):
"""
Symbolic determinant
:param m: matrix
:type x: ndarray with symbolic elements
:return: determinant
:rtype: ndarray with symbolic elements
.. runblock:: pycon
>>> from spatialmath.base.symbolic import *
>>> from spatialmath.base import rot2
... | dab990c333eeb2adff1ee8f1389df5e88d87ddf5 | 638,050 |
def transpose2(lists, defval=0):
""" Transpose a list of list. defval is used instead of None for uneven lengthed lists. """
if not lists: return []
return map(lambda *row: [elem or defval for elem in row], *lists) | 8d75ed2fc88cb33ce30b692c1bd22a873d6da7b2 | 638,051 |
def unslug(_input):
"""Convert slugs back into normal strings"""
return _input.replace('-', ' ').replace('_', ' ') | 675b6ac50e8f09d54617429886c69e070b36054c | 638,052 |
def pages_to_edges(wiki_linked_pages):
"""
Create edges linking to (inbound) and from (outbound) a page
"""
page = wiki_linked_pages["title"]
in_edges = [(in_page, page) for in_page in wiki_linked_pages["inbound_pages"]]
out_edges = [(page, out_page) for out_page in wiki_linked_pages["outbound_p... | 2380e2a7179df0640d418727dfee04786a2c2989 | 638,054 |
def create_summary_document_for_es(data):
"""
This function will create document structure appropriate for es
:param data: data to parse
:return: part of document to be inserted into es
"""
results = list()
for k, v in data.items():
results.append({
"name": k,
... | 5708c1c5d72717101e2c8ad72afaabe9f138a01b | 638,055 |
from datetime import datetime
def valid_date(date):
"""
Checks if DATE is of form MM/DD/YYYY. Does not check if YYYY is correct.
Also, does not check for edge cases, i.e. Feb 30.
"""
mdy = date.split("/")
if (len(mdy) == 3):
try:
m = int(mdy[0])
d = int(mdy[1])
... | c17954c86bb1208b606e331659cbe4ed888a1d09 | 638,057 |
import re
def format_indeed_post_date(post_date):
"""
Format a Posted date to a numeric string of the recorded days
Arguments : posted date string
Return : Numeric string
"""
if ("Publiée à l'instant" in post_date) or ("Aujourd'hui" in post_date):
return str(0)
else:
temp... | e13474dff9474a69e8e823d270a262f1c2bed597 | 638,058 |
import requests
import json
def post(base_url, action_url, params):
"""
发送post请求
:param base_url:
:param action_url:
:param params:
:return:
"""
full_url = base_url + action_url
# 请求头
headers = {
"Content-type": "application/json",
'Upgrade': 'HTTP/1.1'
}
... | 7367abf7470dca93944458865ee23e49ee413e45 | 638,059 |
def get_emoji_code(raw_emoji: str):
"""
:param raw_emoji: The raw str emoji
:return: ascii code of emoji
"""
return ord(str(raw_emoji)) | 77e1be11ca6015b1a47f947e614f02be4dec19a9 | 638,060 |
def valence_band_offset(mat, ref_mat):
"""
Calculate the valence band offset $E_v - E_{v,ref}$ between two semiconductor materials.
:param Material mat:
Material whose conduction band position is to be determined.
:param Material ref_mat:
Material whose conduction band minimum is used a... | b8215c6a97e3a40c7c8eb7b3411c33fda777ad6d | 638,061 |
def sequence_sum(begin_number, end_number, step):
"""
Goes through a loop and finds the sum of the sequence specified by three integer inputs.
:param begin_number: the starting integer value.
:param end_number: the ending integer value.
:param step: integer of how many numbers to increase each step.... | 03c9b86a823b59558105c6d4d769e4c6b18c2c28 | 638,062 |
def decompose_column_name(col_name):
"""Returns separate parts of a hobo column name
Argument:
- col_name (str): the column name
Returns:
- tuple: (variable_name, unit_name, serial_text)
"""
x=col_name.split('(')
try:
serial_text=x[1].split(')... | 2084d02d9ec3e5a2fe4bf7cc153bacd763d308fe | 638,063 |
def _get_key(dict_like, key):
"""
Examples
--------
>>> a = dict(b=1)
>>> _get_key(a, 'b')
1
>>> _get_key(a, 'c') == ""
True
"""
try:
return dict_like[key]
except KeyError:
return "" | 036e7d5b9767af333937a2cd5afef792136bfe16 | 638,064 |
import zlib
def adler(filepath,BLOCKSIZE=2**20):
"""
Create an additive adler32 checksum. Faster than sha1.
From the documentation:
> Changed in version 3.0: Always returns an unsigned value.
> To generate the same numeric value across all Python versions and
> platforms, use adler32(data)... | 9591175339f17af8a414fc6948890dbfd36a4374 | 638,065 |
import csv
def into_list2(fIn,**kwargs):
"""
Read data from file into a 2D list.
Lines with '#' are not read.
Parameters
----------
fIn : str
Path to input file
delimeter : str (optional)
Delimeter for parsing lines in file. (default is ',')
type : str (optional)
... | 788d93e448670dc86fba92653a26d6ba36f1641f | 638,066 |
def count_hits(bh, vc, verbose=False):
"""
Count the vc hits per genome
"""
hc = {}
for g in bh:
hc[g] = {}
for b in bh[g]:
hc[g][vc[b]] = hc[g].get(vc[b], 0) + 1
besthit = None
bhc = 0
for h in hc[g]:
if hc[g][h] > bhc:
... | a1329fb3fef13f4bc0a7dd3adad350cd6834d232 | 638,067 |
def fragment(size, lstlike):
"""Faster alternative to grouper for lists/strings."""
return (lstlike[i : i + size] for i in range(0, len(lstlike), size)) | 788460d689a7c9e3747fdaa0276bedeb0fe2e727 | 638,068 |
import subprocess
def run_command(arguments):
"""
Args:
arguments(list of str): Arguments to be executed as a command.
Arguments are passed as if calling subprocess.call() directly
"""
return subprocess.call(arguments) | 02cf631c46c7f084bd3a810c21c7e1ccb68c0f0e | 638,069 |
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print(word)
# Poop out
result = None
return result | 28f48ddc8a59cb115a1d42d2bf781e5a2fddc795 | 638,070 |
import argparse
def WrapMessageInNargs(msg, nargs):
"""Create the display help string for a positional arg.
Args:
msg: [str] The possibly repeated text.
nargs: The repetition operator.
Returns:
str, The string representation for printing.
"""
if nargs == '+':
return '{msg} [{msg} ...]'.for... | 41abff64c1986d55754ec061386ea50b40ef4348 | 638,072 |
def w(q2: float, m_parent: float, m_daughter: float) -> float:
"""
Calculates the recoil variable w, which runs from 1 (zero recoil) to the maximum value (depends on daughter).
:param q2: Momentum transfer to the lepton-neutrino system.
:param m_parent: Mass of the parent meson, e.g. the B meson.
:p... | c7b20722df49224db567681667664e687f506743 | 638,073 |
def is_valid_project_type(type):
""" Validates supported project types; currently only maven is supported; hopefully gradle in the future """
if not type:
return False
if "maven" != type:
return False
return True | b450423c06d778701c639c3175b87b271ddfb5d9 | 638,075 |
def map_file():
"""
<enumeratedValueSet variable="map-file"> <value value=""blank.map""/> </enumeratedValueSet>
map file names:
"a.map" ,"b.map" ,"c.map" ,"obstacles.map" ,"blank.map"
"""
cur_map = "chokepoint_1_a.map"
return f'<enumeratedValueSet variable="map-file"> <value value... | b317f6504a25dcd6f15c7af3f2b14a75c4c69d9c | 638,076 |
from typing import Optional
import sys
def query_choice(choices: list[str], question: Optional[str] = None) -> str:
"""Ask the user to pick an option."""
if question is None:
question = "Please pick one of the following:"
options: dict[int, str] = dict(enumerate(choices))
while True:
... | 70ba7f86715cb18f437066dc3304fd9ccc9900c5 | 638,078 |
def train_test_split(tokenized):
"""Returns a train, test tuple of dataframes"""
train = tokenized.query("category != 'title'")
test = tokenized.query("category == 'title'")
return train, test | 749d4c57087422fb2b610bf74ba2909229ef4e12 | 638,079 |
def scrapeSymbol(soup):
""" Scrapes ICO symbol from ICODrops listing """
li = soup.findAll("li")
for idx, yeah in enumerate(li):
span = yeah.find("span", attrs = { "class" : "grey" })
if span and "Ticker:" in span.text:
# Return only first match
return li[idx] \
.text \
.repl... | 9ea86b4396fe6317301241b78ee4ca1f4629cd27 | 638,080 |
import torch
def logits_to_label(logits):
"""
Converts predicted logits from extended binary format
to integer class labels
Parameters
----------
logits : torch.tensor, shape(n_examples, n_labels-1)
Torch tensor consisting of probabilities returned by ORCA model.
Examples
---... | 5e8f06c6562ea70c73629b97fc3798484e9d4a3c | 638,081 |
def heapSort_v2(arr):
"""
工作原理:最大堆,最小堆
编码要素:下沉down,上浮up;demotion,promotion
"""
def down_iter(arr, i, n, comp):
"""堆化(迭代):堆的向下调整算法"""
current = i
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
while True:
if l < n and comp(arr[l],... | 7a92e340627a2bd2cd4b59ce0aaf14ffe6597cd4 | 638,082 |
import random
def get_random_delay(min_time=0.01, max_time=0.1):
"""
Random sleep time between min and max time. Defaults to between 10 and 100ms
:param min_time: minimum time (s)
:param max_time: maximum time (s)
:return: time in seconds
"""
return random.uniform(min_time, max_time) | 6626ebad19a945713e01b6e594ea24e8681f0669 | 638,083 |
def parse_charoffset(charoffset):
"""
Parse charoffset to a tuple containing start and end indices.
Example:
charoffset = '3-7;8-9'
[[3, 7], [8, 9]]
"""
# try split by ';'
charoffsets = charoffset.split(';')
return [[int(x.strip()) for x in offset.split('-')] for off... | 17d1308b7b50748aa8898f434a8f16083f7e4368 | 638,084 |
def join_sets(mod, set_name_list):
"""
Join sets in a list.
If list contains only a single set, return just that set.
:param mod:
:param set_name_list:
:return:
"""
if len(set_name_list) == 0:
return []
elif len(set_name_list) == 1:
return getattr(mod, set_name_list[... | 4460851eb40434c215c4de9705c2c1f329cb9ed7 | 638,086 |
import re
def _add_single_transfer_prefix(prefix_to_check, prefix_to_add,
resource_string):
"""Adds prefix to one resource string if necessary."""
if re.match(prefix_to_check, resource_string):
return resource_string
return prefix_to_add + resource_string | 42ca0414f2f711c02f6285a5b773042ce23f9864 | 638,087 |
import os
def check_exposure(dst, expid):
"""Ensure that all files associated with an exposure have arrived.
Parameters
----------
dst : :class:`str`
Delivery directory, typically ``DESI_SPECTRO_DATA/NIGHT``.
expid : :class:`int`
Exposure number.
Returns
-------
:clas... | 434c819cdd1eb64c71bf73d9bf5e11d5ca7472c8 | 638,088 |
import requests
import json
def get_id(header, device, url, verbose):
"""Loop through devices to find id of device and return it"""
page = 1 # same as 0
url = f"https://{url}/inventory/managedObjects/"
while True:
params = {
"fragmentType": "c8y_IsDevice",
"pageSize":... | 88ef5e349899ba76a7ab659b977b6781a0fc301c | 638,089 |
def none_to_empty(val):
"""Convert None to empty string.
Necessary for fields that are required POST but have no logical value.
"""
if val is None:
return ""
return val | bac9f6e6a5411615500e4ef6d08d654600e2fe62 | 638,090 |
from typing import Dict
import requests
def internetdb(ip_address: str) -> Dict:
""" Get the InternetDB data of a subdomain """
return (requests.get(
f"https://internetdb.shodan.io/{ip_address}"
)).json() | 9deff87b194a3081365af8c37734c4bbad72c882 | 638,091 |
def greet_as_ashish():
"""Simple function recording a closure"""
# captured variable in outer context
# also called a free variable
greet_prefix = "Ashish says:"
def greet(message):
print("{} {}".format(greet_prefix, message))
return greet | f9ed627edfff700964e76841780bec97d1852e26 | 638,092 |
import tempfile
import os
def content_to_file(content, file_path=None):
"""
Write string to a temporary file.
:param content:
:param file_path: absolute path to the desired output file.
"""
if not file_path:
file_path = tempfile.NamedTemporaryFile(mode='w', delete=False).name
wi... | e220fa9ece0c86c0bf9066f5d2a284339d41471c | 638,093 |
def list_strings(n):
"""lists all binary strings of length n, do not modify this function"""
if n == 0:
return [""]
else:
strings = []
for b in list_strings(n-1):
strings.append(b+"0")
strings.append(b+"1")
return strings | e32ba40b99e897f0364f7e8fe3c85e656b0a22b9 | 638,094 |
def cell_id(i,j,k,nx,ny):
"""
Get the cell Id given i,j,k indexes.
* --- * --- * --- *
| 0,2 | 1,2 | 2,2 | <- Cell id 6,7,8
* --- * --- * --- *
| 0,1 | 1,1 | 2,1 | <- Cell id 3,4,5
* --- * --- * --- *
| 0,0 | 1,0 | 2,0 | <- Cell id 0,1,... | 60918565ed77fc6a73121aeeab390d76cf44693f | 638,095 |
import argparse
def process_args():
"""Return processed arguments (options and positional arguments)."""
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='*', help='files to format')
return parser.parse_args() | 50654215d5a372c68a379ac217da7e77544a48a6 | 638,096 |
def AddOne(dataset):
"""AddOne"""
return dataset.map(lambda x: {"b": x["a"] + 1}) | c3e69292f13943378e67da49961ee75573a7b271 | 638,097 |
def parse(exc):
"""Takes in an exception and returns the boto
`Message, Code` properties if they exist - else `None, None`
"""
if exc is not None and hasattr(exc, 'response') and exc.response is not None:
error = exc.response.get('Error', {})
code = error.get('Code', None)
message = er... | 8f0a31ebcc41e4aa11232df1241ec10f498a7342 | 638,099 |
def override(config, overrides):
"""Update a config dictionary with overrides, merging dictionaries.
Where both sides have a dictionary, the override is done recursively.
Where `overrides` contains a value of `None`, the corresponding entry is
deleted from the return value.
.. note:: this does not... | e9b37c3b661b2f152d568fea6121f1c0564d6e71 | 638,100 |
def get_most_visible_camera_annotation(camera_data_dict: dict) -> dict:
"""
Get the most visibile camera's annotation.
:param camera_data_dict: Dictionary of form:
{
'CAM_BACK': {'attribute_tokens': ['cb5118da1ab342aa947717dc53544259'],
'bbox_corners': [600.8315617945755,
4... | f91976008585513dbba34546385dcf4a1bd13eb6 | 638,101 |
import json
def _to_json(self, fp=None, indent=4):
"""
Converts the object to JSON
:param fp=None: an open file_like object to write the json to.
If it is None, then a string with the JSON
will be returned as a string
:param indent=4: The indentation level des... | 247ad11f573db8cff601f29ef5c1e8174c833377 | 638,102 |
def sql_quote(v, name='(Unknown name)', md={}):
"""Quote single quotes in a string by doubling them.
This is needed to securely insert values into sql
string literals in templates that generate sql.
"""
if isinstance(v, bytes):
v = v.decode('UTF-8')
# Remove bad characters
for char... | 920f8b0769449f6e4340efa81d03c8bf8fe4fb25 | 638,103 |
def give_color_to_direction_static(dir):
"""
Assigns a color to the direction (static-defined colors)
Parameters
--------------
dir
Direction
Returns
--------------
col
Color
"""
direction_colors = [[-0.5, "#4444FF"], [-0.1, "#AAAAFF"], [0.0, "#CCCCCC"], [0.5, "... | 5f8713edd8a0ce75bc20a38cf2e714e992dbda49 | 638,104 |
from pathlib import Path
def check_file(file_name: str) -> bool:
"""Check file_name exists based on input.
Args:
file_name (str): file name to check
"""
try:
file_path = Path(file_name)
return file_path.exists()
except TypeError:
return False | bd5ea642e0f6841346f03bf295b02371a756c720 | 638,105 |
def g(x, y):
"""Constraint penalty"""
return (x + 5) ** 2 + (y + 5) ** 2 - 25 | 7c56b5ca1eaeb15dfbc63ce25b56d2eebf89cf52 | 638,106 |
def onset_attributes_to_onset(o_beat, o_subdiv):
"""
Convert arrays of o_bt and o_sub to o.
- See eq. (1) of the paper.
"""
def o_bt_o_sub_to_o(o_bt, o_sub):
def convert_sub(x):
""" o_sub from its 2's complement representation to exact value."""
return (x + 3) % 7 -... | 43e9660f5a55ed8bf203f3b62276f55f3de6aece | 638,107 |
import torch
def _is_tensor_index_moved_to_start(indices):
"""
Given an index, determine if the indexed part of the getitem is moved to the zero'th dimension
"""
has_tensor_index = False
continuous_tensor_index = True
if torch.is_tensor(indices[0]):
return True
for index in indic... | 7f96d70fff404aabf01ae540177f691adb7a858d | 638,108 |
def symDecomp(mat,obj):
"""
Decompose the matrix into a symmetrical and an antisymmetrical matrix
"""
if not mat.isSquare or mat._cMat:
return (None,None)
else:
m = mat.matrix
anti = obj
for i in range(0,mat.dim[0]-1):
for j in range(i+1,mat.dim[1]):
... | 9657ccd0910067fa448eec0a6709b030d4efb8e2 | 638,109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.