content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_batch(sentences, params, dico):
""" Convert a list of tokenized sentences into a Pytorch batch
args:
sentences: list of sentences
params: attribute params of the loaded model
dico: dictionary
returns:
word_ids: indices of the tokens
lengths: lengths of ea... | 54,500 |
def path_label_squeeze(paths):
"""Returns a weights sum of paths solutions, for visualization."""
v_range = tf.range(1, tf.shape(paths)[-1] + 1, dtype=paths.dtype)
return tf.einsum('ijkn,n->ijk', paths, v_range) | 54,501 |
def _Hz2Semitone(freq):
"""_Hz2Semitone."""
A4 = 440
C0 = A4 * pow(2, -4.75)
name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
if freq == 0:
return "Sil" # silence
else:
h = round(12 * log2(freq / C0))
octave = h // 12
n = h % 12
r... | 54,502 |
def plotSFinalIter(pX,pY,pZ,IX,IY,IZ,DX,DY,DZ,FX,FY,FZ,j,variable):
"""
works with UMBANQ.py and plots all the pitches that were tested.
the p variables (pX, pY, pZ) are all the position arrays. the I variables
indicate the initial positions, the D variables indicate the ball's
position at the deci... | 54,503 |
def uCSIsCatLt(code):
"""Check whether the character is part of Lt UCS Category """
ret = libxml2mod.xmlUCSIsCatLt(code)
return ret | 54,504 |
def export_file(isamAppliance, path, name, filename, check_mode=False, force=False):
"""
Exporting a file from the runtime template files directory
:param isamAppliance:
:param path:
:param name:
:param check_mode:
:param force:
:return:
"""
warnings = []
check_file = _check... | 54,505 |
def make_pos_array_and_diff(trials: List[dict]) -> List[dict]:
"""
Parameters
----------
trials : Non-filtered refinement trials
Returns
-------
A list of dictionaries with updated position and difference of neighbours
"""
_trials = trials[:]
for i, c in enumerate(trials):
... | 54,506 |
def test_log_works_in_train_callback(tmpdir):
"""
Tests that log can be called within callback
"""
class TestCallback(callbacks.Callback):
# helpers
count = 1
choices = [False, True]
# used to compute expected values
callback_funcs_called = collections.defaultdi... | 54,507 |
def plot_heat(ax, sat_delta_ti, min_limit, cbar=False):
""" Plot satmut deltas.
Args:
ax (Axis): matplotlib axis to plot to.
sat_delta_ti (4 x L_sm array): Single target delta matrix for saturated mutagenesis region,
min_limit (float): Minimum heatmap limit.
"""
vlim = max(min_limi... | 54,508 |
def a(O, R_r, E, aggregator='sum', include_v=True):
""" Applies and returns the aggregating function of the Interaction Network
Parameters
----------
O : numpy.ndarray
Object matrix
R_r : numpy.ndarray
Binary matrix that indexes the receiver objects
E : numpy.ndarray
Predict... | 54,509 |
def add_horse_people(id, body):
"""
Adds a people to the horse
:param id: Identifier of the horse
:type id: str
:param body: New association(s) to the horse
:type body: list | bytes
:rtype: None
"""
if connexion.request.is_json:
body = [Association.from_dict(d) for d in... | 54,510 |
def coords_json_to_api_pan(ang_clockwise):
"""converts from robot coordinates to API coordinates."""
return ang_clockwise | 54,511 |
def polnum2str(num, x_orientation=None):
"""
Convert polarization number to str according to AIPS Memo 117.
Uses 'pI', 'pQ', 'pU' and 'pV' to make it clear that these are pseudo-Stokes,
not true Stokes
Parameters
----------
num : int
polarization number
x_orientation : str, opt... | 54,512 |
def test_cli():
"""Check 'version' parameter."""
batch_cmds = ['-v', '--version']
ret_val = toolbox.run_cmd(batch_cmds)
for ret in ret_val:
assert not ret['stderr']
assert ret_val[0]['stdout'] == ret_val[1]['stdout'] | 54,513 |
async def delete_me(twofa: Code2FA, user: UserPass = Depends(is_connected_pass)) -> User:
"""Delete your user."""
if user.totp is not None:
if twofa.code is None or not twofa.verify(user):
raise HTTPException(
status.HTTP_401_UNAUTHORIZED,
"Un code de double a... | 54,514 |
def test_not_keyboard_for_merge():
"""
:return:
"""
with pytest.raises(TypeError) as _:
Keyboa.merge_keyboards_data(keyboards="not_a_keyboard") | 54,515 |
def should_unwrap(obj: Type[ObjectT]) -> bool:
"""Test whether we should use the __args__ attr for resolving the type.
This is useful for determining what type to use at run-time for coercion.
"""
return (not isliteral(obj)) and any(x(obj) for x in _UNWRAPPABLE) | 54,516 |
async def _auto_reload():
"""
Coro which see changes in your code and restart him.
:return:
"""
async for _ in awatch("."):
logging.info("Changes founded. Restarting...")
restart() | 54,517 |
def test_rectangle_hole_radius():
""" Test rectangle hole diameter calculation
"""
r = Rectangle((0,0), 2, 2)
assert_equal(0, r.hole_radius)
r = Rectangle((0,0), 2, 2, 1)
assert_equal(0.5, r.hole_radius) | 54,518 |
def normalize(net,nodesToIndices=None,layersToIndices=None,nodeStart=0,layerStart=0):
"""Returns a copy of the network with layer and node indices as integers.
In network with n nodes the nodes are renamed so that they run from 0 to n-1.
In network has b_a elementary layers in aspect a, the layers are rena... | 54,519 |
def dict_other_json(imagePath, imageData, shapes, fillColor=None, lineColor=None):
"""
:param lineColor: list
:param fillColor: list
:param imageData: str
:param imagePath: str
:return: dict""
"""
# return {"shapes": shapes, "lineColor": lineColor, "fillColor": fillColor, "imageData": im... | 54,520 |
def assert_raises(expr, exc_type):
"""
Helper function to assert `expr` raises an exception of type `exc_type`
Args:
expr: Callable
exec_type: Exception
Returns:
None
Raises:
Assertion error on failure
"""
try:
expr(None)
except exc_type:
a... | 54,521 |
def register_training_set_instance(db: Session, tsm: schemas.TrainingSetMetadata):
"""
Registers a new Training Set Instance. A training set with a start ts, end ts, create ts, name, ID, and a version
:param db: Session
:param tsm: TrainingSetMetadata
"""
# FIXME: We need to set this to the fea... | 54,522 |
def main():
"""
Reads commandline parameters, prints corresponding associated genes with evidence info
"""
postgap_path = os.path.dirname(os.path.realpath(__file__))
logging.config.fileConfig(postgap_path + '/configuration/logging.conf')
options = get_options()
logging.info("Starting postgap with the foll... | 54,523 |
def draw_dot_singlearrows(fname, epsilon, invepsilon, morph_by_state, axs, ays, L_max, all_digits = False, save_dot = True):
"""
This function draws the .dot file associated with the
epsilon-transducer stored in epsilon+invepsilon.
This version works with *memoryful* transducers,
where we assume that the output... | 54,524 |
def get_post(post_id):
""" Get the post. """
# Returns: (post_title, post_body, user_tuple)
route = '{}/api/v2.0/posts/' +\
'{}?key={}&filter=MLLKIHJMHIHKKFMJLLHGMKIMMGOKFFN'
response = requests.get(route.format(ms_config["ms_host"], post_id, ms_config["api_key"]))
try:
data = ... | 54,525 |
def track_from_filename(filename, filetype = None, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
"""
Create a track object from a filename.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
filename: A string containing the path to t... | 54,526 |
def create_sectors_from_entities(
entities: List[Entity], created_by: Identity
) -> List[Identity]:
"""Create sectors from entities."""
sectors = []
for entity in entities:
sector = create_sector_from_entity(entity, created_by)
if sector is None:
continue
sectors.ap... | 54,527 |
def minor1d(array1d, i):
"""Accept 1D array and return a new array with element i removed."""
range1 = list(range(i)) + list(range(i+1, array1d.shape[0]))
return array1d[np.array(range1)] | 54,528 |
def get_ast_field_name(ast):
"""Return the normalized field name for the given AST node."""
replacements = {
# We always rewrite the following field names into their proper underlying counterparts.
'__typename': '@class'
}
base_field_name = ast.name.value
normalized_name = replacemen... | 54,529 |
def public_api(host_uri):
"""
Note: unlike the authenticated variant, this helper might get called even
if the API isn't going to be used, so it's important that it doesn't try to
actually connect to the API host or something.
"""
conf = fatcat_openapi_client.Configuration()
conf.host = host... | 54,530 |
def main(observation=None, mask=None, outName=None, velStart=None, velEnd=None, velPixel=None, normDepth=None, normLande=None, normWave=None):
"""Run the LSD code.
Arguments are:
observation -- name of a spectrum file
mask -- name of the LSD mask file
outName -- name of the output LSD ... | 54,531 |
def draw_heatmap_fingerprints(
fluor_df, results_dir, scale, class_order=None, prefix='', test=False
):
"""
Draws a heatmap for each analyte representing the median reading for each
peptide
Input
----------
- fluor_df: Dataframe of fluorescence readings output from running
combine_plate... | 54,532 |
def convex_hull_3d(input, inputmsk=None, outhull=None, inhull=None, copy=False, copyoutside=True):
"""
Calculates 3D convex hull of non-masked voxels of an image.
By default, returns an image where inside-hull-voxels have value :samp:`inhull`
and outside-hull-voxels have value :samp:`outhull`.
:typ... | 54,533 |
def liquid_filter(_filter: FilterT) -> FilterT:
"""A filter function decorator that wraps `TypeError` in `FilterArgumentError`."""
@wraps(_filter)
def wrapper(val: object, *args: Any, **kwargs: Any) -> Any:
try:
return _filter(val, *args, **kwargs)
except TypeError as err:
... | 54,534 |
def end():
"""
Terminates a PyNGL script, flushes all buffers, and closes all
internal files.
Ngl.end()
"""
NhlClose()
return None | 54,535 |
def unseven(nzo, workdir, workdir_complete, delete, one_folder, sevens):
""" Unpack multiple sets '7z' of 7Zip files from 'workdir' to 'workdir_complete.
When 'delete' is set, originals will be deleted.
"""
i = 0
unseven_failed = False
tms = time()
# Find multi-volume sets, because 7zip... | 54,536 |
def check_home():
"""
Checks the button that is clicked from the home screen and returns the corrseponding values.Returns
1 if Play button is clicked, 3 if Instructions button is clicked, and 4 if About button is clicked
"""
global value, right_click
value = 0
mouse = pygame.mouse.get_pos()
if 370 <= mouse[... | 54,537 |
def olivine(piezometer=None):
""" Data base for calcite piezometers. It returns the material parameter,
the exponent parameter and a warn with the "average" grain size measure to be use.
Parameter
---------
piezometer : string or None
the piezometric relation
References
----------
... | 54,538 |
def serialize(value):
"""If the value is an BSON ObjectId, cast it to a string."""
if isinstance(value, bson.objectid.ObjectId):
return str(value)
else:
return value | 54,539 |
def test_sudoku_negative():
"""Raise an error when generating a Sudoku graph of order -1."""
pytest.raises(nx.NetworkXError, nx.sudoku_graph, n=-1) | 54,540 |
def stash_node_versions(node_id):
"""Gets all version of a node.
stash currently only keeps upto 10 versions.
"""
return stash_invoke('node-versions', node_id) | 54,541 |
def ReEncode(outFileName):
"""\
Prefab.
Takes in audio and video frames and encodes them to a compressed video file
using ffmpeg to do the compression.
Inboxes:
- "inbox" -- NOT USED
- "control" -- Shutdown signalling
- "video" -- Video frames to be saved
- "aud... | 54,542 |
def read_basis_templates(objtype, subtype='', outwave=None, nspec=None,
infile=None, onlymeta=False, verbose=False):
"""Return the basis (continuum) templates for a given object type. Optionally
returns a randomly selected subset of nspec spectra sampled at
wavelengths outwave.
... | 54,543 |
def get_new_data():
"""Read in models, read in csv, get new data, calculate relative errors,
update csv.
New data: pull all stock data up to and including the previous day.
"""
relative_error_csv = Path(RELATIVE_ERRORS_DIREC)
models_file = Path(MODELS_DIRECTORY)
if models_file.is_file() and ... | 54,544 |
def readConfig(configFile):
# returns list of parameters
# with key 'name'
"""
reads the config file to dictionary
"""
logging.debug("Loading config")
with open(configFile) as json_file:
try:
d = json.load(json_file)
except:
print ("failed to parse... | 54,545 |
def predict_one_epoch(sess, ops, train_writer):
""" ops: dict mapping from string to tf ops """
is_training = True
# Shuffle train samples
# train_idxs = np.arange(0, len(TRAIN_DATASET))
# 预测不需要打乱
# np.random.shuffle(train_idxs)
# num_batches = len(TRAIN_DATASET) // BATCH_SIZE
num_batch... | 54,546 |
def test_dataclass_from_dict():
"""Test dataclass from dict parsing."""
raw = {
"a": 1,
"b": 1.0,
"c": "hello",
"d": 1,
"e": {"a": 2, "b": "test", "c": "test", "d": None},
}
res = dataclass_from_dict(BasicModel, raw)
# test the basic values
assert isinstan... | 54,547 |
def main(argv):
"""Go Main Go"""
st = NetworkTable('IACLIMATE')
now = datetime.datetime.now() - datetime.timedelta(days=1)
pgconn = get_dbconn('coop', user='nobody')
ccursor = pgconn.cursor()
gfunc = "gdd50"
gbase = 50
if len(argv) == 2 and argv[1] == "gdd52":
gfunc = "gdd52"
... | 54,548 |
def hex_to_rgb(hex: str, hsl: bool = False) -> Tuple[int, int, int]:
"""Converts a HEX code into RGB or HSL.
Taken from https://stackoverflow.com/a/62083599/7853533
Args:
hex (str): Takes both short as well as long HEX codes.
hsl (bool): Converts the given HEX code into HSL value if True.
... | 54,549 |
def connect(ctx, timeout=None):
"""
Returns a connection to the database. Does some initial-setup
too, though that's probably a bad design somehow.
The optional timeout parameter is an integer expressing the number of seconds
to set the underlying connection object to timeout after.
NOTE: Timeo... | 54,550 |
def findNextName(name):
"""None"""
pass | 54,551 |
def load_burn_data(url) -> xr.Dataset:
"""Open a GeoTIFF into an in memory DataArray
with DataArray labelled as given name"""
geotiff_burn = xr.open_rasterio(url)
burn_dataset = geotiff_burn.to_dataset('band')
return burn_dataset | 54,552 |
def strip_org(name):
""" Returns the name with ORG_PREFIX stripped from it.
"""
if name.startswith(ORG_PREFIX):
return name[len(ORG_PREFIX):]
else:
return name | 54,553 |
def _ios_format_data(cmd_outputs: json) -> json:
"""
This function will retrieve data from differents
commands outputs and gegroup them in a structured data format.
Three command are executed on devices
-> show ip ospf neighbor detail
-> show ip ospf interface
-> show ip ospf
... | 54,554 |
def get_mode_C_array(mode_C):
"""冷房の運転モードを取得する
Args:
mode_C(str): 冷房方式
Returns:
tuple: 冷房の運転モード
"""
# 運転モード(冷房)
if mode_C == '住戸全体を連続的に冷房する方式':
return tuple(["全館連続"] * 12)
else:
return ('居室間歇', '居室間歇', '居室間歇', '居室間歇', '居室間歇', None, None, None, None, None, None,... | 54,555 |
def launch_and_move(prog_array, workspace,
get_wid=get_wid_by_pid, new_name=None):
"""Launch application and move the created window to `workspace`.
Returns the window id as used by wmcrtl.
`prog_array` : list forwarded to subprocess.Popen. This should
include the co... | 54,556 |
def construct_label_array(video_labels):
"""Construction label array."""
label_arr = np.zeros((cfg.MODEL.NUM_CLASSES, ))
# AVA label index starts from 1.
for lbl in video_labels:
if lbl == -1:
continue
assert lbl >= 1 and lbl <= 80
label_arr[lbl - 1] = 1
return l... | 54,557 |
def any(x: _cpp.Variable,
dim: Optional[str] = None,
*,
out: Optional[_cpp.Variable] = None) -> _cpp.Variable:
"""Element-wise OR over the specified dimension or all dimensions if not
provided.
:param x: Input data.
:param dim: Optional dimension along which to calculate the OR.... | 54,558 |
def get_date():
""" gets current date """
return datetime.now() | 54,559 |
def plot(data, labels, caption):
"""plot the data distribution, !!YOU CAN READ THIS LATER, if you are interested
"""
colors = cm.rainbow(np.linspace(0, 1, len(set(labels))))
for i in set(labels):
xs = []
ys = []
for index, label in enumerate(labels):
if label == i:
... | 54,560 |
def singular(plural):
"""
Take a plural English word and turn it into singular
Obviously, this doesn't work in general. It know just enough words to
generate XML tag names for list items. For example, if we have an element
called 'tracks' in the response, it will be serialized as a list without
... | 54,561 |
def run(
args: Optional[Sequence[str]] = None,
*,
prog: Optional[str] = None,
resolver: Optional[Resolver] = None,
) -> None:
"""
Locks Docker images referenced from a Dockerfile.
This is the main entry point of the application
that can be called from a command line.
"""
parser ... | 54,562 |
def create_simple_keras_model(learning_rate=0.1):
"""Returns an instance of `tf.Keras.Model` with just one dense layer.
Args:
learning_rate: The learning rate to use with the SGD optimizer.
Returns:
An instance of `tf.Keras.Model`.
"""
model = tf.keras.models.Sequential([
tf.keras.layers.Flatt... | 54,563 |
def main(
args: List[str],
path_to_dir_with_main_module: str = "battery_handyman",
testing: bool = False
) -> None:
"""The entrypoint of the application
With testing == False this function can not be covered
"""
cli_parser = battery_handyman.cli.setup_parser()
parsed_args = ... | 54,564 |
def elli(x, rot=0, xoffset=0, cond=1e6, actuator_noise=0.0, both=False):
"""Ellipsoid test objective function"""
x = np.asarray(x)
if not isscalar(x[0]): # parallel evaluation
return [elli(xi, rot) for xi in x] # could save 20% overall
if rot:
x = rotate(x)
N = len(x)
if actuat... | 54,565 |
def plot_coauthor_network(docs: DocumentSet, *, max_authors=None, **kwargs):
"""Plot a co-author network.
This is a shorthand for `plot_network(build_coauthor_network(docs))`."""
b, p = split_kwargs(**kwargs)
return plot_network(
build_coauthor_network(docs, max_authors=max_authors, **b), *... | 54,566 |
def read_gene_list(fname, id_type):
"""Return references for genes from a file with the given ID type.
Parameters
----------
fname : str
The name of the file containing the list of genes. Each line of the
file corresponds to a single gene.
id_type : str
The type of identifie... | 54,567 |
def print_temp_message(msg: str):
"""
print a message and reset the cursor to the begining of the line
"""
print(clear_line(), msg, Cursor.BACK(len(msg)), sep="", end="", flush=True) | 54,568 |
def backtest(
start_date: datetime = None,
end_date: datetime = None,
interval=1,
yield_interval=100,
start_balances: Dict[str, float] = None,
starting_coin: str = None,
config: Config = None,
):
"""
:param config: Configuration object to use
:param start_date: Date to backtest... | 54,569 |
def main(*args, **kwargs):
"""
Main function
Retrieves, forms data, and prints out information
"""
print()
# First retrieve the JSON
data = get_url(API_URL)
# Interpret results into a list of matches
matches = [Match(**unpack) for unpack in data["matches"]]
# Find the long... | 54,570 |
def define_vgg_pre_processing(tf_input):
"""
This function defines the vgg_pre_processing network using the tensorflow nn
api.
Parameters
----------
tf_input: tensorflow.Tensor
The input tensor to the network. The image is expected to be in RGB
format.
Returns
-------
... | 54,571 |
def evaluate(model_path, data_path):
"""
Evaluates given model with test set separated from all training data.
Gives details about accuracy for every class. Outputs results od screen.
Args:
model_path (str): path to model file
data_path (str): training data directory... | 54,572 |
def subreservoir(weight: Tensor, k=3):
"""
size of weight must devide by k
"""
subres_size = weight.size(0) // k
mask = np.zeros_like(weight)
for i in range(k):
mask[i * subres_size: (i + 1) * subres_size, i * subres_size: (i + 1) * subres_size] = torch.ones(subres_size,
... | 54,573 |
def buy_tickets(request):
""" Provides the event form data and passes it to the frontend as json """
form_html = ""
message_html = ""
success = True
# Ensure all required data has been sent
if 'event' not in request.GET or not request.GET['event']:
messages.error(request, 'No event infor... | 54,574 |
def plot_tags(tags: np.array):
"""
plots a barplot for the occurrences of all tags given in the numpy array
:param tags: numpy array containing tags like section or class or subclass for each patent
:return: plots and saves a barplot
"""
df = pd.DataFrame.from_dict(Counter(tags), orient='index')... | 54,575 |
def crop_and_revenue_to_df(financial_annual_overview, waste_adjusted_yields, total_sales, vadded_sales, education_rev, tourism_rev, hospitality_rev, grants_rev):
"""Adding yields and sales information to financial overview
Notes:
Adds waste-adjusted yields for crops 1, 2, 3 and 4 with t... | 54,576 |
def cr_notification_dispatcher(r, **attr):
"""
Send a notification.
"""
if r.representation == "html" and \
r.name == "shelter" and r.id and not r.component:
T = current.T
msg = current.msg
record = r.record
message = ""
text = ""
s_id = re... | 54,577 |
def download_blob(bucket_name, source_blob_name):
"""Downloads a blob from the bucket."""
client = storage.Client()
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(source_blob_name)
return blob.download_as_string() | 54,578 |
def update_posts(diff_info, update_all=False):
"""添加或修改文章"""
repo = PostRepo(
current_app.config["REPO_DIR"],
current_app.config["REPO_SSHKEY"],
current_app.config["REPO_BRANCH"],
)
if update_all:
updated_blobs, removed_blobs = repo.get_all_posts()
else:
upda... | 54,579 |
def _recursive_freeze(module: torch.nn.Module,
train_bn: bool = True) -> None:
"""Freezes the layers of a given module.
Args:
module: The module to freeze
train_bn: If True, leave the BatchNorm layers in training mode
"""
children = list(module.children())
if no... | 54,580 |
def draw_inventory(engine, selected_item, viewport):
"""インベントリを描画する"""
player = engine.player
if selected_item == 99:
player.equipment.equip_update()
engine.flower_light()
engine.game_state = GAME_STATE.NORMAL
viewport_left = viewport[0]
viewport_right = viewport[1]
v... | 54,581 |
def test_random():
"""Try to sort 100,000 randomly generated strings without exception."""
# Repeat test 100,000 times
for _ in py23_range(100000):
# Made a list of five randomly generated strings
lst = [''.join(sample(printable, randint(7, 30)))
for __ in py23_range(5)]
... | 54,582 |
def val_epoch(state: train_state.TrainState):
"""
perform a validation epoch
:param state:
:return:
"""
val_config = deepcopy(config)
val_config['data']['val_fns'] = "path_to_tvqa/val{:03d}of008.tfrecord"
val_config['data']['num_val_files'] = 8
val_config['data']['do_random_scale'] =... | 54,583 |
def getBERTFeatures(model, text, attn_head_idx=-1): # attn_head_idx - index o[]
"""
Get BERT features for the `text`
Args:
model: BERT model of type `BertForPreTrainingCustom`
text: required, get features for this text
attn_head_idx: optional, defaults to last layer
Returns:
... | 54,584 |
def filter_rows_via_column_matching(data, column, index=0):
"""
Filter data, by keeping rows whose particular field index matches the
column criteria
It takes parameters:
data (data in the form of a list of lists)
column (used as the match criteria for a particular field of the data)
and op... | 54,585 |
def _print_collected_tasks(dictionary, show_nodes):
"""Print the information on collected tasks.
Parameters
----------
dictionary: dict
A dictionary with path on the first level, tasks on the second, dependencies and
products on the third.
show_nodes: bool
Indicator for whet... | 54,586 |
def get_disk_part():
"""Query disk part information of current system"""
result_list = list()
disk_list = psutil.disk_partitions()
for item in disk_list:
tmp_dic = dict()
tmp_dic["device_name"] = item.device
tmp_dic["mount_point"] = item.mountpoint
tmp_dic["fs_type"] = i... | 54,587 |
def get_td_at_index(tr, index):
"""
When calculating the rowspan for a given cell it is required to find all
table cells 'below' the initial cell with a v_merge. This function will
return the td element at the passed in index, taking into account colspans.
"""
current = 0
for td in tr.xpath(... | 54,588 |
async def test_async_get_development_config(
aresponses, readarr_client: ReadarrClient
) -> None:
"""Test getting development config."""
aresponses.add(
"127.0.0.1:8787",
f"/api/{READARR_API}/config/development",
"GET",
aresponses.Response(
status=200,
... | 54,589 |
def _normalize_name(name: str) -> str:
"""
Normalizes the given name.
"""
return re.sub(r"[^a-zA-Z0-9.\-_]", "_", name) | 54,590 |
def time_step(las, historic_las, max_t, transport, data_df,
transport_threshold, transport_time, transport_severity,
transport_release, beta_threshold, beta_time, beta_severity,
lockdown_release, nat=False):
"""
Enacts all actions of the day such as the morning commute,... | 54,591 |
def generate_geneset():
"""
Populates the GeneSet class with atoms and fragments to be used
by the engine. As it stands these are hardcoded into the engine
but will probably be adapted in future versions
Parameters
----------
None
Returns
----------
GeneSet : object
ret... | 54,592 |
def filter_claims_by_date(claims_data, from_date, to_date):
"""Return claims falling in the specified date range."""
return [
claim for claim in claims_data
if (from_date <= claim.clm_from_dt <= to_date)
] | 54,593 |
def get_policies_in_category(jamf_url, object_type, object_name, enc_creds, verbosity):
"""return all policies in a category"""
url = "{}/JSSResource/{}/{}".format(
jamf_url, object_types(object_type), object_name
)
r = curl.request("GET", url, enc_creds, verbosity)
if r.status_code == 200... | 54,594 |
async def add_note(fltr):
""" .save """
try:
from userbot.modules.sql_helper.notes_sql import add_note
except AttributeError:
await fltr.edit("`Bot Non-SQL modunda işləyir!!`")
return
keyword = fltr.pattern_match.group(1)
string = fltr.text.partition(keyword)[2]
msg = aw... | 54,595 |
def get_sorted_nodelist(nodelist, timeout):
"""
check all nodes and poll for latency,
eliminate nodes with no response, then sort
nodes by increasing latency and return as a list
"""
pool_size = mp.cpu_count()*2
n = len(nodelist)
with mp.Pool(processes=pool_size) as pool:
... | 54,596 |
def featurise_mols(smiles_list, representation, bond_radius=3, nBits=2048):
"""
Featurise molecules according to representation
:param smiles_list: list of molecule SMILES
:param representation: str giving the representation. Can be 'fingerprints' or 'fragments'.
:param bond_radius: int giving the b... | 54,597 |
def clear_inactive_structural_variant_sets(_self):
"""Task to cleanup variant sets and their variants that are stuck in a non-active status for a long time."""
return models.cleanup_variant_sets() | 54,598 |
def unicode2str(content):
"""Convert the unicode element of the content to str recursively."""
if isinstance(content, dict):
result = {}
for key in content.keys():
result[unicode2str(key)] = unicode2str(content[key])
return result
elif isinstance(content, list):
r... | 54,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.